Index: moodle/admin/generator.php
--- moodle/admin/generator.php Base (1.33)
+++ moodle/admin/generator.php Locally Modified (Based On 1.33)
@@ -191,7 +191,7 @@
 
     public function generate_users() {
         global $DB, $CFG;
-
+        require_once($CFG->dirroot.'/user/lib.php');
         /**
          * USER GENERATION
          */
@@ -260,7 +260,7 @@
             $user->lang        = $CFG->lang;
             $user->timemodified= time();
 
-            $user->id = $DB->insert_record("user", $user);
+            $user->id = create_user($user);

             $users_count++;
             $users[] = $user->id;
             $next_user_id = $user->id + 1;

Index: moodle/admin/uploaduser.php
--- moodle/admin/uploaduser.php Base (1.106)
+++ moodle/admin/uploaduser.php Locally Modified (Based On 1.106)
@@ -6,6 +6,7 @@
 require('../config.php');
 require_once($CFG->libdir.'/adminlib.php');
 require_once($CFG->libdir.'/csvlib.class.php');
+require_once($CFG->dirroot.'/user/lib.php');
 require_once($CFG->dirroot.'/user/profile/lib.php');
 require_once('uploaduser_form.php');
 
@@ -540,7 +541,7 @@
                 }
             }
 
-            if ($user->id = $DB->insert_record('user', $user)) {
+            if ($user->id = create_user($user, null, $returnurl)) {
                 $info = ': ' . $user->username .' (ID = ' . $user->id . ')';
                 $upt->track('status', $struseradded);
                 $upt->track('id', $user->id, 'normal', false);

Index: moodle/auth/cas/auth.php
--- moodle/auth/cas/auth.php Base (1.43)
+++ moodle/auth/cas/auth.php Locally Modified (Based On 1.43)
@@ -17,6 +17,7 @@
 }
 require_once($CFG->libdir.'/authlib.php');
 require_once($CFG->dirroot.'/auth/cas/CAS/CAS.php');
+require_once($CFG->dirroot.'/user/lib.php');
 /**
  * CAS authentication plugin.
  */
@@ -866,7 +867,7 @@
                 }
 
                 //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-                if ($id = $DB->insert_record('user', $user)) {
+                if ($id = create_user($user)) {
                     echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array($user->username, $id)); echo "\n";
                     $userobj = $this->update_user_record($user->username);
                     if (!empty($this->config->forcechangepassword)) {

Index: moodle/auth/email/auth.php
--- moodle/auth/email/auth.php Base (1.24)
+++ moodle/auth/email/auth.php Locally Modified (Based On 1.24)
@@ -76,11 +76,12 @@
     function user_signup($user, $notify=true) { 
         global $CFG, $DB;
         require_once($CFG->dirroot.'/user/profile/lib.php');
+        require_once($CFG->dirroot.'/user/lib.php');
 
         $user->password = hash_internal_user_password($user->password);
 
         //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-        if (! ($user->id = $DB->insert_record('user', $user)) ) {
+        if (! ($user->id = create_user($user))) {
             print_error('auth_emailnoinsert','auth_email');
         }
 
Index: moodle/auth/ldap/auth.php
--- moodle/auth/ldap/auth.php Base (1.84)
+++ moodle/auth/ldap/auth.php Locally Modified (Based On 1.84)
@@ -29,6 +29,7 @@
 
 
 require_once($CFG->libdir.'/authlib.php');
+require_once($CFG->dirroot.'/user/lib.php');
 
 /**
  * LDAP authentication plugin.
@@ -420,7 +421,7 @@
         }
 
         //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-        if (! ($user->id = $DB->insert_record('user', $user)) ) {
+        if (! ($user->id = create_user($user)) ) {
             print_error('auth_emailnoinsert', 'auth_email');
         }
 
@@ -797,7 +798,7 @@
                 }
 
                 //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-                if ($id = $DB->insert_record('user', $user)) {
+                if ($id = create_user($user)) {
                     echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array($user->username, $id)); echo "\n";
                     $userobj = $this->update_user_record($user->username);
                     if (!empty($this->config->forcechangepassword)) {

Index: moodle/auth/mnet/auth.php
--- moodle/auth/mnet/auth.php Base (1.68)
+++ moodle/auth/mnet/auth.php Locally Modified (Based On 1.68)
@@ -240,6 +240,7 @@
     function confirm_mnet_session($token, $remotewwwroot) {
         global $CFG, $MNET, $SESSION, $DB;
         require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
+        require_once $CFG->dirroot . '/user/lib.php';
 
         // verify the remote host is configured locally before attempting RPC call
         if (! $remotehost = $DB->get_record('mnet_host', array('wwwroot' => $remotewwwroot, 'deleted' => 0))) {
@@ -300,7 +301,7 @@
             $remoteuser->firstaccess = time(); // First time user in this server, grab it here
 
             //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-            $remoteuser->id = $DB->insert_record('user', $remoteuser);
+            $remoteuser->id = create_user($remoteuser);
             $firsttime = true;
             $localuser = $remoteuser;
         }

Index: moodle/backup/restorelib.php
--- moodle/backup/restorelib.php Base (1.413)
+++ moodle/backup/restorelib.php Locally Modified (Based On 1.413)
@@ -3039,8 +3039,8 @@
 
                     //We are going to create the user
                     //The structure is exactly as we need
+                    $newid = create_user($user);
-                    $newid = $DB->insert_record("user", $user);
                     //Put the new id
                     $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,"new");
                 }

Index: moodle/enrol/imsenterprise/enrol.php
--- moodle/enrol/imsenterprise/enrol.php Base (1.31)
+++ moodle/enrol/imsenterprise/enrol.php Locally Modified (Based On 1.31)
@@ -5,6 +5,7 @@
 * @package enrol_imsenterprise
 */
 require_once($CFG->dirroot.'/group/lib.php');
+require_once($CFG->dirroot.'/user/lib.php');
 
 // The following flags are set in the configuration
 // $CFG->enrol_imsfilelocation:        where is the file we are looking for?
@@ -647,7 +648,7 @@
             $person->timemodified = time();
             $person->mnethostid = $CFG->mnet_localhost_id;
             //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-            if($id = $DB->insert_record('user', $person)){
+            if ($id = create_user($person)) {
     /*
     Photo processing is deactivated until we hear from Moodle dev forum about modification to gdlib.
 
Index: moodle/enrol/mnet/enrol.php
--- moodle/enrol/mnet/enrol.php Base (1.30)
+++ moodle/enrol/mnet/enrol.php Locally Modified (Based On 1.30)
@@ -295,8 +295,10 @@
     * @return bool              Whether the enrolment has been successful
     */
     function enrol_user($user, $courseid) {
-        global $MNET, $MNET_REMOTE_CLIENT, $DB;
+        global $MNET, $MNET_REMOTE_CLIENT, $DB, $CFG;
 
+        require_once($CFG->dirroot.'/user/lib.php');
+
         $userrecord = $DB->get_record('user',array('username'=>$user['username'], 'mnethostid'=>$MNET_REMOTE_CLIENT->id));
 
         if ($userrecord == false) {
@@ -311,7 +313,7 @@
             $userrecord->mnethostid = $MNET_REMOTE_CLIENT->id;
 
             //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
-            if ($userrecord->id = $DB->insert_record('user', $userrecord)) {
+            if ($userrecord->id = create_user($userrecord)) {
                 $userrecord = $DB->get_record('user', array('id'=>$userrecord->id));
             } else {
                 throw new mnet_server_exception(5011, get_string('couldnotcreateuser', 'enrol_mnet'));

Index: moodle/lib/db/install.php
--- moodle/lib/db/install.php Base (1.20)
+++ moodle/lib/db/install.php Locally Modified (Based On 1.20)
@@ -6,6 +6,8 @@
 function xmldb_main_install() {
     global $CFG, $DB, $SITE;
 
+    require_once($CFG->dirroot.'/user/lib.php');
+
 /// make sure system context exists
     $syscontext = get_system_context(false);
     if ($syscontext->id != 1) {
@@ -143,7 +145,7 @@
     $guest->confirmed   = 1;
     $guest->lang        = $CFG->lang;
     $guest->timemodified= time();
-    $guest->id = $DB->insert_record('user', $guest);
+    $guest->id = create_user($guest);
 
 
 /// Now create admin user
@@ -160,7 +162,7 @@
     $admin->maildisplay  = 1;
     $admin->timemodified = time();
     $admin->lastip       = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr(); // installation hijacking prevention
-    $admin->id = $DB->insert_record('user', $admin);
+    $admin->id = create_user($admin, 'installadmin');
 
 
 /// Install the roles system.

Index: moodle/lib/moodlelib.php
--- moodle/lib/moodlelib.php Base (1.1278)
+++ moodle/lib/moodlelib.php Locally Modified (Based On 1.1278)
@@ -3318,6 +3318,8 @@
 function create_user_record($username, $password, $auth='manual') {
     global $CFG, $DB;
 
+    require_once($CFG->dirroot.'/user/lib.php');
+    
     //just in case check text case
     $username = trim(moodle_strtolower($username));
 
@@ -3357,7 +3359,7 @@
     $newuser->timemodified = time();
     $newuser->mnethostid = $CFG->mnet_localhost_id;
 
-    $DB->insert_record('user', $newuser);
+    create_user($newuser);
     $user = get_complete_user_data('username', $newuser->username);
     if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
         set_user_preference('auth_forcepasswordchange', 1, $user->id);


Index: moodle/user/editadvanced.php
--- moodle/user/editadvanced.php Base (1.66)
+++ moodle/user/editadvanced.php Locally Modified (Based On 1.66)
@@ -26,6 +26,7 @@
 require_once('../config.php');
 require_once($CFG->libdir.'/gdlib.php');
 require_once($CFG->libdir.'/adminlib.php');
+require_once($CFG->dirroot.'/user/lib.php');
 require_once($CFG->dirroot.'/user/editadvanced_form.php');
 require_once($CFG->dirroot.'/user/editlib.php');
 require_once($CFG->dirroot.'/user/profile/lib.php');
@@ -146,7 +147,7 @@
         $usernew->mnethostid = $CFG->mnet_localhost_id; // always local user
         $usernew->confirmed  = 1;       
         $usernew->password = hash_internal_user_password($usernew->newpassword);        
-        $usernew->id = $DB->insert_record('user', $usernew);
+        $usernew->id = create_user($usernew);        
         $usercreated = true;
 
     } else {

Index: moodle/lang/en_utf8/error.php
--- moodle/lang/en_utf8/error.php Base (1.215)
+++ moodle/lang/en_utf8/error.php Locally Modified (Based On 1.215)
@@ -460,7 +460,10 @@
 $string['userautherror'] = 'Unknown auth plugin';
 $string['userauthunsupported'] = 'Auth plugin not supported here';
 $string['useremailduplicate'] = 'Duplicate address';
+$string['useremailexist'] = 'Email address is already exist';
+$string['useridnumberexist'] = 'User id is already exist';
 $string['usermustbemnet'] = 'Users in the MNET access control list must be remote MNET users';
+$string['usernameexist'] = 'Username is already exist';
 $string['usernotaddedadmin'] = 'Cannot delete admin accounts';
 $string['usernotaddederror'] = 'User not added - error';
 $string['usernotaddedregistered'] = 'User not added - already registered';
@@ -476,6 +479,7 @@
 $string['usernotupdatedadmin'] = 'Cannot update admin accounts';
 $string['usernotupdatederror'] = 'User not updated - error';
 $string['usernotupdatednotexists'] = 'User not updated - does not exist';
+$string['userpasswordrequired'] = 'User required a password.';
 $string['userselectortoomany'] = 'user_selector got more than one selected user, even though multiselect is false.';
 $string['upgraderunning'] = 'Site is being upgraded, please retry later.';
 $string['younotteacher'] = 'You are not a teacher!';

Index: moodle/user/lib.php
--- moodle/user/lib.php No Base Revision
+++ moodle/user/lib.php Locally New
@@ -0,0 +1,118 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Create new user and insert the record into user table
+ * and return the "id" field.
+ *
+ * It will first perform validation and initialize the necessary field
+ * for user's information before inserting to DB.
+ *
+ * @param object $user
+ * @param string $module
+ * @param string $returnurl
+ * @return int
+ */
+function create_user($user, $module = null, $returnurl = null){
+    global $CFG, $DB;
+    
+    if (empty($returnurl) && (!empty($_SERVER['HTTP_REFERER']))) {
+        $returnurl = trim($_SERVER['HTTP_REFERER']);
+    } else if (empty($returnurl)){
+        $returnurl = trim($CFG->wwwroot);
+    }
+
+    // check the username existance in DB
+    if (!empty($user->username)) {
+        $username = $DB->get_record('user', array('username'=>$user->username));
+        if (!empty($username)) {
+            throw new moodle_exception('usernameexist', '', $returnurl);
+        }
+    }
+
+    // make sure password has been set.
+    if (empty($user->password)) {        
+            throw new moodle_exception('userpasswordrequired', '', $returnurl);
+    }
+
+    // check the email existance in DB
+    if (!empty($user->email)) {
+         $email = $DB->get_record('user', array('email'=>$user->email));
+        if (!empty($email)) {
+            throw new moodle_exception('useremailexist', '', $returnurl);
+        }
+    }
+
+    if ($user->firstname) {
+        $user->firstname = trim(ucfirst(strtolower($user->firstname)));       
+    }
+
+    if ($user->lastname) {
+        $user->lastname = trim(ucfirst(strtolower($user->lastname)));
+    }
+
+    if (empty($user->timemodified)) {
+        $user->timemodified = time();
+    }
+
+    if (empty($user->timecreated)) {
+        $user->timecreated = time();
+    }
+    
+    if (empty($user->lang)) {
+        $user->lang = $CFG->lang;
+    }
+        
+    if (empty($user->mnethostid)) {
+        $user->mnethostid = $CFG->mnet_localhost_id; // local user
+    }
+
+    if (empty($user->auth)) {
+        $user->auth = $CFG->auth;
+    }
+
+    if (empty($user->confirmed)) {
+        if ($user->auth == 'cas' || $user->auth == 'ldap' || $user->auth == 'manual') {
+            $user->confirmed = 1;
+        } else {
+            $user->confirmed = 0;
+        }
+    }
+    
+    if ($module == 'installadmin') {
+        if (empty($user->lastip) && CLI_SCRIPT) {
+            $user->lastip = '0.0.0.0';
+        } else if (empty($user->lastip)) {
+            $user->lastip = getremoteaddr();
+        }
+
+        if (empty($user->maildisplay)) {
+            $user->maildisplay = 1;
+        }
+    }
+    
+    if (empty($user->deleted)) {
+        $user->deleted = 0;
+    }
+
+    /// Disable pictures based on global setting or existing empty value
+    if (!empty($CFG->disableuserimages) || empty($user->picture)) {
+        $user->picture = 0;
+    }
+        
+    $user->id = $DB->insert_record("user", $user);
+    return $user->id;    
+}
