upgrade.php 66 KB
Newer Older
1
2
3
4
<?php
/**
 *
 * @package    mahara
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
15
16
 *
 */

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

/**
 * Class to use for installation exceptions
 */
17
class InstallationException extends SystemException {}
18

19
require_once('ddl.php');
20
21

/**
22
23
 * This function checks core and plugins for which need to be upgraded/installed
 *
24
25
26
27
 * Note: This function is sometimes executed during upgrades from
 * ancient databases.  Avoid rash assumptions about what's installed
 * or these upgrades may fail.
 *
28
29
 * @param string $name The name of the plugin to check. If no name is specified,
 *                     all plugins are checked.
30
31
32
 * @return mixed If a name is specified, an object will be returned with upgrade data
 *                     about the requested component (which can be "core", "local", or a plugin).
 *                     If the component desn't need to be updated, an empty array will be returned.
33
34
35
 *               If no name is specified, an array of such objects will be returned.
 *                     It will also include an array key "settings", which will be an array
 *                     that may contain metadata about the upgrade/install process.
36
 */
37
function check_upgrades($name=null) {
38

39
40
41
    $pluginstocheck = plugin_types();

    $toupgrade = array();
42
    $settings = array();
43
44
    $toupgradecount = 0;
    $newinstallcount = 0;
45
    $installing = false;
46
    $newinstalls = array();
47
48
49
50
51
52

    require('version.php');
    // check core first...
    if (empty($name) || $name == 'core') {
        try {
            $coreversion = get_config('version');
Elliot Pahl's avatar
Elliot Pahl committed
53
        }
54
55
56
        catch (Exception $e) {
            $coreversion = 0;
        }
57
        $corerelease = get_config('release');
58
59
60
61
        $core = new stdClass();
        $core->to = $config->version;
        $core->torelease = $config->release;
        $core->toseries = $config->series;
62
        $toupgrade['core'] = $core;
63
        if (empty($coreversion)) {
64
            if (is_mysql()) { // Show a more informative error message if using mysql with skip-innodb
65
                // In MySQL 5.6.x, we run the command 'SHOW ENGINES' to check if InnoDB is enabled or not
66
                global $db;
67
68
69
70
71
72
73
74
75
76
77
                $result = $db->Execute("SHOW ENGINES");
                $hasinnodb = false;
                while (!$result->EOF) {
                    if ($result->fields['Engine'] == 'InnoDB' && ($result->fields['Support'] == 'YES' || $result->fields['Support'] == 'DEFAULT')) {
                        $hasinnodb = true;
                        break;
                    }
                    $result->MoveNext();
                }

                if (!$hasinnodb) {
78
79
80
                    throw new ConfigSanityException("Mahara requires InnoDB tables.  Please ensure InnoDB tables are enabled in your MySQL server.");
                }
            }
81
82
            $core->install = true;
            $installing = true;
Elliot Pahl's avatar
Elliot Pahl committed
83
        }
84
        else if ($config->version > $coreversion) {
Elliot Pahl's avatar
Elliot Pahl committed
85
            if (isset($config->minupgradefrom) && isset($config->minupgraderelease)
86
                && $coreversion < $config->minupgradefrom) {
87
                throw new ConfigSanityException("Must upgrade to $config->minupgradefrom "
88
89
                                          . "($config->minupgraderelease) first "
                                          . " (you have $coreversion ($corerelease)");
90
            }
91
            $toupgradecount ++;
92
93
            $core->upgrade = true;
            $core->from = $coreversion;
94
            $core->fromrelease = $corerelease;
95
        }
96
        else if ($config->version < $coreversion) {
97
98
            // Core can't be upgraded. Remove it from the list!
            unset($toupgrade['core']);
99
100
101
102
103
104
            if (get_config('productionmode')) {
                throw new ConfigSanityException("Database version of Mahara $corerelease ($coreversion) is newer "
                                            . "than files version $config->release ($config->version). "
                                            . "Please make sure you have the correct Mahara files in place.");
            }
            else {
105
106
107
                if (!defined('SITEOUTOFSYNC')) {
                    define('SITEOUTOFSYNC', 'core');
                }
108
109
            }
        }
110
111
112
113
        else {
            // Core doesn't need to be upgraded. Remove it from the list!
            unset($toupgrade['core']);
        }
114
115
    }

116
    // If we were just checking if the core needed to be upgraded, we can stop here
117
118
119
120
    if ($name == 'core') {
        return $toupgrade['core'];
    }

121
122
123
124
125
126
127
128
    if (!$installing && (empty($name) || $name == 'local')) {
        $localversion = get_config('localversion');
        $localrelease = get_config('localrelease');
        if (is_null($localversion)) {
            $localversion = 0;
            $localrelease = 0;
        }

129
        $config = new stdClass();
130
131
132
        require(get_config('docroot') . 'local/version.php');

        if ($config->version > $localversion) {
133
            $toupgradecount ++;
134
135
136
137
138
139
140
141
142
143
144
145
146
147
            $toupgrade['local'] = (object) array(
                'upgrade'     => true,
                'from'        => $localversion,
                'fromrelease' => $localrelease,
                'to'          => $config->version,
                'torelease'   => $config->release,
            );
        }

        if ($name == 'local') {
            return $toupgrade['local'];
        }
    }

148
149
    $plugins = array();
    if (!empty($name)) {
150
151
152
153
154
155
        try {
            $bits = explode('.', $name);
            $pt = $bits[0];
            $pn = $bits[1];
            $pp = null;
            if ($pt == 'blocktype' && strpos($pn, '/') !== false) {
156
                $bits = explode('/', $pn);
157
158
159
160
161
162
                $pp = get_config('docroot') . 'artefact/' . $bits[0]  . '/blocktype/' . $bits[1];
            }
            validate_plugin($pt, $pn, $pp);
            $plugins[] = explode('.', $name);
        }
        catch (InstallationException $_e) {
163
            log_warn(get_string('pluginnotinstallable', 'mahara', $pt, $pn) . $_e->GetMessage());
164
        }
165
166
167
168
169
    }
    else {
        foreach ($pluginstocheck as $plugin) {
            $dirhandle = opendir(get_config('docroot') . $plugin);
            while (false !== ($dir = readdir($dirhandle))) {
170
                if (strpos($dir, '.') === 0 or 'CVS' == $dir) {
171
172
                    continue;
                }
173
174
                $plugin_dir = get_config('docroot') . $plugin . '/' . $dir;
                if (!is_dir($plugin_dir)) {
175
176
                    continue;
                }
177
178
179
180
181
                try {
                    validate_plugin($plugin, $dir);
                    $plugins[] = array($plugin, $dir);
                }
                catch (InstallationException $_e) {
182
                    log_warn(get_string('pluginnotinstallable', 'mahara', $plugin, $dir) . $_e->GetMessage(), true , false);
183
184
185
                }

                if ($plugin == 'artefact') { // go check it for blocks as well
186
                    $btlocation = $plugin_dir . '/blocktype';
187
                    if (!is_dir($btlocation)) {
188
                        continue;
Elliot Pahl's avatar
Elliot Pahl committed
189
                    }
190
191
                    $btdirhandle = opendir($btlocation);
                    while (false !== ($btdir = readdir($btdirhandle))) {
192
                        if (strpos($btdir, '.') === 0 or 'CVS' == $btdir) {
193
194
                            continue;
                        }
195
                        if (!is_dir(get_config('docroot') . $plugin . '/' . $dir . '/blocktype/' . $btdir)) {
196
197
198
                            continue;
                        }
                        $plugins[] = array('blocktype', $dir . '/' . $btdir);
199
200
                    }
                }
201
202
203
            }
        }
    }
204
    $outofsyncplugins = array();
205
206
207
208
209
210
    foreach ($plugins as $plugin) {
        $plugintype = $plugin[0];
        $pluginname = $plugin[1];
        $pluginpath = "$plugin[0]/$plugin[1]";
        $pluginkey  = "$plugin[0].$plugin[1]";

211
212
213
214
215
216
        if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
            // sigh.. we're a bit special...
            $bits = explode('/', $pluginname);
            $pluginpath = 'artefact/' . $bits[0] . '/blocktype/' . $bits[1];
        }

217
218
219
        // Don't try to get the plugin info if we are installing - it will
        // definitely fail
        $pluginversion = 0;
220
221
222
223
224
225
226
227
228
        if (!$installing && table_exists(new XMLDBTable($plugintype . '_installed'))) {
            if ($plugintype == 'blocktype' && strpos($pluginname, '/')) {
                $bits = explode('/', $pluginname);
                $installed = get_record('blocktype_installed', 'name', $bits[1], 'artefactplugin', $bits[0]);
            }
            else {
                $installed = get_record($plugintype . '_installed', 'name', $pluginname);
            }
            if ($installed) {
229
230
231
                $pluginversion = $installed->version;
                $pluginrelease =  $installed->release;
            }
232
        }
233

234
        $config = new stdClass();
235
        require(get_config('docroot') . $pluginpath . '/version.php');
236

237
238
239
240
241
        $classname = generate_class_name($plugintype, $pluginname);
        safe_require($plugintype, $pluginname);
        // Check if there is a displayname
        $plugindisplayname = call_static_method($classname, 'get_plugin_display_name');

242
        if (empty($pluginversion)) {
243
            $newinstall = false;
244
            if (empty($installing) && $pluginkey != $name) {
245
                $newinstall = true;
246
            }
247
            $plugininfo = new stdClass();
248
249
250
            $plugininfo->install = true;
            $plugininfo->to = $config->version;
            $plugininfo->torelease = $config->release;
251
252
253
254
255
256
            if (property_exists($config, 'requires_config')) {
                $plugininfo->requires_config = $config->requires_config;
            }
            if (property_exists($config, 'requires_parent')) {
                $plugininfo->requires_parent = $config->requires_parent;
            }
257
            $plugininfo->displayname = $plugindisplayname;
258

259
260
261
262
263
264
265
266
267
            try {
                $classname::sanity_check();
            }
            catch (InstallationException $exc) {
                $plugininfo->to = get_string('notinstalled', 'admin');
                $plugininfo->torelease = get_string('notinstalled', 'admin');
                $plugininfo->errormsg = $exc->getMessage();
            }

268
269
270
271
272
273
274
275
276
277
            if ($newinstall) {
                $plugininfo->from = get_string('notinstalled', 'admin');
                $plugininfo->fromrelease = get_string('notinstalled', 'admin');
                $plugininfo->newinstall = true;
                $newinstallcount ++;
                $newinstalls[$pluginkey] = $plugininfo;
            }
            else {
                $toupgrade[$pluginkey] = $plugininfo;
            }
278
279
        }
        else if ($config->version > $pluginversion) {
280
281
282
283
284
            if (isset($config->minupgradefrom) && isset($config->minupgraderelease)
                && $pluginversion < $config->minupgradefrom) {
                throw new ConfigSanityException("Must upgrade to $config->minupgradefrom "
                                          . " ($config->minupgraderelease) first "
                                          . " (you have $pluginversion ($pluginrelease))");
285
            }
286
            $toupgradecount++;
287
            $plugininfo = new stdClass();
288
289
290
291
292
            $plugininfo->upgrade = true;
            $plugininfo->from = $pluginversion;
            $plugininfo->fromrelease = $pluginrelease;
            $plugininfo->to = $config->version;
            $plugininfo->torelease = $config->release;
293
294
295
296
297
298
            if (property_exists($config, 'requires_config')) {
                $plugininfo->requires_config = $config->requires_config;
            }
            if (property_exists($config, 'requires_parent')) {
                $plugininfo->requires_parent = $config->requires_parent;
            }
299
            $plugininfo->displayname = $plugindisplayname;
300
301
302
303
304
305
306
307
308
309
310
311
312

            try {
                $classname::sanity_check();
            }
            catch (InstallationException $exc) {
                $plugininfo->to = $config->version;
                $plugininfo->torelease = $pluginrelease;
                $plugininfo->errormsg = $exc->getMessage();
                $toupgrade[$pluginkey] = $plugininfo;

                continue;
            }

313
314
            $toupgrade[$pluginkey] = $plugininfo;
        }
315
        else if ($config->version < $pluginversion) {
316
            $plugindisplayname = !empty($plugindisplayname) ? $plugindisplayname : (!empty($config->name) ? $config->name : $pluginpath);
317
318
319
320
321
322
323
            if (get_config('productionmode')) {
                throw new ConfigSanityException("Database version of Mahara plugin " . $plugindisplayname . " "
                                            . $pluginrelease . " (" . $pluginversion . ") is newer "
                                            . "than files version " . $config->release . " (" . $config->version . "). "
                                            . "Please make sure you have the correct Mahara plugin files in place.");
            }
            else {
324
                $outofsyncplugins[] = $plugindisplayname;
325
326
            }
        }
327
    }
328
    if (!empty($outofsyncplugins)) {
329
330
331
        if (!defined('SITEOUTOFSYNC')) {
            define('SITEOUTOFSYNC', implode(', ', $outofsyncplugins));
        }
332
    }
333
    // if we've just asked for one, don't return an array...
334
    if (!empty($name)) {
335
        if (count($toupgrade) == 1) {
336
            $upgrade = new stdClass();
337
338
339
340
341
342
343
344
            $upgrade->name = $name;
            foreach ((array)$toupgrade[$name] as $key => $value) {
                $upgrade->{$key} = $value;
            }
            return $upgrade;
        }
        else {
            return array();
345
346
        }
    }
347
348

    // If we get here, it's because we have an array of objects to return
349
    uksort($toupgrade, 'sort_upgrades');
350
    $settings['newinstallcount'] = $newinstallcount;
351
    $settings['newinstalls'] = $newinstalls;
352
353
    $settings['toupgradecount'] = $toupgradecount;
    $toupgrade['settings'] = $settings;
354
355
356
    return $toupgrade;
}

357
358
359
360
361
/**
 * Upgrades the core system to given upgrade version.
 *
 * @param object $upgrade   The version to upgrade to
 * @return bool             Whether the upgrade succeeded or not
362
 * @throws SQLException     If the upgrade failed due to a database error
363
 */
364
365
366
function upgrade_core($upgrade) {
    global $db;

367
    $location = get_config('libroot') . 'db/';
Penny Leach's avatar
Penny Leach committed
368
369

    db_begin();
370
371

    if (!empty($upgrade->install)) {
372
        install_from_xmldb_file($location . 'install.xml');
373
374
375
    }
    else {
        require_once($location . 'upgrade.php');
Penny Leach's avatar
Penny Leach committed
376
        xmldb_core_upgrade($upgrade->from);
377
378
    }

Penny Leach's avatar
Penny Leach committed
379
380
    set_config('version', $upgrade->to);
    set_config('release', $upgrade->torelease);
381
    set_config('series', $upgrade->toseries);
382
    bump_cache_version();
Elliot Pahl's avatar
Elliot Pahl committed
383

384
    if (!empty($upgrade->install)) {
Penny Leach's avatar
Penny Leach committed
385
        core_postinst();
386
    }
387

Penny Leach's avatar
Penny Leach committed
388
389
    db_commit();
    return true;
390
391
}

392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/**
 * Upgrades local customisations.
 *
 * @param object $upgrade   The version to upgrade to
 * @return bool             Whether the upgrade succeeded or not
 * @throws SQLException     If the upgrade failed due to a database error
 */
function upgrade_local($upgrade) {
    db_begin();

    require_once(get_config('docroot') . 'local/upgrade.php');
    xmldb_local_upgrade($upgrade->from);

    set_config('localversion', $upgrade->to);
    set_config('localrelease', $upgrade->torelease);
407
    bump_cache_version();
408
409
410
411
412

    db_commit();
    return true;
}

413
414
415
/**
 * Upgrades the plugin to a new version
 *
416
417
418
419
 * Note: This function is sometimes executed during upgrades from
 * ancient databases.  Avoid rash assumptions about what's installed
 * or these upgrades may fail.
 *
420
421
 * @param object $upgrade   Information about the plugin to upgrade
 * @return bool             Whether the upgrade succeeded or not
422
 * @throws SQLException     If the upgrade failed due to a database error
423
 */
424
425
426
427
428
429
430
431
function upgrade_plugin($upgrade) {
    global $db;

    $plugintype = '';
    $pluginname = '';

    list($plugintype, $pluginname) = explode('.', $upgrade->name);

432
433
    if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
        list($artefactplugin, $blocktypename) = explode('/', $pluginname);
434
435
436
437
438
439
        $location = get_config('docroot') . 'artefact/' . $artefactplugin . '/blocktype/' . $blocktypename . '/db/';
        $function = 'xmldb_' . $plugintype . '_' . $blocktypename . '_upgrade';
    }
    else {
        $location = get_config('docroot') . $plugintype . '/' . $pluginname . '/db/';
        $function = 'xmldb_' . $plugintype . '_' . $pluginname . '_upgrade';
Elliot Pahl's avatar
Elliot Pahl committed
440
    }
441

442
    db_begin();
443
444
445

    if (!empty($upgrade->install)) {
        if (is_readable($location . 'install.xml')) {
446
            install_from_xmldb_file($location . 'install.xml');
447
448
449
450
451
        }
    }
    else {
        if (is_readable($location .  'upgrade.php')) {
            require_once($location . 'upgrade.php');
452
453
454
            if (!$function($upgrade->from)) {
                throw new InstallationException("Failed to run " . $function . " (check logs for errors)");
            }
455
456
457
        }
    }

458
    $installed = new stdClass();
459
460
461
    $installed->name = $pluginname;
    $installed->version = $upgrade->to;
    $installed->release = $upgrade->torelease;
462
463
464
465
466
467
468
469
    if ($plugintype == 'blocktype') {
        if (!empty($blocktypename)) {
            $installed->name = $blocktypename;
        }
        if (!empty($artefactplugin)) { // blocks come from artefactplugins.
            $installed->artefactplugin = $artefactplugin;
        }
    }
470
471
472
473
474
475
    if (property_exists($upgrade, 'requires_config')) {
        $installed->requires_config = $upgrade->requires_config;
    }
    if (property_exists($upgrade, 'requires_parent')) {
        $installed->requires_parent = $upgrade->requires_parent;
    }
476
    $installtable = $plugintype . '_installed';
477
478
479

    if (!empty($upgrade->install)) {
        insert_record($installtable,$installed);
Elliot Pahl's avatar
Elliot Pahl committed
480
    }
481
482
483
    else {
        update_record($installtable, $installed, 'name');
    }
484
    bump_cache_version();
485
486

    // postinst stuff...
Nigel McNie's avatar
Nigel McNie committed
487
    safe_require($plugintype, $pluginname);
488
    $pcname = generate_class_name($plugintype, $installed->name);
489
490
491
492
493
494
495
496
497
498
499

    if ($crons = call_static_method($pcname, 'get_cron')) {
        foreach ($crons as $cron) {
            $cron = (object)$cron;
            if (empty($cron->callfunction)) {
                throw new InstallationException("cron for $pcname didn't supply function name");
            }
            if (!is_callable(array($pcname, $cron->callfunction))) {
                throw new InstallationException("cron $cron->callfunction for $pcname supplied but wasn't callable");
            }
            $new = false;
500
            $table = $plugintype . '_cron';
501
502
503
            if (!empty($upgrade->install)) {
                $new = true;
            }
504
            else if (!record_exists($table, 'plugin', $pluginname, 'callfunction', $cron->callfunction)) {
505
506
507
508
                $new = true;
            }
            $cron->plugin = $pluginname;
            if (!empty($new)) {
509
                insert_record($table, $cron);
510
511
            }
            else {
512
                update_record($table, $cron, array('plugin', 'callfunction'));
513
514
515
            }
        }
    }
Elliot Pahl's avatar
Elliot Pahl committed
516

517
518
519
520
    if ($events = call_static_method($pcname, 'get_event_subscriptions')) {
        foreach ($events as $event) {
            $event = (object)$event;

521
            if (!record_exists('event_type', 'name', $event->event)) {
522
523
524
525
526
527
528
529
530
                throw new InstallationException("event $event->event for $pcname doesn't exist!");
            }
            if (empty($event->callfunction)) {
                throw new InstallationException("event $event->event for $pcname didn't supply function name");
            }
            if (!is_callable(array($pcname, $event->callfunction))) {
                throw new InstallationException("event $event->event with function $event->callfunction for $pcname supplied but wasn't callable");
            }
            $exists = false;
531
            $table = $plugintype . '_event_subscription';
532
            $block = blocktype_namespaced_to_single($pluginname);
533
            if (empty($upgrade->install)) {
534
                $exists = get_record($table, 'plugin' , $block, 'event', $event->event);
535
            }
536
            $event->plugin = $block;
537
            if (empty($exists)) {
538
                insert_record($table, $event);
539
540
            }
            else {
541
                update_record($table, $event, array('id' => $exists->id));
542
543
544
545
            }
        }
    }

546
547
548
549
550
551
    if ($activities = call_static_method($pcname, 'get_activity_types')) {
        foreach ($activities as $activity) {
            $classname = 'ActivityType' . ucfirst($plugintype) . ucfirst($pluginname) . ucfirst($activity->name);
            if (!class_exists($classname)) {
                throw new InstallationException(get_string('classmissing', 'error',  $classname, $pluginname, $plugintype));
            }
552
553
554
555
556
557
558
559
560
561
562
563
            // Add activity_type if it doesn't exist
            if (!get_record('activity_type', 'name', $activity->name, 'plugintype', $plugintype, 'pluginname', $pluginname)) {
                $activity->plugintype = $plugintype;
                $activity->pluginname = $pluginname;
                $activity->defaultmethod = get_config('defaultnotificationmethod') ? get_config('defaultnotificationmethod') : $activity->defaultmethod;
                $where = (object) array(
                    'name'       => $activity->name,
                    'plugintype' => $plugintype,
                    'pluginname' => $pluginname,
                );
                ensure_record_exists('activity_type', $where, $activity);
            }
564
565
566
        }
    }

567
    // install artefact types
568
    if ($plugintype == 'artefact') {
569
570
571
        if (!is_callable(array($pcname, 'get_artefact_types'))) {
            throw new InstallationException("Artefact plugin $pcname must implement get_artefact_types and doesn't");
        }
572
573
574
        $types = call_static_method($pcname, 'get_artefact_types');
        $ph = array();
        if (is_array($types)) {
575
576
577
578
579
580
581
582
583
584
            // Check for missing plugins - don't try to remove their data.
            // Bugs 505732 and 1287344.
            $used_types = get_records_sql_assoc("SELECT t.name, count(a.id) ct, t.plugin FROM {artefact_installed_type} t
                    LEFT JOIN {artefact} a ON t.name = a.artefacttype
                    GROUP BY t.name
                    HAVING count(a.id) > 0 AND plugin = '$pluginname'");
            if ($used_types === FALSE) {
                $used_types = array();
            }

585
586
587
            foreach ($types as $type) {
                $ph[] = '?';
                if (!record_exists('artefact_installed_type', 'plugin', $pluginname, 'name', $type)) {
588
                    $t = new stdClass();
589
590
591
592
                    $t->name = $type;
                    $t->plugin = $pluginname;
                    insert_record('artefact_installed_type',$t);
                }
593
594
595
                if (isset($used_types[$type])) {
                    unset($used_types[$type]);
                }
596
            }
597
598
599
600
601
602
603

            foreach ($used_types as $type) {
                $ph[] = '?';
            }

            $used_types = array_keys($used_types);

604
605
            $select = '(plugin = ? AND name NOT IN (' . implode(',', $ph) . '))';
            delete_records_select('artefact_installed_type', $select,
606
607
608
609
                    array_merge(array($pluginname),$types,$used_types));
            if (!empty($used_types)) {
                log_warn('Plugin for artefact type(s) "' . implode('", "', $used_types) . '" has gone away', true, false);
            }
610
611
        }
    }
Elliot Pahl's avatar
Elliot Pahl committed
612

613
614
615
    // install blocktype categories.
    if ($plugintype == 'blocktype' && get_config('installed')) {
        install_blocktype_categories_for_plugin($pluginname);
616
        install_blocktype_viewtypes_for_plugin($pluginname);
617
618
    }

619
620
    $prevversion = (empty($upgrade->install)) ? $upgrade->from : 0;
    call_static_method($pcname, 'postinst', $prevversion);
Elliot Pahl's avatar
Elliot Pahl committed
621

622
623
    db_commit();
    return true;
624
625
626
}

function core_postinst() {
627
    // Attempt to create session directories
628
    $sessionpath = get_config('sessionpath');
629
    $status = Session::create_directory_levels($sessionpath);
630

631
    $now = db_format_timestamp(time());
632
633
634
    // Set default search plugin
    set_config('searchplugin', 'internal');

635
    set_config('lang', 'en.utf8');
636
    set_config('installation_key', get_random_key());
637
    set_config('installation_time', $now);
638
    set_config('stats_installation_time', $now);
639
    set_config('passwordpolicy', '8_ulns');
640

641
642
643
644
645
646
647
    // Pre-define SMTP settings
    set_config('smtphosts', '');
    set_config('smtpport', '');
    set_config('smtpuser', '');
    set_config('smtppass', '');
    set_config('smtpsecure', '');

648
649
650
651
652
653
654
655
656
    // XMLDB adds a table's keys immediately after creating the table.  Some
    // foreign keys therefore cannot be created during the XMLDB installation,
    // because they refer to tables created later in the installation.  These
    // missing keys can be created now that all the core tables exist.
    $table = new XMLDBTable('usr');
    $key = new XMLDBKey('profileiconfk');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('profileicon'), 'artefact', array('id'));
    add_key($table, $key);

657
658
659
660
661
    $table = new XMLDBTable('institution');
    $key = new XMLDBKey('logofk');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('logo'), 'artefact', array('id'));
    add_key($table, $key);

662
    // PostgreSQL supports indexes over functions of columns, MySQL does not.
663
    // We make use if this if we can
664
    if (is_postgres()) {
665
        // Improve the username index
666
667
        execute_sql('DROP INDEX {usr_use_uix}');
        execute_sql('CREATE UNIQUE INDEX {usr_use_uix} ON {usr}(LOWER(username))');
668

669
670
671
672
673
674
675
676
677
        // Add user search indexes
        // Postgres only.  We could create non-lowercased indexes in MySQL, but
        // they would not be useful, and would require a change to varchar columns.
        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_ema_ix} ON {usr}(LOWER(email))');
        execute_sql('CREATE INDEX {usr_stu_ix} ON {usr}(LOWER(studentid))');

678
679
        // Only one profile view per user
        execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
680
681
    }

682
683
684
685
686
687
688
689
690
691
692
    // Some more advanced constraints. XMLDB can't handle this in its xml file format
    execute_sql('ALTER TABLE {artefact} 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)
    )');
    execute_sql('ALTER TABLE {view} 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)
    )');
693
694
695
696
    execute_sql('ALTER TABLE {artefact} ADD CHECK (
        (author IS NOT NULL AND authorname IS NULL    ) OR
        (author IS NULL     AND authorname IS NOT NULL)
    )');
697
    execute_sql('ALTER TABLE {view_access} ADD CHECK (
698
699
700
701
702
        (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)
703
    )');
704
705
706
707
708
    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)
    )');
709

710
    set_antispam_defaults();
711
    reload_html_filters();
712
713

    // Default set of sites from which iframe content can be embedded
714
715
    // See also the postinst() function in plugins for other valid iframes
    // by searching for 'iframe_source_icon'
716
717
718
719
720
721
722
723
724
    $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',
725
        'voki.com/php/'                            => 'Voki',
726
727
728
729
730
731
732
    );
    $iframedomains = array(
        'YouTube'      => 'www.youtube.com',
        'Vimeo'        => 'vimeo.com',
        'SlideShare'   => 'www.slideshare.net',
        'Glogster'     => 'www.glogster.com',
        'WikiEducator' => 'wikieducator.org',
733
        'Voki'         => 'voki.com',
734
735
736
    );
    update_safe_iframes($iframesources, $iframedomains);

737
738
739
    require_once(get_config('docroot') . 'lib/file.php');
    update_magicdb_path();

740
    return $status;
741
742
}

743
function core_install_lastcoredata_defaults() {
744
    global $USER;
745
    db_begin();
746
    $institution = new stdClass();
747
748
749
    $institution->name = 'mahara';
    $institution->displayname = 'No Institution';
    $institution->authplugin  = 'internal';
750
    $institution->theme  = 'default';
751
    $institution->priority = 0;
752
    insert_record('institution', $institution);
753

754
    $auth_instance = new stdClass();
755
    $auth_instance->instancename  = 'Internal';
756
    $auth_instance->priority='1';
757
758
    $auth_instance->institution   = 'mahara';
    $auth_instance->authname      = 'internal';
759
    $auth_instance->active        = 1;
760
761
    $auth_instance->id = insert_record('auth_instance', $auth_instance, 'id', true);

762
    // Insert the root user
763
    $userid = 0;
764
    $user = new stdClass();
765
    $user->id = $userid;
766
767
768
769
770
771
    $user->username = 'root';
    $user->password = '*';
    $user->salt = '*';
    $user->firstname = 'System';
    $user->lastname = 'User';
    $user->email = 'root@example.org';
772
    $user->quota = get_config_plugin('artefact', 'file', 'defaultquota');
773
    $user->authinstance = $auth_instance->id;
774
    $user->admin = 1;
775

776
777
    if (is_mysql()) { // gratuitous mysql workaround
        $newid = insert_record('usr', $user, 'id', true);
778
        set_field('usr', 'id', 0, 'id', $newid);
779
        execute_sql('ALTER TABLE {usr} AUTO_INCREMENT=1');
780
    }
781
782
783
    else {
        insert_record('usr', $user);
    }
784

785
786
787
788
789
    $pages = site_content_pages();
    $now = db_format_timestamp(time());
    foreach ($pages as $name) {
        $page = new stdClass();
        $page->ctime = $now;
790
        $page->institution = 'mahara';
791
        $page->content = get_string($name . 'defaultcontent', 'install', get_string('staticpageconfigdefaults', 'install',  get_config('wwwroot') . 'admin/site/pages.php'));
792
        $page->name = $name;
793
794
795
796
797
        $page->mtime = $now;
        $page->mauthor = $userid;
        insert_record('site_content', $page);
    }

798
799
800
801
802
    $versionedpages = site_content_version_pages();
    foreach ($versionedpages as $name) {
        $page = new stdClass();
        $page->ctime = $now;
        $page->institution = 'mahara';
803
        $page->content = get_string($name . 'defaultcontent', 'install', get_string('versionedpageconfigdefault', 'install', get_config('wwwroot') . 'admin/site/privacy.php?fs=' . $name));
804
805
806
807
808
809
        $page->type = $name;
        $page->author = $userid;
        $page->version = '1.0';
        insert_record('site_content_version', $page);
    }

810
811
812
    // install the default layout options
    install_view_layout_defaults();

813
    require_once('group.php');
814
    install_system_profile_view();
815
    install_system_dashboard_view();
816
    install_system_grouphomepage_view();
817
818
    require_once('view.php');
    install_system_portfolio_view();
819

820
821
822
    require_once('license.php');
    install_licenses_default();

823
824
825
    require_once('skin.php');
    install_skins_default();

826
827
    install_auth_default();

828
829
830
831
    // Remove admin privs from root user as it doesn't need it now
    $user->admin = 0;
    update_record('usr', $user, array('id' => 0));

832
    // Insert the admin user
833
    $user = new stdClass();
834
    $user->username = 'admin';
835
    $user->salt = auth_get_random_salt();
836
    $user->password = crypt('mahara', '$2a$' . get_config('bcrypt_cost') . '$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 22));
837
    $user->password = substr($user->password, 0, 7) . substr($user->password, 7+22);
838
    $user->authinstance = $auth_instance->id;
839
840
841
842
843
    $user->passwordchange = 1;
    $user->admin = 1;
    $user->firstname = 'Admin';
    $user->lastname = 'User';
    $user->email = 'admin@example.org';
844
    $user->quota = get_config_plugin('artefact', 'file', 'defaultquota');
845
    $user->ctime = db_format_timestamp(time());
846
847
848
849
    $user->id = insert_record('usr', $user, 'id', true);
    set_profile_field($user->id, 'email', $user->email);
    set_profile_field($user->id, 'firstname', $user->firstname);
    set_profile_field($user->id, 'lastname', $user->lastname);
850
851
    // Accept the user privacy agreement on install
    $sitecontentid = get_field('site_content_version', 'id', 'type', 'privacy', 'institution', 'mahara');
852
853
854
    save_user_reply_to_agreement($user->id, $sitecontentid, 1);
    // Accept the user T&C on install
    $sitecontentid = get_field('site_content_version', 'id', 'type', 'termsandconditions', 'institution', 'mahara');
855
    save_user_reply_to_agreement($user->id, $sitecontentid, 1);
856
    handle_event('createuser', $user, array('password'));
857
    activity_add_admin_defaults(array($user->id));
858
    db_commit();
859
860

    // if we're installing, set up the block categories here and then poll the plugins.
Elliot Pahl's avatar
Elliot Pahl committed
861
    // if we're upgrading this happens somewhere else.  This is because of dependency issues around
862
    // the order of installation stuff.
863
    install_blocktype_extras();
864

865
866
    // Setting user access roles for content block access
    $table = new XMLDBTable('usr_access_roles');
867
868
869

    $roles = array('peer' => 0, 'manager' => 1, 'peermanager' => 1);
    foreach ($roles as $role => $state) {
870
        $obj = new stdClass();
871
872
        $obj->role              = $role;
        $obj->see_block_content = $state;
873
        insert_record('usr_access_roles', $obj);
874
    }
875
876
}

877
878
879
function core_install_firstcoredata_defaults() {
    // Install the default institution
    db_begin();
Elliot Pahl's avatar
Elliot Pahl committed
880

881
    set_config('session_timeout', 86400);
882
    set_config('sitename', 'Mahara');
883
    set_config('defaultregistrationexpirylifetime', 1209600);
884
    set_config('defaultaccountinactivewarn', 604800);
885
    set_config('creategroups', 'all');
886
    set_config('createpublicgroups', 'all');
887
    set_config('allowpublicviews', 1);
888
    set_config('allowpublicprofiles', 1);
889
    set_config('allowanonymouspages', 0);
890
    set_config('generatesitemap', 1);
891
892
893
    set_config('showselfsearchsideblock', 0);
    set_config('showtagssideblock', 1);
    set_config('tagssideblockmaxtags', 20);
894
    set_config('usersallowedmultipleinstitutions', 1);
895
    set_config('userscanchooseviewthemes', 0);
896
    set_config('anonymouscomments', 1);
897
    set_config('homepageinfo', 1);
898
    set_config('showonlineuserssideblock', 1);
899
    set_config('footerlinks', serialize(array('legal', 'about', 'contactus', 'manualhelp')));
900
    set_config('nousernames', 0);
901
    set_config('onlineuserssideblockmaxusers', 10);
902
    set_config('loggedinprofileviewaccess', 1);
903
    set_config('dropdownmenu', 0);
904
905
    // Set this to a random starting number to make minor version slightly harder to detect
    set_config('cacheversion', rand(1000, 9999));
906
    set_config('watchlistnotification_delay', 20);
907
908

    // install the applications
909
    $app = new stdClass();
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
    $app->name = 'mahara';
    $app->displayname = 'Mahara';
    $app->xmlrpcserverurl = '/api/xmlrpc/server.php';
    $app->ssolandurl = '/auth/xmlrpc/land.php';
    insert_record('application', $app);

    $app->name = 'moodle';
    $app->displayname = 'Moodle';
    $app->xmlrpcserverurl = '/mnet/xmlrpc/server.php';
    $app->ssolandurl = '/auth/mnet/land.php';
    insert_record('application', $app);

    // insert the event types
    $eventtypes = array(
        'createuser',
        'updateuser',
        'suspenduser',
        'unsuspenduser',
        'deleteuser',
        'undeleteuser',
        'expireuser',
        'unexpireuser',
        'deactivateuser',
        'activateuser',
934
        'userjoinsgroup',
935
        'userleavesgroup',
936
        'userchangegrouprole',
937
938
        'saveartefact',
        'deleteartefact',
939
        'deleteartefacts',
940
941
        'saveview',
        'deleteview',
942
        'blockinstancecommit',
943
        'deleteblockinstance',
944
945
946
947
        'addfriend',
        'removefriend',
        'addfriendrequest',
        'removefriendrequest',
Richard Mansfield's avatar
Richard Mansfield committed
948
        'creategroup',
949
        'loginas',
950
        'clearcaches',
951
952
953
954
955
956
        'createview',
        'createcollection',
        'updatecollection',
        'deletecollection',
        'addsubmission',
        'releasesubmission',
957
958
        'updateviewaccess',
        'sharedcommenttogroup'
959
960
961
    );

    foreach ($eventtypes as $et) {
962
        $e = new stdClass();
963
964
965
966
        $e->name = $et;
        insert_record('event_type', $e);
    }

967
968
969
970
971
    // install the core event subscriptions
    $subs = array(
        array(
            'event'        => 'createuser',
            'callfunction' => 'activity_set_defaults',
972
        ),
973
974
975
976
        array(
            'event'        => 'createuser',
            'callfunction' => 'add_user_to_autoadd_groups',
        ),
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
        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',
        ),
993
994
995
996
997
    );

    foreach ($subs as $sub) {
        insert_record('event_subscription', (object)$sub);
    }
Elliot Pahl's avatar
Elliot Pahl committed
998

999
    // Install the activity types. Name, admin, delay, allownonemethod, defaultmethod.
1000
    $activitytypes = array(
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
        array('maharamessage',      0, 0, 0, 'email'),
        array('usermessage',        0, 0, 0, 'email'),
        array('watchlist',          0, 1, 1, 'email'),
        array('viewaccess',         0, 1, 1, 'email'),
        array('contactus',          1, 1, 1, 'email'),
        array('objectionable',      1, 1, 1, 'email'),
        array('virusrepeat',        1, 1, 1, 'email'),
        array('virusrelease',       1, 1, 1, 'email'),
        array('institutionmessage', 0, 0, 1, 'email'),
        array('groupmessage',       0, 1, 1, 'email'),
1011
1012
1013
    );

    foreach ($activitytypes as $at) {
1014
        $a = new stdClass();
1015
1016
1017
        $a->name = $at[0];
        $a->admin = $at[1];
        $a->delay = $at[2];
1018
        $a->allownonemethod = $at[3];
1019
        $a->defaultmethod = $at[4];
1020
1021
1022
1023
1024
        insert_record('activity_type', $a);
    }

    // install the cronjobs...
    $cronjobs = array(