MDL-8096 - user edit form splitting, refactoring, cleanup and fixing - work in progre...
authorskodak <skodak>
Thu, 25 Jan 2007 00:04:02 +0000 (00:04 +0000)
committerskodak <skodak>
Thu, 25 Jan 2007 00:04:02 +0000 (00:04 +0000)
* new editadvanced form for creating of users and editing without restrictions
* elliminated fantom changeme user
* updated links and installation process
* see TODO comments in code

admin/index.php
admin/settings/users.php
admin/user.php
lib/adminlib.php
lib/weblib.php
user/edit_form_common.php [new file with mode: 0644]
user/editadvanced.php [new file with mode: 0644]
user/editadvanced_form.php [new file with mode: 0644]
user/tabs.php

index 96814f3..56a9d36 100644 (file)
 
 /// Set up the admin user
     if (empty($CFG->rolesactive)) {
-        redirect('user.php');
+        create_admin_user();
     }
 
 /// Check for valid admin user
index 483846c..f93997d 100644 (file)
@@ -9,7 +9,7 @@ $ADMIN->add('users', new admin_externalpage('userauthentication', get_string('au
 // stuff under the "accounts" subcategory
 $ADMIN->add('users', new admin_category('accounts', get_string('accounts', 'admin')));
 $ADMIN->add('accounts', new admin_externalpage('editusers', get_string('userlist','admin'), "$CFG->wwwroot/$CFG->admin/user.php", array('moodle/user:update', 'moodle/user:delete')));
-$ADMIN->add('accounts', new admin_externalpage('addnewuser', get_string('addnewuser'), "$CFG->wwwroot/$CFG->admin/user.php?newuser=true", 'moodle/user:create'));
+$ADMIN->add('accounts', new admin_externalpage('addnewuser', get_string('addnewuser'), "$CFG->wwwroot/user/editadvanced.php?id=-1", 'moodle/user:create'));
 $ADMIN->add('accounts', new admin_externalpage('uploadusers', get_string('uploadusers'), "$CFG->wwwroot/$CFG->admin/uploaduser.php", 'moodle/site:uploadusers'));
 $ADMIN->add('accounts', new admin_externalpage('profilefields', get_string('profilefields','admin'), "$CFG->wwwroot/user/profile/index.php", 'moodle/user:update'));
 
index 5d74bc5..2fe06de 100644 (file)
@@ -3,7 +3,6 @@
     require_once('../config.php');
     require_once($CFG->libdir.'/adminlib.php');
 
-    $newuser      = optional_param('newuser', 0, PARAM_BOOL);
     $delete       = optional_param('delete', 0, PARAM_INT);
     $confirm      = optional_param('confirm', '', PARAM_ALPHANUM);   //md5 confirmation hash
     $confirmuser  = optional_param('confirmuser', 0, PARAM_INT);
@@ -18,6 +17,9 @@
     $lu           = optional_param('lu', '2', PARAM_INT);            // show local users
     $acl          = optional_param('acl', '0', PARAM_INT);           // id of user to tweak mnet ACL (requires $access)
 
+    $adminroot = admin_get_root();
+    admin_externalpage_setup('editusers', $adminroot);
+
     // Let's see if we have *any* mnet users. Just ask for a single record
     $mnet_users = get_records_select('user', " auth='mnet' AND mnethostid != '{$CFG->mnet_localhost_id}' ", '', '*', '0', '1');
     if(is_array($mnet_users) && count($mnet_users) > 0) {
         }
     }
 
-    if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID)) {  // Should never happen
-        redirect('index.php');
+    $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
+    $site = get_site();
+
+    if (!has_capability('moodle/user:update', $sitecontext) and !has_capability('moodle/user:delete', $sitecontext)) {
+        error('You do not have the required permission to edit/delete users.');
     }
 
-    if (empty($CFG->rolesactive)) {   // No admin user yet.
-
-        $user = new object();
-        $user->firstname    = get_string('admin');
-        $user->lastname     = get_string('user');
-        $user->username     = 'admin';
-        $user->password     = hash_internal_user_password('admin');
-        $user->email        = 'root@localhost';
-        $user->confirmed    = 1;
-        $user->mnethostid   = $CFG->mnet_localhost_id;
-        $user->lang         = $CFG->lang;
-        $user->maildisplay  = 1;
-        $user->timemodified = time();
-
-        if (! $user->id = insert_record('user', $user)) {
-            error("SERIOUS ERROR: Could not create admin user record !!!");
-        }
+    $stredit   = get_string('edit');
+    $strdelete = get_string('delete');
+    $strdeletecheck = get_string('deletecheck');
+    $strsearch = get_string('search');
+    $strshowallusers = get_string('showallusers');
 
-        if (! $user = get_record('user', 'id', $user->id)) {   // Double check.
-            error("User ID was incorrect (can't find it)");
-        }
+    admin_externalpage_print_header($adminroot);
 
-
-        // Assign the default admin role to the new user.
-        if (!$adminroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW)) {
-            error('No admin role could be found');
-        }
-        foreach ($adminroles as $adminrole) {
-            role_assign($adminrole->id, $user->id, 0, $sitecontext->id);
+    if ($confirmuser and confirm_sesskey()) {
+        if (!$user = get_record('user', 'id', $confirmuser)) {
+            error("No such user!");
         }
-        set_config('rolesactive', 1);
 
+        $confirmeduser = new object();
+        $confirmeduser->id = $confirmuser;
+        $confirmeduser->confirmed = 1;
+        $confirmeduser->timemodified = time();
 
-        if (! $site = get_site()) {
-            error("Could not find site-level course");
+        if (update_record('user', $confirmeduser)) {
+            notify(get_string('userconfirmed', '', fullname($user, true)) );
+        } else {
+            notify(get_string('usernotconfirmed', '', fullname($user, true)));
         }
 
-        // Log the user in.
-        $USER = $user;
-        $USER->loggedin = true;
-        $USER->sessionIP = md5(getremoteaddr());   // Store the current IP in the session
-        $USER->site = $CFG->wwwroot;
-        $USER->admin = true;
-        $USER->newadminuser = true;
-
-        sesskey();   // For added security, used to check script parameters
+    } else if ($delete and confirm_sesskey()) {              // Delete a selected user, after confirmation
 
-        load_all_capabilities();
-
-        redirect("$CFG->wwwroot/user/edit.php?id=$user->id&amp;course=$site->id");  // Edit thyself
-        exit;
-
-    } else {
-        if (! $site = get_site()) {
-            error("Could not find site-level course");
+        if (!has_capability('moodle/user:delete', $sitecontext)) {
+            error('You do not have the required permission to delete a user.');
         }
-    }
-
-    require_login();
-
-    $adminroot = admin_get_root();
-
-    if ($newuser) {
-        admin_externalpage_setup('addnewuser', $adminroot);
-    } else {
-        admin_externalpage_setup('editusers', $adminroot);
-    }
-
 
-    if ($newuser) {                 // Create a new user
+        if (!$user = get_record('user', 'id', $delete)) {
+            error("No such user!");
+        }
 
-        if (!has_capability('moodle/user:create', $sitecontext)) {
-            error('You do not have the required permission to create new users.');
+        $primaryadmin = get_admin();
+        if ($user->id == $primaryadmin->id) {
+            error("You are not allowed to delete the primary admin user!");
         }
 
-        if (!$user = get_record('user', 'username', 'changeme')) {   // half finished user from another time
-
-            $user = new object();
-            $user->auth         = 'manual';
-            $user->firstname    = '';
-            $user->lastname     = '';
-            $user->username     = 'changeme';
-            $user->password     = '';
-            $user->email        = '';
-            $user->lang         = $CFG->lang;
-            $user->confirmed    = 1;
-            $user->timemodified = time();
-            $user->mnethostid   = $CFG->mnet_localhost_id;
-
-            if (! $user->id = insert_record('user', $user)) {
-                error('Could not start a new user!');
+        if ($confirm != md5($delete)) {
+            $fullname = fullname($user, true);
+            print_heading(get_string('deleteuser', 'admin'));
+            $optionsyes = array('delete'=>$delete, 'confirm'=>md5($delete), 'sesskey'=>sesskey());
+            notice_yesno(get_string('deletecheckfull', '', "'$fullname'"), 'user.php', 'user.php', $optionsyes, NULL, 'post', 'get');
+            admin_externalpage_print_footer($adminroot);
+            die;
+        } else if (data_submitted() and !$user->deleted) {
+            $updateuser = new object();
+            $updateuser->id = $user->id;
+            $updateuser->deleted = 1;
+            $updateuser->username = addslashes("$user->email.".time());  // Remember it just in case
+            $updateuser->email = '';               // Clear this field to free it up
+            $updateuser->idnumber = '';               // Clear this field to free it up
+            $updateuser->timemodified = time();
+            if (update_record('user', $updateuser)) {
+                // not sure if this is needed. unenrol_student($user->id);  // From all courses
+                delete_records('role_assignments', 'userid', $user->id); // unassign all roles
+                // remove all context assigned on this user?
+                notify(get_string('deletedactivity', '', fullname($user, true)) );
+            } else {
+                notify(get_string('deletednot', '', fullname($user, true)));
             }
         }
-
-        redirect("$CFG->wwwroot/user/edit.php?id=$user->id&amp;course=$site->id");
-
-    } else {                        // List all users for editing
-
-        if (!has_capability('moodle/user:update', $sitecontext) and !has_capability('moodle/user:delete', $sitecontext)) {
-            error('You do not have the required permission to edit/delete users.');
+    } else if ($acl and confirm_sesskey()) {
+        if (!has_capability('moodle/user:delete', $sitecontext)) {
+            // TODO: this should be under a separate capability
+            error('You are not permitted to modify the MNET access control list.');
         }
-
-        $stredit   = get_string('edit');
-        $strdelete = get_string('delete');
-        $strdeletecheck = get_string('deletecheck');
-        $strsearch = get_string('search');
-        $strshowallusers = get_string('showallusers');
-
-        admin_externalpage_print_header($adminroot);
-
-        if ($confirmuser and confirm_sesskey()) {
-            if (!$user = get_record('user', 'id', $confirmuser)) {
-                error("No such user!");
-            }
-
-            $confirmeduser = new object();
-            $confirmeduser->id = $confirmuser;
-            $confirmeduser->confirmed = 1;
-            $confirmeduser->timemodified = time();
-
-            if (update_record('user', $confirmeduser)) {
-                notify(get_string('userconfirmed', '', fullname($user, true)) );
-            } else {
-                notify(get_string('usernotconfirmed', '', fullname($user, true)));
+        if (!$user = get_record('user', 'id', $acl)) {
+            error("No such user.");
+        }
+        if (!is_mnet_remote_user($user)) {
+            error('Users in the MNET access control list must be remote MNET users.');
+        }
+        $accessctrl = strtolower(required_param('accessctrl', PARAM_ALPHA));
+        if ($accessctrl != 'allow' and $accessctrl != 'deny') {
+            error('Invalid access parameter.');
+        }
+        $aclrecord = get_record('mnet_sso_access_control', 'username', $user->username, 'mnet_host_id', $user->mnethostid);
+        if (empty($aclrecord)) {
+            $aclrecord = new object();
+            $aclrecord->mnet_host_id = $user->mnethostid;
+            $aclrecord->username = $user->username;
+            $aclrecord->accessctrl = $accessctrl;
+            if (!insert_record('mnet_sso_access_control', $aclrecord)) {
+                error("Database error - Couldn't modify the MNET access control list.");
             }
-
-        } else if ($delete and confirm_sesskey()) {              // Delete a selected user, after confirmation
-
-            if (!has_capability('moodle/user:delete', $sitecontext)) {
-                error('You do not have the required permission to delete a user.');
+        } else {
+            $aclrecord->accessctrl = $accessctrl;
+            if (!update_record('mnet_sso_access_control', $aclrecord)) {
+                error("Database error - Couldn't modify the MNET access control list.");
             }
+        }
+        $mnethosts = get_records('mnet_host', '', '', 'id', 'id,wwwroot,name');
+        notify("MNET access control list updated: username '$user->username' from host '"
+                . $mnethosts[$user->mnethostid]->name
+                . "' access now set to '$accessctrl'.");
+    }
 
-            if (!$user = get_record('user', 'id', $delete)) {
-                error("No such user!");
-            }
+    // Carry on with the user listing
 
-            $primaryadmin = get_admin();
-            if ($user->id == $primaryadmin->id) {
-                error("You are not allowed to delete the primary admin user!");
-            }
+    $columns = array("firstname", "lastname", "email", "city", "country", "lastaccess");
 
-            if ($confirm != md5($delete)) {
-                $fullname = fullname($user, true);
-                print_heading(get_string('deleteuser', 'admin'));
-                $optionsyes = array('delete'=>$delete, 'confirm'=>md5($delete), 'sesskey'=>sesskey());
-                notice_yesno(get_string('deletecheckfull', '', "'$fullname'"), 'user.php', 'user.php', $optionsyes, NULL, 'post', 'get');
-                admin_externalpage_print_footer($adminroot);
-                die;
-            } else if (data_submitted() and !$user->deleted) {
-                $updateuser = new object();
-                $updateuser->id = $user->id;
-                $updateuser->deleted = 1;
-                $updateuser->username = addslashes("$user->email.".time());  // Remember it just in case
-                $updateuser->email = '';               // Clear this field to free it up
-                $updateuser->idnumber = '';               // Clear this field to free it up
-                $updateuser->timemodified = time();
-                if (update_record('user', $updateuser)) {
-                    // not sure if this is needed. unenrol_student($user->id);  // From all courses
-                    delete_records('role_assignments', 'userid', $user->id); // unassign all roles
-                    // remove all context assigned on this user?
-                    notify(get_string('deletedactivity', '', fullname($user, true)) );
-                } else {
-                    notify(get_string('deletednot', '', fullname($user, true)));
-                }
-            }
-        } else if ($acl and confirm_sesskey()) {
-            if (!has_capability('moodle/user:delete', $sitecontext)) {
-                // TODO: this should be under a separate capability
-                error('You are not permitted to modify the MNET access control list.');
-            }
-            if (!$user = get_record('user', 'id', $acl)) {
-                error("No such user.");
-            }
-            if (!is_mnet_remote_user($user)) {
-                error('Users in the MNET access control list must be remote MNET users.');
-            }
-            $accessctrl = strtolower(required_param('accessctrl', PARAM_ALPHA));
-            if ($accessctrl != 'allow' and $accessctrl != 'deny') {
-                error('Invalid access parameter.');
+    foreach ($columns as $column) {
+        $string[$column] = get_string("$column");
+        if ($sort != $column) {
+            $columnicon = "";
+            if ($column == "lastaccess") {
+                $columndir = "DESC";
+            } else {
+                $columndir = "ASC";
             }
-            $aclrecord = get_record('mnet_sso_access_control', 'username', $user->username, 'mnet_host_id', $user->mnethostid);
-            if (empty($aclrecord)) {
-                $aclrecord = new object();
-                $aclrecord->mnet_host_id = $user->mnethostid;
-                $aclrecord->username = $user->username;
-                $aclrecord->accessctrl = $accessctrl;
-                if (!insert_record('mnet_sso_access_control', $aclrecord)) {
-                    error("Database error - Couldn't modify the MNET access control list.");
-                }
+        } else {
+            $columndir = $dir == "ASC" ? "DESC":"ASC";
+            if ($column == "lastaccess") {
+                $columnicon = $dir == "ASC" ? "up":"down";
             } else {
-                $aclrecord->accessctrl = $accessctrl;
-                if (!update_record('mnet_sso_access_control', $aclrecord)) {
-                    error("Database error - Couldn't modify the MNET access control list.");
-                }
+                $columnicon = $dir == "ASC" ? "down":"up";
             }
-            $mnethosts = get_records('mnet_host', '', '', 'id', 'id,wwwroot,name');
-            notify("MNET access control list updated: username '$user->username' from host '"
-                    . $mnethosts[$user->mnethostid]->name
-                    . "' access now set to '$accessctrl'.");
+            $columnicon = " <img src=\"$CFG->pixpath/t/$columnicon.gif\" alt=\"\" />";
+
         }
+        $$column = "<a href=\"user.php?sort=$column&amp;dir=$columndir&amp;search=".urlencode(stripslashes($search))."&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial\">".$string[$column]."</a>$columnicon";
+    }
 
-        // Carry on with the user listing
+    if ($sort == "name") {
+        $sort = "firstname";
+    }
+    
+    // tell the query which users we are looking at (local, remote, or both)
+    $remotewhere = '';
+    if($mnet_auth_users && ($localusers XOR $remoteusers)) {
+        if ($localusers) {
+            $remotewhere .= " and mnethostid = {$CFG->mnet_localhost_id} ";
+        } else {
+            $remotewhere .= " and mnethostid <> {$CFG->mnet_localhost_id} ";
+        }
+    }
+    
+    $users = get_users_listing($sort, $dir, $page*$perpage, $perpage, $search, $firstinitial, $lastinitial, $remotewhere);
+    $usercount = get_users(false);
+    $usersearchcount = get_users(false, $search, true, "", "", $firstinitial, $lastinitial);
 
-        $columns = array("firstname", "lastname", "email", "city", "country", "lastaccess");
+    if ($search or $firstinitial or $lastinitial) {
+        print_heading("$usersearchcount / $usercount ".get_string('users'));
+        $usercount = $usersearchcount;
+    } else {
+        print_heading("$usercount ".get_string('users'));
+    }
 
-        foreach ($columns as $column) {
-            $string[$column] = get_string("$column");
-            if ($sort != $column) {
-                $columnicon = "";
-                if ($column == "lastaccess") {
-                    $columndir = "DESC";
-                } else {
-                    $columndir = "ASC";
-                }
-            } else {
-                $columndir = $dir == "ASC" ? "DESC":"ASC";
-                if ($column == "lastaccess") {
-                    $columnicon = $dir == "ASC" ? "up":"down";
-                } else {
-                    $columnicon = $dir == "ASC" ? "down":"up";
-                }
-                $columnicon = " <img src=\"$CFG->pixpath/t/$columnicon.gif\" alt=\"\" />";
+    $alphabet = explode(',', get_string('alphabet'));
+    $strall = get_string('all');
 
-            }
-            $$column = "<a href=\"user.php?sort=$column&amp;dir=$columndir&amp;search=".urlencode(stripslashes($search))."&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial\">".$string[$column]."</a>$columnicon";
-        }
 
-        if ($sort == "name") {
-            $sort = "firstname";
-        }
-        
-        // tell the query which users we are looking at (local, remote, or both)
-        $remotewhere = '';
-        if($mnet_auth_users && ($localusers XOR $remoteusers)) {
-            if ($localusers) {
-                $remotewhere .= " and mnethostid = {$CFG->mnet_localhost_id} ";
-            } else {
-                $remotewhere .= " and mnethostid <> {$CFG->mnet_localhost_id} ";
-            }
+    /// Bar of first initials
+
+    echo "<center><p align=\"center\">";
+    echo get_string("firstname")." : ";
+    if ($firstinitial) {
+        echo " <a href=\"user.php?sort=firstname&amp;dir=ASC&amp;".
+             "perpage=$perpage&amp;lastinitial=$lastinitial\">$strall</a> ";
+    } else {
+        echo " <b>$strall</b> ";
+    }
+    foreach ($alphabet as $letter) {
+        if ($letter == $firstinitial) {
+            echo " <b>$letter</b> ";
+        } else {
+            echo " <a href=\"user.php?sort=firstname&amp;dir=ASC&amp;".
+                 "perpage=$perpage&amp;lastinitial=$lastinitial&amp;firstinitial=$letter\">$letter</a> ";
         }
-        
-        $users = get_users_listing($sort, $dir, $page*$perpage, $perpage, $search, $firstinitial, $lastinitial, $remotewhere);
-        $usercount = get_users(false);
-        $usersearchcount = get_users(false, $search, true, "", "", $firstinitial, $lastinitial);
-
-        if ($search or $firstinitial or $lastinitial) {
-            print_heading("$usersearchcount / $usercount ".get_string('users'));
-            $usercount = $usersearchcount;
+    }
+    echo "<br />";
+
+    /// Bar of last initials
+
+    echo get_string("lastname")." : ";
+    if ($lastinitial) {
+        echo " <a href=\"user.php?sort=lastname&amp;dir=ASC&amp;".
+             "perpage=$perpage&amp;firstinitial=$firstinitial\">$strall</a> ";
+    } else {
+        echo " <b>$strall</b> ";
+    }
+    foreach ($alphabet as $letter) {
+        if ($letter == $lastinitial) {
+            echo " <b>$letter</b> ";
         } else {
-            print_heading("$usercount ".get_string('users'));
+            echo " <a href=\"user.php?sort=lastname&amp;dir=ASC&amp;".
+                 "perpage=$perpage&amp;firstinitial=$firstinitial&amp;lastinitial=$letter\">$letter</a> ";
         }
+    }
+    echo "</p>";
+    echo "</center>";
 
-        $alphabet = explode(',', get_string('alphabet'));
-        $strall = get_string('all');
+    print_paging_bar($usercount, $page, $perpage,
+            "user.php?sort=$sort&amp;dir=$dir&amp;perpage=$perpage&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial&amp;search=".urlencode(stripslashes($search))."&amp;");
 
+    flush();
 
-        /// Bar of first initials
 
-        echo "<center><p align=\"center\">";
-        echo get_string("firstname")." : ";
-        if ($firstinitial) {
-            echo " <a href=\"user.php?sort=firstname&amp;dir=ASC&amp;".
-                 "perpage=$perpage&amp;lastinitial=$lastinitial\">$strall</a> ";
-        } else {
-            echo " <b>$strall</b> ";
+    if (!$users) {
+        $match = array();
+        if ($search !== '') {
+           $match[] = s($search);
         }
-        foreach ($alphabet as $letter) {
-            if ($letter == $firstinitial) {
-                echo " <b>$letter</b> ";
-            } else {
-                echo " <a href=\"user.php?sort=firstname&amp;dir=ASC&amp;".
-                     "perpage=$perpage&amp;lastinitial=$lastinitial&amp;firstinitial=$letter\">$letter</a> ";
-            }
+        if ($firstinitial) {
+           $match[] = get_string('firstname').": $firstinitial"."___";
         }
-        echo "<br />";
-
-        /// Bar of last initials
-
-        echo get_string("lastname")." : ";
         if ($lastinitial) {
-            echo " <a href=\"user.php?sort=lastname&amp;dir=ASC&amp;".
-                 "perpage=$perpage&amp;firstinitial=$firstinitial\">$strall</a> ";
-        } else {
-            echo " <b>$strall</b> ";
+           $match[] = get_string('lastname').": $lastinitial"."___";
         }
-        foreach ($alphabet as $letter) {
-            if ($letter == $lastinitial) {
-                echo " <b>$letter</b> ";
-            } else {
-                echo " <a href=\"user.php?sort=lastname&amp;dir=ASC&amp;".
-                     "perpage=$perpage&amp;firstinitial=$firstinitial&amp;lastinitial=$letter\">$letter</a> ";
-            }
-        }
-        echo "</p>";
-        echo "</center>";
+        $matchstring = implode(", ", $match);
+        print_heading(get_string('nousersmatching', '', $matchstring));
 
-        print_paging_bar($usercount, $page, $perpage,
-                "user.php?sort=$sort&amp;dir=$dir&amp;perpage=$perpage&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial&amp;search=".urlencode(stripslashes($search))."&amp;");
+        $table = NULL;
 
-        flush();
+    } else {
 
+        $countries = get_list_of_countries();
+        if (empty($mnethosts)) {
+            $mnethosts = get_records('mnet_host', '', '', 'id', 'id,wwwroot,name');
+        }
 
-        if (!$users) {
-            $match = array();
-            if ($search !== '') {
-               $match[] = s($search);
+        foreach ($users as $key => $user) {
+            if (!empty($user->country)) {
+                $users[$key]->country = $countries[$user->country];
             }
-            if ($firstinitial) {
-               $match[] = get_string('firstname').": $firstinitial"."___";
+        }
+        if ($sort == "country") {  // Need to resort by full country name, not code
+            foreach ($users as $user) {
+                $susers[$user->id] = $user->country;
             }
-            if ($lastinitial) {
-               $match[] = get_string('lastname').": $lastinitial"."___";
+            asort($susers);
+            foreach ($susers as $key => $value) {
+                $nusers[] = $users[$key];
             }
-            $matchstring = implode(", ", $match);
-            print_heading(get_string('nousersmatching', '', $matchstring));
-
-            $table = NULL;
-
-        } else {
+            $users = $nusers;
+        }
 
-            $countries = get_list_of_countries();
-            if (empty($mnethosts)) {
-                $mnethosts = get_records('mnet_host', '', '', 'id', 'id,wwwroot,name');
+        $mainadmin = get_admin();
+        $table->head = array ("$firstname / $lastname", $email, $city, $country, $lastaccess, "", "", "");
+        $table->align = array ("left", "left", "left", "left", "left", "center", "center", "center");
+        $table->width = "95%";
+        foreach ($users as $user) {
+            if ($user->username == 'changeme' or $user->username == 'guest') {
+                continue; // do not dispaly dummy new user and guest here
             }
 
-            foreach ($users as $key => $user) {
-                if (!empty($user->country)) {
-                    $users[$key]->country = $countries[$user->country];
-                }
-            }
-            if ($sort == "country") {  // Need to resort by full country name, not code
-                foreach ($users as $user) {
-                    $susers[$user->id] = $user->country;
-                }
-                asort($susers);
-                foreach ($susers as $key => $value) {
-                    $nusers[] = $users[$key];
+            if ($user->id == $USER->id) {
+                $deletebutton = "";
+            } else {
+                if (has_capability('moodle/user:delete', $sitecontext)) {
+                    $deletebutton = "<a href=\"user.php?delete=$user->id&amp;sesskey=$USER->sesskey\">$strdelete</a>";
+                } else {
+                    $deletebutton ="";
                 }
-                $users = $nusers;
             }
 
-            $table->head = array ("$firstname / $lastname", $email, $city, $country, $lastaccess, "", "", "");
-            $table->align = array ("left", "left", "left", "left", "left", "center", "center", "center");
-            $table->width = "95%";
-            foreach ($users as $user) {
-                if ($user->username == 'changeme' or $user->username == 'guest') {
-                    continue; // do not dispaly dummy new user and guest here
-                }
-
-                if ($user->id == $USER->id) {
-                    $deletebutton = "";
+            if (has_capability('moodle/user:update', $sitecontext) and ($user->id==$USER->id or $user->id != $mainadmin->id) and !is_mnet_remote_user($user)) {
+                $editbutton = "<a href=\"../user/editadvanced.php?id=$user->id&amp;course=$site->id\">$stredit</a>";
+                if ($user->confirmed == 0) {
+                    $confirmbutton = "<a href=\"user.php?confirmuser=$user->id&amp;sesskey=$USER->sesskey\">" . get_string('confirm') . "</a>";
                 } else {
-                    if (has_capability('moodle/user:delete', $sitecontext)) {
-                        $deletebutton = "<a href=\"user.php?delete=$user->id&amp;sesskey=$USER->sesskey\">$strdelete</a>";
-                    } else {
-                        $deletebutton ="";
-                    }
+                    $confirmbutton = "";
                 }
-
-                if (has_capability('moodle/user:update', $sitecontext) and ! is_mnet_remote_user($user)) {
-                    $editbutton = "<a href=\"../user/edit.php?id=$user->id&amp;course=$site->id\">$stredit</a>";
-                    if ($user->confirmed == 0) {
-                        $confirmbutton = "<a href=\"user.php?confirmuser=$user->id&amp;sesskey=$USER->sesskey\">" . get_string('confirm') . "</a>";
-                    } else {
-                        $confirmbutton = "";
-                    }
+            } else {
+                $editbutton ="";
+                if ($user->confirmed == 0) {
+                    $confirmbutton = "<span class=\"dimmed_text\">".get_string('confirm')."</span>";
                 } else {
-                    $editbutton ="";
-                    if ($user->confirmed == 0) {
-                        $confirmbutton = "<span class=\"dimmed_text\">".get_string('confirm')."</span>";
-                    } else {
-                        $confirmbutton = "";
-                    }
-                }
-
-                // for remote users, shuffle columns around and display MNET stuff
-                if (is_mnet_remote_user($user)) {
-                    $accessctrl = 'allow';
-                    if ($acl = get_record('mnet_sso_access_control', 'username', $user->username, 'mnet_host_id', $user->mnethostid)) {
-                        $accessctrl = $acl->accessctrl;
-                    }
-                    $changeaccessto = ($accessctrl == 'deny' ? 'allow' : 'deny');
-                    // delete button in confirm column - remote users should already be confirmed
-                    // TODO: no delete for remote users, for now. new userid, delete flag, unique on username/host...
                     $confirmbutton = "";
-                    // ACL in delete column
-                    $deletebutton = get_string($accessctrl, 'mnet');
-                    if (has_capability('moodle/user:delete', $sitecontext)) {
-                        // TODO: this should be under a separate capability
-                        $deletebutton .= " (<a href=\"?acl={$user->id}&amp;accessctrl=$changeaccessto&amp;sesskey={$USER->sesskey}\">"
-                                . get_string($changeaccessto, 'mnet') . " access</a>)";
-                    }
-                    // mnet info in edit column
-                    $editbutton = $mnethosts[$user->mnethostid]->name;
                 }
+            }
 
-                if ($user->lastaccess) {
-                    $strlastaccess = format_time(time() - $user->lastaccess);
-                } else {
-                    $strlastaccess = get_string('never');
+            // for remote users, shuffle columns around and display MNET stuff
+            if (is_mnet_remote_user($user)) {
+                $accessctrl = 'allow';
+                if ($acl = get_record('mnet_sso_access_control', 'username', $user->username, 'mnet_host_id', $user->mnethostid)) {
+                    $accessctrl = $acl->accessctrl;
                 }
-                $fullname = fullname($user, true);
-
-                $table->data[] = array ("<a href=\"../user/view.php?id=$user->id&amp;course=$site->id\">$fullname</a>",
-                                    "$user->email",
-                                    "$user->city",
-                                    "$user->country",
-                                    $strlastaccess,
-                                    $editbutton,
-                                    $deletebutton,
-                                    $confirmbutton);
+                $changeaccessto = ($accessctrl == 'deny' ? 'allow' : 'deny');
+                // delete button in confirm column - remote users should already be confirmed
+                // TODO: no delete for remote users, for now. new userid, delete flag, unique on username/host...
+                $confirmbutton = "";
+                // ACL in delete column
+                $deletebutton = get_string($accessctrl, 'mnet');
+                if (has_capability('moodle/user:delete', $sitecontext)) {
+                    // TODO: this should be under a separate capability
+                    $deletebutton .= " (<a href=\"?acl={$user->id}&amp;accessctrl=$changeaccessto&amp;sesskey={$USER->sesskey}\">"
+                            . get_string($changeaccessto, 'mnet') . " access</a>)";
+                }
+                // mnet info in edit column
+                $editbutton = $mnethosts[$user->mnethostid]->name;
             }
-        }
 
-        if($mnet_auth_users) {
-            echo "<p style=\"text-align:center\">";
-            if ($localusers == 1 && $remoteusers == 1) {
-                echo '<a href="?lu=0">'.get_string('hidelocal','mnet').'</a> | ';
-            } elseif ($localusers == 0)  {
-                echo '<a href="?lu=1">'.get_string('showlocal','mnet').'</a> | ';
+            if ($user->lastaccess) {
+                $strlastaccess = format_time(time() - $user->lastaccess);
             } else {
-                echo get_string('hidelocal','mnet').' | ';
+                $strlastaccess = get_string('never');
             }
-            if ($localusers == 1 && $remoteusers == 1) {
-                echo '<a href="?ru=0">'.get_string('hideremote','mnet').'</a>';
-            } elseif ($remoteusers == 0) {
-                echo '<a href="?ru=1">'.get_string('showremote','mnet').'</a>';
-            } else {
-                echo get_string('hideremote','mnet');
-            }
-            echo "</p>";
+            $fullname = fullname($user, true);
+
+            $table->data[] = array ("<a href=\"../user/view.php?id=$user->id&amp;course=$site->id\">$fullname</a>",
+                                "$user->email",
+                                "$user->city",
+                                "$user->country",
+                                $strlastaccess,
+                                $editbutton,
+                                $deletebutton,
+                                $confirmbutton);
         }
+    }
 
-        echo "<table class=\"searchbox\" align=\"center\" cellpadding=\"10\"><tr><td>";
-        echo "<form action=\"user.php\" method=\"get\">";
-        echo "<input type=\"text\" name=\"search\" value=\"".s($search, true)."\" size=\"20\" />";
-        echo "<input type=\"submit\" value=\"$strsearch\" />";
-        if ($search) {
-            echo "<input type=\"button\" onclick=\"document.location='user.php';\" value=\"$strshowallusers\" />";
+    if($mnet_auth_users) {
+        echo "<p style=\"text-align:center\">";
+        if ($localusers == 1 && $remoteusers == 1) {
+            echo '<a href="?lu=0">'.get_string('hidelocal','mnet').'</a> | ';
+        } elseif ($localusers == 0)  {
+            echo '<a href="?lu=1">'.get_string('showlocal','mnet').'</a> | ';
+        } else {
+            echo get_string('hidelocal','mnet').' | ';
         }
-        echo "</form>";
-        echo "</td></tr></table>";
+        if ($localusers == 1 && $remoteusers == 1) {
+            echo '<a href="?ru=0">'.get_string('hideremote','mnet').'</a>';
+        } elseif ($remoteusers == 0) {
+            echo '<a href="?ru=1">'.get_string('showremote','mnet').'</a>';
+        } else {
+            echo get_string('hideremote','mnet');
+        }
+        echo "</p>";
+    }
 
+    echo "<table class=\"searchbox\" align=\"center\" cellpadding=\"10\"><tr><td>";
+    echo "<form action=\"user.php\" method=\"get\">";
+    echo "<input type=\"text\" name=\"search\" value=\"".s($search, true)."\" size=\"20\" />";
+    echo "<input type=\"submit\" value=\"$strsearch\" />";
+    if ($search) {
+        echo "<input type=\"button\" onclick=\"document.location='user.php';\" value=\"$strshowallusers\" />";
+    }
+    echo "</form>";
+    echo "</td></tr></table>";
+
+    if (has_capability('moodle/user:create', $sitecontext)) {
+        print_heading('<a href="../user/editadvanced.php?id=-1">'.get_string('addnewuser').'</a>');
+    }
+    if (!empty($table)) {
+        print_table($table);
+        print_paging_bar($usercount, $page, $perpage,
+                         "user.php?sort=$sort&amp;dir=$dir&amp;perpage=$perpage".
+                         "&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial&amp;search=".urlencode(stripslashes($search))."&amp;");
         if (has_capability('moodle/user:create', $sitecontext)) {
-            print_heading("<a href=\"user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string('addnewuser')."</a>");
-        }
-        if (!empty($table)) {
-            print_table($table);
-            print_paging_bar($usercount, $page, $perpage,
-                             "user.php?sort=$sort&amp;dir=$dir&amp;perpage=$perpage".
-                             "&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial&amp;search=".urlencode(stripslashes($search))."&amp;");
-            if (has_capability('moodle/user:create', $sitecontext)) {
-                print_heading("<a href=\"user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a>");
-            }
+            print_heading('<a href="../user/editadvanced.php?id=-1">'.get_string('addnewuser').'</a>');
         }
+    }
 
 
-        admin_externalpage_print_footer($adminroot);
-    }
+    admin_externalpage_print_footer($adminroot);
+
 
 ?>
index 44a458c..0f22ea1 100644 (file)
@@ -481,6 +481,55 @@ function upgrade_get_javascript() {
 
     return $linktoscrolltoerrors;
 }
+
+function create_admin_user() {
+    global $CFG, $USER;
+
+    if (empty($CFG->rolesactive)) {   // No admin user yet.
+
+        $user = new object();
+        $user->auth         = 'manual';
+        $user->firstname    = get_string('admin');
+        $user->lastname     = get_string('user');
+        $user->username     = 'admin';
+        $user->password     = hash_internal_user_password('admin');
+        $user->email        = 'root@localhost';
+        $user->confirmed    = 1;
+        $user->mnethostid   = $CFG->mnet_localhost_id;
+        $user->lang         = $CFG->lang;
+        $user->maildisplay  = 1;
+        $user->timemodified = time();
+
+        if (!$user->id = insert_record('user', $user)) {
+            error('SERIOUS ERROR: Could not create admin user record !!!');
+        }
+
+        if (!$user = get_record('user', 'id', $user->id)) {   // Double check.
+            error('User ID was incorrect (can\'t find it)');
+        }
+
+        // Assign the default admin roles to the new user.
+        if (!$adminroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW)) {
+            error('No admin role could be found');
+        }
+        $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
+        foreach ($adminroles as $adminrole) {
+            role_assign($adminrole->id, $user->id, 0, $sitecontext->id);
+        }
+
+        set_config('rolesactive', 1);
+
+        // Log the user in.
+        $USER = get_complete_user_data('username', 'admin');
+        $USER->newadminuser = 1;
+        load_all_capabilities();
+
+        redirect("$CFG->wwwroot/user/editadvanced.php?id=$user->id");  // Edit thyself
+    } else {
+        error('Can not create admin!');
+    }
+}
+
 ////////////////////////////////////////////////
 /// upgrade logging functions
 ////////////////////////////////////////////////
index 4d5e2fa..b964b81 100644 (file)
@@ -3070,9 +3070,8 @@ function print_user_picture($userid, $courseid, $picture, $size=0, $return=false
         $class .= " defaultuserpic";
         $src =  "$CFG->pixpath/u/$file.png";
     }
-    if (!$alttext) {
-        $imagealt = '';
-    } else if ($user = get_record('user','id',$userid)) {
+    $imagealt = '';
+    if ($alttext and $user = get_record('user','id',$userid)) {
         if (!empty($user->imagealt)) {
             $imagealt = $user->imagealt;
         } else {
diff --git a/user/edit_form_common.php b/user/edit_form_common.php
new file mode 100644 (file)
index 0000000..23747ce
--- /dev/null
@@ -0,0 +1,201 @@
+<?php  //$Id$
+
+        $mform->addElement('text', 'firstname', get_string('firstname'), 'maxlength="100" size="30"');
+        $mform->addRule('firstname', $strrequired, 'required', null, 'client');
+        $mform->setType('firstname', PARAM_NOTAGS);
+
+        $mform->addElement('text', 'lastname', get_string('lastname'), 'maxlength="100" size="30"');
+        $mform->addRule('lastname', $strrequired, 'required', null, 'client');
+        $mform->setType('lastname', PARAM_NOTAGS);
+
+        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
+        $mform->addRule('email', $strrequired, 'required', null, 'client');
+
+        $choices = array();
+        $choices['0'] = get_string('emaildisplayno');
+        $choices['1'] = get_string('emaildisplayyes');
+        $choices['2'] = get_string('emaildisplaycourse');
+        $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
+        $mform->setDefault('emaildisplay', 2);
+
+        $choices = array();
+        $choices['0'] = get_string('emailenable');
+        $choices['1'] = get_string('emaildisable');
+        $mform->addElement('select', 'emailstop', get_string('emailactive'), $choices);
+        $mform->setDefault('emailenable', 1);
+
+        $choices = array();
+        $choices['0'] = get_string('textformat');
+        $choices['1'] = get_string('htmlformat');
+        $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
+        $mform->setDefault('mailformat', 1);
+        $mform->setAdvanced('mailformat');
+
+        if (!empty($CFG->allowusermailcharset)) {
+            $choices = array();
+            $charsets = get_list_of_charsets();
+            if (!empty($CFG->sitemailcharset)) {
+                $choices['0'] = get_string('site').' ('.$CFG->sitemailcharset.')';
+            } else {
+                $choices['0'] = get_string('site').' ('.current_charset().')';
+            }
+            $choices = array_merge($choices, $charsets);
+            $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
+            $mform->setAdvanced('preference_mailcharset');
+        }
+
+        $choices = array();
+        $choices['0'] = get_string('emaildigestoff');
+        $choices['1'] = get_string('emaildigestcomplete');
+        $choices['2'] = get_string('emaildigestsubjects');
+        $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
+        $mform->setDefault('maildigest', 0);
+        $mform->setAdvanced('maildigest');
+
+        $choices = array();
+        $choices['1'] = get_string('autosubscribeyes');
+        $choices['0'] = get_string('autosubscribeno');
+        $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
+        $mform->setDefault('autosubscribe', 0);
+        $mform->setAdvanced('autosubscribe');
+
+        if (!empty($CFG->forum_trackreadposts)) {
+            $choices = array();
+            $choices['0'] = get_string('trackforumsno');
+            $choices['1'] = get_string('trackforumsyes');
+            $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
+            $mform->setDefault('trackforums', 0);
+            $mform->setAdvanced('trackforums');
+        }
+
+        if ($CFG->htmleditor) {
+            $choices = array();
+            $choices['0'] = get_string('texteditor');
+            $choices['1'] = get_string('htmleditor');
+            $mform->addElement('select', 'htmleditor', get_string('textediting'), $choices);
+            $mform->setDefault('htmleditor', 1);
+            $mform->setAdvanced('htmleditor');
+        }
+
+        if (empty($CFG->enableajax)) {
+            $mform->addElement('static', 'ajaxdisabled', get_string('ajaxuse'), get_string('ajaxno'));
+            $mform->setAdvanced('ajaxdisabled');
+        } else {
+            $choices = array();
+            $choices['0'] = get_string('ajaxno');
+            $choices['1'] = get_string('ajaxyes');
+            $mform->addElement('select', 'ajax', get_string('ajaxuse'), $choices);
+            $mform->setDefault('ajax', 0);
+            $mform->setAdvanced('ajax');
+        }
+
+        $choices = array();
+        $choices['0'] = get_string('screenreaderno');
+        $choices['1'] = get_string('screenreaderyes');
+        $mform->addElement('select', 'screenreader', get_string('screenreaderuse'), $choices);
+        $mform->setDefault('screenreader', 0);
+        $mform->setAdvanced('screenreader');
+
+        $mform->addElement('text', 'city', get_string('city'), 'maxlength="100" size="25"');
+        $mform->setType('city', PARAM_MULTILANG);
+        $mform->addRule('city', $strrequired, 'required', null, 'client');
+
+
+        $choices = get_list_of_countries();
+        $choices= array(''=>get_string('selectacountry').'...') + $choices;
+        $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
+        $mform->addRule('country', $strrequired, 'required', null, 'client');
+        if (!empty($CFG->country)) {
+            $mform->setDefault('country', $CFG->country);
+        }
+
+        $choices = get_list_of_timezones();
+        $choices['99'] = get_string('serverlocaltime');
+        if ($CFG->forcetimezone != 99) {
+            $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
+        } else {
+            $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
+            $mform->setDefault('timezone', '99');
+        }
+
+        $choices = array();
+        if ($choices = get_list_of_languages()) {
+            $mform->addElement('select', 'lang', get_string('preferredlanguage'), $choices);
+            $mform->setDefault('lang', $CFG->lang);
+        }
+
+        if (!empty($CFG->allowuserthemes)) {
+            $choices = array();
+            $choices[''] = get_string('default');
+            $choices += get_list_of_themes();
+            $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
+            $mform->setAdvanced('theme');
+        }
+
+        $mform->addElement('htmleditor', 'description', get_string('userdescription'));
+        $mform->setType('description', PARAM_CLEAN);
+        $mform->setHelpButton('description', array('text', get_string('helptext')));
+        //TODO: set as 'required' in normal edit form
+
+        if (!empty($CFG->gdversion)) {
+            $mform->addElement('header', 'moodle_picture', get_string('pictureof'));//TODO: Accessibility fix fieldset legend
+
+            $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
+            //TODO: set current picture as default value
+
+            $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
+            $mform->setDefault('deletepicture',false);
+            //TODO: remove when picture not present or user->id==0
+
+            $mform->addElement('file', 'imagefile', get_string('newpicture'));
+            $mform->setHelpButton('imagefile', array('picture', get_string('helppicture')));
+
+            $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
+            $mform->setType('imagealt', PARAM_MULTILANG);
+
+        }
+        //TODO: remove if empty($CFG->disableuserimages) in normal edit form
+
+        /// Moodle optional fields
+        /// TODO: freeze what's needed
+        $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
+        $mform->setAdvanced('moodle_optional');
+
+        $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
+        $mform->setType('url', PARAM_URL);
+
+        $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
+        $mform->setType('icq', PARAM_CLEAN);
+
+        $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
+        $mform->setType('skype', PARAM_CLEAN);
+
+        $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
+        $mform->setType('aim', PARAM_CLEAN);
+
+        $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
+        $mform->setType('yahoo', PARAM_CLEAN);
+
+        $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
+        $mform->setType('msn', PARAM_CLEAN);
+
+        $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="64" size="25"');
+        $mform->setType('idnumber', PARAM_RAW);
+
+        $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"');
+        $mform->setType('institution', PARAM_MULTILANG);
+
+        $mform->addElement('text', 'department', get_string('department'), 'maxlength="30" size="25"');
+        $mform->setType('department', PARAM_MULTILANG);
+
+        $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
+        $mform->setType('phone1', PARAM_CLEAN);
+
+        $mform->addElement('text', 'phone2', get_string('phone'), 'maxlength="20" size="25"');
+        $mform->setType('phone2', PARAM_CLEAN);
+
+        $mform->addElement('text', 'address', get_string('address'), 'maxlength="70" size="25"');
+        $mform->setType('address', PARAM_MULTILANG);
+
+
+?>
\ No newline at end of file
diff --git a/user/editadvanced.php b/user/editadvanced.php
new file mode 100644 (file)
index 0000000..c51786e
--- /dev/null
@@ -0,0 +1,203 @@
+<?php // $Id$
+
+    require_once('../config.php');
+    require_once($CFG->libdir.'/gdlib.php');
+    require_once($CFG->libdir.'/adminlib.php');
+    require_once($CFG->dirroot.'/user/editadvanced_form.php');
+
+    $id     = optional_param('id', $USER->id, PARAM_INT);    // user id; -1 if creating new user
+    $course = optional_param('course', SITEID, PARAM_INT);   // course id (defaults to Site)
+
+    if (!$course = get_record('course', 'id', $course)) {
+        error('Course ID was incorrect');
+    }
+    require_login($course->id);
+    httpsrequired(); // HTTPS is potentially required in this page because there are passwords
+
+    if ($id == -1) {
+        // creating new user
+        require_capability('moodle/user:create', get_context_instance(CONTEXT_SYSTEM, SITEID));
+        $user = new object();
+        $user->id = -1;
+        $user->auth = 'manual';
+        $user->confirmed = 1;
+    } else {
+        // editing existing user
+        require_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM, SITEID));
+        if (!$user = get_record('user', 'id', $id)) {
+            error('User ID was incorrect');
+        }
+    }
+
+    // remote users cannot be edited
+    if ($user->id != -1 and is_mnet_remote_user($user)) {
+        redirect($CFG->wwwroot . "/user/view.php?id=$id&course={$course->id}");
+    }
+
+    $mainadmin = get_admin();
+    if ($user->id != $USER->id and $user->id == $mainadmin->id) {  // Can't edit primary admin
+        print_error('adminprimarynoedit');
+    }
+
+    if (isguestuser($user->id)) { // the real guest user can not be edited
+        print_error('guestnoeditprofileother');
+    }
+
+    //load preferences
+    if (!empty($user->id) and $preferences = get_user_preferences(null, null, $user->id)) {
+        foreach($preferences as $name=>$value) {
+            $user->{'preference_'.$name} = $value;
+        }
+    }
+    //TODO: Load the custom profile fields
+
+    //create form
+    $userform = new user_editadvanced_form(null, $course);
+    $userform->set_data($user);
+
+    if ($usernew = $userform->get_data()) {
+        add_to_log($course->id, 'user', 'update', "view.php?id=$user->id&course=$course->id", '');
+
+        $authplugin = get_auth_plugin($CFG->auth);
+
+        $usernew->timemodified = time();
+
+        if ($usernew->id == -1) {
+            unset($usernew->id);
+            $usernew->mnethostid = $CFG->mnet_localhost_id; // always local user
+            $usernew->confirmed = 1;
+            if (!$usernew->id = insert_record('user', $usernew)) {
+                error('Error creating user record');
+            }
+        } else {
+            if (update_record('user', $usernew)) {
+                if (method_exists($authplugin, 'user_update')){
+                    // pass a true $userold here
+                    if (! $authplugin->user_update($user, $userform->get_data(false))) {
+                        // auth update failed, rollback for moodle
+                        update_record('user', addslashes_object($user));
+                        error('Failed to update user data on external auth: '.$usernew->auth.
+                                '. See the server logs for more details.');
+                    }
+                };
+            } else {
+                error('Error updating user record');
+            }
+        }
+
+        //set new password if specified
+        if (!empty($usernew->newpassword)) {
+            if ($authplugin->can_change_password()) {
+                if (method_exists($authplugin, 'user_update_password')){
+                    if (!$authplugin->user_update_password($user->username, $usernew->newpassword)){
+                        error('Failed to update password on external auth: ' . $usernew->auth .
+                                '. See the server logs for more details.');
+                    }
+                } else {
+                    error('Your external authentication module is misconfigued!');
+                }
+            }
+        }
+
+        //update preferences
+        $ua = (array)$usernew;
+        foreach($ua as $key=>$value) {
+            if (strpos($key, 'preference_') === 0) {
+                $name = substr($key, strlen('preference_'));
+                set_user_preference($name, $value, $usernew->id);
+            }
+        }
+
+        //update user picture
+        if ($usernew->deletepicture) {
+            //TODO - delete the files
+            set_field('user', 'picture', 0, 'id', $usernew->id);
+        } else if ($usernew->picture = save_profile_image($usernew->id, $userform->get_um(), 'users')) {
+            set_field('user', 'picture', 1, 'id', $usernew->id);
+        }
+
+        // update mail bounces
+        if ($user->email != $usernew->email) {
+            set_bounce_count($usernew,true);
+            set_send_count($usernew,true);
+        }
+
+        /// Update forum track preference.
+        if (($usernew->trackforums != $user->trackforums) && !$usernew->trackforums) {
+            require_once($CFG->dirroot.'/mod/forum/lib.php');
+            forum_tp_delete_read_records($usernew->id);
+        }
+
+        //TODO: Save the custom profile fields
+
+        if ($user->id == $USER->id) {
+            // Override old $USER session variable
+            $usernew = (array)get_record('user', 'id', $newuser->id); // reload from db
+            foreach ($usernew as $variable => $value) {
+                $USER->$variable = $value;
+            }
+            if (!empty($USER->newadminuser)) {
+                unset($USER->newadminuser);
+                // redirect to admin/ to continue with installation
+                redirect("$CFG->wwwroot/$CFG->admin/");
+            } else { 
+                redirect("$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id");
+            }
+        } else {
+            redirect("$CFG->wwwroot/$CFG->admin/user.php");
+        }
+        //never reached
+    }
+
+
+/// Display page header
+    if ($user->id == -1 or ($user->id != $USER->id)) {
+        $adminroot = admin_get_root();
+        if ($user->id == -1) {
+            admin_externalpage_setup('addnewuser', $adminroot);
+            admin_externalpage_print_header($adminroot);
+        } else {
+            admin_externalpage_setup('editusers', $adminroot);
+            admin_externalpage_print_header($adminroot);
+            $userfullname = fullname($user, true);
+            print_heading($userfullname);
+        }
+    } else if (!empty($USER->newadminuser)) {
+        print_header();
+        print_simple_box(get_string('configintroadmin', 'admin'), 'center', '50%');
+        echo '<br />';
+    } else {
+        $streditmyprofile = get_string('editmyprofile');
+        $strparticipants = get_string('participants');
+        $strnewuser = get_string('newuser');
+        $userfullname = fullname($user, true);
+        if ($course->id != SITEID) {
+            print_header("$course->shortname: $streditmyprofile", "$course->fullname: $streditmyprofile",
+                         "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a>
+                          -> <a href=\"index.php?id=$course->id\">$strparticipants</a>
+                          -> <a href=\"view.php?id=$user->id&amp;course=$course->id\">$userfullname</a>
+                          -> $streditmyprofile", "");
+        } else {
+            print_header("$course->shortname: $streditmyprofile", "$course->fullname",
+                         "<a href=\"view.php?id=$user->id&amp;course=$course->id\">$userfullname</a>
+                          -> $streditmyprofile", "");
+        }
+        /// Print tabs at the top
+        $showroles = 1;
+        $currenttab = 'editprofile';
+        require('tabs.php');
+    }
+
+/// Finally display THE form
+    $userform->display();
+
+/// and proper footer
+    if ($user->id == -1) {
+        admin_externalpage_print_footer($adminroot);
+    } else if (!empty($USER->newadminuser)) {
+        print_footer('none');
+    } else {
+        print_footer($course);
+    }
+
+?>
diff --git a/user/editadvanced_form.php b/user/editadvanced_form.php
new file mode 100644 (file)
index 0000000..ce1d031
--- /dev/null
@@ -0,0 +1,89 @@
+<?php //$Id$
+
+require_once($CFG->dirroot.'/lib/formslib.php');
+require_once($CFG->dirroot.'/user/profile/lib.php');
+
+class user_editadvanced_form extends moodleform {
+
+    // Define the form
+    function definition () {
+        global $USER, $CFG;
+
+        $mform =& $this->_form;
+        $course = $this->_customdata;
+        $this->set_upload_manager(new upload_manager('imagefile', false, false, null, false, 0, true, true, false));
+        $strrequired = get_string('required');
+
+        /// Add some extra hidden fields
+        $mform->addElement('hidden', 'id');
+        $mform->addElement('hidden', 'course', $course->id);
+
+        /// Print the required moodle fields first
+        $mform->addElement('header', 'moodle', $strrequired);
+
+        $mform->addElement('text', 'username', get_string('username'), 'size="20"');
+        $mform->addRule('username', $strrequired, 'required', null, 'client');
+        $mform->setType('username', PARAM_RAW);
+
+        $modules = get_list_of_plugins('auth');
+        $auth_options = array();
+        foreach ($modules as $module) {
+            $auth_options[$module] = get_string("auth_$module"."title", "auth");
+        }
+        $mform->addElement('select', 'auth', get_string('chooseauthmethod','auth'), $auth_options);
+        $mform->setHelpButton('auth', array('authchange', get_string('chooseauthmethod','auth')));
+        $mform->setAdvanced('auth');
+
+        $mform->addElement('text', 'newpassword', get_string('newpassword'), 'size="20"');
+        $mform->setType('newpassword', PARAM_RAW);
+        //TODO: add missing help - empty means no change
+
+        $mform->addElement('checkbox', 'preference_auth_forcepasswordchange', get_string('forcepasswordchange'));
+        //TODO: add missing help - user will be forced to change password
+
+        require('edit_form_common.php');
+
+        $this->add_action_buttons(false, get_string('updatemyprofile'));
+    }
+
+    function definition_after_data() {
+        global $USER, $CFG;
+
+        $mform =& $this->_form;
+        $user = get_record('user', 'id', $mform->getElementValue('id'));
+
+        if ($user) {
+
+            // user can not change own auth method
+            if ($user->id == $USER->id) {
+                $mform->hardFreeze('auth');
+                $mform->hardFreeze('preference_auth_forcepasswordchange');
+            }
+        }
+
+        // admin must choose some password and supply correct email
+        if (!empty($USER->newadminuser)) {
+            $mform->addRule('newpassword', get_string('required'), 'required', null, 'client');
+
+            $email = $mform->getElement('email');
+            if ($email->getValue() == 'root@localhost') {
+                $email->setValue('');
+            }
+        }
+
+        if (!empty($CFG->gdversion)) {
+            $image = $mform->getElement('currentpicture');
+            if ($user) {
+                $image->setValue(print_user_picture($user->id, SITEID, $user->picture, 64, true, false, '', true));
+            } else {
+                $image->setValue(print_user_picture(0, SITEID, 0, 64, true, false, '', true));
+            }
+        }
+    }
+
+    function get_um() {
+        return $this->_upload_manager;
+    }
+}
+
+?>
index a33dff2..bddfa6a 100644 (file)
 
     /// Can only edit profile if it belongs to user or current user is admin and not editing primary admin
 
-        if (($mainadmin = get_admin()) === false) {
-            $mainadmin->id = 0; /// Weird - no primary admin!
-        }
+        $mainadmin = get_admin();
 
         if (is_mnet_remote_user($user)) {
             // cannot edit remote users
         }
         else if ((!empty($USER->id) and ($USER->id == $user->id) and !isguest()) or
-            (has_capability('moodle/user:editprofile', $personalcontext) and ($user->id != $mainadmin->id)) ) {
+            (has_capability('moodle/user:update', $sitecontext) and ($user->id != $mainadmin->id)) ) {
 
             if(empty($CFG->loginhttps)) {
                 $wwwroot = $CFG->wwwroot;
             } else {
                 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
             }
-
-            $toprow[] = new tabobject('editprofile', $wwwroot.'/user/edit.php?id='.$user->id.'&amp;course='.$course->id, get_string('editmyprofile'));
+            if (has_capability('moodle/user:update', $sitecontext) and ($user->id==$USER->id or $user->id != $mainadmin->id)) {
+                $toprow[] = new tabobject('editprofile', $wwwroot.'/user/editadvanced.php?id='.$user->id.'&amp;course='.$course->id, get_string('editmyprofile'));
+            } else {
+                $toprow[] = new tabobject('editprofile', $wwwroot.'/user/edit.php?id='.$user->id.'&amp;course='.$course->id, get_string('editmyprofile'));
+            }
         }
 
     /// Everyone can see posts for this user