[ Index ]

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

title

Body

[close]

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

   1  <?PHP  //$Id: postgres7.php,v 1.237.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  // This file is tailored to PostgreSQL 7
   8  
   9  function main_upgrade($oldversion=0) {
  10  
  11      global $CFG, $THEME, $db;
  12  
  13      $result = true;
  14  
  15  
  16      if ($oldversion < 2003010101) {
  17          delete_records("log_display", "module", "user");
  18          $new->module = "user";
  19          $new->action = "view";
  20          $new->mtable = "user";
  21          $new->field  = "CONCAT(firstname,\" \",lastname)";
  22          insert_record("log_display", $new);
  23  
  24          delete_records("log_display", "module", "course");
  25          $new->module = "course";
  26          $new->action = "view";
  27          $new->mtable = "course";
  28          $new->field  = "fullname";
  29          insert_record("log_display", $new);
  30          $new->action = "update";
  31          insert_record("log_display", $new);
  32          $new->action = "enrol";
  33          insert_record("log_display", $new);
  34      }
  35      
  36      //support user based course creating
  37      if ($oldversion < 2003032400) {
  38          execute_sql("CREATE TABLE {$CFG->prefix}user_coursecreators (
  39                                    id int8 SERIAL PRIMARY KEY,
  40                                    userid int8  NOT NULL default '0'
  41                                    )");
  42      }
  43  
  44      if ($oldversion < 2003041400) {
  45          table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
  46      }
  47  
  48      if ($oldversion < 2003042104) {  // Try to update permissions of all files
  49          if ($files = get_directory_list($CFG->dataroot)) {
  50              echo "Attempting to update permissions for all files... ignore any errors.";
  51              foreach ($files as $file) {
  52                  echo "$CFG->dataroot/$file<br />";
  53                  @chmod("$CFG->dataroot/$file", $CFG->directorypermissions);
  54              }
  55          }
  56      }
  57  
  58      if ($oldversion < 2003042400) {
  59      // Rebuild all course caches, because of changes to do with visible variable
  60          if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
  61              require_once("$CFG->dirroot/course/lib.php");
  62              foreach ($courses as $course) {
  63                  $modinfo = serialize(get_array_of_activities($course->id));
  64  
  65                  if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
  66                      notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
  67                  }
  68              }
  69          }
  70      }
  71  
  72      if ($oldversion < 2003042500) {                 
  73      //  Convert all usernames to lowercase.  
  74          $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user"); 
  75          $cerrors = "";
  76          $rarray = array();
  77  
  78          foreach ($users as $user) {      // Check for possible conflicts
  79              $lcname = trim(moodle_strtolower($user->username));
  80              if (in_array($lcname, $rarray)) {
  81                  $cerrors .= $user->id."->".$lcname.'<br/>' ; 
  82              } else {
  83                  array_push($rarray,$lcname);
  84              }
  85          }
  86  
  87          if ($cerrors != '') {
  88              notify("Error: Cannot convert usernames to lowercase. 
  89                      Following usernames would overlap (id->username):<br/> $cerrors . 
  90                      Please resolve overlapping errors."); 
  91              $result = false;
  92          }
  93  
  94          $cerrors = "";
  95          echo "Checking userdatabase:<br />";
  96          foreach ($users as $user) {
  97              $lcname = trim(moodle_strtolower($user->username));
  98              if ($lcname != $user->username) {
  99                  $convert = set_field("user" , "username" , $lcname, "id", $user->id);
 100                  if (!$convert) {
 101                      if ($cerrors){
 102                         $cerrors .= ", ";
 103                      }   
 104                      $cerrors .= $item;
 105                  } else {
 106                      echo ".";
 107                  }   
 108              }
 109          }
 110          if ($cerrors != '') {
 111              notify("There were errors when converting following usernames to lowercase. 
 112                     '$cerrors' . Sorry, but you will need to fix your database by hand.");
 113              $result = false;
 114          }
 115      }
 116  
 117      if ($oldversion < 2003042700) {
 118          /// Changing to multiple indexes
 119          execute_sql(" CREATE INDEX {$CFG->prefix}log_coursemoduleaction_idx ON {$CFG->prefix}log (course,module,action) ");
 120          execute_sql(" CREATE INDEX {$CFG->prefix}log_courseuserid_idx ON {$CFG->prefix}log (course,userid) ");
 121      }
 122  
 123      if ($oldversion < 2003042801) {
 124          execute_sql("CREATE TABLE {$CFG->prefix}course_display (
 125                           id SERIAL PRIMARY KEY,
 126                           course integer NOT NULL default '0',
 127                           userid integer NOT NULL default '0',
 128                           display integer NOT NULL default '0'
 129                        )");
 130  
 131          execute_sql("CREATE INDEX {$CFG->prefix}course_display_courseuserid_idx ON {$CFG->prefix}course_display (course,userid)");
 132      }
 133  
 134      if ($oldversion < 2003050400) {
 135          table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
 136      }
 137                                                              
 138      if ($oldversion < 2003050401) {
 139          table_column("user", "", "lang", "VARCHAR", "5", "", "$CFG->lang" ,"NOT NULL","");
 140      }
 141  
 142      if ($oldversion < 2003050900) {
 143          table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
 144      }
 145  
 146      if ($oldversion < 2003050902) {
 147          if (get_records("modules", "name", "pgassignment")) {
 148              print_simple_box("Note: the pgassignment module will soon be deleted from CVS!  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "$THEME->cellheading", "20", "noticebox");
 149          }
 150      }
 151  
 152      if ($oldversion < 2003051600) {
 153          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");
 154      }
 155  
 156      if ($oldversion < 2003052300) {
 157          table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
 158      }
 159  
 160      if ($oldversion < 2003072100) {
 161          table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
 162      }
 163  
 164      if ($oldversion < 2003072101) {
 165          table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
 166      }
 167  
 168      if ($oldversion < 2003072800) {
 169          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");
 170          flush();
 171          execute_sql(" CREATE INDEX {$CFG->prefix}log_timecoursemoduleaction_idx ON {$CFG->prefix}log (time,course,module,action) ");
 172          execute_sql(" CREATE INDEX {$CFG->prefix}user_students_courseuserid_idx ON {$CFG->prefix}user_students (course,userid) ");
 173          execute_sql(" CREATE INDEX {$CFG->prefix}user_teachers_courseuserid_idx ON {$CFG->prefix}user_teachers (course,userid) ");
 174      }
 175  
 176      if ($oldversion < 2003072802) {
 177          table_column("course_categories", "", "description", "text", "", "", "");
 178          table_column("course_categories", "", "parent", "integer", "10", "unsigned");
 179          table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
 180          table_column("course_categories", "", "courseorder", "text", "", "", "");
 181          table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
 182          table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
 183      }
 184  
 185      if ($oldversion < 2003080400) {
 186          notify("If the following command fails you may want to change the type manually, from TEXT to INTEGER.  Moodle should keep working even if you don't.");
 187          table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
 188          table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
 189      }
 190  
 191      if ($oldversion < 2003081502) {
 192          execute_sql(" CREATE TABLE {$CFG->prefix}scale (
 193                           id SERIAL PRIMARY KEY,
 194                           courseid integer NOT NULL default '0',
 195                           userid integer NOT NULL default '0',
 196                           name varchar(255) NOT NULL default '',
 197                           scale text,
 198                           description text,
 199                           timemodified integer NOT NULL default '0'
 200                        )");
 201      }
 202  
 203      if ($oldversion < 2003081503) {
 204          table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
 205          get_scales_menu(0);    // Just to force the default scale to be created
 206      }
 207  
 208      if ($oldversion < 2003081600) {
 209          table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
 210          table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
 211      }
 212  
 213      if ($oldversion < 2003081900) {
 214          table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
 215      }
 216  
 217      if ($oldversion < 2003080700) {
 218          notify("Cleaning up categories and course ordering...");
 219          fix_course_sortorder();
 220      }
 221  
 222  
 223      if ($oldversion < 2003082001) {
 224          table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
 225      }
 226  
 227      if ($oldversion < 2003082101) {
 228          execute_sql(" CREATE INDEX {$CFG->prefix}course_category_idx ON {$CFG->prefix}course (category) ");
 229      }
 230      if ($oldversion < 2003082702) {
 231          execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
 232      }
 233  
 234      if ($oldversion < 2003091000) {
 235          # Old field that was never added!
 236          table_column("course", "", "showrecent", "integer", "10", "unsigned", "1", "", "numsections");
 237      }
 238  
 239      if ($oldversion < 2003091400) {
 240          table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
 241      }
 242  
 243      if ($oldversion < 2003092900) {
 244          table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
 245      }
 246  
 247      if ($oldversion < 2003102700) {
 248          table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
 249          table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
 250  
 251          $db->debug = false;
 252          $CFG->debug = 0;
 253          notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
 254          flush();
 255  
 256          if ($courses = get_records_select("course", "category > 0")) {
 257              foreach ($courses as $course) {
 258                  notify("Processing " . format_string($course->fullname) . " ...", "green");
 259                  flush();
 260                  if ($users = get_records_select("user_teachers", "course = '$course->id'", 
 261                                                  "id", "id, userid, timeaccess")) {
 262                      foreach ($users as $user) {
 263                          $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '$course->id' and userid = '$user->userid'                                                               ORDER by time DESC");
 264                          if (empty($loginfo->time)) {
 265                              $loginfo->time = 0;
 266                          }
 267                          execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '$loginfo->time' 
 268                                       WHERE userid = '$user->userid' AND course = '$course->id'", false);
 269                          
 270                      }
 271                  }
 272  
 273                  if ($users = get_records_select("user_students", "course = '$course->id'", 
 274                                                  "id", "id, userid, timeaccess")) {
 275                      foreach ($users as $user) {
 276                          $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log 
 277                                                     WHERE course = '$course->id' and userid = '$user->userid' 
 278                                                     ORDER by time DESC");
 279                          if (empty($loginfo->time)) {
 280                              $loginfo->time = 0;
 281                          }
 282                          execute_sql("UPDATE {$CFG->prefix}user_students 
 283                                       SET timeaccess = '$loginfo->time' 
 284                                       WHERE userid = '$user->userid' AND course = '$course->id'", false);
 285                          
 286                      }
 287                  }
 288              }
 289          }
 290          notify("All courses complete.", "green");
 291          $db->debug = true;
 292      }
 293  
 294      if ($oldversion < 2003103100) {
 295          table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
 296      }
 297  
 298  
 299      if ($oldversion < 2003121600) {
 300          execute_sql("CREATE TABLE {$CFG->prefix}groups (
 301                          id SERIAL PRIMARY KEY,
 302                          courseid integer NOT NULL default '0',
 303                          name varchar(255) NOT NULL default '',
 304                          description text,
 305                          lang varchar(10) NOT NULL default '',
 306                          picture integer NOT NULL default '0',
 307                          timecreated integer NOT NULL default '0',
 308                          timemodified integer NOT NULL default '0'
 309                       )");
 310      
 311          execute_sql("CREATE INDEX {$CFG->prefix}groups_idx ON {$CFG->prefix}groups (courseid) ");
 312      
 313          execute_sql("CREATE TABLE {$CFG->prefix}groups_members (
 314                          id SERIAL PRIMARY KEY,
 315                          groupid integer NOT NULL default '0',
 316                          userid integer NOT NULL default '0',
 317                          timeadded integer NOT NULL default '0'
 318                       )");
 319        
 320          execute_sql("CREATE INDEX {$CFG->prefix}groups_members_idx ON {$CFG->prefix}groups_members (groupid) ");
 321      }
 322  
 323      if ($oldversion < 2003122600) {
 324          table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
 325          table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
 326      }
 327  
 328      if ($oldversion < 2004010900) {
 329          table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
 330      }
 331  
 332      if ($oldversion < 2004011700) {
 333          modify_database("", "CREATE TABLE prefix_event (
 334                                  id SERIAL PRIMARY KEY,
 335                                  name varchar(255) NOT NULL default '',
 336                                  description text,
 337                                  courseid integer NOT NULL default '0',
 338                                  groupid integer NOT NULL default '0',
 339                                  userid integer NOT NULL default '0',
 340                                  modulename varchar(20) NOT NULL default '',
 341                                  instance integer NOT NULL default '0',
 342                                  eventtype varchar(20) NOT NULL default '',
 343                                  timestart integer NOT NULL default '0',
 344                                  timeduration integer NOT NULL default '0',
 345                                  timemodified integer NOT NULL default '0'
 346                               ); ");
 347  
 348          modify_database("", "CREATE INDEX prefix_event_courseid_idx ON prefix_event (courseid);");
 349          modify_database("", "CREATE INDEX prefix_event_userid_idx ON prefix_event (userid);");
 350      }
 351  
 352  
 353      if ($oldversion < 2004012800) {
 354          modify_database("", "CREATE TABLE prefix_user_preferences (
 355                                  id SERIAL PRIMARY KEY,
 356                                  userid integer NOT NULL default '0',
 357                                  name varchar(50) NOT NULL default '',
 358                                  value varchar(255) NOT NULL default ''
 359                               ); ");
 360  
 361          modify_database("", "CREATE INDEX prefix_user_preferences_useridname_idx ON prefix_user_preferences (userid,name);");
 362      }
 363  
 364      if ($oldversion < 2004012900) {
 365          table_column("config", "value", "value", "text", "", "", "");
 366      }
 367  
 368      if ($oldversion < 2004013101) {
 369          table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
 370          set_config("upgrade", "logs");
 371      }
 372  
 373      if ($oldversion < 2004020900) {
 374          table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
 375      }
 376  
 377      if ($oldversion < 2004020903) {
 378          modify_database("", "CREATE TABLE prefix_cache_text (
 379                                  id SERIAL PRIMARY KEY,
 380                                  md5key varchar(32) NOT NULL default '',
 381                                  formattedtext text,
 382                                  timemodified integer NOT NULL default '0'
 383                               );");
 384      }
 385  
 386      if ($oldversion < 2004021000) {
 387          $textfilters = array();
 388          for ($i=1; $i<=10; $i++) {
 389              $variable = "textfilter$i";
 390              if (!empty($CFG->$variable)) {   /// No more filters
 391                  if (is_readable("$CFG->dirroot/".$CFG->$variable)) {
 392                      $textfilters[] = $CFG->$variable;
 393                  }
 394              }
 395          }
 396          $textfilters = implode(',', $textfilters);
 397          if (empty($textfilters)) {
 398              $textfilters = 'mod/glossary/dynalink.php';
 399          }
 400          set_config('textfilters', $textfilters);
 401      }
 402  
 403      if ($oldversion < 2004021201) {
 404          modify_database("", "CREATE TABLE prefix_cache_filters (
 405                                  id SERIAL PRIMARY KEY,
 406                                  filter varchar(32) NOT NULL default '',
 407                                  version integer NOT NULL default '0',
 408                                  md5key varchar(32) NOT NULL default '',
 409                                  rawtext text,
 410                                  timemodified integer NOT NULL default '0'
 411                               );");
 412  
 413          modify_database("", "CREATE INDEX prefix_cache_filters_filtermd5key_idx ON prefix_cache_filters (filter,md5key);");
 414          modify_database("", "CREATE INDEX prefix_cache_text_md5key_idx ON prefix_cache_text (md5key);");
 415      }
 416  
 417      if ($oldversion < 2004021500) {
 418          table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
 419      }
 420  
 421      if ($oldversion < 2004021700) {
 422          if (!empty($CFG->textfilters)) {
 423              $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
 424              $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
 425              $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
 426              $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
 427              $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
 428              $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
 429              set_config("textfilters", $CFG->textfilters);
 430          }
 431      }
 432  
 433      if ($oldversion < 2004022000) {
 434          table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
 435      }
 436  
 437      if ($oldversion < 2004022200) {     /// Final renaming I hope.  :-)
 438          if (!empty($CFG->textfilters)) {
 439              $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
 440              $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
 441              $textfilters = explode(',', $CFG->textfilters);
 442              foreach ($textfilters as $key => $textfilter) {
 443                  $textfilters[$key] = trim($textfilter);
 444              }
 445              set_config("textfilters", implode(',',$textfilters));
 446          }
 447      }
 448  
 449      if ($oldversion < 2004030702) {     /// Because of the renaming of Czech language pack
 450          execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
 451          execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
 452      }
 453  
 454      if ($oldversion < 2004041800) {     /// Integrate Block System from contrib
 455          table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
 456      }
 457  
 458      if ($oldversion < 2004042600) {     /// Rebuild course caches for resource icons
 459          //include_once("$CFG->dirroot/course/lib.php");
 460          //rebuild_course_cache();
 461      }
 462  
 463      if ($oldversion < 2004042700) {     /// Increase size of lang fields
 464          table_column("user",   "lang", "lang", "varchar", "10", "", "en");
 465          table_column("groups", "lang", "lang", "varchar", "10", "", "");
 466          table_column("course", "lang", "lang", "varchar", "10", "", "");
 467      }
 468  
 469      if ($oldversion < 2004042701) {     /// Add hiddentopics field to control hidden topics behaviour
 470          #table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
 471          #See 'hiddensections' further down
 472      }
 473  
 474      if ($oldversion < 2004042702) {     /// Add a format field for the description 
 475          table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
 476      }
 477  
 478      if ($oldversion < 2004043001) {     /// Add hiddentopics field to control hidden topics behaviour
 479          table_column("course", "", "hiddensections", "integer", "2", "unsigned", "0", "not null", "visible");
 480      }
 481      
 482      if ($oldversion < 2004050400) {     /// add a visible field for events
 483          table_column("event", "", "visible", "smallint", "1", "", "1", "not null", "timeduration");
 484          if ($events = get_records('event')) {
 485              foreach($events as $event) {
 486                  if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
 487                      if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
 488                          set_field('event', 'visible', 0, 'id', $event->id);
 489                      }
 490                  }
 491              }
 492          }
 493      }
 494  
 495      if ($oldversion < 2004052800) {     /// First version tagged "1.4 development", version.php 1.227
 496          set_config('siteblocksadded', true);   /// This will be used later by the block upgrade
 497      }
 498  
 499      if ($oldversion < 2004053000) {     /// set defaults for site course
 500          $site = get_site();
 501          set_field('course', 'numsections', 0, 'id', $site->id);
 502          set_field('course', 'groupmodeforce', 1, 'id', $site->id);
 503          set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
 504          set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
 505          set_field('course', 'student', get_string('user'), 'id', $site->id);
 506          set_field('course', 'students', get_string('users'), 'id', $site->id);
 507      }
 508  
 509      if ($oldversion < 2004060100) {
 510          set_config('digestmailtime', 0);
 511          table_column('user', "", 'maildigest', 'smallint', '1', '', '0', 'not null', 'mailformat');
 512      }
 513  
 514      if ($oldversion < 2004062400) {
 515          table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
 516          table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
 517      }
 518  
 519      if ($oldversion < 2004062401) {
 520          table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
 521          execute_sql('UPDATE '.$CFG->prefix.'course SET idnumber = shortname');   // By default
 522      }
 523  
 524      if ($oldversion < 2004062600) {
 525          table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
 526      }
 527  
 528      if ($oldversion < 2004072900) {
 529          table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
 530      }
 531  
 532      if ($oldversion < 2004072901) {  // Fixing error in schema
 533          if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
 534              delete_records('log_display', 'module', 'course', 'action', 'update');
 535              insert_record('log_display', $record, false);
 536          }
 537      }
 538  
 539      if ($oldversion < 2004081200) {  // Fixing version errors in some blocks
 540          set_field('blocks', 'version', 2004081200, 'name', 'admin');
 541          set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
 542          set_field('blocks', 'version', 2004081200, 'name', 'course_list');
 543      }
 544  
 545      if ($oldversion < 2004081500) {  // Adding new "auth" field to user table to allow more flexibility
 546          table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
 547  
 548          execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");  // Set everyone to 'manual' to be sure
 549  
 550          if ($admins = get_admins()) {   // Set all the NON-admins to whatever the current auth module is
 551              $adminlist = array();
 552              foreach ($admins as $user) {
 553                  $adminlist[] = $user->id; 
 554              }
 555              $adminlist = implode(',', $adminlist);
 556              execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE id NOT IN ($adminlist)");
 557          }
 558      }
 559      
 560      if ($oldversion < 2004082600) {
 561          //update auth-fields for external users
 562          // following code would not work in 1.8
 563  /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
 564          if (function_exists('auth_get_userlist')) {
 565              $externalusers = auth_get_userlist();
 566              if (!empty($externalusers)){
 567                  $externalusers = '\''. implode('\',\'',$externalusers).'\'';
 568                  execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
 569              }
 570          }*/
 571      }
 572          
 573      if ($oldversion < 2004082900) {  // Make sure guest is "manual" too.
 574          set_field('user', 'auth', 'manual', 'username', 'guest');
 575      }
 576  
 577      /* Just commenteed unused fields out
 578      if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
 579              table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
 580              execute_sql("CREATE INDEX {$CFG->prefix}user_auth_guid_idx ON {$CFG->prefix}user (auth, guid)"); 
 581      }
 582      */
 583  
 584      if ($oldversion < 2004091900) {  //Modify idnumber to hold longer keys 
 585          set_field('user', 'auth', 'manual', 'username', 'guest');
 586          table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
 587          execute_sql("DROP INDEX {$CFG->prefix}user_idnumber_idx ;",false);// added in case of conflicts with upgrade from 14stable
 588          execute_sql("DROP INDEX {$CFG->prefix}user_auth_idx ;",false);// added in case of conflicts with upgrade from 14stable
 589          execute_sql("CREATE INDEX {$CFG->prefix}user_idnumber_idx ON {$CFG->prefix}user (idnumber)"); 
 590          execute_sql("CREATE INDEX {$CFG->prefix}user_auth_idx ON {$CFG->prefix}user (auth)"); 
 591      }
 592  
 593      if ($oldversion < 2004092000) { //redoing this just to be sure that column type is text (postgres type changes didnt work when this was done first time)
 594          table_column("config", "value", "value", "text", "", "", "");
 595      }
 596  
 597      if ($oldversion < 2004093001) { // add new table for sessions storage
 598          execute_sql(" CREATE TABLE {$CFG->prefix}sessions (
 599                            sesskey char(32) PRIMARY KEY,
 600                            expiry integer NOT null,
 601                            expireref varchar(64),
 602                            data text NOT null
 603                        );");
 604  
 605          execute_sql(" CREATE INDEX {$CFG->prefix}sessions_expiry_idx ON {$CFG->prefix}sessions (expiry)");
 606      }
 607  
 608      if ($oldversion < 2004111500) {  // Update any users/courses using wrongly-named lang pack
 609          execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
 610          execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
 611      }
 612  
 613      if ($oldversion < 2004111700) { // add indexes- drop them first silently to avoid conflicts when upgrading.
 614          execute_sql("DROP INDEX {$CFG->prefix}course_idnumber_idx;",false);
 615          execute_sql("DROP INDEX {$CFG->prefix}course_shortname_idx;",false);
 616          execute_sql("DROP INDEX {$CFG->prefix}user_students_userid_idx;",false);
 617          execute_sql("DROP INDEX {$CFG->prefix}user_teachers_userid_idx;",false);
 618  
 619          modify_database("","CREATE INDEX {$CFG->prefix}course_idnumber_idx ON {$CFG->prefix}course (idnumber);" );
 620          modify_database("","CREATE INDEX {$CFG->prefix}course_shortname_idx ON {$CFG->prefix}course (shortname);" );
 621          modify_database("","CREATE INDEX {$CFG->prefix}user_students_userid_idx ON {$CFG->prefix}user_students (userid);");
 622          modify_database("","CREATE INDEX {$CFG->prefix}user_teachers_userid_idx ON {$CFG->prefix}user_teachers (userid);");
 623      }
 624   
 625      if ($oldversion < 2004111700) { // add an index to event for timestart and timeduration- drop them first silently to avoid conflicts when upgrading.
 626          execute_sql("DROP INDEX {$CFG->prefix}event_timestart_idx;",false);
 627          execute_sql("DROP INDEX {$CFG->prefix}event_timeduration_idx;",false);
 628  
 629          modify_database('','CREATE INDEX prefix_event_timestart_idx ON prefix_event (timestart);');
 630          modify_database('','CREATE INDEX prefix_event_timeduration_idx ON prefix_event (timeduration);');
 631      }
 632  
 633      if ($oldversion < 2004117000) { // add an index on the groups_members table- drop them first silently to avoid conflicts when upgrading.
 634          execute_sql("DROP INDEX {$CFG->prefix}groups_members_userid_idx;",false);
 635  
 636          modify_database('','CREATE INDEX prefix_groups_members_userid_idx ON prefix_groups_members (userid);');
 637      }
 638      
 639      if ($oldversion < 2004111700) { //add indexes on modules and course_modules- drop them first silently to avoid conflicts when upgrading.
 640          execute_sql("DROP INDEX {$CFG->prefix}course_modules_visible_idx;",false);
 641          execute_sql("DROP INDEX {$CFG->prefix}course_modules_course_idx;",false); 
 642          execute_sql("DROP INDEX {$CFG->prefix}course_modules_module_idx;",false); 
 643          execute_sql("DROP INDEX {$CFG->prefix}course_modules_instance_idx;",false);
 644          execute_sql("DROP INDEX {$CFG->prefix}course_modules_deleted_idx;",false);
 645          execute_sql("DROP INDEX {$CFG->prefix}modules_name_idx;",false);
 646  
 647          modify_database('','CREATE INDEX prefix_course_modules_visible_idx ON prefix_course_modules (visible);');
 648          modify_database('','CREATE INDEX prefix_course_modules_course_idx ON prefix_course_modules (course);');
 649          modify_database('','CREATE INDEX prefix_course_modules_module_idx ON prefix_course_modules (module);');
 650          modify_database('','CREATE INDEX prefix_course_modules_instance_idx ON prefix_course_modules (instance);');
 651          modify_database('','CREATE INDEX prefix_course_modules_deleted_idx ON prefix_course_modules (deleted);');
 652          modify_database('','CREATE INDEX prefix_modules_name_idx ON prefix_modules (name);');
 653      }
 654      
 655      if ($oldversion < 2004111700) { // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
 656          execute_sql("DROP INDEX {$CFG->prefix}user_students_timeaccess_idx;",false);
 657  
 658          modify_database('','CREATE INDEX prefix_user_students_timeaccess_idx ON prefix_user_students (timeaccess);');
 659      }
 660      
 661      if ($oldversion < 2004111700) { //add indexes on faux foreign keys  - drop them first silently to avoid conflicts when upgrading.
 662          execute_sql("DROP INDEX {$CFG->prefix}course_sections_coursesection_idx;",false);
 663          execute_sql("DROP INDEX {$CFG->prefix}scale_courseid_idx;",false); 
 664          execute_sql("DROP INDEX {$CFG->prefix}user_admins_userid_idx;",false);
 665          execute_sql("DROP INDEX {$CFG->prefix}user_coursecreators_userid_idx;",false); 
 666  
 667          modify_database('','CREATE INDEX prefix_course_sections_coursesection_idx ON prefix_course_sections (course,section);');
 668          modify_database('','CREATE INDEX prefix_scale_courseid_idx ON prefix_scale (courseid);');
 669          modify_database('','CREATE INDEX prefix_user_admins_userid_idx ON prefix_user_admins (userid);');
 670          modify_database('','CREATE INDEX prefix_user_coursecreators_userid_idx ON prefix_user_coursecreators (userid);');
 671      }
 672     
 673      if ($oldversion < 2004111700) { // make new indexes on user table.
 674          fix_course_sortorder(0,0,1);
 675  
 676          execute_sql("DROP INDEX {$CFG->prefix}course_category_idx;",false);
 677          execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk;",false);
 678          modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder)"); 
 679  
 680          execute_sql("DROP INDEX {$CFG->prefix}user_deleted_idx;",false);
 681          execute_sql("DROP INDEX {$CFG->prefix}user_confirmed_idx;",false);
 682          execute_sql("DROP INDEX {$CFG->prefix}user_firstname_idx;",false);
 683          execute_sql("DROP INDEX {$CFG->prefix}user_lastname_idx;",false);
 684          execute_sql("DROP INDEX {$CFG->prefix}user_city_idx;",false); 
 685          execute_sql("DROP INDEX {$CFG->prefix}user_country_idx;",false); 
 686          execute_sql("DROP INDEX {$CFG->prefix}user_lastaccess_idx;",false);
 687  
 688          modify_database("","CREATE INDEX prefix_user_deleted_idx ON prefix_user (deleted)");
 689          modify_database("","CREATE INDEX prefix_user_confirmed_idx ON prefix_user (confirmed)");
 690          modify_database("","CREATE INDEX prefix_user_firstname_idx ON prefix_user (firstname)");
 691          modify_database("","CREATE INDEX prefix_user_lastname_idx ON prefix_user (lastname)");
 692          modify_database("","CREATE INDEX prefix_user_city_idx ON prefix_user (city)");
 693          modify_database("","CREATE INDEX prefix_user_country_idx ON prefix_user (country)");
 694          modify_database("","CREATE INDEX prefix_user_lastaccess_idx ON prefix_user (lastaccess)");
 695      }
 696  
 697      if ($oldversion < 2004111700) { // one more index for email (for sorting)
 698          execute_sql("DROP INDEX {$CFG->prefix}user_email_idx;",false);
 699  
 700          modify_database('','CREATE INDEX prefix_user_email_idx ON prefix_user (email);');
 701       }
 702  
 703      if ($oldversion < 2004112200) { // new 'enrol' field for enrolment tables
 704          table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
 705          table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
 706          modify_database("","CREATE INDEX {$CFG->prefix}user_students_enrol_idx ON {$CFG->prefix}user_students (enrol);");
 707          modify_database("","CREATE INDEX {$CFG->prefix}user_teachers_enrol_idx ON {$CFG->prefix}user_teachers (enrol);");
 708      } 
 709  
 710      if ($oldversion < 2004112300) { // update log display to use correct postgres friendly sql
 711          execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\' \'||lastname' WHERE module='user' AND action='view' AND mtable='user'");
 712          execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\' \'||lastname' WHERE module='course' AND action='user report' AND mtable='user'");
 713      }
 714  
 715      if ($oldversion < 2004112400) {
 716  
 717          /// Delete duplicate enrolments 
 718          /// and then tell the database course,userid is a unique combination
 719          if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid ".
 720                                          "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
 721              foreach ($users as $user) {
 722                  delete_records_select("user_students", "userid = '$user->userid' ".
 723                                       "AND course = '$user->course' AND id <> '$user->id'");
 724              }
 725          }
 726          flush();
 727  
 728          // drop some indexes quietly -- they may or may not exist depending on what version 
 729          // the user upgrades from 
 730          execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_idx ", false);
 731          execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_uk  ", false);        
 732          modify_database('','CREATE UNIQUE INDEX prefix_user_students_courseuserid_uk ON prefix_user_students (course,userid);');        
 733  
 734          /// Delete duplicate teacher enrolments 
 735          /// and then tell the database course,userid is a unique combination
 736          if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid ".
 737                                          "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
 738              foreach ($users as $user) {
 739                  delete_records_select("user_teachers", "userid = '$user->userid' ".
 740                                       "AND course = '$user->course' AND id <> '$user->id'");
 741              }
 742          }
 743          flush();
 744  
 745          // drop some indexes quietly -- they may or may not exist depending on what version 
 746          // the user upgrades from 
 747          execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_idx ", false);
 748          execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_uk  ", false);
 749          modify_database('','CREATE UNIQUE INDEX prefix_user_teachers_courseuserid_uk ON prefix_user_teachers (course,userid);');        
 750      } 
 751      
 752      if ($oldversion < 2004112401) {
 753          // some postgres databases may have a non-unique index mislabeled unique.
 754          fix_course_sortorder(0,0,1);
 755          execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk  ", false);
 756          execute_sql("DROP INDEX {$CFG->prefix}course_category_idx  ", false);
 757          modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder);");
 758          
 759          // odd! username was missing its unique index!
 760          // first silently drop it just in case...
 761          execute_sql("ALTER TABLE {$CFG->prefix}user DROP CONSTRAINT {$CFG->prefix}user_username_uk;", false);   
 762          execute_sql("DROP INDEX {$CFG->prefix}user_username_uk", false);
 763          modify_database('', "CREATE UNIQUE INDEX prefix_user_username_uk ON prefix_user (username);");
 764          
 765      } 
 766  
 767      if ($oldversion < 2004112900) {
 768          table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
 769      }
 770  
 771      if ($oldversion < 2004121400) {
 772          table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
 773      }
 774  
 775      if ($oldversion < 2004121600) {
 776          modify_database('',"CREATE TABLE prefix_dst_preset (
 777                                  id SERIAL PRIMARY KEY,
 778                                  name varchar(48) NOT NULL default '',
 779                                  apply_offset integer NOT NULL default '0',
 780                                  activate_index integer NOT NULL default '1',
 781                                  activate_day integer NOT NULL default '1',
 782                                  activate_month integer NOT NULL default '1',
 783                                  activate_time char(5) NOT NULL default '03:00',
 784                                  deactivate_index integer NOT NULL default '1',
 785                                  deactivate_day integer NOT NULL default '1',
 786                                  deactivate_month integer NOT NULL default '2',
 787                                  deactivate_time char(5) NOT NULL default '03:00',
 788                                  last_change integer NOT NULL default '0',
 789                                  next_change integer NOT NULL default '0',
 790                                  current_offset integer NOT NULL default '0'
 791                               );");
 792      }
 793  
 794      if ($oldversion < 2004122800) {
 795          execute_sql("DROP TABLE {$CFG->prefix}message", false);
 796          execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
 797          execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
 798  
 799          execute_sql("DROP INDEX {$CFG->prefix}message_useridfrom_idx", false);
 800          execute_sql("DROP INDEX {$CFG->prefix}message_useridto_idx", false);
 801          execute_sql("DROP INDEX {$CFG->prefix}message_read_useridfrom_idx", false);
 802          execute_sql("DROP INDEX {$CFG->prefix}message_read_useridto_idx", false);
 803          execute_sql("DROP INDEX {$CFG->prefix}message_contacts_useridcontactid_idx", false);
 804  
 805          modify_database('',"CREATE TABLE prefix_message (
 806                                 id SERIAL PRIMARY KEY,
 807                                 useridfrom integer NOT NULL default '0',
 808                                 useridto integer NOT NULL default '0',
 809                                 message text,
 810                                 timecreated integer NOT NULL default '0',
 811                                 messagetype varchar(50) NOT NULL default ''
 812                              );
 813  
 814                              CREATE INDEX prefix_message_useridfrom_idx ON prefix_message (useridfrom);
 815                              CREATE INDEX prefix_message_useridto_idx ON prefix_message (useridto);
 816  
 817                              CREATE TABLE prefix_message_read (
 818                                 id SERIAL PRIMARY KEY,
 819                                 useridfrom integer NOT NULL default '0',
 820                                 useridto integer NOT NULL default '0',
 821                                 message text,
 822                                 timecreated integer NOT NULL default '0',
 823                                 timeread integer NOT NULL default '0',
 824                                 messagetype varchar(50) NOT NULL default '',
 825                                 mailed integer NOT NULL default '0'
 826                              );
 827  
 828                              CREATE INDEX prefix_message_read_useridfrom_idx ON prefix_message_read (useridfrom);
 829                              CREATE INDEX prefix_message_read_useridto_idx ON prefix_message_read (useridto);
 830                              ");
 831        
 832          modify_database('',"CREATE TABLE prefix_message_contacts (
 833                                 id SERIAL PRIMARY KEY,
 834                                 userid integer NOT NULL default '0',
 835                                 contactid integer NOT NULL default '0',
 836                                 blocked integer NOT NULL default '0'
 837                              );
 838  
 839                              CREATE INDEX prefix_message_contacts_useridcontactid_idx ON prefix_message_contacts (userid,contactid);
 840                              ");
 841  
 842          modify_database('',"INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'firstname||\' \'||lastname');
 843                              INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'firstname||\' \'||lastname');
 844                              ");
 845      }
 846  
 847      if ($oldversion < 2004122801) {
 848          table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
 849          table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
 850      }
 851         
 852                                  
 853      if ($oldversion < 2005010100) {
 854          modify_database('',"INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'firstname||\' \'||lastname');
 855                              INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'firstname||\' \'||lastname');
 856                              INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'firstname||\' \'||lastname');
 857                              INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'firstname||\' \'||lastname');
 858                              ");
 859      }
 860  
 861      if ($oldversion < 2005011000) {     // Create a .htaccess file in dataroot, just in case
 862          if (!file_exists($CFG->dataroot.'/.htaccess')) {
 863              if ($handle = fopen($CFG->dataroot.'/.htaccess', 'w')) {   // For safety
 864                  @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
 865                  @fclose($handle); 
 866                  notify("Created a default .htaccess file in $CFG->dataroot");
 867              }
 868          }
 869      }
 870  
 871      if ($oldversion < 2005012500) { // add new table for meta courses.
 872          /*
 873          modify_database("","CREATE TABLE prefix_meta_course (
 874               id SERIAL primary key,
 875               parent_course integer NOT NULL,
 876               child_course integer NOT NULL
 877               );");
 878  
 879          modify_database("","CREATE INDEX prefix_meta_course_parent_idx ON prefix_meta_course (parent_course);");
 880          modify_database("","CREATE INDEX prefix_meta_course_child_idx ON prefix_meta_course (child_course);");
 881          table_column('course','','meta_course','integer','1','','0','not null');
 882          */ // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
 883      }
 884  
 885      if ($oldversion < 2005012501) { //fix table names for consistency
 886          execute_sql("DROP TABLE {$CFG->prefix}meta_course",false); // drop silently
 887          execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course",false); // drop silently
 888          
 889          modify_database("","CREATE TABLE prefix_course_meta (
 890               id SERIAL primary key,
 891               parent_course integer NOT NULL,
 892               child_course integer NOT NULL
 893               );");
 894  
 895          modify_database("","CREATE INDEX prefix_course_meta_parent_idx ON prefix_course_meta (parent_course);");
 896          modify_database("","CREATE INDEX prefix_course_meta_child_idx ON prefix_course_meta (child_course);");
 897          table_column('course','','metacourse','integer','1','','0','not null');
 898      }
 899  
 900      if ($oldversion < 2005020100) {
 901          fix_course_sortorder(0, 1, 1);
 902      } 
 903  
 904      if ($oldversion < 2005021000) {     // New fields for theme choices
 905          table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
 906          table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
 907          table_column('user',   '', 'theme', 'varchar', '50', '', '', '', 'lang');
 908  
 909          set_config('theme', 'standardwhite');         // Reset to a known good theme 
 910      }
 911  
 912      if ($oldversion < 2005021700) {
 913          table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
 914      }
 915  
 916      if ($oldversion < 2005021800) {
 917          modify_database("","CREATE TABLE adodb_logsql (
 918                                created timestamp NOT NULL,
 919                                sql0 varchar(250) NOT NULL,
 920                                sql1 text NOT NULL,
 921                                params text NOT NULL,
 922                                tracer text NOT NULL,
 923                                timer decimal(16,6) NOT NULL
 924                             );");
 925      }
 926  
 927      if ($oldversion < 2005022400) {
 928          table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
 929          table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
 930      }
 931  
 932      if ($oldversion < 2005030501) {
 933          table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
 934          table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
 935          table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
 936          table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
 937      }
 938  
 939      if ($oldversion < 2005032300) {
 940          table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
 941          execute_sql('UPDATE '.$CFG->prefix.'user SET timezonename = \'\'');
 942      }
 943  
 944  
 945      if ($oldversion < 2005032600) {
 946          execute_sql('DROP TABLE '.$CFG->prefix.'dst_preset', false);
 947          modify_database('',"CREATE TABLE prefix_timezone (
 948                                id SERIAL PRIMARY KEY,
 949                                name varchar(100) NOT NULL default '',
 950                                year integer NOT NULL default '0',
 951                                rule varchar(20) NOT NULL default '',
 952                                gmtoff integer NOT NULL default '0',
 953                                dstoff integer NOT NULL default '0',
 954                                dst_month integer NOT NULL default '0',
 955                                dst_startday integer NOT NULL default '0',
 956                                dst_weekday integer NOT NULL default '0',
 957                                dst_skipweeks integer NOT NULL default '0',
 958                                dst_time varchar(5) NOT NULL default '00:00',
 959                                std_month integer NOT NULL default '0',
 960                                std_startday integer NOT NULL default '0',
 961                                std_weekday integer NOT NULL default '0',
 962                                std_skipweeks integer NOT NULL default '0',
 963                                std_time varchar(5) NOT NULL default '00:00'
 964                              );");
 965      }
 966  
 967      if ($oldversion < 2005032800) {
 968          modify_database('',"CREATE TABLE prefix_grade_category (
 969                                id SERIAL PRIMARY KEY,
 970                                name varchar(64) default NULL,
 971                                courseid integer NOT NULL default '0',
 972                                drop_x_lowest integer NOT NULL default '0',
 973                                bonus_points integer NOT NULL default '0',
 974                                hidden integer NOT NULL default '0',
 975                                weight decimal(4,2) default '0.00'
 976                              );");
 977          
 978          modify_database('',"CREATE INDEX prefix_grade_category_courseid_idx ON prefix_grade_category (courseid);");
 979          
 980          modify_database('',"CREATE TABLE prefix_grade_exceptions (
 981                                id SERIAL PRIMARY KEY,
 982                                courseid integer  NOT NULL default '0',
 983                                grade_itemid integer  NOT NULL default '0',
 984                                userid integer  NOT NULL default '0'
 985                              );");
 986          
 987          modify_database('',"CREATE INDEX prefix_grade_exceptions_courseid_idx ON prefix_grade_exceptions (courseid);");
 988          
 989          
 990          modify_database('',"CREATE TABLE prefix_grade_item (
 991                                id SERIAL PRIMARY KEY,
 992                                courseid integer default NULL,
 993                                category integer default NULL,
 994                                modid integer default NULL,
 995                                cminstance integer default NULL,
 996                                scale_grade float(11) default '1.0000000000',
 997                                extra_credit integer NOT NULL default '0',
 998                                sort_order integer  NOT NULL default '0'
 999                              );");
1000          
1001          modify_database('',"CREATE INDEX prefix_grade_item_courseid_idx ON prefix_grade_item (courseid);");
1002          
1003          modify_database('',"CREATE TABLE prefix_grade_letter (
1004                                id SERIAL PRIMARY KEY,
1005                                courseid integer NOT NULL default '0',
1006                                letter varchar(8) NOT NULL default 'NA',
1007                                grade_high decimal(6,2) NOT NULL default '100.00',
1008                                grade_low decimal(6,2) NOT NULL default '0.00'
1009                              );");
1010  
1011          modify_database('',"CREATE INDEX prefix_grade_letter_courseid_idx ON prefix_grade_letter (courseid);");
1012          
1013          modify_database('',"CREATE TABLE prefix_grade_preferences (
1014                                id SERIAL PRIMARY KEY,
1015                                courseid integer default NULL,
1016                                preference integer NOT NULL default '0',
1017                                value integer NOT NULL default '0'
1018                              );");
1019          
1020          modify_database('',"CREATE UNIQUE INDEX prefix_grade_prefs_courseidpref_uk ON prefix_grade_preferences (courseid,preference);");
1021      }
1022  
1023      if ($oldversion < 2005033100) {   // Get rid of defunct field from course modules table
1024           delete_records('course_modules', 'deleted', 1);  // Delete old records we don't need any more
1025           execute_sql('DROP INDEX '.$CFG->prefix.'course_modules_deleted_idx;');  // Old index
1026           execute_sql('ALTER TABLE '.$CFG->prefix.'course_modules DROP deleted;');    // Old field
1027      }
1028  
1029      if ($oldversion < 2005040800) {
1030          table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
1031          execute_sql(" ALTER TABLE {$CFG->prefix}user DROP timezonename ");
1032      }
1033  
1034      if ($oldversion < 2005041101) {
1035          require_once($CFG->libdir.'/filelib.php');
1036          if (is_readable($CFG->dirroot.'/lib/timezones.txt')) {  // Distribution file
1037              if ($timezones = get_records_csv($CFG->dirroot.'/lib/timezones.txt', 'timezone')) {
1038                  $db->debug = false;
1039                  update_timezone_records($timezones);
1040                  notify(count($timezones).' timezones installed');
1041                  $db->debug = true;
1042              }
1043          }
1044      }
1045  
1046      if ($oldversion < 2005041900) {  // Copy all Dialogue entries into Messages, and hide Dialogue module
1047  
1048          if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
1049                                            FROM '.$CFG->prefix.'dialogue_conversations c,
1050                                                 '.$CFG->prefix.'dialogue_entries e
1051                                           WHERE e.conversationid = c.id')) {
1052              foreach ($entries as $entry) {
1053                  $message = NULL;
1054                  $message->useridfrom    = $entry->userid;
1055                  $message->useridto      = $entry->recipientid;
1056                  $message->message       = addslashes($entry->text);
1057                  $message->format        = FORMAT_HTML;
1058                  $message->timecreated   = $entry->timecreated;
1059                  $message->messagetype   = 'direct';
1060              
1061                  insert_record('message_read', $message);
1062              }
1063          }
1064  
1065          set_field('modules', 'visible', 0, 'name', 'dialogue');
1066  
1067          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');
1068  
1069      }
1070  
1071      if ($oldversion < 2005042100) {
1072          $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
1073      }
1074  
1075      if ($oldversion < 2005042400) {  // Add user tracking prefs field.
1076          table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
1077      }
1078  
1079      if ($oldversion < 2005051500) {  // Add user tracking prefs field.
1080          table_column('grade_category', 'weight', 'weight', 'numeric(5,2)', '', '', '0.00', '', '');
1081      }
1082  
1083      if ($oldversion < 2005053000 ) { // Add config_plugins table
1084          
1085          // this table was created on the MOODLE_15_STABLE branch
1086          // so it may already exist. Therefore we hide potential errors
1087          // (Postgres doesn't support CREATE TABLE IF NOT EXISTS)
1088          execute_sql("CREATE TABLE {$CFG->prefix}config_plugins (
1089                          id     SERIAL PRIMARY KEY,
1090                          plugin varchar(100) NOT NULL default 'core',
1091                          name   varchar(100) NOT NULL default '',
1092                          value  text NOT NULL default '',
1093                          CONSTRAINT {$CFG->prefix}config_plugins_plugin_name_uk UNIQUE (plugin, name)
1094                       );", false);
1095  
1096      }
1097  
1098      if ($oldversion < 2005060200) {  // migrate some config items to config_plugins table
1099  
1100          // NOTE: this block is in both postgres AND mysql upgrade
1101          // files. If you edit either, update the otherone. 
1102          $user_fields = array("firstname", "lastname", "email", 
1103                               "phone1", "phone2", "department", 
1104                               "address", "city", "country", 
1105                               "description", "idnumber", "lang");
1106          if (!empty($CFG->auth)) { // if we have no auth, just pass
1107              foreach ($user_fields as $field) {
1108                  $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
1109                  foreach ($suffixes as $suffix) {
1110                      $key = 'auth_user_' . $field . $suffix;
1111                      if (isset($CFG->$key)) {
1112                          
1113                          // translate keys & values
1114                          // to the new convention
1115                          // this should support upgrading 
1116                          // even 1.5dev installs
1117                          $newkey = $key;
1118                          $newval = $CFG->$key;
1119                          if ($suffix === '') {
1120                              $newkey = 'field_map_' . $field;
1121                          } elseif ($suffix === '_editlock') {
1122                              $newkey = 'field_lock_' . $field;
1123                              $newval = ($newval==1) ? 'locked' : 'unlocked'; // translate 0/1 to locked/unlocked
1124                          } elseif ($suffix === '_updateremote') {
1125                              $newkey = 'field_updateremote_' . $field;                            
1126                          } elseif ($suffix === '_updatelocal') {
1127                              $newkey = 'field_updatelocal_' . $field;
1128                              $newval = ($newval==1) ? 'onlogin' : 'oncreate'; // translate 0/1 to locked/unlocked
1129                          }
1130  
1131                          if (!(set_config($newkey, addslashes($newval), 'auth/'.$CFG->auth)
1132                              && delete_records('config', 'name', $key))) {
1133                              notify("Error updating Auth configuration $key to {$CFG->auth} $newkey .");
1134                              $result = false;
1135                          }
1136                      } // end if isset key
1137                  } // end foreach suffix
1138              } // end foreach field
1139          }
1140      }
1141  
1142      if ($oldversion < 2005060201) {  // Close down the Attendance module, we are removing it from CVS.
1143          if (!file_exists($CFG->dirroot.'/mod/attendance/lib.php')) {
1144              if (count_records('attendance')) {   // We have some data, so should keep it
1145  
1146                  set_field('modules', 'visible', 0, 'name', 'attendance');
1147                  notify('The Attendance module has been discontinued.  If you really want to 
1148                          continue using it, you should download it individually from 
1149                          http://download.moodle.org/modules and install it, then 
1150                          reactivate it from Admin >> Configuration >> Modules.  
1151                          None of your existing data has been deleted, so all existing 
1152                          Attendance activities should re-appear.');
1153  
1154              } else {  // No data, so do a complete delete
1155  
1156                  execute_sql('DROP TABLE '.$CFG->prefix.'attendance', false);
1157                  delete_records('modules', 'name', 'attendance');
1158                  notify("The Attendance module has been discontinued and removed from your site.  
1159                          You weren't using it anyway.  ;-)");
1160              }
1161          }
1162      }
1163  
1164      if ($oldversion < 2005060223) { // Mass cleanup of bad postgres upgrade scripts
1165          execute_sql("DROP TABLE {$CFG->prefix}attendance_roll", false); // There are no attendance module anymore
1166          modify_database('','ALTER TABLE prefix_config ALTER value SET NOT NULL');
1167          modify_database('','ALTER TABLE prefix_course ALTER metacourse SET NOT NULL');
1168          modify_database('','ALTER TABLE prefix_course ALTER theme SET NOT NULL');
1169          modify_database('','ALTER TABLE prefix_event ALTER repeatid SET NOT NULL');
1170          modify_database('','ALTER TABLE prefix_groups ALTER password SET NOT NULL');
1171          modify_database('','ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
1172          modify_database('','ALTER TABLE prefix_message ALTER format SET NOT NULL');
1173          modify_database('','ALTER TABLE prefix_message_read ALTER format SET NOT NULL');
1174          modify_database('','ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
1175          modify_database('','ALTER TABLE prefix_user ALTER aim DROP DEFAULT');
1176          modify_database('','ALTER TABLE prefix_user ALTER idnumber DROP DEFAULT');
1177          modify_database('','ALTER TABLE prefix_user ALTER msn DROP DEFAULT');
1178          modify_database('','ALTER TABLE prefix_user ALTER policyagreed SET NOT NULL');
1179          modify_database('','ALTER TABLE prefix_user ALTER skype DROP DEFAULT');
1180          modify_database('','ALTER TABLE prefix_user ALTER theme SET NOT NULL');
1181          modify_database('','ALTER TABLE prefix_user ALTER timezone SET NOT NULL');
1182          modify_database('','ALTER TABLE prefix_user ALTER trackforums SET NOT NULL');
1183          modify_database('','ALTER TABLE prefix_user ALTER yahoo DROP DEFAULT');
1184          modify_database('','ALTER TABLE prefix_user_students ALTER enrol SET NOT NULL');
1185          modify_database('','ALTER TABLE prefix_user_teachers ALTER enrol SET NOT NULL');
1186      }
1187  
1188      if ($oldversion < 2005071700) {  // Close down the Dialogue module, we are removing it from CVS.
1189          if (!file_exists($CFG->dirroot.'/mod/dialogue/lib.php')) {
1190              if (count_records('dialogue')) {   // We have some data, so should keep it
1191  
1192                  set_field('modules', 'visible', 0, 'name', 'dialogue');
1193                  notify('The Dialogue module has been discontinued.  If you really want to 
1194                          continue using it, you should download it individually from 
1195                          http://download.moodle.org/modules and install it, then 
1196                          reactivate it from Admin >> Configuration >> Modules.  
1197                          None of your existing data has been deleted, so all existing 
1198                          Dialogue activities should re-appear.');
1199  
1200              } else {  // No data, so do a complete delete
1201  
1202                  execute_sql('DROP TABLE '.$CFG->prefix.'dialogue', false);
1203                  delete_records('modules', 'name', 'dialogue');
1204                  notify("The Dialogue module has been discontinued and removed from your site.  
1205                          You weren't using it anyway.  ;-)");
1206              }
1207          }
1208      }
1209  
1210      if ($oldversion < 2005072000) {  // Add a couple fields to mdl_event to work towards iCal import/export
1211          table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
1212          table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
1213      }
1214      
1215      if ($oldversion < 2005072100) { // run the online assignment cleanup code
1216          include($CFG->dirroot.'/'.$CFG->admin.'/oacleanup.php');
1217          if (function_exists('online_assignment_cleanup')) {
1218              online_assignment_cleanup();
1219          }
1220      }
1221  
1222      if ($oldversion < 2005072200) { // fix the mistakenly-added currency stuff from enrol/authorize
1223          execute_sql("DROP TABLE {$CFG->prefix}currencies", false); // drop silently
1224          execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
1225          $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
1226          table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
1227      }
1228  
1229      if ($oldversion < 2005081600) { //set up the course requests table
1230          modify_database('',"CREATE TABLE prefix_course_request (
1231             id SERIAL PRIMARY KEY,
1232             fullname varchar(254) NOT NULL default '',
1233             shortname varchar(15) NOT NULL default '',
1234             summary text NOT NULL default '',
1235             reason text NOT NULL default '',
1236             requester INTEGER NOT NULL default 0
1237           );");
1238          
1239          modify_database('','CREATE INDEX prefix_course_request_shortname_idx ON prefix_course_request (shortname);');
1240  
1241          table_column('course','','requested');
1242      }
1243  
1244      if ($oldversion < 2005081601) {
1245          modify_database('','CREATE TABLE prefix_course_allowed_modules (
1246              id SERIAL PRIMARY KEY,
1247              course INTEGER NOT NULL default 0,
1248              module INTEGER NOT NULL default 0
1249           );');
1250           
1251          modify_database('','CREATE INDEX prefix_course_allowed_modules_course_idx ON prefix_course_allowed_modules (course);');
1252          modify_database('','CREATE INDEX prefix_course_allowed_modules_module_idx ON prefix_course_allowed_modules (module);');
1253          table_column('course','','restrictmodules','int','1','','0','not null');
1254      }
1255      
1256      if ($oldversion < 2005081700) {
1257          table_column('course_categories','','depth','integer');
1258          table_column('course_categories','','path','varchar','255');
1259      }
1260  
1261      if  ($oldversion < 2005090100) { // stats!
1262          modify_database('','CREATE TABLE prefix_stats_daily (
1263             id SERIAL PRIMARY KEY,
1264             courseid INTEGER NOT NULL default 0,
1265             timeend INTEGER NOT NULL default 0,
1266             students INTEGER NOT NULL default 0,
1267             teachers INTEGER NOT NULL default 0,
1268             activestudents INTEGER NOT NULL default 0,
1269             activeteachers INTEGER NOT NULL default 0,
1270             studentreads INTEGER NOT NULL default 0,
1271             studentwrites INTEGER NOT NULL default 0,
1272             teacherreads INTEGER NOT NULL default 0,
1273             teacherwrites INTEGER NOT NULL default 0,
1274             logins INTEGER NOT NULL default 0,
1275             uniquelogins INTEGER NOT NULL default 0
1276          );');
1277  
1278          modify_database('','CREATE INDEX prefix_stats_daily_courseid_idx ON prefix_stats_daily (courseid);');
1279          modify_database('','CREATE INDEX prefix_stats_daily_timeend_idx ON prefix_stats_daily (timeend);');
1280          
1281          modify_database('','CREATE TABLE prefix_stats_weekly (
1282             id SERIAL PRIMARY KEY,
1283             courseid INTEGER NOT NULL default 0,
1284             timeend INTEGER NOT NULL default 0,
1285             students INTEGER NOT NULL default 0,
1286             teachers INTEGER NOT NULL default 0,
1287             activestudents INTEGER NOT NULL default 0,
1288             activeteachers INTEGER NOT NULL default 0,
1289             studentreads INTEGER NOT NULL default 0,
1290             studentwrites INTEGER NOT NULL default 0,
1291             teacherreads INTEGER NOT NULL default 0,
1292             teacherwrites INTEGER NOT NULL default 0,
1293             logins INTEGER NOT NULL default 0,
1294             uniquelogins INTEGER NOT NULL default 0
1295          );');
1296  
1297          modify_database('','CREATE INDEX prefix_stats_weekly_courseid_idx ON prefix_stats_weekly (courseid);');
1298          modify_database('','CREATE INDEX prefix_stats_weekly_timeend_idx ON prefix_stats_weekly (timeend);');
1299  
1300          modify_database('','CREATE TABLE prefix_stats_monthly (
1301             id SERIAL PRIMARY KEY,
1302             courseid INTEGER NOT NULL default 0,
1303             timeend INTEGER NOT NULL default 0,
1304             students INTEGER NOT NULL default 0,
1305             teachers INTEGER NOT NULL default 0,
1306             activestudents INTEGER NOT NULL default 0,
1307             activeteachers INTEGER NOT NULL default 0,
1308             studentreads INTEGER NOT NULL default 0,
1309             studentwrites INTEGER NOT NULL default 0,
1310             teacherreads INTEGER NOT NULL default 0,
1311             teacherwrites INTEGER NOT NULL default 0,
1312             logins INTEGER NOT NULL default 0,
1313             uniquelogins INTEGER NOT NULL default 0
1314          );');
1315  
1316          modify_database('','CREATE INDEX prefix_stats_monthly_courseid_idx ON prefix_stats_monthly (courseid);');
1317          modify_database('','CREATE INDEX prefix_stats_monthly_timeend_idx ON prefix_stats_monthly (timeend);');
1318          
1319          modify_database("","CREATE TABLE prefix_stats_user_daily (
1320             id SERIAL PRIMARY KEY,
1321             courseid INTEGER NOT NULL default 0,
1322             userid INTEGER NOT NULL default 0,
1323             roleid INTEGER NOT NULL default 0,
1324             timeend INTEGER NOT NULL default 0,
1325             statsreads INTEGER NOT NULL default 0,
1326             statswrites INTEGER NOT NULL default 0,
1327             stattype varchar(30) NOT NULL default ''
1328           );");
1329           
1330           modify_database("","CREATE INDEX prefix_stats_user_daily_courseid_idx ON prefix_stats_user_daily (courseid);");
1331           modify_database("","CREATE INDEX prefix_stats_user_daily_userid_idx ON prefix_stats_user_daily (userid);");
1332           modify_database("","CREATE INDEX prefix_stats_user_daily_roleid_idx ON prefix_stats_user_daily (roleid);");
1333           modify_database("","CREATE INDEX prefix_stats_user_daily_timeend_idx ON prefix_stats_user_daily (timeend);");
1334  
1335           modify_database("","CREATE TABLE prefix_stats_user_weekly (
1336             id SERIAL PRIMARY KEY,
1337             courseid INTEGER NOT NULL default 0,
1338             userid INTEGER NOT NULL default 0,
1339             roleid INTEGER NOT NULL default 0,
1340             timeend INTEGER NOT NULL default 0,
1341             statsreads INTEGER NOT NULL default 0,
1342             statswrites INTEGER NOT NULL default 0,
1343             stattype varchar(30) NOT NULL default ''
1344           );");
1345           
1346           modify_database("","CREATE INDEX prefix_stats_user_weekly_courseid_idx ON prefix_stats_user_weekly (courseid);");
1347           modify_database("","CREATE INDEX prefix_stats_user_weekly_userid_idx ON prefix_stats_user_weekly (userid);");
1348           modify_database("","CREATE INDEX prefix_stats_user_weekly_roleid_idx ON prefix_stats_user_weekly (roleid);");
1349           modify_database("","CREATE INDEX prefix_stats_user_weekly_timeend_idx ON prefix_stats_user_weekly (timeend);");
1350  
1351           modify_database("","CREATE TABLE prefix_stats_user_monthly (
1352             id SERIAL PRIMARY KEY,
1353             courseid INTEGER NOT NULL default 0,
1354             userid INTEGER NOT NULL default 0,
1355             roleid INTEGER NOT NULL default 0,
1356             timeend INTEGER NOT NULL default 0,
1357             statsreads INTEGER NOT NULL default 0,
1358             statswrites INTEGER NOT NULL default 0,
1359             stattype varchar(30) NOT NULL default ''
1360           );");
1361           
1362           modify_database("","CREATE INDEX prefix_stats_user_monthly_courseid_idx ON prefix_stats_user_monthly (courseid);");
1363           modify_database("","CREATE INDEX prefix_stats_user_monthly_userid_idx ON prefix_stats_user_monthly (userid);");
1364           modify_database("","CREATE INDEX prefix_stats_user_monthly_roleid_idx ON prefix_stats_user_monthly (roleid);");
1365           modify_database("","CREATE INDEX prefix_stats_user_monthly_timeend_idx ON prefix_stats_user_monthly (timeend);");
1366      }
1367      
1368      if ($oldversion < 2005100300) {
1369          table_column('course','','expirynotify','integer','1');
1370          table_column('course','','expirythreshold','integer');
1371          table_column('course','','notifystudents','integer','1');
1372          $new = new stdClass();
1373          $new->name = 'lastexpirynotify';
1374          $new->value = 0;
1375          insert_record('config', $new);
1376      }
1377  
1378      if ($oldversion < 2005100400) {
1379          table_column('course','','enrollable','integer','1','unsigned','1');
1380          table_column('course','','enrolstartdate','integer');
1381          table_column('course','','enrolenddate','integer');
1382      }
1383  
1384  
1385      if ($oldversion < 2005101200) { // add enrolment key to course_request.
1386          table_column('course_request','','password','text');
1387      }
1388  
1389      if ($oldversion < 2006030800) { # add extra indexes to log (see bug #4112)
1390          modify_database('',"CREATE INDEX prefix_log_userid_idx ON prefix_log (userid);");
1391          modify_database('',"CREATE INDEX prefix_log_info_idx ON prefix_log (info);");
1392      }
1393  
1394      if ($oldversion < 2006030900) {
1395          table_column('course','','enrol','varchar','20','','');
1396  
1397          if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
1398              set_config('enrol_plugins_enabled', 'manual');
1399              set_config('enrol', 'manual');
1400          } else {
1401              set_config('enrol_plugins_enabled', 'manual,'.$CFG->enrol);
1402          }
1403  
1404          require_once("$CFG->dirroot/enrol/enrol.class.php");
1405          $defaultenrol = enrolment_factory::factory($CFG->enrol);
1406          if (!method_exists($defaultenrol, 'print_entry')) { // switch enrollable to off for all courses in this case
1407              modify_database('', 'UPDATE prefix_course SET enrollable = 0');
1408          }
1409  
1410          execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
1411          execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
1412  
1413      }
1414      
1415      if ($oldversion < 2006031000) {
1416  
1417          modify_database("","CREATE TABLE prefix_post (
1418            id SERIAL PRIMARY KEY,
1419            userid INTEGER NOT NULL default 0,
1420            courseid INTEGER NOT NULL default 0,
1421            groupid INTEGER NOT NULL default 0,
1422            moduleid INTEGER NOT NULL default 0,
1423            coursemoduleid INTEGER NOT NULL default 0,
1424            subject varchar(128) NOT NULL default '',
1425            summary text,
1426            content text,
1427            uniquehash varchar(128) NOT NULL default '',
1428            rating INTEGER NOT NULL default 0,
1429            format INTEGER NOT NULL default 0,
1430            publishstate varchar(10) CHECK (publishstate IN ('draft','site','public')) NOT NULL default 'draft',
1431            lastmodified INTEGER NOT NULL default '0',
1432            created INTEGER NOT NULL default '0'
1433          );");
1434  
1435           modify_database("","CREATE INDEX id_user_idx ON prefix_post  (id, courseid);");
1436           modify_database("","CREATE INDEX post_lastmodified_idx ON prefix_post (lastmodified);");
1437           modify_database("","CREATE INDEX post_subject_idx ON prefix_post (subject);");
1438  
1439           modify_database("","CREATE TABLE prefix_tags (
1440            id SERIAL PRIMARY KEY,
1441            type varchar(255) NOT NULL default 'official',
1442            userid INTEGER NOT NULL default 0,
1443            text varchar(255) NOT NULL default ''
1444          );");
1445  
1446           modify_database("","CREATE TABLE prefix_blog_tag_instance (
1447            id SERIAL PRIMARY KEY,
1448            entryid integer NOT NULL default 0,
1449            tagid integer NOT NULL default 0,
1450            groupid integer NOT NULL default 0,
1451            courseid integer NOT NULL default 0,
1452            userid integer NOT NULL default 0
1453          );");
1454      }
1455  
1456      if ($oldversion < 2006031400) {
1457          require_once("$CFG->dirroot/enrol/enrol.class.php");
1458          $defaultenrol = enrolment_factory::factory($CFG->enrol);
1459          if (!method_exists($defaultenrol, 'print_entry')) {
1460              set_config('enrol', 'manual');
1461          }
1462      }
1463  
1464      if ($oldversion < 2006032000) {
1465          table_column('post','','module','varchar','20','','','not null', 'id');
1466          modify_database('',"CREATE INDEX post_module_idx ON prefix_post (module);");
1467          modify_database('',"UPDATE prefix_post SET module = 'blog';");
1468      }
1469  
1470      if ($oldversion < 2006032001) {
1471          table_column('blog_tag_instance','','timemodified','integer','10','unsigned','0','not null', 'userid'); 
1472          modify_database('',"CREATE INDEX bti_entryid_idx ON prefix_blog_tag_instance (entryid);");
1473          modify_database('',"CREATE INDEX bti_tagid_idx ON prefix_blog_tag_instance (tagid);");
1474          modify_database('',"UPDATE prefix_blog_tag_instance SET timemodified = '".time()."';");
1475      }
1476  
1477      if ($oldversion < 2006040500) { // Add an index to course_sections that was never upgraded (bug 5100)
1478          execute_sql(" CREATE INDEX {$CFG->prefix}course_sections_coursesection_idx ON {$CFG->prefix}course_sections (course,section) ", false);
1479      }
1480  
1481      if ($oldversion < 2006041100) {
1482          table_column('course_modules','','visibleold','integer','1','unsigned','1','not null', 'visible');
1483      }
1484  
1485      if ($oldversion < 2006042400) {
1486          // Look through table log_display and get rid of duplicates.
1487          $rs = get_recordset_sql('SELECT DISTINCT * FROM '.$CFG->prefix.'log_display');
1488          
1489          // Drop the log_display table and create it back with an id field.
1490          execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
1491          
1492          modify_database('', "CREATE TABLE prefix_log_display (
1493                                 id SERIAL PRIMARY KEY,
1494                                 module varchar(30) NOT NULL default '',
1495                                 action varchar(40) NOT NULL default '',
1496                                 mtable varchar(30) NOT NULL default '',
1497                                 field varchar(50) NOT NULL default '')");
1498          
1499          // Add index to ensure that module and action combination is unique.
1500          modify_database('', 'CREATE INDEX prefix_log_display_moduleaction ON prefix_log_display (module,action)');
1501          
1502          // Insert the records back in, sans duplicates.
1503          if ($rs) {
1504              while (!$rs->EOF) {
1505                  $sql = "INSERT INTO {$CFG->prefix}log_display ".
1506                              "VALUES('', '".$rs->fields['module']."', ".
1507                              "'".$rs->fields['action']."', ".
1508                              "'".$rs->fields['mtable']."', ".
1509                              "'".$rs->fields['field']."')";
1510                  
1511                  execute_sql($sql, false);
1512                  $rs->MoveNext();
1513              }
1514              rs_close($rs);
1515          }
1516      }
1517      
1518      // add 2 indexes to tags table
1519      if ($oldversion < 2006042401) {
1520          modify_database('',"CREATE INDEX tags_typeuserid_idx ON prefix_tags (type, userid);");
1521          modify_database('',"CREATE INDEX tags_text_idx ON prefix_tags (text);");
1522      }
1523      
1524      if ($oldversion < 2006050500) {
1525          table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
1526      }
1527  
1528      if ($oldversion < 2006050502) {  // Close down the Dialogue module, we are removing it from CVS.
1529          if (!file_exists($CFG->dirroot.'/mod/dialogue/lib.php')) {
1530              if (!count_records('dialogue_conversations')) {   // no data, drop the extra tables
1531                  execute_sql('DROP TABLE '.$CFG->prefix.'dialogue_conversations', false);
1532                  execute_sql('DROP TABLE '.$CFG->prefix.'dialogue_entries', false);
1533                  notify("The Dialogue module has been discontinued and removed from your site.  
1534                          You weren't using it anyway.  ;-)");
1535              }
1536          }
1537  
1538          table_column('course_request', 'password', 'password', 'varchar', '50', '', '');
1539  
1540          table_column('course', 'currency', 'currency', 'varchar', '3');
1541  
1542          modify_database('', 'ALTER TABLE prefix_course_categories
1543              ALTER COLUMN path SET DEFAULT \'\'');
1544  
1545          table_column('log_display', 'module', 'module', 'varchar', '20');
1546  
1547          modify_database("","DROP INDEX id_user_idx");
1548          modify_database("","DROP INDEX post_lastmodified_idx");
1549          modify_database("","DROP INDEX post_subject_idx");
1550          modify_database('',"DROP INDEX bti_entryid_idx");
1551          modify_database('',"DROP INDEX bti_tagid_idx");
1552          modify_database('',"DROP INDEX post_module_idx");
1553          modify_database('',"DROP INDEX tags_typeuserid_idx");
1554          modify_database('',"DROP INDEX tags_text_idx");
1555  
1556          modify_database("","CREATE INDEX {$CFG->prefix}id_user_idx           ON prefix_post (id, courseid);");
1557          modify_database("","CREATE INDEX {$CFG->prefix}post_lastmodified_idx ON prefix_post (lastmodified);");
1558          modify_database("","CREATE INDEX {$CFG->prefix}post_subject_idx      ON prefix_post (subject);");
1559          modify_database('',"CREATE INDEX {$CFG->prefix}bti_entryid_idx       ON prefix_blog_tag_instance (entryid);");
1560          modify_database('',"CREATE INDEX {$CFG->prefix}bti_tagid_idx         ON prefix_blog_tag_instance (tagid);");
1561          modify_database('',"CREATE INDEX {$CFG->prefix}post_module_idx       ON prefix_post (moduleid);");
1562          modify_database('',"CREATE INDEX {$CFG->prefix}tags_typeuserid_idx   ON prefix_tags (type, userid);");
1563          modify_database('',"CREATE INDEX {$CFG->prefix}tags_text_idx         ON prefix_tags (text);");
1564  
1565      }
1566  
1567      // renaming of reads and writes for stats_user_xyz
1568      if ($oldversion < 2006052400) { // change this later
1569  
1570          // we are using this because we want silent updates
1571  
1572          execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN reads TO statsreads", false);
1573          execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN writes TO statswrites", false);
1574          execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN reads TO statsreads", false);
1575          execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN writes TO statswrites", false);
1576          execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN reads TO statsreads", false);
1577          execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN writes TO statswrites", false);
1578  
1579      }
1580  
1581      // Adding some missing log actions
1582      if ($oldversion < 2006060400) {
1583          // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
1584          if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
1585              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
1586          }
1587          if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
1588              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
1589          }
1590          if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
1591              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
1592          }
1593          if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
1594              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
1595          }
1596          if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
1597              execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
1598          }
1599      }
1600  
1601      //Renaming lastIP to lastip (all fields lowercase)
1602      if ($oldversion < 2006060900) {
1603          //Not needed unded PG because it stores fieldnames lowecase by default
1604          //Only if it exists (because MOODLE_16_STABLE could have done this work before. Bug 5763)
1605          //$fields = $db->MetaColumnNames($CFG->prefix.'user');
1606          //if (in_array('lastIP',$fields)) {
1607          //    table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "", "currentlogin");
1608          //}
1609      }
1610  
1611      
1612      if ($oldversion < 2006080400) {
1613           modify_database('', "CREATE TABLE prefix_role (
1614                                    id SERIAL PRIMARY KEY,
1615                                    name varchar(255) NOT NULL default '',
1616                                    shortname varchar(100) NOT NULL default '',     
1617                                    description text NOT NULL default '',
1618                                    sortorder integer NOT NULL default '0'
1619                                  );");
1620  
1621           modify_database('', "CREATE TABLE prefix_context (
1622                                    id SERIAL PRIMARY KEY,
1623                                    level integer NOT NULL default 0,
1624                                    instanceid integer NOT NULL default 0
1625                                  );");
1626  
1627  
1628           modify_database('', "CREATE TABLE prefix_role_assignments (
1629                                    id SERIAL PRIMARY KEY,
1630                                    roleid integer NOT NULL default 0,
1631                                    contextid integer NOT NULL default 0,
1632                                    userid integer NOT NULL default 0,
1633                                    hidden integer NOT NULL default 0,
1634                                    timestart integer NOT NULL default 0,
1635                                    timeend integer NOT NULL default 0,
1636                                    timemodified integer NOT NULL default 0,
1637                                    modifierid integer NOT NULL default 0,
1638                                    enrol varchar(20) NOT NULL default '',
1639                                    sortorder integer NOT NULL default '0'
1640                                  );");
1641  
1642          modify_database('', "CREATE TABLE prefix_role_capabilities (
1643                                    id SERIAL PRIMARY KEY,
1644                                    contextid integer NOT NULL default 0,
1645                                    roleid integer NOT NULL default 0,
1646                                    capability varchar(255) NOT NULL default '',
1647                                    permission integer NOT NULL default 0,
1648                                    timemodified integer NOT NULL default 0,
1649                                    modifierid integer NOT NULL default 0
1650                                  );");
1651  
1652          modify_database('', "CREATE TABLE prefix_role_deny_grant (
1653                                    id SERIAL PRIMARY KEY,
1654                                    roleid integer NOT NULL default '0',
1655                                    unviewableroleid integer NOT NULL default '0'
1656                                  );");
1657                                  
1658          modify_database('', "CREATE TABLE prefix_capabilities ( 
1659                                id SERIAL PRIMARY KEY,
1660                                name varchar(255) NOT NULL default '', 
1661                                captype varchar(50) NOT NULL default '', 
1662                                contextlevel integer NOT NULL default 0, 
1663                                component varchar(100) NOT NULL default ''
1664                                  );"); 
1665                                  
1666          modify_database('', "CREATE TABLE prefix_role_names ( 
1667                                id SERIAL PRIMARY KEY,
1668                                roleid integer NOT NULL default 0,
1669                                contextid integer NOT NULL default 0, 
1670                                text text NOT NULL default ''
1671                                  );");                                
1672                                                                                       
1673      }
1674      
1675      if ($oldversion < 2006081000) {
1676          modify_database('',"CREATE INDEX prefix_role_sortorder_idx ON prefix_role (sortorder);");
1677          modify_database('',"CREATE INDEX prefix_context_instanceid_idx ON prefix_context (instanceid);");
1678          modify_database('',"CREATE UNIQUE INDEX prefix_context_levelinstanceid_idx ON prefix_context (level, instanceid);"); 
1679          modify_database('',"CREATE INDEX prefix_role_assignments_roleid_idx ON prefix_role_assignments (roleid);");
1680          modify_database('',"CREATE INDEX prefix_role_assignments_contextidid_idx ON prefix_role_assignments (contextid);");
1681          modify_database('',"CREATE INDEX prefix_role_assignments_userid_idx ON prefix_role_assignments (userid);");
1682          modify_database('',"CREATE UNIQUE INDEX prefix_role_assignments_contextidroleiduserid_idx ON prefix_role_assignments (contextid, roleid, userid);");
1683          modify_database('',"CREATE INDEX prefix_role_assignments_sortorder_idx ON prefix_role_assignments (sortorder);");
1684          modify_database('',"CREATE INDEX prefix_role_capabilities_roleid_idx ON prefix_role_capabilities (roleid);");
1685          modify_database('',"CREATE INDEX prefix_role_capabilities_contextid_idx ON prefix_role_capabilities (contextid);");
1686          modify_database('',"CREATE INDEX prefix_role_capabilities_modifierid_idx ON prefix_role_capabilities (modifierid);");
1687          // MDL-10640  adding missing index from upgrade
1688          modify_database('',"CREATE INDEX prefix_role_capabilities_capability_idx ON prefix_role_capabilities (capability);");
1689          modify_database('',"CREATE UNIQUE INDEX prefix_role_capabilities_roleidcontextidcapability_idx ON prefix_role_capabilities (roleid, contextid, capability);"); 
1690          modify_database('',"CREATE INDEX prefix_role_deny_grant_roleid_idx ON prefix_role_deny_grant (roleid);");
1691          modify_database('',"CREATE INDEX prefix_role_deny_grant_unviewableroleid_idx ON prefix_role_deny_grant (unviewableroleid);");
1692          modify_database('',"CREATE UNIQUE INDEX prefix_role_deny_grant_roleidunviewableroleid_idx ON prefix_role_deny_grant (roleid, unviewableroleid);");
1693          modify_database('',"CREATE UNIQUE INDEX prefix_capabilities_name_idx ON prefix_capabilities (name);");
1694          modify_database('',"CREATE INDEX prefix_role_names_roleid_idx ON prefix_role_names (roleid);");
1695          modify_database('',"CREATE INDEX prefix_role_names_contextid_idx ON prefix_role_names (contextid);");
1696          modify_database('',"CREATE UNIQUE INDEX prefix_role_names_roleidcontextid_idx ON prefix_role_names (roleid, contextid);");    
1697      }
1698          
1699      if ($oldversion < 2006081700) { 
1700          modify_database('',"DROP TABLE prefix_role_deny_grant");
1701          
1702          modify_database('',"CREATE TABLE prefix_role_allow_assign (    
1703              id SERIAL PRIMARY KEY,     
1704              roleid integer NOT NULL default '0',   
1705              allowassign integer NOT NULL default '0'      
1706          );");
1707  
1708          modify_database('',"CREATE INDEX prefix_role_allow_assign_roleid_idx ON prefix_role_allow_assign (roleid);");
1709          modify_database('',"CREATE INDEX prefix_role_allow_assign_allowassign_idx ON prefix_role_allow_assign (allowassign);");
1710          modify_database('',"CREATE UNIQUE INDEX prefix_role_allow_assign_roleidallowassign_idx ON prefix_role_allow_assign (roleid, allowassign);");
1711  
1712          modify_database('',"CREATE TABLE prefix_role_allow_override (    
1713              id SERIAL PRIMARY KEY,     
1714              roleid integer NOT NULL default '0',   
1715              allowoverride integer NOT NULL default '0'      
1716          );");
1717          
1718          modify_database('',"CREATE INDEX prefix_role_allow_override_roleid_idx ON prefix_role_allow_override (roleid);");
1719          modify_database('',"CREATE INDEX prefix_role_allow_override_allowoverride_idx ON prefix_role_allow_override (allowoverride);");
1720          modify_database('',"CREATE UNIQUE INDEX prefix_role_allow_override_roleidallowoverride_idx ON prefix_role_allow_override (roleid, allowoverride);");
1721                 
1722      }
1723      
1724      if ($oldversion < 2006082100) {
1725          execute_sql("DROP INDEX {$CFG->prefix}context_levelinstanceid_idx;",false);
1726          table_column('context', 'level', 'aggregatelevel', 'integer', '10', 'unsigned', '0', 'not null', '');
1727          modify_database('',"CREATE UNIQUE INDEX prefix_context_aggregatelevelinstanceid_idx ON prefix_context (aggregatelevel, instanceid);"); 
1728      }
1729  
1730      if ($oldversion < 2006082200) {
1731          table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', '');
1732      }
1733  
1734      if ($oldversion < 2006082800) {
1735          table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
1736      }
1737  
1738      if ($oldversion < 2006082900) {
1739          execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
1740          execute_sql("
1741              CREATE TABLE {$CFG->prefix}sessions2 (
1742                  sesskey VARCHAR(255) NOT NULL default '',
1743                  expiry TIMESTAMP NOT NULL,
1744                  expireref VARCHAR(255),
1745                  created TIMESTAMP NOT NULL,
1746                  modified TIMESTAMP NOT NULL,
1747                  sessdata TEXT,
1748                  CONSTRAINT {$CFG->prefix}sess_ses_pk PRIMARY KEY (sesskey)
1749              );", true);
1750  
1751          execute_sql("
1752              CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
1753          execute_sql("
1754              CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
1755      }
1756      
1757      if ($oldversion < 2006083002) {
1758          table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
1759      }
1760  
1761      if ($oldversion < 2006083100) {
1762          execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP NOT NULL");
1763          execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP DEFAULT");
1764      }
1765  
1766      if ($oldversion < 2006083101) {
1767          execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP NOT NULL");
1768          execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP DEFAULT");
1769      }
1770  
1771      if ($oldversion < 2006083102) {
1772          execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP NOT NULL");
1773          execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP DEFAULT");
1774      }
1775  
1776      if ($oldversion < 2006090200) {
1777          execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP NOT NULL");
1778          execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP DEFAULT");
1779          execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP NOT NULL");
1780          execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP DEFAULT");
1781      }
1782  
1783      // table to keep track of course page access times, used in online participants block, and participants list
1784      if ($oldversion < 2006091200) {
1785          execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( 
1786                      id SERIAL PRIMARY KEY,     
1787                      userid integer NOT NULL default 0,
1788                      courseid integer NOT NULL default 0, 
1789                      timeaccess integer NOT NULL default 0
1790                      );", true);
1791  
1792          execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_userid_idx ON {$CFG->prefix}user_lastaccess (userid);", true);
1793          execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_courseid_idx ON {$CFG->prefix}user_lastaccess (courseid);", true);
1794          execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}user_lastaccess_useridcourseid_idx ON {$CFG->prefix}user_lastaccess (userid, courseid);", true);
1795      
1796      }
1797  
1798      if (!empty($CFG->rolesactive) and $oldversion < 2006091212) {   // Reload the guest roles completely with new defaults
1799          if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
1800              delete_records('capabilities');
1801              $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1802              foreach ($guestroles as $guestrole) {
1803                  delete_records('role_capabilities', 'roleid', $guestrole->id);
1804                  assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
1805              }
1806          }
1807      }
1808  
1809      if ($oldversion < 2006091700) {
1810          table_column('course','','defaultrole','integer','10', 'unsigned', '0', 'not null');
1811      }
1812  
1813      if ($oldversion < 2006091800) {
1814          delete_records('config', 'name', 'showsiteparticipantslist');
1815          delete_records('config', 'name', 'requestedteachername');
1816          delete_records('config', 'name', 'requestedteachersname');
1817          delete_records('config', 'name', 'requestedstudentname');
1818          delete_records('config', 'name', 'requestedstudentsname');
1819      }
1820  
1821      if (!empty($CFG->rolesactive) and $oldversion < 2006091901) {
1822          if ($roles = get_records('role')) {
1823              $first = array_shift($roles);
1824              if (!empty($first->shortname)) {
1825                  // shortnames already exist
1826              } else {
1827                  table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
1828                  $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
1829                  foreach ($legacy_names as $name) {
1830                      if ($roles = get_roles_with_capability('moodle/legacy:'.$name, CAP_ALLOW)) {
1831                          $i = '';
1832                          foreach ($roles as $role) {
1833                              if (empty($role->shortname)) {
1834                                  $updated = new object();
1835                                  $updated->id = $role->id;
1836                                  $updated->shortname = $name.$i;
1837                                  update_record('role', $updated);
1838                                  $i++;
1839                              }
1840                          }
1841                      }
1842                  }
1843              }
1844          }
1845      }
1846  
1847      /// Tables for customisable user profile fields
1848      if ($oldversion < 2006092000) {
1849          execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (
1850                          id BIGSERIAL,
1851                          name VARCHAR(255) NOT NULL default '',
1852                          datatype VARCHAR(255) NOT NULL default '',
1853                          categoryid BIGINT NOT NULL default 0,
1854                          sortorder BIGINT NOT NULL default 0,
1855                          required SMALLINT NOT NULL default 0,
1856                          locked SMALLINT NOT NULL default 0,
1857                          visible SMALLINT NOT NULL default 0,
1858                          defaultdata TEXT,
1859                          CONSTRAINT {$CFG->prefix}userinfofiel_id_pk PRIMARY KEY (id));", true);
1860  
1861          execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_field IS 'Customisable user profile fields';", true);
1862  
1863          execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (
1864                          id BIGSERIAL,
1865                          name VARCHAR(255) NOT NULL default '',
1866                          sortorder BIGINT NOT NULL default 0,
1867                          CONSTRAINT {$CFG->prefix}userinfocate_id_pk PRIMARY KEY (id));", true);
1868  
1869          execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_category IS 'Customisable fields categories';", true);
1870  
1871          execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (
1872                          id BIGSERIAL,
1873                          userid BIGINT NOT NULL default 0,
1874                          fieldid BIGINT NOT NULL default 0,
1875                          data TEXT NOT NULL,
1876                          CONSTRAINT {$CFG->prefix}userinfodata_id_pk PRIMARY KEY (id));", true);
1877  
1878          execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_data IS 'Data for the customisable user fields';", true);
1879  
1880      }
1881  
1882      if ($oldversion < 2006092200) {
1883          table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', '');
1884  /*      execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false);
1885          execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false);  // see 2006092409 below */   
1886      }
1887  
1888      if ($oldversion < 2006092302) {
1889          // fix sortorder first if needed
1890          if ($roles = get_all_roles()) {
1891              $i = 0;
1892              foreach ($roles as $rolex) {
1893                  if ($rolex->sortorder != $i) {
1894                      $r = new object();
1895                      $r->id = $rolex->id;
1896                      $r->sortorder = $i;
1897                      update_record('role', $r);
1898                  }
1899                  $i++;
1900              }
1901          }
1902  /*        execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;");
1903          execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)");*/
1904      }
1905  
1906      if ($oldversion < 2006092400) {
1907          table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
1908      }
1909  
1910      if ($oldversion < 2006092409) {
1911          // ok, once more and now correctly!
1912          execute_sql("DROP INDEX \"aggregatelevel-instanceid\";", false);
1913          execute_sql("DROP INDEX \"contextlevel-instanceid\";", false);
1914          execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false);
1915  
1916          execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix;", false);
1917          execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix;", false);
1918          execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false);
1919      }
1920  
1921      if ($oldversion < 2006092410) {
1922          /// Convert all the PG unique keys into their corresponding unique indexes
1923          /// we don't want such keys inside Moodle 1.7 and above
1924          /// Look for all the UNIQUE CONSTRAINSTS existing in DB
1925          $uniquecons = get_records_sql ("SELECT conname, relname, conkey, clas.oid AS tableoid
1926                                            FROM pg_constraint cons,
1927                                                 pg_class clas
1928                                           WHERE cons.contype='u'
1929                                             AND cons.conrelid = clas.oid");
1930          /// Iterate over every unique constraint, calculating its fields
1931          if ($uniquecons) {
1932              foreach ($uniquecons as $uniquecon) {
1933                  $conscols = trim(trim($uniquecon->conkey, '}'), '{');
1934                  $conscols = explode(',', $conscols);
1935              /// Iterate over each column to fetch its name
1936                  $indexcols = array();
1937                  foreach ($conscols as $conscol) {
1938                      $column = get_record_sql ("SELECT attname, attname
1939                                                   FROM pg_attribute
1940                                                  WHERE attrelid = $uniquecon->tableoid
1941                                                    AND attnum   = $conscol");
1942                      $indexcols[] = $column->attname;
1943                  }
1944              /// Drop the old UNIQUE CONSTRAINT
1945                  execute_sql ("ALTER TABLE $uniquecon->relname DROP CONSTRAINT $uniquecon->conname", false);
1946              /// Create the new UNIQUE INDEX
1947                  execute_sql ("CREATE UNIQUE INDEX {$uniquecon->relname}_".implode('_', $indexcols)."_uix ON $uniquecon->relname (".implode(', ', $indexcols).')', false);
1948              }
1949          }
1950      }
1951  
1952      if ($oldversion < 2006092601) {
1953              table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', '');
1954      }
1955  
1956      //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
1957  
1958      return $result;
1959  }
1960  
1961  ?>


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7