Esempio n. 1
0
function setup_user()
{
    global $grid;
    if (!empty($grid->user)) {
        return;
    }
    if (!empty($grid->request)) {
        $view = $grid->request->params['view'];
        if (strpos($view, 'wispr') !== false || strpos($view, '404') !== false) {
            return;
        }
    }
    ini_set('session.name', 'SESSION');
    ini_set('session.use_cookies', true);
    ini_set('session.cookie_lifetime', time() + 60 * 60 * 24 * 365);
    ini_set('session.gc_maxlifetime', time() + 60 * 60 * 24 * 365);
    session_set_save_handler('session_open', 'session_close', 'session_read', 'session_write', 'session_delete', 'session_gc');
    register_shutdown_function('session_write_close');
    session_start();
    if (!empty($_SESSION['user_id'])) {
        $user = $grid->db->record('user', $_SESSION['user_id']);
    }
    if (empty($user)) {
        $user = create_user();
    }
    $grid->user = $user;
    $grid->users = array($user->id => $user);
}
Esempio n. 2
0
function create_user_from_mysql()
{
    $q = new mysql();
    ini_set('display_errors', 1);
    ini_set('error_reporting', E_ALL);
    ini_set('error_prepend_string', null);
    ini_set('error_append_string', null);
    $GLOBALS["WAIT"] = true;
    build_progress("{start}", 10);
    $results = $q->QUERY_SQL("SELECT * FROM CreateUserQueue", "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error;
        build_progress("MySQL error", 110);
        return;
    }
    @mkdir("/usr/share/artica-postfix/ressources/logs/web/create-users", 0755, true);
    echo mysql_num_rows($results) . " member(s) to create...\n";
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $zMD5 = $ligne["zMD5"];
        $content = $ligne["content"];
        @file_put_contents("/usr/share/artica-postfix/ressources/logs/web/create-users/{$zMD5}", $content);
        if (create_user($zMD5)) {
            build_progress("{removing_order}", 95);
            $q->QUERY_SQL("DELETE FROM `CreateUserQueue` WHERE `zMD5`='{$zMD5}'", "artica_backup");
        } else {
            $q->QUERY_SQL("DELETE FROM `CreateUserQueue` WHERE `zMD5`='{$zMD5}'", "artica_backup");
            build_progress("{failed}", 110);
            return;
        }
    }
    build_progress("{done}", 100);
}
Esempio n. 3
0
function console_create_user($args)
{
    $fname = array_shift($args);
    $lname = array_shift($args);
    $email = array_shift($args);
    $admin = array_shift($args) == 'true';
    if (is_null($fname) || is_null($lname) || is_null($email)) {
        throw new Exception('create_user: Missing arguments. Expected: (fname, lname, email, admin)');
    }
    $display_name = $fname . " " . $lname;
    $username = str_replace(" ", "_", strtolower($display_name));
    $user_data = array('username' => $username, 'display_name' => $display_name, 'email' => $email, 'password_generator' => 'random', 'timezone' => 0, 'autodetect_time_zone' => 1, 'create_contact' => false, 'company_id' => owner_company()->getId(), 'send_email_notification' => true, 'personal_project' => 0);
    // array
    try {
        DB::beginWork();
        $user = create_user($user_data, $admin, '');
        if (!$user->getContact() instanceof Contact) {
            $contact = new Contact();
            $contact->setFirstName($fname);
            $contact->setLastName($lname);
            $contact->setEmail($email);
            $contact->setUserId($user->getId());
            $contact->save();
        }
        DB::commit();
    } catch (Exception $e) {
        DB::rollback();
        throw $e;
    }
}
Esempio n. 4
0
function authenticate(&$sid)
{
    global $user, $TABLE_USERS, $rpgDB;
    if (!$user->data['is_registered']) {
        return false;
    }
    $sid->_sid = $user->session_id;
    $sid->_username = $user->data['username'];
    $sid->_email = $user->data['user_email'];
    $sid->_ip = $user->ip;
    // Attempt to retrieve the user session details from the db.
    $sql = sprintf("SELECT iplog, slength, dm FROM %s WHERE pname = '%s'", $TABLE_USERS, $sid->_username);
    $res = $rpgDB->query($sql);
    if (!$res) {
        $err = $rpgDB->error();
        __printFatalErr("Failed to query database: " . $err['message'] . "\n" . $sql, __LINE__, __FILE__);
    }
    if ($rpgDB->num_rows() == 1) {
        // Record the user data.
        $row = $rpgDB->fetch_row($res);
        $sid->_iplog = unserialize(stripslashes($row['iplog']));
        $sid->_slength = $row['slength'];
        $sid->_dm = $row['dm'] == 'Y';
    } else {
        create_user($user->data['username']);
        $sid->_iplog = "";
        $sid->_slength = 180;
        $sid->_dm = false;
    }
    return true;
}
Esempio n. 5
0
 public function create_new_user($email)
 {
     if (!$this->config['weautocreateusers']) {
         return null;
     }
     if (record_exists('artefact_internal_profile_email', 'email', $email)) {
         throw new AccountAutoCreationException(get_string('emailalreadyclaimed', 'auth.browserid', $email));
     }
     if (record_exists('usr', 'username', $email)) {
         throw new AccountAutoCreationException(get_string('emailclaimedasusername', 'auth.browserid', $email));
     }
     // Personal details are currently not provided by the Persona API.
     $user = new stdClass();
     $user->username = $email;
     $user->firstname = '';
     $user->lastname = '';
     $user->email = $email;
     // no need for a password on Persona accounts
     $user->password = '';
     $user->passwordchange = 0;
     $user->authinstance = $this->instanceid;
     // Set default values to activate this user
     $user->deleted = 0;
     $user->expiry = null;
     $user->suspendedcusr = null;
     $user->id = create_user($user, array(), $this->institution);
     return $user;
 }
Esempio n. 6
0
function prep_DB_content()
{
    global $conn;
    create_tables($conn);
    create_user($conn);
    create_user_devices($conn);
    create_env($conn);
    create_env_devices($conn);
}
Esempio n. 7
0
 private function update_user()
 {
     $fb_response = $this->facebook->api('/me');
     $this->display_name = $fb_response['name'];
     global $db;
     if (user_exists($this)) {
         $this->updated = time();
         $db->query('UPDATE users SET display_name = "' . $this->display_name . '", updated = ' . $this->updated . ' WHERE uid = ' . $this->uid);
     } else {
         create_user($this);
     }
 }
Esempio n. 8
0
function create_linked_user($username, $email, $password, $panelType)
{
    // Global variables
    global $redis_enabled, $redis_server;
    // Connect to the DB
    $ret = create_connection($connection);
    if ($ret !== true) {
        return $ret;
    }
    // Connect to Redis
    if ($redis_enabled === true) {
        $redis = new Redis();
        if (!$redis->connect($redis_server)) {
            $redis = false;
        }
    } else {
        $redis = false;
    }
    // Validate input
    $ret = validate_input($username, $email, $password, $panelType);
    if ($ret !== true) {
        end_connection(true, $connection);
        return $ret;
    }
    // Create user
    if (create_user($username, $email, $password, $userid, $apikey, $connection) !== true) {
        end_connection(true, $connection);
        return 'Username already exists';
    }
    // Set the type of user profile
    $prefix = 'data/' . $panelType;
    // Create feeds
    if (create_feeds($prefix . '_feeds.json', $feeds, $apikey) !== true) {
        end_connection(true, $connection);
        return 'Error while creating the feeds';
    }
    // Create inputs
    if (create_inputs($prefix . '_inputs.json', $userid, $inputs, $connection, $redis) !== true) {
        end_connection(true, $connection);
        return 'Error while creating the inputs';
    }
    // Create processes
    if (create_processes($prefix . '_processes.json', $feeds, $inputs, $apikey) !== true) {
        end_connection(true, $connection);
        return 'Error while creating the processes';
    }
    end_connection(false, $connection);
    return true;
}
function create_and_enrol_user($student_name, $ruserid, $courseid)
{
    if (preg_match('/^\\s*(.+?)\\s*(\\S+)\\s*$/', $student_name, $names)) {
        $fname = $names[1];
        $sname = $names[2];
    } else {
        $fname = '';
        $sname = $student_name;
    }
    $userid = get_existing_user($ruserid, $fname, $sname);
    if (!$userid) {
        $userid = create_user($ruserid, $fname, $sname);
    }
    enrol_user($userid, $courseid);
}
Esempio n. 10
0
function import_submit(Pieform $form, $values)
{
    global $SESSION;
    $date = time();
    $nicedate = date('Y/m/d h:i:s', $date);
    $uploaddir = get_config('dataroot') . 'import/test-' . $date . '/';
    $filename = $uploaddir . $values['file']['name'];
    check_dir_exists($uploaddir);
    move_uploaded_file($values['file']['tmp_name'], $filename);
    if ($values['file']['type'] == 'application/zip') {
        // Unzip here
        $command = sprintf('%s %s %s %s', escapeshellcmd(get_config('pathtounzip')), escapeshellarg($filename), get_config('unzipdirarg'), escapeshellarg($uploaddir));
        $output = array();
        exec($command, $output, $returnvar);
        if ($returnvar != 0) {
            $SESSION->add_error_msg('Unable to unzip the file');
            redirect('/import/');
        }
        $filename = $uploaddir . 'leap2a.xml';
        if (!is_file($filename)) {
            $SESSION->add_error_msg('No leap2a.xml file detected - please check your export file again');
            redirect('/import/');
        }
    }
    // Create dummy user
    $user = (object) array('username' => 'import_' . $date, 'password' => 'import1', 'firstname' => 'Imported', 'lastname' => 'User (' . $nicedate . ')', 'email' => '*****@*****.**');
    $userid = create_user($user);
    // And we're good to go
    echo '<pre>';
    $filename = substr($filename, strlen(get_config('dataroot')));
    require_once dirname(dirname(__FILE__)) . '/import/lib.php';
    safe_require('import', 'leap');
    db_begin();
    $importer = PluginImport::create_importer(null, (object) array('token' => '', 'usr' => $userid, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'data' => array('filename' => $filename), 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_STDOUT, 'profile' => true));
    $importer->process();
    // Now done, delete the temporary e-mail address if there's a new one
    // A bit sucky, presumes only one email in the import
    $email = artefact_instance_from_id(get_field('artefact', 'id', 'title', '*****@*****.**', 'artefacttype', 'email', 'owner', $userid));
    $email->delete();
    execute_sql('UPDATE {artefact_internal_profile_email} SET principal = 1 WHERE "owner" = ?', array($userid));
    db_commit();
    echo "\n\n";
    echo 'Done. You can <a href="' . get_config('wwwroot') . '/admin/users/changeuser.php?id=' . $userid . '">change to this user</a> to inspect the result, ';
    echo 'or <a href="' . get_config('wwwroot') . 'import/">try importing again</a>';
    echo '</pre>';
    exit;
}
Esempio n. 11
0
function import_next_user($filename, $username, $authinstance)
{
    global $ADDEDUSERS, $FAILEDUSERS;
    log_debug('adding user ' . $username . ' from ' . $filename);
    $authobj = get_record('auth_instance', 'id', $authinstance);
    $institution = new Institution($authobj->institution);
    $date = time();
    $nicedate = date('Y/m/d h:i:s', $date);
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $username);
    $uploaddir = get_config('dataroot') . 'import/' . $niceuser . '-' . $date . '/';
    check_dir_exists($uploaddir);
    // Unzip the file
    $archive = new ZipArchive();
    if ($archive->open($filename) && $archive->extractTo($uploaddir)) {
        // successfully extracted
        $archive->close();
    } else {
        $FAILEDUSERS[$username] = get_string('unzipfailed', 'admin', hsc($filename));
        return;
    }
    $leap2afilename = $uploaddir . 'leap2a.xml';
    if (!is_file($leap2afilename)) {
        $FAILEDUSERS[$username] = get_string('noleap2axmlfiledetected', 'admin');
        log_debug($FAILEDUSERS[$username]);
        return;
    }
    // If the username is already taken, append something to the end
    while (get_record('usr', 'username', $username)) {
        $username .= "_";
    }
    $user = (object) array('authinstance' => $authinstance, 'username' => $username, 'firstname' => 'Imported', 'lastname' => 'User', 'password' => get_random_key(6), 'passwordchange' => 1);
    db_begin();
    try {
        $user->id = create_user($user, array(), $institution, $authobj);
    } catch (EmailException $e) {
        // Suppress any emails (e.g. new institution membership) sent out
        // during user creation, becuase the user doesn't have an email
        // address until we've imported them from the Leap2A file.
        log_debug("Failed sending email during user import");
    }
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $user->username);
    $record = (object) array('token' => '', 'usr' => $user->id, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'data' => array('importfile' => $filename, 'importfilename' => $filename, 'importid' => $niceuser . time(), 'mimetype' => file_mime_type($filename)), 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_FILE, 'profile' => true);
    $tr = new LocalImporterTransport($record);
    $tr->extract_file();
    $importer = PluginImport::create_importer(null, $tr, $record);
    unset($record, $tr);
    try {
        $importer->process();
        log_info("Imported user account {$user->id} from Leap2A file, see" . $importer->get('logfile') . 'for a full log');
    } catch (ImportException $e) {
        log_info("Leap2A import failed: " . $e->getMessage());
        $FAILEDUSERS[$username] = get_string("leap2aimportfailed");
        db_rollback();
    }
    db_commit();
    if (empty($FAILEDUSERS[$username])) {
        // Reload the user details, as various fields are changed by the
        // importer when importing (e.g. firstname/lastname)
        $newuser = get_record('usr', 'id', $user->id);
        $newuser->clearpasswd = $user->password;
        $ADDEDUSERS[] = $newuser;
    }
    return;
}
Esempio n. 12
0
    $username = "******";
    $password = "******";
    $dbname = "ESPDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    if ($conn->query($sql) === TRUE) {
        echo "User Successfully Registered";
        register($_POST[firstname], $_POST[middlename], $_POST[lastname], $_POST[email], $_POST[dob], $_POST[phone], $_POST[addr1], $_POST[addr2], $_POST[city], $_POST[state], $_POST[country], $_POST[postalCode]);
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        $msg = "Error: " . "<br>" . $conn->error;
        $h_fail = $h_fail . "?msg=" . $msg;
        header($h_fail);
        exit;
    }
    $conn->close();
}
//---------------------------------------------------------------Function Calls--------------------------------------------------------------
if ($_POST[register]) {
    create_user($_POST[email], $_POST[pass1], $_POST[pass2], $_POST[firstname], $_POST[middlename], $_POST[lastname]);
    //register($_POST[firstname], $_POST[middlename], $_POST[lastname], $_POST[email], $_POST[dob], $_POST[phone], $_POST[addr1], $_POST[addr2], $_POST[city], $_POST[state], $_POST[country], $_POST[postalCode]);
}
//-------------------------------------------------------- End of Function Calls ------------------------------------------------------------
?>


Esempio n. 13
0
/**
 * Creates a new user.
 */
function author_save_new()
{
    require_privs('admin.edit');
    extract(psa(array('privs', 'name', 'email', 'RealName')));
    $privs = assert_int($privs);
    if (is_valid_username($name) && is_valid_email($email)) {
        if (user_exists($name)) {
            author_list(array(gTxt('author_already_exists', array('{name}' => $name)), E_ERROR));
            return;
        }
        $password = generate_password(PASSWORD_LENGTH);
        $rs = create_user($name, $email, $password, $RealName, $privs);
        if ($rs) {
            send_password($RealName, $name, $email, $password);
            author_list(gTxt('password_sent_to') . sp . $email);
            return;
        }
    }
    author_list(array(gTxt('error_adding_new_author'), E_ERROR));
}
Esempio n. 14
0
<link rel="stylesheet" href="inc/style.css">
</head>
<body>

<?php 
if (file_exists("install.php")) {
    unlink("install.php");
}
include_once "client_functions.php";
include_once "users.php";
include_once "admin_functions.php";
include_once "list.php";
if (admin_logged_in()) {
    if (isset($_POST['create'])) {
        echo '<div class="login-card">';
        echo "<center>Password : "******"</center>";
        echo '</div>';
        direct("admin.php", 3);
    } elseif (isset($_POST['log_out'])) {
        session_destroy();
        direct('admin.php', 0);
    } elseif (isset($_POST['update_book'])) {
        $list = new BookList(get_pathname());
        $list->saveList();
        echo '<div class="login-card">';
        echo "<center>List has been updated.</center>";
        echo '</div>';
        direct('admin.php', 3);
    } else {
        echo '<div class="login-card">';
        echo "<form method='post' action=''>\n\t\t<input type='submit' name='create' value='Create User' class='login login-submit' />\n\t\t<br/>\n\t\t<input type='submit' name='update_book' value='Update List' class='login login-submit' />\n\t\t<br/>\n\t\t<input type='submit' name='log_out' value='Logout' class='login login-submit' />\n\t\t</form>";
Esempio n. 15
0
 function create_registered_user($profilefields = array())
 {
     global $registration, $SESSION, $USER;
     require_once get_config('libroot') . 'user.php';
     db_begin();
     // Move the user record to the usr table from the registration table
     $registrationid = $registration->id;
     unset($registration->id);
     unset($registration->expiry);
     if ($expirytime = get_config('defaultregistrationexpirylifetime')) {
         $registration->expiry = db_format_timestamp(time() + $expirytime);
     }
     $registration->lastlogin = db_format_timestamp(time());
     $authinstance = get_record('auth_instance', 'institution', $registration->institution, 'authname', $registration->authtype ? $registration->authtype : 'internal');
     if (false == $authinstance) {
         throw new ConfigException('No ' . ($registration->authtype ? $registration->authtype : 'internal') . ' auth instance for institution');
     }
     if (!empty($registration->extra)) {
         // Additional user settings were added during confirmation
         $extrafields = unserialize($registration->extra);
     }
     $user = new User();
     $user->active = 1;
     $user->authinstance = $authinstance->id;
     $user->firstname = $registration->firstname;
     $user->lastname = $registration->lastname;
     $user->email = $registration->email;
     $user->username = get_new_username($user->firstname . $user->lastname);
     $user->passwordchange = 1;
     // Points that indicate the user is a "new user" who should be restricted from spammy activities.
     // We count these down when they do good things; when they have 0 they're no longer a "new user"
     if (is_using_probation()) {
         $user->probation = get_config('probationstartingpoints');
     } else {
         $user->probation = 0;
     }
     if ($registration->institution != 'mahara') {
         if (count_records_select('institution', "name != 'mahara'") == 1 || $registration->pending == 2) {
             if (get_config_plugin('artefact', 'file', 'institutionaloverride')) {
                 $user->quota = get_field('institution', 'defaultquota', 'name', $registration->institution);
             }
         }
     }
     create_user($user, $profilefields);
     // If the institution is 'mahara' then don't do anything
     if ($registration->institution != 'mahara') {
         $institutions = get_records_select_array('institution', "name != 'mahara'");
         // If there is only one available, join it without requiring approval
         if (count($institutions) == 1) {
             $user->join_institution($registration->institution);
         } else {
             if ($registration->pending == 2) {
                 if (get_config('requireregistrationconfirm') || get_field('institution', 'registerconfirm', 'name', $registration->institution)) {
                     $user->join_institution($registration->institution);
                 }
             } else {
                 if ($registration->authtype && $registration->authtype != 'internal') {
                     $auth = AuthFactory::create($authinstance->id);
                     if ($auth->weautocreateusers) {
                         $user->join_institution($registration->institution);
                     } else {
                         $user->add_institution_request($registration->institution);
                     }
                 } else {
                     $user->add_institution_request($registration->institution);
                 }
             }
         }
         if (!empty($extrafields->institutionstaff)) {
             // If the user isn't a member yet, this does nothing, but that's okay, it'll
             // only be set after successful confirmation.
             set_field('usr_institution', 'staff', 1, 'usr', $user->id, 'institution', $registration->institution);
         }
     }
     if (!empty($registration->lang) && $registration->lang != 'default') {
         set_account_preference($user->id, 'lang', $registration->lang);
     }
     // Delete the old registration record
     delete_records('usr_registration', 'id', $registrationid);
     db_commit();
     // Log the user in and send them to the homepage
     $USER = new LiveUser();
     $USER->reanimate($user->id, $authinstance->id);
     if (function_exists('local_post_register')) {
         local_post_register($registration);
     }
     $SESSION->add_ok_msg(get_string('registrationcomplete', 'mahara', get_config('sitename')));
     $SESSION->set('resetusername', true);
     redirect();
 }
Esempio n. 16
0
<?php

session_start();
include 'account_utils.php';
require_once 'mysqli_connect.php';
if (isset($_SESSION['login'])) {
    header("Location: index.php");
    exit;
}
if (isset($_POST['create_account'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    if (create_user($dbc, $username, $password, $_POST['password2'], $_POST['firstname'], $_POST['lastname'])) {
        login($dbc, $username, $password);
        header("Location: picks_table.php");
    } else {
        echo '
Something went wrong and I\'m too tired to figure it out.

<form action="create_account.php" method="post">
	User name:<br>
	<input type="text" name="username"><br>
	User password:<br>
	<input type="password" name="password"><br>
	Re-enter password:<br>
	<input type="password" name="password2"><br>
	First Name:<br>
	<input type="text" name="firstname"><br>
	Last Name:<br>
	<input type="text" name="lastname"><br>
Esempio n. 17
0
    setcookie("artica-language", $_SESSION["detected_lang"], time() + 172800);
}
if (isset($_GET["confirm"])) {
    confirm();
    exit;
}
if (isset($_GET["create-ou"])) {
    create_ou();
    exit;
}
if (isset($_GET["create-domain"])) {
    create_domain();
    exit;
}
if (isset($_GET["create-user"])) {
    create_user();
    exit;
}
if (isset($_GET["create-group"])) {
    create_group();
    exit;
}
if (isset($_GET["create-groupwares"])) {
    create_groupwares();
    exit;
}
if (isset($_GET["create-conclusion"])) {
    create_conclusion();
    exit;
}
if (isset($_GET["getcredentials"])) {
Esempio n. 18
0
function adduser_submit(Pieform $form, $values)
{
    global $USER, $SESSION, $TRANSPORTER;
    db_begin();
    raise_time_limit(180);
    // Create user
    $user = (object) array('authinstance' => $values['authinstance'], 'username' => $values['username'], 'firstname' => $values['firstname'] ? $values['firstname'] : 'Imported', 'lastname' => $values['lastname'] ? $values['lastname'] : 'User', 'email' => $values['email'], 'password' => $values['password'], 'passwordchange' => 1);
    if ($USER->get('admin')) {
        // Not editable by institutional admins
        $user->staff = (int) ($values['staff'] == 'on');
        $user->admin = (int) ($values['admin'] == 'on');
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $user->quota = $values['quota'];
    }
    $authinstance = get_record('auth_instance', 'id', $values['authinstance']);
    $remoteauth = false;
    if ($authinstance->authname != 'internal') {
        $remoteauth = true;
    }
    if (!isset($values['remoteusername'])) {
        $values['remoteusername'] = null;
    }
    $user->id = create_user($user, array(), $authinstance->institution, $remoteauth, $values['remoteusername'], $values);
    if (isset($user->admin) && $user->admin) {
        require_once 'activity.php';
        activity_add_admin_defaults(array($user->id));
    }
    if ($values['institutionadmin']) {
        set_field('usr_institution', 'admin', 1, 'usr', $user->id, 'institution', $authinstance->institution);
    }
    if (isset($values['leap2afile'])) {
        // And we're good to go
        $importdata = (object) array('token' => '', 'usr' => $user->id, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_FILE, 'profile' => true);
        $importer = PluginImport::create_importer(null, $TRANSPORTER, $importdata);
        try {
            $importer->process();
            log_info("Imported user account {$user->id} from Leap2A file, see " . $importer->get('logfile') . ' for a full log');
        } catch (ImportException $e) {
            log_info("Leap2A import failed: " . $e->getMessage());
            die_info(get_string('leap2aimportfailed', 'admin'));
        }
        // Reload the user details, as various fields are changed by the
        // importer when importing (e.g. firstname/lastname)
        $user = get_record('usr', 'id', $user->id);
    }
    db_commit();
    if (!empty($user->email)) {
        try {
            email_user($user, $USER, get_string('accountcreated', 'mahara', get_config('sitename')), get_string('accountcreatedchangepasswordtext', 'mahara', $user->firstname, get_config('sitename'), $user->username, $values['password'], get_config('wwwroot'), get_config('sitename')), get_string('accountcreatedchangepasswordhtml', 'mahara', $user->firstname, get_config('wwwroot'), get_config('sitename'), $user->username, $values['password'], get_config('wwwroot'), get_config('wwwroot'), get_config('sitename')));
        } catch (EmailException $e) {
            $SESSION->add_error_msg(get_string('newuseremailnotsent', 'admin'));
        }
    }
    $SESSION->add_ok_msg(get_string('newusercreated', 'admin'));
    redirect('/admin/users/edit.php?id=' . $user->id);
}
Esempio n. 19
0
 /**
  * Create multiple users
  * @param array|struct $params - need to be define as struct for XMLRPC
  * @subparam string $params:user->username
  * @subparam string $params:user->firstname
  * @subparam string $params:user->lastname
  * @subparam string $params:user->email
  * @subparam string $params:user->password
  * @return array $return ids of new user
  * @subreturn integer $return:id user id
  */
 static function create_users($params)
 {
     global $USER;
     if (has_capability('moodle/user:create', get_context_instance(CONTEXT_SYSTEM))) {
         $userids = array();
         foreach ($params as $userparams) {
             $user = new stdClass();
             if (array_key_exists('email', $userparams)) {
                 $user->email = clean_param($userparams['email'], PARAM_NOTAGS);
             }
             if (array_key_exists('password', $userparams)) {
                 $user->password = clean_param($userparams['password'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('idnumber', $userparams)) {
                 $user->idnumber = clean_param($userparams['idnumber'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('description', $userparams)) {
                 $user->description = clean_param($userparams['description'], PARAM_TEXT);
             }
             if (array_key_exists('username', $userparams)) {
                 $user->username = clean_param($userparams['username'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('auth', $userparams)) {
                 $user->auth = clean_param($userparams['auth'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('confirmed', $userparams)) {
                 $user->confirmed = clean_param($userparams['confirmed'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('firstname', $userparams)) {
                 $user->firstname = clean_param($userparams['firstname'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('lastname', $userparams)) {
                 $user->lastname = clean_param($userparams['lastname'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('emailstop', $userparams)) {
                 $user->emailstop = clean_param($userparams['emailstop'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('lang', $userparams)) {
                 $user->lang = clean_param($userparams['lang'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('theme', $userparams)) {
                 $user->theme = clean_param($userparams['theme'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('timezone', $userparams)) {
                 $user->timezone = clean_param($userparams['timezone'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('city', $userparams)) {
                 $user->city = clean_param($userparams['city'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('country', $userparams)) {
                 $user->country = clean_param($userparams['country'], PARAM_ALPHANUMEXT);
             }
             if (array_key_exists('mailformat', $userparams)) {
                 $user->mailformat = clean_param($userparams['mailformat'], PARAM_ALPHANUMEXT);
             }
             try {
                 $userids[$userparams['username']] = create_user($user);
             } catch (dml_write_exception $e) {
                 throw new moodle_exception('wscouldnotcreateeuserindb');
             }
         }
         return $userids;
     } else {
         throw new moodle_exception('wscouldnotcreateeusernopermission');
     }
 }
	private function createUserFromContactForm ($user, $contactId, $email, $sendEmail = true) {
		$createUser = false;
		$createPass = false;

		if ( array_var ($user, 'create-user')) {
			$createUser = true;
			if ( array_var ($user, 'create-password') || !$sendEmail) { 
				$createPass = true;
				$password =  array_var($user, 'password');
				$password_a =  array_var($user, 'password_a');
			}
			$type =  array_var($user, 'type');
			$username =  array_var($user, 'username');
		}
		if ($createUser){
			if ($createPass){
				$userData = array(
					'contact_id' => $contactId,
					'username' => $username,
					'email' => $email,
					'password' => $password,
					'password_a' => $password_a,
					'type' => $type,
					'password_generator' => 'specify',
					'send_email_notification' => $sendEmail
				);
			}else{
				$userData = array(
					'contact_id' => $contactId,
					'username' => $username,
					'email' => $email,
					'type' => $type,
					'password_generator' => 'link',
					'send_email_notification' => $sendEmail
				);
			}
			$valid =  Contacts::validateUser($contactId);
			create_user($userData, '');
		}
		
	}
Esempio n. 21
0
/**
 * Users admin page
 *
 * @param App $a
 */
function admin_page_users_post(&$a)
{
    $pending = x($_POST, 'pending') ? $_POST['pending'] : array();
    $users = x($_POST, 'user') ? $_POST['user'] : array();
    $nu_name = x($_POST, 'new_user_name') ? $_POST['new_user_name'] : '';
    $nu_nickname = x($_POST, 'new_user_nickname') ? $_POST['new_user_nickname'] : '';
    $nu_email = x($_POST, 'new_user_email') ? $_POST['new_user_email'] : '';
    check_form_security_token_redirectOnErr('/admin/users', 'admin_users');
    if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) {
        require_once 'include/user.php';
        $result = create_user(array('username' => $nu_name, 'email' => $nu_email, 'nickname' => $nu_nickname, 'verified' => 1));
        if (!$result['success']) {
            notice($result['message']);
            return;
        }
        $nu = $result['user'];
        $preamble = deindent(t('
			Dear %1$s,
				the administrator of %2$s has set up an account for you.'));
        $body = deindent(t('
			The login details are as follows:

			Site Location:	%1$s
			Login Name:		%2$s
			Password:		%3$s

			You may change your password from your account "Settings" page after logging
			in.

			Please take a few moments to review the other account settings on that page.

			You may also wish to add some basic information to your default profile
			(on the "Profiles" page) so that other people can easily find you.

			We recommend setting your full name, adding a profile photo,
			adding some profile "keywords" (very useful in making new friends) - and
			perhaps what country you live in; if you do not wish to be more specific
			than that.

			We fully respect your right to privacy, and none of these items are necessary.
			If you are new and do not know anybody here, they may help
			you to make some new and interesting friends.

			Thank you and welcome to %4$s.'));
        $preamble = sprintf($preamble, $nu['username'], $a->config['sitename']);
        $body = sprintf($body, $a->get_baseurl(), $nu['email'], $result['password'], $a->config['sitename']);
        notification(array('type' => "SYSTEM_EMAIL", 'to_email' => $nu['email'], 'subject' => sprintf(t('Registration details for %s'), $a->config['sitename']), 'preamble' => $preamble, 'body' => $body));
    }
    if (x($_POST, 'page_users_block')) {
        foreach ($users as $uid) {
            q("UPDATE `user` SET `blocked`=1-`blocked` WHERE `uid`=%s", intval($uid));
        }
        notice(sprintf(tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)), count($users)));
    }
    if (x($_POST, 'page_users_delete')) {
        require_once "include/Contact.php";
        foreach ($users as $uid) {
            user_remove($uid);
        }
        notice(sprintf(tt("%s user deleted", "%s users deleted", count($users)), count($users)));
    }
    if (x($_POST, 'page_users_approve')) {
        require_once "mod/regmod.php";
        foreach ($pending as $hash) {
            user_allow($hash);
        }
    }
    if (x($_POST, 'page_users_deny')) {
        require_once "mod/regmod.php";
        foreach ($pending as $hash) {
            user_deny($hash);
        }
    }
    goaway($a->get_baseurl(true) . '/admin/users');
    return;
    // NOTREACHED
}
Esempio n. 22
0
<?php

session_start();
require '../app/Autoloader.class.php';
App\Autoloader::register();
$config = App\Config::getInstance();
$bdd = App\database\Database::getInstance_bdd($config->get("db_name"), $config->get("db_user"), $config->get("db_pass"), $config->get("db_host"));
require '../functions/functions.php';
if (isset($_POST['login']) && isset($_POST['email']) && isset($_POST['password1']) && isset($_POST['password2']) && $_POST['password1'] == $_POST['password2']) {
    if (create_user($bdd, $_POST['login'], $_POST['email'], $_POST['password1'])) {
        $_SESSION['alert'] = "Success";
        header("Location: ../index.php");
        die;
    } else {
        $_SESSION['alert'] = "ERROR";
        header("Location: ../index.php");
        die;
    }
} else {
    $_SESSION['alert'] = "ERROR";
    header("Location: ../index.php");
    die;
}
Esempio n. 23
0
 /**
  * Setup the DB fixture data
  */
 public function setup()
 {
     parent::setUp();
     $tables = array('block_instance', 'cache_flags', 'capabilities', 'context', 'context_temp', 'course', 'course_modules', 'course_categories', 'course_sections', 'files', 'files_cleanup', 'grade_items', 'grade_categories', 'groups', 'groups_members', 'modules', 'role', 'role_names', 'role_context_levels', 'role_assignments', 'role_capabilities', 'user');
     $this->create_test_tables($tables, 'lib');
     $this->create_test_table('forum', 'mod/forum');
     $this->switch_to_test_db();
     global $DB, $CFG;
     // Insert needed capabilities
     $DB->insert_record('capabilities', array('id' => 45, 'name' => 'moodle/course:update', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 14, 'name' => 'moodle/site:backup', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 17, 'name' => 'moodle/site:restore', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 52, 'name' => 'moodle/course:managefiles', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 73, 'name' => 'moodle/user:editownprofile', 'cattype' => 'write', 'contextlevel' => 10, 'component' => 'moodle', 'riskbitmask' => 16));
     // Insert system context
     $DB->insert_record('context', array('id' => 1, 'contextlevel' => 10, 'instanceid' => 0, 'path' => '/1', 'depth' => 1));
     $DB->insert_record('context', array('id' => 2, 'contextlevel' => 50, 'instanceid' => 1, 'path' => '/1/2', 'depth' => 2));
     // Insert site course
     $DB->insert_record('course', array('category' => 0, 'sortorder' => 1, 'fullname' => 'Test site', 'shortname' => 'test', 'format' => 'site', 'modinfo' => 'a:0:{}'));
     // User and capability stuff (stolen from testaccesslib.php)
     $syscontext = get_system_context(false);
     $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
     /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
     assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
     update_capabilities('moodle');
     update_capabilities('mod/forum');
     $contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2)));
     $contexts[0] = $syscontext;
     $contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
     $this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
     $users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0)));
     $admin = $this->testdb->get_record('role', array('shortname' => 'admin'));
     $ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('a' => array($users['a']->id, $admin->id, $contexts[0]->id)));
     $this->switch_global_user_id(1);
     accesslib_clear_all_caches_for_unit_testing();
     // Create a coursecat
     $newcategory = new stdClass();
     $newcategory->name = 'test category';
     $newcategory->sortorder = 999;
     if (!($newcategory->id = $DB->insert_record('course_categories', $newcategory))) {
         print_error('cannotcreatecategory', '', '', format_string($newcategory->name));
     }
     $newcategory->context = get_context_instance(CONTEXT_COURSECAT, $newcategory->id);
     mark_context_dirty($newcategory->context->path);
     fix_course_sortorder();
     // Required to build course_categories.depth and .path.
     $this->coursecat = $DB->get_record('course_categories', array('id' => $newcategory->id));
     // Create a course
     $coursedata = new stdClass();
     $coursedata->category = $newcategory->id;
     $coursedata->shortname = 'testcourse';
     $coursedata->fullname = 'Test Course';
     try {
         $this->course = create_course($coursedata);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test course was not correctly deleted
         $this->course = $DB->get_record('course', array('shortname' => $coursedata->shortname));
     }
     // Create a user
     $this->user = new stdClass();
     $this->user->username = '******';
     $this->user->password = '******';
     $this->user->firstname = 'TestUser';
     $this->user->lastname = 'TestUser';
     $this->user->email = '*****@*****.**';
     try {
         $this->user->id = create_user($this->user);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test user was not correctly deleted
         $this->user->id = $DB->get_field('user', 'id', array('username' => $this->user->username));
     }
     // Assign user to course
     // role_assign(5, $this->user->id, 0, get_context_instance(CONTEXT_COURSE, $this->course->id)->id);
     // Create a module
     $module = new stdClass();
     $module->intro = 'Forum used for testing filelib API';
     $module->type = 'general';
     $module->forcesubscribe = 1;
     $module->format = 1;
     $module->name = 'Test Forum';
     $module->module = $DB->get_field('modules', 'id', array('name' => 'forum'));
     $module->modulename = 'forum';
     $module->add = 'forum';
     $module->cmidnumber = '';
     $module->course = $this->course->id;
     $module->instance = forum_add_instance($module, '');
     $this->section = get_course_section(1, $this->course->id);
     $module->section = $this->section->id;
     $module->coursemodule = add_course_module($module);
     add_mod_to_section($module);
     $module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, '');
     rebuild_course_cache($this->course->id);
     $this->module = $DB->get_record('forum', array('id' => $module->instance));
     $this->module->instance = $module->instance;
     // Update local copy of course
     $this->course = $DB->get_record('course', array('id' => $this->course->id));
 }
Esempio n. 24
0
<?php

require 'libs/functions.php';
$user = isset($_POST['username']) ? $_POST['username'] : '';
$pass = isset($_POST['password']) ? $_POST['password'] : '';
$repass = isset($_POST['repassword']) ? $_POST['repassword'] : '';
$fullname = isset($_POST['fullname']) ? $_POST['fullname'] : '';
$code = 0;
if (validate_user($user) == true) {
    if (strcmp($pass, $repass) == 0 && strlen(trim($pass))) {
        $pass = md5($pass);
        $repass = md5($repass);
        $check = create_user($user, $pass, $fullname);
        if ($check == true) {
            header('Location: login.php');
        } else {
            $code = 1;
        }
    } else {
        $code = 2;
    }
} else {
    $code = 3;
}
if ($code > 0) {
    header('Location: register.php?error=' . $code);
}
Esempio n. 25
0
$perm = 0;
if ($adminflag) {
    $perm |= PERM_ADMIN + PERM_ADULT;
} elseif ($adultflag) {
    $perm |= PERM_ADULT;
}
if ($writeflag) {
    $perm |= PERM_READ + PERM_WRITE;
} elseif ($readflag) {
    $perm |= PERM_READ;
}
// new user?
if ($newuser) {
    $message = $lang['msg_usernotcreated'];
    if ($name && $password) {
        if (create_user($name, $password, $perm, $email) !== false) {
            // create successful?
            $message = $lang['msg_usercreated'];
        } else {
            // error (e.g. duplicate key)?
            $smarty->assign('alert', true);
        }
    } else {
        // name or password missing?
        $smarty->assign('alert', true);
    }
} elseif ($id && $name) {
    runSQL("UPDATE " . TBL_USERS . "\n               SET name = '" . addslashes($name) . "', permissions = {$perm}, email = '" . addslashes($email) . "'\n\t\t\t WHERE id = {$id}");
    // new password?
    if (!empty($password)) {
        $pw = md5($password);
Esempio n. 26
0
<?php

include_once 'main.php';
if (isset($_GET['login'])) {
    $user_email = mysql_real_escape_string($_POST['user_email']);
    $user_password = mysql_real_escape_string($_POST['user_password']);
    $user_remember = $_POST['user_remember'];
    echo login($user_email, $user_password, $user_remember);
} elseif (isset($_GET['logout'])) {
    logout();
} elseif (isset($_GET['create_user'])) {
    $user_name = mysql_real_escape_string(trim($_POST['user_name']));
    $user_email = mysql_real_escape_string($_POST['user_email']);
    $user_password = mysql_real_escape_string($_POST['user_password']);
    $user_secret_code = $_POST['user_secret_code'];
    echo create_user($user_name, $user_email, $user_password, $user_secret_code);
} elseif (isset($_GET['new_user'])) {
    ?>

	<div class="box_div" id="login_div">
		<div class="box_top_div"><a href="#">Inicio</a> &gt; Nuevo usuario</div>
		<div class="box_body_div">
	<div id="new_user_div"><div>

	<form action="." id="new_user_form"><p>

	<label for="user_name_input">Numero Alumno:</label><br>
	<input type="text" id="user_name_input"><br><br>
	<label for="user_email_input">Email:</label><br>
	<input type="text" id="user_email_input" autocapitalize="off"><br><br>
	<label for="user_password_input">Password:</label><br>
Esempio n. 27
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. 28
0
<?php

include '../common.inc.php';
if (!isset($_SESSION)) {
    session_start();
}
//Check if we are getting POST data
if (isset($_POST['submit'])) {
    //Extract the post data from the form and check it against the database, if we have a match start a session and set the user as logged in
    $email = $_POST['email'];
    $password = $_POST['password'];
    //Check to see if this user already exists in the database
    $exists = is_email_unique($email);
    if ($exists) {
        echo $twig->render('register.html.twig', array('messages' => array('type' => 'danger', 'text' => 'Email address already in use')));
    } else {
        //Email does not exist, register the user then redirect
        $user = create_user($email, $password);
        session_start();
        $_SESSION['user'] = $email;
        header('Location: profile.php');
    }
} else {
    echo $twig->render('register.html.twig', array());
}
?>

/**
 * Add the users to the system. Make sure that they have to change their
 * password on next login also.
 */
function uploadcsv_submit(Pieform $form, $values)
{
    global $SESSION, $CSVDATA, $FORMAT;
    $formatkeylookup = array_flip($FORMAT);
    $authinstance = (int) $values['authinstance'];
    $authobj = get_record('auth_instance', 'id', $authinstance);
    $institution = new Institution($authobj->institution);
    $maxusers = $institution->maxuseraccounts;
    if (!empty($maxusers)) {
        $members = count_records_sql('
            SELECT COUNT(*) FROM {usr} u INNER JOIN {usr_institution} i ON u.id = i.usr
            WHERE i.institution = ? AND u.deleted = 0', array($institution->name));
        if ($members + count($CSVDATA) > $maxusers) {
            $SESSION->add_error_msg(get_string('uploadcsvfailedusersexceedmaxallowed', 'admin'));
            redirect('/admin/users/uploadcsv.php');
        }
    }
    log_info('Inserting users from the CSV file');
    db_begin();
    $addedusers = array();
    foreach ($CSVDATA as $record) {
        log_debug('adding user ' . $record[$formatkeylookup['username']]);
        $user = new StdClass();
        $user->authinstance = $authinstance;
        $user->username = $record[$formatkeylookup['username']];
        $user->firstname = $record[$formatkeylookup['firstname']];
        $user->lastname = $record[$formatkeylookup['lastname']];
        $user->password = $record[$formatkeylookup['password']];
        $user->email = $record[$formatkeylookup['email']];
        if (isset($formatkeylookup['studentid'])) {
            $user->studentid = $record[$formatkeylookup['studentid']];
        }
        if (isset($formatkeylookup['preferredname'])) {
            $user->preferredname = $record[$formatkeylookup['preferredname']];
        }
        $user->passwordchange = (int) $values['forcepasswordchange'];
        $profilefields = new StdClass();
        foreach ($FORMAT as $field) {
            if ($field == 'username' || $field == 'password') {
                continue;
            }
            $profilefields->{$field} = $record[$formatkeylookup[$field]];
        }
        $user->id = create_user($user, $profilefields, $institution, $authobj);
        if ($values['emailusers']) {
            $addedusers[] = $user;
        }
    }
    db_commit();
    // Only send e-mail to users after we're sure they have been inserted
    // successfully
    $straccountcreatedtext = $values['forcepasswordchange'] ? 'accountcreatedchangepasswordtext' : 'accountcreatedtext';
    $straccountcreatedhtml = $values['forcepasswordchange'] ? 'accountcreatedchangepasswordhtml' : 'accountcreatedhtml';
    if ($values['emailusers'] && $addedusers) {
        foreach ($addedusers as $user) {
            $failedusers = array();
            try {
                email_user($user, null, get_string('accountcreated', 'mahara', get_config('sitename')), get_string($straccountcreatedtext, 'mahara', $user->firstname, get_config('sitename'), $user->username, $user->password, get_config('wwwroot'), get_config('sitename')), get_string($straccountcreatedhtml, 'mahara', $user->firstname, get_config('wwwroot'), get_config('sitename'), $user->username, $user->password, get_config('wwwroot'), get_config('wwwroot'), get_config('sitename')));
            } catch (EmailException $e) {
                log_info($e->getMessage());
                $failedusers[] = $user;
            }
        }
        if ($failedusers) {
            $message = get_string('uploadcsvsomeuserscouldnotbeemailed', 'admin') . "\n<ul>\n";
            foreach ($failedusers as $user) {
                $message .= '<li>' . full_name($user) . ' &lt;' . hsc($user->email) . "&gt;</li>\n";
            }
            $message .= "</ul>\n";
            $SESSION->add_info_msg($message, false);
        }
    }
    log_info('Inserted ' . count($CSVDATA) . ' records');
    $SESSION->add_ok_msg(get_string('uploadcsvusersaddedsuccessfully', 'admin'));
    redirect('/admin/users/uploadcsv.php');
}
Esempio n. 30
0
     } else {
         // If old workspace exists, we will migrate
         if (!file_exists($conf_home_path . "/c9/workspace/" . $userdata['efn'])) {
             create_user($username, $password);
         }
         activate_user($username, $password);
     }
     break;
     // Create user
 // Create user
 case "add-user":
     $password = $argv[3];
     if (array_key_exists($username, $users)) {
         print "ERROR: User {$username} already exists\n";
     } else {
         create_user($username, $password);
     }
     break;
     // Logout user
 // Logout user
 case "logout":
     deactivate_user($username);
     // Force all logout operations, even if we list user as not logged in
     break;
     // Just stop node
 // Just stop node
 case "stop-node":
     stop_node($username, false);
     // Force all logout operations, even if we list user as not logged in
     break;
     // Remove user from system