[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/lib/db/ -> mysql.php (source)

   1  <?PHP  //$Id: mysql.php,v 1.256.2.2 2008/05/01 06:03:32 dongsheng Exp $
   2  // THIS FILE IS DEPRECATED!  PLEASE DO NOT MAKE CHANGES TO IT!
   3  //
   4  // IT IS USED ONLY FOR UPGRADES FROM BEFORE MOODLE 1.7, ALL 
   5  // LATER CHANGES SHOULD USE upgrade.php IN THIS DIRECTORY.
   6  //
   7  //
   8  // This file is tailored to MySQL
   9  
  10  function main_upgrade($oldversion=0) {
  11  
  12      global $CFG, $THEME, $db;
  13  
  14      $result = true;
  15  
  16      if ($oldversion == 0) {
  17          execute_sql("
  18            CREATE TABLE `config` (
  19              `id` int(10) unsigned NOT NULL auto_increment,
  20              `name` varchar(255) NOT NULL default '',
  21              `value` varchar(255) NOT NULL default '',
  22              PRIMARY KEY  (`id`),
  23              UNIQUE KEY `name` (`name`)
  24            ) COMMENT='Moodle configuration variables';");
  25          notify("Created a new table 'config' to hold configuration data");
  26      }
  27      if ($oldversion < 2002073100) {
  28          execute_sql(" DELETE FROM `modules` WHERE `name` = 'chat' ");
  29      }
  30      if ($oldversion < 2002080200) {
  31          execute_sql(" ALTER TABLE `modules` DROP `fullname`  ");
  32          execute_sql(" ALTER TABLE `modules` DROP `search`  ");
  33      }
  34      if ($oldversion < 2002080300) {
  35          execute_sql(" ALTER TABLE `log_display` CHANGE `table` `mtable` VARCHAR( 20 ) NOT NULL ");
  36          execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 3 ) DEFAULT '3' NOT NULL ");
  37      }
  38      if ($oldversion < 2002082100) {
  39          execute_sql(" ALTER TABLE `course` CHANGE `guest` `guest` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL ");
  40      }
  41      if ($oldversion < 2002082101) {
  42          execute_sql(" ALTER TABLE `user` ADD `maildisplay` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL AFTER `mailformat` ");
  43      }
  44      if ($oldversion < 2002090100) {
  45          execute_sql(" ALTER TABLE `course_sections` CHANGE `summary` `summary` TEXT NOT NULL ");
  46      }
  47      if ($oldversion < 2002090701) {
  48          execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 10 ) DEFAULT '3' NOT NULL ");
  49          execute_sql(" ALTER TABLE `user_teachers` ADD `role` VARCHAR(40) NOT NULL AFTER `authority` ");
  50      }
  51      if ($oldversion < 2002090800) {
  52          execute_sql(" ALTER TABLE `course` ADD `teachers` VARCHAR( 100 ) DEFAULT 'Teachers' NOT NULL AFTER `teacher` ");
  53          execute_sql(" ALTER TABLE `course` ADD `students` VARCHAR( 100 ) DEFAULT 'Students' NOT NULL AFTER `student` ");
  54      }
  55      if ($oldversion < 2002091000) {
  56          execute_sql(" ALTER TABLE `user` CHANGE `personality` `secret` VARCHAR( 15 ) NOT NULL DEFAULT ''  ");
  57      }
  58      if ($oldversion < 2002091400) {
  59          execute_sql(" ALTER TABLE `user` ADD `lang` VARCHAR( 3 ) DEFAULT 'en' NOT NULL AFTER `country`  ");
  60      }
  61      if ($oldversion < 2002091900) {
  62          notify("Most Moodle configuration variables have been moved to the database and can now be edited via the admin page.");
  63          notify("Although it is not vital that you do so, you might want to edit <U>config.php</U> and remove all the unused settings (except the database, URL and directory definitions).  See <U>config-dist.php</U> for an example of how your new slim config.php should look.");
  64      }
  65      if ($oldversion < 2002092000) {
  66          execute_sql(" ALTER TABLE `user` CHANGE `lang` `lang` VARCHAR(5) DEFAULT 'en' NOT NULL  ");
  67      }
  68      if ($oldversion < 2002092100) {
  69          execute_sql(" ALTER TABLE `user` ADD `deleted` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `confirmed` ");
  70      }
  71      if ($oldversion < 2002101001) {
  72          execute_sql(" ALTER TABLE `user` ADD `htmleditor` TINYINT(1) UNSIGNED DEFAULT '1' NOT NULL AFTER `maildisplay` ");
  73      }
  74      if ($oldversion < 2002101701) {
  75          execute_sql(" ALTER TABLE `reading` RENAME `resource` ");  // Small line with big consequences!
  76          execute_sql(" DELETE FROM `log_display` WHERE module = 'reading'");
  77          execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('resource', 'view', 'resource', 'name') ");
  78          execute_sql(" UPDATE log SET module = 'resource' WHERE module = 'reading' ");
  79          execute_sql(" UPDATE modules SET name = 'resource' WHERE name = 'reading' ");
  80      }
  81  
  82      if ($oldversion < 2002102503) {
  83          execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` ");
  84          require_once("$CFG->dirroot/mod/forum/lib.php");
  85          require_once("$CFG->dirroot/course/lib.php");
  86  
  87          if (! $module = get_record("modules", "name", "forum")) {
  88              notify("Could not find forum module!!");
  89              return false;
  90          }
  91  
  92          // First upgrade the site forums
  93          if ($site = get_site()) {
  94              print_heading("Making News forums editable for main site (moving to section 1)...");
  95              if ($news = forum_get_course_forum($site->id, "news")) {
  96                  $mod->course = $site->id;
  97                  $mod->module = $module->id;
  98                  $mod->instance = $news->id;
  99                  $mod->section = 1;
 100                  if (! $mod->coursemodule = add_course_module($mod) ) {
 101                      notify("Could not add a new course module to the site");
 102                      return false;
 103                  }
 104                  if (! $sectionid = add_mod_to_section($mod) ) {
 105                      notify("Could not add the new course module to that section");
 106                      return false;
 107                  }
 108                  if (! set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
 109                      notify("Could not update the course module with the correct section");
 110                      return false;
 111                  }
 112              }
 113          }
 114  
 115  
 116          // Now upgrade the courses.
 117          if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0")) {
 118              print_heading("Making News and Social forums editable for each course (moving to section 0)...");
 119              foreach ($courses as $course) {
 120                  if ($course->format == "social") {  // we won't touch them
 121                      continue;
 122                  }
 123                  if ($news = forum_get_course_forum($course->id, "news")) {
 124                      $mod->course = $course->id;
 125                      $mod->module = $module->id;
 126                      $mod->instance = $news->id;
 127                      $mod->section = 0;
 128                      if (! $mod->coursemodule = add_course_module($mod) ) {
 129                          notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'");
 130                          return false;
 131                      }
 132                      if (! $sectionid = add_mod_to_section($mod) ) {
 133                          notify("Could not add the new course module to that section");
 134                          return false;
 135                      }
 136                      if (! set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
 137                          notify("Could not update the course module with the correct section");
 138                          return false;
 139                      }
 140                  }
 141                  if ($social = forum_get_course_forum($course->id, "social")) {
 142                      $mod->course = $course->id;
 143                      $mod->module = $module->id;
 144                      $mod->instance = $social->id;
 145                      $mod->section = 0;
 146                      if (! $mod->coursemodule = add_course_module($mod) ) {
 147                          notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'");
 148                          return false;
 149                      }
 150                      if (! $sectionid = add_mod_to_section($mod) ) {
 151                          notify("Could not add the new course module to that section");
 152                          return false;
 153                      }
 154                      if (! set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
 155                          notify("Could not update the course module with the correct section");
 156                          return false;
 157                      }
 158                  }
 159              }
 160          }
 161      }
 162  
 163      if ($oldversion < 2002111003) {
 164          execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` ");
 165          if ($courses = get_records_sql("SELECT * FROM course")) {
 166              require_once("$CFG->dirroot/course/lib.php");
 167              foreach ($courses as $course) {
 168  
 169                  $modinfo = serialize(get_array_of_activities($course->id));
 170  
 171                  if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
 172                      notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
 173                  }
 174              }
 175          }
 176      }
 177  
 178      if ($oldversion < 2002111100) {
 179          print_simple_box_start("CENTER", "", "#FFCCCC");
 180          echo "<FONT SIZE=+1>";
 181          echo "<P>Changes have been made to all built-in themes, to add the new popup navigation menu.";
 182          echo "<P>If you have customised themes, you will need to edit theme/xxxx/header.html as follows:";
 183          echo "<UL><LI>Change anywhere it says <B>$"."button</B> to say <B>$"."menu</B>";
 184          echo "<LI>Add <B>$"."button</B> elsewhere (eg at the end of the navigation bar)</UL>";
 185          echo "<P>See the standard themes for examples, eg: theme/standard/header.html";
 186          print_simple_box_end();
 187      }
 188  
 189      if ($oldversion < 2002111200) {
 190          execute_sql(" ALTER TABLE `course` ADD `showrecent` TINYINT(5) UNSIGNED DEFAULT '1' NOT NULL AFTER `numsections` ");
 191      }
 192  
 193      if ($oldversion < 2002111400) {
 194      // Rebuild all course caches, because some may not be done in new installs (eg site page)
 195          if ($courses = get_records_sql("SELECT * FROM course")) {
 196              require_once("$CFG->dirroot/course/lib.php");
 197              foreach ($courses as $course) {
 198  
 199                  $modinfo = serialize(get_array_of_activities($course->id));
 200  
 201                  if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
 202                      notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
 203                  }
 204              }
 205          }
 206      }
 207  
 208      if ($oldversion < 2002112000) {
 209          set_config("guestloginbutton", 1);
 210      }
 211  
 212      if ($oldversion < 2002122300) {
 213          execute_sql("ALTER TABLE `log` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
 214          execute_sql("ALTER TABLE `user_admins` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
 215          execute_sql("ALTER TABLE `user_students` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
 216          execute_sql("ALTER TABLE `user_teachers` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
 217          execute_sql("ALTER TABLE `user_students` CHANGE `start` `timestart` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
 218          execute_sql("ALTER TABLE `user_students` CHANGE `end` `timeend` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
 219      }
 220  
 221      if ($oldversion < 2002122700) {
 222          if (! record_exists("log_display", "module", "user", "action", "view")) {
 223              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'CONCAT(firstname,' ',lastname)') ");
 224          }
 225      }
 226      if ($oldversion < 2003010101) {
 227          delete_records("log_display", "module", "user");
 228          $new->module = "user";
 229          $new->action = "view";
 230          $new->mtable = "user";
 231          $new->field  = "CONCAT(firstname,\" \",lastname)";
 232          insert_record("log_display", $new);
 233  
 234          delete_records("log_display", "module", "course");
 235          $new->module = "course";
 236          $new->action = "view";
 237          $new->mtable = "course";
 238          $new->field  = "fullname";
 239          insert_record("log_display", $new);
 240          $new->action = "update";
 241          insert_record("log_display", $new);
 242          $new->action = "enrol";
 243          insert_record("log_display", $new);
 244      }
 245  
 246      if ($oldversion < 2003012200) {
 247          // execute_sql(" ALTER TABLE `log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL ");
 248          // Commented out - see below where it's done properly
 249      }
 250  
 251      if ($oldversion < 2003032500) {
 252          modify_database("", "CREATE TABLE `prefix_user_coursecreators` (
 253                               `id` int(10) unsigned NOT NULL auto_increment,
 254                               `userid` int(10) unsigned NOT NULL default '0',
 255                               PRIMARY KEY  (`id`),
 256                               UNIQUE KEY `id` (`id`)
 257                               ) TYPE=MyISAM COMMENT='One record per course creator';");
 258      }
 259      if ($oldversion < 2003032602) {
 260          // Redoing it because of no prefix last time
 261          execute_sql(" ALTER TABLE `{$CFG->prefix}log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL ");
 262          // Add some indexes for speed
 263          execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(course) ");
 264          execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(userid) ");
 265      }
 266  
 267      if ($oldversion < 2003041400) {
 268          table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
 269      }
 270  
 271      if ($oldversion < 2003042104) {  // Try to update permissions of all files
 272          if ($files = get_directory_list($CFG->dataroot)) {
 273              echo "Attempting to update permissions for all files... ignore any errors.";
 274              foreach ($files as $file) {
 275                  echo "$CFG->dataroot/$file<br />";
 276                  @chmod("$CFG->dataroot/$file", $CFG->directorypermissions);
 277              }
 278          }
 279      }
 280  
 281      if ($oldversion < 2003042400) {
 282      // Rebuild all course caches, because of changes to do with visible variable
 283          if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
 284              require_once("$CFG->dirroot/course/lib.php");
 285              foreach ($courses as $course) {
 286                  $modinfo = serialize(get_array_of_activities($course->id));
 287  
 288                  if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
 289                      notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
 290                  }
 291              }
 292          }
 293      }
 294  
 295      if ($oldversion < 2003042500) {
 296      //  Convert all usernames to lowercase.
 297          $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user");
 298          $cerrors = "";
 299          $rarray = array();
 300  
 301          foreach ($users as $user) {      // Check for possible conflicts
 302              $lcname = trim(moodle_strtolower($user->username));
 303              if (in_array($lcname, $rarray)) {
 304                  $cerrors .= $user->id."->".$lcname.'<br/>' ;
 305              } else {
 306                  array_push($rarray,$lcname);
 307              }
 308          }
 309  
 310          if ($cerrors != '') {
 311              notify("Error: Cannot convert usernames to lowercase.
 312                      Following usernames would overlap (id->username):<br/> $cerrors .
 313                      Please resolve overlapping errors.");
 314              $result = false;
 315          }
 316  
 317          $cerrors = "";
 318          echo "Checking userdatabase:<br />";
 319          foreach ($users as $user) {
 320              $lcname = trim(moodle_strtolower($user->username));
 321              if ($lcname != $user->username) {
 322                  $convert = set_field("user" , "username" , $lcname, "id", $user->id);
 323                  if (!$convert) {
 324                      if ($cerrors){
 325                         $cerrors .= ", ";
 326                      }
 327                      $cerrors .= $item;
 328                  } else {
 329                      echo ".";
 330                  }
 331              }
 332          }
 333          if ($cerrors != '') {
 334              notify("There were errors when converting following usernames to lowercase.
 335                     '$cerrors' . Sorry, but you will need to fix your database by hand.");
 336              $result = false;
 337          }
 338      }
 339  
 340      if ($oldversion < 2003042600) {
 341          /// Some more indexes - we need all the help we can get on the logs
 342          //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(module) ");
 343          //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(action) ");
 344      }
 345  
 346      if ($oldversion < 2003042700) {
 347          /// Changing to multiple indexes
 348          execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX module ", false);
 349          execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX action ", false);
 350          execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX course ", false);
 351          execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX userid ", false);
 352          execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX coursemoduleaction (course,module,action) ");
 353          execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX courseuserid (course,userid) ");
 354      }
 355  
 356      if ($oldversion < 2003042801) {
 357          execute_sql("CREATE TABLE `{$CFG->prefix}course_display` (
 358                          `id` int(10) unsigned NOT NULL auto_increment,
 359                          `course` int(10) unsigned NOT NULL default '0',
 360                          `userid` int(10) unsigned NOT NULL default '0',
 361                          `display` int(10) NOT NULL default '0',
 362                          PRIMARY KEY  (`id`),
 363                          UNIQUE KEY `id` (`id`),
 364                          KEY `courseuserid` (course,userid)
 365                       ) TYPE=MyISAM COMMENT='Stores info about how to display the course'");
 366      }
 367  
 368      if ($oldversion < 2003050400) {
 369          table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
 370      }
 371  
 372      if ($oldversion < 2003050900) {
 373          table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
 374      }
 375  
 376      if ($oldversion < 2003050902) {
 377          if (get_records("modules", "name", "pgassignment")) {
 378              print_simple_box("Note: the pgassignment module has been removed (it will be replaced later by the workshop module).  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "$THEME->cellheading", "20", "noticebox");
 379          }
 380      }
 381  
 382      if ($oldversion < 2003051600) {
 383          print_simple_box("Thanks for upgrading!<p>There are many changes since the last release.  Please read the release notes carefully.  If you are using CUSTOM themes you will need to edit them.  You will also need to check your site's config.php file.", "center", "50%", "$THEME->cellheading", "20", "noticebox");
 384      }
 385  
 386      if ($oldversion < 2003052300) {
 387          table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
 388      }
 389  
 390      if ($oldversion < 2003072100) {
 391          table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
 392      }
 393  
 394      if ($oldversion < 2003072101) {
 395          table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
 396      }
 397  
 398      if ($oldversion < 2003072800) {
 399          print_simple_box("The following database index improves performance, but can be quite large - if you are upgrading and you have problems with a limited quota you may want to delete this index later from the '{$CFG->prefix}log' table in your database", "center", "50%", "$THEME->cellheading", "20", "noticebox");
 400          flush();
 401          execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX timecoursemoduleaction (time,course,module,action) ");
 402          execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX courseuserid (course,userid) ");
 403          execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX courseuserid (course,userid) ");
 404      }
 405  
 406      if ($oldversion < 2003072803) {
 407          table_column("course_categories", "", "description", "text", "", "", "");
 408          table_column("course_categories", "", "parent", "integer", "10", "unsigned");
 409          table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
 410          table_column("course_categories", "", "courseorder", "text", "", "", "");
 411          table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
 412          table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
 413      }
 414  
 415      if ($oldversion < 2003080400) {
 416          table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
 417          table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
 418      }
 419  
 420      if ($oldversion < 2003080700) {
 421          notify("Cleaning up categories and course ordering...");
 422          fix_course_sortorder();
 423      }
 424  
 425      if ($oldversion < 2003081001) {
 426          table_column("course", "format", "format", "varchar", "10", "", "topics");
 427      }
 428  
 429      if ($oldversion < 2003081500) {
 430  //        print_simple_box("Some important changes have been made to how course creators work.  Formerly, they could create new courses and assign teachers, and teachers could edit courses.  Now, ordinary teachers can no longer edit courses - they <b>need to be a teacher of a course AND a course creator</b>.  A new site-wide configuration variable allows you to choose whether to allow course creators to create new courses as well (by default this is off).  <p>The following update will automatically convert all your existing teachers into course creators, to maintain backward compatibility.  Make sure you look at your upgraded site carefully and understand these new changes.", "center", "50%", "$THEME->cellheading", "20", "noticebox");
 431  
 432  //        $count = 0;
 433  //        $errorcount = 0;
 434  //        if ($teachers = get_records("user_teachers")) {
 435  //            foreach ($teachers as $teacher) {
 436  //                if (! record_exists("user_coursecreators", "userid", $teacher->userid)) {
 437  //                    $creator = NULL;
 438  //                    $creator->userid = $teacher->userid;
 439  //                    if (!insert_record("user_coursecreators", $creator)) {
 440  //                        $errorcount++;
 441  //                    } else {
 442  //                        $count++;
 443  //                    }
 444  //                }
 445  //            }
 446  //        }
 447  //        print_simple_box("$count teachers were upgraded to course creators (with $errorcount errors)", "center", "50%", "$THEME->cellheading", "20", "noticebox");
 448  
 449      }
 450  
 451      if ($oldversion < 2003081501) {
 452          execute_sql(" CREATE TABLE `{$CFG->prefix}scale` (
 453                           `id` int(10) unsigned NOT NULL auto_increment,
 454                           `courseid` int(10) unsigned NOT NULL default '0',
 455                           `userid` int(10) unsigned NOT NULL default '0',
 456                           `name` varchar(255) NOT NULL default '',
 457                           `scale` text NOT NULL,
 458                           `description` text NOT NULL,
 459                           `timemodified` int(10) unsigned NOT NULL default '0',
 460                           PRIMARY KEY  (id)
 461                         ) TYPE=MyISAM COMMENT='Defines grading scales'");
 462  
 463      }
 464  
 465      if ($oldversion < 2003081503) {
 466          table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
 467          get_scales_menu(0);    // Just to force the default scale to be created
 468      }
 469  
 470      if ($oldversion < 2003081600) {
 471          table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
 472          table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
 473      }
 474  
 475      if ($oldversion < 2003081900) {
 476          table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
 477      }
 478  
 479      if ($oldversion < 2003082001) {
 480          table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
 481      }
 482  
 483      if ($oldversion < 2003082101) {
 484          execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX category (category) ");
 485      }
 486      if ($oldversion < 2003082702) {
 487          execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
 488      }
 489  
 490      if ($oldversion < 2003091400) {
 491          table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
 492      }
 493  
 494      if ($oldversion < 2003092900) {
 495          table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
 496      }
 497  
 498      if ($oldversion < 2003102700) {
 499          table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
 500          table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
 501  
 502          $db->debug = false;
 503          $CFG->debug = 0;
 504          notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
 505          flush();
 506  
 507          if ($courses = get_records_select("course", "category > 0")) {
 508              foreach ($courses as $course) {
 509                  notify("Processing " . format_string($course->fullname) . " ...", "green");
 510                  flush();
 511                  if ($users = get_records_select("user_teachers", "course = '$course->id'",
 512                                                  "id", "id, userid, timeaccess")) {
 513                      foreach ($users as $user) {
 514                          $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '$course->id' and userid = '$user->userid'                                                               ORDER by time DESC");
 515                          if (empty($loginfo->time)) {
 516                              $loginfo->time = 0;
 517                          }
 518                          execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '$loginfo->time'
 519                                       WHERE userid = '$user->userid' AND course = '$course->id'", false);
 520  
 521                      }
 522                  }
 523  
 524                  if ($users = get_records_select("user_students", "course = '$course->id'",
 525                                                  "id", "id, userid, timeaccess")) {
 526                      foreach ($users as $user) {
 527                          $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log
 528                                                     WHERE course = '$course->id' and userid = '$user->userid'
 529                                                     ORDER by time DESC");
 530                          if (empty($loginfo->time)) {
 531                              $loginfo->time = 0;
 532                          }
 533                          execute_sql("UPDATE {$CFG->prefix}user_students
 534                                       SET timeaccess = '$loginfo->time'
 535                                       WHERE userid = '$user->userid' AND course = '$course->id'", false);
 536  
 537                      }
 538                  }
 539              }
 540          }
 541          notify("All courses complete.", "green");
 542          $db->debug = true;
 543      }
 544  
 545      if ($oldversion < 2003103100) {
 546          table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
 547      }
 548  
 549      if ($oldversion < 2003121600) {
 550          modify_database("", "CREATE TABLE `prefix_groups` (
 551                                  `id` int(10) unsigned NOT NULL auto_increment,
 552                                  `courseid` int(10) unsigned NOT NULL default '0',
 553                                  `name` varchar(254) NOT NULL default '',
 554                                  `description` text NOT NULL,
 555                                  `lang` varchar(10) NOT NULL default 'en',
 556                                  `picture` int(10) unsigned NOT NULL default '0',
 557                                  `timecreated` int(10) unsigned NOT NULL default '0',
 558                                  `timemodified` int(10) unsigned NOT NULL default '0',
 559                                  PRIMARY KEY  (`id`),
 560                                  KEY `courseid` (`courseid`)
 561                                ) TYPE=MyISAM COMMENT='Each record is a group in a course.'; ");
 562  
 563          modify_database("", "CREATE TABLE `prefix_groups_members` (
 564                                  `id` int(10) unsigned NOT NULL auto_increment,
 565                                  `groupid` int(10) unsigned NOT NULL default '0',
 566                                  `userid` int(10) unsigned NOT NULL default '0',
 567                                  `timeadded` int(10) unsigned NOT NULL default '0',
 568                                  PRIMARY KEY  (`id`),
 569                                  KEY `groupid` (`groupid`)
 570                                ) TYPE=MyISAM COMMENT='Lists memberships of users in groups'; ");
 571      }
 572  
 573      if ($oldversion < 2003121800) {
 574          table_column("course", "modinfo", "modinfo", "longtext", "", "", "");
 575      }
 576  
 577      if ($oldversion < 2003122600) {
 578          table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "showreports");
 579          table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
 580      }
 581  
 582      if ($oldversion < 2004010900) {
 583          table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
 584      }
 585  
 586      if ($oldversion < 2004011700) {
 587          modify_database("", "CREATE TABLE `prefix_event` (
 588                                `id` int(10) unsigned NOT NULL auto_increment,
 589                                `name` varchar(255) NOT NULL default '',
 590                                `description` text NOT NULL,
 591                                `courseid` int(10) unsigned NOT NULL default '0',
 592                                `groupid` int(10) unsigned NOT NULL default '0',
 593                                `userid` int(10) unsigned NOT NULL default '0',
 594                                `modulename` varchar(20) NOT NULL default '',
 595                                `instance` int(10) unsigned NOT NULL default '0',
 596                                `eventtype` varchar(20) NOT NULL default '',
 597                                `timestart` int(10) unsigned NOT NULL default '0',
 598                                `timeduration` int(10) unsigned NOT NULL default '0',
 599                                `timemodified` int(10) unsigned NOT NULL default '0',
 600                                PRIMARY KEY  (`id`),
 601                                UNIQUE KEY `id` (`id`),
 602                                KEY `courseid` (`courseid`),
 603                                KEY `userid` (`userid`)
 604                              ) TYPE=MyISAM COMMENT='For everything with a time associated to it'; ");
 605      }
 606  
 607      if ($oldversion < 2004012800) {
 608          modify_database("", "CREATE TABLE `prefix_user_preferences` (
 609                                `id` int(10) unsigned NOT NULL auto_increment,
 610                                `userid` int(10) unsigned NOT NULL default '0',
 611                                `name` varchar(50) NOT NULL default '',
 612                                `value` varchar(255) NOT NULL default '',
 613                                PRIMARY KEY  (`id`),
 614                                UNIQUE KEY `id` (`id`),
 615                                KEY `useridname` (userid,name)
 616                              ) TYPE=MyISAM COMMENT='Allows modules to store arbitrary user preferences'; ");
 617      }
 618  
 619      if ($oldversion < 2004012900) {
 620          table_column("config", "value", "value", "text", "", "", "");
 621      }
 622  
 623      if ($oldversion < 2004013101) {
 624          table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
 625          set_config("upgrade", "logs");
 626      }
 627  
 628      if ($oldversion < 2004020900) {
 629          table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
 630      }
 631  
 632      if ($oldversion < 2004020903) {
 633          modify_database("", "CREATE TABLE `prefix_cache_text` (
 634                                  `id` int(10) unsigned NOT NULL auto_increment,
 635                                  `md5key` varchar(32) NOT NULL default '',
 636                                  `formattedtext` longtext NOT NULL,
 637                                  `timemodified` int(10) unsigned NOT NULL default '0',
 638                                  PRIMARY KEY  (`id`),
 639                                  KEY `md5key` (`md5key`)
 640                               ) TYPE=MyISAM COMMENT='For storing temporary copies of processed texts';");
 641      }
 642  
 643      if ($oldversion < 2004021000) {
 644          $textfilters = array();
 645          for ($i=1; $i<=10; $i++) {
 646              $variable = "textfilter$i";
 647              if (!empty($CFG->$variable)) {   /// No more filters
 648                  if (is_readable("$CFG->dirroot/".$CFG->$variable)) {
 649                      $textfilters[] = $CFG->$variable;
 650                  }
 651              }
 652          }
 653          $textfilters = implode(',', $textfilters);
 654          if (empty($textfilters)) {
 655              $textfilters = 'mod/glossary/dynalink.php';
 656          }
 657          set_config('textfilters', $textfilters);
 658      }
 659  
 660      if ($oldversion < 2004021201) {
 661          modify_database("", "CREATE TABLE `prefix_cache_filters` (
 662                                  `id` int(10) unsigned NOT NULL auto_increment,
 663                                  `filter` varchar(32) NOT NULL default '',
 664                                  `version` int(10) unsigned NOT NULL default '0',
 665                                  `md5key` varchar(32) NOT NULL default '',
 666                                  `rawtext` text NOT NULL,
 667                                  `timemodified` int(10) unsigned NOT NULL default '0',
 668                                  PRIMARY KEY  (`id`),
 669                                  KEY `filtermd5key` (filter,md5key)
 670                                ) TYPE=MyISAM COMMENT='For keeping information about cached data';");
 671      }
 672  
 673      if ($oldversion < 2004021500) {
 674          table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
 675      }
 676  
 677      if ($oldversion < 2004021700) {
 678          if (!empty($CFG->textfilters)) {
 679              $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
 680              $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
 681              $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
 682              $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
 683              $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
 684              $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
 685              set_config("textfilters", $CFG->textfilters);
 686          }
 687      }
 688  
 689      if ($oldversion < 2004022000) {
 690          table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
 691      }
 692  
 693      if ($oldversion < 2004022200) {     /// Final renaming I hope.  :-)
 694          if (!empty($CFG->textfilters)) {
 695              $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
 696              $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
 697              $textfilters = explode(',', $CFG->textfilters);
 698              foreach ($textfilters as $key => $textfilter) {
 699                  $textfilters[$key] = trim($textfilter);
 700              }
 701              set_config("textfilters", implode(',',$textfilters));
 702          }
 703      }
 704  
 705      if ($oldversion < 2004030702) {     /// Because of the renaming of Czech language pack
 706          execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
 707          execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
 708      }
 709  
 710      if ($oldversion < 2004041800) {     /// Integrate Block System from contrib
 711          table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
 712      }
 713  
 714      if ($oldversion < 2004042600) {     /// Rebuild course caches for resource icons
 715          //include_once("$CFG->dirroot/course/lib.php");
 716          //rebuild_course_cache();
 717      }
 718  
 719      if ($oldversion < 2004042700) {     /// Increase size of lang fields
 720          table_column("user",   "lang", "lang", "varchar", "10", "", "en");
 721          table_column("groups", "lang", "lang", "varchar", "10", "", "");
 722          table_column("course", "lang", "lang", "varchar", "10", "", "");
 723      }
 724  
 725      if ($oldversion < 2004042701) {     /// Add hiddentopics field to control hidden topics behaviour
 726          table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
 727      }
 728  
 729      if ($oldversion < 2004042702) {     /// add a format field for the description
 730          table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
 731      }
 732  
 733      if ($oldversion < 2004042900) {
 734          execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP `showrecent` ");
 735      }
 736  
 737      if ($oldversion < 2004043001) {     /// Change hiddentopics to hiddensections
 738          table_column("course", "hiddentopics", "hiddensections", "integer", "2", "unsigned", "0", "not null");
 739      }
 740  
 741      if ($oldversion < 2004050400) {     /// add a visible field for events
 742          table_column("event", "", "visible", "tinyint", "1", "", "1", "not null", "timeduration");
 743          if ($events = get_records('event')) {
 744              foreach($events as $event) {
 745                  if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
 746                      if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
 747                          set_field('event', 'visible', 0, 'id', $event->id);
 748                      }
 749                  }
 750              }
 751          }
 752      }
 753  
 754      if ($oldversion < 2004052800) {     /// First version tagged "1.4 development", version.php 1.227
 755          set_config('siteblocksadded', true);   /// This will be used later by the block upgrade
 756      }
 757  
 758      if ($oldversion < 2004053000) {     /// set defaults for site course
 759          $site = get_site();
 760          set_field('course', 'numsections', 0, 'id', $site->id);
 761          set_field('course', 'groupmodeforce', 1, 'id', $site->id);
 762          set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
 763          set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
 764          set_field('course', 'student', get_string('user'), 'id', $site->id);
 765          set_field('course', 'students', get_string('users'), 'id', $site->id);
 766      }
 767  
 768      if ($oldversion < 2004060100) {
 769          set_config('digestmailtime', 0);
 770          table_column('user', "", 'maildigest', 'tinyint', '1', '', '0', 'not null', 'mailformat');
 771      }
 772  
 773      if ($oldversion < 2004062400) {
 774          table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
 775          table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
 776      }
 777  
 778      if ($oldversion < 2004062401) {
 779          table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
 780          execute_sql('UPDATE '.$CFG->prefix.'course SET idnumber = shortname');   // By default
 781      }
 782  
 783      if ($oldversion < 2004062600) {
 784          table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
 785      }
 786  
 787      if ($oldversion < 2004072900) {
 788          table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
 789      }
 790  
 791      if ($oldversion < 2004072901) {  // Fixing error in schema
 792          if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
 793              delete_records('log_display', 'module', 'course', 'action', 'update');
 794              insert_record('log_display', $record, false);
 795          }
 796      }
 797  
 798      if ($oldversion < 2004081200) {  // Fixing version errors in some blocks
 799          set_field('blocks', 'version', 2004081200, 'name', 'admin');
 800          set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
 801          set_field('blocks', 'version', 2004081200, 'name', 'course_list');
 802      }
 803  
 804      if ($oldversion < 2004081500) {  // Adding new "auth" field to user table to allow more flexibility
 805          table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
 806  
 807          execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");  // Set everyone to 'manual' to be sure
 808  
 809          if ($admins = get_admins()) {   // Set all the NON-admins to whatever the current auth module is
 810              $adminlist = array();
 811              foreach ($admins as $user) {
 812                  $adminlist[] = $user->id; 
 813              }
 814              $adminlist = implode(',', $adminlist);
 815              execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE id NOT IN ($adminlist)");
 816          }
 817      }
 818      
 819      if ($oldversion < 2004082200) { // Making admins teachers on site course
 820          $site = get_site();
 821          $admins = get_admins();
 822          foreach ($admins as $admin) {
 823              add_teacher($admin->id, $site->id);
 824          }
 825      }
 826  
 827      if ($oldversion < 2004082600) {
 828          //update auth-fields for external users
 829          // following code would not work in 1.8
 830  /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
 831          if (function_exists('auth_get_userlist')) {
 832              $externalusers = auth_get_userlist();
 833              if (!empty($externalusers)){
 834                  $externalusers = '\''. implode('\',\'',$externalusers).'\'';
 835                  execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
 836              }
 837          }*/
 838      }
 839  
 840      if ($oldversion < 2004082900) {  // Make sure guest is "manual" too.
 841          set_field('user', 'auth', 'manual', 'username', 'guest');
 842      }
 843      
 844      /* Commented out unused guid-field code
 845      if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
 846          table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
 847          execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX authguid (auth, guid)");
 848      }
 849      */
 850  
 851      if ($oldversion < 2004091900) { // modify idnumber to hold longer values
 852          table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
 853          execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_idnumber",false); // added in case of conflicts with upgrade from 14stable
 854          execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_auth",false); // added in case of conflicts with upgrade from 14stable
 855  
 856          execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX idnumber (idnumber)");
 857          execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX auth (auth)");
 858      }
 859  
 860      if ($oldversion < 2004093001) { // add new table for sessions storage
 861          execute_sql(" CREATE TABLE `{$CFG->prefix}sessions` (
 862                            `sesskey` char(32) NOT null,
 863                            `expiry` int(11) unsigned NOT null,
 864                            `expireref` varchar(64),
 865                            `data` text NOT null,
 866                            PRIMARY KEY (`sesskey`), 
 867                            KEY (`expiry`) 
 868                        ) TYPE=MyISAM COMMENT='Optional database session storage, not used by default';");
 869      }
 870  
 871      if ($oldversion < 2004111500) {  // Update any users/courses using wrongly-named lang pack
 872          execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
 873          execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
 874      }
 875  
 876      if ($oldversion < 2004111700) { // add indexes. - drop them first silently to avoid conflicts when upgrading.
 877          execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX idnumber;",false);
 878          execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX shortname;",false);
 879          execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` DROP INDEX userid;",false);
 880          execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` DROP INDEX userid;",false);
 881  
 882          execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX idnumber (idnumber);");
 883          execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX shortname (shortname);");
 884          execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX userid (userid);");
 885          execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX userid (userid);");
 886      }
 887  
 888      if ($oldversion < 2004111700) {// add an index to event for timestart and timeduration. - drop them first silently to avoid conflicts when upgrading.
 889          execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timestart;",false);
 890          execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timeduration;",false); 
 891  
 892          modify_database('','ALTER TABLE prefix_event ADD INDEX timestart (timestart);');
 893          modify_database('','ALTER TABLE prefix_event ADD INDEX timeduration (timeduration);');
 894      }
 895  
 896      if ($oldversion < 2004111700) { //add indexes on modules and course_modules. - drop them first silently to avoid conflicts when upgrading.
 897          execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key visible;",false);
 898          execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key course;",false);
 899          execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key module;",false);
 900          execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key instance;",false);
 901          execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key deleted;",false);
 902          execute_sql("ALTER TABLE {$CFG->prefix}modules drop key name;",false);
 903  
 904          modify_database('','ALTER TABLE prefix_course_modules add key visible(visible);');
 905          modify_database('','ALTER TABLE prefix_course_modules add key course(course);');
 906          modify_database('','ALTER TABLE prefix_course_modules add key module(module);');
 907          modify_database('','ALTER TABLE prefix_course_modules add key instance (instance);');
 908          modify_database('','ALTER TABLE prefix_course_modules add key deleted (deleted);');
 909          modify_database('','ALTER TABLE prefix_modules add key name(name);');
 910      }
 911  
 912      if ($oldversion < 2004111700) { // add an index on the groups_members table. - drop them first silently to avoid conflicts when upgrading.
 913          execute_sql("ALTER TABLE {$CFG->prefix}groups_members DROP INDEX userid;",false);
 914  
 915          modify_database('','ALTER TABLE prefix_groups_members ADD INDEX userid (userid);');
 916      }
 917  
 918      if ($oldversion < 2004111700) { // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
 919          execute_sql("ALTER TABLE {$CFG->prefix}user_students DROP INDEX timeaccess;",false);
 920  
 921          modify_database('','ALTER TABLE prefix_user_students ADD INDEX timeaccess (timeaccess);');
 922      }
 923  
 924      if ($oldversion < 2004111700) {  // add indexes on faux-foreign keys. - drop them first silently to avoid conflicts when upgrading.
 925          execute_sql("ALTER TABLE {$CFG->prefix}scale DROP INDEX courseid;",false);
 926          execute_sql("ALTER TABLE {$CFG->prefix}user_admins DROP INDEX userid;",false);
 927          execute_sql("ALTER TABLE {$CFG->prefix}user_coursecreators DROP INDEX userid;",false);
 928  
 929          modify_database('','ALTER TABLE prefix_scale ADD INDEX courseid (courseid);');
 930          modify_database('','ALTER TABLE prefix_user_admins ADD INDEX userid (userid);');
 931          modify_database('','ALTER TABLE prefix_user_coursecreators ADD INDEX userid (userid);');
 932      }
 933  
 934      if ($oldversion < 2004111700) { // replace index on course
 935          fix_course_sortorder(0,0,1);
 936          execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category",false);
 937  
 938          execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category_sortorder;",false);
 939          modify_database('', "ALTER TABLE `prefix_course` ADD UNIQUE KEY category_sortorder(category,sortorder)"); 
 940  
 941          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;",false);
 942          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;",false);
 943          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;",false);
 944          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;",false);
 945          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;",false); 
 946          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;",false); 
 947          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;",false);
 948  
 949          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_deleted_idx  (deleted)");
 950          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_confirmed_idx (confirmed)");
 951          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_firstname_idx (firstname)");
 952          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastname_idx (lastname)");
 953          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_city_idx (city)");
 954          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_country_idx (country)");
 955          modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastaccess_idx (lastaccess)");
 956       }
 957   
 958      if ($oldversion < 2004111700) { // one more index for email (for sorting)
 959          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;",false);
 960          modify_database('','ALTER TABLE `prefix_user` ADD INDEX prefix_user_email_idx (email);');
 961      }
 962  
 963      if ($oldversion < 2004112200) { // new 'enrol' field for enrolment tables
 964          table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
 965          table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
 966          execute_sql("ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX enrol (enrol);");
 967          execute_sql("ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX enrol (enrol);");
 968      }
 969      
 970      if ($oldversion < 2004112400) {
 971          /// Delete duplicate enrolments 
 972          /// and then tell the database course,userid is a unique combination
 973          if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid ".
 974                                          "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
 975              foreach ($users as $user) {
 976                  delete_records_select("user_students", "userid = '$user->userid' ".
 977                                       "AND course = '$user->course' AND id <> '$user->id'");
 978              }
 979          }
 980          flush();
 981          
 982          modify_database('','ALTER TABLE prefix_user_students DROP INDEX courseuserid;');
 983          modify_database('','ALTER TABLE prefix_user_students ADD UNIQUE INDEX courseuserid(course,userid);');        
 984  
 985          /// Delete duplicate teacher enrolments 
 986          /// and then tell the database course,userid is a unique combination
 987          if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid ".
 988                                          "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
 989              foreach ($users as $user) {
 990                  delete_records_select("user_teachers", "userid = '$user->userid' ".
 991                                       "AND course = '$user->course' AND id <> '$user->id'");
 992              }
 993          }
 994          flush();
 995          modify_database('','ALTER TABLE prefix_user_teachers DROP INDEX courseuserid;');
 996          modify_database('','ALTER TABLE prefix_user_teachers ADD UNIQUE INDEX courseuserid(course,userid);');        
 997      } 
 998  
 999      if ($oldversion < 2004112900) {
1000          table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
1001      }
1002  
1003      if ($oldversion < 2004121400) {
1004          table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
1005      }
1006  
1007      if ($oldversion < 2004121500) {
1008          modify_database('',"CREATE TABLE prefix_dst_preset (
1009              id int(10) NOT NULL auto_increment,
1010              name char(48) default '' NOT NULL,
1011              
1012              apply_offset tinyint(3) default '0' NOT NULL,
1013              
1014              activate_index tinyint(1) default '1' NOT NULL,
1015              activate_day tinyint(1) default '1' NOT NULL,
1016              activate_month tinyint(2) default '1' NOT NULL,
1017              activate_time char(5) default '03:00' NOT NULL,
1018              
1019              deactivate_index tinyint(1) default '1' NOT NULL,
1020              deactivate_day tinyint(1) default '1' NOT NULL,
1021              deactivate_month tinyint(2) default '2' NOT NULL,
1022              deactivate_time char(5) default '03:00' NOT NULL,
1023              
1024              last_change int(10) default '0' NOT NULL,
1025              next_change int(10) default '0' NOT NULL,
1026              current_offset tinyint(3) default '0' NOT NULL,
1027              
1028              PRIMARY KEY (id))");
1029      }       
1030  
1031      if ($oldversion < 2004122800) {
1032          execute_sql("DROP TABLE {$CFG->prefix}message", false);
1033          execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
1034          execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
1035  
1036          modify_database('',"CREATE TABLE `prefix_message` (
1037                                 `id` int(10) unsigned NOT NULL auto_increment,
1038                                 `useridfrom` int(10) NOT NULL default '0',
1039                                 `useridto` int(10) NOT NULL default '0',
1040                                 `message` text NOT NULL,
1041                                 `timecreated` int(10) NOT NULL default '0',
1042                                 `messagetype` varchar(50) NOT NULL default '',
1043                                 PRIMARY KEY  (`id`),
1044                                 KEY `useridfrom` (`useridfrom`),
1045                                 KEY `useridto` (`useridto`)
1046                               ) TYPE=MyISAM COMMENT='Stores all unread messages';");
1047  
1048          modify_database('',"CREATE TABLE `prefix_message_read` (
1049                                 `id` int(10) unsigned NOT NULL auto_increment,
1050                                 `useridfrom` int(10) NOT NULL default '0',
1051                                 `useridto` int(10) NOT NULL default '0',
1052                                 `message` text NOT NULL,
1053                                 `timecreated` int(10) NOT NULL default '0',
1054                                 `timeread` int(10) NOT NULL default '0',
1055                                 `messagetype` varchar(50) NOT NULL default '',
1056                                 `mailed` tinyint(1) NOT NULL default '0',
1057                                 PRIMARY KEY  (`id`),
1058                                 KEY `useridfrom` (`useridfrom`),
1059                                 KEY `useridto` (`useridto`)
1060                               ) TYPE=MyISAM COMMENT='Stores all messages that have been read';");
1061  
1062          modify_database('',"CREATE TABLE `prefix_message_contacts` (
1063                                 `id` int(10) unsigned NOT NULL auto_increment,
1064                                 `userid` int(10) unsigned NOT NULL default '0',
1065                                 `contactid` int(10) unsigned NOT NULL default '0',
1066                                 `blocked` tinyint(1) unsigned NOT NULL default '0',
1067                                 PRIMARY KEY  (`id`),
1068                                 UNIQUE KEY `usercontact` (`userid`,`contactid`)
1069                               ) TYPE=MyISAM COMMENT='Maintains lists of relationships between users';");
1070  
1071          modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
1072          modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
1073      }
1074  
1075      if ($oldversion < 2004122801) {
1076          table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
1077          table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
1078      }
1079  
1080      if ($oldversion < 2005010100) {
1081          modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
1082          modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
1083          modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
1084          modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
1085      }
1086  
1087      if ($oldversion < 2005011000) {     // Create a .htaccess file in dataroot, just in case
1088          if (!file_exists($CFG->dataroot.'/.htaccess')) {
1089              if ($handle = fopen($CFG->dataroot.'/.htaccess', 'w')) {   // For safety
1090                  @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
1091                  @fclose($handle); 
1092                  notify("Created a default .htaccess file in $CFG->dataroot");
1093              }
1094          }
1095      }
1096      
1097  
1098      if ($oldversion < 2005012500) { 
1099          /*
1100          // add new table for meta courses.
1101          modify_database("","CREATE TABLE `prefix_meta_course` (
1102              `id` int(1) unsigned NOT NULL auto_increment,
1103              `parent_course` int(10) NOT NULL default 0,
1104              `child_course` int(10) NOT NULL default 0,
1105              PRIMARY KEY (`id`),
1106              KEY `parent_course` (parent_course),
1107              KEY `child_course` (child_course)
1108          );");
1109          // add flag to course field
1110          table_column('course','','meta_course','integer','1','','0','not null');
1111          */ // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
1112      }
1113  
1114      if ($oldversion < 2005012501) { 
1115          execute_sql("DROP TABLE {$CFG->prefix}meta_course",false); // drop silently
1116          execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course",false); // drop silently
1117          
1118          // add new table for meta courses.
1119          modify_database("","CREATE TABLE `prefix_course_meta` (
1120              `id` int(10) unsigned NOT NULL auto_increment,
1121              `parent_course` int(10) NOT NULL default 0,
1122              `child_course` int(10) NOT NULL default 0,
1123              PRIMARY KEY (`id`),
1124              KEY `parent_course` (parent_course),
1125              KEY `child_course` (child_course)
1126          );");
1127          // add flag to course field
1128          table_column('course','','metacourse','integer','1','','0','not null');
1129      }
1130  
1131      if ($oldversion < 2005012800) {
1132          // fix a typo (int 1 becomes int 10) 
1133          table_column('course_meta','id','id','integer','10','','0','not null');
1134      }
1135  
1136      if ($oldversion < 2005020100) {
1137          fix_course_sortorder(0, 1, 1);
1138      }   
1139  
1140  
1141      if ($oldversion < 2005020101) {
1142          // hopefully this is the LAST TIME we need to do this ;)
1143          if ($rows = count_records("course_meta")) {
1144              // we need to upgrade
1145              modify_database("","CREATE TABLE `prefix_course_meta_tmp` (
1146              `parent_course` int(10) NOT NULL default 0,
1147              `child_course` int(10) NOT NULL default 0);");
1148              
1149              execute_sql("INSERT INTO {$CFG->prefix}course_meta_tmp (parent_course,child_course) 
1150                 SELECT {$CFG->prefix}course_meta.parent_course, {$CFG->prefix}course_meta.child_course
1151                 FROM {$CFG->prefix}course_meta");
1152              $insertafter = true;
1153          }
1154  
1155          execute_sql("DROP TABLE {$CFG->prefix}course_meta");
1156  
1157          modify_database("","CREATE TABLE `prefix_course_meta` (
1158              `id` int(10) unsigned NOT NULL auto_increment,
1159              `parent_course` int(10) unsigned NOT NULL default 0,
1160              `child_course` int(10) unsigned NOT NULL default 0,
1161              PRIMARY KEY (`id`),
1162              KEY `parent_course` (parent_course),
1163              KEY `child_course` (child_course));");
1164  
1165          if (!empty($insertafter)) {
1166              execute_sql("INSERT INTO {$CFG->prefix}course_meta (parent_course,child_course) 
1167                 SELECT {$CFG->prefix}course_meta_tmp.parent_course, {$CFG->prefix}course_meta_tmp.child_course
1168                 FROM {$CFG->prefix}course_meta_tmp");
1169  
1170              execute_sql("DROP TABLE {$CFG->prefix}course_meta_tmp");
1171          }
1172      }
1173  
1174      if ($oldversion < 2005020800) {     // Expand module column to max 20 chars
1175          table_column('log','module','module','varchar','20','','','not null');
1176      }
1177  
1178      if ($oldversion < 2005021000) {     // New fields for theme choices
1179          table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
1180          table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
1181          table_column('user',   '', 'theme', 'varchar', '50', '', '', '', 'lang');
1182  
1183          set_config('theme', 'standardwhite');         // Reset to a known good theme 
1184      }
1185      
1186      if ($oldversion < 2005021600) {     // course.idnumber should be varchar(100)
1187          table_column('course', 'idnumber', 'idnumber', 'varchar', '100', '', '', '', '');
1188      }
1189  
1190      if ($oldversion < 2005021700) {
1191          table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
1192      }
1193  
1194      if ($oldversion < 2005021800) {     // For database debugging, not for normal use
1195          modify_database(""," CREATE TABLE `adodb_logsql` (
1196                                 `created` datetime NOT NULL,
1197                                 `sql0` varchar(250) NOT NULL,
1198                                 `sql1` text NOT NULL,
1199                                 `params` text NOT NULL,
1200                                 `tracer` text NOT NULL,
1201                                 `timer` decimal(16,6) NOT NULL
1202                                );");
1203      }
1204  
1205      if ($oldversion < 2005022400) {
1206          // Add more visible digits to the fields
1207          table_column('dst_preset', 'activate_index', 'activate_index', 'tinyint', '2', '', '0', 'not null');
1208          table_column('dst_preset', 'activate_day', 'activate_day', 'tinyint', '2', '', '0', 'not null');
1209          // Add family and year fields
1210          table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
1211          table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
1212      }
1213  
1214      if ($oldversion < 2005030501) {
1215          table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
1216          table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
1217          table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
1218          table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
1219      }
1220  
1221      if ($oldversion < 2005032300) {
1222          table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
1223          execute_sql('UPDATE `'.$CFG->prefix.'user` SET timezonename = \'\'');
1224      }
1225  
1226      if ($oldversion < 2005032600) {
1227          execute_sql('DROP TABLE '.$CFG->prefix.'dst_preset', false);
1228          modify_database('',"CREATE TABLE `prefix_timezone` (
1229                                `id` int(10) NOT NULL auto_increment,
1230                                `name` varchar(100) NOT NULL default '',
1231                                `year` int(11) NOT NULL default '0',
1232                                `rule` varchar(20) NOT NULL default '',
1233                                `gmtoff` int(11) NOT NULL default '0',
1234                                `dstoff` int(11) NOT NULL default '0',
1235                                `dst_month` tinyint(2) NOT NULL default '0',
1236                                `dst_startday` tinyint(3) NOT NULL default '0',
1237                                `dst_weekday` tinyint(3) NOT NULL default '0',
1238                                `dst_skipweeks` tinyint(3) NOT NULL default '0',
1239                                `dst_time` varchar(5) NOT NULL default '00:00',
1240                                `std_month` tinyint(2) NOT NULL default '0',
1241                                `std_startday` tinyint(3) NOT NULL default '0',
1242                                `std_weekday` tinyint(3) NOT NULL default '0',
1243                                `std_skipweeks` tinyint(3) NOT NULL default '0',
1244                                `std_time` varchar(5) NOT NULL default '00:00',
1245                                PRIMARY KEY (`id`)
1246                              ) TYPE=MyISAM COMMENT='Rules for calculating local wall clock time for users';");
1247      }
1248  
1249      if ($oldversion < 2005032800) {
1250          execute_sql("CREATE TABLE `{$CFG->prefix}grade_category` (
1251              `id` int(10) unsigned NOT NULL auto_increment,
1252              `name` varchar(64) NOT NULL default '',
1253              `courseid` int(10) unsigned NOT NULL default '0',
1254              `drop_x_lowest` int(10) unsigned NOT NULL default '0',
1255              `bonus_points` int(10) unsigned NOT NULL default '0',
1256              `hidden` int(10) unsigned NOT NULL default '0',
1257              `weight` decimal(4,2) NOT NULL default '0.00',
1258              PRIMARY KEY  (`id`),
1259              KEY `courseid` (`courseid`)
1260            ) TYPE=MyISAM ;");
1261  
1262          execute_sql("CREATE TABLE `{$CFG->prefix}grade_exceptions` (
1263              `id` int(10) unsigned NOT NULL auto_increment,
1264              `courseid` int(10) unsigned NOT NULL default '0',
1265              `grade_itemid` int(10) unsigned NOT NULL default '0',
1266              `userid` int(10) unsigned NOT NULL default '0',
1267              PRIMARY KEY  (`id`),
1268              KEY `courseid` (`courseid`)
1269            ) TYPE=MyISAM ;");
1270  
1271  
1272          execute_sql("CREATE TABLE `{$CFG->prefix}grade_item` (
1273              `id` int(10) unsigned NOT NULL auto_increment,
1274              `courseid` int(10) unsigned NOT NULL default '0',
1275              `category` int(10) unsigned NOT NULL default '0',
1276              `modid` int(10) unsigned NOT NULL default '0',
1277              `cminstance` int(10) unsigned NOT NULL default '0',
1278              `scale_grade` float(11,10) default '1.0000000000',
1279              `extra_credit` int(10) unsigned NOT NULL default '0',
1280              `sort_order` int(10) unsigned NOT NULL default '0',
1281              PRIMARY KEY  (`id`),
1282              KEY `courseid` (`courseid`)
1283            ) TYPE=MyISAM ;");
1284  
1285  
1286          execute_sql("CREATE TABLE `{$CFG->prefix}grade_letter` (
1287              `id` int(10) unsigned NOT NULL auto_increment,
1288              `courseid` int(10) unsigned NOT NULL default '0',
1289              `letter` varchar(8) NOT NULL default 'NA',
1290              `grade_high` decimal(4,2) NOT NULL default '100.00',
1291              `grade_low` decimal(4,2) NOT NULL default '0.00',
1292              PRIMARY KEY  (`id`),
1293              KEY `courseid` (`courseid`)
1294            ) TYPE=MyISAM ;");
1295            
1296  
1297          execute_sql("CREATE TABLE `{$CFG->prefix}grade_preferences` (
1298              `id` int(10) unsigned NOT NULL auto_increment,
1299              `courseid` int(10) unsigned NOT NULL default '0',
1300              `preference` int(10) NOT NULL default '0',
1301              `value` int(10) NOT NULL default '0',
1302              PRIMARY KEY  (`id`),
1303              UNIQUE KEY `courseidpreference` (`courseid`,`preference`)
1304            ) TYPE=MyISAM ;");
1305            
1306      }
1307  
1308      if ($oldversion < 2005033100) {   // Get rid of defunct field from course modules table
1309           delete_records('course_modules', 'deleted', 1);  // Delete old records we don't need any more
1310           execute_sql('ALTER TABLE `'.$CFG->prefix.'course_modules` DROP INDEX `deleted`');  // Old index
1311           execute_sql('ALTER TABLE `'.$CFG->prefix.'course_modules` DROP `deleted`');    // Old field
1312      }
1313  
1314      if ($oldversion < 2005040800) {
1315          table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
1316          execute_sql(" ALTER TABLE `{$CFG->prefix}user` DROP `timezonename` ");
1317      }
1318      
1319      if ($oldversion < 2005041101) {
1320          require_once($CFG->libdir.'/filelib.php');
1321          if (is_readable($CFG->dirroot.'/lib/timezones.txt')) {  // Distribution file
1322              if ($timezones = get_records_csv($CFG->dirroot.'/lib/timezones.txt', 'timezone')) {
1323                  $db->debug = false;
1324                  update_timezone_records($timezones);
1325                  notify(count($timezones).' timezones installed');
1326                  $db->debug = true;
1327              }
1328          }
1329      }
1330  
1331      if ($oldversion < 2005041900) {  // Copy all Dialogue entries into Messages, and hide Dialogue module
1332  
1333          if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
1334                                            FROM '.$CFG->prefix.'dialogue_conversations c,
1335                                                 '.$CFG->prefix.'dialogue_entries e
1336                                           WHERE e.conversationid = c.id')) {
1337              foreach ($entries as $entry) {
1338                  $message = new object;
1339                  $message->useridfrom    = $entry->userid;
1340                  $message->useridto      = $entry->recipientid;
1341                  $message->message       = addslashes($entry->text);
1342                  $message->format        = FORMAT_HTML;
1343                  $message->timecreated   = $entry->timecreated;
1344                  $message->messagetype   = 'direct';
1345              
1346                  insert_record('message_read', $message);
1347              }
1348          }
1349  
1350          set_field('modules', 'visible', 0, 'name', 'dialogue');
1351  
1352          notify('The Dialogue module has been disabled, and all the old Messages from it copied into the new standard Message feature.  If you really want Dialogue back, you can enable it using the "eye" icon here:  Admin >> Modules >> Dialogue');
1353  
1354      }
1355  
1356      if ($oldversion < 2005042100) {
1357          $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
1358      }
1359  
1360      if ($oldversion < 2005042400) {  // Add user tracking prefs field.
1361          table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
1362      }
1363  
1364      if ($oldversion < 2005053000 ) { // Add config_plugins table
1365          
1366          // this table was created on the MOODLE_15_STABLE branch
1367          // so it may already exist.
1368          $result = execute_sql("CREATE TABLE IF NOT EXISTS `{$CFG->prefix}config_plugins` (
1369                                    `id`         int(10) unsigned NOT NULL auto_increment,
1370                                    `plugin`     varchar(100) NOT NULL default 'core',
1371                                    `name`       varchar(100) NOT NULL default '',
1372                                    `value`      text NOT NULL default '',
1373                                    PRIMARY KEY  (`id`),
1374                                             UNIQUE KEY `plugin_name` (`plugin`, `name`)
1375                                    ) TYPE=MyISAM 
1376                                    COMMENT='Moodle modules and plugins configuration variables';");
1377      }
1378  
1379      if ($oldversion < 2005060200) {  // migrate some config items to config_plugins table
1380  
1381          // NOTE: this block is in both postgres AND mysql upgrade
1382          // files. If you edit either, update the otherone. 
1383          $user_fields = array("firstname", "lastname", "email", 
1384                               "phone1", "phone2", "department", 
1385                               "address", "city", "country", 
1386                               "description", "idnumber", "lang");
1387          if (!empty($CFG->auth)) { // if we have no auth, just pass
1388              foreach ($user_fields as $field) {
1389                  $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
1390                  foreach ($suffixes as $suffix) {
1391                      $key = 'auth_user_' . $field . $suffix;
1392                      if (isset($CFG->$key)) {
1393                          
1394                          // translate keys & values
1395                          // to the new convention
1396                          // this should support upgrading 
1397                          // even 1.5dev installs
1398                          $newkey = $key;
1399                          $newval = $CFG->$key;
1400                          if ($suffix === '') {
1401                              $newkey = 'field_map_' . $field;
1402                          } elseif ($suffix === '_editlock') {
1403                              $newkey = 'field_lock_' . $field;
1404                              $newval = ($newval==1) ? 'locked' : 'unlocked'; // translate 0/1 to locked/unlocked
1405                          } elseif ($suffix === '_updateremote') {
1406                              $newkey = 'field_updateremote_' . $field;                            
1407                          } elseif ($suffix === '_updatelocal') {
1408                              $newkey = 'field_updatelocal_' . $field;
1409                              $newval = ($newval==1) ? 'onlogin' : 'oncreate'; // translate 0/1 to locked/unlocked
1410                          }
1411  
1412                          if (!(set_config($newkey, addslashes($newval), 'auth/'.$CFG->auth)
1413                              && delete_records('config', 'name', $key))) {
1414                              notify("Error updating Auth configuration $key to {$CFG->auth} $newkey .");
1415                              $result = false;
1416                          }
1417                      } // end if isset key
1418                  } // end foreach suffix
1419              } // end foreach field
1420          }
1421      }
1422  
1423      if ($oldversion < 2005060201) {  // Close down the Attendance module, we are removing it from CVS.
1424          if (!file_exists($CFG->dirroot.'/mod/attendance/lib.php')) {
1425              if (count_records('attendance')) {   // We have some data, so should keep it
1426  
1427                  set_field('modules', 'visible', 0, 'name', 'attendance');
1428                  notify('The Attendance module has been discontinued.  If you really want to 
1429                          continue using it, you should download it individually from 
1430                          http://download.moodle.org/modules and install it, then 
1431                          reactivate it from Admin >> Configuration >> Modules.  
1432                          None of your existing data has been deleted, so all existing 
1433                          Attendance activities should re-appear.');
1434  
1435              } else {  // No data, so do a complete delete
1436  
1437                  execute_sql('DROP TABLE '.$CFG->prefix.'attendance', false);
1438                  delete_records('modules', 'name', 'attendance');
1439                  notify("The Attendance module has been discontinued and removed from your site.  
1440                          You weren't using it anyway.  ;-)");
1441              }
1442          }
1443      }
1444  
1445      if ($oldversion < 2005071700) {  // Close down the Dialogue module, we are removing it from CVS.
1446          if (!file_exists($CFG->dirroot.'/mod/dialogue/lib.php')) {
1447              if (count_records('dialogue')) {   // We have some data, so should keep it
1448  
1449                  set_field('modules', 'visible', 0, 'name', 'dialogue');
1450                  notify('The Dialogue module has been discontinued.  If you really want to 
1451                          continue using it, you should download it individually from 
1452                          http://download.moodle.org/modules and install it, then 
1453                          reactivate it from Admin >> Configuration >> Modules.  
1454                          None of your existing data has been deleted, so all existing 
1455                          Dialogue activities should re-appear.');
1456  
1457              } else {  // No data, so do a complete delete
1458  
1459                  execute_sql('DROP TABLE '.$CFG->prefix.'dialogue', false);
1460                  delete_records('modules', 'name', 'dialogue');
1461                  notify("The Dialogue module has been discontinued and removed from your site.  
1462                          You weren't using it anyway.  ;-)");
1463              }
1464          }
1465      }
1466  
1467      if ($oldversion < 2005072000) {  // Add a couple fields to mdl_event to work towards iCal import/export
1468          table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
1469          table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
1470      }
1471  
1472      if ($oldversion < 2005072100) { // run the online assignment cleanup code
1473          include($CFG->dirroot.'/'.$CFG->admin.'/oacleanup.php');
1474          if (function_exists('online_assignment_cleanup')) {
1475              online_assignment_cleanup();
1476          }
1477      }
1478  
1479      if ($oldversion < 2005072200) { // fix the mistakenly-added currency stuff from enrol/authorize
1480          execute_sql("DROP TABLE {$CFG->prefix}currencies", false); // drop silently
1481          execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
1482          $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
1483          table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
1484      }
1485  
1486      if ($oldversion < 2005081600) { //set up the course requests table
1487          modify_database('',"CREATE TABLE `prefix_course_request`  (
1488            `id` int(10) unsigned NOT NULL auto_increment,
1489            `fullname` varchar(254) NOT NULL default '',
1490            `shortname` varchar(15) NOT NULL default '',
1491            `summary` text NOT NULL,
1492            `reason` text NOT NULL,
1493            `requester` int(10) NOT NULL default 0,
1494            PRIMARY KEY (`id`),
1495            KEY `shortname` (`shortname`)
1496          ) TYPE=MyISAM;");
1497          
1498          table_column('course','','requested');
1499      }
1500  
1501      if ($oldversion < 2005081601) {
1502          modify_database('',"CREATE TABLE `prefix_course_allowed_modules` (
1503           `id` int(10) unsigned NOT NULL auto_increment,
1504           `course` int(10) unsigned NOT NULL default 0,
1505           `module` int(10) unsigned NOT NULL default 0,
1506           PRIMARY KEY (`id`),
1507           KEY `course` (`course`),
1508           KEY `module` (`module`)
1509        ) TYPE=MyISAM;");
1510          
1511          table_column('course','','restrictmodules','int','1','','0','not null');
1512      }
1513  
1514      if ($oldversion < 2005081700) {
1515          table_column('course_categories','','depth','integer');
1516          table_column('course_categories','','path','varchar','255');
1517      }
1518  
1519      if ($oldversion < 2005090100) {
1520          modify_database("","CREATE TABLE `prefix_stats_daily` (
1521            `id` int(10) unsigned NOT NULL auto_increment,
1522            `courseid` int(10) unsigned NOT NULL default 0,
1523            `timeend` int(10) unsigned NOT NULL default 0,
1524            `students` int(10) unsigned NOT NULL default 0,
1525            `teachers` int(10) unsigned NOT NULL default 0,
1526            `activestudents` int(10) unsigned NOT NULL default 0,
1527            `activeteachers` int(10) unsigned NOT NULL default 0,
1528            `studentreads` int(10) unsigned NOT NULL default 0,
1529            `studentwrites` int(10) unsigned NOT NULL default 0,
1530            `teacherreads` int(10) unsigned NOT NULL default 0,
1531            `teacherwrites` int(10) unsigned NOT NULL default 0,
1532            `logins` int(10) unsigned NOT NULL default 0,
1533            `uniquelogins` int(10) unsigned NOT NULL default 0,
1534            PRIMARY KEY (`id`),
1535            KEY `courseid` (`courseid`),
1536            KEY `timeend` (`timeend`)
1537         );");
1538  
1539          modify_database("","CREATE TABLE prefix_stats_weekly (
1540            `id` int(10) unsigned NOT NULL auto_increment,
1541            `courseid` int(10) unsigned NOT NULL default 0,
1542            `timeend` int(10) unsigned NOT NULL default 0,
1543            `students` int(10) unsigned NOT NULL default 0,
1544            `teachers` int(10) unsigned NOT NULL default 0,
1545            `activestudents` int(10) unsigned NOT NULL default 0,
1546            `activeteachers` int(10) unsigned NOT NULL default 0,
1547            `studentreads` int(10) unsigned NOT NULL default 0,
1548            `studentwrites` int(10) unsigned NOT NULL default 0,
1549            `teacherreads` int(10) unsigned NOT NULL default 0,
1550            `teacherwrites` int(10) unsigned NOT NULL default 0,
1551            `logins` int(10) unsigned NOT NULL default 0,
1552            `uniquelogins` int(10) unsigned NOT NULL default 0,
1553            PRIMARY KEY (`id`),
1554            KEY `courseid` (`courseid`),
1555            KEY `timeend` (`timeend`)
1556         );");
1557  
1558          modify_database("","CREATE TABLE prefix_stats_monthly (
1559            `id` int(10) unsigned NOT NULL auto_increment,
1560            `courseid` int(10) unsigned NOT NULL default 0,
1561            `timeend` int(10) unsigned NOT NULL default 0,
1562            `students` int(10) unsigned NOT NULL default 0,
1563            `teachers` int(10) unsigned NOT NULL default 0,
1564            `activestudents` int(10) unsigned NOT NULL default 0,
1565            `activeteachers` int(10) unsigned NOT NULL default 0,
1566            `studentreads` int(10) unsigned NOT NULL default 0,
1567            `studentwrites` int(10) unsigned NOT NULL default 0,
1568            `teacherreads` int(10) unsigned NOT NULL default 0,
1569            `teacherwrites` int(10) unsigned NOT NULL default 0,
1570            `logins` int(10) unsigned NOT NULL default 0,
1571            `uniquelogins` int(10) unsigned NOT NULL default 0,
1572            PRIMARY KEY (`id`),
1573            KEY `courseid` (`courseid`),
1574            KEY `timeend` (`timeend`)
1575         );");
1576  
1577          modify_database("","CREATE TABLE prefix_stats_user_daily (
1578            `id` int(10) unsigned NOT NULL auto_increment,
1579            `courseid` int(10) unsigned NOT NULL default 0,
1580            `userid` int(10) unsigned NOT NULL default 0,
1581            `roleid` int(10) unsigned NOT NULL default 0,
1582            `timeend` int(10) unsigned NOT NULL default 0,
1583            `statsreads` int(10) unsigned NOT NULL default 0,
1584            `statswrites` int(10) unsigned NOT NULL default 0,
1585            `stattype` varchar(30) NOT NULL default '',
1586            PRIMARY KEY (`id`),
1587            KEY `courseid` (`courseid`),
1588            KEY `userid` (`userid`),
1589            KEY `roleid` (`roleid`),
1590            KEY `timeend` (`timeend`)
1591         );");
1592  
1593          modify_database("","CREATE TABLE prefix_stats_user_weekly (
1594            `id` int(10) unsigned NOT NULL auto_increment,
1595            `courseid` int(10) unsigned NOT NULL default 0,
1596            `userid` int(10) unsigned NOT NULL default 0,
1597            `roleid` int(10) unsigned NOT NULL default 0,
1598            `timeend` int(10) unsigned NOT NULL default 0,
1599            `statsreads` int(10) unsigned NOT NULL default 0,
1600            `statswrites` int(10) unsigned NOT NULL default 0,
1601            `stattype` varchar(30) NOT NULL default '',
1602            PRIMARY KEY (`id`),
1603            KEY `courseid` (`courseid`),
1604            KEY `userid` (`userid`),
1605            KEY `roleid` (`roleid`),
1606            KEY `timeend` (`timeend`)
1607         );");
1608  
1609          modify_database("","CREATE TABLE prefix_stats_user_monthly (
1610            `id` int(10) unsigned NOT NULL auto_increment,
1611            `courseid` int(10) unsigned NOT NULL default 0,
1612            `userid` int(10) unsigned NOT NULL default 0,
1613            `roleid` int(10) unsigned NOT NULL default 0,
1614            `timeend` int(10) unsigned NOT NULL default 0,
1615            `statsreads` int(10) unsigned NOT NULL default 0,
1616            `statswrites` int(10) unsigned NOT NULL default 0,
1617            `stattype` varchar(30) NOT NULL default '',
1618            PRIMARY KEY (`id`),
1619            KEY `courseid` (`courseid`),
1620            KEY `userid` (`userid`),
1621            KEY `roleid` (`roleid`),
1622            KEY `timeend` (`timeend`)
1623         );");
1624           
1625      }
1626  
1627      if ($oldversion < 2005100300) {
1628          table_column('course','','expirynotify','tinyint','1');
1629          table_column('course','','expirythreshold','int','10');
1630          table_column('course','','notifystudents','tinyint','1');
1631          $new = new stdClass();
1632          $new->name = 'lastexpirynotify';
1633          $new->value = 0;
1634          insert_record('config', $new);
1635      }
1636  
1637      if ($oldversion < 2005100400) {
1638          table_column('course','','enrollable','tinyint','1','unsigned','1');
1639          table_column('course','','enrolstartdate','int');
1640          table_column('course','','enrolenddate','int');
1641      }
1642  
1643      if ($oldversion < 2005101200) { // add enrolment key to course_request.
1644          table_column('course_request','','password','varchar',50);
1645      }
1646  
1647      if ($oldversion < 2006030800) { # add extra indexes to log (see bug #4112)
1648          modify_database('',"ALTER TABLE prefix_log ADD INDEX userid (userid);");
1649          modify_database('',"ALTER TABLE prefix_log ADD INDEX info (info);");
1650      }
1651  
1652      if ($oldversion < 2006030900) {
1653          table_column('course','','enrol','varchar','20','','');
1654  
1655          if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
1656              set_config('enrol_plugins_enabled', 'manual');
1657              set_config('enrol', 'manual');
1658          } else {
1659              set_config('enrol_plugins_enabled', 'manual,'.$CFG->enrol);
1660          }
1661  
1662          require_once("$CFG->dirroot/enrol/enrol.class.php");
1663          $defaultenrol = enrolment_factory::factory($CFG->enrol);
1664          if (!method_exists($defaultenrol, 'print_entry')) { // switch enrollable to off for all courses in this case
1665              modify_database('', 'UPDATE prefix_course SET enrollable = 0');
1666          }
1667  
1668          execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
1669          execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
1670  
1671      }
1672      
1673      if ($oldversion < 2006031000) {
1674  
1675          modify_database("","CREATE TABLE prefix_post (
1676            `id` int(10) unsigned NOT NULL auto_increment,
1677            `userid` int(10) unsigned NOT NULL default '0',
1678            `courseid` int(10) unsigned NOT NULL default'0',
1679            `groupid` int(10) unsigned NOT NULL default'0',
1680            `moduleid` int(10) unsigned NOT NULL default'0',
1681            `coursemoduleid` int(10) unsigned NOT NULL default'0',
1682            `subject` varchar(128) NOT NULL default '',
1683            `summary` longtext,
1684            `content` longtext,
1685            `uniquehash` varchar(128) NOT NULL default '',
1686            `rating` int(10) unsigned NOT NULL default'0',
1687            `format` int(10) unsigned NOT NULL default'0',
1688            `publishstate` enum('draft','site','public') NOT NULL default 'draft',
1689            `lastmodified` int(10) unsigned NOT NULL default '0',
1690            `created` int(10) unsigned NOT NULL default '0',
1691            PRIMARY KEY  (`id`),
1692            UNIQUE KEY `id_user_idx` (`id`, `userid`),
1693            KEY `post_lastmodified_idx` (`lastmodified`),
1694            KEY `post_subject_idx` (`subject`)
1695          ) TYPE=MyISAM  COMMENT='New moodle post table. Holds data posts such as forum entries or blog entries.';");
1696  
1697          modify_database("","CREATE TABLE prefix_tags (
1698            `id` int(10) unsigned NOT NULL auto_increment,
1699            `type` varchar(255) NOT NULL default 'official',
1700            `userid` int(10) unsigned NOT NULL default'0',
1701            `text` varchar(255) NOT NULL default '',
1702            PRIMARY KEY  (`id`)
1703          ) TYPE=MyISAM COMMENT ='tags structure for moodle.';");
1704  
1705          modify_database("","CREATE TABLE prefix_blog_tag_instance (
1706            `id` int(10) unsigned NOT NULL auto_increment,
1707            `entryid` int(10) unsigned NOT NULL default'0',
1708            `tagid` int(10) unsigned NOT NULL default'0',
1709            `groupid` int(10) unsigned NOT NULL default'0',
1710            `courseid` int(10) unsigned NOT NULL default'0',
1711            `userid` int(10) unsigned NOT NULL default'0',
1712            PRIMARY KEY  (`id`)
1713            ) TYPE=MyISAM COMMENT ='tag instance for blogs.';");
1714      }
1715  
1716      if ($oldversion < 2006031400) {
1717          require_once("$CFG->dirroot/enrol/enrol.class.php");
1718          $defaultenrol = enrolment_factory::factory($CFG->enrol);
1719          if (!method_exists($defaultenrol, 'print_entry')) {
1720              set_config('enrol', 'manual');
1721          }
1722      }
1723      
1724      if ($oldversion < 2006031600) {
1725          execute_sql(" ALTER TABLE `{$CFG->prefix}grade_category` CHANGE `weight` `weight` decimal(5,2) default '0.00';");
1726      }
1727  
1728      if ($oldversion < 2006032000) {
1729          table_column('post','','module','varchar','20','','','not null', 'id');
1730          modify_database('',"ALTER TABLE prefix_post ADD INDEX post_module_idx (module);");
1731          modify_database('',"UPDATE prefix_post SET module = 'blog';");
1732      }
1733  
1734      if ($oldversion < 2006032001) {
1735          table_column('blog_tag_instance','','timemodified','integer','10','unsigned','0','not null', 'userid');
1736          modify_database('',"ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_entryid_idx (entryid);");
1737          modify_database('',"ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_tagid_idx (tagid);");
1738          modify_database('',"UPDATE prefix_blog_tag_instance SET timemodified = '".time()."';");
1739      }
1740  
1741      if ($oldversion < 2006040500) { // Add an index to course_sections that was never upgraded (bug 5100)
1742          execute_sql(" CREATE INDEX coursesection ON {$CFG->prefix}course_sections (course,section) ", false);
1743      }
1744  
1745      /// change all the int(11) to int(10) for blogs and tags
1746  
1747      if ($oldversion < 2006041000) {
1748          table_column('post','id','id','integer','10','unsigned','0','not null');
1749          table_column('post','userid','userid','integer','10','unsigned','0','not null');
1750          table_column('post','courseid','courseid','integer','10','unsigned','0','not null');
1751          table_column('post','groupid','groupid','integer','10','unsigned','0','not null');
1752          table_column('post','moduleid','moduleid','integer','10','unsigned','0','not null');
1753          table_column('post','coursemoduleid','coursemoduleid','integer','10','unsigned','0','not null');
1754          table_column('post','rating','rating','integer','10','unsigned','0','not null');
1755          table_column('post','format','format','integer','10','unsigned','0','not null');
1756          table_column('tags','id','id','integer','10','unsigned','0','not null');
1757          table_column('tags','userid','userid','integer','10','unsigned','0','not null');
1758          table_column('blog_tag_instance','id','id','integer','10','unsigned','0','not null');
1759          table_column('blog_tag_instance','entryid','entryid','integer','10','unsigned','0','not null');
1760          table_column('blog_tag_instance','tagid','tagid','integer','10','unsigned','0','not null');
1761          table_column('blog_tag_instance','groupid','groupid','integer','10','unsigned','0','not null');
1762          table_column('blog_tag_instance','courseid','courseid','integer','10','unsigned','0','not null');
1763          table_column('blog_tag_instance','userid','userid','integer','10','unsigned','0','not null');
1764      }
1765  
1766      if ($oldversion < 2006041001) {
1767          table_column('cache_text','formattedtext','formattedtext','longblob','','','','not null');
1768      }
1769      
1770      if ($oldversion < 2006041100) {
1771          table_column('course_modules','','visibleold','integer','1','unsigned','1','not null', 'visible');
1772      }
1773      
1774      if ($oldversion < 2006041801) { // forgot auto_increments for ids
1775          modify_database('',"ALTER TABLE prefix_post CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
1776          modify_database('',"ALTER TABLE prefix_tags CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
1777          modify_database('',"ALTER TABLE prefix_blog_tag_instance CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
1778      }
1779      
1780      // changed user->firstname, user->lastname, course->shortname to varchar(100)
1781      
1782      if ($oldversion < 2006041900) {
1783          table_column('course','shortname','shortname','varchar','100','','','not null');
1784          table_column('user','firstname','firstname','varchar','100','','','not null');
1785          table_column('user','lastname','lastname','varchar','100','','','not null');
1786      }
1787      
1788      if ($oldversion < 2006042400) {
1789          // Look through table log_display and get rid of duplicates.
1790          $rs = get_recordset_sql('SELECT DISTINCT * FROM '.$CFG->prefix.'log_display');
1791          
1792          // Drop the log_display table and create it back with an id field.
1793          execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
1794          
1795          modify_database('', "CREATE TABLE prefix_log_display (
1796                                 `id` int(10) unsigned NOT NULL auto_increment,
1797                                 `module` varchar(30),
1798                                 `action` varchar(40),
1799                                 `mtable` varchar(30),
1800                                 `field` varchar(50),
1801                                 PRIMARY KEY (`id`)
1802                                 ) TYPE=MyISAM");
1803          
1804          // Add index to ensure that module and action combination is unique.
1805          modify_database('', "ALTER TABLE prefix_log_display ADD UNIQUE `moduleaction`(`module` , `action`)");
1806          
1807          // Insert the records back in, sans duplicates.
1808          if ($rs) {
1809              while (!$rs->EOF) {
1810                  $sql = "INSERT INTO {$CFG->prefix}log_display ".
1811                              "VALUES('', '".$rs->fields['module']."', ".
1812                              "'".$rs->fields['action']."', ".
1813                              "'".$rs->fields['mtable']."', ".
1814                              "'".$rs->fields['field']."')";
1815                  
1816                  execute_sql($sql, false);
1817                  $rs->MoveNext();
1818              }
1819              rs_close($rs);
1820          }
1821      }
1822      
1823      // change tags->type to varchar(20), adding 2 indexes for tags table.
1824      if ($oldversion < 2006042401) {
1825          table_column('tags','type','type','varchar','20','','','not null');
1826          modify_database('',"ALTER TABLE prefix_tags ADD INDEX tags_typeuserid_idx (type(20), userid)");
1827          modify_database('',"ALTER TABLE prefix_tags ADD INDEX tags_text_idx(text(255))");
1828      }
1829      
1830      /***************************************************
1831       * The following is an effort to change all the    *
1832       * default NULLs to NOT NULL defaut '' in all      *
1833       * mysql tables, to prevent 5303 and be consistent *
1834       ***************************************************/
1835  
1836      if ($oldversion < 2006042800) {
1837  
1838          execute_sql("UPDATE {$CFG->prefix}grade_category SET name='' WHERE name IS NULL");
1839          table_column('grade_category','name','name','varchar','64','','','not null');
1840  
1841          execute_sql("UPDATE {$CFG->prefix}grade_category SET weight='0' WHERE weight IS NULL");
1842          execute_sql("ALTER TABLE {$CFG->prefix}grade_category change weight weight decimal(5,2) NOT NULL default 0.00");
1843          execute_sql("UPDATE {$CFG->prefix}grade_item SET courseid='0' WHERE courseid IS NULL");
1844          table_column('grade_item','courseid','courseid','int','10','unsigned','0','not null');
1845  
1846          execute_sql("UPDATE {$CFG->prefix}grade_item SET category='0' WHERE category IS NULL");
1847          table_column('grade_item','category','category','int','10','unsigned','0','not null');
1848  
1849          execute_sql("UPDATE {$CFG->prefix}grade_item SET modid='0' WHERE modid IS NULL");
1850          table_column('grade_item','modid','modid','int','10','unsigned','0','not null');
1851  
1852          execute_sql("UPDATE {$CFG->prefix}grade_item SET cminstance='0' WHERE cminstance IS NULL");
1853          table_column('grade_item','cminstance','cminstance','int','10','unsigned','0','not null');
1854  
1855          execute_sql("UPDATE {$CFG->prefix}grade_item SET scale_grade='0' WHERE scale_grade IS NULL");
1856          execute_sql("ALTER TABLE {$CFG->prefix}grade_item change scale_grade scale_grade float(11,10) NOT NULL default 1.0000000000");
1857          
1858          execute_sql("UPDATE {$CFG->prefix}grade_preferences SET courseid='0' WHERE courseid IS NULL");
1859          table_column('grade_preferences','courseid','courseid','int','10','unsigned','0','not null');
1860  
1861          execute_sql("UPDATE {$CFG->prefix}user SET idnumber='' WHERE idnumber IS NULL");
1862          table_column('user','idnumber','idnumber','varchar','64','','','not null');
1863  
1864          execute_sql("UPDATE {$CFG->prefix}user SET icq='' WHERE icq IS NULL");
1865          table_column('user','icq','icq','varchar','15','','','not null');
1866          
1867          execute_sql("UPDATE {$CFG->prefix}user SET skype='' WHERE skype IS NULL");
1868          table_column('user','skype','skype','varchar','50','','','not null');
1869          
1870          execute_sql("UPDATE {$CFG->prefix}user SET yahoo='' WHERE yahoo IS NULL");
1871          table_column('user','yahoo','yahoo','varchar','50','','','not null');
1872  
1873          execute_sql("UPDATE {$CFG->prefix}user SET aim='' WHERE aim IS NULL");
1874          table_column('user','aim','aim','varchar','50','','','not null');
1875  
1876          execute_sql("UPDATE {$CFG->prefix}user SET msn='' WHERE msn IS NULL");
1877          table_column('user','msn','msn','varchar','50','','','not null');
1878  
1879          execute_sql("UPDATE {$CFG->prefix}user SET phone1='' WHERE phone1 IS NULL");
1880          table_column('user','phone1','phone1','varchar','20','','','not null');
1881  
1882          execute_sql("UPDATE {$CFG->prefix}user SET phone2='' WHERE phone2 IS NULL");
1883          table_column('user','phone2','phone2','varchar','20','','','not null');
1884  
1885          execute_sql("UPDATE {$CFG->prefix}user SET institution='' WHERE institution IS NULL");
1886          table_column('user','institution','institution','varchar','40','','','not null');
1887  
1888          execute_sql("UPDATE {$CFG->prefix}user SET department='' WHERE department IS NULL");
1889          table_column('user','department','department','varchar','30','','','not null');
1890  
1891          execute_sql("UPDATE {$CFG->prefix}user SET address='' WHERE address IS NULL");
1892          table_column('user','address','address','varchar','70','','','not null');
1893          
1894          execute_sql("UPDATE {$CFG->prefix}user SET city='' WHERE city IS NULL");
1895          table_column('user','city','city','varchar','20','','','not null');
1896  
1897          execute_sql("UPDATE {$CFG->prefix}user SET country='' WHERE country IS NULL");
1898          table_column('user','country','country','char','2','','','not null');
1899  
1900          execute_sql("UPDATE {$CFG->prefix}user SET lang='' WHERE lang IS NULL");
1901          table_column('user','lang','lang','varchar','10','','en','not null');
1902  
1903          execute_sql("UPDATE {$CFG->prefix}user SET lastIP='' WHERE lastIP IS NULL");
1904          table_column('user','lastIP','lastIP','varchar','15','','','not null');
1905  
1906          execute_sql("UPDATE {$CFG->prefix}user SET secret='' WHERE secret IS NULL");
1907          table_column('user','secret','secret','varchar','15','','','not null');
1908  
1909          execute_sql("UPDATE {$CFG->prefix}user SET picture='0' WHERE picture IS NULL");
1910          table_column('user','picture','picture','tinyint','1','','0','not null');
1911  
1912          execute_sql("UPDATE {$CFG->prefix}user SET url='' WHERE url IS NULL");
1913          table_column('user','url','url','varchar','255','','','not null');
1914      }
1915      
1916      if ($oldversion < 2006050400) {
1917  
1918          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;",false);
1919          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;",false);
1920          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;",false);
1921          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;",false);
1922          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;",false);
1923          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;",false);
1924          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;",false);
1925          execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;",false);
1926  
1927          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_deleted (deleted)",false);
1928          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_confirmed (confirmed)",false);
1929          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_firstname (firstname)",false);
1930          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastname (lastname)",false);
1931          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_city (city)",false);
1932          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_country (country)",false);
1933          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastaccess (lastaccess)",false);
1934          execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_email (email)",false);
1935      }
1936      
1937      if ($oldversion < 2006050500) {
1938          table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
1939      }
1940  
1941      if ($oldversion < 2006050501) {
1942          table_column('sessions', 'data', 'data', 'mediumtext', '', '', '', 'not null');
1943      }
1944      
1945      // renaming of reads and writes for stats_user_xyz
1946      if ($oldversion < 2006052400) { // change this later
1947  
1948          // we are using this because we want silent updates
1949  
1950          execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
1951          execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
1952          execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
1953          execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
1954          execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
1955          execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
1956    
1957      }
1958  
1959      // Adding some missing log actions
1960      if ($oldversion < 2006060400) {
1961          // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
1962          if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
1963              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
1964          }
1965          if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
1966              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
1967          }
1968          if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
1969              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
1970          }
1971          if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
1972              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
1973          }
1974          if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
1975              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
1976          }
1977      }
1978  
1979      //Renaming lastIP to lastip (all fields lowercase)
1980      if ($oldversion < 2006060900) {
1981          //Only if it exists
1982          $fields = $db->MetaColumnNames($CFG->prefix.'user');
1983          if (in_array('lastIP',$fields)) {
1984              table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "not null", "currentlogin");
1985          }
1986      }
1987  
1988      // Change in MySQL 5.0.3 concerning how decimals are stored. Mimic from 16_STABLE
1989      // this isn't dangerous because it's a simple type change, but be careful with
1990      // versions and duplicate work in order to provide smooth upgrade paths.
1991      if ($oldversion < 2006071800) {
1992          table_column('grade_letter', 'grade_high', 'grade_high', 'decimal(5,2)', '', '', '100.00', 'not null', '');
1993          table_column('grade_letter', 'grade_low', 'grade_low', 'decimal(5,2)', '', '', '0.00', 'not null', '');
1994      }
1995      
1996      if ($oldversion < 2006080400) {
1997          execute_sql("CREATE TABLE {$CFG->prefix}role (
1998                                `id` int(10) unsigned NOT NULL auto_increment,
1999                                `name` varchar(255) NOT NULL default '',
2000                                `shortname` varchar(100) NOT NULL default '',
2001                                `description` text NOT NULL default '',
2002                                `sortorder` int(10) unsigned NOT NULL default '0',
2003                                PRIMARY KEY  (`id`)
2004                              )", true);
2005  
2006          execute_sql("CREATE TABLE {$CFG->prefix}context (
2007                                `id` int(10) unsigned NOT NULL auto_increment,
2008                                `level` int(10) unsigned NOT NULL default '0',
2009                                `instanceid` int(10) unsigned NOT NULL default '0',
2010                                PRIMARY KEY  (`id`)
2011                              )", true);
2012  
2013          execute_sql("CREATE TABLE {$CFG->prefix}role_assignments (
2014                                `id` int(10) unsigned NOT NULL auto_increment,
2015                                `roleid` int(10) unsigned NOT NULL default '0',
2016                                `contextid` int(10) unsigned NOT NULL default '0',
2017                                `userid` int(10) unsigned NOT NULL default '0',
2018                                `hidden` int(1) unsigned NOT NULL default '0',
2019                                `timestart` int(10) unsigned NOT NULL default '0',
2020                                `timeend` int(10) unsigned NOT NULL default '0',
2021                                `timemodified` int(10) unsigned NOT NULL default '0',
2022                                `modifierid` int(10) unsigned NOT NULL default '0',
2023                                `enrol` varchar(20) NOT NULL default '',
2024                                `sortorder` int(10) unsigned NOT NULL default '0',
2025                                PRIMARY KEY  (`id`)
2026                              )", true);
2027  
2028          execute_sql("CREATE TABLE {$CFG->prefix}role_capabilities (
2029                                `id` int(10) unsigned NOT NULL auto_increment,
2030                                `contextid` int(10) unsigned NOT NULL default '0',
2031                                `roleid` int(10) unsigned NOT NULL default '0',
2032                                `capability` varchar(255) NOT NULL default '',
2033                                `permission` int(10) unsigned NOT NULL default '0',
2034                                `timemodified` int(10) unsigned NOT NULL default '0',
2035                                `modifierid` int(10) unsigned NOT NULL default '0',
2036                                PRIMARY KEY (`id`)
2037                              )", true);
2038                              
2039          execute_sql("CREATE TABLE {$CFG->prefix}role_deny_grant (
2040                                `id` int(10) unsigned NOT NULL auto_increment,
2041                                `roleid` int(10) unsigned NOT NULL default '0',
2042                                `unviewableroleid` int(10) unsigned NOT NULL default '0',
2043                                PRIMARY KEY (`id`)
2044                              )", true);
2045                              
2046          execute_sql("CREATE TABLE {$CFG->prefix}capabilities ( 
2047                                `id` int(10) unsigned NOT NULL auto_increment, 
2048                                `name` varchar(255) NOT NULL default '', 
2049                                `captype` varchar(50) NOT NULL default '', 
2050                                `contextlevel` int(10) unsigned NOT NULL default '0', 
2051                                `component` varchar(100) NOT NULL default '', 
2052                                PRIMARY KEY (`id`) 
2053                              )", true);     
2054                              
2055          execute_sql("CREATE TABLE {$CFG->prefix}role_names ( 
2056                                `id` int(10) unsigned NOT NULL auto_increment, 
2057                                `roleid` int(10) unsigned NOT NULL default '0',
2058                                `contextid` int(10) unsigned NOT NULL default '0', 
2059                                `text` text NOT NULL default '',
2060                                PRIMARY KEY (`id`) 
2061                              )", true);                      
2062                          
2063      }
2064      
2065      if ($oldversion < 2006081000) {
2066        
2067          execute_sql("ALTER TABLE `{$CFG->prefix}role` ADD INDEX `sortorder` (`sortorder`)",true);
2068          
2069          execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD INDEX `instanceid` (`instanceid`)",true);
2070          execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `level-instanceid` (`level`, `instanceid`)",true);
2071  
2072          execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `roleid` (`roleid`)",true);
2073          execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `contextid` (`contextid`)",true);  
2074          execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `userid` (`userid`)",true);
2075          execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD UNIQUE INDEX `contextid-roleid-userid` (`contextid`, `roleid`, `userid`)",true);
2076          execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `sortorder` (`sortorder`)",true);
2077  
2078          execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `roleid` (`roleid`)",true);
2079          execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `contextid` (`contextid`)",true); 
2080          execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `modifierid` (`modifierid`)",true);                
2081          // MDL-10640  adding missing index from upgrade
2082          execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `capability` (`capability`)",true);   
2083          execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD UNIQUE INDEX `roleid-contextid-capability` (`roleid`, `contextid`, `capability`)",true);         
2084                          
2085          execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `roleid` (`roleid`)",true);
2086          execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `unviewableroleid` (`unviewableroleid`)",true);    
2087          execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD UNIQUE INDEX `roleid-unviewableroleid` (`roleid`, `unviewableroleid`)",true);         
2088         
2089          execute_sql("ALTER TABLE `{$CFG->prefix}capabilities` ADD UNIQUE INDEX `name` (`name`)",true); 
2090                               
2091          execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `roleid` (`roleid`)",true);                         
2092          execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `contextid` (`contextid`)",true); 
2093          execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD UNIQUE INDEX `roleid-contextid` (`roleid`, `contextid`)",true);                 
2094      }
2095      
2096      if ($oldversion < 2006081600) {
2097          execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` CHANGE permission permission int(10) NOT NULL default '0'",true);   
2098      }
2099      
2100      // drop role_deny_grant table, and create 2 new ones
2101      if ($oldversion < 2006081700) {
2102          execute_sql("DROP TABLE `{$CFG->prefix}role_deny_grant`", true);
2103          
2104          execute_sql("CREATE TABLE {$CFG->prefix}role_allow_assign (
2105                      `id` int(10) unsigned NOT NULL auto_increment,
2106                      `roleid` int(10) unsigned NOT NULL default '0',
2107                      `allowassign` int(10) unsigned NOT NULL default '0',
2108                      KEY `roleid` (`roleid`),
2109                      KEY `allowassign` (`allowassign`),
2110                      UNIQUE KEY `roleid-allowassign` (`roleid`, `allowassign`),
2111                      PRIMARY KEY (`id`)
2112                      )", true); 
2113                              
2114          execute_sql("CREATE TABLE {$CFG->prefix}role_allow_override (
2115                      `id` int(10) unsigned NOT NULL auto_increment,
2116                      `roleid` int(10) unsigned NOT NULL default '0',
2117                      `allowoverride` int(10) unsigned NOT NULL default '0',