### Eclipse Workspace Patch 1.0
#P moodle
Index: mod/forum/db/upgrade.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/forum/db/upgrade.php,v
retrieving revision 1.21
diff -u -r1.21 upgrade.php
--- mod/forum/db/upgrade.php	31 Jul 2008 08:01:50 -0000	1.21
+++ mod/forum/db/upgrade.php	12 Aug 2008 09:30:23 -0000
@@ -37,14 +37,9 @@
 //===== 1.9.0 upgrade line ======//
 
     if ($result and $oldversion < 2007101511) {
-        notify('Processing forum grades, this may take a while if there are many forums...', 'notifysuccess');
         //MDL-13866 - send forum ratins to gradebook again
         require_once($CFG->dirroot.'/mod/forum/lib.php');
-        // too much debug output
-        $DB->set_debug(false);
-        forum_update_grades();
-        $DB->set_debug(true);
-
+        forum_upgrade_grades();
         upgrade_mod_savepoint($result, 2007101511, 'forum');
     }
 
Index: admin/index.php
===================================================================
RCS file: /cvsroot/moodle/moodle/admin/index.php,v
retrieving revision 1.334
diff -u -r1.334 index.php
--- admin/index.php	4 Aug 2008 07:27:49 -0000	1.334
+++ admin/index.php	12 Aug 2008 09:29:49 -0000
@@ -14,9 +14,7 @@
         die;
     }
 
-/// Turn off time limits and try to flush everything all the time, sometimes upgrades can be slow.
-
-    @set_time_limit(0);
+/// try to flush everything all the time
     @ob_implicit_flush(true);
     while(@ob_end_clean()); // ob_end_flush prevents sending of headers
 
@@ -30,15 +28,8 @@
     $confirmrelease = optional_param('confirmrelease', 0, PARAM_BOOL);
     $agreelicense   = optional_param('agreelicense', 0, PARAM_BOOL);
     $autopilot      = optional_param('autopilot', 0, PARAM_BOOL);
-    $ignoreupgradewarning = optional_param('ignoreupgradewarning', 0, PARAM_BOOL);
     $confirmplugincheck = optional_param('confirmplugincheck', 0, PARAM_BOOL);
 
-/// check upgrade status first
-    if ($ignoreupgradewarning) {
-        $SESSION->upgraderunning = 0;
-    }
-    upgrade_check_running("Upgrade already running in this session, please wait!<br />Click on the exclamation marks to ignore this warning (<a href=\"index.php?ignoreupgradewarning=1\">!!!</a>).", 10);
-
 /// set install/upgrade autocontinue session flag
     if ($autopilot) {
         $SESSION->installautopilot = $autopilot;
@@ -174,8 +165,6 @@
     /// Continue with the instalation
         $DB->set_debug(false);
 
-        /// Groups install is now in core above.
-
         // Install the roles system.
         moodle_install_roles();
 
@@ -202,10 +191,11 @@
         admin_apply_default_settings(NULL, true);
 
         notify($strdatabasesuccess, "green");
-        require_once $CFG->dirroot.'/mnet/lib.php';
+        require_once $CFG->dirroot.'/mnet/lib.php'; // hack - set up mnet
 
         print_continue('index.php');
         print_footer('none');
+
         die;
     }
 
@@ -305,6 +295,7 @@
                 die();
 
             } else {
+
                 $strdatabasesuccess  = get_string("databasesuccess");
                 $navigation = build_navigation(array(array('name'=>$strdatabasesuccess, 'link'=>null, 'type'=>'misc')));
                 print_header($strdatabasechecking, $stradministration, $navigation,
@@ -380,9 +371,6 @@
         }
     }
 
-/// Groups install/upgrade is now in core above.
-
-
 /// Find and check all main modules and load them up or upgrade them if necessary
 /// first old *.php update and then the new upgrade.php script
     upgrade_activity_modules("$CFG->wwwroot/$CFG->admin/index.php");  // Return here afterwards
Index: lib/db/upgradelib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/db/upgradelib.php,v
retrieving revision 1.18
diff -u -r1.18 upgradelib.php
--- lib/db/upgradelib.php	31 Jul 2008 22:15:33 -0000	1.18
+++ lib/db/upgradelib.php	12 Aug 2008 09:30:11 -0000
@@ -73,6 +73,7 @@
     $i = 0;
     foreach ($rs as $course) {
         $i++;
+        upgrade_set_timeout(60*5); // set up timeout, may also abort execution
         $context = get_context_instance(CONTEXT_COURSE, $course->id);
         upgrade_migrate_files_course($context, '/', true);
         $pbar->update($i, $count, "Migrated course files - course $i/$count.");
@@ -174,6 +175,8 @@
 
     if ($rs = $DB->get_recordset_select('post', "module='blog' AND attachment IS NOT NULL AND attachment <> 1")) {
 
+        upgrade_set_timeout(60*20); // set up timeout, may also abort execution
+
         $pbar = new progress_bar('migrateblogfiles', 500, true);
 
         $olddebug = $DB->get_debug();
@@ -183,9 +186,8 @@
             $i++;
             $pathname = "$CFG->dataroot/blog/attachments/$entry->id/$entry->attachment";
             if (!file_exists($pathname)) {
-                // hmm, we could set atatchment NULL here, but it would break badly in concurrent ugprades, disabling for now
-                //$entry->attachment = NULL;
-                //$DB->update_record('post', $entry);
+                $entry->attachment = NULL;
+                $DB->update_record('post', $entry);
                 continue;
             }
 
@@ -204,7 +206,7 @@
 
             if (!$fs->file_exists(SYSCONTEXTID, 'blog', $entry->id, '/', $filename)) {
                 $file_record = array('contextid'=>SYSCONTEXTID, 'filearea'=>'blog', 'itemid'=>$entry->id, 'filepath'=>'/', 'filename'=>$filename,
-                                     'timecreated'=>filectime($pathname), 'timemodified'=>filemtime($pathname), 'userid'=>$post->userid);
+                                     'timecreated'=>filectime($pathname), 'timemodified'=>filemtime($pathname), 'userid'=>$entry->userid);
                 $fs->create_file_from_pathname($file_record, $pathname);
             }
             @unlink($pathname);
Index: lib/db/upgrade.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/db/upgrade.php,v
retrieving revision 1.226
diff -u -r1.226 upgrade.php
--- lib/db/upgrade.php	7 Aug 2008 13:36:59 -0000	1.226
+++ lib/db/upgrade.php	12 Aug 2008 09:30:11 -0000
@@ -29,6 +29,7 @@
     ////////////////////////////////////////
 
     if ($result && $oldversion < 2008030700) {
+        upgrade_set_timeout(60*20); // this may take a while
 
     /// Define index contextid-lowerboundary (not unique) to be dropped form grade_letters
         $table = new xmldb_table('grade_letters');
@@ -61,6 +62,8 @@
     }
 
     if ($result && $oldversion < 2008050700) {
+        upgrade_set_timeout(60*20); // this may take a while
+
     /// Fix minor problem caused by MDL-5482.
         require_once($CFG->dirroot . '/question/upgrade.php');
         $result = $result && question_fix_random_question_parents();
@@ -85,6 +88,7 @@
 
     if ($result && $oldversion < 2008051201) {
         notify('Increasing size of user idnumber field, this may take a while...', 'notifysuccess');
+        upgrade_set_timeout(60*20); // this may take a while
 
     /// Under MySQL and Postgres... detect old NULL contents and change them by correct empty string. MDL-14859
         if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
@@ -135,6 +139,8 @@
     }
 
     if ($result && $oldversion < 2008063001) {
+        upgrade_set_timeout(60*20); // this may take a while
+
         // table to be modified
         $table = new xmldb_table('tag_instance');
         // add field
@@ -602,6 +608,7 @@
     /// Main savepoint reached
         upgrade_main_savepoint($result, 2008080600);
     }
+
     if ($result && $oldversion < 2008080701) {
 
     /// Define field visible to be added to repository
Index: mod/lesson/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/lesson/lib.php,v
retrieving revision 1.54
diff -u -r1.54 lib.php
--- mod/lesson/lib.php	31 Jul 2008 08:01:50 -0000	1.54
+++ mod/lesson/lib.php	12 Aug 2008 09:30:29 -0000
@@ -385,43 +385,57 @@
 /**
  * Update grades in central gradebook
  *
- * @param object $lesson null means all lessons
- * @param int $userid specific user only, 0 mean all
+ * @param object $lesson
+ * @param int $userid specific user only, 0 means all
  */
-function lesson_update_grades($lesson=null, $userid=0, $nullifnone=true) {
+function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
-    if (!function_exists('grade_update')) { //workaround for buggy PHP versions
-        require_once($CFG->libdir.'/gradelib.php');
-    }
+    require_once($CFG->libdir.'/gradelib.php');
 
-    if ($lesson != null) {
-        if ($grades = lesson_get_user_grades($lesson, $userid)) {
-            lesson_grade_item_update($lesson, $grades);
-
-        } else if ($userid and $nullifnone) {
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = NULL;
-            lesson_grade_item_update($lesson, $grade);
+    if ($lesson->grade == 0) {
+        lesson_grade_item_update($lesson);
 
-        } else {
-            lesson_grade_item_update($lesson);
-        }
+    } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
+        lesson_grade_item_update($lesson, $grades);
+
+    } else if ($userid and $nullifnone) {
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = NULL;
+        lesson_grade_item_update($lesson, $grade);
 
     } else {
-        $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
-                  FROM {lesson} l, {course_modules} cm, {modules} m
-                 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $lesson) {
-                if ($lesson->grade != 0) {
-                    lesson_update_grades($lesson, 0, false);
-                } else {
-                    lesson_grade_item_update($lesson);
-                }
-            }
-            $rs->close();
+        lesson_grade_item_update($lesson);
+    }
+}
+
+/**
+ * Update all grades in gradebook.
+ */
+function lesson_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {lesson} l, {course_modules} cm, {modules} m
+             WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT l.*, cm.idnumber AS cmidnumber, l.course AS courseid
+              FROM {lesson} l, {course_modules} cm, {modules} m
+             WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('lessonupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $lesson) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            lesson_update_grades($lesson, 0, false);
+            $pbar->update($i, $count, "Updating Lesson grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
Index: lib/weblib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/weblib.php,v
retrieving revision 1.1124
diff -u -r1.1124 weblib.php
--- lib/weblib.php	7 Aug 2008 22:38:46 -0000	1.1124
+++ lib/weblib.php	12 Aug 2008 09:30:10 -0000
@@ -5677,7 +5677,7 @@
         $module = 'error';
     }
 
-    if (!isset($CFG->theme)) {
+    if (!isset($CFG->theme) or !isset($CFG->stylesheets)) {
         // error found before setup.php finished
         _print_early_error($errorcode, $module, $a);
     } else {
Index: lib/setup.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/setup.php,v
retrieving revision 1.244
diff -u -r1.244 setup.php
--- lib/setup.php	25 Jul 2008 08:27:50 -0000	1.244
+++ lib/setup.php	12 Aug 2008 09:30:04 -0000
@@ -159,6 +159,15 @@
 /// Load up any configuration from the config table
     $CFG = get_config();
 
+/// Verify upgrade is not running
+    if (isset($CFG->upgraderunning)) {
+        if ($CFG->upgraderunning < time()) {
+            unset_config('upgraderunning');
+        } else {
+            print_error('upgraderunning');
+        }
+    }
+
 /// Turn on SQL logging if required
     if (!empty($CFG->logsql)) {
         $DB->set_logging(true);
Index: lib/moodlelib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/moodlelib.php,v
retrieving revision 1.1092
diff -u -r1.1092 moodlelib.php
--- lib/moodlelib.php	8 Aug 2008 10:22:59 -0000	1.1092
+++ lib/moodlelib.php	12 Aug 2008 09:30:04 -0000
@@ -2597,7 +2597,7 @@
         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
     }
 
-    if ($CFG->fullnamedisplay == 'firstname lastname') {
+    if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
         return $user->firstname .' '. $user->lastname;
 
     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
@@ -6417,6 +6417,45 @@
     return false;
 }
 
+/**
+ * Sets maximum expected time needed for upgrade task.
+ * Please always make sure that upgrade will not run longer!
+ *
+ * The script may be automatically aborted if upgrade times out.  
+ *
+ * @param int $max_execution_time in seconds (can not be less than 60 s)
+ * @return void
+ */
+function upgrade_set_timeout($max_execution_time=300) {
+    global $CFG;
+
+    if (isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
+        $upgraderunning = get_config(null, 'upgraderunning');
+    } else {
+        $upgraderunning = $CFG->upgraderunning;
+    } 
+    
+    if (!$upgraderunning) {
+        // upgrade not running or aborted
+        print_error('upgradetimedout', 'admin', "$CFG->wwroot/$CFG->admin/");
+        die;
+    }
+
+    if ($max_execution_time < 60) {
+        // protection against 0 here
+        $max_execution_time = 60;
+    }
+
+    $expected_end = time() + $max_execution_time;
+
+    if ($expected_end < $upgraderunning + 10 and $expected_end > $upgraderunning - 10) {
+        // no need to store new end, it is nearly the same ;-)
+        return;
+    }
+
+    set_time_limit($max_execution_time);
+    set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
+}
 
 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
 
Index: lib/adminlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/adminlib.php,v
retrieving revision 1.237
diff -u -r1.237 adminlib.php
--- lib/adminlib.php	6 Aug 2008 03:30:55 -0000	1.237
+++ lib/adminlib.php	12 Aug 2008 09:29:57 -0000
@@ -26,6 +26,13 @@
 require_once($CFG->libdir.'/xmlize.php');
 require_once($CFG->libdir .'/messagelib.php');      // Messagelib functions
 
+global $upgradeloghandle, $upgradelogbuffer;
+
+$upgradeloghandle = false;
+$upgradelogbuffer = '';
+
+
+
 function upgrade_main_savepoint($result, $version) {
     global $CFG;
 
@@ -38,6 +45,14 @@
     } else {
         notify ("Upgrade savepoint: Error during main upgrade to version $version");
     }
+
+    // reset upgrade timeout to default
+    upgrade_set_timeout();
+
+    // this is a safe place to stop upgrades if user aborts page loading
+    if (connection_aborted()) {
+        die;
+    }
 }
 
 function upgrade_mod_savepoint($result, $version, $modname) {
@@ -57,6 +72,14 @@
     } else {
         notify ("Upgrade savepoint: Error during mod upgrade to version $version");
     }
+
+    // reset upgrade timeout to default
+    upgrade_set_timeout();
+
+    // this is a safe place to stop upgrades if user aborts page loading
+    if (connection_aborted()) {
+        die;
+    }
 }
 
 function upgrade_plugin_savepoint($result, $version, $type, $dir) {
@@ -819,31 +842,41 @@
 /// upgrade logging functions
 ////////////////////////////////////////////////
 
-$upgradeloghandle = false;
-$upgradelogbuffer = '';
-// I did not find out how to use static variable in callback function,
-// the problem was that I could not flush the static buffer :-(
-global $upgradeloghandle, $upgradelogbuffer;
-
 /**
- * Check if upgrade is already running.
- *
- * If anything goes wrong due to missing call to upgrade_log_finish()
- * just restart the browser.
- *
- * @param string warning message indicating upgrade is already running
- * @param int page reload timeout
+ * Marks start of upgrade, blocks any other access to site.
+ * The upgrade is finished at the end of script or after timeout.
  */
-function upgrade_check_running($message, $timeout) {
-    global $SESSION;
+function start_upgrade() {
+    global $CFG;
 
-    if (!empty($SESSION->upgraderunning)) {
-        print_header();
-        redirect(me(), $message, $timeout);
+    static $started = false;
+
+    if ($started) {
+        upgrade_set_timeout(120);
+
+    } else {
+        ignore_user_abort(true);
+        register_shutdown_function('upgrade_finished_handler');
+        if ($CFG->version === '') {
+            // db not installed yet
+            $CFG->upgraderunning = time()+300;
+        } else {
+            set_config('upgraderunning', time()+300);
+        }
+        $started = true;
     }
 }
 
 /**
+ * Internal function - executed at the very end of each upgrade.
+ */
+function upgrade_finished_handler() {
+    upgrade_log_finish();    
+    unset_config('upgraderunning');
+    ignore_user_abort(false);
+}
+
+/**
  * Start logging of output into file (if not disabled) and
  * prevent aborting and concurrent execution of upgrade script.
  *
@@ -852,25 +885,21 @@
  * This function may be called repeatedly.
  */
 function upgrade_log_start() {
-    global $CFG, $upgradeloghandle, $SESSION;
+    global $upgradeloghandle;
 
-    if (!empty($SESSION->upgraderunning)) {
-        return; // logging already started
-    }
+    start_upgrade(); // make sure the upgrade is started
 
-    @ignore_user_abort(true);            // ignore if user stops or otherwise aborts page loading
-    $SESSION->upgraderunning = 1;     // set upgrade indicator
-    if (empty($CFG->dbsessions)) {       // workaround for bug in adodb, db session can not be restarted
-        session_write_close();           // from now on user can reload page - will be displayed warning
+    if ($upgradeloghandle and ($upgradeloghandle !== 'error')) {
+        debugging('Inccorect use of upgrade_log_start(), upgrade already logging.');
+        return;
     }
+
     make_upload_directory('upgradelogs');
     ob_start('upgrade_log_callback', 2); // function for logging to disk; flush each line of text ASAP
-    register_shutdown_function('upgrade_log_finish'); // in case somebody forgets to stop logging
 }
 
 /**
- * Terminate logging of output, flush all data, allow script aborting
- * and reopen session for writing. Function print_error() does terminate the logging too.
+ * Terminate logging of output, flush all data.
  *
  * Please make sure that each upgrade_log_start() is properly terminated by
  * this function or print_error().
@@ -878,11 +907,7 @@
  * This function may be called repeatedly.
  */
 function upgrade_log_finish() {
-    global $CFG, $upgradeloghandle, $upgradelogbuffer, $SESSION;
-
-    if (empty($SESSION->upgraderunning)) {
-        return; // logging already terminated
-    }
+    global $CFG, $upgradeloghandle, $upgradelogbuffer;
 
     @ob_end_flush();
     if ($upgradelogbuffer !== '') {
@@ -893,14 +918,6 @@
         @fclose($upgradeloghandle);
         $upgradeloghandle = false;
     }
-    @session_start();                // ignore header errors, we only need to reopen session
-
-    $SESSION->upgraderunning = 0; // clear upgrade indicator
-
-    if (connection_aborted()) {
-        die;
-    }
-    @ignore_user_abort(false);
 }
 
 /**
@@ -4206,9 +4223,10 @@
     }
 
     function write_setting($data) {
-        $url = $this->baseurl . '&amp;new=' . $data;
+        //TODO: rewrite without redirect
+/*        $url = $this->baseurl . '&amp;new=' . $data;
         redirect($url);
-        exit;
+        exit;*/
     }
 
     function is_related($query) {
@@ -4536,7 +4554,7 @@
     global $CFG;
 
     if (is_null($node)) {
-        $node =& admin_get_root();
+        $node = admin_get_root();
     }
 
     if (is_a($node, 'admin_category')) {
Index: mod/data/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/data/lib.php,v
retrieving revision 1.191
diff -u -r1.191 lib.php
--- mod/data/lib.php	11 Aug 2008 13:45:41 -0000	1.191
+++ mod/data/lib.php	12 Aug 2008 09:30:17 -0000
@@ -798,43 +798,60 @@
 }
 
 /**
- * Update grades by firing grade_updated event
+ * Update activity grades
  *
- * @param object $data null means all databases
- * @param int $userid specific user only, 0 mean all
+ * @param object $data
+ * @param int $userid specific user only, 0 means all
  */
-function data_update_grades($data=null, $userid=0, $nullifnone=true) {
+function data_update_grades($data, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
     require_once($CFG->libdir.'/gradelib.php');
 
-    if ($data != null) {
-        if ($grades = data_get_user_grades($data, $userid)) {
-            data_grade_item_update($data, $grades);
-
-        } else if ($userid and $nullifnone) {
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = NULL;
-            data_grade_item_update($data, $grade);
+    if (!$data->assessed) {
+        data_grade_item_update($data);
 
-        } else {
-            data_grade_item_update($data);
-        }
+    } else if ($grades = data_get_user_grades($data, $userid)) {
+        data_grade_item_update($data, $grades);
+
+    } else if ($userid and $nullifnone) {
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = NULL;
+        data_grade_item_update($data, $grade);
 
     } else {
-        $sql = "SELECT d.*, cm.idnumber as cmidnumber
-                  FROM {data} d, {course_modules} cm, {modules} m
-                 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $data) {
-                if ($data->assessed) {
-                    data_update_grades($data, 0, false);
-                } else {
-                    data_grade_item_update($data);
-                }
-            }
-            $rs->close();
+        data_grade_item_update($data);
+    }
+}
+
+/**
+ * Update all grades in gradebook.
+ */
+function data_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {data} d, {course_modules} cm, {modules} m
+             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT d.*, cm.idnumber AS cmidnumber, d.course AS courseid
+              FROM {data} d, {course_modules} cm, {modules} m
+             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        // too much debug output
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('dataupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $data) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            data_update_grades($data, 0, false);
+            $pbar->update($i, $count, "Updating Database grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
Index: user/editlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/user/editlib.php,v
retrieving revision 1.25
diff -u -r1.25 editlib.php
--- user/editlib.php	31 Jul 2008 22:15:33 -0000	1.25
+++ user/editlib.php	12 Aug 2008 09:30:30 -0000
@@ -100,7 +100,7 @@
     $mform->setType('lastname', PARAM_NOTAGS);
 
     // Do not show email field if change confirmation is pending
-    if ($CFG->emailchangeconfirmation && !empty($user->preference_newemail)) {
+    if (!empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
         $notice = get_string('auth_emailchangepending', 'auth', $user);
         $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id='.$user->id.'">'
                 . get_string('auth_emailchangecancel', 'auth') . '</a>';
@@ -167,7 +167,7 @@
         $mform->setAdvanced('trackforums');
     }
 
-    if ($CFG->htmleditor) {
+    if (!empty($CFG->htmleditor)) {
         $choices = array();
         $choices['0'] = get_string('texteditor');
         $choices['1'] = get_string('htmleditor');
Index: lang/en_utf8/admin.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lang/en_utf8/admin.php,v
retrieving revision 1.218
diff -u -r1.218 admin.php
--- lang/en_utf8/admin.php	7 Aug 2008 22:56:34 -0000	1.218
+++ lang/en_utf8/admin.php	12 Aug 2008 09:29:52 -0000
@@ -733,6 +733,7 @@
 Once you do this you can not go back again. <br /><br />
 Please note that this process can take a long time. <br /><br />
 Are you sure you want to upgrade this server to this version?';
+$string['upgradetimedout'] = 'Upgrade timed out, please restart the upgrade.';
 $string['upgradingdata'] = 'Upgrading data';
 $string['upgradinglogs'] = 'Upgrading logs';
 $string['uploaduserspreview'] = 'Upload users preview';
Index: lang/en_utf8/error.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lang/en_utf8/error.php,v
retrieving revision 1.122
diff -u -r1.122 error.php
--- lang/en_utf8/error.php	8 Aug 2008 11:50:46 -0000	1.122
+++ lang/en_utf8/error.php	12 Aug 2008 09:29:52 -0000
@@ -436,6 +436,7 @@
 $string['updatersserror'] = 'There was an error trying to update RSS feed with id: $a';
 $string['upgradeversionfail'] = 'Upgrade of backup system failed! (Could not update version in config table.)';
 $string['upgradefail'] = 'Upgrade failed! $a';
+$string['upgraderunning'] = 'Site is being upgraded, please retry later.';
 $string['younotteacher'] = 'You are not a teacher!';
 $string['wrongcall'] = 'This script is called wrongly';
 $string['wrongcontextid'] = 'Context ID was incorrect (cannot find it)';
Index: mod/assignment/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/assignment/lib.php,v
retrieving revision 1.344
diff -u -r1.344 lib.php
--- mod/assignment/lib.php	11 Aug 2008 15:31:55 -0000	1.344
+++ mod/assignment/lib.php	12 Aug 2008 09:30:14 -0000
@@ -2212,41 +2212,60 @@
 }
 
 /**
- * Update grades by firing grade_updated event
+ * Update activity grades
  *
- * @param object $assignment null means all assignments
- * @param int $userid specific user only, 0 mean all
+ * @param object $assignment
+ * @param int $userid specific user only, 0 means all
  */
-function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
+function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
     require_once($CFG->libdir.'/gradelib.php');
 
-    if ($assignment != null) {
-        if ($grades = assignment_get_user_grades($assignment, $userid)) {
-            foreach($grades as $k=>$v) {
-                if ($v->rawgrade == -1) {
-                    $grades[$k]->rawgrade = null;
-                }
+    if ($assignment->grade == 0) {
+        assignment_grade_item_update($assignment);
+
+    } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
+        foreach($grades as $k=>$v) {
+            if ($v->rawgrade == -1) {
+                $grades[$k]->rawgrade = null;
             }
-            assignment_grade_item_update($assignment, $grades);
-        } else {
-            assignment_grade_item_update($assignment);
         }
+        assignment_grade_item_update($assignment, $grades);
 
     } else {
-        $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
-                  FROM {assignment} a, {course_modules} cm, {modules} m
-                 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $assignment) {
-                if ($assignment->grade != 0) {
-                    assignment_update_grades($assignment);
-                } else {
-                    assignment_grade_item_update($assignment);
-                }
-            }
-            $rs->close();
-        }
+        assignment_grade_item_update($assignment);
+    }
+}
+
+/**
+ * Update all grades in gradebook.
+ */
+function assignment_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {assignment} a, {course_modules} cm, {modules} m
+             WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
+              FROM {assignment} a, {course_modules} cm, {modules} m
+             WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        // too much debug output
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('assignmentupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $assignment) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            assignment_update_grades($assignment);
+            $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
+        }
+        $DB->set_debug($prevdebug);
+        $rs->close();
+        upgrade_set_timeout(); // reset to default timeout
     }
 }
 
Index: mod/scorm/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/scorm/lib.php,v
retrieving revision 1.98
diff -u -r1.98 lib.php
--- mod/scorm/lib.php	24 Jul 2008 21:59:16 -0000	1.98
+++ mod/scorm/lib.php	12 Aug 2008 09:30:30 -0000
@@ -441,39 +441,54 @@
 /**
  * Update grades in central gradebook
  *
- * @param object $scorm null means all scormbases
+ * @param object $scorm
  * @param int $userid specific user only, 0 mean all
  */
-function scorm_update_grades($scorm=null, $userid=0, $nullifnone=true) {
+function scorm_update_grades($scorm, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
-    if (!function_exists('grade_update')) { //workaround for buggy PHP versions
-        require_once($CFG->libdir.'/gradelib.php');
-    }
+    require_once($CFG->libdir.'/gradelib.php');
 
-    if ($scorm != null) {
-        if ($grades = scorm_get_user_grades($scorm, $userid)) {
-            scorm_grade_item_update($scorm, $grades);
-
-        } else if ($userid and $nullifnone) {
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = NULL;
-            scorm_grade_item_update($scorm, $grade);
+    if ($grades = scorm_get_user_grades($scorm, $userid)) {
+        scorm_grade_item_update($scorm, $grades);
 
-        } else {
-            scorm_grade_item_update($scorm);
-        }
+    } else if ($userid and $nullifnone) {
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = NULL;
+        scorm_grade_item_update($scorm, $grade);
 
     } else {
-        $sql = "SELECT s.*, cm.idnumber as cmidnumber
-                  FROM {scorm} s, {course_modules} cm, {modules} m
-                 WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $scorm) {
-                scorm_update_grades($scorm, 0, false);
-            }
-            $rs->close();
+        scorm_grade_item_update($scorm);
+    }
+}
+
+/**
+ * Update all grades in gradebook.
+ */
+function scorm_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {scorm} s, {course_modules} cm, {modules} m
+             WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT s.*, cm.idnumber AS cmidnumber, s.course AS courseid
+              FROM {scorm} s, {course_modules} cm, {modules} m
+             WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('scormupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $scorm) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            scorm_update_grades($scorm, 0, false);
+            $pbar->update($i, $count, "Updating Scorm grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
Index: mod/forum/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/forum/lib.php,v
retrieving revision 1.700
diff -u -r1.700 lib.php
--- mod/forum/lib.php	9 Aug 2008 14:24:59 -0000	1.700
+++ mod/forum/lib.php	12 Aug 2008 09:30:23 -0000
@@ -1384,45 +1384,62 @@
 }
 
 /**
- * Update grades by firing grade_updated event
+ * Update activity grades
  *
- * @param object $forum null means all forums
- * @param int $userid specific user only, 0 mean all
+ * @param object $forum
+ * @param int $userid specific user only, 0 means all
  * @param boolean $nullifnone return null if grade does not exist
  * @return void
  */
-function forum_update_grades($forum=null, $userid=0, $nullifnone=true) {
+function forum_update_grades($forum, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
+    require_once($CFG->libdir.'/gradelib.php');
 
-    if ($forum != null) {
-        require_once($CFG->libdir.'/gradelib.php');
-        if ($grades = forum_get_user_grades($forum, $userid)) {
-            forum_grade_item_update($forum, $grades);
+    if (!$forum->assessed) {
+        forum_grade_item_update($forum);
 
-        } else if ($userid and $nullifnone) {
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = NULL;
-            forum_grade_item_update($forum, $grade);
+    } else if ($grades = forum_get_user_grades($forum, $userid)) {
+        forum_grade_item_update($forum, $grades);
 
-        } else {
-            forum_grade_item_update($forum);
-        }
+    } else if ($userid and $nullifnone) {
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = NULL;
+        forum_grade_item_update($forum, $grade);
 
     } else {
-        $sql = "SELECT f.*, cm.idnumber as cmidnumber
-                  FROM {forum} f, {course_modules} cm, {modules} m
-                 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $forum) {
-                if ($forum->assessed) {
-                    forum_update_grades($forum, 0, false);
-                } else {
-                    forum_grade_item_update($forum);
-                }
-            }
-            $rs->close();
+        forum_grade_item_update($forum);
+    }
+}
+
+/**
+ * Update all grades in gradebook.
+ */
+function forum_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {forum} f, {course_modules} cm, {modules} m
+             WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT f.*, cm.idnumber AS cmidnumber, f.course AS courseid
+              FROM {forum} f, {course_modules} cm, {modules} m
+             WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        // too much debug output
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('forumupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $forum) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            forum_update_grades($forum, 0, false);
+            $pbar->update($i, $count, "Updating Forum grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
Index: mod/assignment/db/upgrade.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/assignment/db/upgrade.php,v
retrieving revision 1.18
diff -u -r1.18 upgrade.php
--- mod/assignment/db/upgrade.php	31 Jul 2008 22:15:34 -0000	1.18
+++ mod/assignment/db/upgrade.php	12 Aug 2008 09:30:14 -0000
@@ -26,13 +26,9 @@
 //===== 1.9.0 upgrade line ======//
 
     if ($result && $oldversion < 2007101511) {
-        notify('Processing assignment grades, this may take a while if there are many assignments...', 'notifysuccess');
         // change grade typo to text if no grades MDL-13920
         require_once $CFG->dirroot.'/mod/assignment/lib.php';
-        // too much debug output
-        $DB->set_debug(false);
-        assignment_update_grades();
-        $DB->set_debug(true);
+        assignment_upgrade_grades();
         upgrade_mod_savepoint($result, 2007101511, 'assignment');
     }
 
@@ -63,6 +59,7 @@
             $i = 0;
             foreach ($rs as $submission) {
                 $i++;
+                upgrade_set_timeout(180); // set up timeout, may also abort execution
                 $basepath = "$CFG->dataroot/$submission->course/$CFG->moddata/assignment/$submission->assignment/$submission->userid/";
                 if (!file_exists($basepath)) {
                     //no files
Index: mod/hotpot/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/hotpot/lib.php,v
retrieving revision 1.104
diff -u -r1.104 lib.php
--- mod/hotpot/lib.php	24 Jul 2008 21:59:15 -0000	1.104
+++ mod/hotpot/lib.php	12 Aug 2008 09:30:28 -0000
@@ -1256,46 +1256,63 @@
 
 /**
  * Update grades in central gradebook
- * this function is called from db/upgrade.php
- *     it is initially called with no arguments, which forces it to get a list of all hotpots
- *     it then iterates through the hotpots, calling itself to create a grade record for each hotpot
- *
- * @param object $hotpot null means all hotpots
+ * @param object $hotpot
  * @param int $userid specific user only, 0 means all users
  */
-function hotpot_update_grades($hotpot=null, $userid=0, $nullifnone=true) {
+function hotpot_update_grades($hotpot, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
     require_once($CFG->libdir.'/gradelib.php');
 
-    if (is_null($hotpot)) {
-        // update (=create) grades for all hotpots
-        $sql = "
-            SELECT h.*, cm.idnumber as cmidnumber
-            FROM {hotpot} h, {course_modules} cm, {modules} m
-            WHERE m.name='hotpot' AND m.id=cm.module AND cm.instance=h.id"
-        ;
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $hotpot) {
-                hotpot_update_grades($hotpot, 0, false);
-            }
-            $rs->close();
-        }
+    // update (=create) grade for a single hotpot
+    if ($grades = hotpot_get_user_grades($hotpot, $userid)) {
+        hotpot_grade_item_update($hotpot, $grades);
+
+    } else if ($userid && $nullifnone) {
+        // no grades for this user, but we must force the creation of a "null" grade record
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = null;
+        hotpot_grade_item_update($hotpot, $grade);
+
     } else {
-        // update (=create) grade for a single hotpot
-        if ($grades = hotpot_get_user_grades($hotpot, $userid)) {
-            hotpot_grade_item_update($hotpot, $grades);
-
-        } else if ($userid && $nullifnone) {
-            // no grades for this user, but we must force the creation of a "null" grade record
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = null;
-            hotpot_grade_item_update($hotpot, $grade);
+        // no grades and no userid
+        hotpot_grade_item_update($hotpot);
+    }
+}
 
-        } else {
-            // no grades and no userid
-            hotpot_grade_item_update($hotpot);
+/**
+ * Update all grades in gradebook.
+ * this function is called from db/upgrade.php
+ *     it iterates through the hotpots, calling hotpot_update_grades() to create a grade record for each hotpot
+ */
+function hotpot_upgrade_grades() {
+    global $DB;
+
+    // upgrade (=create) grades for all hotpots
+    $sql = "
+        SELECT COUNT('x')
+        FROM {hotpot} h, {course_modules} cm, {modules} m
+        WHERE m.name='hotpot' AND m.id=cm.module AND cm.instance=h.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "
+        SELECT h.*, cm.idnumber AS cmidnumber
+        FROM {hotpot} h, {course_modules} cm, {modules} m
+        WHERE m.name='hotpot' AND m.id=cm.module AND cm.instance=h.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        // too much debug output
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('hotpotupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $hotpot) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            hotpot_update_grades($hotpot, 0, false);
+            $pbar->update($i, $count, "Updating Hotpot grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
Index: mod/hotpot/db/upgrade.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/hotpot/db/upgrade.php,v
retrieving revision 1.4
diff -u -r1.4 upgrade.php
--- mod/hotpot/db/upgrade.php	15 May 2008 21:40:07 -0000	1.4
+++ mod/hotpot/db/upgrade.php	12 Aug 2008 09:30:28 -0000
@@ -12,18 +12,9 @@
 
     // update hotpot grades from sites earlier than Moodle 1.9, 27th March 2008
     if ($result && $oldversion < 2007101511) {
-
-        // ensure "hotpot_update_grades" function is available
+        // ensure "hotpot_upgrade_grades" function is available
         require_once $CFG->dirroot.'/mod/hotpot/lib.php';
-
-        // disable display of debugging messages
-        $DB->set_debug(false);
-
-        notify('Processing hotpot grades, this may take a while if there are many hotpots...', 'notifysuccess');
-        hotpot_update_grades();
-
-        // restore debug
-        $DB->set_debug(true);
+        hotpot_upgrade_grades();
     }
 
     return $result;
Index: mod/quiz/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/quiz/lib.php,v
retrieving revision 1.310
diff -u -r1.310 lib.php
--- mod/quiz/lib.php	31 Jul 2008 08:01:50 -0000	1.310
+++ mod/quiz/lib.php	12 Aug 2008 09:30:29 -0000
@@ -304,43 +304,57 @@
 /**
  * Update grades in central gradebook
  *
- * @param object $quiz null means all quizs
- * @param int $userid specific user only, 0 mean all
+ * @param object $quiz
+ * @param int $userid specific user only, 0 means all
  */
-function quiz_update_grades($quiz=null, $userid=0, $nullifnone=true) {
+function quiz_update_grades($quiz, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
-    if (!function_exists('grade_update')) { //workaround for buggy PHP versions
-        require_once($CFG->libdir.'/gradelib.php');
-    }
+    require_once($CFG->libdir.'/gradelib.php');
 
-    if ($quiz != null) {
-        if ($grades = quiz_get_user_grades($quiz, $userid)) {
-            quiz_grade_item_update($quiz, $grades);
-
-        } else if ($userid and $nullifnone) {
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = NULL;
-            quiz_grade_item_update($quiz, $grade);
+    if ($quiz->grade == 0) {
+        quiz_grade_item_update($quiz);
 
-        } else {
-            quiz_grade_item_update($quiz);
-        }
+    } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
+        quiz_grade_item_update($quiz, $grades);
+
+    } else if ($userid and $nullifnone) {
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = NULL;
+        quiz_grade_item_update($quiz, $grade);
 
     } else {
-        $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
-                  FROM {quiz} a, {course_modules} cm, {modules} m
-                 WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $quiz) {
-                if ($quiz->grade != 0) {
-                    quiz_update_grades($quiz, 0, false);
-                } else {
-                    quiz_grade_item_update($quiz);
-                }
-            }
-            $rs->close();
+        quiz_grade_item_update($quiz);
+    }
+}
+    
+/**
+ * Update all grades in gradebook.
+ */
+function quiz_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {quiz} a, {course_modules} cm, {modules} m
+             WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
+              FROM {quiz} a, {course_modules} cm, {modules} m
+             WHERE m.name='quiz' AND m.id=cm.module AND cm.instance=a.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('quizupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $quiz) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            quiz_update_grades($quiz, 0, false);
+            $pbar->update($i, $count, "Updating Quiz grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
Index: mod/glossary/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/mod/glossary/lib.php,v
retrieving revision 1.219
diff -u -r1.219 lib.php
--- mod/glossary/lib.php	9 Aug 2008 14:24:59 -0000	1.219
+++ mod/glossary/lib.php	12 Aug 2008 09:30:25 -0000
@@ -323,43 +323,58 @@
 }
 
 /**
- * Update grades by firing grade_updated event
+ * Update activity grades
  *
  * @param object $glossary null means all glossaries
- * @param int $userid specific user only, 0 mean all
+ * @param int $userid specific user only, 0 means all
  */
 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
     global $CFG, $DB;
     require_once($CFG->libdir.'/gradelib.php');
 
-    if ($glossary != null) {
-        if ($grades = glossary_get_user_grades($glossary, $userid)) {
-            glossary_grade_item_update($glossary, $grades);
-
-        } else if ($userid and $nullifnone) {
-            $grade = new object();
-            $grade->userid   = $userid;
-            $grade->rawgrade = NULL;
-            glossary_grade_item_update($glossary, $grade);
-
-        } else {
-            glossary_grade_item_update($glossary);
-        }
+    if ($glossary->assessed) {
+        glossary_grade_item_update($glossary);
+    } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
+        glossary_grade_item_update($glossary, $grades);
+
+    } else if ($userid and $nullifnone) {
+        $grade = new object();
+        $grade->userid   = $userid;
+        $grade->rawgrade = NULL;
+        glossary_grade_item_update($glossary, $grade);
 
     } else {
-        $sql = "SELECT g.*, cm.idnumber as cmidnumber
-                  FROM {glossary} g, {course_modules} cm, {modules} m
-                 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
-        if ($rs = $DB->get_recordset_sql($sql)) {
-            foreach ($rs as $glossary) {
-                if ($glossary->assessed) {
-                    glossary_update_grades($glossary, 0, false);
-                } else {
-                    glossary_grade_item_update($glossary);
-                }
-            }
-            $rs->close();
+        glossary_grade_item_update($glossary);
+    }
+}
+
+/**
+ * Update all grades in gradebook.
+ */
+function glossary_upgrade_grades() {
+    global $DB;
+
+    $sql = "SELECT COUNT('x')
+              FROM {glossary} g, {course_modules} cm, {modules} m
+             WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
+    $count = $DB->count_records_sql($sql);
+
+    $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
+              FROM {glossary} g, {course_modules} cm, {modules} m
+             WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
+    if ($rs = $DB->get_recordset_sql($sql)) {
+        $prevdebug = $DB->get_debug();
+        $DB->set_debug(false);
+        $pbar = new progress_bar('glossaryupgradegrades', 500, true);
+        $i=0;
+        foreach ($rs as $glossary) {
+            $i++;
+            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
+            glossary_update_grades($glossary, 0, false);
+            $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
         }
+        $DB->set_debug($prevdebug);
+        $rs->close();
     }
 }
 
