/** * Initialise the iterator * @return boolean success */ function init() { global $CFG; $this->close(); grade_regrade_final_grades($this->course->id); $course_item = grade_item::fetch_course_item($this->course->id); if ($course_item->needsupdate) { // can not calculate all final grades - sorry return false; } if (strpos($CFG->gradebookroles, ',') !== false) { $gradebookroles = " = {$CFG->gradebookroles}"; } else { $gradebookroles = " IN ({$CFG->gradebookroles})"; } $relatedcontexts = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $this->course->id)); if ($this->groupid) { $groupsql = "INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid = u.id"; $groupwheresql = "AND gm.groupid = {$this->groupid}"; } else { $groupsql = ""; $groupwheresql = ""; } $users_sql = "SELECT u.*\n FROM {$CFG->prefix}user u\n INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid\n {$groupsql}\n WHERE ra.roleid {$gradebookroles}\n AND ra.contextid {$relatedcontexts}\n {$groupwheresql}\n ORDER BY u.id ASC"; $this->users_rs = get_recordset_sql($users_sql); if (!empty($this->grade_items)) { $itemids = array_keys($this->grade_items); $itemids = implode(',', $itemids); $grades_sql = "SELECT g.*\n FROM {$CFG->prefix}grade_grades g\n INNER JOIN {$CFG->prefix}user u ON g.userid = u.id\n INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid\n {$groupsql}\n WHERE ra.roleid {$gradebookroles}\n AND ra.contextid {$relatedcontexts}\n AND g.itemid IN ({$itemids})\n {$groupwheresql}\n ORDER BY g.userid ASC, g.itemid ASC"; $this->grades_rs = get_recordset_sql($grades_sql); } return true; }
/** * Update grades by firing grade_updated event * * @param object $assignment null means all assignments * @param int $userid specific user only, 0 mean all */ function webquestscorm_update_grades($webquestscorm = null, $userid = 0, $nullifnone = true) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once $CFG->libdir . '/gradelib.php'; } if ($webquestscorm != null) { if ($grades = webquestscorm_get_user_grades($webquestscorm, $userid)) { foreach ($grades as $k => $v) { if ($v->rawgrade == -1) { $grades[$k]->rawgrade = null; } } webquestscorm_grade_item_update($webquestscorm, $grades); } else { webquestscorm_grade_item_update($webquestscorm); } } else { $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid\n FROM {$CFG->prefix}webquestscorm a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m\n WHERE m.name='webquestscorm' AND m.id=cm.module AND cm.instance=a.id"; if ($rs = get_recordset_sql($sql)) { while ($webquestscorm = rs_fetch_next_record($rs)) { if ($webquestscorm->grade != 0) { webquestscorm_update_grades($webquestscorm); } else { webquestscorm_grade_item_update($webquestscorm); } } rs_close($rs); } } }
function print_filter(&$mform, $data) { global $CFG, $db; $columns = $db->MetaColumns($CFG->prefix . 'course'); $filteroptions = array(); $filteroptions[''] = get_string('choose'); $coursecolumns = array(); foreach ($columns as $c) { $coursecolumns[$c->name] = $c->name; } if (!isset($coursecolumns[$data->field])) { print_error('nosuchcolumn'); } $reportclassname = 'report_' . $this->report->type; $reportclass = new $reportclassname($this->report); $components = cr_unserialize($this->report->components); $conditions = $components['conditions']; $courselist = $reportclass->elements_by_conditions($conditions); if (!empty($courselist)) { if ($rs = get_recordset_sql('SELECT DISTINCT(' . $data->field . ') as ufield FROM ' . $CFG->prefix . 'course WHERE ' . $data->field . ' <> "" ORDER BY ufield ASC')) { while ($u = rs_fetch_next_record($rs)) { $filteroptions[base64_encode($u->ufield)] = $u->ufield; } } } $mform->addElement('select', 'filter_fcoursefield_' . $data->field, get_string($data->field), $filteroptions); $mform->setType('filter_courses', PARAM_INT); }
public static function getRecordDataById($type, $id) { $sql = 'SELECT c.id, c.name, c.ctime, c.description, cv.view AS viewid, c.owner FROM {collectio}n c LEFT OUTER JOIN {collection_view} cv ON cv.collection = c.id WHERE id = ? ORDER BY cv.displayorder asc LIMIT 1;'; $record = get_record_sql($sql, array($id)); if (!$record) { return false; } $record->name = str_replace(array("\r\n", "\n", "\r"), ' ', strip_tags($record->name)); $record->description = str_replace(array("\r\n", "\n", "\r"), ' ', strip_tags($record->description)); // Created by if (intval($record->owner) > 0) { $record->createdby = get_record('usr', 'id', $record->owner); $record->createdbyname = display_name($record->createdby); } // Get all views included in that collection $sql = 'SELECT v.id, v.title FROM {view} v LEFT OUTER JOIN {collection_view} cv ON cv.view = v.id WHERE cv.collection = ?'; $views = recordset_to_array(get_recordset_sql($sql, array($id))); if ($views) { $record_views = array(); foreach ($views as $view) { if (isset($view->id)) { $record_views[$view->id] = $view->title; } } $record->views = $record_views; } return $record; }
function block_openshare_updategroup($courseid, $groupid) { $sql = 'SELECT u.id FROM mdl_user u JOIN mdl_role_assignments ra ON ra.userid = u.id JOIN mdl_role r ON ra.roleid = r.id JOIN mdl_context con ON ra.contextid = con.id JOIN mdl_course c ON c.id = con.instanceid AND con.contextlevel = 50 WHERE (r.shortname = \'student\' OR r.shortname = \'teacher\' OR r.shortname = \'editingteacher\' OR r.shortname = \'coursecreator\') AND c.id = ' . $courseid; $rs = get_recordset_sql($sql); if (!empty($rs)) { while ($rec = rs_fetch_next_record($rs)) { //prep dataobject for door $groupenroll = new object(); $groupenroll->timeadded = time(); $groupenroll->groupid = $groupid; $groupenroll->userid = $rec->id; $ingroup = get_record("groups_members", "groupid", $groupid, "userid", $rec->id); if (empty($ingroup)) { insert_record("groups_members", $groupenroll); print 'updated' . $groupenroll->groupid . $groupenroll->userid . '<br/>'; } } } else { print_error("No users in this course!"); } // Close the recordset to save memory rs_close($rs); }
function folio_control_page_edit_move($page) { // Find the security information for the page. global $CFG; $url = url; $page_ident = intval($page->page_ident); $parentpage_ident = intval($page->parentpage_ident); // Check to see if we're on the homepage. if (folio_page_is_homepage($page)) { // Don't allow moving a homepage. $run_result = '<input type="hidden" name="parentpage_ident" value="' . $page->parentpage_ident . '" />'; } elseif (!isloggedin()) { // Have to be logged in to move a page. // mark control as disabled & don't bother loading all of the pages. $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\" DISABLED>"; // Get parentpage title $pages = recordset_to_array(get_recordset_sql('select page_ident, title from ' . $CFG->prefix . 'folio_page ' . 'WHERE newest = 1 and user_ident = ' . $page->user_ident . ' AND page_ident = ' . $page->parentpage_ident)); // build if ($pages) { // Iterate foreach ($pages as $potentialpage) { // Selected $run_result .= '<OPTION VALUE=' . $potentialpage->page_ident . " SELECTED=true>" . $potentialpage->title . "\n"; } $run_result .= "</SELECT><br/>\n" . "<input type='hidden' name='parentpage_ident' value='{$potentialpage->page_ident}' />\n"; } else { // No pages. Show control set to homepage & disabled. $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\" disabled=TRUE>" . '<OPTION VALUE="' . $page->parentpage_ident . '" SELECTED=true>Homepage' . "</SELECT><br/>\n" . "<input type='hidden' name='parentpage_ident' value='{$potentialpage->page_ident}' />\n"; } $run_result = templates_draw(array('context' => 'databoxvertical', 'name' => 'Parent Page', 'contents' => $run_result)); } else { // Ok conditions, build the control. $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\">"; // Get all titles for active pages belonging to the current user $pages = recordset_to_array(get_recordset_sql('select page_ident, title from ' . $CFG->prefix . 'folio_page ' . 'WHERE newest = 1 and user_ident = ' . $page->user_ident . ' AND page_ident <> ' . $page->page_ident . ' AND parentpage_ident <> ' . $page->page_ident . ' order by title')); // build if ($pages) { // Iterate foreach ($pages as $potentialpage) { if ($page->parentpage_ident == $potentialpage->page_ident) { // Selected $run_result .= '<OPTION VALUE=' . $potentialpage->page_ident . " SELECTED=true>" . $potentialpage->title . "\n"; } else { // !Selected $run_result .= '<OPTION VALUE=' . $potentialpage->page_ident . " >" . $potentialpage->title . "\n"; } } $run_result .= "</SELECT><br/>\n"; } else { // No pages. Show control set to homepage & disabled. $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\" disabled=TRUE>" . '<OPTION VALUE="' . $page->parentpage_ident . '" SELECTED=true>Homepage' . "</SELECT><br/>\n"; } $run_result = templates_draw(array('context' => 'databoxvertical', 'name' => 'Parent Page', 'contents' => $run_result)); } return $run_result; }
function xmldb_forum_upgrade($oldversion = 0) { global $CFG, $THEME, $db; $result = true; /// And upgrade begins here. For each one, you'll need one /// block of code similar to the next one. Please, delete /// this comment lines once this file start handling proper /// upgrade code. /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php /// $result = result of "/lib/ddllib.php" function calls /// } if ($result && $oldversion < 2007101000) { /// Define field timemodified to be added to forum_queue $table = new XMLDBTable('forum_queue'); $field = new XMLDBField('timemodified'); $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'postid'); /// Launch add field timemodified $result = $result && add_field($table, $field); } //===== 1.9.0 upgrade line ======// if ($result and $oldversion < 2007101511) { notify('Processing forum grades, this may take a while if there are many forums...', 'notifysuccess'); //MDL-13866 - send forum ratins to gradebook again require_once $CFG->dirroot . '/mod/forum/lib.php'; // too much debug output $db->debug = false; forum_update_grades(); $db->debug = true; } if ($result && $oldversion < 2007101512) { /// Cleanup the forum subscriptions notify('Removing stale forum subscriptions', 'notifysuccess'); $roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW); $roles = array_keys($roles); $roles = implode(',', $roles); $sql = "SELECT fs.userid, f.id AS forumid\n FROM {$CFG->prefix}forum f\n JOIN {$CFG->prefix}course c ON c.id = f.course\n JOIN {$CFG->prefix}context ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = " . CONTEXT_COURSE . ")\n JOIN {$CFG->prefix}forum_subscriptions fs ON fs.forum = f.id\n LEFT JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = ctx.id AND ra.userid = fs.userid AND ra.roleid IN ({$roles}))\n WHERE ra.id IS NULL"; if ($rs = get_recordset_sql($sql)) { $db->debug = false; while ($remove = rs_fetch_next_record($rs)) { delete_records('forum_subscriptions', 'userid', $remove->userid, 'forum', $remove->forumid); echo '.'; } $db->debug = true; rs_close($rs); } } if ($result && $oldversion < 2007101513) { delete_records('forum_ratings', 'post', 0); /// Clean existing wrong rates. MDL-18227 } return $result; }
function display_search_field($value = '') { global $CFG; $varcharlat = sql_compare_text('content'); $varcharlong = sql_compare_text('content1'); $latlongsrs = get_recordset_sql("SELECT DISTINCT {$varcharlat} AS la, {$varcharlong} AS lo\n FROM {$CFG->prefix}data_content\n WHERE fieldid = {$this->field->id}\n ORDER BY {$varcharlat}, {$varcharlong}"); $options = array(); while ($latlong = rs_fetch_next_record($latlongsrs)) { $options[$latlong->la . ',' . $latlong->lo] = $latlong->la . ',' . $latlong->lo; } rs_close($latlongsrs); return choose_from_menu($options, 'f_' . $this->field->id, $value, 'choose', '', 0, true); }
/** * Queries for draft posts, including necessary joins with other fields. * @param string $where Text of WHERE clause e.g. 'fdr.id=14'. May refer * to aliases fdr (drafts), fd (discussions), fp (posts; post being * replied to), fpfirst (first post in discussion), and u (user being * replied to) * @return array Array of forum_draft objects (empty if none) */ static function query_drafts($where) { global $CFG; $result = array(); $rs = get_recordset_sql("\nSELECT\n fdr.*, fd.id AS discussionid, fpfirst.subject AS discussionsubject, \n f.course AS courseid,\n " . forum_utils::select_username_fields('u', false) . "\nFROM\n {$CFG->prefix}forumng_drafts fdr\n LEFT JOIN {$CFG->prefix}forumng_posts fp ON fdr.parentpostid = fp.id\n LEFT JOIN {$CFG->prefix}forumng_discussions fd ON fp.discussionid = fd.id\n LEFT JOIN {$CFG->prefix}forumng_posts fpfirst ON fd.postid = fpfirst.id\n LEFT JOIN {$CFG->prefix}user u ON fp.userid = u.id\n INNER JOIN {$CFG->prefix}forumng f ON fdr.forumid = f.id\nWHERE\n {$where}\nORDER BY\n fdr.saved DESC\n "); if (!$rs) { throw new forum_exception("Failed to query for draft posts"); } while ($rec = rs_fetch_next_record($rs)) { $result[] = new forum_draft($rec); } rs_close($rs); return $result; }
function sermon_alphabetical_get_one_node($letterstartnumber) { global $CFG, $COURSE, $alphabet; if (empty($letterstartnumber)) { return ''; } $extrawhere = array(); for ($x = 0; $x < NUMBER_OF_PARTION_LETTERS; $x++) { $extrawhere[] = "name LIKE '{$alphabet[$letterstartnumber + $x]}%' "; } //get the relavant sermons for this sermon series $sql = "SELECT r.*, rs.datedelivered, rs.seriesname, rs.book, rs.beginchapter, cm.id as `cmid`,\n rs.guestspeaker, rs.guestspeakername, rs.hitcounter, rs.lastaccess \n FROM {$CFG->prefix}resource r \n JOIN {$CFG->prefix}resource_sermon rs ON rs.resourceid = r.id\n JOIN {$CFG->prefix}course_modules cm ON cm.instance = r.id \n WHERE r.type = 'sermon' AND r.course = {$COURSE->id} AND name != '' "; $sql .= !empty($extrawhere) ? ' AND (' . implode(' OR ', $extrawhere) . ')' : ''; $sql .= " ORDER BY r.name ASC"; $sermons = get_recordset_sql($sql); //loop through and make them into an array of objecst compatible for a json_encode $letters = array(); while (($sermon = rs_fetch_next_record($sermons)) !== false) { if (empty($sermon->seriesname)) { $sermon->seriesname = 'no name'; } $sermon->datedelivered = date('m-d-Y', $sermon->datedelivered); $sermonnode = new stdClass(); $sermonnode->attributes = new stdClass(); $sermonnode->attributes->id = $sermon->cmid . '~' . sermon_block_make_name_safe_for_id($sermon->seriesname); $sermonnode->attributes->class = 'leaf sermon'; if (!empty($sermon->reference)) { $sermonnode->attributes->class .= ' mp3 '; } else { if (!empty($sermon->referencesermontext)) { $sermonnode->attributes->class .= ' text '; } else { if (!empty($sermon->referencelesson)) { $sermonnode->attributes->class .= ' lesson '; } } } $sermonnode->attributes->class .= rs_fetch_record($sermons) === false ? ' last ' : ''; $sermonnode->data = get_string('sermonleaf', 'resource', $sermon); $letters[] = $sermonnode; } $letters = array_values($letters); if (empty($letters)) { return ''; } return $letters; }
/** * Due to MDL-14750, subquestions of multianswer questions restored from backup will * have the wrong parent, and due to MDL-10899 subquestions of multianswer questions * that have been moved between categories will be in the wrong category, This code fixes these up. */ function question_multianswer_fix_subquestion_parents_and_categories() { global $CFG; $result = true; $rs = get_recordset_sql('SELECT q.id, q.category, qma.sequence FROM ' . $CFG->prefix . 'question q JOIN ' . $CFG->prefix . 'question_multianswer qma ON q.id = qma.question'); if ($rs) { while ($q = rs_fetch_next_record($rs)) { if (!empty($q->sequence)) { $result = $result && execute_sql('UPDATE ' . $CFG->prefix . 'question' . ' SET parent = ' . $q->id . ', category = ' . $q->category . ' WHERE id IN (' . $q->sequence . ') AND parent <> 0'); } } rs_close($rs); } else { $result = false; } return $result; }
/** * Get the current version, or -1 if the table isn't present * @return Integer **/ function folio_getVersion() { global $CFG; // Find. $versions = recordset_to_array(get_recordset_sql("SELECT version as v, version FROM " . $CFG->prefix . "folio_version")); if ($versions) { $i = -1; foreach ($versions as $version) { if ($i < $version->version) { $i = $version->version; } } return $version->version; } else { // Table not found. Folios probably aren't installed yet. return -1; } }
function sermon_series_get_one_node($seriesname) { global $CFG, $COURSE; if (empty($seriesname)) { return ''; } //get the relavant sermons for this sermon series $sql = "SELECT r.*, rs.datedelivered, rs.seriesname, rs.book, rs.beginchapter, cm.id as `cmid`,\n rs.guestspeaker, rs.guestspeakername, rs.hitcounter, rs.lastaccess \n FROM {$CFG->prefix}resource r \n JOIN {$CFG->prefix}resource_sermon rs ON rs.resourceid = r.id\n JOIN {$CFG->prefix}course_modules cm ON cm.instance = r.id \n WHERE r.type = 'sermon' AND r.course = {$COURSE->id} AND name != '' AND rs.seriesname = '{$seriesname}'\n ORDER BY rs.seriesname ASC, rs.datedelivered DESC"; $sermons = get_recordset_sql($sql); //loop through and make them into an array of objecst compatible for a json_encode $series = array(); while (($sermon = rs_fetch_next_record($sermons)) !== false) { if (empty($sermon->seriesname)) { $sermon->seriesname = 'no name'; } //clean up some variable // $sermon->seriesname = stripslashes($sermon->seriesname); // $sermon->name = stripslashes($sermon->name); $sermon->datedelivered = date('m-d-Y', $sermon->datedelivered); $sermonnode = new stdClass(); $sermonnode->attributes = new stdClass(); $sermonnode->attributes->id = $sermon->cmid . '~' . sermon_block_make_name_safe_for_id($sermon->seriesname); $sermonnode->attributes->class = 'leaf sermon'; if (!empty($sermon->reference)) { $sermonnode->attributes->class .= ' mp3 '; } else { if (!empty($sermon->referencesermontext)) { $sermonnode->attributes->class .= ' text '; } else { if (!empty($sermon->referencelesson)) { $sermonnode->attributes->class .= ' lesson '; } } } $sermonnode->attributes->class .= rs_fetch_record($sermons) === false ? ' last ' : ''; $sermonnode->data = get_string('sermonleaf', 'resource', $sermon); $series[] = $sermonnode; } $series = array_values($series); if (empty($series)) { return ''; } return $series; }
/** * Creates the mail queue and runs query to obtain list of posts that should * be mailed. * @param bool $tracetimes True if it should call mtrace to display * performance information */ function __construct($tracetimes) { global $CFG; $this->time = time(); $this->forum = null; $this->discussion = null; $this->storedrecord = null; $this->postcount = 0; // Check if an earlier run got aborted. In that case we mark all // messages as mailed anyway because it's better to skip some than // to send out double-posts. if ($pending = get_config('forumng', $this->get_pending_flag_name())) { $this->mark_mailed($pending); } // Note that we are mid-run set_config($this->get_pending_flag_name(), $this->time, 'forumng'); $querychunk = $this->get_query_chunk($this->time); if (!($this->rs = get_recordset_sql($sql = "\nSELECT\n " . forum_utils::select_forum_fields('f') . ",\n " . forum_utils::select_discussion_fields('fd') . ",\n " . forum_utils::select_post_fields('discussionpost') . ",\n " . forum_utils::select_post_fields('fp') . ",\n " . forum_utils::select_post_fields('reply') . ",\n " . forum_utils::select_course_module_fields('cm') . ",\n " . forum_utils::select_context_fields('x') . ",\n " . forum_utils::select_username_fields('u', true) . ",\n " . forum_utils::select_username_fields('eu') . ",\n " . forum_utils::select_username_fields('replyu') . ",\n " . forum_utils::select_username_fields('replyeu') . ",\n " . forum_utils::select_course_fields('c') . ",\n clonecm.id AS cloneid\n{$querychunk}\nORDER BY\n clonecm.course, f.id, fd.id, fp.id"))) { throw new forum_exception("Mail queue query failed"); } }
/** * Delete a single wiki page. Assumes that permission check has already been run. * Looks to see if there are any child pages, if so, doesn't allow deleting until those are * removed as well. * * @package folio * @param array $page The mysql page record. * @param string $page_title The passed in title used to access the page. Assumes that it has already * been decoded by the function in lib.php away from the URL form & into the normal presentation form. * @param string $username The username of the page owner. Used to create post link * to the finished page. * @returns HTML code to delete a folio page. **/ function folio_page_delete($page, $page_title, $username) { global $CFG; global $profile_id; global $language; global $page_owner; global $metatags; // Set url var $url = url; // Error, need a page record. if (!$page) { error('Sorry, but you can not delete a page that has not yet been created.'); } // Get children records. $pages = recordset_to_array(get_recordset_sql('SELECT * FROM ' . $CFG->prefix . 'folio_page p ' . "WHERE parentpage_ident = {$page->page_ident} AND newest = 1")); // Build results if ($pages) { // don't offer to delete pages with children. link to titles $run_result = 'Sorry, but you can not delete a page that has child pages under it. Delete each' . ' of the child pages, and then come back and delete this page.<br/>' . '<ul>'; foreach ($pages as $page) { $run_result .= "<li><a href=\"{$url}{$username}/page/" . folio_page_encodetitle($page->title) . "\">{$page->title}</a>"; } $run_result .= "</ul>"; } else { $run_result = <<<END <form method="post" name="elggform" action="{$url}_folio/action_redirection.php"> \t<h2>{$page_title}</h2> \t<p> Click the 'delete' button to completely remove this page. You will not be able to undo this process.<br/> \t\t<input type="hidden" name="action" value="folio:page:delete" /> \t\t<input type="hidden" name="page_ident" value="{$page->page_ident}" /> \t\t<input type="submit" value="Delete" /> \t</p> END; } return $run_result; }
function folio_control_childpagelist($username, $page, $profile_id) { global $CFG; $url = url; if (!$page) { // No pages passed. Can't show sub-pages of a page that doesnt' exist. return ''; } else { // Grab matching records. $pages = recordset_to_array(get_recordset_sql("SELECT DISTINCT w.* FROM " . $CFG->prefix . "folio_page w " . "INNER JOIN " . $CFG->prefix . "folio_page_security p ON w.security_ident = p.security_ident " . 'WHERE w.parentpage_ident = ' . $page->page_ident . ' AND w.page_ident <> ' . $page->page_ident . ' AND w.newest = 1 AND ' . folio_page_security_where('p', 'w', 'read', $profile_id) . ' ORDER BY title ')); $html = '<a href="' . $url . $username . '/page/' . folio_page_encodetitle($page->title) . '/addpage">Add a new page under this one</a><br/>'; if ($pages) { // Build html $html .= '<ul>'; foreach ($pages as $childpage) { // Load values. $html .= "<li><a href=\"{$url}" . $username . '/page/' . folio_page_encodetitle($childpage->title) . '">' . $childpage->title . "</a>\n"; } $html .= '</ul>'; } } return $html; }
/** * Grading cron job */ function grade_cron() { global $CFG; $now = time(); $sql = "SELECT i.*\n FROM {$CFG->prefix}grade_items i\n WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < {$now} AND EXISTS (\n SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)"; // go through all courses that have proper final grades and lock them if needed if ($rs = get_recordset_sql($sql)) { if ($rs->RecordCount() > 0) { while ($item = rs_fetch_next_record($rs)) { $grade_item = new grade_item($item, false); $grade_item->locked = $now; $grade_item->update('locktime'); } } rs_close($rs); } $grade_inst = new grade_grade(); $fields = 'g.' . implode(',g.', $grade_inst->required_fields); $sql = "SELECT {$fields}\n FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i\n WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < {$now} AND g.itemid=i.id AND EXISTS (\n SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)"; // go through all courses that have proper final grades and lock them if needed if ($rs = get_recordset_sql($sql)) { if ($rs->RecordCount() > 0) { while ($grade = rs_fetch_next_record($rs)) { $grade_grade = new grade_grade($grade, false); $grade_grade->locked = $now; $grade_grade->update('locktime'); } } rs_close($rs); } }
/** * Based off of the incoming parameters, build a SQL where condition **/ function buildWhere($purpose, $reader_ident, $user_ident, $types, $types_avoid) { global $CFG; if ($purpose == 'activity') { // FIND FRIENDS AND JOINED COMMUNITIES. // Find key values for friends. $friendlist = array(); $friends = recordset_to_array(get_recordset_sql("SELECT DISTINCT friend as i, friend FROM " . $CFG->prefix . "friends where owner = {$user_ident}")); if ($friends) { foreach ($friends as $friend) { $friendlist[] = $friend->friend; } } // Find key values for owned communities $friends = recordset_to_array(get_recordset_sql("SELECT DISTINCT ident as i, ident FROM " . $CFG->prefix . "users where owner = {$user_ident}")); if ($friends) { foreach ($friends as $friend) { $friendlist[] = $friend->ident; } } // Transform array into a where clause. if (count($friendlist) > 0) { $friendlist = implode(',', $friendlist); $where = 'owner_ident in (' . $friendlist . ')'; } else { // If a person has no friends or communities, then they have no activity. $where = ' false '; } } elseif ($purpose == 'subscribe') { // Subscribe to a person's feed. $where = "owner_ident = {$user_ident}"; } else { die('unknown purpose passed to feeds.php'); } // Add permissions $where .= ' AND access in ("' . implode('","', rss_permissionlist($reader_ident)) . '")'; // Add type filter $where .= rss_buildwhere('type', $types, $types_avoid); return $where; }
function survey_print_recent_activity($course, $viewfullnames, $timestart) { global $CFG; $modinfo = get_fast_modinfo($course); $ids = array(); foreach ($modinfo->cms as $cm) { if ($cm->modname != 'survey') { continue; } if (!$cm->uservisible) { continue; } $ids[$cm->instance] = $cm->instance; } if (!$ids) { return false; } $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right? if (!($rs = get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,\n u.firstname, u.lastname, u.email, u.picture\n FROM {$CFG->prefix}survey_answers sa\n JOIN {$CFG->prefix}user u ON u.id = sa.userid\n WHERE sa.survey IN ({$slist}) AND sa.time > {$timestart}\n GROUP BY sa.userid, sa.survey, u.firstname, u.lastname, u.email, u.picture\n ORDER BY time ASC"))) { return false; } $surveys = array(); while ($survey = rs_fetch_next_record($rs)) { $cm = $modinfo->instances['survey'][$survey->survey]; $survey->name = $cm->name; $survey->cmid = $cm->id; $surveys[] = $survey; } rs_close($rs); if (!$surveys) { return false; } print_headline(get_string('newsurveyresponses', 'survey') . ':'); foreach ($surveys as $survey) { $url = $CFG->wwwroot . '/mod/survey/view.php?id=' . $survey->cmid; print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames); } return true; }
$exclude = array_merge(array_keys($mnetenrolledusers), array_keys($remtenrolledusers)); $exclude[] = 0; $select = 'AND u.username!=\'guest\' AND u.id NOT IN (' . join(',', $exclude) . ') '; unset($exclude); $searchtext = trim($searchtext); if ($searchtext !== '') { // Search for a subset of remaining users $LIKE = sql_ilike(); $FULLNAME = sql_fullname(); $select .= " AND ({$FULLNAME} {$LIKE} '%{$searchtext}%' OR email {$LIKE} '%{$searchtext}%') "; } $sql = 'SELECT id, firstname, lastname, email FROM ' . $CFG->prefix . 'user u WHERE deleted = 0 AND confirmed = 1 AND mnethostid = ' . $CFG->mnet_localhost_id . ' ' . $select . 'ORDER BY lastname ASC, firstname ASC'; $availableusers = get_recordset_sql($sql, 0, MAX_USERS_PER_PAGE); /// Print the page /// get language strings $str = get_strings(array('enrolmentplugins', 'configuration', 'users', 'administration')); /// Get some language strings $strpotentialusers = get_string('potentialusers', 'role'); $strexistingusers = get_string('existingusers', 'role'); $straction = get_string('assignroles', 'role'); $strroletoassign = get_string('roletoassign', 'role'); $strcurrentcontext = get_string('currentcontext', 'role'); $strsearch = get_string('search'); $strshowall = get_string('showall'); $strparticipants = get_string('participants'); $strsearchresults = get_string('searchresults'); admin_externalpage_print_header(); print_box('<strong>' . s($mnet_peer->name) . ' : ' . format_string($course->shortname) . ' ' . format_string($course->fullname) . '</strong><br />' . get_string("enrolcourseenrol_desc", "mnet"));
/** * Update grades by firing grade_updated event * * @param object $assignment null means all assignments * @param int $userid specific user only, 0 mean all */ function assignment_update_grades($assignment = null, $userid = 0, $nullifnone = true) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once $CFG->libdir . '/gradelib.php'; } if ($assignment != null) { if ($grades = assignment_get_user_grades($assignment, $userid)) { foreach ($grades as $k => $v) { if ($v->rawgrade == -1) { $grades[$k]->rawgrade = null; } } assignment_grade_item_update($assignment); grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades); } } else { $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid\n FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m\n WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id"; if ($rs = get_recordset_sql($sql)) { if ($rs->RecordCount() > 0) { while ($assignment = rs_fetch_next_record($rs)) { assignment_grade_item_update($assignment); if ($assignment->grade != 0) { assignment_update_grades($assignment); } } } rs_close($rs); } } }
/** * Clean up the tag tables, making sure all tagged object still exists. * * This should normally not be necessary, but in case related tags are not deleted * when the tagged record is removed, this should be done once in a while, perhaps on * an occasional cron run. On a site with lots of tags, this could become an expensive * function to call: don't run at peak time. */ function tag_cleanup() { global $CFG; $instances = get_recordset('tag_instance'); // cleanup tag instances while ($instance = rs_fetch_next_record($instances)) { $delete = false; if (!record_exists('tag', 'id', $instance->tagid)) { // if the tag has been removed, instance should be deleted. $delete = true; } else { switch ($instance->itemtype) { case 'user': // users are marked as deleted, but not actually deleted if (record_exists('user', 'id', $instance->itemid, 'deleted', 1)) { $delete = true; } break; default: // anything else, if the instance is not there, delete. if (!record_exists($instance->itemtype, 'id', $instance->itemid)) { $delete = true; } break; } } if ($delete) { tag_delete_instance($instance->itemtype, $instance->itemid, $instance->tagid); //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER); } } rs_close($instances); // TODO: this will only clean tags of type 'default'. This is good as // it won't delete 'official' tags, but the day we get more than two // types, we need to fix this. $unused_tags = get_recordset_sql("SELECT tg.id FROM {$CFG->prefix}tag tg WHERE tg.tagtype = 'default' AND NOT EXISTS (" . "SELECT 'x' FROM {$CFG->prefix}tag_instance ti WHERE ti.tagid = tg.id)"); // cleanup tags while ($unused_tag = rs_fetch_next_record($unused_tags)) { tag_delete($unused_tag->id); //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER); } rs_close($unused_tags); }
function assignment_print_overview($courses, &$htmlarray) { global $USER, $CFG; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($assignments = get_all_instances_in_courses('assignment', $courses))) { return; } $assignmentids = array(); // Do assignment_base::isopen() here without loading the whole thing for speed foreach ($assignments as $key => $assignment) { $time = time(); if ($assignment->timedue) { if ($assignment->preventlate) { $isopen = $assignment->timeavailable <= $time && $time <= $assignment->timedue; } else { $isopen = $assignment->timeavailable <= $time; } } if (empty($isopen) || empty($assignment->timedue)) { unset($assignments[$key]); } else { $assignmentids[] = $assignment->id; } } if (empty($assignmentids)) { // no assigments to look at - we're done return true; } $strduedate = get_string('duedate', 'assignment'); $strduedateno = get_string('duedateno', 'assignment'); $strgraded = get_string('graded', 'assignment'); $strnotgradedyet = get_string('notgradedyet', 'assignment'); $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment'); $strsubmitted = get_string('submitted', 'assignment'); $strassignment = get_string('modulename', 'assignment'); $strreviewed = get_string('reviewed', 'assignment'); // NOTE: we do all possible database work here *outside* of the loop to ensure this scales // build up and array of unmarked submissions indexed by assigment id/ userid // for use where the user has grading rights on assigment $rs = get_recordset_sql("SELECT id, assignment, userid \n FROM {$CFG->prefix}assignment_submissions\n WHERE teacher = 0 AND timemarked = 0\n AND assignment IN (" . implode(',', $assignmentids) . ")"); $unmarkedsubmissions = array(); while ($ra = rs_fetch_next_record($rs)) { $unmarkedsubmissions[$ra->assignment][$ra->userid] = $ra->id; } rs_close($rs); // get all user submissions, indexed by assigment id $mysubmissions = get_records_sql("SELECT assignment, timemarked, teacher, grade\n FROM {$CFG->prefix}assignment_submissions \n WHERE userid = {$USER->id} AND \n assignment IN (" . implode(',', $assignmentids) . ")"); foreach ($assignments as $assignment) { $str = '<div class="assignment overview"><div class="name">' . $strassignment . ': ' . '<a ' . ($assignment->visible ? '' : ' class="dimmed"') . 'title="' . $strassignment . '" href="' . $CFG->wwwroot . '/mod/assignment/view.php?id=' . $assignment->coursemodule . '">' . $assignment->name . '</a></div>'; if ($assignment->timedue) { $str .= '<div class="info">' . $strduedate . ': ' . userdate($assignment->timedue) . '</div>'; } else { $str .= '<div class="info">' . $strduedateno . '</div>'; } $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule); if (has_capability('mod/assignment:grade', $context)) { // count how many people can submit $submissions = 0; // init if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) { foreach ($students as $student) { if (isset($unmarkedsubmissions[$assignment->id][$student->id])) { $submissions++; } } } if ($submissions) { $str .= get_string('submissionsnotgraded', 'assignment', $submissions); } } else { if (isset($mysubmissions[$assignment->id])) { $submission = $mysubmissions[$assignment->id]; if ($submission->teacher == 0 && $submission->timemarked == 0) { $str .= $strsubmitted . ', ' . $strnotgradedyet; } else { if ($submission->grade <= 0) { $str .= $strsubmitted . ', ' . $strreviewed; } else { $str .= $strsubmitted . ', ' . $strgraded; } } } else { $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue); } } $str .= '</div>'; if (empty($htmlarray[$assignment->course]['assignment'])) { $htmlarray[$assignment->course]['assignment'] = $str; } else { $htmlarray[$assignment->course]['assignment'] .= $str; } } }
/** * Daily cron. It executes at settlement time (default is 00:05). * * @access private */ function cron_daily() { global $CFG, $SITE; require_once $CFG->dirroot . '/enrol/authorize/authorizenetlib.php'; $oneday = 86400; $timenow = time(); $onepass = $timenow - $oneday; $settlementtime = authorize_getsettletime($timenow); $timediff30 = $settlementtime - 30 * $oneday; // Delete orders that no transaction was made. $select = "(status='" . AN_STATUS_NONE . "') AND (timecreated<'{$timediff30}')"; delete_records_select('enrol_authorize', $select); // Pending orders are expired with in 30 days. $select = "(status='" . AN_STATUS_AUTH . "') AND (timecreated<'{$timediff30}')"; execute_sql("UPDATE {$CFG->prefix}enrol_authorize SET status='" . AN_STATUS_EXPIRE . "' WHERE {$select}", false); // Delete expired orders 60 days later. $timediff60 = $settlementtime - 60 * $oneday; $select = "(status='" . AN_STATUS_EXPIRE . "') AND (timecreated<'{$timediff60}')"; delete_records_select('enrol_authorize', $select); // XXX TODO SEND EMAIL to 'enrol/authorize:uploadcsv' // get_users_by_capability() does not handling user level resolving // After user resolving, get_admin() to get_users_by_capability() $adminuser = get_admin(); $select = "status IN(" . AN_STATUS_UNDERREVIEW . "," . AN_STATUS_APPROVEDREVIEW . ") AND (timecreated<'{$onepass}') AND (timecreated>'{$timediff60}')"; $count = count_records_select('enrol_authorize', $select); if ($count) { $a = new stdClass(); $a->count = $count; $a->course = $SITE->shortname; $subject = get_string('pendingechecksubject', 'enrol_authorize', $a); $a = new stdClass(); $a->count = $count; $a->url = $CFG->wwwroot . '/enrol/authorize/uploadcsv.php'; $message = get_string('pendingecheckemail', 'enrol_authorize', $a); @email_to_user($adminuser, $adminuser, $subject, $message); } // Daily warning email for pending orders expiring. if (empty($CFG->an_emailexpired)) { return; // not enabled } // Pending orders count will be expired. $timediffem = $settlementtime - (30 - intval($CFG->an_emailexpired)) * $oneday; $select = "(status='" . AN_STATUS_AUTH . "') AND (timecreated<'{$timediffem}') AND (timecreated>'{$timediff30}')"; $count = count_records_select('enrol_authorize', $select); if (!$count) { return; } // Email to admin $a = new stdClass(); $a->pending = $count; $a->days = $CFG->an_emailexpired; $a->course = $SITE->shortname; $subject = get_string('pendingorderssubject', 'enrol_authorize', $a); $a = new stdClass(); $a->pending = $count; $a->days = $CFG->an_emailexpired; $a->course = $SITE->fullname; $a->enrolurl = "{$CFG->wwwroot}/{$CFG->admin}/enrol_config.php?enrol=authorize"; $a->url = $CFG->wwwroot . '/enrol/authorize/index.php?status=' . AN_STATUS_AUTH; $message = get_string('pendingordersemail', 'enrol_authorize', $a); email_to_user($adminuser, $adminuser, $subject, $message); // Email to teachers if (empty($CFG->an_emailexpiredteacher)) { return; // email feature disabled for teachers. } $sorttype = empty($CFG->an_sorttype) ? 'ttl' : $CFG->an_sorttype; $sql = "SELECT e.courseid, e.currency, c.fullname, c.shortname,\n COUNT(e.courseid) AS cnt, SUM(e.amount) as ttl\n FROM {$CFG->prefix}enrol_authorize e\n INNER JOIN {$CFG->prefix}course c ON c.id = e.courseid\n WHERE (e.status = " . AN_STATUS_AUTH . ")\n AND (e.timecreated < {$timediffem})\n AND (e.timecreated > {$timediff30})\n GROUP BY e.courseid\n ORDER BY {$sorttype} DESC"; for ($rs = get_recordset_sql($sql); $courseinfo = rs_fetch_next_record($rs);) { $lastcourse = $courseinfo->courseid; $context = get_context_instance(CONTEXT_COURSE, $lastcourse); if ($paymentmanagers = get_users_by_capability($context, 'enrol/authorize:managepayments')) { $a = new stdClass(); $a->course = $courseinfo->shortname; $a->pending = $courseinfo->cnt; $a->days = $CFG->an_emailexpired; $subject = get_string('pendingorderssubject', 'enrol_authorize', $a); $a = new stdClass(); $a->course = $courseinfo->fullname; $a->pending = $courseinfo->cnt; $a->currency = $courseinfo->currency; $a->sumcost = $courseinfo->ttl; $a->days = $CFG->an_emailexpired; $a->url = $CFG->wwwroot . '/enrol/authorize/index.php?course=' . $lastcourse . '&status=' . AN_STATUS_AUTH; $message = get_string('pendingordersemailteacher', 'enrol_authorize', $a); foreach ($paymentmanagers as $paymentmanager) { email_to_user($paymentmanager, $adminuser, $subject, $message); } } } rs_close($rs); }
function main_upgrade($oldversion = 0) { global $CFG, $THEME, $db; $result = true; if ($oldversion < 2003010101) { delete_records("log_display", "module", "user"); $new->module = "user"; $new->action = "view"; $new->mtable = "user"; $new->field = "CONCAT(firstname,\" \",lastname)"; insert_record("log_display", $new); delete_records("log_display", "module", "course"); $new->module = "course"; $new->action = "view"; $new->mtable = "course"; $new->field = "fullname"; insert_record("log_display", $new); $new->action = "update"; insert_record("log_display", $new); $new->action = "enrol"; insert_record("log_display", $new); } //support user based course creating if ($oldversion < 2003032400) { execute_sql("CREATE TABLE {$CFG->prefix}user_coursecreators (\n id int8 SERIAL PRIMARY KEY,\n userid int8 NOT NULL default '0'\n )"); } if ($oldversion < 2003041400) { table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score"); } if ($oldversion < 2003042104) { // Try to update permissions of all files if ($files = get_directory_list($CFG->dataroot)) { echo "Attempting to update permissions for all files... ignore any errors."; foreach ($files as $file) { echo "{$CFG->dataroot}/{$file}<br />"; @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions); } } } if ($oldversion < 2003042400) { // Rebuild all course caches, because of changes to do with visible variable if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) { require_once "{$CFG->dirroot}/course/lib.php"; foreach ($courses as $course) { $modinfo = serialize(get_array_of_activities($course->id)); if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) { notify("Could not cache module information for course '" . format_string($course->fullname) . "'!"); } } } } if ($oldversion < 2003042500) { // Convert all usernames to lowercase. $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user"); $cerrors = ""; $rarray = array(); foreach ($users as $user) { // Check for possible conflicts $lcname = trim(moodle_strtolower($user->username)); if (in_array($lcname, $rarray)) { $cerrors .= $user->id . "->" . $lcname . '<br/>'; } else { array_push($rarray, $lcname); } } if ($cerrors != '') { notify("Error: Cannot convert usernames to lowercase. \n Following usernames would overlap (id->username):<br/> {$cerrors} . \n Please resolve overlapping errors."); $result = false; } $cerrors = ""; echo "Checking userdatabase:<br />"; foreach ($users as $user) { $lcname = trim(moodle_strtolower($user->username)); if ($lcname != $user->username) { $convert = set_field("user", "username", $lcname, "id", $user->id); if (!$convert) { if ($cerrors) { $cerrors .= ", "; } $cerrors .= $item; } else { echo "."; } } } if ($cerrors != '') { notify("There were errors when converting following usernames to lowercase. \n '{$cerrors}' . Sorry, but you will need to fix your database by hand."); $result = false; } } if ($oldversion < 2003042700) { /// Changing to multiple indexes execute_sql(" CREATE INDEX {$CFG->prefix}log_coursemoduleaction_idx ON {$CFG->prefix}log (course,module,action) "); execute_sql(" CREATE INDEX {$CFG->prefix}log_courseuserid_idx ON {$CFG->prefix}log (course,userid) "); } if ($oldversion < 2003042801) { execute_sql("CREATE TABLE {$CFG->prefix}course_display (\n id SERIAL PRIMARY KEY,\n course integer NOT NULL default '0',\n userid integer NOT NULL default '0',\n display integer NOT NULL default '0'\n )"); execute_sql("CREATE INDEX {$CFG->prefix}course_display_courseuserid_idx ON {$CFG->prefix}course_display (course,userid)"); } if ($oldversion < 2003050400) { table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", ""); } if ($oldversion < 2003050401) { table_column("user", "", "lang", "VARCHAR", "5", "", "{$CFG->lang}", "NOT NULL", ""); } if ($oldversion < 2003050900) { table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", ""); } if ($oldversion < 2003050902) { if (get_records("modules", "name", "pgassignment")) { 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"); } } if ($oldversion < 2003051600) { 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"); } if ($oldversion < 2003052300) { table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor"); } if ($oldversion < 2003072100) { table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker"); } if ($oldversion < 2003072101) { table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", ""); } if ($oldversion < 2003072800) { 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"); flush(); execute_sql(" CREATE INDEX {$CFG->prefix}log_timecoursemoduleaction_idx ON {$CFG->prefix}log (time,course,module,action) "); execute_sql(" CREATE INDEX {$CFG->prefix}user_students_courseuserid_idx ON {$CFG->prefix}user_students (course,userid) "); execute_sql(" CREATE INDEX {$CFG->prefix}user_teachers_courseuserid_idx ON {$CFG->prefix}user_teachers (course,userid) "); } if ($oldversion < 2003072802) { table_column("course_categories", "", "description", "text", "", "", ""); table_column("course_categories", "", "parent", "integer", "10", "unsigned"); table_column("course_categories", "", "sortorder", "integer", "10", "unsigned"); table_column("course_categories", "", "courseorder", "text", "", "", ""); table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1"); table_column("course_categories", "", "timemodified", "integer", "10", "unsigned"); } if ($oldversion < 2003080400) { 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."); table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned"); table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category"); } if ($oldversion < 2003081502) { execute_sql(" CREATE TABLE {$CFG->prefix}scale (\n id SERIAL PRIMARY KEY,\n courseid integer NOT NULL default '0',\n userid integer NOT NULL default '0',\n name varchar(255) NOT NULL default '',\n scale text,\n description text,\n timemodified integer NOT NULL default '0'\n )"); } if ($oldversion < 2003081503) { table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed"); get_scales_menu(0); // Just to force the default scale to be created } if ($oldversion < 2003081600) { table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role"); table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall"); } if ($oldversion < 2003081900) { table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0"); } if ($oldversion < 2003080700) { notify("Cleaning up categories and course ordering..."); fix_course_sortorder(); } if ($oldversion < 2003082001) { table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format"); } if ($oldversion < 2003082101) { execute_sql(" CREATE INDEX {$CFG->prefix}course_category_idx ON {$CFG->prefix}course (category) "); } if ($oldversion < 2003082702) { execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') "); } if ($oldversion < 2003091000) { # Old field that was never added! table_column("course", "", "showrecent", "integer", "10", "unsigned", "1", "", "numsections"); } if ($oldversion < 2003091400) { table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score"); } if ($oldversion < 2003092900) { table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker"); } if ($oldversion < 2003102700) { table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time"); table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified"); $db->debug = false; $CFG->debug = 0; notify("Calculating access times. Please wait - this may take a long time on big sites...", "green"); flush(); if ($courses = get_records_select("course", "category > 0")) { foreach ($courses as $course) { notify("Processing " . format_string($course->fullname) . " ...", "green"); flush(); if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) { foreach ($users as $user) { $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log WHERE course = '{$course->id}' and userid = '{$user->userid}' ORDER by time DESC"); if (empty($loginfo->time)) { $loginfo->time = 0; } execute_sql("UPDATE {$CFG->prefix}user_teachers SET timeaccess = '{$loginfo->time}' \n WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false); } } if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) { foreach ($users as $user) { $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log \n WHERE course = '{$course->id}' and userid = '{$user->userid}' \n ORDER by time DESC"); if (empty($loginfo->time)) { $loginfo->time = 0; } execute_sql("UPDATE {$CFG->prefix}user_students \n SET timeaccess = '{$loginfo->time}' \n WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false); } } } } notify("All courses complete.", "green"); $db->debug = true; } if ($oldversion < 2003103100) { table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes"); } if ($oldversion < 2003121600) { execute_sql("CREATE TABLE {$CFG->prefix}groups (\n id SERIAL PRIMARY KEY,\n courseid integer NOT NULL default '0',\n name varchar(255) NOT NULL default '',\n description text,\n lang varchar(10) NOT NULL default '',\n picture integer NOT NULL default '0',\n timecreated integer NOT NULL default '0',\n timemodified integer NOT NULL default '0'\n )"); execute_sql("CREATE INDEX {$CFG->prefix}groups_idx ON {$CFG->prefix}groups (courseid) "); execute_sql("CREATE TABLE {$CFG->prefix}groups_members (\n id SERIAL PRIMARY KEY,\n groupid integer NOT NULL default '0',\n userid integer NOT NULL default '0',\n timeadded integer NOT NULL default '0'\n )"); execute_sql("CREATE INDEX {$CFG->prefix}groups_members_idx ON {$CFG->prefix}groups_members (groupid) "); } if ($oldversion < 2003122600) { table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible"); table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode"); } if ($oldversion < 2004010900) { table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible"); } if ($oldversion < 2004011700) { modify_database("", "CREATE TABLE prefix_event (\n id SERIAL PRIMARY KEY,\n name varchar(255) NOT NULL default '',\n description text,\n courseid integer NOT NULL default '0',\n groupid integer NOT NULL default '0',\n userid integer NOT NULL default '0',\n modulename varchar(20) NOT NULL default '',\n instance integer NOT NULL default '0',\n eventtype varchar(20) NOT NULL default '',\n timestart integer NOT NULL default '0',\n timeduration integer NOT NULL default '0',\n timemodified integer NOT NULL default '0'\n ); "); modify_database("", "CREATE INDEX prefix_event_courseid_idx ON prefix_event (courseid);"); modify_database("", "CREATE INDEX prefix_event_userid_idx ON prefix_event (userid);"); } if ($oldversion < 2004012800) { modify_database("", "CREATE TABLE prefix_user_preferences (\n id SERIAL PRIMARY KEY,\n userid integer NOT NULL default '0',\n name varchar(50) NOT NULL default '',\n value varchar(255) NOT NULL default ''\n ); "); modify_database("", "CREATE INDEX prefix_user_preferences_useridname_idx ON prefix_user_preferences (userid,name);"); } if ($oldversion < 2004012900) { table_column("config", "value", "value", "text", "", "", ""); } if ($oldversion < 2004013101) { table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module"); set_config("upgrade", "logs"); } if ($oldversion < 2004020900) { table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce"); } if ($oldversion < 2004020903) { modify_database("", "CREATE TABLE prefix_cache_text (\n id SERIAL PRIMARY KEY,\n md5key varchar(32) NOT NULL default '',\n formattedtext text,\n timemodified integer NOT NULL default '0'\n );"); } if ($oldversion < 2004021000) { $textfilters = array(); for ($i = 1; $i <= 10; $i++) { $variable = "textfilter{$i}"; if (!empty($CFG->{$variable})) { /// No more filters if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) { $textfilters[] = $CFG->{$variable}; } } } $textfilters = implode(',', $textfilters); if (empty($textfilters)) { $textfilters = 'mod/glossary/dynalink.php'; } set_config('textfilters', $textfilters); } if ($oldversion < 2004021201) { modify_database("", "CREATE TABLE prefix_cache_filters (\n id SERIAL PRIMARY KEY,\n filter varchar(32) NOT NULL default '',\n version integer NOT NULL default '0',\n md5key varchar(32) NOT NULL default '',\n rawtext text,\n timemodified integer NOT NULL default '0'\n );"); modify_database("", "CREATE INDEX prefix_cache_filters_filtermd5key_idx ON prefix_cache_filters (filter,md5key);"); modify_database("", "CREATE INDEX prefix_cache_text_md5key_idx ON prefix_cache_text (md5key);"); } if ($oldversion < 2004021500) { table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture"); } if ($oldversion < 2004021700) { if (!empty($CFG->textfilters)) { $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters); set_config("textfilters", $CFG->textfilters); } } if ($oldversion < 2004022000) { table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email"); } if ($oldversion < 2004022200) { /// Final renaming I hope. :-) if (!empty($CFG->textfilters)) { $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters); $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters); $textfilters = explode(',', $CFG->textfilters); foreach ($textfilters as $key => $textfilter) { $textfilters[$key] = trim($textfilter); } set_config("textfilters", implode(',', $textfilters)); } } if ($oldversion < 2004030702) { /// Because of the renaming of Czech language pack execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'"); execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'"); } if ($oldversion < 2004041800) { /// Integrate Block System from contrib table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo"); } if ($oldversion < 2004042600) { /// Rebuild course caches for resource icons //include_once("$CFG->dirroot/course/lib.php"); //rebuild_course_cache(); } if ($oldversion < 2004042700) { /// Increase size of lang fields table_column("user", "lang", "lang", "varchar", "10", "", "en"); table_column("groups", "lang", "lang", "varchar", "10", "", ""); table_column("course", "lang", "lang", "varchar", "10", "", ""); } if ($oldversion < 2004042701) { /// Add hiddentopics field to control hidden topics behaviour #table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible"); #See 'hiddensections' further down } if ($oldversion < 2004042702) { /// Add a format field for the description table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description"); } if ($oldversion < 2004043001) { /// Add hiddentopics field to control hidden topics behaviour table_column("course", "", "hiddensections", "integer", "2", "unsigned", "0", "not null", "visible"); } if ($oldversion < 2004050400) { /// add a visible field for events table_column("event", "", "visible", "smallint", "1", "", "1", "not null", "timeduration"); if ($events = get_records('event')) { foreach ($events as $event) { if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) { if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) { set_field('event', 'visible', 0, 'id', $event->id); } } } } } if ($oldversion < 2004052800) { /// First version tagged "1.4 development", version.php 1.227 set_config('siteblocksadded', true); /// This will be used later by the block upgrade } if ($oldversion < 2004053000) { /// set defaults for site course $site = get_site(); set_field('course', 'numsections', 0, 'id', $site->id); set_field('course', 'groupmodeforce', 1, 'id', $site->id); set_field('course', 'teacher', get_string('administrator'), 'id', $site->id); set_field('course', 'teachers', get_string('administrators'), 'id', $site->id); set_field('course', 'student', get_string('user'), 'id', $site->id); set_field('course', 'students', get_string('users'), 'id', $site->id); } if ($oldversion < 2004060100) { set_config('digestmailtime', 0); table_column('user', "", 'maildigest', 'smallint', '1', '', '0', 'not null', 'mailformat'); } if ($oldversion < 2004062400) { table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall'); table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall'); } if ($oldversion < 2004062401) { table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname'); execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname'); // By default } if ($oldversion < 2004062600) { table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang'); } if ($oldversion < 2004072900) { table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate'); } if ($oldversion < 2004072901) { // Fixing error in schema if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) { delete_records('log_display', 'module', 'course', 'action', 'update'); insert_record('log_display', $record, false); } } if ($oldversion < 2004081200) { // Fixing version errors in some blocks set_field('blocks', 'version', 2004081200, 'name', 'admin'); set_field('blocks', 'version', 2004081200, 'name', 'calendar_month'); set_field('blocks', 'version', 2004081200, 'name', 'course_list'); } if ($oldversion < 2004081500) { // Adding new "auth" field to user table to allow more flexibility table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id'); execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'"); // Set everyone to 'manual' to be sure if ($admins = get_admins()) { // Set all the NON-admins to whatever the current auth module is $adminlist = array(); foreach ($admins as $user) { $adminlist[] = $user->id; } $adminlist = implode(',', $adminlist); execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})"); } } if ($oldversion < 2004082600) { //update auth-fields for external users // following code would not work in 1.8 /* include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php"); if (function_exists('auth_get_userlist')) { $externalusers = auth_get_userlist(); if (!empty($externalusers)){ $externalusers = '\''. implode('\',\'',$externalusers).'\''; execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username IN ($externalusers)"); } }*/ } if ($oldversion < 2004082900) { // Make sure guest is "manual" too. set_field('user', 'auth', 'manual', 'username', 'guest'); } /* Just commenteed unused fields out if ($oldversion < 2004090300) { // Add guid-field used in user syncronization table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth'); execute_sql("CREATE INDEX {$CFG->prefix}user_auth_guid_idx ON {$CFG->prefix}user (auth, guid)"); } */ if ($oldversion < 2004091900) { //Modify idnumber to hold longer keys set_field('user', 'auth', 'manual', 'username', 'guest'); table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', ''); execute_sql("DROP INDEX {$CFG->prefix}user_idnumber_idx ;", false); // added in case of conflicts with upgrade from 14stable execute_sql("DROP INDEX {$CFG->prefix}user_auth_idx ;", false); // added in case of conflicts with upgrade from 14stable execute_sql("CREATE INDEX {$CFG->prefix}user_idnumber_idx ON {$CFG->prefix}user (idnumber)"); execute_sql("CREATE INDEX {$CFG->prefix}user_auth_idx ON {$CFG->prefix}user (auth)"); } 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) table_column("config", "value", "value", "text", "", "", ""); } if ($oldversion < 2004093001) { // add new table for sessions storage execute_sql(" CREATE TABLE {$CFG->prefix}sessions (\n sesskey char(32) PRIMARY KEY,\n expiry integer NOT null,\n expireref varchar(64),\n data text NOT null\n );"); execute_sql(" CREATE INDEX {$CFG->prefix}sessions_expiry_idx ON {$CFG->prefix}sessions (expiry)"); } if ($oldversion < 2004111500) { // Update any users/courses using wrongly-named lang pack execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'"); execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'"); } if ($oldversion < 2004111700) { // add indexes- drop them first silently to avoid conflicts when upgrading. execute_sql("DROP INDEX {$CFG->prefix}course_idnumber_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}course_shortname_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_students_userid_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_teachers_userid_idx;", false); modify_database("", "CREATE INDEX {$CFG->prefix}course_idnumber_idx ON {$CFG->prefix}course (idnumber);"); modify_database("", "CREATE INDEX {$CFG->prefix}course_shortname_idx ON {$CFG->prefix}course (shortname);"); modify_database("", "CREATE INDEX {$CFG->prefix}user_students_userid_idx ON {$CFG->prefix}user_students (userid);"); modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_userid_idx ON {$CFG->prefix}user_teachers (userid);"); } if ($oldversion < 2004111700) { // add an index to event for timestart and timeduration- drop them first silently to avoid conflicts when upgrading. execute_sql("DROP INDEX {$CFG->prefix}event_timestart_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}event_timeduration_idx;", false); modify_database('', 'CREATE INDEX prefix_event_timestart_idx ON prefix_event (timestart);'); modify_database('', 'CREATE INDEX prefix_event_timeduration_idx ON prefix_event (timeduration);'); } if ($oldversion < 2004117000) { // add an index on the groups_members table- drop them first silently to avoid conflicts when upgrading. execute_sql("DROP INDEX {$CFG->prefix}groups_members_userid_idx;", false); modify_database('', 'CREATE INDEX prefix_groups_members_userid_idx ON prefix_groups_members (userid);'); } if ($oldversion < 2004111700) { //add indexes on modules and course_modules- drop them first silently to avoid conflicts when upgrading. execute_sql("DROP INDEX {$CFG->prefix}course_modules_visible_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}course_modules_course_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}course_modules_module_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}course_modules_instance_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}course_modules_deleted_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}modules_name_idx;", false); modify_database('', 'CREATE INDEX prefix_course_modules_visible_idx ON prefix_course_modules (visible);'); modify_database('', 'CREATE INDEX prefix_course_modules_course_idx ON prefix_course_modules (course);'); modify_database('', 'CREATE INDEX prefix_course_modules_module_idx ON prefix_course_modules (module);'); modify_database('', 'CREATE INDEX prefix_course_modules_instance_idx ON prefix_course_modules (instance);'); modify_database('', 'CREATE INDEX prefix_course_modules_deleted_idx ON prefix_course_modules (deleted);'); modify_database('', 'CREATE INDEX prefix_modules_name_idx ON prefix_modules (name);'); } if ($oldversion < 2004111700) { // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading execute_sql("DROP INDEX {$CFG->prefix}user_students_timeaccess_idx;", false); modify_database('', 'CREATE INDEX prefix_user_students_timeaccess_idx ON prefix_user_students (timeaccess);'); } if ($oldversion < 2004111700) { //add indexes on faux foreign keys - drop them first silently to avoid conflicts when upgrading. execute_sql("DROP INDEX {$CFG->prefix}course_sections_coursesection_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}scale_courseid_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_admins_userid_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_coursecreators_userid_idx;", false); modify_database('', 'CREATE INDEX prefix_course_sections_coursesection_idx ON prefix_course_sections (course,section);'); modify_database('', 'CREATE INDEX prefix_scale_courseid_idx ON prefix_scale (courseid);'); modify_database('', 'CREATE INDEX prefix_user_admins_userid_idx ON prefix_user_admins (userid);'); modify_database('', 'CREATE INDEX prefix_user_coursecreators_userid_idx ON prefix_user_coursecreators (userid);'); } if ($oldversion < 2004111700) { // make new indexes on user table. fix_course_sortorder(0, 0, 1); execute_sql("DROP INDEX {$CFG->prefix}course_category_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk;", false); modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder)"); execute_sql("DROP INDEX {$CFG->prefix}user_deleted_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_confirmed_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_firstname_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_lastname_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_city_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_country_idx;", false); execute_sql("DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false); modify_database("", "CREATE INDEX prefix_user_deleted_idx ON prefix_user (deleted)"); modify_database("", "CREATE INDEX prefix_user_confirmed_idx ON prefix_user (confirmed)"); modify_database("", "CREATE INDEX prefix_user_firstname_idx ON prefix_user (firstname)"); modify_database("", "CREATE INDEX prefix_user_lastname_idx ON prefix_user (lastname)"); modify_database("", "CREATE INDEX prefix_user_city_idx ON prefix_user (city)"); modify_database("", "CREATE INDEX prefix_user_country_idx ON prefix_user (country)"); modify_database("", "CREATE INDEX prefix_user_lastaccess_idx ON prefix_user (lastaccess)"); } if ($oldversion < 2004111700) { // one more index for email (for sorting) execute_sql("DROP INDEX {$CFG->prefix}user_email_idx;", false); modify_database('', 'CREATE INDEX prefix_user_email_idx ON prefix_user (email);'); } if ($oldversion < 2004112200) { // new 'enrol' field for enrolment tables table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null'); table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null'); modify_database("", "CREATE INDEX {$CFG->prefix}user_students_enrol_idx ON {$CFG->prefix}user_students (enrol);"); modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_enrol_idx ON {$CFG->prefix}user_teachers (enrol);"); } if ($oldversion < 2004112300) { // update log display to use correct postgres friendly sql execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='user' AND action='view' AND mtable='user'"); execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='course' AND action='user report' AND mtable='user'"); } if ($oldversion < 2004112400) { /// Delete duplicate enrolments /// and then tell the database course,userid is a unique combination if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) { foreach ($users as $user) { delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'"); } } flush(); // drop some indexes quietly -- they may or may not exist depending on what version // the user upgrades from execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_idx ", false); execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_uk ", false); modify_database('', 'CREATE UNIQUE INDEX prefix_user_students_courseuserid_uk ON prefix_user_students (course,userid);'); /// Delete duplicate teacher enrolments /// and then tell the database course,userid is a unique combination if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) { foreach ($users as $user) { delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'"); } } flush(); // drop some indexes quietly -- they may or may not exist depending on what version // the user upgrades from execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_idx ", false); execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_uk ", false); modify_database('', 'CREATE UNIQUE INDEX prefix_user_teachers_courseuserid_uk ON prefix_user_teachers (course,userid);'); } if ($oldversion < 2004112401) { // some postgres databases may have a non-unique index mislabeled unique. fix_course_sortorder(0, 0, 1); execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk ", false); execute_sql("DROP INDEX {$CFG->prefix}course_category_idx ", false); modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder);"); // odd! username was missing its unique index! // first silently drop it just in case... execute_sql("ALTER TABLE {$CFG->prefix}user DROP CONSTRAINT {$CFG->prefix}user_username_uk;", false); execute_sql("DROP INDEX {$CFG->prefix}user_username_uk", false); modify_database('', "CREATE UNIQUE INDEX prefix_user_username_uk ON prefix_user (username);"); } if ($oldversion < 2004112900) { table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed'); } if ($oldversion < 2004121400) { table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description'); } if ($oldversion < 2004121600) { modify_database('', "CREATE TABLE prefix_dst_preset (\n id SERIAL PRIMARY KEY,\n name varchar(48) NOT NULL default '',\n apply_offset integer NOT NULL default '0',\n activate_index integer NOT NULL default '1',\n activate_day integer NOT NULL default '1',\n activate_month integer NOT NULL default '1',\n activate_time char(5) NOT NULL default '03:00',\n deactivate_index integer NOT NULL default '1',\n deactivate_day integer NOT NULL default '1',\n deactivate_month integer NOT NULL default '2',\n deactivate_time char(5) NOT NULL default '03:00',\n last_change integer NOT NULL default '0',\n next_change integer NOT NULL default '0',\n current_offset integer NOT NULL default '0'\n );"); } if ($oldversion < 2004122800) { execute_sql("DROP TABLE {$CFG->prefix}message", false); execute_sql("DROP TABLE {$CFG->prefix}message_read", false); execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false); execute_sql("DROP INDEX {$CFG->prefix}message_useridfrom_idx", false); execute_sql("DROP INDEX {$CFG->prefix}message_useridto_idx", false); execute_sql("DROP INDEX {$CFG->prefix}message_read_useridfrom_idx", false); execute_sql("DROP INDEX {$CFG->prefix}message_read_useridto_idx", false); execute_sql("DROP INDEX {$CFG->prefix}message_contacts_useridcontactid_idx", false); modify_database('', "CREATE TABLE prefix_message (\n id SERIAL PRIMARY KEY,\n useridfrom integer NOT NULL default '0',\n useridto integer NOT NULL default '0',\n message text,\n timecreated integer NOT NULL default '0',\n messagetype varchar(50) NOT NULL default ''\n );\n\n CREATE INDEX prefix_message_useridfrom_idx ON prefix_message (useridfrom);\n CREATE INDEX prefix_message_useridto_idx ON prefix_message (useridto);\n\n CREATE TABLE prefix_message_read (\n id SERIAL PRIMARY KEY,\n useridfrom integer NOT NULL default '0',\n useridto integer NOT NULL default '0',\n message text,\n timecreated integer NOT NULL default '0',\n timeread integer NOT NULL default '0',\n messagetype varchar(50) NOT NULL default '',\n mailed integer NOT NULL default '0'\n );\n\n CREATE INDEX prefix_message_read_useridfrom_idx ON prefix_message_read (useridfrom);\n CREATE INDEX prefix_message_read_useridto_idx ON prefix_message_read (useridto);\n "); modify_database('', "CREATE TABLE prefix_message_contacts (\n id SERIAL PRIMARY KEY,\n userid integer NOT NULL default '0',\n contactid integer NOT NULL default '0',\n blocked integer NOT NULL default '0'\n );\n\n CREATE INDEX prefix_message_contacts_useridcontactid_idx ON prefix_message_contacts (userid,contactid);\n "); modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'firstname||\\' \\'||lastname');\n INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'firstname||\\' \\'||lastname');\n "); } if ($oldversion < 2004122801) { table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message'); table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message'); } if ($oldversion < 2005010100) { modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'firstname||\\' \\'||lastname');\n INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'firstname||\\' \\'||lastname');\n INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'firstname||\\' \\'||lastname');\n INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'firstname||\\' \\'||lastname');\n "); } if ($oldversion < 2005011000) { // Create a .htaccess file in dataroot, just in case if (!file_exists($CFG->dataroot . '/.htaccess')) { if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) { // For safety @fwrite($handle, "deny from all\r\nAllowOverride None\r\n"); @fclose($handle); notify("Created a default .htaccess file in {$CFG->dataroot}"); } } } if ($oldversion < 2005012500) { // add new table for meta courses. /* modify_database("","CREATE TABLE prefix_meta_course ( id SERIAL primary key, parent_course integer NOT NULL, child_course integer NOT NULL );"); modify_database("","CREATE INDEX prefix_meta_course_parent_idx ON prefix_meta_course (parent_course);"); modify_database("","CREATE INDEX prefix_meta_course_child_idx ON prefix_meta_course (child_course);"); table_column('course','','meta_course','integer','1','','0','not null'); */ // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it) } if ($oldversion < 2005012501) { //fix table names for consistency execute_sql("DROP TABLE {$CFG->prefix}meta_course", false); // drop silently execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false); // drop silently modify_database("", "CREATE TABLE prefix_course_meta (\n id SERIAL primary key,\n parent_course integer NOT NULL,\n child_course integer NOT NULL\n );"); modify_database("", "CREATE INDEX prefix_course_meta_parent_idx ON prefix_course_meta (parent_course);"); modify_database("", "CREATE INDEX prefix_course_meta_child_idx ON prefix_course_meta (child_course);"); table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null'); } if ($oldversion < 2005020100) { fix_course_sortorder(0, 1, 1); } if ($oldversion < 2005021000) { // New fields for theme choices table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang'); table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang'); table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang'); set_config('theme', 'standardwhite'); // Reset to a known good theme } if ($oldversion < 2005021700) { table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone'); } if ($oldversion < 2005021800) { modify_database("", "CREATE TABLE adodb_logsql (\n created timestamp NOT NULL,\n sql0 varchar(250) NOT NULL,\n sql1 text NOT NULL,\n params text NOT NULL,\n tracer text NOT NULL,\n timer decimal(16,6) NOT NULL\n );"); } if ($oldversion < 2005022400) { table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name'); table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family'); } if ($oldversion < 2005030501) { table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq'); table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq'); table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq'); table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq'); } if ($oldversion < 2005032300) { table_column('user', 'dstpreset', 'timezonename', 'varchar', '100'); execute_sql('UPDATE ' . $CFG->prefix . 'user SET timezonename = \'\''); } if ($oldversion < 2005032600) { execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false); modify_database('', "CREATE TABLE prefix_timezone (\n id SERIAL PRIMARY KEY,\n name varchar(100) NOT NULL default '',\n year integer NOT NULL default '0',\n rule varchar(20) NOT NULL default '',\n gmtoff integer NOT NULL default '0',\n dstoff integer NOT NULL default '0',\n dst_month integer NOT NULL default '0',\n dst_startday integer NOT NULL default '0',\n dst_weekday integer NOT NULL default '0',\n dst_skipweeks integer NOT NULL default '0',\n dst_time varchar(5) NOT NULL default '00:00',\n std_month integer NOT NULL default '0',\n std_startday integer NOT NULL default '0',\n std_weekday integer NOT NULL default '0',\n std_skipweeks integer NOT NULL default '0',\n std_time varchar(5) NOT NULL default '00:00'\n );"); } if ($oldversion < 2005032800) { modify_database('', "CREATE TABLE prefix_grade_category (\n id SERIAL PRIMARY KEY,\n name varchar(64) default NULL,\n courseid integer NOT NULL default '0',\n drop_x_lowest integer NOT NULL default '0',\n bonus_points integer NOT NULL default '0',\n hidden integer NOT NULL default '0',\n weight decimal(4,2) default '0.00'\n );"); modify_database('', "CREATE INDEX prefix_grade_category_courseid_idx ON prefix_grade_category (courseid);"); modify_database('', "CREATE TABLE prefix_grade_exceptions (\n id SERIAL PRIMARY KEY,\n courseid integer NOT NULL default '0',\n grade_itemid integer NOT NULL default '0',\n userid integer NOT NULL default '0'\n );"); modify_database('', "CREATE INDEX prefix_grade_exceptions_courseid_idx ON prefix_grade_exceptions (courseid);"); modify_database('', "CREATE TABLE prefix_grade_item (\n id SERIAL PRIMARY KEY,\n courseid integer default NULL,\n category integer default NULL,\n modid integer default NULL,\n cminstance integer default NULL,\n scale_grade float(11) default '1.0000000000',\n extra_credit integer NOT NULL default '0',\n sort_order integer NOT NULL default '0'\n );"); modify_database('', "CREATE INDEX prefix_grade_item_courseid_idx ON prefix_grade_item (courseid);"); modify_database('', "CREATE TABLE prefix_grade_letter (\n id SERIAL PRIMARY KEY,\n courseid integer NOT NULL default '0',\n letter varchar(8) NOT NULL default 'NA',\n grade_high decimal(6,2) NOT NULL default '100.00',\n grade_low decimal(6,2) NOT NULL default '0.00'\n );"); modify_database('', "CREATE INDEX prefix_grade_letter_courseid_idx ON prefix_grade_letter (courseid);"); modify_database('', "CREATE TABLE prefix_grade_preferences (\n id SERIAL PRIMARY KEY,\n courseid integer default NULL,\n preference integer NOT NULL default '0',\n value integer NOT NULL default '0'\n );"); modify_database('', "CREATE UNIQUE INDEX prefix_grade_prefs_courseidpref_uk ON prefix_grade_preferences (courseid,preference);"); } if ($oldversion < 2005033100) { // Get rid of defunct field from course modules table delete_records('course_modules', 'deleted', 1); // Delete old records we don't need any more execute_sql('DROP INDEX ' . $CFG->prefix . 'course_modules_deleted_idx;'); // Old index execute_sql('ALTER TABLE ' . $CFG->prefix . 'course_modules DROP deleted;'); // Old field } if ($oldversion < 2005040800) { table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99'); execute_sql(" ALTER TABLE {$CFG->prefix}user DROP timezonename "); } if ($oldversion < 2005041101) { require_once $CFG->libdir . '/filelib.php'; if (is_readable($CFG->dirroot . '/lib/timezones.txt')) { // Distribution file if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) { $db->debug = false; update_timezone_records($timezones); notify(count($timezones) . ' timezones installed'); $db->debug = true; } } } if ($oldversion < 2005041900) { // Copy all Dialogue entries into Messages, and hide Dialogue module if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated FROM ' . $CFG->prefix . 'dialogue_conversations c, ' . $CFG->prefix . 'dialogue_entries e WHERE e.conversationid = c.id')) { foreach ($entries as $entry) { $message = NULL; $message->useridfrom = $entry->userid; $message->useridto = $entry->recipientid; $message->message = addslashes($entry->text); $message->format = FORMAT_HTML; $message->timecreated = $entry->timecreated; $message->messagetype = 'direct'; insert_record('message_read', $message); } } set_field('modules', 'visible', 0, 'name', 'dialogue'); 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'); } if ($oldversion < 2005042100) { $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result; } if ($oldversion < 2005042400) { // Add user tracking prefs field. table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe'); } if ($oldversion < 2005051500) { // Add user tracking prefs field. table_column('grade_category', 'weight', 'weight', 'numeric(5,2)', '', '', '0.00', '', ''); } if ($oldversion < 2005053000) { // Add config_plugins table // this table was created on the MOODLE_15_STABLE branch // so it may already exist. Therefore we hide potential errors // (Postgres doesn't support CREATE TABLE IF NOT EXISTS) execute_sql("CREATE TABLE {$CFG->prefix}config_plugins (\n id SERIAL PRIMARY KEY,\n plugin varchar(100) NOT NULL default 'core',\n name varchar(100) NOT NULL default '',\n value text NOT NULL default '',\n CONSTRAINT {$CFG->prefix}config_plugins_plugin_name_uk UNIQUE (plugin, name)\n );", false); } if ($oldversion < 2005060200) { // migrate some config items to config_plugins table // NOTE: this block is in both postgres AND mysql upgrade // files. If you edit either, update the otherone. $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang"); if (!empty($CFG->auth)) { // if we have no auth, just pass foreach ($user_fields as $field) { $suffixes = array('', '_editlock', '_updateremote', '_updatelocal'); foreach ($suffixes as $suffix) { $key = 'auth_user_' . $field . $suffix; if (isset($CFG->{$key})) { // translate keys & values // to the new convention // this should support upgrading // even 1.5dev installs $newkey = $key; $newval = $CFG->{$key}; if ($suffix === '') { $newkey = 'field_map_' . $field; } elseif ($suffix === '_editlock') { $newkey = 'field_lock_' . $field; $newval = $newval == 1 ? 'locked' : 'unlocked'; // translate 0/1 to locked/unlocked } elseif ($suffix === '_updateremote') { $newkey = 'field_updateremote_' . $field; } elseif ($suffix === '_updatelocal') { $newkey = 'field_updatelocal_' . $field; $newval = $newval == 1 ? 'onlogin' : 'oncreate'; // translate 0/1 to locked/unlocked } if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) { notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} ."); $result = false; } } // end if isset key } // end foreach suffix } // end foreach field } } if ($oldversion < 2005060201) { // Close down the Attendance module, we are removing it from CVS. if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) { if (count_records('attendance')) { // We have some data, so should keep it set_field('modules', 'visible', 0, 'name', 'attendance'); notify('The Attendance module has been discontinued. If you really want to continue using it, you should download it individually from http://download.moodle.org/modules and install it, then reactivate it from Admin >> Configuration >> Modules. None of your existing data has been deleted, so all existing Attendance activities should re-appear.'); } else { // No data, so do a complete delete execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false); delete_records('modules', 'name', 'attendance'); notify("The Attendance module has been discontinued and removed from your site. \n You weren't using it anyway. ;-)"); } } } if ($oldversion < 2005060223) { // Mass cleanup of bad postgres upgrade scripts execute_sql("DROP TABLE {$CFG->prefix}attendance_roll", false); // There are no attendance module anymore modify_database('', 'ALTER TABLE prefix_config ALTER value SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_course ALTER metacourse SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_course ALTER theme SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_event ALTER repeatid SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_groups ALTER password SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_message ALTER format SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_message_read ALTER format SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_user ALTER aim DROP DEFAULT'); modify_database('', 'ALTER TABLE prefix_user ALTER idnumber DROP DEFAULT'); modify_database('', 'ALTER TABLE prefix_user ALTER msn DROP DEFAULT'); modify_database('', 'ALTER TABLE prefix_user ALTER policyagreed SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_user ALTER skype DROP DEFAULT'); modify_database('', 'ALTER TABLE prefix_user ALTER theme SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_user ALTER timezone SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_user ALTER trackforums SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_user ALTER yahoo DROP DEFAULT'); modify_database('', 'ALTER TABLE prefix_user_students ALTER enrol SET NOT NULL'); modify_database('', 'ALTER TABLE prefix_user_teachers ALTER enrol SET NOT NULL'); } if ($oldversion < 2005071700) { // Close down the Dialogue module, we are removing it from CVS. if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) { if (count_records('dialogue')) { // We have some data, so should keep it set_field('modules', 'visible', 0, 'name', 'dialogue'); notify('The Dialogue module has been discontinued. If you really want to continue using it, you should download it individually from http://download.moodle.org/modules and install it, then reactivate it from Admin >> Configuration >> Modules. None of your existing data has been deleted, so all existing Dialogue activities should re-appear.'); } else { // No data, so do a complete delete execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false); delete_records('modules', 'name', 'dialogue'); notify("The Dialogue module has been discontinued and removed from your site. \n You weren't using it anyway. ;-)"); } } } if ($oldversion < 2005072000) { // Add a couple fields to mdl_event to work towards iCal import/export table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible'); table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid'); } if ($oldversion < 2005072100) { // run the online assignment cleanup code include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php'; if (function_exists('online_assignment_cleanup')) { online_assignment_cleanup(); } } if ($oldversion < 2005072200) { // fix the mistakenly-added currency stuff from enrol/authorize execute_sql("DROP TABLE {$CFG->prefix}currencies", false); // drop silently execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false); $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency; table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost'); } if ($oldversion < 2005081600) { //set up the course requests table modify_database('', "CREATE TABLE prefix_course_request (\n id SERIAL PRIMARY KEY,\n fullname varchar(254) NOT NULL default '',\n shortname varchar(15) NOT NULL default '',\n summary text NOT NULL default '',\n reason text NOT NULL default '',\n requester INTEGER NOT NULL default 0\n );"); modify_database('', 'CREATE INDEX prefix_course_request_shortname_idx ON prefix_course_request (shortname);'); table_column('course', '', 'requested'); } if ($oldversion < 2005081601) { modify_database('', 'CREATE TABLE prefix_course_allowed_modules ( id SERIAL PRIMARY KEY, course INTEGER NOT NULL default 0, module INTEGER NOT NULL default 0 );'); modify_database('', 'CREATE INDEX prefix_course_allowed_modules_course_idx ON prefix_course_allowed_modules (course);'); modify_database('', 'CREATE INDEX prefix_course_allowed_modules_module_idx ON prefix_course_allowed_modules (module);'); table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null'); } if ($oldversion < 2005081700) { table_column('course_categories', '', 'depth', 'integer'); table_column('course_categories', '', 'path', 'varchar', '255'); } if ($oldversion < 2005090100) { // stats! modify_database('', 'CREATE TABLE prefix_stats_daily ( id SERIAL PRIMARY KEY, courseid INTEGER NOT NULL default 0, timeend INTEGER NOT NULL default 0, students INTEGER NOT NULL default 0, teachers INTEGER NOT NULL default 0, activestudents INTEGER NOT NULL default 0, activeteachers INTEGER NOT NULL default 0, studentreads INTEGER NOT NULL default 0, studentwrites INTEGER NOT NULL default 0, teacherreads INTEGER NOT NULL default 0, teacherwrites INTEGER NOT NULL default 0, logins INTEGER NOT NULL default 0, uniquelogins INTEGER NOT NULL default 0 );'); modify_database('', 'CREATE INDEX prefix_stats_daily_courseid_idx ON prefix_stats_daily (courseid);'); modify_database('', 'CREATE INDEX prefix_stats_daily_timeend_idx ON prefix_stats_daily (timeend);'); modify_database('', 'CREATE TABLE prefix_stats_weekly ( id SERIAL PRIMARY KEY, courseid INTEGER NOT NULL default 0, timeend INTEGER NOT NULL default 0, students INTEGER NOT NULL default 0, teachers INTEGER NOT NULL default 0, activestudents INTEGER NOT NULL default 0, activeteachers INTEGER NOT NULL default 0, studentreads INTEGER NOT NULL default 0, studentwrites INTEGER NOT NULL default 0, teacherreads INTEGER NOT NULL default 0, teacherwrites INTEGER NOT NULL default 0, logins INTEGER NOT NULL default 0, uniquelogins INTEGER NOT NULL default 0 );'); modify_database('', 'CREATE INDEX prefix_stats_weekly_courseid_idx ON prefix_stats_weekly (courseid);'); modify_database('', 'CREATE INDEX prefix_stats_weekly_timeend_idx ON prefix_stats_weekly (timeend);'); modify_database('', 'CREATE TABLE prefix_stats_monthly ( id SERIAL PRIMARY KEY, courseid INTEGER NOT NULL default 0, timeend INTEGER NOT NULL default 0, students INTEGER NOT NULL default 0, teachers INTEGER NOT NULL default 0, activestudents INTEGER NOT NULL default 0, activeteachers INTEGER NOT NULL default 0, studentreads INTEGER NOT NULL default 0, studentwrites INTEGER NOT NULL default 0, teacherreads INTEGER NOT NULL default 0, teacherwrites INTEGER NOT NULL default 0, logins INTEGER NOT NULL default 0, uniquelogins INTEGER NOT NULL default 0 );'); modify_database('', 'CREATE INDEX prefix_stats_monthly_courseid_idx ON prefix_stats_monthly (courseid);'); modify_database('', 'CREATE INDEX prefix_stats_monthly_timeend_idx ON prefix_stats_monthly (timeend);'); modify_database("", "CREATE TABLE prefix_stats_user_daily (\n id SERIAL PRIMARY KEY,\n courseid INTEGER NOT NULL default 0,\n userid INTEGER NOT NULL default 0,\n roleid INTEGER NOT NULL default 0,\n timeend INTEGER NOT NULL default 0,\n statsreads INTEGER NOT NULL default 0,\n statswrites INTEGER NOT NULL default 0,\n stattype varchar(30) NOT NULL default ''\n );"); modify_database("", "CREATE INDEX prefix_stats_user_daily_courseid_idx ON prefix_stats_user_daily (courseid);"); modify_database("", "CREATE INDEX prefix_stats_user_daily_userid_idx ON prefix_stats_user_daily (userid);"); modify_database("", "CREATE INDEX prefix_stats_user_daily_roleid_idx ON prefix_stats_user_daily (roleid);"); modify_database("", "CREATE INDEX prefix_stats_user_daily_timeend_idx ON prefix_stats_user_daily (timeend);"); modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n id SERIAL PRIMARY KEY,\n courseid INTEGER NOT NULL default 0,\n userid INTEGER NOT NULL default 0,\n roleid INTEGER NOT NULL default 0,\n timeend INTEGER NOT NULL default 0,\n statsreads INTEGER NOT NULL default 0,\n statswrites INTEGER NOT NULL default 0,\n stattype varchar(30) NOT NULL default ''\n );"); modify_database("", "CREATE INDEX prefix_stats_user_weekly_courseid_idx ON prefix_stats_user_weekly (courseid);"); modify_database("", "CREATE INDEX prefix_stats_user_weekly_userid_idx ON prefix_stats_user_weekly (userid);"); modify_database("", "CREATE INDEX prefix_stats_user_weekly_roleid_idx ON prefix_stats_user_weekly (roleid);"); modify_database("", "CREATE INDEX prefix_stats_user_weekly_timeend_idx ON prefix_stats_user_weekly (timeend);"); modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n id SERIAL PRIMARY KEY,\n courseid INTEGER NOT NULL default 0,\n userid INTEGER NOT NULL default 0,\n roleid INTEGER NOT NULL default 0,\n timeend INTEGER NOT NULL default 0,\n statsreads INTEGER NOT NULL default 0,\n statswrites INTEGER NOT NULL default 0,\n stattype varchar(30) NOT NULL default ''\n );"); modify_database("", "CREATE INDEX prefix_stats_user_monthly_courseid_idx ON prefix_stats_user_monthly (courseid);"); modify_database("", "CREATE INDEX prefix_stats_user_monthly_userid_idx ON prefix_stats_user_monthly (userid);"); modify_database("", "CREATE INDEX prefix_stats_user_monthly_roleid_idx ON prefix_stats_user_monthly (roleid);"); modify_database("", "CREATE INDEX prefix_stats_user_monthly_timeend_idx ON prefix_stats_user_monthly (timeend);"); } if ($oldversion < 2005100300) { table_column('course', '', 'expirynotify', 'integer', '1'); table_column('course', '', 'expirythreshold', 'integer'); table_column('course', '', 'notifystudents', 'integer', '1'); $new = new stdClass(); $new->name = 'lastexpirynotify'; $new->value = 0; insert_record('config', $new); } if ($oldversion < 2005100400) { table_column('course', '', 'enrollable', 'integer', '1', 'unsigned', '1'); table_column('course', '', 'enrolstartdate', 'integer'); table_column('course', '', 'enrolenddate', 'integer'); } if ($oldversion < 2005101200) { // add enrolment key to course_request. table_column('course_request', '', 'password', 'text'); } if ($oldversion < 2006030800) { # add extra indexes to log (see bug #4112) modify_database('', "CREATE INDEX prefix_log_userid_idx ON prefix_log (userid);"); modify_database('', "CREATE INDEX prefix_log_info_idx ON prefix_log (info);"); } if ($oldversion < 2006030900) { table_column('course', '', 'enrol', 'varchar', '20', '', ''); if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') { set_config('enrol_plugins_enabled', 'manual'); set_config('enrol', 'manual'); } else { set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol); } require_once "{$CFG->dirroot}/enrol/enrol.class.php"; $defaultenrol = enrolment_factory::factory($CFG->enrol); if (!method_exists($defaultenrol, 'print_entry')) { // switch enrollable to off for all courses in this case modify_database('', 'UPDATE prefix_course SET enrollable = 0'); } execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'"); execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''"); } if ($oldversion < 2006031000) { modify_database("", "CREATE TABLE prefix_post (\n id SERIAL PRIMARY KEY,\n userid INTEGER NOT NULL default 0,\n courseid INTEGER NOT NULL default 0,\n groupid INTEGER NOT NULL default 0,\n moduleid INTEGER NOT NULL default 0,\n coursemoduleid INTEGER NOT NULL default 0,\n subject varchar(128) NOT NULL default '',\n summary text,\n content text,\n uniquehash varchar(128) NOT NULL default '',\n rating INTEGER NOT NULL default 0,\n format INTEGER NOT NULL default 0,\n publishstate varchar(10) CHECK (publishstate IN ('draft','site','public')) NOT NULL default 'draft',\n lastmodified INTEGER NOT NULL default '0',\n created INTEGER NOT NULL default '0'\n );"); modify_database("", "CREATE INDEX id_user_idx ON prefix_post (id, courseid);"); modify_database("", "CREATE INDEX post_lastmodified_idx ON prefix_post (lastmodified);"); modify_database("", "CREATE INDEX post_subject_idx ON prefix_post (subject);"); modify_database("", "CREATE TABLE prefix_tags (\n id SERIAL PRIMARY KEY,\n type varchar(255) NOT NULL default 'official',\n userid INTEGER NOT NULL default 0,\n text varchar(255) NOT NULL default ''\n );"); modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n id SERIAL PRIMARY KEY,\n entryid integer NOT NULL default 0,\n tagid integer NOT NULL default 0,\n groupid integer NOT NULL default 0,\n courseid integer NOT NULL default 0,\n userid integer NOT NULL default 0\n );"); } if ($oldversion < 2006031400) { require_once "{$CFG->dirroot}/enrol/enrol.class.php"; $defaultenrol = enrolment_factory::factory($CFG->enrol); if (!method_exists($defaultenrol, 'print_entry')) { set_config('enrol', 'manual'); } } if ($oldversion < 2006032000) { table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id'); modify_database('', "CREATE INDEX post_module_idx ON prefix_post (module);"); modify_database('', "UPDATE prefix_post SET module = 'blog';"); } if ($oldversion < 2006032001) { table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid'); modify_database('', "CREATE INDEX bti_entryid_idx ON prefix_blog_tag_instance (entryid);"); modify_database('', "CREATE INDEX bti_tagid_idx ON prefix_blog_tag_instance (tagid);"); modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';"); } if ($oldversion < 2006040500) { // Add an index to course_sections that was never upgraded (bug 5100) execute_sql(" CREATE INDEX {$CFG->prefix}course_sections_coursesection_idx ON {$CFG->prefix}course_sections (course,section) ", false); } if ($oldversion < 2006041100) { table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible'); } if ($oldversion < 2006042400) { // Look through table log_display and get rid of duplicates. $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display'); // Drop the log_display table and create it back with an id field. execute_sql("DROP TABLE {$CFG->prefix}log_display", false); modify_database('', "CREATE TABLE prefix_log_display (\n id SERIAL PRIMARY KEY,\n module varchar(30) NOT NULL default '',\n action varchar(40) NOT NULL default '',\n mtable varchar(30) NOT NULL default '',\n field varchar(50) NOT NULL default '')"); // Add index to ensure that module and action combination is unique. modify_database('', 'CREATE INDEX prefix_log_display_moduleaction ON prefix_log_display (module,action)'); // Insert the records back in, sans duplicates. if ($rs) { while (!$rs->EOF) { $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')"; execute_sql($sql, false); $rs->MoveNext(); } rs_close($rs); } } // add 2 indexes to tags table if ($oldversion < 2006042401) { modify_database('', "CREATE INDEX tags_typeuserid_idx ON prefix_tags (type, userid);"); modify_database('', "CREATE INDEX tags_text_idx ON prefix_tags (text);"); } if ($oldversion < 2006050500) { table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null'); } if ($oldversion < 2006050502) { // Close down the Dialogue module, we are removing it from CVS. if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) { if (!count_records('dialogue_conversations')) { // no data, drop the extra tables execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_conversations', false); execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_entries', false); notify("The Dialogue module has been discontinued and removed from your site. \n You weren't using it anyway. ;-)"); } } table_column('course_request', 'password', 'password', 'varchar', '50', '', ''); table_column('course', 'currency', 'currency', 'varchar', '3'); modify_database('', 'ALTER TABLE prefix_course_categories ALTER COLUMN path SET DEFAULT \'\''); table_column('log_display', 'module', 'module', 'varchar', '20'); modify_database("", "DROP INDEX id_user_idx"); modify_database("", "DROP INDEX post_lastmodified_idx"); modify_database("", "DROP INDEX post_subject_idx"); modify_database('', "DROP INDEX bti_entryid_idx"); modify_database('', "DROP INDEX bti_tagid_idx"); modify_database('', "DROP INDEX post_module_idx"); modify_database('', "DROP INDEX tags_typeuserid_idx"); modify_database('', "DROP INDEX tags_text_idx"); modify_database("", "CREATE INDEX {$CFG->prefix}id_user_idx ON prefix_post (id, courseid);"); modify_database("", "CREATE INDEX {$CFG->prefix}post_lastmodified_idx ON prefix_post (lastmodified);"); modify_database("", "CREATE INDEX {$CFG->prefix}post_subject_idx ON prefix_post (subject);"); modify_database('', "CREATE INDEX {$CFG->prefix}bti_entryid_idx ON prefix_blog_tag_instance (entryid);"); modify_database('', "CREATE INDEX {$CFG->prefix}bti_tagid_idx ON prefix_blog_tag_instance (tagid);"); modify_database('', "CREATE INDEX {$CFG->prefix}post_module_idx ON prefix_post (moduleid);"); modify_database('', "CREATE INDEX {$CFG->prefix}tags_typeuserid_idx ON prefix_tags (type, userid);"); modify_database('', "CREATE INDEX {$CFG->prefix}tags_text_idx ON prefix_tags (text);"); } // renaming of reads and writes for stats_user_xyz if ($oldversion < 2006052400) { // change this later // we are using this because we want silent updates execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN reads TO statsreads", false); execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN writes TO statswrites", false); execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN reads TO statsreads", false); execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN writes TO statswrites", false); execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN reads TO statsreads", false); execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN writes TO statswrites", false); } // Adding some missing log actions if ($oldversion < 2006060400) { // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!) if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')"); } } //Renaming lastIP to lastip (all fields lowercase) if ($oldversion < 2006060900) { //Not needed unded PG because it stores fieldnames lowecase by default //Only if it exists (because MOODLE_16_STABLE could have done this work before. Bug 5763) //$fields = $db->MetaColumnNames($CFG->prefix.'user'); //if (in_array('lastIP',$fields)) { // table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "", "currentlogin"); //} } if ($oldversion < 2006080400) { modify_database('', "CREATE TABLE prefix_role (\n id SERIAL PRIMARY KEY,\n name varchar(255) NOT NULL default '',\n shortname varchar(100) NOT NULL default '', \n description text NOT NULL default '',\n sortorder integer NOT NULL default '0'\n );"); modify_database('', "CREATE TABLE prefix_context (\n id SERIAL PRIMARY KEY,\n level integer NOT NULL default 0,\n instanceid integer NOT NULL default 0\n );"); modify_database('', "CREATE TABLE prefix_role_assignments (\n id SERIAL PRIMARY KEY,\n roleid integer NOT NULL default 0,\n contextid integer NOT NULL default 0,\n userid integer NOT NULL default 0,\n hidden integer NOT NULL default 0,\n timestart integer NOT NULL default 0,\n timeend integer NOT NULL default 0,\n timemodified integer NOT NULL default 0,\n modifierid integer NOT NULL default 0,\n enrol varchar(20) NOT NULL default '',\n sortorder integer NOT NULL default '0'\n );"); modify_database('', "CREATE TABLE prefix_role_capabilities (\n id SERIAL PRIMARY KEY,\n contextid integer NOT NULL default 0,\n roleid integer NOT NULL default 0,\n capability varchar(255) NOT NULL default '',\n permission integer NOT NULL default 0,\n timemodified integer NOT NULL default 0,\n modifierid integer NOT NULL default 0\n );"); modify_database('', "CREATE TABLE prefix_role_deny_grant (\n id SERIAL PRIMARY KEY,\n roleid integer NOT NULL default '0',\n unviewableroleid integer NOT NULL default '0'\n );"); modify_database('', "CREATE TABLE prefix_capabilities ( \n id SERIAL PRIMARY KEY,\n name varchar(255) NOT NULL default '', \n captype varchar(50) NOT NULL default '', \n contextlevel integer NOT NULL default 0, \n component varchar(100) NOT NULL default ''\n );"); modify_database('', "CREATE TABLE prefix_role_names ( \n id SERIAL PRIMARY KEY,\n roleid integer NOT NULL default 0,\n contextid integer NOT NULL default 0, \n text text NOT NULL default ''\n );"); } if ($oldversion < 2006081000) { modify_database('', "CREATE INDEX prefix_role_sortorder_idx ON prefix_role (sortorder);"); modify_database('', "CREATE INDEX prefix_context_instanceid_idx ON prefix_context (instanceid);"); modify_database('', "CREATE UNIQUE INDEX prefix_context_levelinstanceid_idx ON prefix_context (level, instanceid);"); modify_database('', "CREATE INDEX prefix_role_assignments_roleid_idx ON prefix_role_assignments (roleid);"); modify_database('', "CREATE INDEX prefix_role_assignments_contextidid_idx ON prefix_role_assignments (contextid);"); modify_database('', "CREATE INDEX prefix_role_assignments_userid_idx ON prefix_role_assignments (userid);"); modify_database('', "CREATE UNIQUE INDEX prefix_role_assignments_contextidroleiduserid_idx ON prefix_role_assignments (contextid, roleid, userid);"); modify_database('', "CREATE INDEX prefix_role_assignments_sortorder_idx ON prefix_role_assignments (sortorder);"); modify_database('', "CREATE INDEX prefix_role_capabilities_roleid_idx ON prefix_role_capabilities (roleid);"); modify_database('', "CREATE INDEX prefix_role_capabilities_contextid_idx ON prefix_role_capabilities (contextid);"); modify_database('', "CREATE INDEX prefix_role_capabilities_modifierid_idx ON prefix_role_capabilities (modifierid);"); // MDL-10640 adding missing index from upgrade modify_database('', "CREATE INDEX prefix_role_capabilities_capability_idx ON prefix_role_capabilities (capability);"); modify_database('', "CREATE UNIQUE INDEX prefix_role_capabilities_roleidcontextidcapability_idx ON prefix_role_capabilities (roleid, contextid, capability);"); modify_database('', "CREATE INDEX prefix_role_deny_grant_roleid_idx ON prefix_role_deny_grant (roleid);"); modify_database('', "CREATE INDEX prefix_role_deny_grant_unviewableroleid_idx ON prefix_role_deny_grant (unviewableroleid);"); modify_database('', "CREATE UNIQUE INDEX prefix_role_deny_grant_roleidunviewableroleid_idx ON prefix_role_deny_grant (roleid, unviewableroleid);"); modify_database('', "CREATE UNIQUE INDEX prefix_capabilities_name_idx ON prefix_capabilities (name);"); modify_database('', "CREATE INDEX prefix_role_names_roleid_idx ON prefix_role_names (roleid);"); modify_database('', "CREATE INDEX prefix_role_names_contextid_idx ON prefix_role_names (contextid);"); modify_database('', "CREATE UNIQUE INDEX prefix_role_names_roleidcontextid_idx ON prefix_role_names (roleid, contextid);"); } if ($oldversion < 2006081700) { modify_database('', "DROP TABLE prefix_role_deny_grant"); modify_database('', "CREATE TABLE prefix_role_allow_assign ( \n id SERIAL PRIMARY KEY, \n roleid integer NOT NULL default '0', \n allowassign integer NOT NULL default '0' \n );"); modify_database('', "CREATE INDEX prefix_role_allow_assign_roleid_idx ON prefix_role_allow_assign (roleid);"); modify_database('', "CREATE INDEX prefix_role_allow_assign_allowassign_idx ON prefix_role_allow_assign (allowassign);"); modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_assign_roleidallowassign_idx ON prefix_role_allow_assign (roleid, allowassign);"); modify_database('', "CREATE TABLE prefix_role_allow_override ( \n id SERIAL PRIMARY KEY, \n roleid integer NOT NULL default '0', \n allowoverride integer NOT NULL default '0' \n );"); modify_database('', "CREATE INDEX prefix_role_allow_override_roleid_idx ON prefix_role_allow_override (roleid);"); modify_database('', "CREATE INDEX prefix_role_allow_override_allowoverride_idx ON prefix_role_allow_override (allowoverride);"); modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_override_roleidallowoverride_idx ON prefix_role_allow_override (roleid, allowoverride);"); } if ($oldversion < 2006082100) { execute_sql("DROP INDEX {$CFG->prefix}context_levelinstanceid_idx;", false); table_column('context', 'level', 'aggregatelevel', 'integer', '10', 'unsigned', '0', 'not null', ''); modify_database('', "CREATE UNIQUE INDEX prefix_context_aggregatelevelinstanceid_idx ON prefix_context (aggregatelevel, instanceid);"); } if ($oldversion < 2006082200) { table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', ''); } if ($oldversion < 2006082800) { table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor'); } if ($oldversion < 2006082900) { execute_sql("DROP TABLE {$CFG->prefix}sessions", true); execute_sql("\n CREATE TABLE {$CFG->prefix}sessions2 (\n sesskey VARCHAR(255) NOT NULL default '',\n expiry TIMESTAMP NOT NULL,\n expireref VARCHAR(255),\n created TIMESTAMP NOT NULL,\n modified TIMESTAMP NOT NULL,\n sessdata TEXT,\n CONSTRAINT {$CFG->prefix}sess_ses_pk PRIMARY KEY (sesskey)\n );", true); execute_sql("\n CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true); execute_sql("\n CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true); } if ($oldversion < 2006083002) { table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', ''); } if ($oldversion < 2006083100) { execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP NOT NULL"); execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP DEFAULT"); } if ($oldversion < 2006083101) { execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP NOT NULL"); execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP DEFAULT"); } if ($oldversion < 2006083102) { execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP NOT NULL"); execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP DEFAULT"); } if ($oldversion < 2006090200) { execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP NOT NULL"); execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP DEFAULT"); execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP NOT NULL"); execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP DEFAULT"); } // table to keep track of course page access times, used in online participants block, and participants list if ($oldversion < 2006091200) { execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n id SERIAL PRIMARY KEY, \n userid integer NOT NULL default 0,\n courseid integer NOT NULL default 0, \n timeaccess integer NOT NULL default 0\n );", true); execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_userid_idx ON {$CFG->prefix}user_lastaccess (userid);", true); execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_courseid_idx ON {$CFG->prefix}user_lastaccess (courseid);", true); execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}user_lastaccess_useridcourseid_idx ON {$CFG->prefix}user_lastaccess (userid, courseid);", true); } if (!empty($CFG->rolesactive) and $oldversion < 2006091212) { // Reload the guest roles completely with new defaults if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) { delete_records('capabilities'); $sitecontext = get_context_instance(CONTEXT_SYSTEM); foreach ($guestroles as $guestrole) { delete_records('role_capabilities', 'roleid', $guestrole->id); assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id); } } } if ($oldversion < 2006091700) { table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null'); } if ($oldversion < 2006091800) { delete_records('config', 'name', 'showsiteparticipantslist'); delete_records('config', 'name', 'requestedteachername'); delete_records('config', 'name', 'requestedteachersname'); delete_records('config', 'name', 'requestedstudentname'); delete_records('config', 'name', 'requestedstudentsname'); } if (!empty($CFG->rolesactive) and $oldversion < 2006091901) { if ($roles = get_records('role')) { $first = array_shift($roles); if (!empty($first->shortname)) { // shortnames already exist } else { table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name'); $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest'); foreach ($legacy_names as $name) { if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) { $i = ''; foreach ($roles as $role) { if (empty($role->shortname)) { $updated = new object(); $updated->id = $role->id; $updated->shortname = $name . $i; update_record('role', $updated); $i++; } } } } } } } /// Tables for customisable user profile fields if ($oldversion < 2006092000) { execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n id BIGSERIAL,\n name VARCHAR(255) NOT NULL default '',\n datatype VARCHAR(255) NOT NULL default '',\n categoryid BIGINT NOT NULL default 0,\n sortorder BIGINT NOT NULL default 0,\n required SMALLINT NOT NULL default 0,\n locked SMALLINT NOT NULL default 0,\n visible SMALLINT NOT NULL default 0,\n defaultdata TEXT,\n CONSTRAINT {$CFG->prefix}userinfofiel_id_pk PRIMARY KEY (id));", true); execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_field IS 'Customisable user profile fields';", true); execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n id BIGSERIAL,\n name VARCHAR(255) NOT NULL default '',\n sortorder BIGINT NOT NULL default 0,\n CONSTRAINT {$CFG->prefix}userinfocate_id_pk PRIMARY KEY (id));", true); execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_category IS 'Customisable fields categories';", true); execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n id BIGSERIAL,\n userid BIGINT NOT NULL default 0,\n fieldid BIGINT NOT NULL default 0,\n data TEXT NOT NULL,\n CONSTRAINT {$CFG->prefix}userinfodata_id_pk PRIMARY KEY (id));", true); execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_data IS 'Data for the customisable user fields';", true); } if ($oldversion < 2006092200) { table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', ''); /* execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false); execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false); // see 2006092409 below */ } if ($oldversion < 2006092302) { // fix sortorder first if needed if ($roles = get_all_roles()) { $i = 0; foreach ($roles as $rolex) { if ($rolex->sortorder != $i) { $r = new object(); $r->id = $rolex->id; $r->sortorder = $i; update_record('role', $r); } $i++; } } /* execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;"); execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)");*/ } if ($oldversion < 2006092400) { table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', ''); } if ($oldversion < 2006092409) { // ok, once more and now correctly! execute_sql("DROP INDEX \"aggregatelevel-instanceid\";", false); execute_sql("DROP INDEX \"contextlevel-instanceid\";", false); execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false); execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix;", false); execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix;", false); execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false); } if ($oldversion < 2006092410) { /// Convert all the PG unique keys into their corresponding unique indexes /// we don't want such keys inside Moodle 1.7 and above /// Look for all the UNIQUE CONSTRAINSTS existing in DB $uniquecons = get_records_sql("SELECT conname, relname, conkey, clas.oid AS tableoid\n FROM pg_constraint cons,\n pg_class clas\n WHERE cons.contype='u'\n AND cons.conrelid = clas.oid"); /// Iterate over every unique constraint, calculating its fields if ($uniquecons) { foreach ($uniquecons as $uniquecon) { $conscols = trim(trim($uniquecon->conkey, '}'), '{'); $conscols = explode(',', $conscols); /// Iterate over each column to fetch its name $indexcols = array(); foreach ($conscols as $conscol) { $column = get_record_sql("SELECT attname, attname\n FROM pg_attribute\n WHERE attrelid = {$uniquecon->tableoid}\n AND attnum = {$conscol}"); $indexcols[] = $column->attname; } /// Drop the old UNIQUE CONSTRAINT execute_sql("ALTER TABLE {$uniquecon->relname} DROP CONSTRAINT {$uniquecon->conname}", false); /// Create the new UNIQUE INDEX execute_sql("CREATE UNIQUE INDEX {$uniquecon->relname}_" . implode('_', $indexcols) . "_uix ON {$uniquecon->relname} (" . implode(', ', $indexcols) . ')', false); } } } if ($oldversion < 2006092601) { table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', ''); } ////// DO NOT ADD NEW THINGS HERE!! USE upgrade.php and the lib/ddllib.php functions. return $result; }
/// Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = get_recordset_sql("SELECT id, firstname, lastname\n FROM {$CFG->prefix}user\n WHERE confirmed = 0\n AND firstaccess > 0\n AND firstaccess < {$cuttime}"); while ($user = rs_fetch_next_record($rs)) { if (delete_records('user', 'id', $user->id)) { mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } } rs_close($rs); } flush(); /// Delete users who haven't completed profile within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = get_recordset_sql("SELECT id, username\n FROM {$CFG->prefix}user\n WHERE confirmed = 1\n AND lastaccess > 0\n AND lastaccess < {$cuttime}\n AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')"); while ($user = rs_fetch_next_record($rs)) { if (delete_records('user', 'id', $user->id)) { mtrace("Deleted not fully setup user {$user->username} ({$user->id})"); } } rs_close($rs); } flush(); /// Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; if (delete_records_select("log", "time < '{$loglifetime}'")) { mtrace("Deleted old log records"); }
/** * Retrieve all of the allowable permission types for the passed userid * @param int $userid -1 is a valid option, just sets to public permissions. **/ function rss_permissionlist($userid) { global $CFG; if ($userid == -1) { return array('PUBLIC', 'MODERATED', 'VIEW_ONLY'); } // Default permissions already availabled to logged-in users. $list = array('PUBLIC', 'LOGGED_IN', 'MODERATED', 'VIEW_ONLY'); // Find values for joined communities. $communities = recordset_to_array(get_recordset_sql("SELECT distinct u.ident as i, u.ident FROM " . $CFG->prefix . "friends e inner join " . $CFG->prefix . "users u on e.friend = u.ident where e.owner={$userid} and user_type = 'community'")); if ($communities) { foreach ($communities as $community) { $list[] = 'community' . $community->ident; } } // Find values for owned communities $communities = recordset_to_array(get_recordset_sql("SELECT DISTINCT ident as username, ident FROM " . $CFG->prefix . "users where owner = {$userid}")); if ($communities) { foreach ($communities as $community) { $list[] = 'community' . $community->username; } } // Find values for joined groups. $groups = recordset_to_array(get_recordset_sql("SELECT distinct g.ident as i, g.ident FROM " . $CFG->prefix . "group_membership m inner join " . $CFG->prefix . "groups g on m.group_id = g.ident where m.user_id={$userid} ")); if ($groups) { foreach ($groups as $group) { $list[] = 'group' . $group->ident; } } // Find values for owned groups $groups = recordset_to_array(get_recordset_sql("SELECT DISTINCT ident as i, ident FROM " . $CFG->prefix . "groups where owner = {$userid}")); if ($groups) { foreach ($groups as $group) { $list[] = 'group' . $group->ident; } } return $list; }
function main_upgrade($oldversion = 0) { global $CFG, $THEME, $db; $result = true; if ($oldversion == 0) { execute_sql("\n CREATE TABLE `config` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(255) NOT NULL default '',\n `value` varchar(255) NOT NULL default '',\n PRIMARY KEY (`id`),\n UNIQUE KEY `name` (`name`)\n ) COMMENT='Moodle configuration variables';"); notify("Created a new table 'config' to hold configuration data"); } if ($oldversion < 2002073100) { execute_sql(" DELETE FROM `modules` WHERE `name` = 'chat' "); } if ($oldversion < 2002080200) { execute_sql(" ALTER TABLE `modules` DROP `fullname` "); execute_sql(" ALTER TABLE `modules` DROP `search` "); } if ($oldversion < 2002080300) { execute_sql(" ALTER TABLE `log_display` CHANGE `table` `mtable` VARCHAR( 20 ) NOT NULL "); execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 3 ) DEFAULT '3' NOT NULL "); } if ($oldversion < 2002082100) { execute_sql(" ALTER TABLE `course` CHANGE `guest` `guest` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL "); } if ($oldversion < 2002082101) { execute_sql(" ALTER TABLE `user` ADD `maildisplay` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL AFTER `mailformat` "); } if ($oldversion < 2002090100) { execute_sql(" ALTER TABLE `course_sections` CHANGE `summary` `summary` TEXT NOT NULL "); } if ($oldversion < 2002090701) { execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 10 ) DEFAULT '3' NOT NULL "); execute_sql(" ALTER TABLE `user_teachers` ADD `role` VARCHAR(40) NOT NULL AFTER `authority` "); } if ($oldversion < 2002090800) { execute_sql(" ALTER TABLE `course` ADD `teachers` VARCHAR( 100 ) DEFAULT 'Teachers' NOT NULL AFTER `teacher` "); execute_sql(" ALTER TABLE `course` ADD `students` VARCHAR( 100 ) DEFAULT 'Students' NOT NULL AFTER `student` "); } if ($oldversion < 2002091000) { execute_sql(" ALTER TABLE `user` CHANGE `personality` `secret` VARCHAR( 15 ) NOT NULL DEFAULT '' "); } if ($oldversion < 2002091400) { execute_sql(" ALTER TABLE `user` ADD `lang` VARCHAR( 3 ) DEFAULT 'en' NOT NULL AFTER `country` "); } if ($oldversion < 2002091900) { notify("Most Moodle configuration variables have been moved to the database and can now be edited via the admin page."); notify("Although it is not vital that you do so, you might want to edit <U>config.php</U> and remove all the unused settings (except the database, URL and directory definitions). See <U>config-dist.php</U> for an example of how your new slim config.php should look."); } if ($oldversion < 2002092000) { execute_sql(" ALTER TABLE `user` CHANGE `lang` `lang` VARCHAR(5) DEFAULT 'en' NOT NULL "); } if ($oldversion < 2002092100) { execute_sql(" ALTER TABLE `user` ADD `deleted` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `confirmed` "); } if ($oldversion < 2002101001) { execute_sql(" ALTER TABLE `user` ADD `htmleditor` TINYINT(1) UNSIGNED DEFAULT '1' NOT NULL AFTER `maildisplay` "); } if ($oldversion < 2002101701) { execute_sql(" ALTER TABLE `reading` RENAME `resource` "); // Small line with big consequences! execute_sql(" DELETE FROM `log_display` WHERE module = 'reading'"); execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('resource', 'view', 'resource', 'name') "); execute_sql(" UPDATE log SET module = 'resource' WHERE module = 'reading' "); execute_sql(" UPDATE modules SET name = 'resource' WHERE name = 'reading' "); } if ($oldversion < 2002102503) { execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` "); require_once "{$CFG->dirroot}/mod/forum/lib.php"; require_once "{$CFG->dirroot}/course/lib.php"; if (!($module = get_record("modules", "name", "forum"))) { notify("Could not find forum module!!"); return false; } // First upgrade the site forums if ($site = get_site()) { print_heading("Making News forums editable for main site (moving to section 1)..."); if ($news = forum_get_course_forum($site->id, "news")) { $mod->course = $site->id; $mod->module = $module->id; $mod->instance = $news->id; $mod->section = 1; if (!($mod->coursemodule = add_course_module($mod))) { notify("Could not add a new course module to the site"); return false; } if (!($sectionid = add_mod_to_section($mod))) { notify("Could not add the new course module to that section"); return false; } if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) { notify("Could not update the course module with the correct section"); return false; } } } // Now upgrade the courses. if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0")) { print_heading("Making News and Social forums editable for each course (moving to section 0)..."); foreach ($courses as $course) { if ($course->format == "social") { // we won't touch them continue; } if ($news = forum_get_course_forum($course->id, "news")) { $mod->course = $course->id; $mod->module = $module->id; $mod->instance = $news->id; $mod->section = 0; if (!($mod->coursemodule = add_course_module($mod))) { notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'"); return false; } if (!($sectionid = add_mod_to_section($mod))) { notify("Could not add the new course module to that section"); return false; } if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) { notify("Could not update the course module with the correct section"); return false; } } if ($social = forum_get_course_forum($course->id, "social")) { $mod->course = $course->id; $mod->module = $module->id; $mod->instance = $social->id; $mod->section = 0; if (!($mod->coursemodule = add_course_module($mod))) { notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'"); return false; } if (!($sectionid = add_mod_to_section($mod))) { notify("Could not add the new course module to that section"); return false; } if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) { notify("Could not update the course module with the correct section"); return false; } } } } } if ($oldversion < 2002111003) { execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` "); if ($courses = get_records_sql("SELECT * FROM course")) { require_once "{$CFG->dirroot}/course/lib.php"; foreach ($courses as $course) { $modinfo = serialize(get_array_of_activities($course->id)); if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) { notify("Could not cache module information for course '" . format_string($course->fullname) . "'!"); } } } } if ($oldversion < 2002111100) { print_simple_box_start("CENTER", "", "#FFCCCC"); echo "<FONT SIZE=+1>"; echo "<P>Changes have been made to all built-in themes, to add the new popup navigation menu."; echo "<P>If you have customised themes, you will need to edit theme/xxxx/header.html as follows:"; echo "<UL><LI>Change anywhere it says <B>\$" . "button</B> to say <B>\$" . "menu</B>"; echo "<LI>Add <B>\$" . "button</B> elsewhere (eg at the end of the navigation bar)</UL>"; echo "<P>See the standard themes for examples, eg: theme/standard/header.html"; print_simple_box_end(); } if ($oldversion < 2002111200) { execute_sql(" ALTER TABLE `course` ADD `showrecent` TINYINT(5) UNSIGNED DEFAULT '1' NOT NULL AFTER `numsections` "); } if ($oldversion < 2002111400) { // Rebuild all course caches, because some may not be done in new installs (eg site page) if ($courses = get_records_sql("SELECT * FROM course")) { require_once "{$CFG->dirroot}/course/lib.php"; foreach ($courses as $course) { $modinfo = serialize(get_array_of_activities($course->id)); if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) { notify("Could not cache module information for course '" . format_string($course->fullname) . "'!"); } } } } if ($oldversion < 2002112000) { set_config("guestloginbutton", 1); } if ($oldversion < 2002122300) { execute_sql("ALTER TABLE `log` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL "); execute_sql("ALTER TABLE `user_admins` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL "); execute_sql("ALTER TABLE `user_students` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL "); execute_sql("ALTER TABLE `user_teachers` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL "); execute_sql("ALTER TABLE `user_students` CHANGE `start` `timestart` INT(10) UNSIGNED DEFAULT '0' NOT NULL "); execute_sql("ALTER TABLE `user_students` CHANGE `end` `timeend` INT(10) UNSIGNED DEFAULT '0' NOT NULL "); } if ($oldversion < 2002122700) { if (!record_exists("log_display", "module", "user", "action", "view")) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'CONCAT(firstname,' ',lastname)') "); } } if ($oldversion < 2003010101) { delete_records("log_display", "module", "user"); $new->module = "user"; $new->action = "view"; $new->mtable = "user"; $new->field = "CONCAT(firstname,\" \",lastname)"; insert_record("log_display", $new); delete_records("log_display", "module", "course"); $new->module = "course"; $new->action = "view"; $new->mtable = "course"; $new->field = "fullname"; insert_record("log_display", $new); $new->action = "update"; insert_record("log_display", $new); $new->action = "enrol"; insert_record("log_display", $new); } if ($oldversion < 2003012200) { // execute_sql(" ALTER TABLE `log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL "); // Commented out - see below where it's done properly } if ($oldversion < 2003032500) { modify_database("", "CREATE TABLE `prefix_user_coursecreators` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `userid` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `id` (`id`)\n ) TYPE=MyISAM COMMENT='One record per course creator';"); } if ($oldversion < 2003032602) { // Redoing it because of no prefix last time execute_sql(" ALTER TABLE `{$CFG->prefix}log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL "); // Add some indexes for speed execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(course) "); execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(userid) "); } if ($oldversion < 2003041400) { table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score"); } if ($oldversion < 2003042104) { // Try to update permissions of all files if ($files = get_directory_list($CFG->dataroot)) { echo "Attempting to update permissions for all files... ignore any errors."; foreach ($files as $file) { echo "{$CFG->dataroot}/{$file}<br />"; @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions); } } } if ($oldversion < 2003042400) { // Rebuild all course caches, because of changes to do with visible variable if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) { require_once "{$CFG->dirroot}/course/lib.php"; foreach ($courses as $course) { $modinfo = serialize(get_array_of_activities($course->id)); if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) { notify("Could not cache module information for course '" . format_string($course->fullname) . "'!"); } } } } if ($oldversion < 2003042500) { // Convert all usernames to lowercase. $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user"); $cerrors = ""; $rarray = array(); foreach ($users as $user) { // Check for possible conflicts $lcname = trim(moodle_strtolower($user->username)); if (in_array($lcname, $rarray)) { $cerrors .= $user->id . "->" . $lcname . '<br/>'; } else { array_push($rarray, $lcname); } } if ($cerrors != '') { notify("Error: Cannot convert usernames to lowercase.\n Following usernames would overlap (id->username):<br/> {$cerrors} .\n Please resolve overlapping errors."); $result = false; } $cerrors = ""; echo "Checking userdatabase:<br />"; foreach ($users as $user) { $lcname = trim(moodle_strtolower($user->username)); if ($lcname != $user->username) { $convert = set_field("user", "username", $lcname, "id", $user->id); if (!$convert) { if ($cerrors) { $cerrors .= ", "; } $cerrors .= $item; } else { echo "."; } } } if ($cerrors != '') { notify("There were errors when converting following usernames to lowercase.\n '{$cerrors}' . Sorry, but you will need to fix your database by hand."); $result = false; } } if ($oldversion < 2003042600) { /// Some more indexes - we need all the help we can get on the logs //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(module) "); //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(action) "); } if ($oldversion < 2003042700) { /// Changing to multiple indexes execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX module ", false); execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX action ", false); execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX course ", false); execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX userid ", false); execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX coursemoduleaction (course,module,action) "); execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX courseuserid (course,userid) "); } if ($oldversion < 2003042801) { execute_sql("CREATE TABLE `{$CFG->prefix}course_display` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `course` int(10) unsigned NOT NULL default '0',\n `userid` int(10) unsigned NOT NULL default '0',\n `display` int(10) NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `id` (`id`),\n KEY `courseuserid` (course,userid)\n ) TYPE=MyISAM COMMENT='Stores info about how to display the course'"); } if ($oldversion < 2003050400) { table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", ""); } if ($oldversion < 2003050900) { table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", ""); } if ($oldversion < 2003050902) { if (get_records("modules", "name", "pgassignment")) { print_simple_box("Note: the pgassignment module has been removed (it will be replaced later by the workshop module). Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "{$THEME->cellheading}", "20", "noticebox"); } } if ($oldversion < 2003051600) { 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"); } if ($oldversion < 2003052300) { table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor"); } if ($oldversion < 2003072100) { table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker"); } if ($oldversion < 2003072101) { table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", ""); } if ($oldversion < 2003072800) { 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"); flush(); execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX timecoursemoduleaction (time,course,module,action) "); execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX courseuserid (course,userid) "); execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX courseuserid (course,userid) "); } if ($oldversion < 2003072803) { table_column("course_categories", "", "description", "text", "", "", ""); table_column("course_categories", "", "parent", "integer", "10", "unsigned"); table_column("course_categories", "", "sortorder", "integer", "10", "unsigned"); table_column("course_categories", "", "courseorder", "text", "", "", ""); table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1"); table_column("course_categories", "", "timemodified", "integer", "10", "unsigned"); } if ($oldversion < 2003080400) { table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned"); table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category"); } if ($oldversion < 2003080700) { notify("Cleaning up categories and course ordering..."); fix_course_sortorder(); } if ($oldversion < 2003081001) { table_column("course", "format", "format", "varchar", "10", "", "topics"); } if ($oldversion < 2003081500) { // print_simple_box("Some important changes have been made to how course creators work. Formerly, they could create new courses and assign teachers, and teachers could edit courses. Now, ordinary teachers can no longer edit courses - they <b>need to be a teacher of a course AND a course creator</b>. A new site-wide configuration variable allows you to choose whether to allow course creators to create new courses as well (by default this is off). <p>The following update will automatically convert all your existing teachers into course creators, to maintain backward compatibility. Make sure you look at your upgraded site carefully and understand these new changes.", "center", "50%", "$THEME->cellheading", "20", "noticebox"); // $count = 0; // $errorcount = 0; // if ($teachers = get_records("user_teachers")) { // foreach ($teachers as $teacher) { // if (! record_exists("user_coursecreators", "userid", $teacher->userid)) { // $creator = NULL; // $creator->userid = $teacher->userid; // if (!insert_record("user_coursecreators", $creator)) { // $errorcount++; // } else { // $count++; // } // } // } // } // print_simple_box("$count teachers were upgraded to course creators (with $errorcount errors)", "center", "50%", "$THEME->cellheading", "20", "noticebox"); } if ($oldversion < 2003081501) { execute_sql(" CREATE TABLE `{$CFG->prefix}scale` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default '0',\n `userid` int(10) unsigned NOT NULL default '0',\n `name` varchar(255) NOT NULL default '',\n `scale` text NOT NULL,\n `description` text NOT NULL,\n `timemodified` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (id)\n ) TYPE=MyISAM COMMENT='Defines grading scales'"); } if ($oldversion < 2003081503) { table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed"); get_scales_menu(0); // Just to force the default scale to be created } if ($oldversion < 2003081600) { table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role"); table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall"); } if ($oldversion < 2003081900) { table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0"); } if ($oldversion < 2003082001) { table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format"); } if ($oldversion < 2003082101) { execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX category (category) "); } if ($oldversion < 2003082702) { execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') "); } if ($oldversion < 2003091400) { table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score"); } if ($oldversion < 2003092900) { table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker"); } if ($oldversion < 2003102700) { table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time"); table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified"); $db->debug = false; $CFG->debug = 0; notify("Calculating access times. Please wait - this may take a long time on big sites...", "green"); flush(); if ($courses = get_records_select("course", "category > 0")) { foreach ($courses as $course) { notify("Processing " . format_string($course->fullname) . " ...", "green"); flush(); if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) { foreach ($users as $user) { $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log WHERE course = '{$course->id}' and userid = '{$user->userid}' ORDER by time DESC"); if (empty($loginfo->time)) { $loginfo->time = 0; } execute_sql("UPDATE {$CFG->prefix}user_teachers SET timeaccess = '{$loginfo->time}'\n WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false); } } if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) { foreach ($users as $user) { $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log\n WHERE course = '{$course->id}' and userid = '{$user->userid}'\n ORDER by time DESC"); if (empty($loginfo->time)) { $loginfo->time = 0; } execute_sql("UPDATE {$CFG->prefix}user_students\n SET timeaccess = '{$loginfo->time}'\n WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false); } } } } notify("All courses complete.", "green"); $db->debug = true; } if ($oldversion < 2003103100) { table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes"); } if ($oldversion < 2003121600) { modify_database("", "CREATE TABLE `prefix_groups` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default '0',\n `name` varchar(254) NOT NULL default '',\n `description` text NOT NULL,\n `lang` varchar(10) NOT NULL default 'en',\n `picture` int(10) unsigned NOT NULL default '0',\n `timecreated` int(10) unsigned NOT NULL default '0',\n `timemodified` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`)\n ) TYPE=MyISAM COMMENT='Each record is a group in a course.'; "); modify_database("", "CREATE TABLE `prefix_groups_members` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `groupid` int(10) unsigned NOT NULL default '0',\n `userid` int(10) unsigned NOT NULL default '0',\n `timeadded` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `groupid` (`groupid`)\n ) TYPE=MyISAM COMMENT='Lists memberships of users in groups'; "); } if ($oldversion < 2003121800) { table_column("course", "modinfo", "modinfo", "longtext", "", "", ""); } if ($oldversion < 2003122600) { table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "showreports"); table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode"); } if ($oldversion < 2004010900) { table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible"); } if ($oldversion < 2004011700) { modify_database("", "CREATE TABLE `prefix_event` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(255) NOT NULL default '',\n `description` text NOT NULL,\n `courseid` int(10) unsigned NOT NULL default '0',\n `groupid` int(10) unsigned NOT NULL default '0',\n `userid` int(10) unsigned NOT NULL default '0',\n `modulename` varchar(20) NOT NULL default '',\n `instance` int(10) unsigned NOT NULL default '0',\n `eventtype` varchar(20) NOT NULL default '',\n `timestart` int(10) unsigned NOT NULL default '0',\n `timeduration` int(10) unsigned NOT NULL default '0',\n `timemodified` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `id` (`id`),\n KEY `courseid` (`courseid`),\n KEY `userid` (`userid`)\n ) TYPE=MyISAM COMMENT='For everything with a time associated to it'; "); } if ($oldversion < 2004012800) { modify_database("", "CREATE TABLE `prefix_user_preferences` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `userid` int(10) unsigned NOT NULL default '0',\n `name` varchar(50) NOT NULL default '',\n `value` varchar(255) NOT NULL default '',\n PRIMARY KEY (`id`),\n UNIQUE KEY `id` (`id`),\n KEY `useridname` (userid,name)\n ) TYPE=MyISAM COMMENT='Allows modules to store arbitrary user preferences'; "); } if ($oldversion < 2004012900) { table_column("config", "value", "value", "text", "", "", ""); } if ($oldversion < 2004013101) { table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module"); set_config("upgrade", "logs"); } if ($oldversion < 2004020900) { table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce"); } if ($oldversion < 2004020903) { modify_database("", "CREATE TABLE `prefix_cache_text` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `md5key` varchar(32) NOT NULL default '',\n `formattedtext` longtext NOT NULL,\n `timemodified` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `md5key` (`md5key`)\n ) TYPE=MyISAM COMMENT='For storing temporary copies of processed texts';"); } if ($oldversion < 2004021000) { $textfilters = array(); for ($i = 1; $i <= 10; $i++) { $variable = "textfilter{$i}"; if (!empty($CFG->{$variable})) { /// No more filters if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) { $textfilters[] = $CFG->{$variable}; } } } $textfilters = implode(',', $textfilters); if (empty($textfilters)) { $textfilters = 'mod/glossary/dynalink.php'; } set_config('textfilters', $textfilters); } if ($oldversion < 2004021201) { modify_database("", "CREATE TABLE `prefix_cache_filters` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `filter` varchar(32) NOT NULL default '',\n `version` int(10) unsigned NOT NULL default '0',\n `md5key` varchar(32) NOT NULL default '',\n `rawtext` text NOT NULL,\n `timemodified` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `filtermd5key` (filter,md5key)\n ) TYPE=MyISAM COMMENT='For keeping information about cached data';"); } if ($oldversion < 2004021500) { table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture"); } if ($oldversion < 2004021700) { if (!empty($CFG->textfilters)) { $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters); $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters); set_config("textfilters", $CFG->textfilters); } } if ($oldversion < 2004022000) { table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email"); } if ($oldversion < 2004022200) { /// Final renaming I hope. :-) if (!empty($CFG->textfilters)) { $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters); $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters); $textfilters = explode(',', $CFG->textfilters); foreach ($textfilters as $key => $textfilter) { $textfilters[$key] = trim($textfilter); } set_config("textfilters", implode(',', $textfilters)); } } if ($oldversion < 2004030702) { /// Because of the renaming of Czech language pack execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'"); execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'"); } if ($oldversion < 2004041800) { /// Integrate Block System from contrib table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo"); } if ($oldversion < 2004042600) { /// Rebuild course caches for resource icons include_once "{$CFG->dirroot}/course/lib.php"; rebuild_course_cache(); } if ($oldversion < 2004042700) { /// Increase size of lang fields table_column("user", "lang", "lang", "varchar", "10", "", "en"); table_column("groups", "lang", "lang", "varchar", "10", "", ""); table_column("course", "lang", "lang", "varchar", "10", "", ""); } if ($oldversion < 2004042701) { /// Add hiddentopics field to control hidden topics behaviour table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible"); } if ($oldversion < 2004042702) { /// add a format field for the description table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description"); } if ($oldversion < 2004042900) { execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP `showrecent` "); } if ($oldversion < 2004043001) { /// Change hiddentopics to hiddensections table_column("course", "hiddentopics", "hiddensections", "integer", "2", "unsigned", "0", "not null"); } if ($oldversion < 2004050400) { /// add a visible field for events table_column("event", "", "visible", "tinyint", "1", "", "1", "not null", "timeduration"); if ($events = get_records('event')) { foreach ($events as $event) { if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) { if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) { set_field('event', 'visible', 0, 'id', $event->id); } } } } } if ($oldversion < 2004052800) { /// First version tagged "1.4 development", version.php 1.227 set_config('siteblocksadded', true); /// This will be used later by the block upgrade } if ($oldversion < 2004053000) { /// set defaults for site course $site = get_site(); set_field('course', 'numsections', 0, 'id', $site->id); set_field('course', 'groupmodeforce', 1, 'id', $site->id); set_field('course', 'teacher', get_string('administrator'), 'id', $site->id); set_field('course', 'teachers', get_string('administrators'), 'id', $site->id); set_field('course', 'student', get_string('user'), 'id', $site->id); set_field('course', 'students', get_string('users'), 'id', $site->id); } if ($oldversion < 2004060100) { set_config('digestmailtime', 0); table_column('user', "", 'maildigest', 'tinyint', '1', '', '0', 'not null', 'mailformat'); } if ($oldversion < 2004062400) { table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall'); table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall'); } if ($oldversion < 2004062401) { table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname'); execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname'); // By default } if ($oldversion < 2004062600) { table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang'); } if ($oldversion < 2004072900) { table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate'); } if ($oldversion < 2004072901) { // Fixing error in schema if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) { delete_records('log_display', 'module', 'course', 'action', 'update'); insert_record('log_display', $record, false); } } if ($oldversion < 2004081200) { // Fixing version errors in some blocks set_field('blocks', 'version', 2004081200, 'name', 'admin'); set_field('blocks', 'version', 2004081200, 'name', 'calendar_month'); set_field('blocks', 'version', 2004081200, 'name', 'course_list'); } if ($oldversion < 2004081500) { // Adding new "auth" field to user table to allow more flexibility table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id'); execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'"); // Set everyone to 'manual' to be sure if ($admins = get_admins()) { // Set all the NON-admins to whatever the current auth module is $adminlist = array(); foreach ($admins as $user) { $adminlist[] = $user->id; } $adminlist = implode(',', $adminlist); execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})"); } } if ($oldversion < 2004082200) { // Making admins teachers on site course $site = get_site(); $admins = get_admins(); foreach ($admins as $admin) { add_teacher($admin->id, $site->id); } } if ($oldversion < 2004082600) { //update auth-fields for external users // following code would not work in 1.8 /* include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php"); if (function_exists('auth_get_userlist')) { $externalusers = auth_get_userlist(); if (!empty($externalusers)){ $externalusers = '\''. implode('\',\'',$externalusers).'\''; execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username IN ($externalusers)"); } }*/ } if ($oldversion < 2004082900) { // Make sure guest is "manual" too. set_field('user', 'auth', 'manual', 'username', 'guest'); } /* Commented out unused guid-field code if ($oldversion < 2004090300) { // Add guid-field used in user syncronization table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth'); execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX authguid (auth, guid)"); } */ if ($oldversion < 2004091900) { // modify idnumber to hold longer values table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', ''); execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_idnumber", false); // added in case of conflicts with upgrade from 14stable execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_auth", false); // added in case of conflicts with upgrade from 14stable execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX idnumber (idnumber)"); execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX auth (auth)"); } if ($oldversion < 2004093001) { // add new table for sessions storage execute_sql(" CREATE TABLE `{$CFG->prefix}sessions` (\n `sesskey` char(32) NOT null,\n `expiry` int(11) unsigned NOT null,\n `expireref` varchar(64),\n `data` text NOT null,\n PRIMARY KEY (`sesskey`), \n KEY (`expiry`) \n ) TYPE=MyISAM COMMENT='Optional database session storage, not used by default';"); } if ($oldversion < 2004111500) { // Update any users/courses using wrongly-named lang pack execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'"); execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'"); } if ($oldversion < 2004111700) { // add indexes. - drop them first silently to avoid conflicts when upgrading. execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX idnumber;", false); execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX shortname;", false); execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` DROP INDEX userid;", false); execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` DROP INDEX userid;", false); execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX idnumber (idnumber);"); execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX shortname (shortname);"); execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX userid (userid);"); execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX userid (userid);"); } if ($oldversion < 2004111700) { // add an index to event for timestart and timeduration. - drop them first silently to avoid conflicts when upgrading. execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timestart;", false); execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timeduration;", false); modify_database('', 'ALTER TABLE prefix_event ADD INDEX timestart (timestart);'); modify_database('', 'ALTER TABLE prefix_event ADD INDEX timeduration (timeduration);'); } if ($oldversion < 2004111700) { //add indexes on modules and course_modules. - drop them first silently to avoid conflicts when upgrading. execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key visible;", false); execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key course;", false); execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key module;", false); execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key instance;", false); execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key deleted;", false); execute_sql("ALTER TABLE {$CFG->prefix}modules drop key name;", false); modify_database('', 'ALTER TABLE prefix_course_modules add key visible(visible);'); modify_database('', 'ALTER TABLE prefix_course_modules add key course(course);'); modify_database('', 'ALTER TABLE prefix_course_modules add key module(module);'); modify_database('', 'ALTER TABLE prefix_course_modules add key instance (instance);'); modify_database('', 'ALTER TABLE prefix_course_modules add key deleted (deleted);'); modify_database('', 'ALTER TABLE prefix_modules add key name(name);'); } if ($oldversion < 2004111700) { // add an index on the groups_members table. - drop them first silently to avoid conflicts when upgrading. execute_sql("ALTER TABLE {$CFG->prefix}groups_members DROP INDEX userid;", false); modify_database('', 'ALTER TABLE prefix_groups_members ADD INDEX userid (userid);'); } if ($oldversion < 2004111700) { // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading execute_sql("ALTER TABLE {$CFG->prefix}user_students DROP INDEX timeaccess;", false); modify_database('', 'ALTER TABLE prefix_user_students ADD INDEX timeaccess (timeaccess);'); } if ($oldversion < 2004111700) { // add indexes on faux-foreign keys. - drop them first silently to avoid conflicts when upgrading. execute_sql("ALTER TABLE {$CFG->prefix}scale DROP INDEX courseid;", false); execute_sql("ALTER TABLE {$CFG->prefix}user_admins DROP INDEX userid;", false); execute_sql("ALTER TABLE {$CFG->prefix}user_coursecreators DROP INDEX userid;", false); modify_database('', 'ALTER TABLE prefix_scale ADD INDEX courseid (courseid);'); modify_database('', 'ALTER TABLE prefix_user_admins ADD INDEX userid (userid);'); modify_database('', 'ALTER TABLE prefix_user_coursecreators ADD INDEX userid (userid);'); } if ($oldversion < 2004111700) { // replace index on course fix_course_sortorder(0, 0, 1); execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category", false); execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category_sortorder;", false); modify_database('', "ALTER TABLE `prefix_course` ADD UNIQUE KEY category_sortorder(category,sortorder)"); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_deleted_idx (deleted)"); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_confirmed_idx (confirmed)"); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_firstname_idx (firstname)"); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastname_idx (lastname)"); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_city_idx (city)"); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_country_idx (country)"); modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastaccess_idx (lastaccess)"); } if ($oldversion < 2004111700) { // one more index for email (for sorting) execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;", false); modify_database('', 'ALTER TABLE `prefix_user` ADD INDEX prefix_user_email_idx (email);'); } if ($oldversion < 2004112200) { // new 'enrol' field for enrolment tables table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null'); table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null'); execute_sql("ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX enrol (enrol);"); execute_sql("ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX enrol (enrol);"); } if ($oldversion < 2004112400) { /// Delete duplicate enrolments /// and then tell the database course,userid is a unique combination if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) { foreach ($users as $user) { delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'"); } } flush(); modify_database('', 'ALTER TABLE prefix_user_students DROP INDEX courseuserid;'); modify_database('', 'ALTER TABLE prefix_user_students ADD UNIQUE INDEX courseuserid(course,userid);'); /// Delete duplicate teacher enrolments /// and then tell the database course,userid is a unique combination if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) { foreach ($users as $user) { delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'"); } } flush(); modify_database('', 'ALTER TABLE prefix_user_teachers DROP INDEX courseuserid;'); modify_database('', 'ALTER TABLE prefix_user_teachers ADD UNIQUE INDEX courseuserid(course,userid);'); } if ($oldversion < 2004112900) { table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed'); } if ($oldversion < 2004121400) { table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description'); } if ($oldversion < 2004121500) { modify_database('', "CREATE TABLE prefix_dst_preset (\n id int(10) NOT NULL auto_increment,\n name char(48) default '' NOT NULL,\n \n apply_offset tinyint(3) default '0' NOT NULL,\n \n activate_index tinyint(1) default '1' NOT NULL,\n activate_day tinyint(1) default '1' NOT NULL,\n activate_month tinyint(2) default '1' NOT NULL,\n activate_time char(5) default '03:00' NOT NULL,\n \n deactivate_index tinyint(1) default '1' NOT NULL,\n deactivate_day tinyint(1) default '1' NOT NULL,\n deactivate_month tinyint(2) default '2' NOT NULL,\n deactivate_time char(5) default '03:00' NOT NULL,\n \n last_change int(10) default '0' NOT NULL,\n next_change int(10) default '0' NOT NULL,\n current_offset tinyint(3) default '0' NOT NULL,\n \n PRIMARY KEY (id))"); } if ($oldversion < 2004122800) { execute_sql("DROP TABLE {$CFG->prefix}message", false); execute_sql("DROP TABLE {$CFG->prefix}message_read", false); execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false); modify_database('', "CREATE TABLE `prefix_message` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `useridfrom` int(10) NOT NULL default '0',\n `useridto` int(10) NOT NULL default '0',\n `message` text NOT NULL,\n `timecreated` int(10) NOT NULL default '0',\n `messagetype` varchar(50) NOT NULL default '',\n PRIMARY KEY (`id`),\n KEY `useridfrom` (`useridfrom`),\n KEY `useridto` (`useridto`)\n ) TYPE=MyISAM COMMENT='Stores all unread messages';"); modify_database('', "CREATE TABLE `prefix_message_read` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `useridfrom` int(10) NOT NULL default '0',\n `useridto` int(10) NOT NULL default '0',\n `message` text NOT NULL,\n `timecreated` int(10) NOT NULL default '0',\n `timeread` int(10) NOT NULL default '0',\n `messagetype` varchar(50) NOT NULL default '',\n `mailed` tinyint(1) NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `useridfrom` (`useridfrom`),\n KEY `useridto` (`useridto`)\n ) TYPE=MyISAM COMMENT='Stores all messages that have been read';"); modify_database('', "CREATE TABLE `prefix_message_contacts` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `userid` int(10) unsigned NOT NULL default '0',\n `contactid` int(10) unsigned NOT NULL default '0',\n `blocked` tinyint(1) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `usercontact` (`userid`,`contactid`)\n ) TYPE=MyISAM COMMENT='Maintains lists of relationships between users';"); modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'CONCAT(firstname,\" \",lastname)'); "); modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'CONCAT(firstname,\" \",lastname)'); "); } if ($oldversion < 2004122801) { table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message'); table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message'); } if ($oldversion < 2005010100) { modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'CONCAT(firstname,\" \",lastname)'); "); modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'CONCAT(firstname,\" \",lastname)'); "); modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'CONCAT(firstname,\" \",lastname)'); "); modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'CONCAT(firstname,\" \",lastname)'); "); } if ($oldversion < 2005011000) { // Create a .htaccess file in dataroot, just in case if (!file_exists($CFG->dataroot . '/.htaccess')) { if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) { // For safety @fwrite($handle, "deny from all\r\nAllowOverride None\r\n"); @fclose($handle); notify("Created a default .htaccess file in {$CFG->dataroot}"); } } } if ($oldversion < 2005012500) { /* // add new table for meta courses. modify_database("","CREATE TABLE `prefix_meta_course` ( `id` int(1) unsigned NOT NULL auto_increment, `parent_course` int(10) NOT NULL default 0, `child_course` int(10) NOT NULL default 0, PRIMARY KEY (`id`), KEY `parent_course` (parent_course), KEY `child_course` (child_course) );"); // add flag to course field table_column('course','','meta_course','integer','1','','0','not null'); */ // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it) } if ($oldversion < 2005012501) { execute_sql("DROP TABLE {$CFG->prefix}meta_course", false); // drop silently execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false); // drop silently // add new table for meta courses. modify_database("", "CREATE TABLE `prefix_course_meta` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `parent_course` int(10) NOT NULL default 0,\n `child_course` int(10) NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `parent_course` (parent_course),\n KEY `child_course` (child_course)\n );"); // add flag to course field table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null'); } if ($oldversion < 2005012800) { // fix a typo (int 1 becomes int 10) table_column('course_meta', 'id', 'id', 'integer', '10', '', '0', 'not null'); } if ($oldversion < 2005020100) { fix_course_sortorder(0, 1, 1); } if ($oldversion < 2005020101) { // hopefully this is the LAST TIME we need to do this ;) if ($rows = count_records("course_meta")) { // we need to upgrade modify_database("", "CREATE TABLE `prefix_course_meta_tmp` (\n `parent_course` int(10) NOT NULL default 0,\n `child_course` int(10) NOT NULL default 0);"); execute_sql("INSERT INTO {$CFG->prefix}course_meta_tmp (parent_course,child_course) \n SELECT {$CFG->prefix}course_meta.parent_course, {$CFG->prefix}course_meta.child_course\n FROM {$CFG->prefix}course_meta"); $insertafter = true; } execute_sql("DROP TABLE {$CFG->prefix}course_meta"); modify_database("", "CREATE TABLE `prefix_course_meta` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `parent_course` int(10) unsigned NOT NULL default 0,\n `child_course` int(10) unsigned NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `parent_course` (parent_course),\n KEY `child_course` (child_course));"); if (!empty($insertafter)) { execute_sql("INSERT INTO {$CFG->prefix}course_meta (parent_course,child_course) \n SELECT {$CFG->prefix}course_meta_tmp.parent_course, {$CFG->prefix}course_meta_tmp.child_course\n FROM {$CFG->prefix}course_meta_tmp"); execute_sql("DROP TABLE {$CFG->prefix}course_meta_tmp"); } } if ($oldversion < 2005020800) { // Expand module column to max 20 chars table_column('log', 'module', 'module', 'varchar', '20', '', '', 'not null'); } if ($oldversion < 2005021000) { // New fields for theme choices table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang'); table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang'); table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang'); set_config('theme', 'standardwhite'); // Reset to a known good theme } if ($oldversion < 2005021600) { // course.idnumber should be varchar(100) table_column('course', 'idnumber', 'idnumber', 'varchar', '100', '', '', '', ''); } if ($oldversion < 2005021700) { table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone'); } if ($oldversion < 2005021800) { // For database debugging, not for normal use modify_database("", " CREATE TABLE `adodb_logsql` (\n `created` datetime NOT NULL,\n `sql0` varchar(250) NOT NULL,\n `sql1` text NOT NULL,\n `params` text NOT NULL,\n `tracer` text NOT NULL,\n `timer` decimal(16,6) NOT NULL\n );"); } if ($oldversion < 2005022400) { // Add more visible digits to the fields table_column('dst_preset', 'activate_index', 'activate_index', 'tinyint', '2', '', '0', 'not null'); table_column('dst_preset', 'activate_day', 'activate_day', 'tinyint', '2', '', '0', 'not null'); // Add family and year fields table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name'); table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family'); } if ($oldversion < 2005030501) { table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq'); table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq'); table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq'); table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq'); } if ($oldversion < 2005032300) { table_column('user', 'dstpreset', 'timezonename', 'varchar', '100'); execute_sql('UPDATE `' . $CFG->prefix . 'user` SET timezonename = \'\''); } if ($oldversion < 2005032600) { execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false); modify_database('', "CREATE TABLE `prefix_timezone` (\n `id` int(10) NOT NULL auto_increment,\n `name` varchar(100) NOT NULL default '',\n `year` int(11) NOT NULL default '0',\n `rule` varchar(20) NOT NULL default '',\n `gmtoff` int(11) NOT NULL default '0',\n `dstoff` int(11) NOT NULL default '0',\n `dst_month` tinyint(2) NOT NULL default '0',\n `dst_startday` tinyint(3) NOT NULL default '0',\n `dst_weekday` tinyint(3) NOT NULL default '0',\n `dst_skipweeks` tinyint(3) NOT NULL default '0',\n `dst_time` varchar(5) NOT NULL default '00:00',\n `std_month` tinyint(2) NOT NULL default '0',\n `std_startday` tinyint(3) NOT NULL default '0',\n `std_weekday` tinyint(3) NOT NULL default '0',\n `std_skipweeks` tinyint(3) NOT NULL default '0',\n `std_time` varchar(5) NOT NULL default '00:00',\n PRIMARY KEY (`id`)\n ) TYPE=MyISAM COMMENT='Rules for calculating local wall clock time for users';"); } if ($oldversion < 2005032800) { execute_sql("CREATE TABLE `{$CFG->prefix}grade_category` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(64) NOT NULL default '',\n `courseid` int(10) unsigned NOT NULL default '0',\n `drop_x_lowest` int(10) unsigned NOT NULL default '0',\n `bonus_points` int(10) unsigned NOT NULL default '0',\n `hidden` int(10) unsigned NOT NULL default '0',\n `weight` decimal(4,2) NOT NULL default '0.00',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`)\n ) TYPE=MyISAM ;"); execute_sql("CREATE TABLE `{$CFG->prefix}grade_exceptions` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default '0',\n `grade_itemid` int(10) unsigned NOT NULL default '0',\n `userid` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`)\n ) TYPE=MyISAM ;"); execute_sql("CREATE TABLE `{$CFG->prefix}grade_item` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default '0',\n `category` int(10) unsigned NOT NULL default '0',\n `modid` int(10) unsigned NOT NULL default '0',\n `cminstance` int(10) unsigned NOT NULL default '0',\n `scale_grade` float(11,10) default '1.0000000000',\n `extra_credit` int(10) unsigned NOT NULL default '0',\n `sort_order` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`)\n ) TYPE=MyISAM ;"); execute_sql("CREATE TABLE `{$CFG->prefix}grade_letter` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default '0',\n `letter` varchar(8) NOT NULL default 'NA',\n `grade_high` decimal(4,2) NOT NULL default '100.00',\n `grade_low` decimal(4,2) NOT NULL default '0.00',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`)\n ) TYPE=MyISAM ;"); execute_sql("CREATE TABLE `{$CFG->prefix}grade_preferences` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default '0',\n `preference` int(10) NOT NULL default '0',\n `value` int(10) NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `courseidpreference` (`courseid`,`preference`)\n ) TYPE=MyISAM ;"); } if ($oldversion < 2005033100) { // Get rid of defunct field from course modules table delete_records('course_modules', 'deleted', 1); // Delete old records we don't need any more execute_sql('ALTER TABLE `' . $CFG->prefix . 'course_modules` DROP INDEX `deleted`'); // Old index execute_sql('ALTER TABLE `' . $CFG->prefix . 'course_modules` DROP `deleted`'); // Old field } if ($oldversion < 2005040800) { table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99'); execute_sql(" ALTER TABLE `{$CFG->prefix}user` DROP `timezonename` "); } if ($oldversion < 2005041101) { require_once $CFG->libdir . '/filelib.php'; if (is_readable($CFG->dirroot . '/lib/timezones.txt')) { // Distribution file if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) { $db->debug = false; update_timezone_records($timezones); notify(count($timezones) . ' timezones installed'); $db->debug = true; } } } if ($oldversion < 2005041900) { // Copy all Dialogue entries into Messages, and hide Dialogue module if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated FROM ' . $CFG->prefix . 'dialogue_conversations c, ' . $CFG->prefix . 'dialogue_entries e WHERE e.conversationid = c.id')) { foreach ($entries as $entry) { $message = new object(); $message->useridfrom = $entry->userid; $message->useridto = $entry->recipientid; $message->message = addslashes($entry->text); $message->format = FORMAT_HTML; $message->timecreated = $entry->timecreated; $message->messagetype = 'direct'; insert_record('message_read', $message); } } set_field('modules', 'visible', 0, 'name', 'dialogue'); 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'); } if ($oldversion < 2005042100) { $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result; } if ($oldversion < 2005042400) { // Add user tracking prefs field. table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe'); } if ($oldversion < 2005053000) { // Add config_plugins table // this table was created on the MOODLE_15_STABLE branch // so it may already exist. $result = execute_sql("CREATE TABLE IF NOT EXISTS `{$CFG->prefix}config_plugins` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `plugin` varchar(100) NOT NULL default 'core',\n `name` varchar(100) NOT NULL default '',\n `value` text NOT NULL default '',\n PRIMARY KEY (`id`),\n UNIQUE KEY `plugin_name` (`plugin`, `name`)\n ) TYPE=MyISAM \n COMMENT='Moodle modules and plugins configuration variables';"); } if ($oldversion < 2005060200) { // migrate some config items to config_plugins table // NOTE: this block is in both postgres AND mysql upgrade // files. If you edit either, update the otherone. $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang"); if (!empty($CFG->auth)) { // if we have no auth, just pass foreach ($user_fields as $field) { $suffixes = array('', '_editlock', '_updateremote', '_updatelocal'); foreach ($suffixes as $suffix) { $key = 'auth_user_' . $field . $suffix; if (isset($CFG->{$key})) { // translate keys & values // to the new convention // this should support upgrading // even 1.5dev installs $newkey = $key; $newval = $CFG->{$key}; if ($suffix === '') { $newkey = 'field_map_' . $field; } elseif ($suffix === '_editlock') { $newkey = 'field_lock_' . $field; $newval = $newval == 1 ? 'locked' : 'unlocked'; // translate 0/1 to locked/unlocked } elseif ($suffix === '_updateremote') { $newkey = 'field_updateremote_' . $field; } elseif ($suffix === '_updatelocal') { $newkey = 'field_updatelocal_' . $field; $newval = $newval == 1 ? 'onlogin' : 'oncreate'; // translate 0/1 to locked/unlocked } if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) { notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} ."); $result = false; } } // end if isset key } // end foreach suffix } // end foreach field } } if ($oldversion < 2005060201) { // Close down the Attendance module, we are removing it from CVS. if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) { if (count_records('attendance')) { // We have some data, so should keep it set_field('modules', 'visible', 0, 'name', 'attendance'); notify('The Attendance module has been discontinued. If you really want to continue using it, you should download it individually from http://download.moodle.org/modules and install it, then reactivate it from Admin >> Configuration >> Modules. None of your existing data has been deleted, so all existing Attendance activities should re-appear.'); } else { // No data, so do a complete delete execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false); delete_records('modules', 'name', 'attendance'); notify("The Attendance module has been discontinued and removed from your site. \n You weren't using it anyway. ;-)"); } } } if ($oldversion < 2005071700) { // Close down the Dialogue module, we are removing it from CVS. if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) { if (count_records('dialogue')) { // We have some data, so should keep it set_field('modules', 'visible', 0, 'name', 'dialogue'); notify('The Dialogue module has been discontinued. If you really want to continue using it, you should download it individually from http://download.moodle.org/modules and install it, then reactivate it from Admin >> Configuration >> Modules. None of your existing data has been deleted, so all existing Dialogue activities should re-appear.'); } else { // No data, so do a complete delete execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false); delete_records('modules', 'name', 'dialogue'); notify("The Dialogue module has been discontinued and removed from your site. \n You weren't using it anyway. ;-)"); } } } if ($oldversion < 2005072000) { // Add a couple fields to mdl_event to work towards iCal import/export table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible'); table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid'); } if ($oldversion < 2005072100) { // run the online assignment cleanup code include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php'; if (function_exists('online_assignment_cleanup')) { online_assignment_cleanup(); } } if ($oldversion < 2005072200) { // fix the mistakenly-added currency stuff from enrol/authorize execute_sql("DROP TABLE {$CFG->prefix}currencies", false); // drop silently execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false); $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency; table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost'); } if ($oldversion < 2005081600) { //set up the course requests table modify_database('', "CREATE TABLE `prefix_course_request` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `fullname` varchar(254) NOT NULL default '',\n `shortname` varchar(15) NOT NULL default '',\n `summary` text NOT NULL,\n `reason` text NOT NULL,\n `requester` int(10) NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `shortname` (`shortname`)\n ) TYPE=MyISAM;"); table_column('course', '', 'requested'); } if ($oldversion < 2005081601) { modify_database('', "CREATE TABLE `prefix_course_allowed_modules` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `course` int(10) unsigned NOT NULL default 0,\n `module` int(10) unsigned NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `course` (`course`),\n KEY `module` (`module`)\n ) TYPE=MyISAM;"); table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null'); } if ($oldversion < 2005081700) { table_column('course_categories', '', 'depth', 'integer'); table_column('course_categories', '', 'path', 'varchar', '255'); } if ($oldversion < 2005090100) { modify_database("", "CREATE TABLE `prefix_stats_daily` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default 0,\n `timeend` int(10) unsigned NOT NULL default 0,\n `students` int(10) unsigned NOT NULL default 0,\n `teachers` int(10) unsigned NOT NULL default 0,\n `activestudents` int(10) unsigned NOT NULL default 0,\n `activeteachers` int(10) unsigned NOT NULL default 0,\n `studentreads` int(10) unsigned NOT NULL default 0,\n `studentwrites` int(10) unsigned NOT NULL default 0,\n `teacherreads` int(10) unsigned NOT NULL default 0,\n `teacherwrites` int(10) unsigned NOT NULL default 0,\n `logins` int(10) unsigned NOT NULL default 0,\n `uniquelogins` int(10) unsigned NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`),\n KEY `timeend` (`timeend`)\n );"); modify_database("", "CREATE TABLE prefix_stats_weekly (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default 0,\n `timeend` int(10) unsigned NOT NULL default 0,\n `students` int(10) unsigned NOT NULL default 0,\n `teachers` int(10) unsigned NOT NULL default 0,\n `activestudents` int(10) unsigned NOT NULL default 0,\n `activeteachers` int(10) unsigned NOT NULL default 0,\n `studentreads` int(10) unsigned NOT NULL default 0,\n `studentwrites` int(10) unsigned NOT NULL default 0,\n `teacherreads` int(10) unsigned NOT NULL default 0,\n `teacherwrites` int(10) unsigned NOT NULL default 0,\n `logins` int(10) unsigned NOT NULL default 0,\n `uniquelogins` int(10) unsigned NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`),\n KEY `timeend` (`timeend`)\n );"); modify_database("", "CREATE TABLE prefix_stats_monthly (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default 0,\n `timeend` int(10) unsigned NOT NULL default 0,\n `students` int(10) unsigned NOT NULL default 0,\n `teachers` int(10) unsigned NOT NULL default 0,\n `activestudents` int(10) unsigned NOT NULL default 0,\n `activeteachers` int(10) unsigned NOT NULL default 0,\n `studentreads` int(10) unsigned NOT NULL default 0,\n `studentwrites` int(10) unsigned NOT NULL default 0,\n `teacherreads` int(10) unsigned NOT NULL default 0,\n `teacherwrites` int(10) unsigned NOT NULL default 0,\n `logins` int(10) unsigned NOT NULL default 0,\n `uniquelogins` int(10) unsigned NOT NULL default 0,\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`),\n KEY `timeend` (`timeend`)\n );"); modify_database("", "CREATE TABLE prefix_stats_user_daily (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default 0,\n `userid` int(10) unsigned NOT NULL default 0,\n `roleid` int(10) unsigned NOT NULL default 0,\n `timeend` int(10) unsigned NOT NULL default 0,\n `statsreads` int(10) unsigned NOT NULL default 0,\n `statswrites` int(10) unsigned NOT NULL default 0,\n `stattype` varchar(30) NOT NULL default '',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`),\n KEY `userid` (`userid`),\n KEY `roleid` (`roleid`),\n KEY `timeend` (`timeend`)\n );"); modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default 0,\n `userid` int(10) unsigned NOT NULL default 0,\n `roleid` int(10) unsigned NOT NULL default 0,\n `timeend` int(10) unsigned NOT NULL default 0,\n `statsreads` int(10) unsigned NOT NULL default 0,\n `statswrites` int(10) unsigned NOT NULL default 0,\n `stattype` varchar(30) NOT NULL default '',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`),\n KEY `userid` (`userid`),\n KEY `roleid` (`roleid`),\n KEY `timeend` (`timeend`)\n );"); modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n `id` int(10) unsigned NOT NULL auto_increment,\n `courseid` int(10) unsigned NOT NULL default 0,\n `userid` int(10) unsigned NOT NULL default 0,\n `roleid` int(10) unsigned NOT NULL default 0,\n `timeend` int(10) unsigned NOT NULL default 0,\n `statsreads` int(10) unsigned NOT NULL default 0,\n `statswrites` int(10) unsigned NOT NULL default 0,\n `stattype` varchar(30) NOT NULL default '',\n PRIMARY KEY (`id`),\n KEY `courseid` (`courseid`),\n KEY `userid` (`userid`),\n KEY `roleid` (`roleid`),\n KEY `timeend` (`timeend`)\n );"); } if ($oldversion < 2005100300) { table_column('course', '', 'expirynotify', 'tinyint', '1'); table_column('course', '', 'expirythreshold', 'int', '10'); table_column('course', '', 'notifystudents', 'tinyint', '1'); $new = new stdClass(); $new->name = 'lastexpirynotify'; $new->value = 0; insert_record('config', $new); } if ($oldversion < 2005100400) { table_column('course', '', 'enrollable', 'tinyint', '1', 'unsigned', '1'); table_column('course', '', 'enrolstartdate', 'int'); table_column('course', '', 'enrolenddate', 'int'); } if ($oldversion < 2005101200) { // add enrolment key to course_request. table_column('course_request', '', 'password', 'varchar', 50); } if ($oldversion < 2006030800) { # add extra indexes to log (see bug #4112) modify_database('', "ALTER TABLE prefix_log ADD INDEX userid (userid);"); modify_database('', "ALTER TABLE prefix_log ADD INDEX info (info);"); } if ($oldversion < 2006030900) { table_column('course', '', 'enrol', 'varchar', '20', '', ''); if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') { set_config('enrol_plugins_enabled', 'manual'); set_config('enrol', 'manual'); } else { set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol); } require_once "{$CFG->dirroot}/enrol/enrol.class.php"; $defaultenrol = enrolment_factory::factory($CFG->enrol); if (!method_exists($defaultenrol, 'print_entry')) { // switch enrollable to off for all courses in this case modify_database('', 'UPDATE prefix_course SET enrollable = 0'); } execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'"); execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''"); } if ($oldversion < 2006031000) { modify_database("", "CREATE TABLE prefix_post (\n `id` int(10) unsigned NOT NULL auto_increment,\n `userid` int(10) unsigned NOT NULL default '0',\n `courseid` int(10) unsigned NOT NULL default'0',\n `groupid` int(10) unsigned NOT NULL default'0',\n `moduleid` int(10) unsigned NOT NULL default'0',\n `coursemoduleid` int(10) unsigned NOT NULL default'0',\n `subject` varchar(128) NOT NULL default '',\n `summary` longtext,\n `content` longtext,\n `uniquehash` varchar(128) NOT NULL default '',\n `rating` int(10) unsigned NOT NULL default'0',\n `format` int(10) unsigned NOT NULL default'0',\n `publishstate` enum('draft','site','public') NOT NULL default 'draft',\n `lastmodified` int(10) unsigned NOT NULL default '0',\n `created` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `id_user_idx` (`id`, `userid`),\n KEY `post_lastmodified_idx` (`lastmodified`),\n KEY `post_subject_idx` (`subject`)\n ) TYPE=MyISAM COMMENT='New moodle post table. Holds data posts such as forum entries or blog entries.';"); modify_database("", "CREATE TABLE prefix_tags (\n `id` int(10) unsigned NOT NULL auto_increment,\n `type` varchar(255) NOT NULL default 'official',\n `userid` int(10) unsigned NOT NULL default'0',\n `text` varchar(255) NOT NULL default '',\n PRIMARY KEY (`id`)\n ) TYPE=MyISAM COMMENT ='tags structure for moodle.';"); modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n `id` int(10) unsigned NOT NULL auto_increment,\n `entryid` int(10) unsigned NOT NULL default'0',\n `tagid` int(10) unsigned NOT NULL default'0',\n `groupid` int(10) unsigned NOT NULL default'0',\n `courseid` int(10) unsigned NOT NULL default'0',\n `userid` int(10) unsigned NOT NULL default'0',\n PRIMARY KEY (`id`)\n ) TYPE=MyISAM COMMENT ='tag instance for blogs.';"); } if ($oldversion < 2006031400) { require_once "{$CFG->dirroot}/enrol/enrol.class.php"; $defaultenrol = enrolment_factory::factory($CFG->enrol); if (!method_exists($defaultenrol, 'print_entry')) { set_config('enrol', 'manual'); } } if ($oldversion < 2006031600) { execute_sql(" ALTER TABLE `{$CFG->prefix}grade_category` CHANGE `weight` `weight` decimal(5,2) default '0.00';"); } if ($oldversion < 2006032000) { table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id'); modify_database('', "ALTER TABLE prefix_post ADD INDEX post_module_idx (module);"); modify_database('', "UPDATE prefix_post SET module = 'blog';"); } if ($oldversion < 2006032001) { table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid'); modify_database('', "ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_entryid_idx (entryid);"); modify_database('', "ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_tagid_idx (tagid);"); modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';"); } if ($oldversion < 2006040500) { // Add an index to course_sections that was never upgraded (bug 5100) execute_sql(" CREATE INDEX coursesection ON {$CFG->prefix}course_sections (course,section) ", false); } /// change all the int(11) to int(10) for blogs and tags if ($oldversion < 2006041000) { table_column('post', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'courseid', 'courseid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'groupid', 'groupid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'moduleid', 'moduleid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'coursemoduleid', 'coursemoduleid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'rating', 'rating', 'integer', '10', 'unsigned', '0', 'not null'); table_column('post', 'format', 'format', 'integer', '10', 'unsigned', '0', 'not null'); table_column('tags', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null'); table_column('tags', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('blog_tag_instance', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null'); table_column('blog_tag_instance', 'entryid', 'entryid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('blog_tag_instance', 'tagid', 'tagid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('blog_tag_instance', 'groupid', 'groupid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('blog_tag_instance', 'courseid', 'courseid', 'integer', '10', 'unsigned', '0', 'not null'); table_column('blog_tag_instance', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null'); } if ($oldversion < 2006041001) { table_column('cache_text', 'formattedtext', 'formattedtext', 'longblob', '', '', '', 'not null'); } if ($oldversion < 2006041100) { table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible'); } if ($oldversion < 2006041801) { // forgot auto_increments for ids modify_database('', "ALTER TABLE prefix_post CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT"); modify_database('', "ALTER TABLE prefix_tags CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT"); modify_database('', "ALTER TABLE prefix_blog_tag_instance CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT"); } // changed user->firstname, user->lastname, course->shortname to varchar(100) if ($oldversion < 2006041900) { table_column('course', 'shortname', 'shortname', 'varchar', '100', '', '', 'not null'); table_column('user', 'firstname', 'firstname', 'varchar', '100', '', '', 'not null'); table_column('user', 'lastname', 'lastname', 'varchar', '100', '', '', 'not null'); } if ($oldversion < 2006042400) { // Look through table log_display and get rid of duplicates. $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display'); // Drop the log_display table and create it back with an id field. execute_sql("DROP TABLE {$CFG->prefix}log_display", false); modify_database('', "CREATE TABLE prefix_log_display (\n `id` int(10) unsigned NOT NULL auto_increment,\n `module` varchar(30),\n `action` varchar(40),\n `mtable` varchar(30),\n `field` varchar(50),\n PRIMARY KEY (`id`)\n ) TYPE=MyISAM"); // Add index to ensure that module and action combination is unique. modify_database('', "ALTER TABLE prefix_log_display ADD UNIQUE `moduleaction`(`module` , `action`)"); // Insert the records back in, sans duplicates. if ($rs && $rs->RecordCount() > 0) { while (!$rs->EOF) { $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')"; execute_sql($sql, false); $rs->MoveNext(); } } } // change tags->type to varchar(20), adding 2 indexes for tags table. if ($oldversion < 2006042401) { table_column('tags', 'type', 'type', 'varchar', '20', '', '', 'not null'); modify_database('', "ALTER TABLE prefix_tags ADD INDEX tags_typeuserid_idx (type(20), userid)"); modify_database('', "ALTER TABLE prefix_tags ADD INDEX tags_text_idx(text(255))"); } /*************************************************** * The following is an effort to change all the * * default NULLs to NOT NULL defaut '' in all * * mysql tables, to prevent 5303 and be consistent * ***************************************************/ if ($oldversion < 2006042800) { execute_sql("UPDATE {$CFG->prefix}grade_category SET name='' WHERE name IS NULL"); table_column('grade_category', 'name', 'name', 'varchar', '64', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}grade_category SET weight='0' WHERE weight IS NULL"); execute_sql("ALTER TABLE {$CFG->prefix}grade_category change weight weight decimal(5,2) NOT NULL default 0.00"); execute_sql("UPDATE {$CFG->prefix}grade_item SET courseid='0' WHERE courseid IS NULL"); table_column('grade_item', 'courseid', 'courseid', 'int', '10', 'unsigned', '0', 'not null'); execute_sql("UPDATE {$CFG->prefix}grade_item SET category='0' WHERE category IS NULL"); table_column('grade_item', 'category', 'category', 'int', '10', 'unsigned', '0', 'not null'); execute_sql("UPDATE {$CFG->prefix}grade_item SET modid='0' WHERE modid IS NULL"); table_column('grade_item', 'modid', 'modid', 'int', '10', 'unsigned', '0', 'not null'); execute_sql("UPDATE {$CFG->prefix}grade_item SET cminstance='0' WHERE cminstance IS NULL"); table_column('grade_item', 'cminstance', 'cminstance', 'int', '10', 'unsigned', '0', 'not null'); execute_sql("UPDATE {$CFG->prefix}grade_item SET scale_grade='0' WHERE scale_grade IS NULL"); execute_sql("ALTER TABLE {$CFG->prefix}grade_item change scale_grade scale_grade float(11,10) NOT NULL default 1.0000000000"); execute_sql("UPDATE {$CFG->prefix}grade_preferences SET courseid='0' WHERE courseid IS NULL"); table_column('grade_preferences', 'courseid', 'courseid', 'int', '10', 'unsigned', '0', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET idnumber='' WHERE idnumber IS NULL"); table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET icq='' WHERE icq IS NULL"); table_column('user', 'icq', 'icq', 'varchar', '15', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET skype='' WHERE skype IS NULL"); table_column('user', 'skype', 'skype', 'varchar', '50', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET yahoo='' WHERE yahoo IS NULL"); table_column('user', 'yahoo', 'yahoo', 'varchar', '50', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET aim='' WHERE aim IS NULL"); table_column('user', 'aim', 'aim', 'varchar', '50', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET msn='' WHERE msn IS NULL"); table_column('user', 'msn', 'msn', 'varchar', '50', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET phone1='' WHERE phone1 IS NULL"); table_column('user', 'phone1', 'phone1', 'varchar', '20', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET phone2='' WHERE phone2 IS NULL"); table_column('user', 'phone2', 'phone2', 'varchar', '20', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET institution='' WHERE institution IS NULL"); table_column('user', 'institution', 'institution', 'varchar', '40', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET department='' WHERE department IS NULL"); table_column('user', 'department', 'department', 'varchar', '30', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET address='' WHERE address IS NULL"); table_column('user', 'address', 'address', 'varchar', '70', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET city='' WHERE city IS NULL"); table_column('user', 'city', 'city', 'varchar', '20', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET country='' WHERE country IS NULL"); table_column('user', 'country', 'country', 'char', '2', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET lang='' WHERE lang IS NULL"); table_column('user', 'lang', 'lang', 'varchar', '10', '', 'en', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET lastIP='' WHERE lastIP IS NULL"); table_column('user', 'lastIP', 'lastIP', 'varchar', '15', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET secret='' WHERE secret IS NULL"); table_column('user', 'secret', 'secret', 'varchar', '15', '', '', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET picture='0' WHERE picture IS NULL"); table_column('user', 'picture', 'picture', 'tinyint', '1', '', '0', 'not null'); execute_sql("UPDATE {$CFG->prefix}user SET url='' WHERE url IS NULL"); table_column('user', 'url', 'url', 'varchar', '255', '', '', 'not null'); } if ($oldversion < 2006050400) { execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_deleted (deleted)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_confirmed (confirmed)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_firstname (firstname)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastname (lastname)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_city (city)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_country (country)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastaccess (lastaccess)", false); execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_email (email)", false); } if ($oldversion < 2006050500) { table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null'); } if ($oldversion < 2006050501) { table_column('sessions', 'data', 'data', 'mediumtext', '', '', '', 'not null'); } // renaming of reads and writes for stats_user_xyz if ($oldversion < 2006052400) { // change this later // we are using this because we want silent updates execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `reads` statsreads int(10) unsigned NOT NULL default 0", false); execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `writes` statswrites int(10) unsigned NOT NULL default 0", false); execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `reads` statsreads int(10) unsigned NOT NULL default 0", false); execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `writes` statswrites int(10) unsigned NOT NULL default 0", false); execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `reads` statsreads int(10) unsigned NOT NULL default 0", false); execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `writes` statswrites int(10) unsigned NOT NULL default 0", false); } // Adding some missing log actions if ($oldversion < 2006060400) { // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!) if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')"); } if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) { execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')"); } } //Renaming lastIP to lastip (all fields lowercase) if ($oldversion < 2006060900) { //Only if it exists $fields = $db->MetaColumnNames($CFG->prefix . 'user'); if (in_array('lastIP', $fields)) { table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "not null", "currentlogin"); } } // Change in MySQL 5.0.3 concerning how decimals are stored. Mimic from 16_STABLE // this isn't dangerous because it's a simple type change, but be careful with // versions and duplicate work in order to provide smooth upgrade paths. if ($oldversion < 2006071800) { table_column('grade_letter', 'grade_high', 'grade_high', 'decimal(5,2)', '', '', '100.00', 'not null', ''); table_column('grade_letter', 'grade_low', 'grade_low', 'decimal(5,2)', '', '', '0.00', 'not null', ''); } if ($oldversion < 2006080400) { execute_sql("CREATE TABLE {$CFG->prefix}role (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(255) NOT NULL default '',\n `shortname` varchar(100) NOT NULL default '',\n `description` text NOT NULL default '',\n `sortorder` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`)\n )", true); execute_sql("CREATE TABLE {$CFG->prefix}context (\n `id` int(10) unsigned NOT NULL auto_increment,\n `level` int(10) unsigned NOT NULL default '0',\n `instanceid` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`)\n )", true); execute_sql("CREATE TABLE {$CFG->prefix}role_assignments (\n `id` int(10) unsigned NOT NULL auto_increment,\n `roleid` int(10) unsigned NOT NULL default '0',\n `contextid` int(10) unsigned NOT NULL default '0',\n `userid` int(10) unsigned NOT NULL default '0',\n `hidden` int(1) unsigned NOT NULL default '0',\n `timestart` int(10) unsigned NOT NULL default '0',\n `timeend` int(10) unsigned NOT NULL default '0',\n `timemodified` int(10) unsigned NOT NULL default '0',\n `modifierid` int(10) unsigned NOT NULL default '0',\n `enrol` varchar(20) NOT NULL default '',\n `sortorder` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`)\n )", true); execute_sql("CREATE TABLE {$CFG->prefix}role_capabilities (\n `id` int(10) unsigned NOT NULL auto_increment,\n `contextid` int(10) unsigned NOT NULL default '0',\n `roleid` int(10) unsigned NOT NULL default '0',\n `capability` varchar(255) NOT NULL default '',\n `permission` int(10) unsigned NOT NULL default '0',\n `timemodified` int(10) unsigned NOT NULL default '0',\n `modifierid` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`)\n )", true); execute_sql("CREATE TABLE {$CFG->prefix}role_deny_grant (\n `id` int(10) unsigned NOT NULL auto_increment,\n `roleid` int(10) unsigned NOT NULL default '0',\n `unviewableroleid` int(10) unsigned NOT NULL default '0',\n PRIMARY KEY (`id`)\n )", true); execute_sql("CREATE TABLE {$CFG->prefix}capabilities ( \n `id` int(10) unsigned NOT NULL auto_increment, \n `name` varchar(255) NOT NULL default '', \n `captype` varchar(50) NOT NULL default '', \n `contextlevel` int(10) unsigned NOT NULL default '0', \n `component` varchar(100) NOT NULL default '', \n PRIMARY KEY (`id`) \n )", true); execute_sql("CREATE TABLE {$CFG->prefix}role_names ( \n `id` int(10) unsigned NOT NULL auto_increment, \n `roleid` int(10) unsigned NOT NULL default '0',\n `contextid` int(10) unsigned NOT NULL default '0', \n `text` text NOT NULL default '',\n PRIMARY KEY (`id`) \n )", true); } if ($oldversion < 2006081000) { execute_sql("ALTER TABLE `{$CFG->prefix}role` ADD INDEX `sortorder` (`sortorder`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD INDEX `instanceid` (`instanceid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `level-instanceid` (`level`, `instanceid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `roleid` (`roleid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `contextid` (`contextid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `userid` (`userid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD UNIQUE INDEX `contextid-roleid-userid` (`contextid`, `roleid`, `userid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `sortorder` (`sortorder`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `roleid` (`roleid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `contextid` (`contextid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `modifierid` (`modifierid`)", true); // MDL-10640 adding missing index from upgrade execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `capability` (`capability`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD UNIQUE INDEX `roleid-contextid-capability` (`roleid`, `contextid`, `capability`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `roleid` (`roleid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `unviewableroleid` (`unviewableroleid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD UNIQUE INDEX `roleid-unviewableroleid` (`roleid`, `unviewableroleid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}capabilities` ADD UNIQUE INDEX `name` (`name`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `roleid` (`roleid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `contextid` (`contextid`)", true); execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD UNIQUE INDEX `roleid-contextid` (`roleid`, `contextid`)", true); } if ($oldversion < 2006081600) { execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` CHANGE permission permission int(10) NOT NULL default '0'", true); } // drop role_deny_grant table, and create 2 new ones if ($oldversion < 2006081700) { execute_sql("DROP TABLE `{$CFG->prefix}role_deny_grant`", true); execute_sql("CREATE TABLE {$CFG->prefix}role_allow_assign (\n `id` int(10) unsigned NOT NULL auto_increment,\n `roleid` int(10) unsigned NOT NULL default '0',\n `allowassign` int(10) unsigned NOT NULL default '0',\n KEY `roleid` (`roleid`),\n KEY `allowassign` (`allowassign`),\n UNIQUE KEY `roleid-allowassign` (`roleid`, `allowassign`),\n PRIMARY KEY (`id`)\n )", true); execute_sql("CREATE TABLE {$CFG->prefix}role_allow_override (\n `id` int(10) unsigned NOT NULL auto_increment,\n `roleid` int(10) unsigned NOT NULL default '0',\n `allowoverride` int(10) unsigned NOT NULL default '0',\n KEY `roleid` (`roleid`),\n KEY `allowoverride` (`allowoverride`),\n UNIQUE KEY `roleid-allowoverride` (`roleid`, `allowoverride`),\n PRIMARY KEY (`id`)\n )", true); } if ($oldversion < 2006082100) { execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `level-instanceid`;", false); table_column('context', 'level', 'aggregatelevel', 'int', '10', 'unsigned', '0', 'not null', ''); execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `aggregatelevel-instanceid` (`aggregatelevel`, `instanceid`)", false); } if ($oldversion < 2006082200) { table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', ''); } if ($oldversion < 2006082800) { table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor'); } if ($oldversion < 2006082900) { execute_sql("DROP TABLE {$CFG->prefix}sessions", true); execute_sql("\n CREATE TABLE {$CFG->prefix}sessions2 (\n sesskey VARCHAR(64) NOT NULL default '',\n expiry DATETIME NOT NULL,\n expireref VARCHAR(250),\n created DATETIME NOT NULL,\n modified DATETIME NOT NULL,\n sessdata TEXT,\n CONSTRAINT PRIMARY KEY (sesskey)\n ) COMMENT='Optional database session storage in new format, not used by default';", true); execute_sql("\n CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true); execute_sql("\n CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true); } if ($oldversion < 2006083001) { table_column('sessions2', 'sessdata', 'sessdata', 'LONGTEXT', '', '', '', '', ''); } if ($oldversion < 2006083002) { table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', ''); } if ($oldversion < 2006083100) { execute_sql("ALTER TABLE {$CFG->prefix}course CHANGE modinfo modinfo longtext NULL AFTER showgrades"); } if ($oldversion < 2006083101) { execute_sql("ALTER TABLE {$CFG->prefix}course_categories CHANGE description description text NULL AFTER name"); } if ($oldversion < 2006083102) { execute_sql("ALTER TABLE {$CFG->prefix}user CHANGE description description text NULL AFTER url"); } if ($oldversion < 2006090200) { execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE summary summary text NULL AFTER section"); execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE sequence sequence text NULL AFTER section"); } // table to keep track of course page access times, used in online participants block, and participants list if ($oldversion < 2006091200) { execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n `id` int(10) unsigned NOT NULL auto_increment, \n `userid` int(10) unsigned NOT NULL default '0',\n `courseid` int(10) unsigned NOT NULL default '0', \n `timeaccess` int(10) unsigned NOT NULL default '0', \n KEY `userid` (`userid`),\n KEY `courseid` (`courseid`),\n UNIQUE KEY `userid-courseid` (`userid`, `courseid`),\n PRIMARY KEY (`id`) \n )TYPE=MYISAM COMMENT ='time user last accessed any page in a course';", true); } if ($oldversion < 2006091212) { // Reload the guest roles completely with new defaults if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) { delete_records('capabilities'); $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID); foreach ($guestroles as $guestrole) { delete_records('role_capabilities', 'roleid', $guestrole->id); assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id); } } } if ($oldversion < 2006091700) { table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null'); } if ($oldversion < 2006091800) { delete_records('config', 'name', 'showsiteparticipantslist'); delete_records('config', 'name', 'requestedteachername'); delete_records('config', 'name', 'requestedteachersname'); delete_records('config', 'name', 'requestedstudentname'); delete_records('config', 'name', 'requestedstudentsname'); } if ($oldversion < 2006091901) { if ($roles = get_records('role')) { $first = array_shift($roles); if (!empty($first->shortname)) { // shortnames already exist } else { table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name'); $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest'); foreach ($legacy_names as $name) { if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) { $i = ''; foreach ($roles as $role) { if (empty($role->shortname)) { $updated = new object(); $updated->id = $role->id; $updated->shortname = $name . $i; update_record('role', $updated); $i++; } } } } } } } /// Tables for customisable user profile fields if ($oldversion < 2006092000) { execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n id BIGINT(10) NOT NULL auto_increment,\n name VARCHAR(255) NOT NULL default '',\n datatype VARCHAR(255) NOT NULL default '',\n categoryid BIGINT(10) unsigned NOT NULL default 0,\n sortorder BIGINT(10) unsigned NOT NULL default 0,\n required TINYINT(2) unsigned NOT NULL default 0,\n locked TINYINT(2) unsigned NOT NULL default 0,\n visible SMALLINT(4) unsigned NOT NULL default 0,\n defaultdata LONGTEXT,\n CONSTRAINT PRIMARY KEY (id));", true); execute_sql("ALTER TABLE {$CFG->prefix}user_info_field COMMENT='Customisable user profile fields';", true); execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n id BIGINT(10) NOT NULL auto_increment,\n name VARCHAR(255) NOT NULL default '',\n sortorder BIGINT(10) unsigned NOT NULL default 0,\n CONSTRAINT PRIMARY KEY (id));", true); execute_sql("ALTER TABLE {$CFG->prefix}user_info_category COMMENT='Customisable fields categories';", true); execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n id BIGINT(10) NOT NULL auto_increment,\n userid BIGINT(10) unsigned NOT NULL default 0,\n fieldid BIGINT(10) unsigned NOT NULL default 0,\n data LONGTEXT NOT NULL,\n CONSTRAINT PRIMARY KEY (id));", true); execute_sql("ALTER TABLE {$CFG->prefix}user_info_data COMMENT='Data for the customisable user fields';", true); } if ($oldversion < 2006092200) { table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', ''); /* execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false); execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false); // see 2006092409 below */ } if ($oldversion < 2006092201) { execute_sql('TRUNCATE TABLE ' . $CFG->prefix . 'cache_text', true); table_column('cache_text', 'formattedtext', 'formattedtext', 'longtext', '', '', '', 'not null'); } if ($oldversion < 2006092302) { // fix sortorder first if needed if ($roles = get_all_roles()) { $i = 0; foreach ($roles as $rolex) { if ($rolex->sortorder != $i) { $r = new object(); $r->id = $rolex->id; $r->sortorder = $i; update_record('role', $r); } $i++; } } /* execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;", false); execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)", false);*/ } if ($oldversion < 2006092400) { table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', ''); } if ($oldversion < 2006092409) { // ok, once more and now correctly! execute_sql("DROP INDEX `aggregatelevel-instanceid` ON {$CFG->prefix}context ;", false); execute_sql("DROP INDEX `contextlevel-instanceid` ON {$CFG->prefix}context ;", false); execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false); execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix ON {$CFG->prefix}role ;", false); execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role ;", false); execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false); } if ($oldversion < 2006092601) { table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', ''); } ////// DO NOT ADD NEW THINGS HERE!! USE upgrade.php and the lib/ddllib.php functions. return $result; }
} } else { /************************************************************************ * * * context level is above or equal course context level * * in this case we pull out all users matching search criteria (if any) * * * ************************************************************************/ /// MDL-11111 do not include user already assigned this role in this context as available users /// so that the number of available users is right and we save time looping later $availableusers = get_recordset_sql('SELECT id, firstname, lastname, email FROM ' . $CFG->prefix . 'user WHERE ' . $select . ' AND id NOT IN ( SELECT u.id FROM ' . $CFG->prefix . 'role_assignments r, ' . $CFG->prefix . 'user u WHERE r.contextid = ' . $contextid . ' AND u.id = r.userid AND r.roleid = ' . $roleid . ' ' . $selectsql . ') ORDER BY lastname ASC, firstname ASC'); $usercount = $availableusers->_numOfRows; } echo '<div class="selector">'; $assignableroles = array('0' => get_string('listallroles', 'role') . '...') + $assignableroles; popup_form("{$CFG->wwwroot}/{$CFG->admin}/roles/assign.php?userid={$userid}&courseid={$courseid}&contextid={$contextid}&roleid=", $assignableroles, 'switchrole', $roleid, '', '', '', false, 'self', $strroletoassign); echo '</div>'; print_simple_box_start('center'); include 'assign.html'; print_simple_box_end(); if (!empty($errors)) {
/** * Update grades in central gradebook * * @param object $scorm null means all scormbases * @param int $userid specific user only, 0 mean all */ function scorm_update_grades($scorm = null, $userid = 0, $nullifnone = true) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once $CFG->libdir . '/gradelib.php'; } if ($scorm != null) { if ($grades = scorm_get_user_grades($scorm, $userid)) { grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grades); } else { if ($userid and $nullifnone) { $grade = new object(); $grade->userid = $userid; $grade->rawgrade = NULL; grade_update('mod/scorm', $scorm->course, 'mod', 'scorm', $scorm->id, 0, $grade); } } } else { $sql = "SELECT s.*, cm.idnumber as cmidnumber\n FROM {$CFG->prefix}scorm s, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m\n WHERE m.name='scorm' AND m.id=cm.module AND cm.instance=s.id"; if ($rs = get_recordset_sql($sql)) { if ($rs->RecordCount() > 0) { while ($scorm = rs_fetch_next_record($rs)) { scorm_grade_item_update($scorm); scorm_update_grades($scorm, 0, false); } } rs_close($rs); } } }