Ejemplo n.º 1
0
 /**
  * Runs the entire 'make' process.
  *
  * @return int Course id
  */
 public function make()
 {
     global $DB, $CFG;
     raise_memory_limit(MEMORY_EXTRA);
     if ($this->progress && !CLI_SCRIPT) {
         echo html_writer::start_tag('ul');
     }
     $entirestart = microtime(true);
     // Create courses.
     $prevchdir = getcwd();
     chdir($CFG->dirroot);
     $ncourse = self::get_last_testcourse_id();
     foreach (self::$sitecourses as $coursesize => $ncourses) {
         for ($i = 1; $i <= $ncourses[$this->size]; $i++) {
             // Non language-dependant shortname.
             $ncourse++;
             $this->run_create_course(self::SHORTNAMEPREFIX . $ncourse, $coursesize);
         }
     }
     chdir($prevchdir);
     // Store last course id to return it (will be the bigger one).
     $lastcourseid = $DB->get_field('course', 'id', array('shortname' => self::SHORTNAMEPREFIX . $ncourse));
     // Log total time.
     $this->log('sitecompleted', round(microtime(true) - $entirestart, 1));
     if ($this->progress && !CLI_SCRIPT) {
         echo html_writer::end_tag('ul');
     }
     return $lastcourseid;
 }
Ejemplo n.º 2
0
 public function search($q, $courseID = 0, $removeHiddenResults = false)
 {
     if (strlen($q) < 2) {
         return array('error' => get_string('error_query_too_short', 'block_search', 2));
     }
     raise_memory_limit(MEMORY_UNLIMITED);
     //Check if user cached results exist
     $userCacheValidFor = (int) get_config('block_search', 'cache_results_per_user');
     $useUserCache = $userCacheValidFor > 0;
     if (is_siteadmin()) {
         $useUserCache = false;
     }
     if ($useUserCache) {
         $cacheKey = md5(json_encode(array($q, $courseID, $removeHiddenResults)));
         $userCache = cache::make('block_search', 'user_searches');
         if ($results = $userCache->get($cacheKey)) {
             if ($results['filtered'] > time() - (int) $userCacheValidFor) {
                 $results['userCached'] = true;
                 return $results;
             }
         }
     }
     $search = new Search($q, $courseID);
     $search->filterResults($removeHiddenResults);
     $results = $search->getResults();
     if ($useUserCache) {
         $userCache->set($cacheKey, $results);
     }
     return $results;
 }
Ejemplo n.º 3
0
 /**
  * Takes the original course object, subpage cm id and
  * target course. It backs up a subpage in a course, modifies the
  * backup data, creates and restores to target course.
  *
  * @param mod_subpage $subpage subpage to copy from
  * @param object $newcourse Target course object
  */
 public function process($subpage, $newcourse)
 {
     global $CFG, $DB;
     // Start transaction.
     $transaction = $DB->start_delegated_transaction();
     // Raise memory limit for backup and restore.
     raise_memory_limit(MEMORY_EXTRA);
     echo \html_writer::tag('div', get_string('copy_wait', 'subpage'));
     $spsectionid = $subpage->get_course_module()->section;
     // Backup the course.
     $backupstart = time();
     $this->display_progress(get_string('copy_backingupcourse', 'subpage'));
     list($activityids, $sectionids) = $this->get_includes($subpage);
     $backupid = $this->backup($subpage->get_course(), $activityids, array_merge($sectionids, array($spsectionid)));
     $this->display_progress(null, $backupstart);
     // Update backup file.
     $updatebackupstart = time();
     $this->display_progress(get_string('copy_modifyingbackup', 'subpage'));
     $this->update_backup($this->backupbasepath, $newcourse->id, $sectionids, $spsectionid, $subpage->get_course_module()->id);
     $this->display_progress(null, $updatebackupstart);
     // Restore into a new course.
     $restorestart = time();
     $this->display_progress(get_string('copy_restoringcourse', 'subpage'));
     $this->restore($backupid, $newcourse);
     $this->display_progress(null, $restorestart);
     // Completed OK, so commit transaction.
     $transaction->allow_commit();
 }
Ejemplo n.º 4
0
Archivo: lib.php Proyecto: ftecpos/ia2
function print_object_moodle($object)
{
    // we may need a lot of memory here
    raise_memory_limit(MEMORY_EXTRA);
    if (CLI_SCRIPT) {
        //fwrite(STDERR, print_r($object, true));
        // fwrite(STDERR, PHP_EOL);
    } else {
        echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
    }
}
 /**
  * Inform existing open recordsets that transaction
  * is starting, this works around MARS problem described
  * in MDL-37734.
  */
 public function transaction_starts()
 {
     if ($this->buffer !== null) {
         $this->unregister();
         return;
     }
     if (!$this->rsrc) {
         $this->unregister();
         return;
     }
     // This might eat memory pretty quickly...
     raise_memory_limit('2G');
     $this->buffer = array();
     while ($next = $this->fetch_next()) {
         $this->buffer[] = $next;
     }
 }
 function apply($discussion, $all, $selected, $formdata)
 {
     global $COURSE, $USER, $CFG;
     // Get HTML
     $poststext = '';
     $postshtml = '';
     $discussion->build_selected_posts_email($selected, $poststext, $postshtml, false);
     // Remove all styles
     $postshtml = preg_replace('~(<[^>]*)\\sclass\\s*=\\s*("[^"]*")|(\'[^\']*\')([^>*]>)~', '$1$4', $postshtml);
     $postshtml = preg_replace('~(<[^>]*)\\sstyle\\s*=\\s*("[^"]*")|(\'[^\']*\')([^>*]>)~', '$1$4', $postshtml);
     $postshtml = preg_replace('~<hr[^>]*/>~', '', $postshtml);
     // Add link back to discussion
     $postshtml .= '<div><a href="' . $CFG->wwwroot . '/mod/forumng/discuss.php?' . $discussion->get_link_params(forum::PARAM_HTML) . '">' . get_string('savedposts_original', 'forumng') . '</a></div>';
     // Get title
     if ($all) {
         $title = get_string('savedposts_all', 'forumng', $discussion->get_subject());
         $tags = get_string('savedposts_all_tag', 'forumng');
     } else {
         if (count($selected) == 1) {
             $post = $discussion->get_root_post()->find_child(reset($selected));
             $a = (object) array('subject' => $post->get_effective_subject(), 'name' => $post->get_forum()->display_user_name($post->get_user()));
             $title = get_string('savedposts_one', 'forumng', $a);
             $tags = get_string('savedposts_one_tag', 'forumng');
         } else {
             $title = get_string('savedposts_selected', 'forumng', $discussion->get_subject());
             $tags = get_string('savedposts_selected_tag', 'forumng');
         }
     }
     raise_memory_limit('512M');
     // Do portfolio save
     $username = portfolioGetUsername();
     $itemid = "forumngposts" . portfolioGetUUID();
     $dataid = portfolioFormPutContent($itemid, array('ouportfolio:title' => $title, 'ouportfolio:tags' => $tags), $postshtml);
     // Redirect back to discussion
     $discussionurl = $CFG->wwwroot . '/mod/forumng/discuss.php?' . $discussion->get_link_params(forum::PARAM_PLAIN);
     if ($dataid === FALSE) {
         print_error('error_portfoliosave', 'forumng', $discussionurl);
     } else {
         redirect($discussionurl, get_string('savedtoportfolio', 'forumng'));
     }
 }
Ejemplo n.º 7
0
 /**
  * Executes the backup
  * @return void Throws and exception of completes
  */
 public function execute_plan()
 {
     // Basic/initial prevention against time/memory limits
     core_php_time_limit::raise(1 * 60 * 60);
     // 1 hour for 1 course initially granted
     raise_memory_limit(MEMORY_EXTRA);
     // If this is not a course backup, inform the plan we are not
     // including all the activities for sure. This will affect any
     // task/step executed conditionally to stop including information
     // for section and activity backup. MDL-28180.
     if ($this->get_type() !== backup::TYPE_1COURSE) {
         $this->log('notifying plan about excluded activities by type', backup::LOG_DEBUG);
         $this->plan->set_excluding_activities();
     }
     return $this->plan->execute();
 }
 /**
  * Runs the automated backups if required
  *
  * @global moodle_database $DB
  */
 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE)
 {
     global $CFG, $DB;
     $status = true;
     $emailpending = false;
     $now = time();
     $config = get_config('backup');
     mtrace("Checking automated backup status", '...');
     $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
     if ($state === backup_cron_automated_helper::STATE_DISABLED) {
         mtrace('INACTIVE');
         return $state;
     } else {
         if ($state === backup_cron_automated_helper::STATE_RUNNING) {
             mtrace('RUNNING');
             if ($rundirective == self::RUN_IMMEDIATELY) {
                 mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
             } else {
                 mtrace("automated backup are already running. Execution delayed");
             }
             return $state;
         } else {
             mtrace('OK');
         }
     }
     backup_cron_automated_helper::set_state_running();
     mtrace("Getting admin info");
     $admin = get_admin();
     if (!$admin) {
         mtrace("Error: No admin account was found");
         $state = false;
     }
     if ($status) {
         mtrace("Checking courses");
         mtrace("Skipping deleted courses", '...');
         mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
     }
     if ($status) {
         mtrace('Running required automated backups...');
         cron_trace_time_and_memory();
         // This could take a while!
         core_php_time_limit::raise();
         raise_memory_limit(MEMORY_EXTRA);
         $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now);
         $showtime = "undefined";
         if ($nextstarttime > 0) {
             $showtime = date('r', $nextstarttime);
         }
         $rs = $DB->get_recordset('course');
         foreach ($rs as $course) {
             $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
             if (!$backupcourse) {
                 $backupcourse = new stdClass();
                 $backupcourse->courseid = $course->id;
                 $backupcourse->laststatus = self::BACKUP_STATUS_NOTYETRUN;
                 $DB->insert_record('backup_courses', $backupcourse);
                 $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
             }
             // The last backup is considered as successful when OK or SKIPPED.
             $lastbackupwassuccessful = ($backupcourse->laststatus == self::BACKUP_STATUS_SKIPPED || $backupcourse->laststatus == self::BACKUP_STATUS_OK) && ($backupcourse->laststarttime > 0 && $backupcourse->lastendtime > 0);
             // Assume that we are not skipping anything.
             $skipped = false;
             $skippedmessage = '';
             // Check if we are going to be running the backup now.
             $shouldrunnow = $backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now || $rundirective == self::RUN_IMMEDIATELY;
             // If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
             if ($shouldrunnow && $config->backup_auto_skip_hidden) {
                 $skipped = $config->backup_auto_skip_hidden && !$course->visible;
                 $skippedmessage = 'Not visible';
             }
             // If config backup_auto_skip_modif_days is set to true, skip courses
             // that have not been modified since the number of days defined.
             if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
                 $timenotmodifsincedays = $now - $config->backup_auto_skip_modif_days * DAYSECS;
                 // Check log if there were any modifications to the course content.
                 $logexists = self::is_course_modified($course->id, $timenotmodifsincedays);
                 $skipped = $course->timemodified <= $timenotmodifsincedays && !$logexists;
                 $skippedmessage = 'Not modified in the past ' . $config->backup_auto_skip_modif_days . ' days';
             }
             // If config backup_auto_skip_modif_prev is set to true, skip courses
             // that have not been modified since previous backup.
             if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
                 // Check log if there were any modifications to the course content.
                 $logexists = self::is_course_modified($course->id, $backupcourse->laststarttime);
                 $skipped = $course->timemodified <= $backupcourse->laststarttime && !$logexists;
                 $skippedmessage = 'Not modified since previous backup';
             }
             // Check if the course is not scheduled to run right now.
             if (!$shouldrunnow) {
                 $backupcourse->nextstarttime = $nextstarttime;
                 $DB->update_record('backup_courses', $backupcourse);
                 mtrace('Skipping ' . $course->fullname . ' (Not scheduled for backup until ' . $showtime . ')');
             } else {
                 if ($skipped) {
                     // Must have been skipped for a reason.
                     $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
                     $backupcourse->nextstarttime = $nextstarttime;
                     $DB->update_record('backup_courses', $backupcourse);
                     mtrace('Skipping ' . $course->fullname . ' (' . $skippedmessage . ')');
                     mtrace('Backup of \'' . $course->fullname . '\' is scheduled on ' . $showtime);
                 } else {
                     // Backup every non-skipped courses.
                     mtrace('Backing up ' . $course->fullname . '...');
                     // We have to send an email because we have included at least one backup.
                     $emailpending = true;
                     // Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error).
                     if ($backupcourse->laststatus != self::BACKUP_STATUS_UNFINISHED) {
                         // Set laststarttime.
                         $starttime = time();
                         $backupcourse->laststarttime = time();
                         $backupcourse->laststatus = self::BACKUP_STATUS_UNFINISHED;
                         $DB->update_record('backup_courses', $backupcourse);
                         $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
                         $backupcourse->lastendtime = time();
                         $backupcourse->nextstarttime = $nextstarttime;
                         $DB->update_record('backup_courses', $backupcourse);
                         if ($backupcourse->laststatus === self::BACKUP_STATUS_OK) {
                             // Clean up any excess course backups now that we have
                             // taken a successful backup.
                             $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
                         }
                     }
                     mtrace("complete - next execution: {$showtime}");
                 }
             }
         }
         $rs->close();
     }
     //Send email to admin if necessary
     if ($emailpending) {
         mtrace("Sending email to admin");
         $message = "";
         $count = backup_cron_automated_helper::get_backup_status_array();
         $haserrors = $count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0;
         // Build the message text.
         // Summary.
         $message .= get_string('summary') . "\n";
         $message .= "==================================================\n";
         $message .= '  ' . get_string('courses') . '; ' . array_sum($count) . "\n";
         $message .= '  ' . get_string('ok') . '; ' . $count[self::BACKUP_STATUS_OK] . "\n";
         $message .= '  ' . get_string('skipped') . '; ' . $count[self::BACKUP_STATUS_SKIPPED] . "\n";
         $message .= '  ' . get_string('error') . '; ' . $count[self::BACKUP_STATUS_ERROR] . "\n";
         $message .= '  ' . get_string('unfinished') . '; ' . $count[self::BACKUP_STATUS_UNFINISHED] . "\n";
         $message .= '  ' . get_string('warning') . '; ' . $count[self::BACKUP_STATUS_WARNING] . "\n";
         $message .= '  ' . get_string('backupnotyetrun') . '; ' . $count[self::BACKUP_STATUS_NOTYETRUN] . "\n\n";
         //Reference
         if ($haserrors) {
             $message .= "  " . get_string('backupfailed') . "\n\n";
             $dest_url = "{$CFG->wwwroot}/report/backups/index.php";
             $message .= "  " . get_string('backuptakealook', '', $dest_url) . "\n\n";
             //Set message priority
             $admin->priority = 1;
             //Reset unfinished to error
             $DB->set_field('backup_courses', 'laststatus', '0', array('laststatus' => '2'));
         } else {
             $message .= "  " . get_string('backupfinished') . "\n";
         }
         //Build the message subject
         $site = get_site();
         $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))) . ": ";
         if ($haserrors) {
             $prefix .= "[" . strtoupper(get_string('error')) . "] ";
         }
         $subject = $prefix . get_string('automatedbackupstatus', 'backup');
         //Send the message
         $eventdata = new stdClass();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $admin;
         $eventdata->userto = $admin;
         $eventdata->subject = $subject;
         $eventdata->fullmessage = $message;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         $eventdata->component = 'moodle';
         $eventdata->name = 'backup';
         message_send($eventdata);
     }
     //Everything is finished stop backup_auto_running
     backup_cron_automated_helper::set_state_running(false);
     mtrace('Automated backups complete.');
     return $status;
 }
Ejemplo n.º 9
0
 * @copyright  2004 onwards Martin Dougiamas (http://dougiamas.com)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require '../config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->libdir . '/csvlib.class.php';
require_once $CFG->dirroot . '/user/profile/lib.php';
require_once $CFG->dirroot . '/group/lib.php';
require_once $CFG->dirroot . '/cohort/lib.php';
require_once 'uploaduserlib.php';
require_once 'uploaduser_form.php';
$iid = optional_param('iid', '', PARAM_INT);
$previewrows = optional_param('previewrows', 10, PARAM_INT);
@set_time_limit(60 * 60);
// 1 hour should be enough
raise_memory_limit(MEMORY_HUGE);
require_login();
admin_externalpage_setup('uploadusers');
require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM));
$struserrenamed = get_string('userrenamed', 'admin');
$strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
$strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
$strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
$strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
$struserupdated = get_string('useraccountupdated', 'admin');
$strusernotupdated = get_string('usernotupdatederror', 'error');
$strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
$strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
$struseruptodate = get_string('useraccountuptodate', 'admin');
$struseradded = get_string('newuser');
$strusernotadded = get_string('usernotaddedregistered', 'error');
Ejemplo n.º 10
0
    mtrace('Cleaned up contexts');
    gc_cache_flags();
    mtrace('Cleaned cache flags');
    // If you suspect that the context paths are somehow corrupt
    // replace the line below with: build_context_path(true);
    build_context_path();
    mtrace('Built context paths');
    mtrace("Finished clean-up tasks...");
}
// End of occasional clean-up tasks
if (empty($CFG->disablescheduledbackups)) {
    // Defined in config.php
    //Execute backup's cron
    //Perhaps a long time and memory could help in large sites
    @set_time_limit(0);
    @raise_memory_limit("192M");
    if (function_exists('apache_child_terminate')) {
        // if we are running from Apache, give httpd a hint that
        // it can recycle the process after it's done. Apache's
        // memory management is truly awful but we can help it.
        @apache_child_terminate();
    }
    if (file_exists("{$CFG->dirroot}/backup/backup_scheduled.php") and file_exists("{$CFG->dirroot}/backup/backuplib.php") and file_exists("{$CFG->dirroot}/backup/lib.php") and file_exists("{$CFG->libdir}/blocklib.php")) {
        include_once "{$CFG->dirroot}/backup/backup_scheduled.php";
        include_once "{$CFG->dirroot}/backup/backuplib.php";
        include_once "{$CFG->dirroot}/backup/lib.php";
        require_once "{$CFG->libdir}/blocklib.php";
        mtrace("Running backups if required...");
        if (!schedule_backup_cron()) {
            mtrace("ERROR: Something went wrong while performing backup tasks!!!");
        } else {
Ejemplo n.º 11
0
/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    set_time_limit(0);
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run cleanup core cron jobs, but not every time since they aren't too important.
    // These don't have a timer to reduce load, so we'll use a random number
    // to randomly choose the percentage of times we should run these jobs.
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        cron_trace_time_and_memory();
        // Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                delete_user($user);
                // we MUST delete user properly first
                $DB->delete_records('user', array('id' => $user->id));
                // this is a bloody hack, but it might work
                mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
            }
            $rs->close();
        }
        // Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
            }
            $rs->close();
        }
        // 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;
            $DB->delete_records_select("log", "time < ?", array($loglifetime));
            mtrace(" Deleted old log records");
        }
        // Delete old backup_controllers and logs.
        $loglifetime = get_config('backup', 'loglifetime');
        if (!empty($loglifetime)) {
            // Value in days.
            $loglifetime = $timenow - $loglifetime * 3600 * 24;
            // Delete child records from backup_logs.
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers.
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace(" Deleted old backup records");
        }
        // Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
            mtrace(" Deleted old cache_text records");
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace(' Executed tag cron');
        }
        // Context maintenance stuff
        context_helper::cleanup_instances();
        mtrace(' Cleaned up context instances');
        context_helper::build_all_paths(false);
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: context_helper::build_all_paths(true);
        mtrace(' Built context paths');
        // Remove expired cache flags
        gc_cache_flags();
        mtrace(' Cleaned cache flags');
        // Cleanup messaging
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace(' Cleaned up read notifications');
        }
        mtrace(' Deleting temporary files...');
        cron_delete_from_temp();
        // Cleanup user password reset records
        // Delete any reset request records which are expired by more than a day.
        // (We keep recently expired requests around so we can give a different error msg to users who
        // are trying to user a recently expired reset attempt).
        $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
        $earliestvalid = time() - $pwresettime - DAYSECS;
        $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
        mtrace(' Cleaned up old password reset records');
        mtrace("...finished clean-up tasks");
    }
    // End of occasional clean-up tasks
    // Send login failures notification - brute force protection in moodle is weak,
    // we should at least send notices early in each cron execution
    if (notify_login_failures()) {
        mtrace(' Notified login failures');
    }
    // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
    context_helper::create_instances();
    mtrace(' Created missing context instances');
    // Session gc.
    mtrace("Running session gc tasks...");
    \core\session\manager::gc();
    mtrace("...finished stale session cleanup");
    // Run the auth cron, if any before enrolments
    // because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    cron_trace_time_and_memory();
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    // Generate new password emails for users - ppl expect these generated asap
    if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
        mtrace('Creating passwords for new users...');
        $usernamefields = get_all_user_name_fields(true, 'u');
        $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n                                                 {$usernamefields}, u.username, u.lang,\n                                                 p.id as prefid\n                                            FROM {user} u\n                                            JOIN {user_preferences} p ON u.id=p.userid\n                                           WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
        // note: we can not send emails to suspended accounts
        foreach ($newusers as $newuser) {
            // Use a low cost factor when generating bcrypt hash otherwise
            // hashing would be slow when emailing lots of users. Hashes
            // will be automatically updated to a higher cost factor the first
            // time the user logs in.
            if (setnew_password_and_mail($newuser, true)) {
                unset_user_preference('create_password', $newuser);
                set_user_preference('auth_forcepasswordchange', 1, $newuser);
            } else {
                trigger_error("Could not create and mail new user password!");
            }
        }
        $newusers->close();
    }
    // It is very important to run enrol early
    // because other plugins depend on correct enrolment info.
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        cron_trace_time_and_memory();
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    // Run all cron jobs for each module
    mtrace("Starting activity modules");
    get_mailer('buffer');
    if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        foreach ($mods as $mod) {
            $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php";
            if (file_exists($libfile)) {
                include_once $libfile;
                $cron_function = $mod->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing module function {$cron_function} ...", '');
                    cron_trace_time_and_memory();
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    // Reset possible changes by modules to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace("done.");
                }
            }
        }
    }
    get_mailer('close');
    mtrace("Finished activity modules");
    mtrace("Starting blocks");
    if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        // We will need the base class.
        require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
        foreach ($blocks as $block) {
            $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php';
            if (file_exists($blockfile)) {
                require_once $blockfile;
                $classname = 'block_' . $block->name;
                $blockobj = new $classname();
                if (method_exists($blockobj, 'cron')) {
                    mtrace("Processing cron function for " . $block->name . '....', '');
                    cron_trace_time_and_memory();
                    if ($blockobj->cron()) {
                        $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                    }
                    // Reset possible changes by blocks to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace('done.');
                }
            }
        }
    }
    mtrace('Finished blocks');
    mtrace('Starting admin reports');
    cron_execute_plugin_type('report');
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job...');
    cron_trace_time_and_memory();
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    cron_trace_time_and_memory();
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        cron_trace_time_and_memory();
        require_once $CFG->dirroot . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        cron_trace_time_and_memory();
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace('Starting course reports');
    cron_execute_plugin_type('coursereport');
    mtrace('Finished course reports');
    // run gradebook import/export/report cron
    mtrace('Starting gradebook plugins');
    cron_execute_plugin_type('gradeimport');
    cron_execute_plugin_type('gradeexport');
    cron_execute_plugin_type('gradereport');
    mtrace('Finished gradebook plugins');
    // run calendar cron
    require_once "{$CFG->dirroot}/calendar/lib.php";
    calendar_cron();
    // Run external blog cron if needed
    if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        cron_trace_time_and_memory();
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
        mtrace('done.');
    }
    // Run blog associations cleanup
    if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        cron_trace_time_and_memory();
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
        mtrace('done.');
    }
    // Run question bank clean-up.
    mtrace("Starting the question bank cron...", '');
    cron_trace_time_and_memory();
    require_once $CFG->libdir . '/questionlib.php';
    question_bank::cron();
    mtrace('done.');
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    cron_trace_time_and_memory();
    require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // If enabled, fetch information about available updates and eventually notify site admins
    if (empty($CFG->disableupdatenotifications)) {
        $updateschecker = \core\update\checker::instance();
        $updateschecker->cron();
    }
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    cron_trace_time_and_memory();
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // all other plugins
    cron_execute_plugin_type('message', 'message plugins');
    cron_execute_plugin_type('filter', 'filters');
    cron_execute_plugin_type('editor', 'editors');
    cron_execute_plugin_type('format', 'course formats');
    cron_execute_plugin_type('profilefield', 'profile fields');
    cron_execute_plugin_type('webservice', 'webservices');
    cron_execute_plugin_type('repository', 'repository plugins');
    cron_execute_plugin_type('qbehaviour', 'question behaviours');
    cron_execute_plugin_type('qformat', 'question import/export formats');
    cron_execute_plugin_type('qtype', 'question types');
    cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
    cron_execute_plugin_type('theme', 'themes');
    cron_execute_plugin_type('tool', 'admin tools');
    // and finally run any local cronjobs, if any
    if ($locals = core_component::get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        // new cron functions in lib.php first
        cron_execute_plugin_type('local');
        // legacy cron files are executed directly
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace('Running cache cron routines');
    cache_helper::cron();
    mtrace('done.');
    // Run automated backups if required - these may take a long time to execute
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    // Run stats as at the end because they are known to take very long time on large sites
    if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
        require_once $CFG->dirroot . '/lib/statslib.php';
        // check we're not before our runtime
        $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
        if (time() > $timetocheck) {
            // process configured number of days as max (defaulting to 31)
            $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
            if (stats_cron_daily($maxdays)) {
                if (stats_cron_weekly()) {
                    if (stats_cron_monthly()) {
                        stats_clean_old();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // Run badges review cron.
    mtrace("Starting badges cron...");
    require_once $CFG->dirroot . '/badges/cron.php';
    badge_cron();
    mtrace('done.');
    // cleanup file trash - not very important
    $fs = get_file_storage();
    $fs->cron();
    mtrace("Cron script completed correctly");
    gc_collect_cycles();
    mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
Ejemplo n.º 12
0
 /**
  * Performs a full sync with external database.
  *
  * First it creates new courses if necessary, then
  * enrols and unenrols users.
  *
  * @param bool $verbose
  * @return int 0 means success, 1 db connect failure, 4 db read failure
  */
 public function sync_courses($verbose = false)
 {
     global $CFG, $DB;
     // make sure we sync either enrolments or courses
     if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('newcoursetable') or !$this->get_config('newcoursefullname') or !$this->get_config('newcourseshortname')) {
         if ($verbose) {
             mtrace('Course synchronisation skipped.');
         }
         return 0;
     }
     if ($verbose) {
         mtrace('Starting course synchronisation...');
     }
     // we may need a lot of memory here
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     if (!($extdb = $this->db_init())) {
         mtrace('Error while communicating with external enrolment database');
         return 1;
     }
     // first create new courses
     $table = $this->get_config('newcoursetable');
     $fullname = strtolower($this->get_config('newcoursefullname'));
     $shortname = strtolower($this->get_config('newcourseshortname'));
     $idnumber = strtolower($this->get_config('newcourseidnumber'));
     $category = strtolower($this->get_config('newcoursecategory'));
     $localcategoryfield = $this->get_config('localcategoryfield', 'id');
     $sqlfields = array($fullname, $shortname);
     if ($category) {
         $sqlfields[] = $category;
     }
     if ($idnumber) {
         $sqlfields[] = $idnumber;
     }
     $sql = $this->db_get_sql($table, array(), $sqlfields);
     $createcourses = array();
     if ($rs = $extdb->Execute($sql)) {
         if (!$rs->EOF) {
             while ($fields = $rs->FetchRow()) {
                 $fields = array_change_key_case($fields, CASE_LOWER);
                 $fields = $this->db_decode($fields);
                 if (empty($fields[$shortname]) or empty($fields[$fullname])) {
                     if ($verbose) {
                         mtrace('  error: invalid external course record, shortname and fullname are mandatory: ' . json_encode($fields));
                         // hopefully every geek can read JS, right?
                     }
                     continue;
                 }
                 if ($DB->record_exists('course', array('shortname' => $fields[$shortname]))) {
                     // already exists
                     continue;
                 }
                 // allow empty idnumber but not duplicates
                 if ($idnumber and $fields[$idnumber] !== '' and $fields[$idnumber] !== null and $DB->record_exists('course', array('idnumber' => $fields[$idnumber]))) {
                     if ($verbose) {
                         mtrace('  error: duplicate idnumber, can not create course: ' . $fields[$shortname] . ' [' . $fields[$idnumber] . ']');
                     }
                     continue;
                 }
                 if ($category and !($coursecategory = $DB->get_record('course_categories', array($localcategoryfield => $fields[$category]), 'id'))) {
                     if ($verbose) {
                         mtrace('  error: invalid category ' . $localcategoryfield . ', can not create course: ' . $fields[$shortname]);
                     }
                     continue;
                 }
                 $course = new stdClass();
                 $course->fullname = $fields[$fullname];
                 $course->shortname = $fields[$shortname];
                 $course->idnumber = $idnumber ? $fields[$idnumber] : '';
                 $course->category = $category ? $coursecategory->id : NULL;
                 $createcourses[] = $course;
             }
         }
         $rs->Close();
     } else {
         mtrace('Error reading data from the external course table');
         $extdb->Close();
         return 4;
     }
     if ($createcourses) {
         require_once "{$CFG->dirroot}/course/lib.php";
         $templatecourse = $this->get_config('templatecourse');
         $defaultcategory = $this->get_config('defaultcategory');
         $template = false;
         if ($templatecourse) {
             if ($template = $DB->get_record('course', array('shortname' => $templatecourse))) {
                 unset($template->id);
                 unset($template->fullname);
                 unset($template->shortname);
                 unset($template->idnumber);
             } else {
                 if ($verbose) {
                     mtrace("  can not find template for new course!");
                 }
             }
         }
         if (!$template) {
             $courseconfig = get_config('moodlecourse');
             $template = new stdClass();
             $template->summary = '';
             $template->summaryformat = FORMAT_HTML;
             $template->format = $courseconfig->format;
             $template->numsections = $courseconfig->numsections;
             $template->hiddensections = $courseconfig->hiddensections;
             $template->newsitems = $courseconfig->newsitems;
             $template->showgrades = $courseconfig->showgrades;
             $template->showreports = $courseconfig->showreports;
             $template->maxbytes = $courseconfig->maxbytes;
             $template->groupmode = $courseconfig->groupmode;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
             $template->visible = $courseconfig->visible;
             $template->lang = $courseconfig->lang;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
         }
         if (!$DB->record_exists('course_categories', array('id' => $defaultcategory))) {
             if ($verbose) {
                 mtrace("  default course category does not exist!");
             }
             $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
             $first = reset($categories);
             $defaultcategory = $first->id;
         }
         foreach ($createcourses as $fields) {
             $newcourse = clone $template;
             $newcourse->fullname = $fields->fullname;
             $newcourse->shortname = $fields->shortname;
             $newcourse->idnumber = $fields->idnumber;
             $newcourse->category = $fields->category ? $fields->category : $defaultcategory;
             $c = create_course($newcourse);
             if ($verbose) {
                 mtrace("  creating course: {$c->id}, {$c->fullname}, {$c->shortname}, {$c->idnumber}, {$c->category}");
             }
         }
         unset($createcourses);
         unset($template);
     }
     // close db connection
     $extdb->Close();
     if ($verbose) {
         mtrace('...course synchronisation finished.');
     }
     return 0;
 }
Ejemplo n.º 13
0
 /**
  * Forces synchronisation of all enrolments with LDAP server.
  * It creates courses if the plugin is configured to do so.
  *
  * @param progress_trace $trace
  * @param int|null $onecourse limit sync to one course->id, null if all courses
  * @return void
  */
 public function sync_enrolments(progress_trace $trace, $onecourse = null)
 {
     global $CFG, $DB;
     if (!$this->ldap_connect($trace)) {
         $trace->finished();
         return;
     }
     $ldap_pagedresults = ldap_paged_results_supported($this->get_config('ldap_version'));
     // we may need a lot of memory here
     core_php_time_limit::raise();
     raise_memory_limit(MEMORY_HUGE);
     $oneidnumber = null;
     if ($onecourse) {
         if (!($course = $DB->get_record('course', array('id' => $onecourse), 'id,' . $this->enrol_localcoursefield))) {
             // Course does not exist, nothing to do.
             $trace->output("Requested course {$onecourse} does not exist, no sync performed.");
             $trace->finished();
             return;
         }
         if (empty($course->{$this->enrol_localcoursefield})) {
             $trace->output("Requested course {$onecourse} does not have {$this->enrol_localcoursefield}, no sync performed.");
             $trace->finished();
             return;
         }
         $oneidnumber = ldap_filter_addslashes(core_text::convert($course->idnumber, 'utf-8', $this->get_config('ldapencoding')));
     }
     // Get enrolments for each type of role.
     $roles = get_all_roles();
     $enrolments = array();
     foreach ($roles as $role) {
         // Get all contexts
         $ldap_contexts = explode(';', $this->config->{'contexts_role' . $role->id});
         // Get all the fields we will want for the potential course creation
         // as they are light. Don't get membership -- potentially a lot of data.
         $ldap_fields_wanted = array('dn', $this->config->course_idnumber);
         if (!empty($this->config->course_fullname)) {
             array_push($ldap_fields_wanted, $this->config->course_fullname);
         }
         if (!empty($this->config->course_shortname)) {
             array_push($ldap_fields_wanted, $this->config->course_shortname);
         }
         if (!empty($this->config->course_summary)) {
             array_push($ldap_fields_wanted, $this->config->course_summary);
         }
         array_push($ldap_fields_wanted, $this->config->{'memberattribute_role' . $role->id});
         // Define the search pattern
         $ldap_search_pattern = $this->config->objectclass;
         if ($oneidnumber !== null) {
             $ldap_search_pattern = "(&{$ldap_search_pattern}({$this->config->course_idnumber}={$oneidnumber}))";
         }
         $ldap_cookie = '';
         foreach ($ldap_contexts as $ldap_context) {
             $ldap_context = trim($ldap_context);
             if (empty($ldap_context)) {
                 continue;
                 // Next;
             }
             $flat_records = array();
             do {
                 if ($ldap_pagedresults) {
                     ldap_control_paged_result($this->ldapconnection, $this->config->pagesize, true, $ldap_cookie);
                 }
                 if ($this->config->course_search_sub) {
                     // Use ldap_search to find first user from subtree
                     $ldap_result = @ldap_search($this->ldapconnection, $ldap_context, $ldap_search_pattern, $ldap_fields_wanted);
                 } else {
                     // Search only in this context
                     $ldap_result = @ldap_list($this->ldapconnection, $ldap_context, $ldap_search_pattern, $ldap_fields_wanted);
                 }
                 if (!$ldap_result) {
                     continue;
                     // Next
                 }
                 if ($ldap_pagedresults) {
                     ldap_control_paged_result_response($this->ldapconnection, $ldap_result, $ldap_cookie);
                 }
                 // Check and push results
                 $records = ldap_get_entries($this->ldapconnection, $ldap_result);
                 // LDAP libraries return an odd array, really. fix it:
                 for ($c = 0; $c < $records['count']; $c++) {
                     array_push($flat_records, $records[$c]);
                 }
                 // Free some mem
                 unset($records);
             } while ($ldap_pagedresults && !empty($ldap_cookie));
             // If LDAP paged results were used, the current connection must be completely
             // closed and a new one created, to work without paged results from here on.
             if ($ldap_pagedresults) {
                 $this->ldap_close();
                 $this->ldap_connect($trace);
             }
             if (count($flat_records)) {
                 $ignorehidden = $this->get_config('ignorehiddencourses');
                 foreach ($flat_records as $course) {
                     $course = array_change_key_case($course, CASE_LOWER);
                     $idnumber = $course[$this->config->course_idnumber][0];
                     $trace->output(get_string('synccourserole', 'enrol_ldap', array('idnumber' => $idnumber, 'role_shortname' => $role->shortname)));
                     // Does the course exist in moodle already?
                     $course_obj = $DB->get_record('course', array($this->enrol_localcoursefield => $idnumber));
                     if (empty($course_obj)) {
                         // Course doesn't exist
                         if ($this->get_config('autocreate')) {
                             // Autocreate
                             $trace->output(get_string('createcourseextid', 'enrol_ldap', array('courseextid' => $idnumber)));
                             if (!($newcourseid = $this->create_course($course, $trace))) {
                                 continue;
                             }
                             $course_obj = $DB->get_record('course', array('id' => $newcourseid));
                         } else {
                             $trace->output(get_string('createnotcourseextid', 'enrol_ldap', array('courseextid' => $idnumber)));
                             continue;
                             // Next; skip this one!
                         }
                     } else {
                         // Check if course needs update & update as needed.
                         $this->update_course($course_obj, $course, $trace);
                     }
                     // Enrol & unenrol
                     // Pull the ldap membership into a nice array
                     // this is an odd array -- mix of hash and array --
                     $ldapmembers = array();
                     if (array_key_exists('memberattribute_role' . $role->id, $this->config) && !empty($this->config->{'memberattribute_role' . $role->id}) && !empty($course[$this->config->{'memberattribute_role' . $role->id}])) {
                         // May have no membership!
                         $ldapmembers = $course[$this->config->{'memberattribute_role' . $role->id}];
                         unset($ldapmembers['count']);
                         // Remove oddity ;)
                         // If we have enabled nested groups, we need to expand
                         // the groups to get the real user list. We need to do
                         // this before dealing with 'memberattribute_isdn'.
                         if ($this->config->nested_groups) {
                             $users = array();
                             foreach ($ldapmembers as $ldapmember) {
                                 $grpusers = $this->ldap_explode_group($ldapmember, $this->config->{'memberattribute_role' . $role->id});
                                 $users = array_merge($users, $grpusers);
                             }
                             $ldapmembers = array_unique($users);
                             // There might be duplicates.
                         }
                         // Deal with the case where the member attribute holds distinguished names,
                         // but only if the user attribute is not a distinguished name itself.
                         if ($this->config->memberattribute_isdn && $this->config->idnumber_attribute !== 'dn' && $this->config->idnumber_attribute !== 'distinguishedname') {
                             // We need to retrieve the idnumber for all the users in $ldapmembers,
                             // as the idnumber does not match their dn and we get dn's from membership.
                             $memberidnumbers = array();
                             foreach ($ldapmembers as $ldapmember) {
                                 $result = ldap_read($this->ldapconnection, $ldapmember, '(objectClass=*)', array($this->config->idnumber_attribute));
                                 $entry = ldap_first_entry($this->ldapconnection, $result);
                                 $values = ldap_get_values($this->ldapconnection, $entry, $this->config->idnumber_attribute);
                                 array_push($memberidnumbers, $values[0]);
                             }
                             $ldapmembers = $memberidnumbers;
                         }
                     }
                     // Prune old ldap enrolments
                     // hopefully they'll fit in the max buffer size for the RDBMS
                     $sql = "SELECT u.id as userid, u.username, ue.status,\n                                      ra.contextid, ra.itemid as instanceid\n                                 FROM {user} u\n                                 JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.component = 'enrol_ldap' AND ra.roleid = :roleid)\n                                 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = ra.itemid)\n                                 JOIN {enrol} e ON (e.id = ue.enrolid)\n                                WHERE u.deleted = 0 AND e.courseid = :courseid ";
                     $params = array('roleid' => $role->id, 'courseid' => $course_obj->id);
                     $context = context_course::instance($course_obj->id);
                     if (!empty($ldapmembers)) {
                         list($ldapml, $params2) = $DB->get_in_or_equal($ldapmembers, SQL_PARAMS_NAMED, 'm', false);
                         $sql .= "AND u.idnumber {$ldapml}";
                         $params = array_merge($params, $params2);
                         unset($params2);
                     } else {
                         $shortname = format_string($course_obj->shortname, true, array('context' => $context));
                         $trace->output(get_string('emptyenrolment', 'enrol_ldap', array('role_shortname' => $role->shortname, 'course_shortname' => $shortname)));
                     }
                     $todelete = $DB->get_records_sql($sql, $params);
                     if (!empty($todelete)) {
                         $transaction = $DB->start_delegated_transaction();
                         foreach ($todelete as $row) {
                             $instance = $DB->get_record('enrol', array('id' => $row->instanceid));
                             switch ($this->get_config('unenrolaction')) {
                                 case ENROL_EXT_REMOVED_UNENROL:
                                     $this->unenrol_user($instance, $row->userid);
                                     $trace->output(get_string('extremovedunenrol', 'enrol_ldap', array('user_username' => $row->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                                     break;
                                 case ENROL_EXT_REMOVED_KEEP:
                                     // Keep - only adding enrolments
                                     break;
                                 case ENROL_EXT_REMOVED_SUSPEND:
                                     if ($row->status != ENROL_USER_SUSPENDED) {
                                         $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid' => $instance->id, 'userid' => $row->userid));
                                         $trace->output(get_string('extremovedsuspend', 'enrol_ldap', array('user_username' => $row->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                                     }
                                     break;
                                 case ENROL_EXT_REMOVED_SUSPENDNOROLES:
                                     if ($row->status != ENROL_USER_SUSPENDED) {
                                         $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid' => $instance->id, 'userid' => $row->userid));
                                     }
                                     role_unassign_all(array('contextid' => $row->contextid, 'userid' => $row->userid, 'component' => 'enrol_ldap', 'itemid' => $instance->id));
                                     $trace->output(get_string('extremovedsuspendnoroles', 'enrol_ldap', array('user_username' => $row->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                                     break;
                             }
                         }
                         $transaction->allow_commit();
                     }
                     // Insert current enrolments
                     // bad we can't do INSERT IGNORE with postgres...
                     // Add necessary enrol instance if not present yet;
                     $sql = "SELECT c.id, c.visible, e.id as enrolid\n                                  FROM {course} c\n                                  JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'ldap')\n                                 WHERE c.id = :courseid";
                     $params = array('courseid' => $course_obj->id);
                     if (!($course_instance = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE))) {
                         $course_instance = new stdClass();
                         $course_instance->id = $course_obj->id;
                         $course_instance->visible = $course_obj->visible;
                         $course_instance->enrolid = $this->add_instance($course_instance);
                     }
                     if (!($instance = $DB->get_record('enrol', array('id' => $course_instance->enrolid)))) {
                         continue;
                         // Weird; skip this one.
                     }
                     if ($ignorehidden && !$course_instance->visible) {
                         continue;
                     }
                     $transaction = $DB->start_delegated_transaction();
                     foreach ($ldapmembers as $ldapmember) {
                         $sql = 'SELECT id,username,1 FROM {user} WHERE idnumber = ? AND deleted = 0';
                         $member = $DB->get_record_sql($sql, array($ldapmember));
                         if (empty($member) || empty($member->id)) {
                             $trace->output(get_string('couldnotfinduser', 'enrol_ldap', $ldapmember));
                             continue;
                         }
                         $sql = "SELECT ue.status\n                                     FROM {user_enrolments} ue\n                                     JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'ldap')\n                                    WHERE e.courseid = :courseid AND ue.userid = :userid";
                         $params = array('courseid' => $course_obj->id, 'userid' => $member->id);
                         $userenrolment = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
                         if (empty($userenrolment)) {
                             $this->enrol_user($instance, $member->id, $role->id);
                             // Make sure we set the enrolment status to active. If the user wasn't
                             // previously enrolled to the course, enrol_user() sets it. But if we
                             // configured the plugin to suspend the user enrolments _AND_ remove
                             // the role assignments on external unenrol, then enrol_user() doesn't
                             // set it back to active on external re-enrolment. So set it
                             // unconditionally to cover both cases.
                             $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid' => $instance->id, 'userid' => $member->id));
                             $trace->output(get_string('enroluser', 'enrol_ldap', array('user_username' => $member->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                         } else {
                             if (!$DB->record_exists('role_assignments', array('roleid' => $role->id, 'userid' => $member->id, 'contextid' => $context->id, 'component' => 'enrol_ldap', 'itemid' => $instance->id))) {
                                 // This happens when reviving users or when user has multiple roles in one course.
                                 $context = context_course::instance($course_obj->id);
                                 role_assign($role->id, $member->id, $context->id, 'enrol_ldap', $instance->id);
                                 $trace->output("Assign role to user '{$member->username}' in course '{$course_obj->shortname} ({$course_obj->id})'");
                             }
                             if ($userenrolment->status == ENROL_USER_SUSPENDED) {
                                 // Reenable enrolment that was previously disabled. Enrolment refreshed
                                 $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid' => $instance->id, 'userid' => $member->id));
                                 $trace->output(get_string('enroluserenable', 'enrol_ldap', array('user_username' => $member->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                             }
                         }
                     }
                     $transaction->allow_commit();
                 }
             }
         }
     }
     @$this->ldap_close();
     $trace->finished();
 }
 /**
  * Temporarily allocates extra resources needed to export reports
  */
 static function allocate_extra_resources()
 {
     global $CFG;
     //disable the time limit for this executing script
     @set_time_limit(0);
     //up the memory limit
     if (empty($CFG->extramemorylimit)) {
         raise_memory_limit('128M');
     } else {
         raise_memory_limit($CFG->extramemorylimit);
     }
 }
Ejemplo n.º 15
0
/** this function will restore an entire backup.zip into the specified course
 * using standard moodle backup/restore functions, but silently.
 * @param string $pathtofile the absolute path to the backup file.
 * @param int $destinationcourse the course id to restore to.
 * @param boolean $emptyfirst whether to delete all coursedata first.
 * @param boolean $userdata whether to include any userdata that may be in the backup file.
 * @param array $preferences optional, 0 will be used.  Can contain:
 *   metacourse
 *   logs
 *   course_files
 *   messages
 */
function import_backup_file_silently($pathtofile, $destinationcourse, $emptyfirst = false, $userdata = false, $preferences = array())
{
    global $CFG, $SESSION, $USER, $DB;
    // is there such a thing on cron? I guess so..
    global $restore;
    // ick
    if (!defined('RESTORE_SILENTLY')) {
        define('RESTORE_SILENTLY', true);
        // don't output all the stuff to us.
    }
    $debuginfo = 'import_backup_file_silently: ';
    $cleanupafter = false;
    $errorstr = '';
    // passed by reference to restore_precheck to get errors from.
    if (!($course = $DB->get_record('course', array('id' => $destinationcourse)))) {
        mtrace($debuginfo . 'Course with id $destinationcourse was not a valid course!');
        return false;
    }
    // first check we have a valid file.
    if (!file_exists($pathtofile) || !is_readable($pathtofile)) {
        mtrace($debuginfo . 'File ' . $pathtofile . ' either didn\'t exist or wasn\'t readable');
        return false;
    }
    // now make sure it's a zip file
    require_once $CFG->dirroot . '/lib/filelib.php';
    $filename = substr($pathtofile, strrpos($pathtofile, '/') + 1);
    $mimetype = mimeinfo("type", $filename);
    if ($mimetype != 'application/zip') {
        mtrace($debuginfo . 'File ' . $pathtofile . ' was of wrong mimetype (' . $mimetype . ')');
        return false;
    }
    // restore_precheck wants this within dataroot, so lets put it there if it's not already..
    if (strstr($pathtofile, $CFG->dataroot) === false) {
        // first try and actually move it..
        if (!check_dir_exists($CFG->dataroot . '/temp/backup/', true)) {
            mtrace($debuginfo . 'File ' . $pathtofile . ' outside of dataroot and couldn\'t move it! ');
            return false;
        }
        if (!copy($pathtofile, $CFG->dataroot . '/temp/backup/' . $filename)) {
            mtrace($debuginfo . 'File ' . $pathtofile . ' outside of dataroot and couldn\'t move it! ');
            return false;
        } else {
            $pathtofile = 'temp/backup/' . $filename;
            $cleanupafter = true;
        }
    } else {
        // it is within dataroot, so take it off the path for restore_precheck.
        $pathtofile = substr($pathtofile, strlen($CFG->dataroot . '/'));
    }
    if (!backup_required_functions()) {
        mtrace($debuginfo . 'Required function check failed (see backup_required_functions)');
        return false;
    }
    @ini_set("max_execution_time", "3000");
    if (empty($CFG->extramemorylimit)) {
        raise_memory_limit('128M');
    } else {
        raise_memory_limit($CFG->extramemorylimit);
    }
    if (!($backup_unique_code = restore_precheck($destinationcourse, $pathtofile, $errorstr, true))) {
        mtrace($debuginfo . 'Failed restore_precheck (error was ' . $errorstr . ')');
        return false;
    }
    $SESSION->restore = new StdClass();
    // add on some extra stuff we need...
    $SESSION->restore->metacourse = $restore->metacourse = isset($preferences['restore_metacourse']) ? $preferences['restore_metacourse'] : 0;
    $SESSION->restore->restoreto = $restore->restoreto = 1;
    $SESSION->restore->users = $restore->users = $userdata;
    $SESSION->restore->groups = $restore->groups = isset($preferences['restore_groups']) ? $preferences['restore_groups'] : RESTORE_GROUPS_NONE;
    $SESSION->restore->logs = $restore->logs = isset($preferences['restore_logs']) ? $preferences['restore_logs'] : 0;
    $SESSION->restore->user_files = $restore->user_files = $userdata;
    $SESSION->restore->messages = $restore->messages = isset($preferences['restore_messages']) ? $preferences['restore_messages'] : 0;
    $SESSION->restore->blogs = $restore->blogs = isset($preferences['restore_blogs']) ? $preferences['restore_blogs'] : 0;
    $SESSION->restore->course_id = $restore->course_id = $destinationcourse;
    $SESSION->restore->restoreto = 1;
    $SESSION->restore->course_id = $destinationcourse;
    $SESSION->restore->deleting = $emptyfirst;
    $SESSION->restore->restore_course_files = $restore->course_files = isset($preferences['restore_course_files']) ? $preferences['restore_course_files'] : 0;
    $SESSION->restore->restore_site_files = $restore->site_files = isset($preferences['restore_site_files']) ? $preferences['restore_site_files'] : 0;
    $SESSION->restore->backup_version = $SESSION->info->backup_backup_version;
    $SESSION->restore->course_startdateoffset = $course->startdate - $SESSION->course_header->course_startdate;
    restore_setup_for_check($SESSION->restore, $backup_unique_code);
    // maybe we need users (defaults to 2 in restore_setup_for_check)
    if (!empty($userdata)) {
        $SESSION->restore->users = 1;
    }
    // we also need modules...
    if ($allmods = $DB->get_records("modules")) {
        foreach ($allmods as $mod) {
            $modname = $mod->name;
            //Now check that we have that module info in the backup file
            if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
                $SESSION->restore->mods[$modname]->restore = true;
                $SESSION->restore->mods[$modname]->userinfo = $userdata;
            } else {
                // avoid warnings
                $SESSION->restore->mods[$modname]->restore = false;
                $SESSION->restore->mods[$modname]->userinfo = false;
            }
        }
    }
    $restore = clone $SESSION->restore;
    if (!restore_execute($SESSION->restore, $SESSION->info, $SESSION->course_header, $errorstr)) {
        mtrace($debuginfo . 'Failed restore_execute (error was ' . $errorstr . ')');
        return false;
    }
    return true;
}
 * @author Marc Alier i Forment
 * @author David Castro, Ferran Recio, Jordi Piguillem, UPC, 
 * and members of DFWikiteam listed at http://morfeo.upc.edu/crom
 * @version  $Id: exporthtmllib.php,v 1.5 2007/06/15 11:43:18 pigui Exp $
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package HTML_export
 */
require_once '../../../backup/lib.php';
require_once $CFG->libdir . '/filelib.php';
require_once 'sintax.php';
//global variables
global $CFG;
global $WS;
//Adjust some php variables to the execution of this script
@ini_set("max_execution_time", "3000");
raise_memory_limit("memory_limit", "256M");
function wiki_export_html(&$WS)
{
    global $CFG;
    check_dir_exists("{$CFG->dataroot}/temp", true);
    check_dir_exists("{$CFG->dataroot}/temp/html", true);
    check_dir_exists("{$CFG->dataroot}/temp/html/dfwiki{$WS->cm->id}", true);
    check_dir_exists("{$CFG->dataroot}/temp/html/dfwiki{$WS->cm->id}/atachments", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}/moddata", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}/moddata/dfwiki{$WS->cm->id}", true);
    //export contents
    wiki_export_html_content($WS);
    //export attached files
    $flist = list_directories_and_files("{$CFG->dataroot}/{$WS->dfwiki->course}/moddata/dfwiki{$WS->cm->id}");
    if ($flist != null) {
Ejemplo n.º 17
0
            $mform->display();
            echo $OUTPUT->footer();
            die;
        }
    }
}
// Data has already been submitted so we can use the $iid to retrieve it.
$mform2 = new import_mapping_form(null, array('iid' => $iid));
if ($mform2->is_cancelled()) {
    redirect($url);
} else {
    if ($formdata = $mform2->get_data()) {
        $csvimport = new csv_import_reader($iid, 'rooms');
        $header = $csvimport->get_columns();
        @set_time_limit(0);
        raise_memory_limit(MEMORY_EXTRA);
        $csvimport->init();
        $info = array();
        while ($line = $csvimport->next()) {
            if (count($line) <= 1) {
                // there is no data on this line, move on
                continue;
            }
            $data = new stdClass();
            $data->fecha_reserva = $line[0];
            $data->modulo = $line[1];
            $data->confirmado = $line[2];
            $data->activa = $line[3];
            $data->alumno_id = $line[4];
            $data->salas_id = $line[5];
            $data->comentario_alumno = $line[6];
Ejemplo n.º 18
0
/**
 * Upgrade/install other parts of moodle
 * @param bool $verbose
 * @return void, may throw exception
 */
function upgrade_noncore($verbose) {
    global $CFG;

    raise_memory_limit(MEMORY_EXTRA);

    // upgrade all plugins types
    try {
        // Reset caches before any output.
        cache_helper::purge_all(true);
        purge_all_caches();

        $plugintypes = core_component::get_plugin_types();
        foreach ($plugintypes as $type=>$location) {
            upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
        }
        // Update cache definitions. Involves scanning each plugin for any changes.
        cache_helper::update_definitions();
        // Mark the site as upgraded.
        set_config('allversionshash', core_component::get_all_versions_hash());

        // Purge caches again, just to be sure we arn't holding onto old stuff now.
        cache_helper::purge_all(true);
        purge_all_caches();

    } catch (Exception $ex) {
        upgrade_handle_exception($ex);
    }
}
Ejemplo n.º 19
0
 /**
  * Sync all meta course links.
  *
  * @param progress_trace $trace
  * @param int $courseid one course, empty mean all
  * @return int 0 means ok, 1 means error, 2 means plugin disabled
  */
 public function sync(progress_trace $trace, $courseid = null)
 {
     global $DB;
     if (!enrol_is_enabled('manual')) {
         $trace->finished();
         return 2;
     }
     // Unfortunately this may take a long time, execution can be interrupted safely here.
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     $trace->output('Verifying manual enrolment expiration...');
     $params = array('now' => time(), 'useractive' => ENROL_USER_ACTIVE, 'courselevel' => CONTEXT_COURSE);
     $coursesql = "";
     if ($courseid) {
         $coursesql = "AND e.courseid = :courseid";
         $params['courseid'] = $courseid;
     }
     // Deal with expired accounts.
     $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
     if ($action == ENROL_EXT_REMOVED_UNENROL) {
         $instances = array();
         $sql = "SELECT ue.*, e.courseid, c.id AS contextid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')\n                      JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)\n                     WHERE ue.timeend > 0 AND ue.timeend < :now\n                           {$coursesql}";
         $rs = $DB->get_recordset_sql($sql, $params);
         foreach ($rs as $ue) {
             if (empty($instances[$ue->enrolid])) {
                 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
             }
             $instance = $instances[$ue->enrolid];
             // Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
             role_unassign_all(array('userid' => $ue->userid, 'contextid' => $ue->contextid, 'component' => '', 'itemid' => 0), true);
             $this->unenrol_user($instance, $ue->userid);
             $trace->output("unenrolling expired user {$ue->userid} from course {$instance->courseid}", 1);
         }
         $rs->close();
         unset($instances);
     } else {
         if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
             $instances = array();
             $sql = "SELECT ue.*, e.courseid, c.id AS contextid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')\n                      JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)\n                     WHERE ue.timeend > 0 AND ue.timeend < :now\n                           AND ue.status = :useractive\n                           {$coursesql}";
             $rs = $DB->get_recordset_sql($sql, $params);
             foreach ($rs as $ue) {
                 if (empty($instances[$ue->enrolid])) {
                     $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
                 }
                 $instance = $instances[$ue->enrolid];
                 // Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
                 role_unassign_all(array('userid' => $ue->userid, 'contextid' => $ue->contextid, 'component' => '', 'itemid' => 0), true);
                 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
                 $trace->output("suspending expired user {$ue->userid} in course {$instance->courseid}", 1);
             }
             $rs->close();
             unset($instances);
         } else {
             // ENROL_EXT_REMOVED_KEEP means no changes.
         }
     }
     $trace->output('...manual enrolment updates finished.');
     $trace->finished();
     return 0;
 }
Ejemplo n.º 20
0
    public function display($quiz, $cm, $course) {
        global $CFG, $DB, $OUTPUT;

        list($currentgroup, $students, $groupstudents, $allowed) =
                $this->init('responses', 'quiz_responses_settings_form', $quiz, $cm, $course);
        $options = new quiz_responses_options('responses', $quiz, $cm, $course);

        if ($fromform = $this->form->get_data()) {
            $options->process_settings_from_form($fromform);

        } else {
            $options->process_settings_from_params();
        }

        $this->form->set_data($options->get_initial_form_data());

        if ($options->attempts == self::ALL_WITH) {
            // This option is only available to users who can access all groups in
            // groups mode, so setting allowed to empty (which means all quiz attempts
            // are accessible, is not a security porblem.
            $allowed = array();
        }

        // Load the required questions.
        $questions = quiz_report_get_significant_questions($quiz);

        // Prepare for downloading, if applicable.
        $courseshortname = format_string($course->shortname, true,
                array('context' => context_course::instance($course->id)));
        $table = new quiz_responses_table($quiz, $this->context, $this->qmsubselect,
                $options, $groupstudents, $students, $questions, $this->get_base_url());
        $filename = quiz_report_download_filename(get_string('responsesfilename', 'quiz_responses'),
                $courseshortname, $quiz->name);
        $table->is_downloading($options->download, $filename,
                $courseshortname . ' ' . format_string($quiz->name, true));
        if ($table->is_downloading()) {
            raise_memory_limit(MEMORY_EXTRA);
        }

        $this->process_actions($quiz, $cm, $currentgroup, $groupstudents, $allowed, $options->get_url());

        // Start output.
        if (!$table->is_downloading()) {
            // Only print headers if not asked to download data.
            $this->print_header_and_tabs($cm, $course, $quiz, $this->mode);
        }

        if ($groupmode = groups_get_activity_groupmode($cm)) {
            // Groups are being used, so output the group selector if we are not downloading.
            if (!$table->is_downloading()) {
                groups_print_activity_menu($cm, $options->get_url());
            }
        }

        // Print information on the number of existing attempts.
        if (!$table->is_downloading()) {
            // Do not print notices when downloading.
            if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) {
                echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>';
            }
        }

        $hasquestions = quiz_questions_in_quiz($quiz->questions);
        if (!$table->is_downloading()) {
            if (!$hasquestions) {
                echo quiz_no_questions_message($quiz, $cm, $this->context);
            } else if (!$students) {
                echo $OUTPUT->notification(get_string('nostudentsyet'));
            } else if ($currentgroup && !$groupstudents) {
                echo $OUTPUT->notification(get_string('nostudentsingroup'));
            }

            // Print the display options.
            $this->form->display();
        }

        $hasstudents = $students && (!$currentgroup || $groupstudents);
        if ($hasquestions && ($hasstudents || $options->attempts == self::ALL_WITH)) {

            list($fields, $from, $where, $params) = $table->base_sql($allowed);

            $table->set_count_sql("SELECT COUNT(1) FROM $from WHERE $where", $params);

            $table->set_sql($fields, $from, $where, $params);

            if (!$table->is_downloading()) {
                // Print information on the grading method.
                if ($strattempthighlight = quiz_report_highlighting_grading_method(
                        $quiz, $this->qmsubselect, $options->onlygraded)) {
                    echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>';
                }
            }

            // Define table columns.
            $columns = array();
            $headers = array();

            if (!$table->is_downloading() && $options->checkboxcolumn) {
                $columns[] = 'checkbox';
                $headers[] = null;
            }

            $this->add_user_columns($table, $columns, $headers);
            $this->add_state_column($columns, $headers);

            if ($table->is_downloading()) {
                $this->add_time_columns($columns, $headers);
            }

            $this->add_grade_columns($quiz, $options->usercanseegrades, $columns, $headers);

            foreach ($questions as $id => $question) {
                if ($options->showqtext) {
                    $columns[] = 'question' . $id;
                    $headers[] = get_string('questionx', 'question', $question->number);
                }
                if ($options->showresponses) {
                    $columns[] = 'response' . $id;
                    $headers[] = get_string('responsex', 'quiz_responses', $question->number);
                }
                if ($options->showright) {
                    $columns[] = 'right' . $id;
                    $headers[] = get_string('rightanswerx', 'quiz_responses', $question->number);
                }
            }

            $table->define_columns($columns);
            $table->define_headers($headers);
            $table->sortable(true, 'uniqueid');

            // Set up the table.
            $table->define_baseurl($options->get_url());

            $this->configure_user_columns($table);

            $table->no_sorting('feedbacktext');
            $table->column_class('sumgrades', 'bold');

            $table->set_attribute('id', 'attempts');

            $table->collapsible(true);

            $table->out($options->pagesize, true);
        }
        return true;
    }
Ejemplo n.º 21
0
define('PUBLIC', 1);
define('CRON', 1);
define('TITLE', '');
require dirname(dirname(__FILE__)) . '/init.php';
require_once get_config('docroot') . 'artefact/lib.php';
require_once get_config('docroot') . 'import/lib.php';
require_once get_config('docroot') . 'export/lib.php';
require_once get_config('docroot') . 'lib/activity.php';
require_once get_config('docroot') . 'lib/file.php';
// This is here for debugging purposes, it allows us to fake the time to test
// cron behaviour
$realstart = time();
$fake = isset($argv[1]);
$start = $fake ? strtotime($argv[1]) : $realstart;
log_info('---------- cron running ' . date('r', $start) . ' ----------');
raise_memory_limit('128M');
if (!is_writable(get_config('dataroot'))) {
    log_warn("Unable to write to dataroot directory.");
}
// for each plugin type
foreach (plugin_types() as $plugintype) {
    $table = $plugintype . '_cron';
    // get list of cron jobs to run for this plugin type
    $now = $fake ? time() - ($realstart - $start) : time();
    $jobs = get_records_select_array($table, 'nextrun < ? OR nextrun IS NULL', array(db_format_timestamp($now)), '', 'plugin,callfunction,minute,hour,day,month,dayofweek,' . db_format_tsfield('nextrun'));
    if ($jobs) {
        // for each cron entry
        foreach ($jobs as $job) {
            if (!cron_lock($job, $start, $plugintype)) {
                continue;
            }
 public function generate_csv($rid = '', $userid = '', $choicecodes = 1, $choicetext = 0, $currentgroupid)
 {
     global $DB;
     raise_memory_limit('1G');
     $output = array();
     $stringother = get_string('other', 'questionnaire');
     $config = get_config('questionnaire', 'downloadoptions');
     $options = empty($config) ? array() : explode(',', $config);
     $columns = array();
     $types = array();
     foreach ($options as $option) {
         if (in_array($option, array('response', 'submitted', 'id'))) {
             $columns[] = get_string($option, 'questionnaire');
             $types[] = 0;
         } else {
             $columns[] = get_string($option);
             $types[] = 1;
         }
     }
     $nbinfocols = count($columns);
     $idtocsvmap = array('0', '0', '1', '1', '0', '0', '0', '0', '0', '1', '0');
     if (!($survey = $DB->get_record('questionnaire_survey', array('id' => $this->survey->id)))) {
         print_error('surveynotexists', 'questionnaire');
     }
     // Get all responses for this survey in one go.
     $allresponsesrs = $this->get_survey_all_responses($rid, $userid);
     // Do we have any questions of type RADIO, DROP, CHECKBOX OR RATE? If so lets get all their choices in one go.
     $choicetypes = $this->choice_types();
     // Get unique list of question types used in this survey.
     $uniquetypes = $this->get_survey_questiontypes();
     if (count(array_intersect($choicetypes, $uniquetypes) > 0)) {
         $choiceparams = [$this->survey->id];
         $choicesql = "\n                SELECT DISTINCT c.id as cid, q.id as qid, q.precise AS precise, q.name, c.content\n                  FROM {questionnaire_question} q\n                  JOIN {questionnaire_quest_choice} c ON question_id = q.id\n                 WHERE q.survey_id = ? ORDER BY cid ASC\n            ";
         $choicerecords = $DB->get_records_sql($choicesql, $choiceparams);
         $choicesbyqid = [];
         if (!empty($choicerecords)) {
             // Hash the options by question id.
             foreach ($choicerecords as $choicerecord) {
                 if (!isset($choicesbyqid[$choicerecord->qid])) {
                     // New question id detected, intialise empty array to store choices.
                     $choicesbyqid[$choicerecord->qid] = [];
                 }
                 $choicesbyqid[$choicerecord->qid][$choicerecord->cid] = $choicerecord;
             }
         }
     }
     $num = 1;
     $questionidcols = [];
     foreach ($this->questions as $question) {
         // Skip questions that aren't response capable.
         if (!isset($question->response)) {
             continue;
         }
         // Establish the table's field names.
         $qid = $question->id;
         $qpos = $question->position;
         $col = $question->name;
         $type = $question->type_id;
         if (in_array($type, $choicetypes)) {
             /* single or multiple or rate */
             if (!isset($choicesbyqid[$qid])) {
                 throw new coding_exception('Choice question has no choices!', 'question id ' . $qid . ' of type ' . $type);
             }
             $choices = $choicesbyqid[$qid];
             $subqnum = 0;
             switch ($type) {
                 case QUESRADIO:
                     // Single.
                 // Single.
                 case QUESDROP:
                     $columns[][$qpos] = $col;
                     $questionidcols[][$qpos] = $qid;
                     array_push($types, $idtocsvmap[$type]);
                     $thisnum = 1;
                     foreach ($choices as $choice) {
                         $content = $choice->content;
                         // If "Other" add a column for the actual "other" text entered.
                         if (preg_match('/^!other/', $content)) {
                             $col = $choice->name . '_' . $stringother;
                             $columns[][$qpos] = $col;
                             $questionidcols[][$qpos] = null;
                             array_push($types, '0');
                         }
                     }
                     break;
                 case QUESCHECK:
                     // Multiple.
                     $thisnum = 1;
                     foreach ($choices as $choice) {
                         $content = $choice->content;
                         $modality = '';
                         $contents = questionnaire_choice_values($content);
                         if ($contents->modname) {
                             $modality = $contents->modname;
                         } else {
                             if ($contents->title) {
                                 $modality = $contents->title;
                             } else {
                                 $modality = strip_tags($contents->text);
                             }
                         }
                         $col = $choice->name . '->' . $modality;
                         $columns[][$qpos] = $col;
                         $questionidcols[][$qpos] = $qid . '_' . $choice->cid;
                         array_push($types, '0');
                         // If "Other" add a column for the "other" checkbox. Then add a column for the actual "other" text entered.
                         if (preg_match('/^!other/', $content)) {
                             $content = $stringother;
                             $col = $choice->name . '->[' . $content . ']';
                             $columns[][$qpos] = $col;
                             $questionidcols[][$qpos] = null;
                             array_push($types, '0');
                         }
                     }
                     break;
                 case QUESRATE:
                     // Rate.
                     foreach ($choices as $choice) {
                         $nameddegrees = 0;
                         $modality = '';
                         $content = $choice->content;
                         $osgood = false;
                         if ($choice->precise == 3) {
                             $osgood = true;
                         }
                         if (preg_match("/^[0-9]{1,3}=/", $content, $ndd)) {
                             $nameddegrees++;
                         } else {
                             if ($osgood) {
                                 list($contentleft, $contentright) = array_merge(preg_split('/[|]/', $content), array(' '));
                                 $contents = questionnaire_choice_values($contentleft);
                                 if ($contents->title) {
                                     $contentleft = $contents->title;
                                 }
                                 $contents = questionnaire_choice_values($contentright);
                                 if ($contents->title) {
                                     $contentright = $contents->title;
                                 }
                                 $modality = strip_tags($contentleft . '|' . $contentright);
                                 $modality = preg_replace("/[\r\n\t]/", ' ', $modality);
                             } else {
                                 $contents = questionnaire_choice_values($content);
                                 if ($contents->modname) {
                                     $modality = $contents->modname;
                                 } else {
                                     if ($contents->title) {
                                         $modality = $contents->title;
                                     } else {
                                         $modality = strip_tags($contents->text);
                                         $modality = preg_replace("/[\r\n\t]/", ' ', $modality);
                                     }
                                 }
                             }
                             $col = $choice->name . '->' . $modality;
                             $columns[][$qpos] = $col;
                             $questionidcols[][$qpos] = $qid . '_' . $choice->cid;
                             array_push($types, $idtocsvmap[$type]);
                         }
                     }
                     break;
             }
         } else {
             $columns[][$qpos] = $col;
             $questionidcols[][$qpos] = $qid;
             array_push($types, $idtocsvmap[$type]);
         }
         $num++;
     }
     array_push($output, $columns);
     $numrespcols = count($output[0]);
     // Number of columns used for storing question responses.
     // Flatten questionidcols.
     $tmparr = [];
     for ($c = 0; $c < $nbinfocols; $c++) {
         $tmparr[] = null;
         // Pad with non question columns.
     }
     foreach ($questionidcols as $i => $positions) {
         foreach ($positions as $position => $qid) {
             $tmparr[] = $qid;
         }
     }
     $questionidcols = $tmparr;
     // Create array of question positions hashed by question / question + choiceid.
     // And array of questions hashed by position.
     $questionpositions = [];
     $questionsbyposition = [];
     $p = 0;
     foreach ($questionidcols as $qid) {
         if ($qid === null) {
             // This is just padding, skip.
             $p++;
             continue;
         }
         $questionpositions[$qid] = $p;
         if (strpos($qid, '_') !== false) {
             $tmparr = explode('_', $qid);
             $questionid = $tmparr[0];
         } else {
             $questionid = $qid;
         }
         $questionsbyposition[$p] = $this->questions[$questionid];
         $p++;
     }
     $formatoptions = new stdClass();
     $formatoptions->filter = false;
     // To prevent any filtering in CSV output.
     // Get textual versions of responses, add them to output at the correct col position.
     $prevresprow = false;
     // Previous response row.
     $row = [];
     foreach ($allresponsesrs as $responserow) {
         $rid = $responserow->rid;
         $qid = $responserow->question_id;
         $question = $this->questions[$qid];
         $qtype = intval($question->type_id);
         $questionobj = $this->questions[$qid];
         if ($prevresprow !== false && $prevresprow->rid !== $rid) {
             $output[] = $this->process_csv_row($row, $prevresprow, $currentgroupid, $questionsbyposition, $nbinfocols, $numrespcols);
             $row = [];
         }
         if ($qtype === QUESRATE || $qtype === QUESCHECK) {
             $key = $qid . '_' . $responserow->choice_id;
             $position = $questionpositions[$key];
             if ($qtype === QUESRATE) {
                 $choicetxt = $responserow->rank + 1;
             } else {
                 $content = $choicesbyqid[$qid][$responserow->choice_id]->content;
                 if (preg_match('/^!other/', $content)) {
                     // If this is an "other" column, put the text entered in the next position.
                     $row[$position + 1] = $responserow->response;
                     $choicetxt = empty($responserow->choice_id) ? '0' : '1';
                 } else {
                     if (!empty($responserow->choice_id)) {
                         $choicetxt = '1';
                     } else {
                         $choicetxt = '0';
                     }
                 }
             }
             $responsetxt = $choicetxt;
             $row[$position] = $responsetxt;
         } else {
             $position = $questionpositions[$qid];
             if ($questionobj->has_choices()) {
                 // This is choice type question, so process as so.
                 $c = 0;
                 if (in_array(intval($question->type_id), $choicetypes)) {
                     $choices = $choicesbyqid[$qid];
                     // Get position of choice.
                     foreach ($choices as $choice) {
                         $c++;
                         if ($responserow->choice_id === $choice->cid) {
                             break;
                         }
                     }
                 }
                 $content = $choicesbyqid[$qid][$responserow->choice_id]->content;
                 if (preg_match('/^!other/', $content)) {
                     // If this has an "other" text, use it.
                     $responsetxt = get_string('other', 'questionnaire');
                     $responsetxt1 = $responserow->response;
                 } else {
                     if ($choicecodes == 1 && $choicetext == 1) {
                         $responsetxt = $c . ' : ' . $content;
                     } else {
                         if ($choicecodes == 1) {
                             $responsetxt = $c;
                         } else {
                             $responsetxt = $content;
                         }
                     }
                 }
             } else {
                 if (intval($qtype) === QUESYESNO) {
                     // At this point, the boolean responses are returned as characters in the "response"
                     // field instead of "choice_id" for csv exports (CONTRIB-6436).
                     $responsetxt = $responserow->response === 'y' ? "1" : "0";
                 } else {
                     // Strip potential html tags from modality name.
                     $responsetxt = $responserow->response;
                     if (!empty($responsetxt)) {
                         $responsetxt = $responserow->response;
                         $responsetxt = strip_tags($responsetxt);
                         $responsetxt = preg_replace("/[\r\n\t]/", ' ', $responsetxt);
                     }
                 }
             }
             $row[$position] = $responsetxt;
             // Check for "other" text and set it to the next position if present.
             if (!empty($responsetxt1)) {
                 $row[$position + 1] = $responsetxt1;
                 unset($responsetxt1);
             }
         }
         $prevresprow = $responserow;
     }
     // Add final row to output.
     $output[] = $this->process_csv_row($row, $prevresprow, $currentgroupid, $questionsbyposition, $nbinfocols, $numrespcols);
     // Change table headers to incorporate actual question numbers.
     $numcol = 0;
     $numquestion = 0;
     $out = '';
     $oldkey = 0;
     for ($i = $nbinfocols; $i < $numrespcols; $i++) {
         $sep = '';
         $thisoutput = current($output[0][$i]);
         $thiskey = key($output[0][$i]);
         // Case of unnamed rate single possible answer (full stop char is used for support).
         if (strstr($thisoutput, '->.')) {
             $thisoutput = str_replace('->.', '', $thisoutput);
         }
         // If variable is not named no separator needed between Question number and potential sub-variables.
         if ($thisoutput == '' || strstr($thisoutput, '->.') || substr($thisoutput, 0, 2) == '->' || substr($thisoutput, 0, 1) == '_') {
             $sep = '';
         } else {
             $sep = '_';
         }
         if ($thiskey > $oldkey) {
             $oldkey = $thiskey;
             $numquestion++;
         }
         // Abbreviated modality name in multiple or rate questions (COLORS->blue=the color of the sky...).
         $pos = strpos($thisoutput, '=');
         if ($pos) {
             $thisoutput = substr($thisoutput, 0, $pos);
         }
         $other = $sep . $stringother;
         $out = 'Q' . sprintf("%02d", $numquestion) . $sep . $thisoutput;
         $output[0][$i] = $out;
     }
     return $output;
 }
Ejemplo n.º 23
0
// Forced plugin settings override values from config_plugins table
unset($CFG->config_php_settings['forced_plugin_settings']);
if (!isset($CFG->forced_plugin_settings)) {
    $CFG->forced_plugin_settings = array();
}
// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
// inside some URLs used in HTTPSPAGEREQUIRED pages.
$CFG->httpswwwroot = $CFG->wwwroot;
require_once $CFG->libdir . '/setuplib.php';
// Functions that MUST be loaded first
if (NO_OUTPUT_BUFFERING) {
    // we have to call this always before starting session because it discards headers!
    disable_output_buffering();
}
// Increase memory limits if possible
raise_memory_limit(MEMORY_STANDARD);
// Time to start counting
init_performance_info();
// Put $OUTPUT in place, so errors can be displayed.
$OUTPUT = new bootstrap_renderer();
// set handler for uncaught exceptions - equivalent to print_error() call
set_exception_handler('default_exception_handler');
set_error_handler('default_error_handler', E_ALL | E_STRICT);
// If there are any errors in the standard libraries we want to know!
error_reporting(E_ALL);
// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
// http://www.google.com/webmasters/faq.html#prefetchblock
if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch') {
    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
    echo 'Prefetch request forbidden.';
    exit(1);
Ejemplo n.º 24
0
function xmldb_core_upgrade($oldversion = 0)
{
    global $SESSION;
    raise_time_limit(120);
    raise_memory_limit('256M');
    $status = true;
    if ($oldversion < 2009022700) {
        // Get rid of all blocks with position 0 caused by 'about me' block on profile views
        if (count_records('block_instance', 'order', 0) && !count_records_select('block_instance', '"order" < 0')) {
            if (is_mysql()) {
                $ids = get_column_sql('
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column)');
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (' . join(',', $ids) . ')');
            } else {
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column))');
            }
            execute_sql('UPDATE {block_instance} SET "order" = 1 WHERE "order" = 0');
            execute_sql('UPDATE {block_instance} SET "order" = -1 * ("order" - 1) WHERE "order" < 0');
        }
    }
    if ($oldversion < 2009031000) {
        reload_html_filters();
    }
    if ($oldversion < 2009031300) {
        $table = new XMLDBTable('institution');
        $expiry = new XMLDBField('expiry');
        $expiry->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $expiry);
        $expirymailsent = new XMLDBField('expirymailsent');
        $expirymailsent->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $expirymailsent);
        $suspended = new XMLDBField('suspended');
        $suspended->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $suspended);
        // Insert a cron job to check for soon expiring and expired institutions
        if (!record_exists('cron', 'callfunction', 'auth_handle_institution_expiries')) {
            $cron = new StdClass();
            $cron->callfunction = 'auth_handle_institution_expiries';
            $cron->minute = '5';
            $cron->hour = '9';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2009031800) {
        // Files can only attach blogpost artefacts, but we would like to be able to attach them
        // to other stuff.  Rename the existing attachment table artefact_blog_blogpost_file to
        // artefact_file_attachment so we don't end up with many tables doing the same thing.
        execute_sql("ALTER TABLE {artefact_blog_blogpost_file} RENAME TO {artefact_attachment}");
        if (is_postgres()) {
            // Ensure all of the indexes and constraints are renamed
            execute_sql("\n            ALTER TABLE {artefact_attachment} RENAME blogpost TO artefact;\n            ALTER TABLE {artefact_attachment} RENAME file TO attachment;\n\n            ALTER INDEX {arteblogblogfile_blofil_pk} RENAME TO {arteatta_artatt_pk};\n            ALTER INDEX {arteblogblogfile_blo_ix} RENAME TO {arteatta_art_ix};\n            ALTER INDEX {arteblogblogfile_fil_ix} RENAME TO {arteatta_att_ix};\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_blo_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY (artefact) REFERENCES {artefact}(id);\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_fil_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY (attachment) REFERENCES {artefact}(id);\n            ");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_blo_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_blo_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE blogpost artefact BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY {arteatta_art_ix} (artefact) REFERENCES {artefact}(id)");
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_fil_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_fil_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE file attachment BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY {arteatta_att_ix} (attachment) REFERENCES {artefact}(id)");
            }
        }
        // Drop the _pending table. From now on files uploaded as attachments will become artefacts
        // straight away.  Hopefully changes to the upload/file browser form will make it clear to
        // the user that these attachments sit in his/her files area as soon as they are uploaded.
        $table = new XMLDBTable('artefact_blog_blogpost_file_pending');
        drop_table($table);
    }
    if ($oldversion < 2009040900) {
        // The view access page has been putting the string 'null' in as a group role in IE.
        set_field('view_access_group', 'role', null, 'role', 'null');
    }
    if ($oldversion < 2009040901) {
        $table = new XMLDBTable('import_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('import_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
        $table = new XMLDBTable('export_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('export_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2009050700) {
        if ($data = check_upgrades('export.html')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('export.leap')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('import.leap')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009051200) {
        // Rename submittedto column to submittedgroup
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} RENAME submittedto TO submittedgroup");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} DROP FOREIGN KEY {view_sub_fk}");
                execute_sql("ALTER TABLE {view} DROP INDEX {view_sub_ix}");
                execute_sql("ALTER TABLE {view} CHANGE submittedto submittedgroup BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_sub_fk} FOREIGN KEY {view_sub_ix} (submittedgroup) REFERENCES {group}(id)");
            }
        }
        // Add submittedhost column for views submitted to remote moodle hosts
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        // Do this manually because xmldb tries to create a key with the same name (view_sub_vk) as an existing one, and fails.
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY (submittedhost) REFERENCES {host}(wwwroot)");
            execute_sql("CREATE INDEX {view_subh_ix} ON {view} (submittedhost)");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY {view_subh_ix} (submittedhost) REFERENCES {host}(wwwroot)");
            }
        }
    }
    if ($oldversion < 2009051201) {
        // Invisible view access keys for roaming moodle teachers
        $table = new XMLDBTable('view_access_token');
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2009052700) {
        // Install a cron job to clean out old exports
        $cron = new StdClass();
        $cron->callfunction = 'export_cleanup_old_exports';
        $cron->minute = '0';
        $cron->hour = '3,13';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009070600) {
        // This was forgotten as part of the 1.0 -> 1.1 upgrade
        if ($data = check_upgrades('blocktype.file/html')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009070700) {
        foreach (array('addfriend', 'removefriend', 'addfriendrequest', 'removefriendrequest') as $eventtype) {
            $event = (object) array('name' => $eventtype);
            ensure_record_exists('event_type', $event, $event);
        }
    }
    if ($oldversion < 2009070900) {
        if (is_mysql()) {
            execute_sql("ALTER TABLE {usr} DROP FOREIGN KEY {usr_las_fk}");
            execute_sql("ALTER TABLE {usr} DROP INDEX {usr_las_ix}");
        }
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastauthinstance');
        drop_field($table, $field);
    }
    if ($oldversion < 2009080600) {
        $table = new XMLDBTable('view');
        $index = new XMLDBIndex('view_own_type_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('owner'));
        if (!index_exists($table, $index)) {
            // Delete duplicate profile views if there are any, then add an index
            // that will prevent it happening again - but only on postgres, as it's
            // the only db that supports partial indexes
            if ($viewdata = get_records_sql_array("\n                SELECT owner, id\n                FROM {view}\n                WHERE owner IN (\n                    SELECT owner\n                    FROM {view}\n                    WHERE type = 'profile'\n                    GROUP BY owner\n                    HAVING COUNT(*) > 1\n                )\n                AND type = 'profile'\n                ORDER BY owner, id", array())) {
                require_once 'view.php';
                $seen = array();
                foreach ($viewdata as $record) {
                    $seen[$record->owner][] = $record->id;
                }
                foreach ($seen as $owner => $views) {
                    // Remove the first one, which is their real profile view
                    array_shift($views);
                    foreach ($views as $viewid) {
                        delete_records('artefact_feedback', 'view', $viewid);
                        delete_records('view_feedback', 'view', $viewid);
                        delete_records('view_access', 'view', $viewid);
                        delete_records('view_access_group', 'view', $viewid);
                        delete_records('view_access_usr', 'view', $viewid);
                        delete_records('view_access_token', 'view', $viewid);
                        delete_records('view_autocreate_grouptype', 'view', $viewid);
                        delete_records('view_tag', 'view', $viewid);
                        delete_records('usr_watchlist_view', 'view', $viewid);
                        if ($blockinstanceids = get_column('block_instance', 'id', 'view', $viewid)) {
                            foreach ($blockinstanceids as $id) {
                                if (table_exists(new XMLDBTable('blocktype_wall_post'))) {
                                    delete_records('blocktype_wall_post', 'instance', $id);
                                }
                                delete_records('view_artefact', 'block', $id);
                                delete_records('block_instance', 'id', $id);
                            }
                        }
                        delete_records('view', 'id', $viewid);
                    }
                }
            }
            if (is_postgres()) {
                execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
            }
        }
    }
    if ($oldversion < 2009080601) {
        execute_sql("DELETE FROM {group_member_invite} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'invite')");
        execute_sql("DELETE FROM {group_member_request} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'request')");
    }
    if ($oldversion < 2009081800) {
        $event = (object) array('name' => 'creategroup');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009082400) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('username');
        drop_field($table, $field);
        $field = new XMLDBField('salt');
        drop_field($table, $field);
        $field = new XMLDBField('password');
        drop_field($table, $field);
    }
    if ($oldversion < 2009082600) {
        $captcha = get_config('captcha_on_contact_form');
        set_config('captchaoncontactform', (int) (is_null($captcha) || $captcha));
        $captcha = get_config('captcha_on_register_form');
        set_config('captchaonregisterform', (int) (is_null($captcha) || $captcha));
    }
    if ($oldversion < 2009090700) {
        set_config('showselfsearchsideblock', 1);
        set_config('showtagssideblock', 1);
        set_config('tagssideblockmaxtags', 20);
    }
    if ($oldversion < 2009092100) {
        if ($data = check_upgrades('import.file')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.creativecommons')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009092900) {
        $event = (object) array('name' => 'deleteartefacts');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009101600) {
        require_once get_config('docroot') . '/lib/stringparser_bbcode/lib.php';
        // Remove bbcode formatting from existing feedback
        if ($records = get_records_sql_array("SELECT * FROM {view_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('view_feedback', $r);
            }
        }
        if ($records = get_records_sql_array("SELECT * FROM {artefact_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('artefact_feedback', $r);
            }
        }
    }
    if ($oldversion < 2009102100) {
        // Now the view_layout table has to have records for all column widths
        $record = (object) array('columns' => 1, 'widths' => '100');
        insert_record('view_layout', $record);
        $record = (object) array('columns' => 5, 'widths' => '20,20,20,20,20');
        insert_record('view_layout', $record);
    }
    if ($oldversion < 2009102200) {
        if (!count_records_select('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'))) {
            insert_record('activity_type', (object) array('name' => 'groupmessage', 'admin' => 0, 'delay' => 0));
        }
    }
    if ($oldversion < 2009102900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('sessionid');
        drop_field($table, $field);
    }
    if ($oldversion < 2009110500) {
        set_config('creategroups', 'all');
    }
    if ($oldversion < 2009110900) {
        // Fix export cronjob so it runs 12 hours apart
        execute_sql("UPDATE {cron} SET hour = '3,15' WHERE callfunction = 'export_cleanup_old_exports'");
        // Cron job to clean old imports
        $cron = new StdClass();
        $cron->callfunction = 'import_cleanup_old_imports';
        $cron->minute = '0';
        $cron->hour = '4,16';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009111200) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailssent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009111201) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailsbounced');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009120100) {
        // Fix for bug in 1.1 => 1.2 upgrade which may have inserted
        // a second groupmessage activity_type record
        $records = get_records_select_array('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'), 'id');
        if ($records && count($records) > 1) {
            for ($i = 1; $i < count($records); $i++) {
                delete_records('activity_queue', 'type', $records[$i]->id);
                delete_records('notification_internal_activity', 'type', $records[$i]->id);
                delete_records('notification_emaildigest_queue', 'type', $records[$i]->id);
                delete_records('usr_activity_preference', 'activity', $records[$i]->id);
                delete_records('activity_type', 'id', $records[$i]->id);
            }
        }
    }
    if ($oldversion < 2009120900) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010011300) {
        // Clean up the mess left behind by failing to delete blogposts in a transaction
        try {
            include_once get_config('docroot') . 'artefact/lib.php';
            if (function_exists('rebuild_artefact_parent_cache_dirty')) {
                rebuild_artefact_parent_cache_dirty();
            }
        } catch (Exception $e) {
            log_debug('Upgrade 2010011300: rebuild_artefact_parent_cache_dirty failed.');
        }
        execute_sql("\n            INSERT INTO {artefact_blog_blogpost} (blogpost)\n            SELECT id FROM {artefact} WHERE artefacttype = 'blogpost' AND id NOT IN (\n                SELECT blogpost FROM {artefact_blog_blogpost}\n            )");
    }
    if ($oldversion < 2010012701) {
        set_config('userscanchooseviewthemes', 1);
    }
    if ($oldversion < 2010021500) {
        if ($data = check_upgrades('blocktype.recentforumposts')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010031000) {
        // For existing sites, preserve current user search behaviour:
        // Users are only searchable by their display names.
        set_config('userscanhiderealnames', 1);
        execute_sql("\n            INSERT INTO {usr_account_preference} (usr, field, value)\n            SELECT u.id, 'hiderealname', 1\n            FROM {usr} u LEFT JOIN {usr_account_preference} p ON (u.id = p.usr AND p.field = 'hiderealname')\n            WHERE NOT u.preferredname IS NULL AND u.preferredname != '' AND p.field IS NULL\n        ");
    }
    if ($oldversion < 2010040700) {
        // Set antispam defaults
        set_config('formsecret', get_random_key());
        if (!function_exists('checkdnsrr')) {
            require_once get_config('docroot') . 'lib/antispam.php';
        }
        if (checkdnsrr('test.uribl.com.black.uribl.com', 'A')) {
            set_config('antispam', 'advanced');
        } else {
            set_config('antispam', 'simple');
        }
        set_config('spamhaus', 0);
        set_config('surbl', 0);
    }
    if ($oldversion < 2010040800) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010041200) {
        delete_records('config', 'field', 'captchaoncontactform');
        delete_records('config', 'field', 'captchaonregisterform');
    }
    if ($oldversion < 2010041201) {
        $sql = "\n            SELECT u.id\n            FROM {usr} u\n            LEFT JOIN {artefact} a\n                ON (a.owner = u.id AND a.artefacttype = 'blog')\n            WHERE u.id > 0\n            GROUP BY u.id\n            HAVING COUNT(a.id) != 1";
        $manyblogusers = get_records_sql_array($sql, array());
        if ($manyblogusers) {
            foreach ($manyblogusers as $u) {
                $where = (object) array('usr' => $u->id, 'field' => 'multipleblogs');
                $data = (object) array('usr' => $u->id, 'field' => 'multipleblogs', 'value' => 1);
                ensure_record_exists('usr_account_preference', $where, $data);
            }
        }
    }
    if ($oldversion < 2010041600 && table_exists(new XMLDBTable('view_feedback'))) {
        // Add author, authorname to artefact table
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('author');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('authorfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('author'), 'usr', array('id'));
        add_key($table, $key);
        table_column('artefact', null, 'authorname', 'text', null, null, null, '');
        if (is_postgres()) {
            execute_sql("ALTER TABLE {artefact} ALTER COLUMN authorname DROP DEFAULT");
            set_field('artefact', 'authorname', null);
            execute_sql('UPDATE {artefact} SET authorname = g.name FROM {group} g WHERE "group" = g.id');
            execute_sql("UPDATE {artefact} SET authorname = CASE WHEN institution = 'mahara' THEN ? ELSE i.displayname END FROM {institution} i WHERE institution = i.name", array(get_config('sitename')));
        } else {
            execute_sql("UPDATE {artefact} a, {group} g SET a.authorname = g.name WHERE a.group = g.id");
            execute_sql("UPDATE {artefact} a, {institution} i SET a.authorname = CASE WHEN a.institution = 'mahara' THEN ? ELSE i.displayname END WHERE a.institution = i.name", array(get_config('sitename')));
        }
        execute_sql('UPDATE {artefact} SET author = owner WHERE owner IS NOT NULL');
        execute_sql('ALTER TABLE {artefact} ADD CHECK (
            (author IS NOT NULL AND authorname IS NULL    ) OR
            (author IS NULL     AND authorname IS NOT NULL)
        )');
        // Move feedback activity type to artefact plugin
        execute_sql("\n            UPDATE {activity_type}\n            SET plugintype = 'artefact', pluginname = 'comment'\n            WHERE name = 'feedback'\n        ");
        // Install the comment artefact
        if ($data = check_upgrades('artefact.comment')) {
            upgrade_plugin($data);
        }
        // Flag all views & artefacts to enable/disable comments
        table_column('artefact', null, 'allowcomments', 'integer', 1);
        table_column('view', null, 'allowcomments', 'integer', 1, null, 1);
        // Initially allow comments on blogposts, images, files
        set_field_select('artefact', 'allowcomments', 1, 'artefacttype IN (?,?,?)', array('blogpost', 'image', 'file'));
        // Convert old feedback to comment artefacts
        if ($viewfeedback = get_records_sql_array('
            SELECT f.*, v.id AS viewid, v.owner, v.group, v.institution
            FROM {view_feedback} f JOIN {view} v ON f.view = v.id', array())) {
            foreach ($viewfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onview' => $f->viewid);
                insert_record('artefact_comment_comment', $comment);
                if (!empty($f->attachment)) {
                    insert_record('artefact_attachment', (object) array('artefact' => $aid, 'attachment' => $f->attachment));
                }
            }
        }
        // We are throwing away the view information from artefact_feedback.
        // From now on all artefact comments appear together and are not
        // tied to a particular view.
        if ($artefactfeedback = get_records_sql_array('
            SELECT f.*, a.id AS artefactid, a.owner, a.group, a.institution
            FROM {artefact_feedback} f JOIN {artefact} a ON f.artefact = a.id', array())) {
            foreach ($artefactfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onartefact' => $f->artefactid);
                insert_record('artefact_comment_comment', $comment);
            }
        }
        // Drop feedback tables
        $table = new XMLDBTable('view_feedback');
        drop_table($table);
        $table = new XMLDBTable('artefact_feedback');
        drop_table($table);
        // Add site setting for anonymous comments
        set_config('anonymouscomments', 1);
    }
    if ($oldversion < 2010041900 && !table_exists(new XMLDBTable('site_data'))) {
        // Upgrades for admin stats pages
        // Table for collection of historical stats
        $table = new XMLDBTable('site_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'type'));
        create_table($table);
        // Insert cron jobs to save site data
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
        // Put best guess at installation time into config table.
        set_config('installation_time', get_field_sql("SELECT MIN(ctime) FROM {site_content}"));
        // Save the current time so we know when we started collecting stats
        set_config('stats_installation_time', db_format_timestamp(time()));
        // Add ctime to usr table for daily count of users created
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // Add visits column to view table
        $table = new XMLDBTable('view');
        $field = new XMLDBField('visits');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Add table to store daily view visits
        $table = new XMLDBTable('view_visit');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addIndexInfo('ctimeix', XMLDB_INDEX_NOTUNIQUE, array('ctime'));
        create_table($table);
        // Insert a cron job to check for new versions of Mahara
        $cron = new StdClass();
        $cron->callfunction = 'cron_check_for_updates';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2010042600) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('parent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('parentfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('parent'), 'notification_internal_activity', array('id'));
        add_key($table, $key);
        $field = new XMLDBField('from');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('fromfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('from'), 'usr', array('id'));
        add_key($table, $key);
        // Set from column for old user messages
        $usermessages = get_records_array('notification_internal_activity', 'type', get_field('activity_type', 'id', 'name', 'usermessage'));
        if ($usermessages) {
            foreach ($usermessages as &$m) {
                if (preg_match('/sendmessage\\.php\\?id=(\\d+)/', $m->url, $match)) {
                    set_field('notification_internal_activity', 'from', $match[1], 'id', $m->id);
                }
            }
        }
    }
    if ($oldversion < 2010042602 && !get_record('view_type', 'type', 'dashboard')) {
        insert_record('view_type', (object) array('type' => 'dashboard'));
        if ($data = check_upgrades('blocktype.inbox')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.newviews')) {
            upgrade_plugin($data);
        }
        // Install system dashboard view
        require_once get_config('libroot') . 'view.php';
        $dbtime = db_format_timestamp(time());
        $viewdata = (object) array('type' => 'dashboard', 'owner' => 0, 'numcolumns' => 2, 'ownerformat' => FORMAT_NAME_PREFERREDNAME, 'title' => get_string('dashboardviewtitle', 'view'), 'template' => 1, 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'newviews', 'title' => get_string('title', 'blocktype.newviews'), 'column' => 1, 'config' => array('limit' => 5)), array('blocktype' => 'myviews', 'title' => get_string('title', 'blocktype.myviews'), 'column' => 1, 'config' => null), array('blocktype' => 'inbox', 'title' => get_string('inboxblocktitle'), 'column' => 2, 'config' => array('feedback' => true, 'groupmessage' => true, 'institutionmessage' => true, 'maharamessage' => true, 'usermessage' => true, 'viewaccess' => true, 'watchlist' => true, 'maxitems' => '5')), array('blocktype' => 'inbox', 'title' => get_string('topicsimfollowing'), 'column' => 2, 'config' => array('newpost' => true, 'maxitems' => '5')));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        $weights = array(1 => 0, 2 => 0);
        foreach ($blocktypes as $blocktype) {
            if (in_array($blocktype['blocktype'], $installed)) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010042603) {
        execute_sql('ALTER TABLE {usr} ADD COLUMN showhomeinfo SMALLINT NOT NULL DEFAULT 1');
        set_config('homepageinfo', 1);
    }
    if ($oldversion < 2010042604) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('urltext');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2010051000) {
        set_field('activity_type', 'delay', 1, 'name', 'groupmessage');
    }
    if ($oldversion < 2010052000) {
        $showusers = get_config('showonlineuserssideblock');
        set_config('showonlineuserssideblock', (int) (is_null($showusers) || $showusers));
    }
    if ($oldversion < 2010060300) {
        // Add table to associate users with php session ids
        $table = new XMLDBTable('usr_session');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('session', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('session'));
        $table->addIndexInfo('usrix', XMLDB_INDEX_NOTUNIQUE, array('usr'));
        create_table($table);
    }
    if ($oldversion < 2010061100) {
        set_config('registerterms', 1);
    }
    if ($oldversion < 2010061800) {
        insert_record('view_type', (object) array('type' => 'grouphomepage'));
        if ($data = check_upgrades('blocktype.groupmembers')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupinfo')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupviews')) {
            upgrade_plugin($data);
        }
        $dbtime = db_format_timestamp(time());
        // create a system template for group homepage views
        require_once get_config('libroot') . 'view.php';
        $viewdata = (object) array('type' => 'grouphomepage', 'owner' => 0, 'numcolumns' => 1, 'template' => 1, 'title' => get_string('grouphomepage', 'view'), 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'groupinfo', 'title' => '', 'column' => 1, 'config' => null), array('blocktype' => 'recentforumposts', 'title' => get_string('latestforumposts', 'interaction.forum'), 'column' => 1, 'config' => null), array('blocktype' => 'groupviews', 'title' => get_string('Views', 'view'), 'column' => 1, 'config' => null), array('blocktype' => 'groupmembers', 'title' => get_string('Members', 'group'), 'column' => 1, 'config' => null));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        foreach ($blocktypes as $k => $blocktype) {
            if (!in_array($blocktype['blocktype'], $installed)) {
                unset($blocktypes[$k]);
            }
        }
        $weights = array(1 => 0);
        foreach ($blocktypes as $blocktype) {
            $weights[$blocktype['column']]++;
            insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
        }
        // add a default group homepage view for all groups in the system
        unset($viewdata->owner);
        $viewdata->template = 0;
        if (!($groups = get_records_array('group', '', '', '', 'id,public'))) {
            $groups = array();
        }
        foreach ($groups as $group) {
            $viewdata->group = $group->id;
            $id = insert_record('view', $viewdata, 'id', true);
            insert_record('view_access', (object) array('view' => $id, 'accesstype' => $group->public ? 'public' : 'loggedin'));
            insert_record('view_access_group', (object) array('view' => $id, 'group' => $group->id));
            $weights = array(1 => 0);
            foreach ($blocktypes as $blocktype) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010062502) {
        //new feature feedback control on views
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('allowcomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Add comment approval to view/artefact (default 0)
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table = new XMLDBTable('view');
        add_field($table, $field);
        $table = new XMLDBTable('artefact');
        add_field($table, $field);
        // view_access_(group|usr|token) tables are getting wide with duplicated columns,
        // so just create all the necessary columns in view_access and move stuff there
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null);
        change_field_notnull($table, $field);
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('role');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $field = new XMLDBField('usr');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('token');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Copy data to view_access
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, "group", role, startdate, stopdate)
            SELECT view, NULL, "group", role, startdate, stopdate FROM {view_access_group}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, usr, startdate, stopdate)
            SELECT view, NULL, usr, startdate, stopdate FROM {view_access_usr}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, token, visible, startdate, stopdate)
            SELECT view, NULL, token, visible, startdate, stopdate FROM {view_access_token}');
        // Add foreign keys
        $key = new XMLDBKey('groupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('usrfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        add_key($table, $key);
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        add_index($table, $index);
        // Exactly one of accesstype, group, usr, token must be not null
        execute_sql('ALTER TABLE {view_access} ADD CHECK (
            (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL)
        )');
        // Drop old tables
        $table = new XMLDBTable('view_access_group');
        drop_table($table);
        $table = new XMLDBTable('view_access_usr');
        drop_table($table);
        $table = new XMLDBTable('view_access_token');
        drop_table($table);
        // Insert explicit tutor access records for submitted views
        if (!($submittedviews = get_records_sql_array('
            SELECT v.id, v.submittedgroup, g.grouptype
            FROM {view} v JOIN {group} g ON (v.submittedgroup = g.id AND g.deleted = 0)', array()))) {
            $submittedviews = array();
        }
        $roles = array();
        foreach ($submittedviews as $v) {
            if (!isset($roles[$v->grouptype])) {
                $rs = get_column('grouptype_roles', 'role', 'grouptype', $v->grouptype, 'see_submitted_views', 1);
                $roles[$v->grouptype] = empty($rs) ? array() : $rs;
            }
            foreach ($roles[$v->grouptype] as $role) {
                $accessrecord = (object) array('view' => $v->id, 'group' => $v->submittedgroup, 'role' => $role, 'visible' => 0, 'allowcomments' => 1, 'approvecomments' => 0);
                ensure_record_exists('view_access', $accessrecord, $accessrecord);
            }
        }
    }
    if ($oldversion < 2010070700) {
        $table = new XMLDBTable('group_category');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('category');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('categoryfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('category'), 'group_category', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2010071300) {
        set_config('searchusernames', 1);
    }
    if ($oldversion < 2010071500) {
        reload_html_filters();
    }
    if ($oldversion < 2010071600) {
        if (is_postgres()) {
            // change_field_enum should do this
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends', 'objectionable'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2010071900) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('viewnotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2010081000) {
        // new table collection
        $table = new XMLDBTable('collection');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, null);
        $table->addFieldInfo('navigation', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // new table collection_view
        $table = new XMLDBTable('collection_view');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('view'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
        // Drop unique constraint on token column of view_access
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        drop_index($table, $index);
        $index = new XMLDBIndex('tokenix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('token'));
        add_index($table, $index);
    }
    if ($oldversion < 2010081001) {
        if ($data = check_upgrades('artefact.plans')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.plans/plans')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010081100) {
        if ($data = check_upgrades('blocktype.navigation')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010082000) {
        delete_records_select('config', "field IN ('usersrank', 'groupsrank', 'viewsrank')");
    }
    if ($oldversion < 2010091300) {
        // Cron job missing from installs post 2010041900
        if (!record_exists('cron', 'callfunction', 'cron_check_for_updates')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_check_for_updates';
            $cron->minute = rand(0, 59);
            $cron->hour = rand(0, 23);
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010091500) {
        // Previous version of 2010040800 upgrade created the submittedtime
        // column not null (see bug #638550)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        change_field_notnull($table, $field);
        // Our crappy db is full of redundant data (submittedtime depends on
        // submittedhost or submittedgroup) so it's easy to correct this.
        execute_sql("\n            UPDATE {view} SET submittedtime = NULL\n            WHERE submittedtime IS NOT NULL AND submittedgroup IS NULL AND submittedhost IS NULL");
    }
    if ($oldversion < 2010100702) {
        // Add general notification cleanup cron
        if (!record_exists('cron', 'callfunction', 'cron_clean_internal_activity_notifications')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_clean_internal_activity_notifications';
            $cron->minute = 45;
            $cron->hour = 22;
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010110800) {
        // Encrypt all passwords with no set salt values
        $sql = "SELECT * FROM {usr}\n                WHERE salt IS NULL OR salt = ''";
        if ($passwords = get_records_sql_array($sql, array())) {
            foreach ($passwords as $p) {
                $p->salt = substr(md5(rand(1000000, 9999999)), 2, 8);
                $p->password = sha1($p->salt . $p->password);
                update_record('usr', $p);
            }
        }
    }
    if ($oldversion < 2010122200) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('priority');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        set_field('institution', 'priority', 0, 'name', 'mahara');
    }
    if ($oldversion < 2010122201) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('accessconf');
        $field->setAttributes(XMLDB_TYPE_CHAR, 40, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010122700) {
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('accesstypeix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('accesstype'));
        add_index($table, $index);
    }
    if ($oldversion < 2011012800) {
        reload_html_filters();
    }
    if ($oldversion < 2011032500) {
        // Uninstall solr plugin; it's moving to contrib until it's fixed up.
        delete_records('search_cron', 'plugin', 'solr');
        delete_records('search_event_subscription', 'plugin', 'solr');
        delete_records('search_config', 'plugin', 'solr');
        delete_records('search_installed', 'name', 'solr');
        $searchplugin = get_config('searchplugin');
        if ($searchplugin == 'solr') {
            set_config('searchplugin', 'internal');
        }
    }
    if ($oldversion < 2011041800) {
        // Remove titles from system dashboard, group homepage blocks, so new users/groups
        // get blocks with automatically generated, translatable default titles.
        $systemdashboard = get_field('view', 'id', 'owner', 0, 'type', 'dashboard');
        set_field_select('block_instance', 'title', '', "view = ? AND blocktype IN ('newviews','myviews','inbox')", array($systemdashboard));
        $systemgrouphomepage = get_field('view', 'id', 'owner', 0, 'type', 'grouphomepage');
        set_field_select('block_instance', 'title', '', "view = ? AND blocktype IN ('recentforumposts','groupviews','groupmembers')", array($systemgrouphomepage));
    }
    if ($oldversion < 2011042000) {
        // Create empty variables in database for email configuration
        set_config('smtphosts', '');
        set_config('smtpport', '');
        set_config('smtpuser', '');
        set_config('smtppass', '');
        set_config('smtpsecure', '');
        $SESSION->add_info_msg('Email settings now can be configured via Site settings, however they may be overriden by those set in the config file. If you have no specific reason to use config file email configuration, please consider moving them to Site settings area.');
    }
    if ($oldversion < 2011050300) {
        if (get_config('httpswwwroot')) {
            // Notify users about httpswwwroot removal if it is still set
            $SESSION->add_info_msg('HTTPS logins have been deprecated, you need to remove the httpswwwroot variable from config file and switch your wwwroot to https so that the whole site is served over HTTPS.<br>See <a href="https://bugs.launchpad.net/mahara/+bug/646713">https://bugs.launchpad.net/mahara/+bug/646713</a> for more details.', 0);
        }
    }
    if ($oldversion < 2011050600) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('username');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        // This drops the unique index on the username column in postgres.
        // See upgrade 2011051800.
        change_field_precision($table, $field);
    }
    if ($oldversion < 2011051700) {
        // Create new "external" category
        insert_record('blocktype_category', (object) array('name' => 'external'));
        // Migrate existing blocktypes to the new category
        set_field('blocktype_installed_category', 'category', 'external', 'category', 'feeds');
        set_field('blocktype_installed_category', 'category', 'external', 'blocktype', 'externalvideo');
        set_field('blocktype_installed_category', 'category', 'external', 'blocktype', 'googleapps');
        // Delete old "feeds" category
        delete_records('blocktype_category', 'name', 'feeds');
    }
    if ($oldversion < 2011051800) {
        // Restore index that may be missing due to upgrade 2011050600.
        $table = new XMLDBTable('usr');
        $index = new XMLDBIndex('usr_use_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('username'));
        if (!index_exists($table, $index)) {
            if (is_postgres()) {
                // For postgres, create the index on the lowercase username, the way it's
                // done in core_postinst().
                execute_sql('CREATE UNIQUE INDEX {usr_use_uix} ON {usr}(LOWER(username))');
            } else {
                $index = new XMLDBIndex('usernameuk');
                $index->setAttributes(XMLDB_INDEX_UNIQUE, array('username'));
                add_index($table, $index);
            }
        }
    }
    if ($oldversion < 2011052300) {
        if ($data = check_upgrades("blocktype.googleapps")) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2011061100) {
        // This block fixes an issue of upgrading from 1.4_STABLE to master
        // version number is date after 1.4_STABLE
        // 2011052400
        // add_field checks if field exists
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // 2011053100
        // add_field checks if field exists
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('defaultquota');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        // 2011053101
        // add_field checks if field exists
        $table = new XMLDBTable('group');
        $field = new XMLDBField('quota');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $field = new XMLDBField('quotaused');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // 2011060700
        // add_field checks if field exists
        $table = new XMLDBTable('view');
        $field = new XMLDBField('retainview');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // 2011060701
        // site setting to limit online users count
        if (!get_config('onlineuserssideblockmaxusers')) {
            set_config('onlineuserssideblockmaxusers', 10);
        }
        // 2011060701
        // add_field checks if field exists
        // instiutional setting to limit online users type
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('showonlineusers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 2);
        add_field($table, $field);
    }
    if ($oldversion < 2011061300) {
        // Add more indexes to the usr table for user searches
        if (is_postgres()) {
            $table = new XMLDBTable('usr');
            $index = new XMLDBIndex('usr_fir_ix');
            $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('firstname', 'lastname', 'preferredname', 'studentid', 'email'));
            if (!index_exists($table, $index)) {
                execute_sql('CREATE INDEX {usr_fir_ix} ON {usr}(LOWER(firstname))');
                execute_sql('CREATE INDEX {usr_las_ix} ON {usr}(LOWER(lastname))');
                execute_sql('CREATE INDEX {usr_pre_ix} ON {usr}(LOWER(preferredname))');
                execute_sql('CREATE INDEX {usr_stu_ix} ON {usr}(LOWER(studentid))');
                execute_sql('CREATE INDEX {usr_ema_ix} ON {usr}(LOWER(email))');
            }
        }
    }
    if ($oldversion < 2011061400) {
        // Add institution to group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $key = new XMLDBKey('institutionfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // Add shortname to group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('shortnameuk');
        $index->setAttributes(XMLDB_KEY_UNIQUE, array('institution', 'shortname'));
        add_index($table, $index);
    }
    if ($oldversion < 2011061500) {
        // Add favourites
        $table = new XMLDBTable('favorite');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('ownerfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('ownershortuk', XMLDB_INDEX_UNIQUE, array('owner', 'shortname'));
        create_table($table);
        $table = new XMLDBTable('favorite_usr');
        $table->addFieldInfo('favorite', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('favorite,usr'));
        $table->addKeyInfo('favoritefk', XMLDB_KEY_FOREIGN, array('favorite'), 'favorite', array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2011062100) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('allowinstitutionpublicviews');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2011062200) {
        $table = new XMLDBTable('usr_tag');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('tag', XMLDB_TYPE_CHAR, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('usr', 'tag'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2011062300) {
        // Install a cron job to generate the sitemap
        if (!record_exists('cron', 'callfunction', 'cron_sitemap_daily')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_sitemap_daily';
            $cron->minute = '0';
            $cron->hour = '1';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2011062400) {
        // self-registration per institution confrimation setting
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('registerconfirm');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('pending');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('reason');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2011062700) {
        set_config('dropdownmenu', 0);
    }
    if ($oldversion < 2011070500) {
        // Add profileicon foreign key to artefact table, first clearing any bad profileicon
        // values out of usr.
        execute_sql("\n            UPDATE {usr} SET profileicon = NULL\n            WHERE NOT profileicon IN (SELECT id FROM {artefact} WHERE artefacttype = 'profileicon')");
        $table = new XMLDBTable('usr');
        $key = new XMLDBKey('profileiconfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('profileicon'), 'artefact', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011070501) {
        // Add logo to institution table
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('logo');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('logofk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('logo'), 'artefact', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011072200) {
        if (is_postgres()) {
            execute_sql("\n                UPDATE {group}\n                SET quota = CASE WHEN f.quotaused < 52428800 THEN 52428800 ELSE f.quotaused + 52428800 END,\n                    quotaused = f.quotaused\n                FROM (\n                    SELECT g.id AS id, COALESCE(gf.quotaused, 0) AS quotaused\n                    FROM {group} g\n                        LEFT OUTER JOIN (\n                            SELECT a.group, SUM(aff.size) AS quotaused\n                            FROM {artefact} a JOIN {artefact_file_files} aff ON a.id = aff.artefact\n                            WHERE NOT a.group IS NULL\n                            GROUP BY a.group\n                        ) gf ON gf.group = g.id\n                    WHERE g.quota IS NULL AND g.quotaused = 0 AND g.deleted = 0\n                ) f\n                WHERE {group}.id = f.id");
        } else {
            execute_sql("\n                UPDATE {group}, (\n                    SELECT g.id AS id, COALESCE(gf.quotaused, 0) AS quotaused\n                    FROM {group} g\n                        LEFT OUTER JOIN (\n                            SELECT a.group, SUM(aff.size) AS quotaused\n                            FROM {artefact} a JOIN {artefact_file_files} aff ON a.id = aff.artefact\n                            WHERE NOT a.group IS NULL\n                            GROUP BY a.group\n                        ) gf ON gf.group = g.id\n                    WHERE g.quota IS NULL AND g.quotaused = 0 AND g.deleted = 0\n                ) f\n                SET quota = CASE WHEN f.quotaused < 52428800 THEN 52428800 ELSE f.quotaused + 52428800 END,\n                    {group}.quotaused = f.quotaused\n                WHERE {group}.id = f.id");
        }
    }
    if ($oldversion < 2011072600) {
        // Add tables to store custom institution styles
        // Currently only institutions can use them, but merge this with skin tables later...
        $table = new XMLDBTable('style');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('css', XMLDB_TYPE_TEXT);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('style_property');
        $table->addFieldInfo('style', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('style', 'field'));
        $table->addKeyInfo('stylefk', XMLDB_KEY_FOREIGN, array('style'), 'style', array('id'));
        create_table($table);
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('style');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('stylefk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('style'), 'style', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011082200) {
        // Doing a direct insert of the new artefact type instead of running upgrade_plugin(), in order to support the
        // transition from old profile fields to the new socialprofile artefact in Mahara 1.10
        if (!record_exists('artefact_installed_type', 'name', 'html', 'plugin', 'internal')) {
            insert_record('artefact_installed_type', (object) array('name' => 'html', 'plugin' => 'internal'));
        }
        // Move the textbox blocktype into artefact/internal
        set_field('blocktype_installed', 'artefactplugin', 'internal', 'name', 'textbox');
        if ($data = check_upgrades("blocktype.internal/textbox")) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2011082300) {
        // Add institution to view_access table
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        if (!field_exists($table, $field)) {
            add_field($table, $field);
            // Add foreign key
            $key = new XMLDBKey('institutionfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
            add_key($table, $key);
            if (is_postgres()) {
                // Update constraint checks
                execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {view_access_check}');
                execute_sql('ALTER TABLE {view_access} ADD CHECK (
                    (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NULL     AND institution IS NOT NULL))');
            } else {
                // MySQL doesn't support these types of constraints
            }
        }
    }
    if ($oldversion < 2011082400) {
        // Add cron entry for cache cleanup
        $cron = new StdClass();
        $cron->callfunction = 'file_cleanup_old_cached_files';
        $cron->minute = '0';
        $cron->hour = '1';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2011082401) {
        // Set config value for logged-in profile view access
        set_config('loggedinprofileviewaccess', 1);
    }
    if ($oldversion < 2011083000) {
        // Jointype changes
        $table = new XMLDBTable('group');
        $field = new XMLDBField('request');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_field('group', 'request', 1, 'jointype', 'request');
        // Turn all request & invite groups into the 'approve' type
        $field = new XMLDBField('jointype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('open', 'controlled', 'request', 'invite', 'approve'), 'open');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} DROP CONSTRAINT {grou_joi_ck}');
        }
        change_field_enum($table, $field);
        set_field('group', 'jointype', 'approve', 'jointype', 'request');
        set_field('group', 'jointype', 'approve', 'jointype', 'invite');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('open', 'controlled', 'approve'), 'open');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} DROP CONSTRAINT {grou_joi_ck}');
        }
        change_field_enum($table, $field);
        // Move view submission from grouptype to group
        $field = new XMLDBField('submittableto');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        execute_sql("UPDATE {group} SET submittableto = 1 WHERE grouptype IN (SELECT name FROM {grouptype} WHERE submittableto = 1)");
        $table = new XMLDBTable('grouptype');
        $field = new XMLDBField('submittableto');
        drop_field($table, $field);
        // Any group can potentially take submissions, so make sure someone can assess them
        set_field('grouptype_roles', 'see_submitted_views', 1, 'role', 'admin');
        // Move group view editing permission from grouptype_roles to the group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('editroles');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('all', 'notmember', 'admin'), 'all');
        add_field($table, $field);
        execute_sql("\n            UPDATE {group} SET editroles = 'notmember' WHERE grouptype IN (\n                SELECT grouptype FROM {grouptype_roles} WHERE role = 'member' AND edit_views = 0\n            )");
        $table = new XMLDBTable('grouptype_roles');
        $field = new XMLDBField('edit_views');
        drop_field($table, $field);
    }
    if ($oldversion < 2011090900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('password');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        change_field_type($table, $field, true, true);
    }
    if ($oldversion < 2011091200) {
        // Locked group views (only editable by group admins)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('locked');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_field('view', 'locked', 1, 'type', 'grouphomepage');
        // Setting to hide groups from the "Find Groups" listing
        $table = new XMLDBTable('group');
        $field = new XMLDBField('hidden');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Setting to hide group members
        $field = new XMLDBField('hidemembers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Setting to hide group members from members
        $field = new XMLDBField('hidemembersfrommembers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Allow group members to invite friends
        $field = new XMLDBField('invitefriends');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Allow group members to recommend the group to friends
        $field = new XMLDBField('suggestfriends');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2011091300) {
        $table = new XMLDBTable('blocktype_category');
        $field = new XMLDBField('sort');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('0', 'fileimagevideo'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('1', 'blog'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('2', 'general'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('3', 'internal'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('4', 'resume'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('5', 'external'));
        $index = new XMLDBIndex('sortuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('sort'));
        add_index($table, $index, false);
    }
    if ($oldversion < 2011092600) {
        // Move the taggedposts blocktype into artefact/blog/blocktype
        set_field('blocktype_installed', 'artefactplugin', 'blog', 'name', 'taggedposts');
    }
    if ($oldversion < 2011102700) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('logintries');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Every 5 minutes, reset everyone's login attempts to 0
        $cron = new StdClass();
        $cron->callfunction = 'user_login_tries_to_zero';
        $cron->minute = '*/5';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2011111500) {
        $table = new XMLDBTable('blocktype_installed_category');
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('blocktype'));
        add_key($table, $key);
    }
    if ($oldversion < 2011120200) {
        if ($data = check_upgrades('blocktype.blog/taggedposts')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.watchlist')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2012011300) {
        $table = new XMLDBTable('group_member');
        $field = new XMLDBField('method');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL, null, null, null, 'internal');
        add_field($table, $field);
    }
    if ($oldversion < 2012021000) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('unread');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2012021700) {
        $sql = "\n            FROM {usr} u JOIN {auth_instance} ai ON (u.authinstance = ai.id)\n            WHERE u.deleted = 0 AND ai.authname = 'internal' AND u.password != '*' AND u.salt != '*'";
        $pwcount = count_records_sql("SELECT COUNT(*) " . $sql);
        $sql = "\n            SELECT u.id, u.password, u.salt" . $sql . " AND u.id > ?\n            ORDER BY u.id";
        $done = 0;
        $lastid = 0;
        $limit = 2000;
        while ($users = get_records_sql_array($sql, array($lastid), 0, $limit)) {
            foreach ($users as $user) {
                // Wrap the old hashed password inside a SHA512 hash ($6$ is the identifier for SHA512)
                $user->password = crypt($user->password, '$6$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 16));
                // Drop the salt from the password as it may contain secrets that are not stored in the db
                // for example, the passwordsaltmain value
                $user->password = substr($user->password, 0, 3) . substr($user->password, 3 + 16);
                set_field('usr', 'password', $user->password, 'id', $user->id);
                remove_user_sessions($user->id);
                $lastid = $user->id;
            }
            $done += count($users);
            log_debug("Upgrading stored passwords: {$done}/{$pwcount}");
            set_time_limit(30);
        }
    }
    if ($oldversion < 2012022100) {
        reload_html_filters();
    }
    if ($oldversion < 2012042600 && !table_exists(new XMLDBTable('iframe_source'))) {
        // Tables for configurable safe iframe sources
        $table = new XMLDBTable('iframe_source_icon');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('domain', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $iframedomains = array('YouTube' => 'www.youtube.com', 'Vimeo' => 'vimeo.com', 'SlideShare' => 'www.slideshare.net', 'Glogster' => 'www.glogster.com', 'WikiEducator' => 'wikieducator.org', 'Voki' => 'voki.com');
        foreach ($iframedomains as $name => $domain) {
            insert_record('iframe_source_icon', (object) array('name' => $name, 'domain' => $domain));
        }
        $table = new XMLDBTable('iframe_source');
        $table->addFieldInfo('prefix', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('prefix'));
        $table->addKeyInfo('namefk', XMLDB_KEY_FOREIGN, array('name'), 'iframe_source_icon', array('name'));
        create_table($table);
        $iframesources = array('www.youtube.com/embed/' => 'YouTube', 'player.vimeo.com/video/' => 'Vimeo', 'www.slideshare.net/slideshow/embed_code/' => 'SlideShare', 'www.glogster.com/glog/' => 'Glogster', 'www.glogster.com/glog.php' => 'Glogster', 'edu.glogster.com/glog/' => 'Glogster', 'edu.glogster.com/glog.php' => 'Glogster', 'wikieducator.org/index.php' => 'WikiEducator', 'voki.com/php/' => 'Voki');
        foreach ($iframesources as $prefix => $name) {
            insert_record('iframe_source', (object) array('prefix' => $prefix, 'name' => $name));
        }
        $iframeregexp = '%^https?://(' . str_replace('.', '\\.', implode('|', array_keys($iframesources))) . ')%';
        set_config('iframeregexp', $iframeregexp);
    }
    if ($oldversion < 2012042800) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('extra');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2012051500) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('authtype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, null, null, 'internal');
        add_field($table, $field);
        $key = new XMLDBKey('authtype');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('authtype'), 'auth_installed', array('name'));
        add_key($table, $key);
    }
    if ($oldversion < 2012053100) {
        // Clean url fields for usr, group, and view tables.
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 30, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid'));
        add_index($table, $index);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 30, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid'));
        add_index($table, $index);
        $table = new XMLDBTable('view');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid', 'owner', 'group', 'institution'));
        add_index($table, $index);
    }
    if ($oldversion < 2012060100) {
        // Collection submission
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('submittedgroup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
        $key = new XMLDBKey('submittedgroupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('submittedgroup'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('submittedhostfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('submittedhost'), 'host', array('wwwroot'));
        add_key($table, $key);
    }
    if ($oldversion < 2012062900) {
        // Add site registration data tables
        $table = new XMLDBTable('site_registration');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('site_registration_data');
        $table->addFieldInfo('registration_id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('registration_id', 'field'));
        $table->addKeyInfo('regdatafk', XMLDB_KEY_FOREIGN, array('registration_id'), 'site_registration', array('id'));
        create_table($table);
    }
    if ($oldversion < 2012062901) {
        // Add institution registration data tables
        $table = new XMLDBTable('institution_registration');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        create_table($table);
        $table = new XMLDBTable('institution_registration_data');
        $table->addFieldInfo('registration_id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('registration_id', 'field'));
        $table->addKeyInfo('regdatafk', XMLDB_KEY_FOREIGN, array('registration_id'), 'institution_registration', array('id'));
        create_table($table);
        // Install a cron job to collection institution registration data
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_registration_data';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = rand(0, 6);
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012062902) {
        // Add institution stats table
        $table = new XMLDBTable('institution_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'institution', 'type'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        create_table($table);
        // Insert cron jobs to save institution data
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012070200) {
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null);
        add_field($table, $field);
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null);
        add_field($table, $field);
        $field = new XMLDBField('owner');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        change_field_notnull($table, $field);
        // For PostgresSQL, change_field_notnull of $field=owner with precision = 10 BIGINT(10)
        // will add a temporary column, move data from owner column, remove the column 'owner'
        // and then rename the temporary column to 'owner'. Therefore, all indexes and foreign keys
        // related to column 'owner' will be removed
        if (is_postgres()) {
            $key = new XMLDBKey('owner');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
            add_key($table, $key);
        }
        $key = new XMLDBKey('group');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('institution');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // Add constraints
        execute_sql('ALTER TABLE {collection} ADD CHECK (
            (owner IS NOT NULL AND "group" IS NULL     AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NOT NULL AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NULL     AND institution IS NOT NULL)
        )');
    }
    if ($oldversion < 2012070300) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('groupparticipationreports');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2012080200) {
        $sql = "\n            FROM {usr} u JOIN {auth_instance} ai ON (u.authinstance = ai.id)\n            WHERE u.deleted = 0 AND ai.authname = 'internal' AND u.password != '*' AND u.salt != '*'\n            AND u.password NOT LIKE '\$%'";
        $pwcount = count_records_sql("SELECT COUNT(*) " . $sql);
        $sql = "\n            SELECT u.id, u.password, u.salt" . $sql . " AND u.id > ?\n            ORDER BY u.id";
        $done = 0;
        $lastid = 0;
        $limit = 2000;
        while ($users = get_records_sql_array($sql, array($lastid), 0, $limit)) {
            foreach ($users as $user) {
                // Wrap the old hashed password inside a SHA512 hash ($6$ is the identifier for SHA512)
                $user->password = crypt($user->password, '$6$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 16));
                // Drop the salt from the password as it may contain secrets that are not stored in the db
                // for example, the passwordsaltmain value
                $user->password = substr($user->password, 0, 3) . substr($user->password, 3 + 16);
                set_field('usr', 'password', $user->password, 'id', $user->id);
                remove_user_sessions($user->id);
                $lastid = $user->id;
            }
            $done += count($users);
            log_debug("Upgrading stored passwords: {$done}/{$pwcount}");
            set_time_limit(30);
        }
    }
    if ($oldversion < 2012080300) {
        // For multi-tokens we need '|' aka pipe characters either side of their old single token
        execute_sql('UPDATE {usr_account_preference} SET value = \'|\' || value || \'|\'
                            WHERE field=\'mobileuploadtoken\' AND NOT value ' . db_ilike() . '\'|%|\'');
    }
    if ($oldversion < 2012080600) {
        // Every minute, poll an imap mailbox to see if there are new mail bounces
        $cron = new StdClass();
        $cron->callfunction = 'check_imap_for_bounces';
        $cron->minute = '*';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012080601) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('editwindowstart');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
        $field = new XMLDBField('editwindowend');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
    }
    if ($oldversion < 2013011700) {
        set_config('defaultregistrationexpirylifetime', 1209600);
    }
    if ($oldversion < 2013012100) {
        $event = (object) array('name' => 'loginas');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2013012101) {
        $table = new XMLDBTable('event_log');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('realusr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('data', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('realusrfk', XMLDB_KEY_FOREIGN, array('realusr'), 'usr', array('id'));
        create_table($table);
        $cron = new StdClass();
        $cron->callfunction = 'cron_event_log_expire';
        $cron->minute = 7;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2013020500) {
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('license');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensor');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensorurl');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('licensedefault');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensemandatory');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $table = new XMLDBTable('artefact_license');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayname', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('icon', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
    }
    if ($oldversion < 2013020501) {
        require_once 'license.php';
        install_licenses_default();
    }
    if ($oldversion < 2013032202) {
        require_once get_config('libroot') . 'license.php';
        set_field('usr_account_preference', 'value', LICENSE_INSTITUTION_DEFAULT, 'field', 'licensedefault', 'value', '-');
    }
    if ($oldversion < 2013050700) {
        $table = new XMLDBTable('collection_tag');
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('tag', XMLDB_TYPE_CHAR, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('collection', 'tag'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
    }
    if ($oldversion < 2013062600) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('dropdownmenu');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2013081400) {
        // We've made a change to how update_safe_iframe_regex() generates the regex
        // Call this function to make sure the stored value reflects that change.
        update_safe_iframe_regex();
    }
    if ($oldversion < 2013082100) {
        log_debug('Update database for flexible page layouts feature');
        log_debug('1. Create table view_rows_columns');
        $table = new XMLDBTable('view_rows_columns');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('row', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        create_table($table);
        log_debug('2. Remake the table view_layout as view_layout_columns');
        $table = new XMLDBTable('view_layout_columns');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('widths', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('columnwidthuk', XMLDB_KEY_UNIQUE, array('columns', 'widths'));
        create_table($table);
        log_debug('3. Alter table view_layout');
        $table = new XMLDBTable('view_layout');
        $field = new XMLDBField('rows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        $field = new XMLDBField('iscustom');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('layoutmenuorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        log_debug('4. Create table view_layout_rows_columns');
        $table = new XMLDBTable('view_layout_rows_columns');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('viewlayout', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('row', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('rowfk', XMLDB_KEY_FOREIGN, array('viewlayout'), 'view_layout', array('id'));
        $table->addKeyInfo('columnsfk', XMLDB_KEY_FOREIGN, array('columns'), 'view_layout_columns', array('id'));
        create_table($table);
        log_debug('5. Create table usr_custom_layout');
        $table = new XMLDBTable('usr_custom_layout');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('layout', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('layoutfk', XMLDB_KEY_FOREIGN, array('layout'), 'view_layout', array('id'));
        create_table($table);
        log_debug('6. Convert existing view_layout records into new-style view_layouts with just one row');
        $oldlayouts = get_records_array('view_layout', '', '', 'id', 'id, columns, widths');
        foreach ($oldlayouts as $layout) {
            // We don't actually need to populate the "rows", "iscustom" or "layoutmenuorder" columns,
            // because their defaults take care of that.
            // Check to see if there's a view_layout_columns record that matches its widths.
            $colsid = get_field('view_layout_columns', 'id', 'widths', $layout->widths);
            if (!$colsid) {
                $colsid = insert_record('view_layout_columns', (object) array('columns' => $layout->columns, 'widths' => $layout->widths), 'id', true);
            }
            // Now insert a record for it in view_layout_rows_columns, to represent its one row
            insert_record('view_layout_rows_columns', (object) array('viewlayout' => $layout->id, 'row' => 1, 'columns' => $colsid));
            // And also it needs a record in usr_custom_layout saying it belongs to the root user
            insert_record('usr_custom_layout', (object) array('usr' => 0, 'layout' => $layout->id));
        }
        log_debug('7. Drop the obsolete view_layout.columns and view_layout.widths fields');
        $table = new XMLDBTable('view_layout');
        $field = new XMLDBField('columns');
        drop_field($table, $field);
        $field = new XMLDBField('widths');
        drop_field($table, $field);
        log_debug('8. Update default values for tables view_layout, view_layout_columns and view_layout_rows_columns');
        install_view_layout_defaults();
        log_debug('9. Update the table "block_instance"');
        $table = new XMLDBTable('block_instance');
        $field = new XMLDBField('row');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 1);
        // This one tends to take a while...
        set_time_limit(30);
        add_field($table, $field);
        set_time_limit(30);
        // Refactor the block_instance.viewcolumnorderuk key so it includes row.
        $key = new XMLDBKey('viewcolumnorderuk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('view', 'column', 'order'));
        // If this particular site has been around since before Mahara 1.2, this
        // will actually have been created as a unique index rather than a unique
        // key, so check for that first.
        $indexname = find_index_name($table, $key);
        if (preg_match('/uix$/', $indexname)) {
            $index = new XMLDBIndex($indexname);
            $index->setAttributes(XMLDB_INDEX_UNIQUE, array('view', 'column', 'order'));
            drop_index($table, $index);
        } else {
            drop_key($table, $key);
        }
        $key = new XMLDBKey('viewrowcolumnorderuk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('view', 'row', 'column', 'order'));
        add_key($table, $key);
        log_debug('10. Add a "numrows" column to the views table.');
        // The default value of "1" will be correct
        // for all existing views, because they're using the old one-row layout style
        $table = new XMLDBTable('view');
        $field = new XMLDBField('numrows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        log_debug('11. Update the table "view_rows_columns" for existing pages');
        execute_sql('INSERT INTO {view_rows_columns} ("view", "row", "columns") SELECT v.id, 1, v.numcolumns FROM {view} v');
    }
    if ($oldversion < 2013091900) {
        // Create skin table...
        $table = new XMLDBTable('skin');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 10, 'private', XMLDB_NOTNULL);
        $table->addFieldInfo('viewskin', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('bodybgimg', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('viewbgimg', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('ownerfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // Create skin_favorites table...
        $table = new XMLDBTable('skin_favorites');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('user', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('favorites', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userfk', XMLDB_KEY_FOREIGN, array('user'), 'usr', array('id'));
        create_table($table);
        // Create skin_fonts table...
        $table = new XMLDBTable('skin_fonts');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('licence', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('notice', XMLDB_TYPE_TEXT);
        $table->addFieldInfo('previewfont', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('variants', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('fonttype', XMLDB_TYPE_CHAR, 10, 'site', XMLDB_NOTNULL);
        $table->addFieldInfo('onlyheading', XMLDB_TYPE_INTEGER, 1, 0, XMLDB_NOTNULL);
        $table->addFieldInfo('fontstack', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('genericfont', XMLDB_TYPE_CHAR, 10, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('cursive', 'fantasy', 'monospace', 'sans-serif', 'serif'));
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('nameuk', XMLDB_KEY_UNIQUE, array('name'));
        create_table($table);
        // Set column 'skin' to 'view' table...
        $table = new XMLDBTable('view');
        $field = new XMLDBField('skin');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        require_once get_config('libroot') . 'skin.php';
        install_skins_default();
    }
    if ($oldversion < 2013091901) {
        // Add a "skins" table to institutions to record whether they've enabled skins or not
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('skins');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1, 'dropdownmenu');
        add_field($table, $field);
    }
    if ($oldversion < 2013092300) {
        $table = new XMLDBTable('import_entry_requests');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('importid', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entryid', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entryparent', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('strategy', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ownerid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrytype', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrytitle', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrycontent', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('duplicateditemids', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('existingitemids', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('artefactmapping', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('decision', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('owneridfk', XMLDB_KEY_FOREIGN, array('ownerid'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2013092600) {
        //  When uploading file as attachment and attaching it to an artefact, the artefact id
        //  (in artefact field) and uploaded file artefact id (in attachment filed) are stored.
        //  For Resume composite types (educationhistory, employmenthistory, books, etc.) this
        //  is not enough. So we have to add item field to differentiate between e.g. different
        //  employments in employmenhistory and to which employment the user actually whishes to
        //  attach certain attachment...
        $table = new XMLDBTable('artefact_attachment');
        $field = new XMLDBField('item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
    }
    if ($oldversion < 2013112100) {
        // Add a new column 'last_processed_userid' to the table 'activity_queue' in order to
        // split multiple user activity notifications into chunks
        $table = new XMLDBTable('activity_queue');
        $field = new XMLDBField('last_processed_userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('last_processed_useridfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('last_processed_userid'), 'usr', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2013112600) {
        // If a mahara site was upgraded from 1.0 then keys for the following tables
        // may be missing so we will check for them and if missing add them.
        // Normally when we create a foreign key, we create an index alongside it.
        // If these keys were created by the 1.1 upgrade script, they will be missing
        // those indexes. To get the index and the key in place, we have to re-create
        // the key.
        $table = new XMLDBTable('artefact_access_usr');
        $index = new XMLDBIndex('usrfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('usr'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('usr');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_usr.usr column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('usrfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_usr.usr referencing usr.id (the column probably contains some nonexistent user id's");
            }
        }
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('artefact');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_usr.artefact column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('artefactfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_usr.artefact referencing artefact.id (the column probably contains some nonexistent artefact id's)");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('usr', 'artefact'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table artefact_access_usr across columns (usr, artefact). (Probably the table contains some non-unique values in those columns)");
            }
        }
        $table = new XMLDBTable('artefact_access_role');
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('artefact');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_role.artefact column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('artefactfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_role.artefact referencing artefact.id (the column probably contains some nonexistente artefact id's)");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('role', 'artefact'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table artefact_access_role across columns (role, artefact). (Probably there are some non-unique values in those columns.)");
            }
        }
        $table = new XMLDBTable('artefact_attachment');
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            try {
                add_index($table, $index);
            } catch (SQLException $e) {
                log_warn("Couldn't set a non-unique index on column artefact_attachment.artefact");
            }
        }
        $table = new XMLDBTable('group');
        $key = new XMLDBKey('grouptypefk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column group.grouptype referencing grouptype.name (the column probably contains some nonexistent grouptypes)");
            }
        }
        $table = new XMLDBTable('grouptype_roles');
        $index = new XMLDBIndex('grouptypefk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('grouptype'));
        if (!index_exists($table, $index)) {
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column grouptype_roles.grouptype referencing grouptype.name (the column probably contains some nonexistent grouptypes");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('grouptype', 'role'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table grouptype_roles across columns (grouptype, role). (Probably there are some non-unique values in those columns.)");
            }
        }
        $table = new XMLDBTable('view_autocreate_grouptype');
        $index = new XMLDBIndex('viewfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('view'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('view');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change column view_autocreate_grouptype.view to NOT NULL (probably the column contains some NULL values)");
            }
            $key = new XMLDBKey('viewfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column view_autocreate_grouptype.view referencing view.id (probably the column contains some nonexistent view IDs");
            }
        }
        $index = new XMLDBIndex('grouptypefk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('grouptype'));
        if (!index_exists($table, $index)) {
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column view_autocreate_grouptype.grouptype referencing grouptype.name (probably the column contains some nonexistent grouptypes");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('view', 'grouptype'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table view_autocreate_grouptype across columns (view, grouptype). (Probably those columns contain some non-unique values.)");
            }
        }
    }
    if ($oldversion < 2013121300) {
        // view_rows_columns can be missing the 'id' column if upgrading from version
        // earlier than v1.8 and because we are adding a sequential primary column after
        // the table is already made we need to
        // - check that the column doesn't exist then add it without key or sequence
        // - update the values for the new id column to be sequential
        // - then add the primary key and finally make the column sequential
        if ($records = get_records_sql_array('SELECT * FROM {view_rows_columns}', array())) {
            if (empty($records[0]->id)) {
                $table = new XMLDBTable('view_rows_columns');
                $field = new XMLDBField('id');
                $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1, 'view');
                add_field($table, $field);
                $x = 1;
                foreach ($records as $record) {
                    execute_sql('UPDATE {view_rows_columns} SET id = ? WHERE view = ? AND row = ? AND columns = ?', array($x, $record->view, $record->row, $record->columns));
                    $x++;
                }
                // we can't add a sequence on a field unless it has a primary key
                $key = new XMLDBKey('primary');
                $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
                add_key($table, $key);
                $field = new XMLDBField('id');
                $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
                change_field_type($table, $field);
                // but when we change field type postgres drops the keys for the column so we need
                // to add the primary key back again - see line 2205 for more info
                if (is_postgres()) {
                    $key = new XMLDBKey('primary');
                    $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
                    add_key($table, $key);
                }
            }
        }
    }
    if ($oldversion < 2014010700) {
        // If the usr_custom_layout.group column exists, it indicates that we this patch has already
        // been run and we should skip it.
        $table = new XMLDBTable('usr_custom_layout');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, 'usr');
        if (!field_exists($table, $field)) {
            // Add a log output line here so that we can tell whether this patch ran or not.
            log_debug('Correcting custom layout table structures.');
            // fix issue where custom layouts saved in groups, site pages and institutions
            // were set to have usr = 0 because view owner was null
            $table = new XMLDBTable('usr_custom_layout');
            $field = new XMLDBField('usr');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
            change_field_notnull($table, $field);
            // For PostgresSQL, change_field_notnull creates a temporary column, moves data to new temp column
            // and then renames the temp column to 'usr'. Therefore, all indexes and foreign keys
            // related to column 'owner' will be removed
            if (is_postgres()) {
                $key = new XMLDBKey('usr');
                $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
                add_key($table, $key);
            }
            $field = new XMLDBField('group');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, 'usr');
            add_field($table, $field);
            $key = new XMLDBKey('groupfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
            add_key($table, $key);
            $field = new XMLDBField('institution');
            $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null, 'group');
            add_field($table, $field);
            $key = new XMLDBKey('institutionfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
            add_key($table, $key);
            // update previous records
            // get custom layouts with usr = 0 which are not in default set
            $groupcustomlayouts = get_records_sql_array('SELECT ucl.layout FROM {usr_custom_layout} ucl
                                                         LEFT JOIN {view_layout} vl ON vl.id = ucl.layout
                                                         WHERE usr = 0 AND iscustom = 1
                                                         ORDER BY ucl.id', array());
            if ($groupcustomlayouts != false) {
                foreach ($groupcustomlayouts as $groupcustomlayout) {
                    // find views using this custom layout
                    $views = get_records_array('view', 'layout', $groupcustomlayout->layout, '', 'owner, "group", institution');
                    if ($views != false) {
                        foreach ($views as $view) {
                            if (isset($view->owner)) {
                                // view owned by individual
                                $recordexists = get_record('usr_custom_layout', 'usr', $view->owner, 'layout', $groupcustomlayout->layout);
                                if (!$recordexists) {
                                    // add new record into usr_custom_layout table
                                    $customlayout = new stdClass();
                                    $customlayout->usr = $view->owner;
                                    $customlayout->layout = $groupcustomlayout->layout;
                                    insert_record('usr_custom_layout', $customlayout, 'id');
                                }
                            } else {
                                if (isset($view->group)) {
                                    // view owned by group
                                    $recordexists = get_record('usr_custom_layout', 'group', $view->group, 'layout', $groupcustomlayout->layout);
                                    if (!$recordexists) {
                                        // add new record into usr_custom_layout table
                                        $customlayout = new stdClass();
                                        $customlayout->group = $view->group;
                                        $customlayout->layout = $groupcustomlayout->layout;
                                        insert_record('usr_custom_layout', $customlayout, 'id');
                                    }
                                } else {
                                    if (isset($view->institution)) {
                                        // view owned by group
                                        $recordexists = get_record('usr_custom_layout', 'institution', $view->institution, 'layout', $groupcustomlayout->layout);
                                        if (!$recordexists) {
                                            // add new record into usr_custom_layout table
                                            $customlayout = new stdClass();
                                            $customlayout->institution = $view->institution;
                                            $customlayout->layout = $groupcustomlayout->layout;
                                            insert_record('usr_custom_layout', $customlayout, 'id');
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // now remove this custom layout
                    $removedrecords = delete_records('usr_custom_layout', 'usr', '0', 'layout', $groupcustomlayout->layout);
                }
            }
        }
    }
    if ($oldversion < 2014010800) {
        $table = new XMLDBTable('institution_config');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small');
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('instfielduk', XMLDB_INDEX_UNIQUE, array('institution', 'field'));
        create_table($table);
    }
    if ($oldversion < 2014010801) {
        // adding institution column to allow for different site content for each institution
        $table = new XMLDBTable('site_content');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        // resetting the primary key and updating what is currently there to be
        // the 'mahara' institution's site pages
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('name'));
        drop_key($table, $key);
        execute_sql("UPDATE {site_content} SET institution = ?", array('mahara'));
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('name', 'institution'));
        add_key($table, $key);
        $key = new XMLDBKey('institutionfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // now add the default general pages for each existing institution with the values of
        // the 'mahara' institution. These can them be altered via Administration -> Institutions -> General pages
        $sitecontentarray = array();
        $sitecontents = get_records_array('site_content', 'institution', 'mahara');
        foreach ($sitecontents as $sitecontent) {
            $sitecontentarray[$sitecontent->name] = $sitecontent->content;
        }
        $pages = site_content_pages();
        $now = db_format_timestamp(time());
        $institutions = get_records_array('institution');
        foreach ($institutions as $institution) {
            if ($institution->name != 'mahara') {
                foreach ($pages as $name) {
                    $page = new stdClass();
                    $page->name = $name;
                    $page->ctime = $now;
                    $page->mtime = $now;
                    $page->content = $sitecontentarray[$name];
                    $page->institution = $institution->name;
                    insert_record('site_content', $page);
                    $pageconfig = new stdClass();
                    $pageconfig->institution = $institution->name;
                    $pageconfig->field = 'sitepages_' . $name;
                    $pageconfig->value = 'mahara';
                    insert_record('institution_config', $pageconfig);
                }
            }
        }
    }
    if ($oldversion < 2014021100) {
        // Reset the view's skin value, if the skin does not exist
        execute_sql("UPDATE {view} v SET skin = NULL WHERE v.skin IS NOT NULL AND NOT EXISTS (SELECT id FROM {skin} s WHERE v.skin = s.id)");
    }
    if ($oldversion < 2014021200) {
        // Adding new Creative Commons 4.0 licenses.
        // CC4.0 will be added only if:
        // -- The CC4.0 URL doesn't already exist;
        // -- And CC3.0 hasn't been deleted earlier.
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-sa/4.0/';
        $license->displayname = get_string('licensedisplaynamebysa', 'install');
        $license->shortname = get_string('licenseshortnamebysa', 'install');
        $license->icon = 'license:by-sa.png';
        $version30 = 'http://creativecommons.org/licenses/by-sa/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by/4.0/';
        $license->displayname = get_string('licensedisplaynameby', 'install');
        $license->shortname = get_string('licenseshortnameby', 'install');
        $license->icon = 'license:by.png';
        $version30 = 'http://creativecommons.org/licenses/by/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nd/4.0/';
        $license->displayname = get_string('licensedisplaynamebynd', 'install');
        $license->shortname = get_string('licenseshortnamebynd', 'install');
        $license->icon = 'license:by-nd.png';
        $version30 = 'http://creativecommons.org/licenses/by-nd/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc-sa/4.0/';
        $license->displayname = get_string('licensedisplaynamebyncsa', 'install');
        $license->shortname = get_string('licenseshortnamebyncsa', 'install');
        $license->icon = 'license:by-nc-sa.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc-sa/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc/4.0/';
        $license->displayname = get_string('licensedisplaynamebync', 'install');
        $license->shortname = get_string('licenseshortnamebync', 'install');
        $license->icon = 'license:by-nc.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc-nd/4.0/';
        $license->displayname = get_string('licensedisplaynamebyncnd', 'install');
        $license->shortname = get_string('licenseshortnamebyncnd', 'install');
        $license->icon = 'license:by-nc-nd.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc-nd/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
    }
    if ($oldversion < 2014022400) {
        // Make sure artefacts are properly locked for submitted views.
        // Can be a problem for older sites
        $submitted = get_records_sql_array("SELECT v.owner FROM {view_artefact} va\n                        LEFT JOIN {view} v on v.id = va.view\n                        LEFT JOIN {artefact} a on a.id = va.artefact\n                        WHERE (v.submittedgroup IS NOT NULL OR v.submittedhost IS NOT NULL)", array());
        if ($submitted) {
            require_once get_config('docroot') . 'artefact/lib.php';
            foreach ($submitted as $record) {
                ArtefactType::update_locked($record->owner);
            }
        }
    }
    if ($oldversion < 2014022600) {
        $table = new XMLDBTable('host');
        $field = new XMLDBField('portno');
        drop_field($table, $field);
    }
    if ($oldversion < 2014032400) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('sendnow');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2014032500) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('probation');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2014032600) {
        set_config('watchlistnotification_delay', 20);
        if (!table_exists(new XMLDBTable('watchlist_queue'))) {
            $table = new XMLDBTable('watchlist_queue');
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
            $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            $table->addFieldInfo('block', XMLDB_TYPE_INTEGER, 10, null, false);
            $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            $table->addFieldInfo('changed_on', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
            $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
            $table->addKeyInfo('blockfk', XMLDB_KEY_FOREIGN, array('block'), 'block_instance', array('id'));
            $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            create_table($table);
        }
        // new event type: delete blockinstance
        $e = new stdClass();
        $e->name = 'deleteblockinstance';
        ensure_record_exists('event_type', $e, $e);
        // install the core event subscriptions
        $subs = array(array('event' => 'blockinstancecommit', 'callfunction' => 'watchlist_record_changes'), array('event' => 'deleteblockinstance', 'callfunction' => 'watchlist_block_deleted'), array('event' => 'saveartefact', 'callfunction' => 'watchlist_record_changes'), array('event' => 'saveview', 'callfunction' => 'watchlist_record_changes'));
        foreach ($subs as $sub) {
            ensure_record_exists('event_subscription', (object) $sub, (object) $sub);
        }
        // install the cronjobs...
        $cron = new stdClass();
        $cron->callfunction = 'watchlist_process_notifications';
        $cron->minute = '*';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
    }
    if ($oldversion < 2014032700) {
        // Remove bad data created by the upload user via csv where users in no institution
        // have 'licensedefault' set causing an error
        execute_sql("DELETE FROM {usr_account_preference} WHERE FIELD = 'licensedefault' AND usr IN (\n                        SELECT u.id FROM {usr} u\n                        LEFT JOIN {usr_institution} ui ON ui.usr = u.id\n                        WHERE ui.institution = 'mahara' OR ui.institution is null\n                     )");
    }
    if ($oldversion < 2014040300) {
        // Figure out where the magicdb is, and stick with that.
        require_once get_config('libroot') . 'file.php';
        update_magicdb_path();
    }
    // Add id field and corresponding index to institution table.
    if ($oldversion < 2014040400) {
        $table = new XMLDBTable('institution');
        // Add id field.
        $field = new XMLDBField('id');
        if (!field_exists($table, $field)) {
            // Field.
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1, 'name');
            add_field($table, $field);
            // Update ids.
            $institutions = get_records_array('institution');
            $x = 1;
            foreach ($institutions as $institution) {
                execute_sql('UPDATE {institution} SET id = ? WHERE name = ?', array($x, $institution->name));
                $x++;
            }
            $key = new XMLDBKey('inst_id_uk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('id'));
            add_key($table, $key);
            // Add sequence.
            $field = new XMLDBField('id');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
            change_field_type($table, $field);
            // In postgres, keys and indexes are removed when a field is changed ("Add sequence" above), so add the key back.
            if (is_postgres()) {
                $key = new XMLDBKey('inst_id_uk');
                $key->setAttributes(XMLDB_KEY_UNIQUE, array('id'));
                add_key($table, $key);
            }
        }
    }
    if ($oldversion < 2014041401) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('registerallowed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, '0');
        change_field_default($table, $field);
    }
    if ($oldversion < 2014041600) {
        // Add allownonemethod and defaultmethod fields to activity_type table.
        $table = new XMLDBTable('activity_type');
        $field = new XMLDBField('allownonemethod');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, null, null, 1, 'delay');
        add_field($table, $field);
        $field = new XMLDBField('defaultmethod');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, 'email', 'allownonemethod');
        add_field($table, $field);
        // Allow null method in usr_activity_preference.
        // Null indicates "none", no record indicates "not yet set" so use the default.
        $table = new XMLDBTable('usr_activity_preference');
        $field = new XMLDBField('method');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null);
        change_field_notnull($table, $field);
    }
    // Add about me block to existing profile template.
    if ($oldversion < 2014043000) {
        $systemprofileviewid = get_field('view', 'id', 'owner', 0, 'type', 'profile');
        // Find out how many blocks already exist.
        $maxorder = get_field_sql('select max("order") from {block_instance} where "view"=? and "row"=? and "column"=?', array($systemprofileviewid, 1, 1));
        // Create the block at the end of the cell.
        require_once get_config('docroot') . 'blocktype/lib.php';
        $aboutme = new BlockInstance(0, array('blocktype' => 'profileinfo', 'title' => get_string('aboutme', 'blocktype.internal/profileinfo'), 'view' => $systemprofileviewid, 'row' => 1, 'column' => 1, 'order' => $maxorder + 1));
        $aboutme->commit();
        // Move the block to the start of the cell.
        require_once get_config('libroot') . 'view.php';
        $view = new View($systemprofileviewid);
        $view->moveblockinstance(array('id' => $aboutme->get('id'), 'row' => 1, 'column' => 1, 'order' => 1));
    }
    if ($oldversion < 2014050901) {
        require_once get_config('docroot') . 'artefact/lib.php';
        // First drop artefact_parent_cache table.
        $table = new XMLDBTable('artefact_parent_cache');
        drop_table($table, true);
        // Remove cron jobs from DB.
        delete_records('cron', 'callfunction', 'rebuild_artefact_parent_cache_dirty');
        delete_records('cron', 'callfunction', 'rebuild_artefact_parent_cache_complete');
        // Add path field to artefact table.
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '1024', null, null, null, null, null);
        add_field($table, $field);
        // Fill the new field with path data.
        // Set all artefacts to the path they'd have if they have no parent.
        log_debug('Filling in parent artefact paths');
        if (get_config('searchplugin') == 'elasticsearch') {
            log_debug('Dropping elasticsearch artefact triggers');
            require_once get_config('docroot') . 'search/elasticsearch/lib.php';
            ElasticsearchIndexing::drop_triggers('artefact');
        }
        $count = 0;
        $limit = 1000;
        $limitsmall = 200;
        $total = count_records_select('artefact', 'path IS NULL AND parent IS NULL');
        for ($i = 0; $i <= $total; $i += $limitsmall) {
            if (is_mysql()) {
                execute_sql("UPDATE {artefact} SET path = CONCAT('/', id) WHERE path IS NULL AND parent IS NULL LIMIT " . $limitsmall);
            } else {
                // Postgres can only handle limit in subquery
                execute_sql("UPDATE {artefact} SET path = CONCAT('/', id) WHERE id IN (SELECT id FROM {artefact} WHERE path IS NULL AND parent IS NULL LIMIT " . $limitsmall . ")");
            }
            $count += $limitsmall;
            if ($count % $limit == 0 || $count >= $total) {
                if ($count > $total) {
                    $count = $total;
                }
                log_debug("{$count}/{$total}");
                set_time_limit(30);
            }
        }
        $newcount = count_records_select('artefact', 'path IS NULL');
        if ($newcount) {
            $childlevel = 0;
            do {
                $childlevel++;
                $lastcount = $newcount;
                log_debug("Filling in level-{$childlevel} child artefact paths");
                if (is_postgres()) {
                    execute_sql("\n                        UPDATE {artefact}\n                        SET path = p.path || '/' || {artefact}.id\n                        FROM {artefact} p\n                        WHERE\n                            {artefact}.parent=p.id\n                            AND {artefact}.path IS NULL\n                            AND p.path IS NOT NULL\n                    ");
                } else {
                    execute_sql("\n                        UPDATE\n                            {artefact} a\n                            INNER JOIN {artefact} p\n                            ON a.parent = p.id\n                        SET a.path=p.path || '/' || a.id\n                        WHERE\n                            a.path IS NULL\n                            AND p.path IS NOT NULL\n                    ");
                }
                $newcount = count_records_select('artefact', 'path IS NULL');
                // There may be some bad records whose paths can't be filled in,
                // so stop looping if the count stops going down.
            } while ($newcount > 0 && $newcount < $lastcount);
            log_debug("Done filling in child artefact paths");
        }
        if (get_config('searchplugin') == 'elasticsearch') {
            log_debug("Add triggers back in");
            ElasticsearchIndexing::create_triggers('artefact');
        }
    }
    // Make objectionable independent of view_access page.
    if ($oldversion < 2014060300) {
        log_debug("Create 'objectionable' table.");
        $table = new XMLDBTable('objectionable');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('objecttype', XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL);
        $table->addFieldInfo('objectid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('reportedby', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('report', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addFieldInfo('reportedtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('resolvedby', XMLDB_TYPE_INTEGER, 10, null, null);
        $table->addFieldInfo('resolvedtime', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('reporterfk', XMLDB_KEY_FOREIGN, array('reportedby'), 'usr', array('id'));
        $table->addKeyInfo('resolverfk', XMLDB_KEY_FOREIGN, array('resolvedby'), 'usr', array('id'));
        $table->addIndexInfo('objectix', XMLDB_INDEX_NOTUNIQUE, array('objectid', 'objecttype'));
        create_table($table);
        // Migrate data to a new format.
        // Since we don't have report or name of the user, use root ID.
        // Table 'notification_internal_activity' contains data that is
        // not possible to extract in any reasonable way.
        $objectionable = get_records_array('view_access', 'accesstype', 'objectionable');
        db_begin();
        log_debug('Migrating objectionable records to new format');
        if (!empty($objectionable)) {
            $count = 0;
            $limit = 1000;
            $total = count($objectionable);
            foreach ($objectionable as $record) {
                $todb = new stdClass();
                $todb->objecttype = 'view';
                $todb->objectid = $record->view;
                $todb->reportedby = 0;
                $todb->report = '';
                $todb->reportedtime = $record->ctime ? $record->ctime : format_date(time());
                if (!empty($record->stopdate)) {
                    // Since we can't get an ID of a user who resolved an issue, use root ID.
                    $todb->resolvedby = 0;
                    $todb->resolvedtime = $record->stopdate;
                }
                insert_record('objectionable', $todb);
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
        // Delete data from 'view_access' table as we don't need it any more.
        delete_records('view_access', 'accesstype', 'objectionable');
        db_commit();
        log_debug("Drop constraint on 'view_access'");
        // Need to run this to avoid contraints problems on Postgres.
        if (is_postgres()) {
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        log_debug("Update 'view_access' accesstype");
        // Update accesstype in 'view_access' not to use 'objectionable'.
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2014060500) {
        log_debug("Add 'artefact_access' table.");
        $table = new XMLDBTable('artefact_access');
        $table->addFieldInfo('artefact', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('accesstype', XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends'));
        $table->addFieldInfo('group', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('artefactfk', XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
        $table->addKeyInfo('groupfk', XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('accesstypeix', XMLDB_INDEX_NOTUNIQUE, array('accesstype'));
        create_table($table);
    }
    if ($oldversion < 2014061100) {
        log_debug('Add module related tables');
        $table = new XMLDBTable('module_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('module_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('module_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('module_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2014062000) {
        log_debug('Fix up auth_clean_expired_password_requests cron');
        $where = array('callfunction' => 'auth_clean_expired_password_requests');
        $data = array('callfunction' => 'auth_clean_expired_password_requests', 'minute' => '5', 'hour' => '0', 'day' => '*', 'month' => '*', 'dayofweek' => '*');
        ensure_record_exists('cron', (object) $where, (object) $data);
    }
    if ($oldversion < 2014062500) {
        log_debug("Add 'feedbacknotify' option to 'group' table");
        require_once get_config('libroot') . 'group.php';
        $table = new XMLDBTable('group');
        $field = new XMLDBField('feedbacknotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, GROUP_ROLES_ALL);
        if (!field_exists($table, $field)) {
            add_field($table, $field);
        }
    }
    if ($oldversion < 2014073100) {
        log_debug('Delete leftover data which are not associated to any institution');
        // Institution collections
        $collectionids = get_column_sql('
            SELECT id
            FROM {collection} c
            WHERE c.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = c.institution)');
        if ($collectionids) {
            require_once get_config('libroot') . 'collection.php';
            $count = 0;
            $limit = 200;
            $total = count($collectionids);
            foreach ($collectionids as $collectionid) {
                $collection = new Collection($collectionid);
                $collection->delete();
                $count++;
                if ($count % $limit == 0) {
                    log_debug("Deleting leftover collections: {$count}/{$total}");
                    set_time_limit(30);
                }
            }
            log_debug("Deleting leftover collections: {$count}/{$total}");
        }
        log_debug('Delete leftover custom layouts / usr registration');
        // Institution custom layouts and registration
        delete_records_sql('
            DELETE FROM {usr_custom_layout}
            WHERE {usr_custom_layout}.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = {usr_custom_layout}.institution)');
        delete_records_sql('
            DELETE FROM {usr_registration}
            WHERE {usr_registration}.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = {usr_registration}.institution)');
    }
    if ($oldversion < 2014081900) {
        log_debug("Check blocktype 'text' is installed");
        if ($data = check_upgrades('blocktype.text')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014091600) {
        log_debug('Allow anonymous pages');
        $table = new XMLDBTable('view');
        $field = new XMLDBField('anonymise');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_config('allowanonymouspages', 0);
    }
    if ($oldversion < 2014091800) {
        log_debug("Add 'allowarchives' column to the 'group' table");
        $table = new XMLDBTable('group');
        $field = new XMLDBField('allowarchives');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        log_debug("Add 'submittedstatus' column to 'view' table");
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedstatus');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0, 'submittedtime');
        add_field($table, $field);
        log_debug("Need to update the submitted status for any existing views that are submitted");
        execute_sql('UPDATE {view} SET submittedstatus = 1 WHERE submittedgroup IS NOT NULL
                    AND submittedtime IS NOT NULL');
        log_debug("Add 'submittedstatus' column to 'collection' table");
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('submittedstatus');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0, 'submittedtime');
        add_field($table, $field);
        log_debug('Need to update the submitted status for any existing collections that are submitted');
        execute_sql('UPDATE {collection} SET submittedstatus = 1 WHERE submittedgroup IS NOT NULL
                    AND submittedtime IS NOT NULL');
        log_debug('Adding the export queue / submission tables');
        // Add export queue table - each export is one row.
        $table = new XMLDBTable('export_queue');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 50);
        $table->addFieldInfo('exporttype', XMLDB_TYPE_CHAR, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('starttime', XMLDB_TYPE_DATETIME);
        $table->addFieldInfo('externalid', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('submitter', XMLDB_TYPE_INTEGER, 10);
        // for when the submitter is not the owner
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('submitterfk', XMLDB_KEY_FOREIGN, array('submitter'), 'usr', array('id'));
        create_table($table);
        // Add export queue items table which maps what views/collections/artefacts relate to the queue item.
        $table = new XMLDBTable('export_queue_items');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('exportqueueid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('exportqueuefk', XMLDB_KEY_FOREIGN, array('exportqueueid'), 'export_queue', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        create_table($table);
        // Add export archive table to hold info that will allow one to download the zip file
        $table = new XMLDBTable('export_archive');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filename', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filetitle', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filepath', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('submission', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
        // Add archived submissions table to hold submission info
        $table = new XMLDBTable('archived_submissions');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('archiveid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('group', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('externalhost', XMLDB_TYPE_CHAR, 50);
        $table->addFieldInfo('externalid', XMLDB_TYPE_CHAR, 255);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('groupfk', XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        $table->addKeyInfo('archivefk', XMLDB_KEY_FOREIGN, array('archiveid'), 'export_archive', array('id'));
        create_table($table);
        // install the cronjob to process export queue
        $cron = new StdClass();
        $cron->callfunction = 'export_process_queue';
        $cron->minute = '*/6';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
        // install the cronjob to clean up deleted archived submissions items
        $cron = new StdClass();
        $cron->callfunction = 'submissions_delete_removed_archive';
        $cron->minute = '15';
        $cron->hour = '1';
        $cron->day = '1';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
    }
    if ($oldversion < 2014092300) {
        log_debug('Add the socialprofile artefacttype');
        // Need to insert directly into the table instead of running upgrade_plugin(), so that we can transition
        // all the old social network artefact types into the new unified socialprofile type before deleting
        // the old types from artefact_installed_type
        insert_record('artefact_installed_type', (object) array('name' => 'socialprofile', 'plugin' => 'internal'));
        // Convert existing messaging types to socialprofile types.
        $oldmessagingfieldsarray = array('icqnumber', 'msnnumber', 'aimscreenname', 'yahoochat', 'skypeusername', 'jabberusername');
        $oldmessagingfields = implode(',', array_map('db_quote', $oldmessagingfieldsarray));
        $sql = "SELECT * FROM {artefact}\n                WHERE artefacttype IN (" . $oldmessagingfields . ")";
        if ($results = get_records_sql_assoc($sql, array())) {
            $count = 0;
            $limit = 1000;
            $total = count($results);
            safe_require('artefact', 'internal');
            foreach ($results as $result) {
                $i = new ArtefactTypeSocialprofile($result->id, (array) $result);
                $i->set('artefacttype', 'socialprofile');
                switch ($result->artefacttype) {
                    case 'aimscreenname':
                        $i->set('note', 'aim');
                        $i->set('description', get_string('aim', 'artefact.internal'));
                        break;
                    case 'icqnumber':
                        $i->set('note', 'icq');
                        $i->set('description', get_string('icq', 'artefact.internal'));
                        break;
                    case 'jabberusername':
                        $i->set('note', 'jabber');
                        $i->set('description', get_string('jabber', 'artefact.internal'));
                        break;
                    case 'msnnumber':
                    case 'skypeusername':
                        // MSN no longer exists and has been replaced by Skype.
                        $i->set('note', 'skype');
                        $i->set('description', get_string('skype', 'artefact.internal'));
                        break;
                    case 'yahoochat':
                        $i->set('note', 'yahoo');
                        $i->set('description', get_string('yahoo', 'artefact.internal'));
                        break;
                }
                $i->set('title', $result->title);
                $i->commit();
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
        $sql = "SELECT value FROM {search_config} WHERE plugin='elasticsearch' AND field='artefacttypesmap'";
        if ($result = get_field_sql($sql, array())) {
            log_debug('Clean up elasticsearch fields for the old messaging fields');
            $artefacttypesmap_array = explode("\n", $result);
            $elasticsearchartefacttypesmap = array();
            foreach ($artefacttypesmap_array as $key => $value) {
                $tmpkey = explode("|", $value);
                if (count($tmpkey) == 3) {
                    if (!in_array($tmpkey[0], $oldmessagingfieldsarray)) {
                        // we're going to keep this one.
                        $elasticsearchartefacttypesmap[] = $value;
                    }
                }
            }
            // add socialprofile field.
            $elasticsearchartefacttypesmap[] = "socialprofile|Profile|Text";
            // now save the data excluding the old messaging fields.
            set_config_plugin('search', 'elasticsearch', 'artefacttypesmap', implode("\n", $elasticsearchartefacttypesmap));
        }
        log_debug('Delete unused, but still installed artefact types');
        delete_records_select("artefact_installed_type", "name IN (" . $oldmessagingfields . ")");
        log_debug('Install the social profile blocktype so users can see their migrated data');
        if ($data = check_upgrades('blocktype.internal/socialprofile')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014092300) {
        log_debug("Install 'multirecipientnotification' plugin");
        if ($data = check_upgrades('module.multirecipientnotification')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014101300) {
        log_debug("Make sure default notifications are not set to 'none'");
        // Make sure the 'system messages' and 'messages from other users' have a notification method set
        // It was possible after earlier upgrades to set method to 'none'.
        // Also make sure old defaultmethod is respected.
        $activitytypes = get_records_assoc('activity_type');
        foreach ($activitytypes as $type) {
            $type->defaultmethod = get_config('defaultnotificationmethod') ? get_config('defaultnotificationmethod') : 'email';
            if ($type->name == 'maharamessage' || $type->name == 'usermessage') {
                $type->allownonemethod = 0;
            }
            update_record('activity_type', $type);
        }
        // Make sure users have their 'system messages' and 'messages from other users' notification method set
        if ($useractivities = get_records_sql_assoc("SELECT * FROM {activity_type} at, {usr_activity_preference} uap\n                                                     WHERE at.id = uap.activity\n                                                     AND at.name IN ('maharamessage', 'usermessage')\n                                                     AND (method IS NULL OR method = '')", array())) {
            foreach ($useractivities as $activity) {
                $userprefs = new stdClass();
                $userprefs->method = $activity->defaultmethod;
                update_record('usr_activity_preference', $userprefs, array('usr' => $activity->usr, 'activity' => $activity->activity));
            }
        }
    }
    if ($oldversion < 2014101500) {
        log_debug('Place skin fonts in their correct directories');
        if ($fonts = get_records_assoc('skin_fonts', 'fonttype', 'google')) {
            $fontpath = get_config('dataroot') . 'skins/fonts/';
            foreach ($fonts as $font) {
                // if google font is not already in subdir
                if (!is_dir($fontpath . $font->name)) {
                    if (file_exists($fontpath . $font->previewfont)) {
                        // we need to create the subdir and move the file into it
                        $newfontpath = $fontpath . $font->name . '/';
                        check_dir_exists($newfontpath, true, true);
                        rename($fontpath . $font->previewfont, $newfontpath . $font->previewfont);
                        // and move the license file if it exists also
                        if (file_exists($fontpath . $font->licence)) {
                            rename($fontpath . $font->licence, $newfontpath . $font->licence);
                        }
                    } else {
                        // the file is not there for some reason so we might as well delete the font from the db
                        $result = delete_records('skin_fonts', 'name', $font->name);
                        if ($result !== false) {
                            // Check to see if the font is being used in a skin. If it is remove it from
                            // the skin's viewskin data
                            $skins = get_records_array('skin');
                            if (is_array($skins)) {
                                foreach ($skins as $skin) {
                                    $options = unserialize($skin->viewskin);
                                    foreach ($options as $key => $option) {
                                        if (preg_match('/font_family/', $key) && $option == $font->name) {
                                            require_once get_config('docroot') . 'lib/skin.php';
                                            $skinobj = new Skin($skin->id);
                                            $viewskin = $skinobj->get('viewskin');
                                            $viewskin[$key] = false;
                                            $skinobj->set('viewskin', $viewskin);
                                            $skinobj->commit();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if ($oldversion < 2014101501) {
        log_debug('Unlock root user grouphomepage template in case it is locked');
        set_field('view', 'locked', 0, 'type', 'grouphomepage', 'owner', 0);
    }
    if ($oldversion < 2014110500) {
        log_debug('Add cacheversion and assign random string');
        // Adding cacheversion, as an arbitrary number appended to the end of JS & CSS files in order
        // to tell cacheing software when they've been updated. (Without having to use the Mahara
        // minor version for that purpose.)
        // Set this to a random starting number to make minor version slightly harder to detect
        if (!get_config('cacheversion')) {
            set_config('cacheversion', rand(1000, 9999));
        }
    }
    if ($oldversion < 2014110700) {
        log_debug("Add in 'shortcut' category to 'blocktype_category'");
        // Increment all the existing sorts by 1 to make room...
        $cats = get_records_array('blocktype_category', '', '', 'sort desc');
        foreach ($cats as $cat) {
            $cat->sort = $cat->sort + 1;
            update_record('blocktype_category', $cat, 'name');
        }
        $todb = new stdClass();
        $todb->name = 'shortcut';
        $todb->sort = '0';
        insert_record('blocktype_category', $todb);
    }
    if ($oldversion < 2014112700) {
        log_debug("Fix up group homepages so that no duplicate 'groupview' blocks are present");
        // Need to find the group homepages that have more than one groupview on them
        // and merge their data into one groupview as we shouldn't allow more than one groupview block
        // as it breaks pagination
        // First get any pages that have more than one groupview on them
        // and find the status of the groupview blocks
        if ($records = get_records_sql_array("SELECT v.id AS view, bi.id AS block FROM {view} v\n            INNER JOIN {block_instance} bi ON v.id = bi.view\n            WHERE v.id IN (\n                SELECT v.id FROM {view} v\n                 INNER JOIN {block_instance} bi ON v.id = bi.view\n                 WHERE bi.blocktype = 'groupviews'\n                  AND v.type = 'grouphomepage'\n                 GROUP BY v.id\n                 HAVING COUNT(v.id) > 1\n            )\n            AND bi.blocktype='groupviews'\n            ORDER BY v.id, bi.id", array())) {
            require_once get_config('docroot') . 'blocktype/lib.php';
            $lastview = 0;
            // set default
            $info = array();
            $x = -1;
            foreach ($records as $record) {
                if ($lastview != $record->view) {
                    $x++;
                    $info[$x]['in']['showgroupviews'] = 0;
                    $info[$x]['in']['showsharedviews'] = 0;
                    $info[$x]['in']['view'] = $record->view;
                    $info[$x]['in']['block'] = $record->block;
                    $lastview = $record->view;
                } else {
                    $info[$x]['out'][] = $record->block;
                }
                $bi = new BlockInstance($record->block);
                $configdata = $bi->get('configdata');
                if (!empty($configdata['showgroupviews'])) {
                    $info[$x]['in']['showgroupviews'] = 1;
                }
                if (!empty($configdata['showsharedviews'])) {
                    $info[$x]['in']['showsharedviews'] = 1;
                }
            }
            // now that we have info on the state of play we need to save one of the blocks
            // with correct data and delete the not needed blocks
            $count = 0;
            $limit = 1000;
            $total = count($info);
            foreach ($info as $item) {
                $bi = new BlockInstance($item['in']['block']);
                $configdata = $bi->get('configdata');
                $configdata['showgroupviews'] = $item['in']['showgroupviews'];
                $configdata['showsharedviews'] = $item['in']['showsharedviews'];
                $bi->set('configdata', $configdata);
                $bi->commit();
                foreach ($item['out'] as $old) {
                    $bi = new BlockInstance($old);
                    $bi->delete();
                }
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
    }
    if ($oldversion < 2014121200) {
        log_debug('Remove layout preview thumbs directory');
        require_once 'file.php';
        $layoutdir = get_config('dataroot') . 'images/layoutpreviewthumbs';
        if (file_exists($layoutdir)) {
            rmdirr($layoutdir);
        }
    }
    if ($oldversion < 2015013000) {
        log_debug("Add a 'sortorder' column to 'blocktype_installed_category'");
        // Add a sortorder column to blocktype_installed_category
        $table = new XMLDBTable('blocktype_installed_category');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 100000, 'category');
        add_field($table, $field);
    }
    if ($oldversion < 2015021000) {
        log_debug('Need to update any dashboard pages to not have skins');
        // and seen as we are updating and selecting from the same table
        // we need to use a temptable for it to work in mysql
        execute_Sql("UPDATE {view} SET skin = NULL WHERE id IN ( SELECT vid FROM (SELECT id AS vid FROM {view} WHERE type = 'dashboard' AND skin IS NOT NULL) AS temptable)");
    }
    if ($oldversion < 2015021900) {
        log_debug('Remove bbcode formatting from existing wall posts');
        require_once get_config('docroot') . '/lib/stringparser_bbcode/lib.php';
        if ($records = get_records_sql_array("SELECT id, text FROM {blocktype_wall_post} WHERE text LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                $r->text = parse_bbcode($r->text);
                update_record('blocktype_wall_post', $r);
            }
        }
    }
    if ($oldversion < 2015030400) {
        log_debug("Update search config settings");
        if (get_config('searchusernames') === 1) {
            set_config('nousernames', 0);
        } else {
            set_config('nousernames', 1);
        }
        delete_records('config', 'field', 'searchusernames');
    }
    if ($oldversion < 2015032600) {
        log_debug("Update block categories for plugins");
        if ($blocktypes = plugins_installed('blocktype', true)) {
            foreach ($blocktypes as $bt) {
                install_blocktype_categories_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
            }
        }
    }
    if ($oldversion < 2015033000) {
        log_debug("Updating TinyMCE emoticon locations in mahara database");
        // Seeing as tinymce has moved the location of the emoticons
        // we need to fix up a few places where users could have added emoticons.
        // $replacements is key = table, value = column
        $replacements = array('view' => 'description', 'artefact' => 'title', 'artefact' => 'description', 'group' => 'description', 'interaction_forum_post' => 'body', 'notification_internal_activity' => 'message', 'blocktype_wall_post' => 'text', 'site_content' => 'content');
        foreach ($replacements as $key => $value) {
            execute_sql("UPDATE {" . $key . "} SET " . $value . " = REPLACE(" . $value . ", '/emotions/img', '/emoticons/img') WHERE " . $value . " LIKE '%/emotions/img%'");
        }
        // we need to handle block_instance configdata in a special way
        if ($results = get_records_sql_array("SELECT id FROM {block_instance} WHERE configdata LIKE '%/emotions/img%'", array())) {
            log_debug("Updating 'block_instance' data for TinyMCE");
            require_once get_config('docroot') . 'blocktype/lib.php';
            $count = 0;
            $limit = 1000;
            $total = count($results);
            foreach ($results as $result) {
                $bi = new BlockInstance($result->id);
                $configdata = $bi->get('configdata');
                foreach ($configdata as $key => $value) {
                    $configdata[$key] = preg_replace('/\\/emotions\\/img/', '/emotions/img', $value);
                }
                $bi->set('configdata', $configdata);
                $bi->commit();
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
    }
    if ($oldversion < 2015041400) {
        log_debug('Force install of annotation and webservices plugins');
        if ($data = check_upgrades('artefact.annotation')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('auth.webservice')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2015042800) {
        log_debug('Clear Dwoo cache of unescaped institution names');
        require_once 'dwoo/dwoo/dwooAutoload.php';
        @unlink(get_config('dataroot') . 'dwoo/compile/default' . get_config('docroot') . 'theme/raw/' . 'templates/view/accesslistrow.tpl.d' . Dwoo_Core::RELEASE_TAG . '.php');
        @unlink(get_config('dataroot') . 'dwoo/compile/default' . get_config('docroot') . 'theme/raw/' . 'templates/admin/users/accesslistitem.tpl.d' . Dwoo_Core::RELEASE_TAG . '.php');
    }
    if ($oldversion < 2015071500) {
        log_debug('Expanding the size of the import_entry_requests.entrycontent column');
        $table = new XMLDBTable('import_entry_requests');
        $field = new XMLDBField('entrycontent');
        $field->setType(XMLDB_TYPE_TEXT);
        $field->setLength('big');
        change_field_precision($table, $field);
    }
    if ($oldversion < 2015072000) {
        // If we are upgrading from a site built before 2014092300 straight to 15.10
        // then the plugin won't exist as an artefact.
        if (table_exists(new XMLDBTable('artefact_multirecipient_userrelation'))) {
            log_debug('Change installation of artefact plugin multirecipentNotification to plugin module.');
            // first, drop the old triggers
            db_drop_trigger('update_unread_insert2', 'artefact_multirecipient_userrelation');
            db_drop_trigger('update_unread_update2', 'artefact_multirecipient_userrelation');
            db_drop_trigger('update_unread_delete2', 'artefact_multirecipient_userrelation');
            // rename tables artefact_multirecipientnotifiaction_notification and
            // Table: artefact_multirecipient_userrelation to module-prefix
            execute_sql("ALTER TABLE {artefact_multirecipient_notification} RENAME TO {module_multirecipient_notification}");
            execute_sql("ALTER TABLE {artefact_multirecipient_userrelation} RENAME TO {module_multirecipient_userrelation}");
            if (is_postgres()) {
                // Rename seq artefact_multirecipientnotifiaction_notification_id_seq and
                // artefact_multirecipient_userrelation_id_seq
                execute_sql("ALTER SEQUENCE {artefact_multirecipient_notification_id_seq} RENAME TO {module_multirecipient_notification_id_seq}");
                execute_sql("ALTER SEQUENCE {artefact_multirecipient_userrelation_id_seq} RENAME TO {module_multirecipient_userrelation_id_seq}");
            }
            //move event_subscrition entries for artefact plugin
            //multirecipientnotification to table module_event_subscription
            $subscriptions = get_records_array('artefact_event_subscription', 'plugin', 'multirecipientnotification');
            delete_records('artefact_event_subscription', 'plugin', 'multirecipientnotification');
            delete_records('artefact_installed_type', 'plugin', 'multirecipientnotification');
            $installrecord = get_record('artefact_installed', 'name', 'multirecipientnotification');
            if (is_object($installrecord)) {
                insert_record('module_installed', $installrecord);
                delete_records('artefact_installed', 'name', 'multirecipientnotification');
            }
            if (is_array($subscriptions)) {
                foreach ($subscriptions as $subscription) {
                    insert_record('module_event_subscription', $subscription, 'id');
                }
            }
            // recreate trigger
            safe_require('module', 'multirecipientnotification');
            PluginModuleMultirecipientnotification::postinst(0);
        }
    }
    if ($oldversion < 2015081000) {
        log_debug('Add user_login_data table to record when a user logs in');
        $table = new XMLDBTable('usr_login_data');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrloginfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
        // Insert info about current users's logins
        $results = get_records_sql_array("SELECT id,lastlogin FROM {usr} WHERE deleted = 0 AND lastlogin IS NOT NULL");
        $count = 0;
        $limit = 1000;
        $total = count($results);
        foreach ($results as $result) {
            insert_record('usr_login_data', (object) array('usr' => $result->id, 'ctime' => $result->lastlogin));
            $count++;
            if ($count % $limit == 0 || $count == $total) {
                log_debug("{$count}/{$total}");
                set_time_limit(30);
            }
        }
    }
    if ($oldversion < 2015081700) {
        // In 15.10, we changed the registration site policy.
        // We need to remind the site admins to register the site again with the new policy.
        log_debug('Remind the site admins to register the site again with the new policy');
        if (get_config('new_registration_policy') != -1) {
            set_config('new_registration_policy', true);
        }
        if (get_config('registration_sendweeklyupdates')) {
            set_config('registration_sendweeklyupdates', false);
        }
    }
    if ($oldversion < 2015082500) {
        // Add a site default portfolio page template
        log_debug('Add a site default portfolio page template');
        require_once 'view.php';
        install_system_portfolio_view();
    }
    if ($oldversion < 2015091700) {
        log_debug('Update cached customizable theme CSS');
        $styles = get_records_array('institution', 'theme', 'custom', 'id', 'displayname, style');
        if ($styles) {
            foreach ($styles as $newinstitution) {
                $styleid = $newinstitution->style;
                $properties = array();
                $record = (object) array('style' => $styleid);
                $proprecs = get_records_array('style_property', 'style', $styleid, 'field', 'field, value');
                foreach ($proprecs as $p) {
                    $properties[$p->field] = $p->value;
                }
                // Update the css
                $smarty = smarty_core();
                $smarty->assign('data', $properties);
                set_field('style', 'css', $smarty->fetch('customcss.tpl'), 'id', $styleid);
            }
        }
    }
    return $status;
}
Ejemplo n.º 25
0
 /**
  * Sync all meta course links.
  *
  * @param progress_trace $trace
  * @param int $courseid one course, empty mean all
  * @return int 0 means ok, 1 means error, 2 means plugin disabled
  */
 public function sync(progress_trace $trace, $courseid = null)
 {
     global $DB;
     if (!enrol_is_enabled('self')) {
         $trace->finished();
         return 2;
     }
     // Unfortunately this may take a long time, execution can be interrupted safely here.
     core_php_time_limit::raise();
     raise_memory_limit(MEMORY_HUGE);
     $trace->output('Verifying self-enrolments...');
     $params = array('now' => time(), 'useractive' => ENROL_USER_ACTIVE, 'courselevel' => CONTEXT_COURSE);
     $coursesql = "";
     if ($courseid) {
         $coursesql = "AND e.courseid = :courseid";
         $params['courseid'] = $courseid;
     }
     // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
     //       and that user accessed course at least once too (=== user_lastaccess record exists).
     // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
     $sql = "SELECT e.*, ue.userid\n                  FROM {user_enrolments} ue\n                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)\n                  JOIN {user} u ON u.id = ue.userid\n                 WHERE :now - u.lastaccess > e.customint2\n                       {$coursesql}";
     $rs = $DB->get_recordset_sql($sql, $params);
     foreach ($rs as $instance) {
         $userid = $instance->userid;
         unset($instance->userid);
         $this->unenrol_user($instance, $userid);
         $days = $instance->customint2 / 60 * 60 * 24;
         $trace->output("unenrolling user {$userid} from course {$instance->courseid} as they have did not log in for at least {$days} days", 1);
     }
     $rs->close();
     // Now unenrol from course user did not visit for a long time.
     $sql = "SELECT e.*, ue.userid\n                  FROM {user_enrolments} ue\n                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)\n                  JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)\n                 WHERE :now - ul.timeaccess > e.customint2\n                       {$coursesql}";
     $rs = $DB->get_recordset_sql($sql, $params);
     foreach ($rs as $instance) {
         $userid = $instance->userid;
         unset($instance->userid);
         $this->unenrol_user($instance, $userid);
         $days = $instance->customint2 / 60 * 60 * 24;
         $trace->output("unenrolling user {$userid} from course {$instance->courseid} as they have did not access course for at least {$days} days", 1);
     }
     $rs->close();
     $trace->output('...user self-enrolment updates finished.');
     $trace->finished();
     $this->process_expirations($trace, $courseid);
     return 0;
 }
Ejemplo n.º 26
0
/**
 * Sync all meta course links.
 *
 * @param int $courseid one course, empty mean all
 * @param bool $verbose verbose CLI output
 * @return int 0 means ok, 1 means error, 2 means plugin disabled
 */
function enrol_meta_sync($courseid = NULL, $verbose = false)
{
    global $CFG, $DB;
    // purge all roles if meta sync disabled, those can be recreated later here in cron
    if (!enrol_is_enabled('meta')) {
        if ($verbose) {
            mtrace('Meta sync plugin is disabled, unassigning all plugin roles and stopping.');
        }
        role_unassign_all(array('component' => 'enrol_meta'));
        return 2;
    }
    // unfortunately this may take a long time, execution can be interrupted safely
    @set_time_limit(0);
    raise_memory_limit(MEMORY_HUGE);
    if ($verbose) {
        mtrace('Starting user enrolment synchronisation...');
    }
    $instances = array();
    // cache instances
    $meta = enrol_get_plugin('meta');
    $unenrolaction = $meta->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
    $skiproles = $meta->get_config('nosyncroleids', '');
    $skiproles = empty($skiproles) ? array() : explode(',', $skiproles);
    $syncall = $meta->get_config('syncall', 1);
    $allroles = get_all_roles();
    // iterate through all not enrolled yet users
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e');
    $params['courseid'] = $courseid;
    $sql = "SELECT pue.userid, e.id AS enrolid, pue.status\n              FROM {user_enrolments} pue\n              JOIN {enrol} pe ON (pe.id = pue.enrolid AND pe.enrol <> 'meta' AND pe.enrol {$enabled})\n              JOIN {enrol} e ON (e.customint1 = pe.courseid AND e.enrol = 'meta' {$onecourse})\n              JOIN {user} u ON (u.id = pue.userid AND u.deleted = 0)\n         LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = pue.userid)\n             WHERE ue.id IS NULL";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
        }
        $instance = $instances[$ue->enrolid];
        if (!$syncall) {
            // this may be slow if very many users are ignored in sync
            $parentcontext = context_course::instance($instance->customint1);
            list($ignoreroles, $params) = $DB->get_in_or_equal($skiproles, SQL_PARAMS_NAMED, 'ri', false, -1);
            $params['contextid'] = $parentcontext->id;
            $params['userid'] = $ue->userid;
            $select = "contextid = :contextid AND userid = :userid AND component <> 'enrol_meta' AND roleid {$ignoreroles}";
            if (!$DB->record_exists_select('role_assignments', $select, $params)) {
                // bad luck, this user does not have any role we want in parent course
                if ($verbose) {
                    mtrace("  skipping enrolling: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
                continue;
            }
        }
        $meta->enrol_user($instance, $ue->userid, $ue->status);
        if ($verbose) {
            mtrace("  enrolling: {$ue->userid} ==> {$instance->courseid}");
        }
    }
    $rs->close();
    // unenrol as necessary - ignore enabled flag, we want to get rid of existing enrols in any case
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e');
    $params['courseid'] = $courseid;
    $sql = "SELECT ue.*\n              FROM {user_enrolments} ue\n              JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n         LEFT JOIN ({user_enrolments} xpue\n                      JOIN {enrol} xpe ON (xpe.id = xpue.enrolid AND xpe.enrol <> 'meta' AND xpe.enrol {$enabled})\n                   ) ON (xpe.courseid = e.customint1 AND xpue.userid = ue.userid)\n             WHERE xpue.userid IS NULL";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
        }
        $instance = $instances[$ue->enrolid];
        if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
            $meta->unenrol_user($instance, $ue->userid);
            if ($verbose) {
                mtrace("  unenrolling: {$ue->userid} ==> {$instance->courseid}");
            }
            continue;
        } else {
            // ENROL_EXT_REMOVED_SUSPENDNOROLES
            // just disable and ignore any changes
            if ($ue->status != ENROL_USER_SUSPENDED) {
                $meta->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
                $context = context_course::instance($instance->courseid);
                role_unassign_all(array('userid' => $ue->userid, 'contextid' => $context->id, 'component' => 'enrol_meta'));
                if ($verbose) {
                    mtrace("  suspending and removing all roles: {$ue->userid} ==> {$instance->courseid}");
                }
            }
            continue;
        }
    }
    $rs->close();
    // update status - meta enrols + start and end dates are ignored, sorry
    // note the trick here is that the active enrolment and instance constants have value 0
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e');
    $params['courseid'] = $courseid;
    $sql = "SELECT ue.userid, ue.enrolid, pue.pstatus\n              FROM {user_enrolments} ue\n              JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n              JOIN (SELECT xpue.userid, xpe.courseid, MIN(xpue.status + xpe.status) AS pstatus\n                      FROM {user_enrolments} xpue\n                      JOIN {enrol} xpe ON (xpe.id = xpue.enrolid AND xpe.enrol <> 'meta' AND xpe.enrol {$enabled})\n                  GROUP BY xpue.userid, xpe.courseid\n                   ) pue ON (pue.courseid = e.customint1 AND pue.userid = ue.userid)\n             WHERE (pue.pstatus = 0 AND ue.status > 0) OR (pue.pstatus > 0 and ue.status = 0)";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
        }
        $instance = $instances[$ue->enrolid];
        $ue->pstatus = $ue->pstatus == ENROL_USER_ACTIVE ? ENROL_USER_ACTIVE : ENROL_USER_SUSPENDED;
        if ($ue->pstatus == ENROL_USER_ACTIVE and !$syncall and $unenrolaction != ENROL_EXT_REMOVED_UNENROL) {
            // this may be slow if very many users are ignored in sync
            $parentcontext = context_course::instance($instance->customint1);
            list($ignoreroles, $params) = $DB->get_in_or_equal($skiproles, SQL_PARAMS_NAMED, 'ri', false, -1);
            $params['contextid'] = $parentcontext->id;
            $params['userid'] = $ue->userid;
            $select = "contextid = :contextid AND userid = :userid AND component <> 'enrol_meta' AND roleid {$ignoreroles}";
            if (!$DB->record_exists_select('role_assignments', $select, $params)) {
                // bad luck, this user does not have any role we want in parent course
                if ($verbose) {
                    mtrace("  skipping unsuspending: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
                continue;
            }
        }
        $meta->update_user_enrol($instance, $ue->userid, $ue->pstatus);
        if ($verbose) {
            if ($ue->pstatus == ENROL_USER_ACTIVE) {
                mtrace("  unsuspending: {$ue->userid} ==> {$instance->courseid}");
            } else {
                mtrace("  suspending: {$ue->userid} ==> {$instance->courseid}");
            }
        }
    }
    $rs->close();
    // now assign all necessary roles
    $enabled = explode(',', $CFG->enrol_plugins_enabled);
    foreach ($enabled as $k => $v) {
        if ($v === 'meta') {
            continue;
            // no meta sync of meta roles
        }
        $enabled[$k] = 'enrol_' . $v;
    }
    $enabled[] = '';
    // manual assignments are replicated too
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal($enabled, SQL_PARAMS_NAMED, 'e');
    $params['coursecontext'] = CONTEXT_COURSE;
    $params['courseid'] = $courseid;
    $params['activeuser'] = ENROL_USER_ACTIVE;
    $params['enabledinstance'] = ENROL_INSTANCE_ENABLED;
    $sql = "SELECT DISTINCT pra.roleid, pra.userid, c.id AS contextid, e.id AS enrolid, e.courseid\n              FROM {role_assignments} pra\n              JOIN {user} u ON (u.id = pra.userid AND u.deleted = 0)\n              JOIN {context} pc ON (pc.id = pra.contextid AND pc.contextlevel = :coursecontext AND pra.component {$enabled})\n              JOIN {enrol} e ON (e.customint1 = pc.instanceid AND e.enrol = 'meta' {$onecourse} AND e.status = :enabledinstance)\n              JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = u.id AND ue.status = :activeuser)\n              JOIN {context} c ON (c.contextlevel = pc.contextlevel AND c.instanceid = e.courseid)\n         LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = pra.userid AND ra.roleid = pra.roleid AND ra.itemid = e.id AND ra.component = 'enrol_meta')\n             WHERE ra.id IS NULL";
    if ($ignored = $meta->get_config('nosyncroleids')) {
        list($notignored, $xparams) = $DB->get_in_or_equal(explode(',', $ignored), SQL_PARAMS_NAMED, 'ig', false);
        $params = array_merge($params, $xparams);
        $sql = "{$sql} AND pra.roleid {$notignored}";
    }
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ra) {
        role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_meta', $ra->enrolid);
        if ($verbose) {
            mtrace("  assigning role: {$ra->userid} ==> {$ra->courseid} as " . $allroles[$ra->roleid]->shortname);
        }
    }
    $rs->close();
    // remove unwanted roles - include ignored roles and disabled plugins too
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    $params = array();
    $params['coursecontext'] = CONTEXT_COURSE;
    $params['courseid'] = $courseid;
    $params['activeuser'] = ENROL_USER_ACTIVE;
    $params['enabledinstance'] = ENROL_INSTANCE_ENABLED;
    if ($ignored = $meta->get_config('nosyncroleids')) {
        list($notignored, $xparams) = $DB->get_in_or_equal(explode(',', $ignored), SQL_PARAMS_NAMED, 'ig', false);
        $params = array_merge($params, $xparams);
        $notignored = "AND pra.roleid {$notignored}";
    } else {
        $notignored = "";
    }
    $sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid\n              FROM {role_assignments} ra\n              JOIN {enrol} e ON (e.id = ra.itemid AND ra.component = 'enrol_meta' AND e.enrol = 'meta' {$onecourse})\n              JOIN {context} pc ON (pc.instanceid = e.customint1 AND pc.contextlevel = :coursecontext)\n         LEFT JOIN {role_assignments} pra ON (pra.contextid = pc.id AND pra.userid = ra.userid AND pra.roleid = ra.roleid AND pra.component <> 'enrol_meta' {$notignored})\n         LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = ra.userid AND ue.status = :activeuser)\n             WHERE pra.id IS NULL OR ue.id IS NULL OR e.status <> :enabledinstance";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ra) {
        role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_meta', $ra->itemid);
        if ($verbose) {
            mtrace("  unassigning role: {$ra->userid} ==> {$ra->courseid} as " . $allroles[$ra->roleid]->shortname);
        }
    }
    $rs->close();
    // kick out or suspend users without synced roles if syncall disabled
    if (!$syncall) {
        if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
            $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
            $params = array();
            $params['coursecontext'] = CONTEXT_COURSE;
            $params['courseid'] = $courseid;
            $sql = "SELECT ue.userid, ue.enrolid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n                      JOIN {context} c ON (e.courseid = c.instanceid AND c.contextlevel = :coursecontext)\n                 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.itemid = e.id AND ra.userid = ue.userid)\n                     WHERE ra.id IS NULL";
            $ues = $DB->get_recordset_sql($sql, $params);
            foreach ($ues as $ue) {
                if (!isset($instances[$ue->enrolid])) {
                    $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
                }
                $instance = $instances[$ue->enrolid];
                $meta->unenrol_user($instance, $ue->userid);
                if ($verbose) {
                    mtrace("  unenrolling: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
            }
            $ues->close();
        } else {
            // just suspend the users
            $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
            $params = array();
            $params['coursecontext'] = CONTEXT_COURSE;
            $params['courseid'] = $courseid;
            $params['active'] = ENROL_USER_ACTIVE;
            $sql = "SELECT ue.userid, ue.enrolid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n                      JOIN {context} c ON (e.courseid = c.instanceid AND c.contextlevel = :coursecontext)\n                 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.itemid = e.id AND ra.userid = ue.userid)\n                     WHERE ra.id IS NULL AND ue.status = :active";
            $ues = $DB->get_recordset_sql($sql, $params);
            foreach ($ues as $ue) {
                if (!isset($instances[$ue->enrolid])) {
                    $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
                }
                $instance = $instances[$ue->enrolid];
                $meta->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
                if ($verbose) {
                    mtrace("  suspending: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
            }
            $ues->close();
        }
    }
    if ($verbose) {
        mtrace('...user enrolment synchronisation finished.');
    }
    return 0;
}
Ejemplo n.º 27
0
 * @package    mahara
 * @subpackage admin
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
 *
 */
define('INTERNAL', 1);
define('INSTITUTIONALADMIN', 1);
define('MENUITEM', 'configusers/uploadcsv');
require dirname(dirname(dirname(__FILE__))) . '/init.php';
define('TITLE', get_string('uploadcsv', 'admin'));
require_once 'pieforms/pieform.php';
require_once 'institution.php';
safe_require('artefact', 'internal');
raise_memory_limit("512M");
// Turn on autodetecting of line endings, so mac newlines (\r) will work
ini_set('auto_detect_line_endings', 1);
$FORMAT = array();
$ALLOWEDKEYS = array('username', 'password', 'email', 'firstname', 'lastname', 'preferredname', 'studentid', 'introduction', 'officialwebsite', 'personalwebsite', 'blogaddress', 'address', 'town', 'city', 'country', 'homenumber', 'businessnumber', 'mobilenumber', 'faxnumber', 'icqnumber', 'msnnumber', 'aimscreenname', 'yahoochat', 'skypeusername', 'jabberusername', 'occupation', 'industry', 'authinstance');
$CSVERRORS = array();
if ($USER->get('admin')) {
    $authinstances = auth_get_auth_instances();
} else {
    $admininstitutions = $USER->get('admininstitutions');
    $authinstances = auth_get_auth_instances_for_institutions($admininstitutions);
    if (empty($authinstances)) {
        $SESSION->add_info_msg(get_string('configureauthplugin', 'admin'));
        redirect(get_config('wwwroot') . 'admin/users/institutions.php?i=' . key($admininstitutions) . '&amp;edit=1');
    }
}
Ejemplo n.º 28
0
 /**
  * Performs a full sync with external database.
  *
  * First it creates new courses if necessary, then
  * enrols and unenrols users.
  *
  * @param bool $verbose
  * @return int 0 means success, 1 db connect failure, 4 db read failure
  */
 public function sync_courses($verbose = false)
 {
     global $CFG, $DB;
     // Make sure we sync either enrolments or courses.
     if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('newcoursetable') or !$this->get_config('newcoursefullname') or !$this->get_config('newcourseshortname')) {
         if ($verbose) {
             mtrace('Course synchronisation skipped.');
         }
         return 0;
     }
     if ($verbose) {
         mtrace('Starting course synchronisation...');
     }
     // We may need a lot of memory here.
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     if (!($extdb = $this->db_init())) {
         mtrace('Error while communicating with external enrolment database');
         return 1;
     }
     $table = $this->get_config('newcoursetable');
     $fullname = trim($this->get_config('newcoursefullname'));
     $shortname = trim($this->get_config('newcourseshortname'));
     $idnumber = trim($this->get_config('newcourseidnumber'));
     $category = trim($this->get_config('newcoursecategory'));
     // Lowercased versions - necessary because we normalise the resultset with array_change_key_case().
     $fullname_l = strtolower($fullname);
     $shortname_l = strtolower($shortname);
     $idnumber_l = strtolower($idnumber);
     $category_l = strtolower($category);
     $localcategoryfield = $this->get_config('localcategoryfield', 'id');
     $defaultcategory = $this->get_config('defaultcategory');
     if (!$DB->record_exists('course_categories', array('id' => $defaultcategory))) {
         if ($verbose) {
             mtrace("  default course category does not exist!");
         }
         $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
         $first = reset($categories);
         $defaultcategory = $first->id;
     }
     $sqlfields = array($fullname, $shortname);
     if ($category) {
         $sqlfields[] = $category;
     }
     if ($idnumber) {
         $sqlfields[] = $idnumber;
     }
     $sql = $this->db_get_sql($table, array(), $sqlfields, true);
     $createcourses = array();
     if ($rs = $extdb->Execute($sql)) {
         if (!$rs->EOF) {
             while ($fields = $rs->FetchRow()) {
                 $fields = array_change_key_case($fields, CASE_LOWER);
                 $fields = $this->db_decode($fields);
                 if (empty($fields[$shortname_l]) or empty($fields[$fullname_l])) {
                     if ($verbose) {
                         mtrace('  error: invalid external course record, shortname and fullname are mandatory: ' . json_encode($fields));
                         // Hopefully every geek can read JS, right?
                     }
                     continue;
                 }
                 if ($DB->record_exists('course', array('shortname' => $fields[$shortname_l]))) {
                     // Already exists, skip.
                     continue;
                 }
                 // Allow empty idnumber but not duplicates.
                 if ($idnumber and $fields[$idnumber_l] !== '' and $fields[$idnumber_l] !== null and $DB->record_exists('course', array('idnumber' => $fields[$idnumber_l]))) {
                     if ($verbose) {
                         mtrace('  error: duplicate idnumber, can not create course: ' . $fields[$shortname_l] . ' [' . $fields[$idnumber_l] . ']');
                     }
                     continue;
                 }
                 $course = new stdClass();
                 $course->fullname = $fields[$fullname_l];
                 $course->shortname = $fields[$shortname_l];
                 $course->idnumber = $idnumber ? $fields[$idnumber_l] : '';
                 if ($category) {
                     if (empty($fields[$category_l])) {
                         // Empty category means use default.
                         $course->category = $defaultcategory;
                     } else {
                         if ($coursecategory = $DB->get_record('course_categories', array($localcategoryfield => $fields[$category_l]), 'id')) {
                             // Yay, correctly specified category!
                             $course->category = $coursecategory->id;
                             unset($coursecategory);
                         } else {
                             // Bad luck, better not continue because unwanted ppl might get access to course in different category.
                             if ($verbose) {
                                 mtrace('  error: invalid category ' . $localcategoryfield . ', can not create course: ' . $fields[$shortname_l]);
                             }
                             continue;
                         }
                     }
                 } else {
                     $course->category = $defaultcategory;
                 }
                 $createcourses[] = $course;
             }
         }
         $rs->Close();
     } else {
         mtrace('Error reading data from the external course table');
         $extdb->Close();
         return 4;
     }
     if ($createcourses) {
         require_once "{$CFG->dirroot}/course/lib.php";
         $templatecourse = $this->get_config('templatecourse');
         $template = false;
         if ($templatecourse) {
             if ($template = $DB->get_record('course', array('shortname' => $templatecourse))) {
                 $template = fullclone(course_get_format($template)->get_course());
                 unset($template->id);
                 unset($template->fullname);
                 unset($template->shortname);
                 unset($template->idnumber);
             } else {
                 if ($verbose) {
                     mtrace("  can not find template for new course!");
                 }
             }
         }
         if (!$template) {
             $courseconfig = get_config('moodlecourse');
             $template = new stdClass();
             $template->summary = '';
             $template->summaryformat = FORMAT_HTML;
             $template->format = $courseconfig->format;
             $template->newsitems = $courseconfig->newsitems;
             $template->showgrades = $courseconfig->showgrades;
             $template->showreports = $courseconfig->showreports;
             $template->maxbytes = $courseconfig->maxbytes;
             $template->groupmode = $courseconfig->groupmode;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
             $template->visible = $courseconfig->visible;
             $template->lang = $courseconfig->lang;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
         }
         foreach ($createcourses as $fields) {
             $newcourse = clone $template;
             $newcourse->fullname = $fields->fullname;
             $newcourse->shortname = $fields->shortname;
             $newcourse->idnumber = $fields->idnumber;
             $newcourse->category = $fields->category;
             // Detect duplicate data once again, above we can not find duplicates
             // in external data using DB collation rules...
             if ($DB->record_exists('course', array('shortname' => $newcourse->shortname))) {
                 if ($verbose) {
                     mtrace("  can not insert new course, duplicate shortname detected: " . $newcourse->shortname);
                 }
                 continue;
             } else {
                 if (!empty($newcourse->idnumber) and $DB->record_exists('course', array('idnumber' => $newcourse->idnumber))) {
                     if ($verbose) {
                         mtrace("  can not insert new course, duplicate idnumber detected: " . $newcourse->idnumber);
                     }
                     continue;
                 }
             }
             $c = create_course($newcourse);
             if ($verbose) {
                 mtrace("  creating course: {$c->id}, {$c->fullname}, {$c->shortname}, {$c->idnumber}, {$c->category}");
             }
         }
         unset($createcourses);
         unset($template);
     }
     // Close db connection.
     $extdb->Close();
     if ($verbose) {
         mtrace('...course synchronisation finished.');
     }
     return 0;
 }
Ejemplo n.º 29
0
 public function display($quiz, $cm, $course)
 {
     global $CFG, $COURSE, $DB, $OUTPUT;
     $this->context = get_context_instance(CONTEXT_MODULE, $cm->id);
     $download = optional_param('download', '', PARAM_ALPHA);
     list($currentgroup, $students, $groupstudents, $allowed) = $this->load_relevant_students($cm);
     $pageoptions = array();
     $pageoptions['id'] = $cm->id;
     $pageoptions['mode'] = 'overview';
     $reporturl = new moodle_url('/mod/quiz/report.php', $pageoptions);
     $qmsubselect = quiz_report_qm_filter_select($quiz);
     $mform = new mod_quiz_report_overview_settings($reporturl, array('qmsubselect' => $qmsubselect, 'quiz' => $quiz, 'currentgroup' => $currentgroup, 'context' => $this->context));
     if ($fromform = $mform->get_data()) {
         $regradeall = false;
         $regradealldry = false;
         $regradealldrydo = false;
         $attemptsmode = $fromform->attemptsmode;
         if ($qmsubselect) {
             $qmfilter = $fromform->qmfilter;
         } else {
             $qmfilter = 0;
         }
         $regradefilter = !empty($fromform->regradefilter);
         set_user_preference('quiz_report_overview_detailedmarks', $fromform->detailedmarks);
         set_user_preference('quiz_report_pagesize', $fromform->pagesize);
         $detailedmarks = $fromform->detailedmarks;
         $pagesize = $fromform->pagesize;
     } else {
         $regradeall = optional_param('regradeall', 0, PARAM_BOOL);
         $regradealldry = optional_param('regradealldry', 0, PARAM_BOOL);
         $regradealldrydo = optional_param('regradealldrydo', 0, PARAM_BOOL);
         $attemptsmode = optional_param('attemptsmode', null, PARAM_INT);
         if ($qmsubselect) {
             $qmfilter = optional_param('qmfilter', 0, PARAM_INT);
         } else {
             $qmfilter = 0;
         }
         $regradefilter = optional_param('regradefilter', 0, PARAM_INT);
         $detailedmarks = get_user_preferences('quiz_report_overview_detailedmarks', 1);
         $pagesize = get_user_preferences('quiz_report_pagesize', 0);
     }
     $this->validate_common_options($attemptsmode, $pagesize, $course, $currentgroup);
     $displayoptions = array();
     $displayoptions['attemptsmode'] = $attemptsmode;
     $displayoptions['qmfilter'] = $qmfilter;
     $displayoptions['regradefilter'] = $regradefilter;
     $mform->set_data($displayoptions + array('detailedmarks' => $detailedmarks, 'pagesize' => $pagesize));
     if (!$this->should_show_grades($quiz)) {
         $detailedmarks = 0;
     }
     // We only want to show the checkbox to delete attempts
     // if the user has permissions and if the report mode is showing attempts.
     $candelete = has_capability('mod/quiz:deleteattempts', $this->context) && $attemptsmode != QUIZ_REPORT_ATTEMPTS_STUDENTS_WITH_NO;
     if ($attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL) {
         // This option is only available to users who can access all groups in
         // groups mode, so setting allowed to empty (which means all quiz attempts
         // are accessible, is not a security porblem.
         $allowed = array();
     }
     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
     $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
     $displaycoursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id);
     $displaycourseshortname = format_string($COURSE->shortname, true, array('context' => $displaycoursecontext));
     // Load the required questions.
     $questions = quiz_report_get_significant_questions($quiz);
     $table = new quiz_report_overview_table($quiz, $this->context, $qmsubselect, $groupstudents, $students, $detailedmarks, $questions, $candelete, $reporturl, $displayoptions);
     $filename = quiz_report_download_filename(get_string('overviewfilename', 'quiz_overview'), $courseshortname, $quiz->name);
     $table->is_downloading($download, $filename, $displaycourseshortname . ' ' . format_string($quiz->name, true));
     if ($table->is_downloading()) {
         raise_memory_limit(MEMORY_EXTRA);
     }
     // Process actions.
     if (empty($currentgroup) || $groupstudents) {
         if (optional_param('delete', 0, PARAM_BOOL) && confirm_sesskey()) {
             if ($attemptids = optional_param('attemptid', array(), PARAM_INT)) {
                 require_capability('mod/quiz:deleteattempts', $this->context);
                 $this->delete_selected_attempts($quiz, $cm, $attemptids, $allowed);
                 redirect($reporturl->out(false, $displayoptions));
             }
         } else {
             if (optional_param('regrade', 0, PARAM_BOOL) && confirm_sesskey()) {
                 if ($attemptids = optional_param('attemptid', array(), PARAM_INT)) {
                     require_capability('mod/quiz:regrade', $this->context);
                     $this->regrade_attempts($quiz, false, $groupstudents, $attemptids);
                     redirect($reporturl->out(false, $displayoptions));
                 }
             }
         }
     }
     if ($regradeall && confirm_sesskey()) {
         require_capability('mod/quiz:regrade', $this->context);
         $this->regrade_attempts($quiz, false, $groupstudents);
         redirect($reporturl->out(false, $displayoptions), '', 5);
     } else {
         if ($regradealldry && confirm_sesskey()) {
             require_capability('mod/quiz:regrade', $this->context);
             $this->regrade_attempts($quiz, true, $groupstudents);
             redirect($reporturl->out(false, $displayoptions), '', 5);
         } else {
             if ($regradealldrydo && confirm_sesskey()) {
                 require_capability('mod/quiz:regrade', $this->context);
                 $this->regrade_attempts_needing_it($quiz, $groupstudents);
                 redirect($reporturl->out(false, $displayoptions), '', 5);
             }
         }
     }
     // Start output.
     if (!$table->is_downloading()) {
         // Only print headers if not asked to download data
         $this->print_header_and_tabs($cm, $course, $quiz, 'overview');
     }
     if ($groupmode = groups_get_activity_groupmode($cm)) {
         // Groups are being used
         if (!$table->is_downloading()) {
             groups_print_activity_menu($cm, $reporturl->out(true, $displayoptions));
         }
     }
     // Print information on the number of existing attempts
     if (!$table->is_downloading()) {
         //do not print notices when downloading
         if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) {
             echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>';
         }
     }
     $hasquestions = quiz_questions_in_quiz($quiz->questions);
     if (!$table->is_downloading()) {
         if (!$hasquestions) {
             echo quiz_no_questions_message($quiz, $cm, $this->context);
         } else {
             if (!$students) {
                 echo $OUTPUT->notification(get_string('nostudentsyet'));
             } else {
                 if ($currentgroup && !$groupstudents) {
                     echo $OUTPUT->notification(get_string('nostudentsingroup'));
                 }
             }
         }
         // Print display options
         $mform->display();
     }
     $hasstudents = $students && (!$currentgroup || $groupstudents);
     if ($hasquestions && ($hasstudents || $attemptsmode == QUIZ_REPORT_ATTEMPTS_ALL)) {
         // Construct the SQL
         $fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid, ';
         if ($qmsubselect) {
             $fields .= "(CASE " . "   WHEN {$qmsubselect} THEN 1" . "   ELSE 0 " . "END) AS gradedattempt, ";
         }
         list($fields, $from, $where, $params) = $this->base_sql($quiz, $qmsubselect, $qmfilter, $attemptsmode, $allowed);
         $table->set_count_sql("SELECT COUNT(1) FROM {$from} WHERE {$where}", $params);
         // Test to see if there are any regraded attempts to be listed.
         $fields .= ", COALESCE((\n                                SELECT MAX(qqr.regraded)\n                                  FROM {quiz_overview_regrades} qqr\n                                 WHERE qqr.questionusageid = quiza.uniqueid\n                          ), -1) AS regraded";
         if ($regradefilter) {
             $where .= " AND COALESCE((\n                                    SELECT MAX(qqr.regraded)\n                                      FROM {quiz_overview_regrades} qqr\n                                     WHERE qqr.questionusageid = quiza.uniqueid\n                                ), -1) <> -1";
         }
         $table->set_sql($fields, $from, $where, $params);
         if (!$table->is_downloading()) {
             // Regrade buttons
             if (has_capability('mod/quiz:regrade', $this->context)) {
                 $regradesneeded = $this->count_question_attempts_needing_regrade($quiz, $groupstudents);
                 if ($currentgroup) {
                     $a = new stdClass();
                     $a->groupname = groups_get_group_name($currentgroup);
                     $a->coursestudents = get_string('participants');
                     $a->countregradeneeded = $regradesneeded;
                     $regradealldrydolabel = get_string('regradealldrydogroup', 'quiz_overview', $a);
                     $regradealldrylabel = get_string('regradealldrygroup', 'quiz_overview', $a);
                     $regradealllabel = get_string('regradeallgroup', 'quiz_overview', $a);
                 } else {
                     $regradealldrydolabel = get_string('regradealldrydo', 'quiz_overview', $regradesneeded);
                     $regradealldrylabel = get_string('regradealldry', 'quiz_overview');
                     $regradealllabel = get_string('regradeall', 'quiz_overview');
                 }
                 $displayurl = new moodle_url($reporturl, $displayoptions + array('sesskey' => sesskey()));
                 echo '<div class="mdl-align">';
                 echo '<form action="' . $displayurl->out_omit_querystring() . '">';
                 echo '<div>';
                 echo html_writer::input_hidden_params($displayurl);
                 echo '<input type="submit" name="regradeall" value="' . $regradealllabel . '"/>';
                 echo '<input type="submit" name="regradealldry" value="' . $regradealldrylabel . '"/>';
                 if ($regradesneeded) {
                     echo '<input type="submit" name="regradealldrydo" value="' . $regradealldrydolabel . '"/>';
                 }
                 echo '</div>';
                 echo '</form>';
                 echo '</div>';
             }
             // Print information on the grading method
             if ($strattempthighlight = quiz_report_highlighting_grading_method($quiz, $qmsubselect, $qmfilter)) {
                 echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>';
             }
         }
         // Define table columns
         $columns = array();
         $headers = array();
         if (!$table->is_downloading() && $candelete) {
             $columns[] = 'checkbox';
             $headers[] = null;
         }
         $this->add_user_columns($table, $columns, $headers);
         $this->add_time_columns($columns, $headers);
         if ($detailedmarks) {
             foreach ($questions as $slot => $question) {
                 // Ignore questions of zero length
                 $columns[] = 'qsgrade' . $slot;
                 $header = get_string('qbrief', 'quiz', $question->number);
                 if (!$table->is_downloading()) {
                     $header .= '<br />';
                 } else {
                     $header .= ' ';
                 }
                 $header .= '/' . quiz_rescale_grade($question->maxmark, $quiz, 'question');
                 $headers[] = $header;
             }
         }
         if (!$table->is_downloading() && has_capability('mod/quiz:regrade', $this->context) && $this->has_regraded_questions($from, $where, $params)) {
             $columns[] = 'regraded';
             $headers[] = get_string('regrade', 'quiz_overview');
         }
         $this->add_grade_columns($quiz, $columns, $headers);
         $this->set_up_table_columns($table, $columns, $headers, $reporturl, $displayoptions, false);
         $table->set_attribute('class', 'generaltable generalbox grades');
         $table->out($pagesize, true);
     }
     if (!$table->is_downloading() && $this->should_show_grades($quiz)) {
         if ($currentgroup && $groupstudents) {
             list($usql, $params) = $DB->get_in_or_equal($groupstudents);
             $params[] = $quiz->id;
             if ($DB->record_exists_select('quiz_grades', "userid {$usql} AND quiz = ?", $params)) {
                 $imageurl = new moodle_url('/mod/quiz/report/overview/overviewgraph.php', array('id' => $quiz->id, 'groupid' => $currentgroup));
                 $graphname = get_string('overviewreportgraphgroup', 'quiz_overview', groups_get_group_name($currentgroup));
                 echo $OUTPUT->heading($graphname);
                 echo html_writer::tag('div', html_writer::empty_tag('img', array('src' => $imageurl, 'alt' => $graphname)), array('class' => 'graph'));
             }
         }
         if ($DB->record_exists('quiz_grades', array('quiz' => $quiz->id))) {
             $graphname = get_string('overviewreportgraph', 'quiz_overview');
             $imageurl = new moodle_url('/mod/quiz/report/overview/overviewgraph.php', array('id' => $quiz->id));
             echo $OUTPUT->heading($graphname);
             echo html_writer::tag('div', html_writer::empty_tag('img', array('src' => $imageurl, 'alt' => $graphname)), array('class' => 'graph'));
         }
     }
     return true;
 }
Ejemplo n.º 30
0
} else {
    $navlinks = array();
    $navlinks[] = array('name' => $course->shortname, 'link' => "{$CFG->wwwroot}/course/view.php?id={$course->id}", 'type' => 'misc');
    $navlinks[] = array('name' => $strcourserestore, 'link' => null, 'type' => 'misc');
    $navigation = build_navigation($navlinks);
    print_header("{$course->shortname}: {$strcourserestore}", $course->fullname, $navigation);
}
//Print form
echo $OUTPUT->heading("{$strcourserestore}" . (empty($to) ? ': ' . basename($file) : ''));
echo $OUTPUT->box_start();
//Adjust some php variables to the execution of this script
@ini_set("max_execution_time", "3000");
if (empty($CFG->extramemorylimit)) {
    raise_memory_limit('128M');
} else {
    raise_memory_limit($CFG->extramemorylimit);
}
//Call the form, depending the step we are
if (!$launch) {
    include_once "restore_precheck.html";
} else {
    if ($launch == "form") {
        if (!empty($SESSION->restore->importing)) {
            // set up all the config stuff and skip asking the user about it.
            restore_setup_for_check($SESSION->restore, $backup_unique_code);
            include_once "restore_execute.html";
        } else {
            include_once "restore_form.html";
        }
    } else {
        if ($launch == "check") {