upgrade.php 228 KB
Newer Older
1 2 3 4
<?php
/**
 *
 * @package    mahara
Penny Leach's avatar
Penny Leach committed
5
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9 10 11 12 13 14
 *
 */

defined('INTERNAL') || die();

function xmldb_core_upgrade($oldversion=0) {
15
    global $SESSION;
16
    raise_time_limit(120);
17
    raise_memory_limit('256M');
18 19 20

    $status = true;

21
    if ($oldversion < 2009022700) {
22 23
        // 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')) {
24 25 26 27 28 29 30 31 32 33 34 35 36 37
            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))'
                );
            }
38 39 40 41 42
            execute_sql('UPDATE {block_instance} SET "order" = 1 WHERE "order" = 0');
            execute_sql('UPDATE {block_instance} SET "order" = -1 * ("order" - 1) WHERE "order" < 0');
        }
    }

43 44 45 46
    if ($oldversion < 2009031000) {
        reload_html_filters();
    }

47 48 49 50 51 52 53 54 55 56
    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);
57

58 59 60
        $suspended = new XMLDBField('suspended');
        $suspended->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $suspended);
61 62

        // Insert a cron job to check for soon expiring and expired institutions
63 64 65 66 67 68 69 70 71 72
        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);
        }
73 74
    }

75 76 77 78 79 80 81 82 83 84
    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("
85 86
            ALTER TABLE {artefact_attachment} RENAME blogpost TO artefact;
            ALTER TABLE {artefact_attachment} RENAME file TO attachment;
87 88 89 90 91 92 93 94 95 96 97 98 99

            ALTER INDEX {arteblogblogfile_blofil_pk} RENAME TO {arteatta_artatt_pk};
            ALTER INDEX {arteblogblogfile_blo_ix} RENAME TO {arteatta_art_ix};
            ALTER INDEX {arteblogblogfile_fil_ix} RENAME TO {arteatta_att_ix};

            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_blo_fk};
            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY (artefact) REFERENCES {artefact}(id);

            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_fil_fk};
            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY (attachment) REFERENCES {artefact}(id);
            ");
        }
        else if (is_mysql()) {
100 101
            execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_blo_fk}");
            execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_blo_ix}");
102
            execute_sql("ALTER TABLE {artefact_attachment} CHANGE blogpost artefact BIGINT(10) DEFAULT NULL");
103
            execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY {arteatta_art_ix} (artefact) REFERENCES {artefact}(id)");
104

105 106
            execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_fil_fk}");
            execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_fil_ix}");
107
            execute_sql("ALTER TABLE {artefact_attachment} CHANGE file attachment BIGINT(10) DEFAULT NULL");
108
            execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY {arteatta_att_ix} (attachment) REFERENCES {artefact}(id)");
109 110 111 112 113 114 115 116 117
        }

        // 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);
    }

118 119 120 121 122
    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');
    }

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    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);
    }

215 216 217 218 219 220 221 222 223 224 225 226
    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);
        }
    }

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    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);
    }

263 264 265 266 267 268 269 270 271 272 273 274
    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);
    }

275 276 277
    if ($oldversion < 2009070600) {
        // This was forgotten as part of the 1.0 -> 1.1 upgrade
        if ($data = check_upgrades('blocktype.file/html')) {
278
              upgrade_plugin($data);
279 280 281
        };
    }

282 283 284 285 286 287 288
    if ($oldversion < 2009070700) {
        foreach (array('addfriend', 'removefriend', 'addfriendrequest', 'removefriendrequest') as $eventtype) {
            $event = (object) array('name' => $eventtype);
            ensure_record_exists('event_type', $event, $event);
        }
    }

289
    if ($oldversion < 2009070900) {
290 291 292 293
        if (is_mysql()) {
            execute_sql("ALTER TABLE {usr} DROP FOREIGN KEY {usr_las_fk}");
            execute_sql("ALTER TABLE {usr} DROP INDEX {usr_las_ix}");
        }
294 295 296 297 298
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastauthinstance');
        drop_field($table, $field);
    }

299
    if ($oldversion < 2009080600) {
300 301 302 303 304 305 306 307 308
        $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("
                SELECT owner, id
309
                FROM {view}
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
                WHERE owner IN (
                    SELECT owner
                    FROM {view}
                    WHERE type = 'profile'
                    GROUP BY owner
                    HAVING COUNT(*) > 1
                )
                AND type = 'profile'
                ORDER BY owner, id", array())) {

                require_once('view.php');
                $seen = array();
                foreach ($viewdata as $record) {
                    $seen[$record->owner][] = $record->id;
                }
325

326 327 328 329
                foreach ($seen as $owner => $views) {
                    // Remove the first one, which is their real profile view
                    array_shift($views);
                    foreach ($views as $viewid) {
330 331 332 333 334 335 336 337 338 339 340
                        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) {
Son Nguyen's avatar
Son Nguyen committed
341
                                if (table_exists(new XMLDBTable('blocktype_wall_post'))) {
342 343 344 345 346
                                    delete_records('blocktype_wall_post', 'instance', $id);
                                }
                                delete_records('view_artefact', 'block', $id);
                                delete_records('block_instance', 'id', $id);
                            }
347
                        }
348
                        delete_records('view','id', $viewid);
349 350 351
                    }
                }
            }
352 353 354
            if (is_postgres()) {
                execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
            }
355 356 357
        }
    }

358 359 360 361 362
    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')");
    }

Richard Mansfield's avatar
Richard Mansfield committed
363 364 365 366 367 368 369
    if ($oldversion < 2009081800) {
        $event = (object)array(
            'name' => 'creategroup',
        );
        ensure_record_exists('event_type', $event, $event);
    }

370 371 372 373 374 375 376 377 378 379
    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);
    }

380 381 382 383 384 385 386
    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));
    }

387 388 389 390 391 392
    if ($oldversion < 2009090700) {
        set_config('showselfsearchsideblock', 1);
        set_config('showtagssideblock', 1);
        set_config('tagssideblockmaxtags', 20);
    }

393 394 395 396 397 398 399 400 401
    if ($oldversion < 2009092100) {
        if ($data = check_upgrades('import.file')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.creativecommons')) {
            upgrade_plugin($data);
        }
    }

402 403 404 405 406 407 408
    if ($oldversion < 2009092900) {
        $event = (object)array(
            'name' => 'deleteartefacts',
        );
        ensure_record_exists('event_type', $event, $event);
    }

409
    if ($oldversion < 2009101600) {
410
        require_once(get_config('docroot').'/lib/stringparser_bbcode/lib.php');
411 412 413
        // Remove bbcode formatting from existing feedback
        if ($records = get_records_sql_array("SELECT * FROM {view_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
414 415 416
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
417 418 419 420 421
                update_record('view_feedback', $r);
            }
        }
        if ($records = get_records_sql_array("SELECT * FROM {artefact_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
422 423 424
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
425 426 427 428 429
                update_record('artefact_feedback', $r);
            }
        }
    }

430 431 432 433 434 435 436 437 438 439 440 441 442 443
    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);
    }

444
    if ($oldversion < 2009102200) {
445 446 447
        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));
        }
448 449
    }

450 451 452 453 454 455
    if ($oldversion < 2009102900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('sessionid');
        drop_field($table, $field);
    }

456 457 458 459
    if ($oldversion < 2009110500) {
        set_config('creategroups', 'all');
    }

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    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);
    }

475 476 477
    if ($oldversion < 2009111200) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailssent');
478
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
479 480 481
        add_field($table, $field);
    }

482 483 484
    if ($oldversion < 2009111201) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailsbounced');
485
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
486 487 488
        add_field($table, $field);
    }

489 490 491
    if ($oldversion < 2009120100) {
        // Fix for bug in 1.1 => 1.2 upgrade which may have inserted
        // a second groupmessage activity_type record
492
        $records = get_records_select_array('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'), 'id');
493 494
        if ($records && count($records) > 1) {
            for ($i = 1; $i < count($records); $i++) {
495 496 497 498
                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);
499 500 501 502 503
                delete_records('activity_type', 'id', $records[$i]->id);
            }
        }
    }

504
    if ($oldversion < 2009120900) {
505 506 507 508 509 510
        $table = new XMLDBTable('view');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }

511 512
    if ($oldversion < 2010011300) {
        // Clean up the mess left behind by failing to delete blogposts in a transaction
513 514 515 516 517 518 519 520 521
        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.');
        }
522 523 524 525 526 527 528
        execute_sql("
            INSERT INTO {artefact_blog_blogpost} (blogpost)
            SELECT id FROM {artefact} WHERE artefacttype = 'blogpost' AND id NOT IN (
                SELECT blogpost FROM {artefact_blog_blogpost}
            )");
    }

529 530 531 532
    if ($oldversion < 2010012701) {
        set_config('userscanchooseviewthemes', 1);
    }

533 534 535 536 537 538
    if ($oldversion < 2010021500) {
        if ($data = check_upgrades('blocktype.recentforumposts')) {
            upgrade_plugin($data);
        }
    }

539 540 541 542 543 544 545 546 547 548 549 550
    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("
            INSERT INTO {usr_account_preference} (usr, field, value)
            SELECT u.id, 'hiderealname', 1
            FROM {usr} u LEFT JOIN {usr_account_preference} p ON (u.id = p.usr AND p.field = 'hiderealname')
            WHERE NOT u.preferredname IS NULL AND u.preferredname != '' AND p.field IS NULL
        ");
    }

Evan Goldenberg's avatar
Evan Goldenberg committed
551
    if ($oldversion < 2010040700) {
552 553 554 555 556 557 558 559 560 561 562 563 564
        // 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);
Evan Goldenberg's avatar
Evan Goldenberg committed
565 566
    }

567
    if ($oldversion < 2010040800) {
568 569 570 571
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
572 573
    }

574 575 576 577 578
    if ($oldversion < 2010041200) {
        delete_records('config', 'field', 'captchaoncontactform');
        delete_records('config', 'field', 'captchaonregisterform');
    }

579 580 581 582
    if ($oldversion < 2010041201) {
        $sql = "
            SELECT u.id
            FROM {usr} u
583 584 585
            LEFT JOIN {artefact} a
                ON (a.owner = u.id AND a.artefacttype = 'blog')
            WHERE u.id > 0
586
            GROUP BY u.id
587
            HAVING COUNT(a.id) != 1";
588

589
        $manyblogusers = get_records_sql_array($sql, array());
590

591 592 593 594 595 596 597 598 599 600 601 602 603
        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);
            }
604 605 606
        }
    }

607
    if ($oldversion < 2010041600 && table_exists(new XMLDBTable('view_feedback'))) {
608 609 610 611 612 613 614 615 616 617 618 619 620
        // 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()) {
621 622
            execute_sql("ALTER TABLE {artefact} ALTER COLUMN authorname DROP DEFAULT");
            set_field('artefact', 'authorname', null);
623 624 625 626 627 628 629 630 631 632 633 634 635
            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)
        )');
636

637 638 639 640 641 642 643
        // Move feedback activity type to artefact plugin
        execute_sql("
            UPDATE {activity_type}
            SET plugintype = 'artefact', pluginname = 'comment'
            WHERE name = 'feedback'
        ");

644
        // Install the comment artefact
645 646 647
        if ($data = check_upgrades('artefact.comment')) {
            upgrade_plugin($data);
        }
648 649 650 651 652 653

        // 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'));
654 655 656 657 658 659

        // 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) {
660 661 662 663 664 665 666 667 668
                if ($f->author > 0) {
                    $f->authorname = null;
                }
                else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
669 670 671 672 673 674
                $artefact = (object) array(
                    'artefacttype' => 'comment',
                    'owner'        => $f->owner,
                    'group'        => $f->group,
                    'institution'  => $f->institution,
                    'author'       => $f->author,
675
                    'authorname'   => $f->authorname,
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
                    '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) {
705 706 707 708 709 710 711 712 713
                if ($f->author > 0) {
                    $f->authorname = null;
                }
                else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
                $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);
742

743 744
        // Add site setting for anonymous comments
        set_config('anonymouscomments', 1);
745 746
    }

747
    if ($oldversion < 2010041900 && !table_exists(new XMLDBTable('site_data'))) {
748 749
        // Upgrades for admin stats pages

750
        // Table for collection of historical stats
751 752 753 754 755 756
        $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);
757

Richard Mansfield's avatar
Richard Mansfield committed
758
        // Insert cron jobs to save site data
759 760 761 762 763 764 765 766
        $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);
Richard Mansfield's avatar
Richard Mansfield committed
767 768 769 770 771 772 773 774 775

        $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);
776 777 778

        // Put best guess at installation time into config table.
        set_config('installation_time', get_field_sql("SELECT MIN(ctime) FROM {site_content}"));
Richard Mansfield's avatar
Richard Mansfield committed
779

780 781 782
        // Save the current time so we know when we started collecting stats
        set_config('stats_installation_time', db_format_timestamp(time()));

Richard Mansfield's avatar
Richard Mansfield committed
783 784 785 786 787
        // 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);
788 789 790 791 792 793 794 795 796 797 798 799 800 801

        // 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);
802

803 804 805 806 807 808 809 810 811 812 813
        // 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);
    }

Evan Goldenberg's avatar
Evan Goldenberg committed
814
    if ($oldversion < 2010042600) {
Richard Mansfield's avatar
Richard Mansfield committed
815 816 817 818 819 820 821 822 823
        // @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);
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

        $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);
                }
            }
        }
Evan Goldenberg's avatar
Evan Goldenberg committed
846 847
    }

848
    if ($oldversion < 2010042602 && !get_record('view_type', 'type', 'dashboard')) {
849 850 851 852 853 854
        insert_record('view_type', (object)array(
            'type' => 'dashboard',
        ));
        if ($data = check_upgrades('blocktype.inbox')) {
            upgrade_plugin($data);
        }
855 856 857
        if ($data = check_upgrades('blocktype.newviews')) {
            upgrade_plugin($data);
        }
858 859 860 861 862 863
        // Install system dashboard view
        require_once(get_config('libroot') . 'view.php');
        $dbtime = db_format_timestamp(time());
        $viewdata = (object) array(
            'type'        => 'dashboard',
            'owner'       => 0,
864
            'numcolumns'  => 2,
865 866 867 868 869 870 871 872 873 874 875
            '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(
876 877 878
            array(
                'blocktype' => 'newviews',
                'title' => get_string('title', 'blocktype.newviews'),
879 880
                'column' => 1,
                'config' => array(
881
                    'limit' => 5,
882 883
                ),
            ),
884 885 886 887 888 889 890
            array(
                'blocktype' => 'myviews',
                'title' => get_string('title', 'blocktype.myviews'),
                'column' => 1,
                'config' => null,
            ),
            array(
891
                'blocktype' => 'inbox',
892
                'title' => get_string('inboxblocktitle'),
893 894 895
                'column' => 2,
                'config' => array(
                    'feedback' => true,
896 897
                    'groupmessage' => true,
                    'institutionmessage' => true,
898
                    'maharamessage' => true,
899
                    'usermessage' => true,
900 901 902 903 904
                    'viewaccess' => true,
                    'watchlist' => true,
                    'maxitems' => '5',
                ),
            ),
905
            array(
906 907
                'blocktype' => 'inbox',
                'title' => get_string('topicsimfollowing'),
908
                'column' => 2,
909 910 911 912 913 914 915
                'config' => array(
                    'newpost' => true,
                    'maxitems' => '5',
                ),
            ),
        );
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
916
        $weights = array(1 => 0, 2 => 0);
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
        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']),
                ));
            }
        }
    }

932 933 934 935
    if ($oldversion < 2010042603) {
        execute_sql('ALTER TABLE {usr} ADD COLUMN showhomeinfo SMALLINT NOT NULL DEFAULT 1');
        set_config('homepageinfo', 1);
    }
936 937 938 939 940 941 942 943 944

    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);
    }

945 946 947 948
    if ($oldversion < 2010051000) {
        set_field('activity_type', 'delay', 1, 'name', 'groupmessage');
    }

949 950 951 952 953
    if ($oldversion < 2010052000) {
        $showusers = get_config('showonlineuserssideblock');
        set_config('showonlineuserssideblock', (int) (is_null($showusers) || $showusers));
    }

954 955 956 957 958 959 960 961 962 963 964
    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);
    }

965 966 967 968
    if ($oldversion < 2010061100) {
        set_config('registerterms', 1);
    }

969 970 971 972 973 974 975 976 977 978
    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);
        }
979 980
        if ($data = check_upgrades('blocktype.groupviews')) {
            upgrade_plugin($data);
981
        }
982 983 984 985 986 987 988 989 990

        $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,
991
            'title'       => get_string('grouphomepage', 'view'),
992 993 994 995 996 997 998 999 1000 1001
            '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',
1002
                'title' => '',
1003 1004 1005 1006 1007
                'column' => 1,
                'config' => null,
            ),
            array(
                'blocktype' => 'recentforumposts',
1008
                'title' => get_string('latestforumposts', 'interaction.forum'),
1009 1010 1011 1012 1013
                'column' => 1,
                'config' => null,
            ),
            array(
                'blocktype' => 'groupviews',
1014
                'title' => get_string('Views', 'view'),
1015 1016 1017
                'column' => 1,
                'config' => null,
            ),
1018 1019
            array(
                'blocktype' => 'groupmembers',
1020
                'title' => get_string('Members', 'group'),
1021 1022 1023
                'column' => 1,
                'config' => null,
            ),
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        );
        $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']),
            ));
        }
1043

1044
        // add a default group homepage view for all groups in the system
1045 1046 1047
        unset($viewdata->owner);
        $viewdata->template = 0;

1048 1049 1050 1051
        if (!$groups = get_records_array('group', '', '', '', 'id,public')) {
            $groups = array();
        }
        foreach ($groups as $group) {
1052 1053
            $viewdata->group = $group->id;
            $id = insert_record('view', $viewdata, 'id', true);
1054 1055 1056 1057 1058 1059 1060 1061
            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,
            ));
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
            $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']),
                ));
            }
1074 1075
        }
    }
1076 1077 1078
    if ($oldversion < 2010062502) {
        //new feature feedback control on views
        $table = new XMLDBTable('view_access');
1079 1080 1081

        $field = new XMLDBField('allowcomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
1082
        add_field($table, $field);
1083 1084 1085

        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
1086
        add_field($table, $field);
1087 1088 1089 1090 1091 1092

        // 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');
1093
        add_field($table, $field);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

        $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);
1120
        add_field($table, $field);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

        $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');
1163
        drop_table($table);
1164
        $table = new XMLDBTable('view_access_usr');
1165
        drop_table($table);
1166
        $table = new XMLDBTable('view_access_token');
1167
        drop_table($table);
1168 1169

        // Insert explicit tutor access records for submitted views
1170
        if (!$submittedviews = get_records_sql_array('
1171 1172 1173
            SELECT v.id, v.submittedgroup, g.grouptype
            FROM {view} v JOIN {group} g ON (v.submittedgroup = g.id AND g.deleted = 0)',
            array()
1174 1175 1176
        )) {
            $submittedviews = array();
        }
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
        $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);
            }
        }
1195
    }
1196

Richard Mansfield's avatar
Richard Mansfield committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
    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);
    }

1215 1216 1217 1218
    if ($oldversion < 2010071300) {
        set_config('searchusernames', 1);
    }

1219 1220 1221 1222
    if ($oldversion < 2010071500) {
        reload_html_filters();
    }

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    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);
    }

1234 1235 1236 1237 1238 1239 1240
    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);
    }

1241
    if ($oldversion < 2010081000) {
1242 1243 1244 1245 1246 1247 1248 1249 1250

        // 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);
1251
        $table->addFieldInfo('navigation', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
1252 1253 1254 1255 1256 1257 1258 1259
        $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);
1260 1261
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('view'));
1262 1263 1264 1265
        $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);

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
        // 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);

    }

Richard Mansfield's avatar
Richard Mansfield committed
1277 1278 1279 1280 1281 1282 1283 1284 1285
    if ($oldversion < 2010081001) {
        if ($data = check_upgrades('artefact.plans')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.plans/plans')) {
            upgrade_plugin($data);
        }
    }

1286 1287 1288 1289 1290 1291
    if ($oldversion < 2010081100) {
        if ($data = check_upgrades('blocktype.navigation')) {
            upgrade_plugin($data);
        }
    }

1292 1293 1294 1295
    if ($oldversion < 2010082000) {
        delete_records_select('config', "field IN ('usersrank', 'groupsrank', 'viewsrank')");
    }

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
    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);
        }
    }

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    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("
            UPDATE {view} SET submittedtime = NULL
            WHERE submittedtime IS NOT NULL AND submittedgroup IS NULL AND submittedhost IS NULL"
        );
    }

1325
    if ($oldversion < 2010100702) {
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        // 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);
        }
    }

1339 1340 1341 1342
    if ($oldversion < 2010110800) {
        // Encrypt all passwords with no set salt values
        $sql = "SELECT * FROM {usr}
                WHERE salt IS NULL OR salt = ''";
1343 1344 1345 1346 1347 1348
        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);
            }
1349 1350 1351
        }
    }

1352 1353 1354 1355 1356 1357 1358 1359
    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);