upgrade.php 48.3 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
 *
 * @package    mahara
21
 * @subpackage core
22
 * @author     Catalyst IT Ltd
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
26
27
28
29
30
31
32
 *
 */

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

/**
 * Class to use for installation exceptions
 */
33
class InstallationException extends SystemException {}
34

35
require_once('ddl.php');
36
37

/**
38
39
 * This function checks core and plugins for which need to be upgraded/installed
 *
40
41
42
43
 * Note: This function is sometimes executed during upgrades from
 * ancient databases.  Avoid rash assumptions about what's installed
 * or these upgrades may fail.
 *
44
45
46
 * @param string $name The name of the plugin to check. If no name is specified,
 *                     all plugins are checked.
 * @return array of objects
47
 */
48
function check_upgrades($name=null) {
49

50
51
52
53
    $pluginstocheck = plugin_types();

    $toupgrade = array();
    $installing = false;
54
    $disablelogin = false;
55
56

    require('version.php');
57
58
59
    if (isset($config->disablelogin) && !empty($config->disablelogin)) {
        $disablelogin = true;
    }
60
61
62
63
    // check core first...
    if (empty($name) || $name == 'core') {
        try {
            $coreversion = get_config('version');
Elliot Pahl's avatar
Elliot Pahl committed
64
        }
65
66
67
68
        catch (Exception $e) {
            $coreversion = 0;
        }
        if (empty($coreversion)) {
69
70
71
72
73
74
75
            if (is_mysql()) { // Show a more informative error message if using mysql with skip-innodb
                global $db;
                $result = $db->Execute("SHOW VARIABLES LIKE 'have_innodb'");
                if ($result->fields['Value'] != 'YES') {
                    throw new ConfigSanityException("Mahara requires InnoDB tables.  Please ensure InnoDB tables are enabled in your MySQL server.");
                }
            }
76
77
78
79
80
81
            $core = new StdClass;
            $core->install = true;
            $core->to = $config->version;
            $core->torelease = $config->release;
            $toupgrade['core'] = $core;
            $installing = true;
Elliot Pahl's avatar
Elliot Pahl committed
82
        }
83
        else if ($config->version > $coreversion) {
84
            $corerelease = get_config('release');
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
92
93
            $core = new StdClass;
            $core->upgrade = true;
            $core->from = $coreversion;
94
            $core->fromrelease = $corerelease;
95
96
97
98
99
100
            $core->to = $config->version;
            $core->torelease = $config->release;
            $toupgrade['core'] = $core;
        }
    }

101
    // If we were just checking if the core needed to be upgraded, we can stop here
102
    if ($name == 'core') {
103
        $toupgrade['core']->disablelogin = $disablelogin;
104
105
106
        return $toupgrade['core'];
    }

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    if (!$installing && (empty($name) || $name == 'local')) {
        $localversion = get_config('localversion');
        $localrelease = get_config('localrelease');
        if (is_null($localversion)) {
            $localversion = 0;
            $localrelease = 0;
        }

        $config = new StdClass;
        require(get_config('docroot') . 'local/version.php');

        if ($config->version > $localversion) {
            $toupgrade['local'] = (object) array(
                'upgrade'     => true,
                'from'        => $localversion,
                'fromrelease' => $localrelease,
                'to'          => $config->version,
                'torelease'   => $config->release,
            );
        }

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

134
135
    $plugins = array();
    if (!empty($name)) {
136
137
138
139
140
141
        try {
            $bits = explode('.', $name);
            $pt = $bits[0];
            $pn = $bits[1];
            $pp = null;
            if ($pt == 'blocktype' && strpos($pn, '/') !== false) {
142
                $bits = explode('/', $pn);
143
144
145
146
147
148
                $pp = get_config('docroot') . 'artefact/' . $bits[0]  . '/blocktype/' . $bits[1];
            }
            validate_plugin($pt, $pn, $pp);
            $plugins[] = explode('.', $name);
        }
        catch (InstallationException $_e) {
149
            log_warn("Plugin $pt $pn is not installable: " . $_e->GetMessage());
150
        }
151
152
153
154
155
    }
    else {
        foreach ($pluginstocheck as $plugin) {
            $dirhandle = opendir(get_config('docroot') . $plugin);
            while (false !== ($dir = readdir($dirhandle))) {
156
                if (strpos($dir, '.') === 0 or 'CVS' == $dir) {
157
158
159
160
161
                    continue;
                }
                if (!is_dir(get_config('docroot') . $plugin . '/' . $dir)) {
                    continue;
                }
162
163
164
165
166
                try {
                    validate_plugin($plugin, $dir);
                    $plugins[] = array($plugin, $dir);
                }
                catch (InstallationException $_e) {
167
                    log_warn("Plugin $plugin $dir is not installable: " . $_e->GetMessage());
168
169
170
                }

                if ($plugin == 'artefact') { // go check it for blocks as well
171
                    $btlocation = get_config('docroot') . $plugin . '/' . $dir . '/blocktype';
172
                    if (!is_dir($btlocation)) {
173
                        continue;
Elliot Pahl's avatar
Elliot Pahl committed
174
                    }
175
176
                    $btdirhandle = opendir($btlocation);
                    while (false !== ($btdir = readdir($btdirhandle))) {
177
                        if (strpos($btdir, '.') === 0 or 'CVS' == $btdir) {
178
179
                            continue;
                        }
180
                        if (!is_dir(get_config('docroot') . $plugin . '/' . $dir . '/blocktype/' . $btdir)) {
181
182
183
                            continue;
                        }
                        $plugins[] = array('blocktype', $dir . '/' . $btdir);
184
185
                    }
                }
186
187
188
189
190
191
192
193
194
195
            }
        }
    }

    foreach ($plugins as $plugin) {
        $plugintype = $plugin[0];
        $pluginname = $plugin[1];
        $pluginpath = "$plugin[0]/$plugin[1]";
        $pluginkey  = "$plugin[0].$plugin[1]";

196
197
198
199
200
201
        if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
            // sigh.. we're a bit special...
            $bits = explode('/', $pluginname);
            $pluginpath = 'artefact/' . $bits[0] . '/blocktype/' . $bits[1];
        }

202
203
204
        // Don't try to get the plugin info if we are installing - it will
        // definitely fail
        $pluginversion = 0;
205
206
207
208
209
210
211
212
213
        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) {
214
215
216
                $pluginversion = $installed->version;
                $pluginrelease =  $installed->release;
            }
217
        }
218
219

        $config = new StdClass;
220
221
222
        require(get_config('docroot') . $pluginpath . '/version.php');
        if (isset($config->disablelogin) && !empty($config->disablelogin)) {
            $disablelogin = true;
223
224
225
        }

        if (empty($pluginversion)) {
226
227
228
            if (empty($installing) && $pluginkey != $name) {
                continue;
            }
229
230
231
232
            $plugininfo = new StdClass;
            $plugininfo->install = true;
            $plugininfo->to = $config->version;
            $plugininfo->torelease = $config->release;
233
234
235
236
237
238
            if (property_exists($config, 'requires_config')) {
                $plugininfo->requires_config = $config->requires_config;
            }
            if (property_exists($config, 'requires_parent')) {
                $plugininfo->requires_parent = $config->requires_parent;
            }
239
240
241
            $toupgrade[$pluginkey] = $plugininfo;
        }
        else if ($config->version > $pluginversion) {
242
243
244
245
246
            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))");
247
            }
248
249
250
251
252
253
            $plugininfo = new StdClass;
            $plugininfo->upgrade = true;
            $plugininfo->from = $pluginversion;
            $plugininfo->fromrelease = $pluginrelease;
            $plugininfo->to = $config->version;
            $plugininfo->torelease = $config->release;
254
255
256
257
258
259
            if (property_exists($config, 'requires_config')) {
                $plugininfo->requires_config = $config->requires_config;
            }
            if (property_exists($config, 'requires_parent')) {
                $plugininfo->requires_parent = $config->requires_parent;
            }
260
261
262
263
264
265
266
267
268
269
270
            $toupgrade[$pluginkey] = $plugininfo;
        }
    }

    // if we've just asked for one, don't return an array...
    if (!empty($name) && count($toupgrade) == 1) {
        $upgrade = new StdClass;
        $upgrade->name = $name;
        foreach ((array)$toupgrade[$name] as $key => $value) {
            $upgrade->{$key} = $value;
        }
271
        $upgrade->disablelogin = $disablelogin;
272
273
        return $upgrade;
    }
274
    $toupgrade['disablelogin'] = $disablelogin;
275
276
277
    if (count($toupgrade) == 1) {
        $toupgrade = array();
    }
278
    uksort($toupgrade, 'sort_upgrades');
279
280
281
    return $toupgrade;
}

282
283
284
285
286
/**
 * Upgrades the core system to given upgrade version.
 *
 * @param object $upgrade   The version to upgrade to
 * @return bool             Whether the upgrade succeeded or not
287
 * @throws SQLException     If the upgrade failed due to a database error
288
 */
289
290
291
function upgrade_core($upgrade) {
    global $db;

292
    $location = get_config('libroot') . 'db/';
Penny Leach's avatar
Penny Leach committed
293
294

    db_begin();
295
296

    if (!empty($upgrade->install)) {
297
        install_from_xmldb_file($location . 'install.xml');
298
299
300
    }
    else {
        require_once($location . 'upgrade.php');
Penny Leach's avatar
Penny Leach committed
301
        xmldb_core_upgrade($upgrade->from);
302
303
    }

Penny Leach's avatar
Penny Leach committed
304
305
    set_config('version', $upgrade->to);
    set_config('release', $upgrade->torelease);
Elliot Pahl's avatar
Elliot Pahl committed
306

307
    if (!empty($upgrade->install)) {
Penny Leach's avatar
Penny Leach committed
308
        core_postinst();
309
    }
310

Penny Leach's avatar
Penny Leach committed
311
312
    db_commit();
    return true;
313
314
}

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
 * 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);

    db_commit();
    return true;
}

335
336
337
/**
 * Upgrades the plugin to a new version
 *
338
339
340
341
 * Note: This function is sometimes executed during upgrades from
 * ancient databases.  Avoid rash assumptions about what's installed
 * or these upgrades may fail.
 *
342
343
 * @param object $upgrade   Information about the plugin to upgrade
 * @return bool             Whether the upgrade succeeded or not
344
 * @throws SQLException     If the upgrade failed due to a database error
345
 */
346
347
348
349
350
351
352
353
function upgrade_plugin($upgrade) {
    global $db;

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

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

354
355
    if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
        list($artefactplugin, $blocktypename) = explode('/', $pluginname);
356
357
358
359
360
361
        $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
362
    }
363

364
    db_begin();
365
366
367

    if (!empty($upgrade->install)) {
        if (is_readable($location . 'install.xml')) {
368
            install_from_xmldb_file($location . 'install.xml');
369
370
371
372
373
        }
    }
    else {
        if (is_readable($location .  'upgrade.php')) {
            require_once($location . 'upgrade.php');
374
375
376
            if (!$function($upgrade->from)) {
                throw new InstallationException("Failed to run " . $function . " (check logs for errors)");
            }
377
378
379
380
381
382
383
        }
    }

    $installed = new StdClass;
    $installed->name = $pluginname;
    $installed->version = $upgrade->to;
    $installed->release = $upgrade->torelease;
384
385
386
387
388
389
390
391
    if ($plugintype == 'blocktype') {
        if (!empty($blocktypename)) {
            $installed->name = $blocktypename;
        }
        if (!empty($artefactplugin)) { // blocks come from artefactplugins.
            $installed->artefactplugin = $artefactplugin;
        }
    }
392
393
394
395
396
397
    if (property_exists($upgrade, 'requires_config')) {
        $installed->requires_config = $upgrade->requires_config;
    }
    if (property_exists($upgrade, 'requires_parent')) {
        $installed->requires_parent = $upgrade->requires_parent;
    }
398
    $installtable = $plugintype . '_installed';
399
400
401

    if (!empty($upgrade->install)) {
        insert_record($installtable,$installed);
Elliot Pahl's avatar
Elliot Pahl committed
402
    }
403
404
405
406
407
    else {
        update_record($installtable, $installed, 'name');
    }

    // postinst stuff...
Nigel McNie's avatar
Nigel McNie committed
408
    safe_require($plugintype, $pluginname);
409
    $pcname = generate_class_name($plugintype, $installed->name);
410
411
412
413
414
415
416
417
418
419
420

    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;
421
            $table = $plugintype . '_cron';
422
423
424
            if (!empty($upgrade->install)) {
                $new = true;
            }
425
            else if (!record_exists($table, 'plugin', $pluginname, 'callfunction', $cron->callfunction)) {
426
427
428
429
                $new = true;
            }
            $cron->plugin = $pluginname;
            if (!empty($new)) {
430
                insert_record($table, $cron);
431
432
            }
            else {
433
                update_record($table, $cron, array('plugin', 'callfunction'));
434
435
436
            }
        }
    }
Elliot Pahl's avatar
Elliot Pahl committed
437

438
439
440
441
    if ($events = call_static_method($pcname, 'get_event_subscriptions')) {
        foreach ($events as $event) {
            $event = (object)$event;

442
            if (!record_exists('event_type', 'name', $event->event)) {
443
444
445
446
447
448
449
450
451
                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;
452
            $table = $plugintype . '_event_subscription';
453
            $block = blocktype_namespaced_to_single($pluginname);
454
            if (empty($upgrade->install)) {
455
                $exists = get_record($table, 'plugin' , $block, 'event', $event->event);
456
            }
457
            $event->plugin = $block;
458
            if (empty($exists)) {
459
                insert_record($table, $event);
460
461
            }
            else {
462
                update_record($table, $event, array('id' => $exists->id));
463
464
465
466
            }
        }
    }

467
468
469
470
471
472
473
474
    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));
            }
            $activity->plugintype = $plugintype;
            $activity->pluginname = $pluginname;
475
476
477
478
479
            $where = (object) array(
                'name'       => $activity->name,
                'plugintype' => $plugintype,
                'pluginname' => $pluginname,
            );
480
            // Work around the fact that insert_record cached the columns that
481
482
483
            // _were_ in the activity_type table before it was upgraded
            global $INSERTRECORD_NOCACHE;
            $INSERTRECORD_NOCACHE = true;
484
            ensure_record_exists('activity_type', $where, $activity);
485
            unset($INSERTRECORD_NOCACHE);
486
487
488
        }
    }

489
490
     // install artefact types
    if ($plugintype == 'artefact') {
491
492
493
        if (!is_callable(array($pcname, 'get_artefact_types'))) {
            throw new InstallationException("Artefact plugin $pcname must implement get_artefact_types and doesn't");
        }
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
        $types = call_static_method($pcname, 'get_artefact_types');
        $ph = array();
        if (is_array($types)) {
            foreach ($types as $type) {
                $ph[] = '?';
                if (!record_exists('artefact_installed_type', 'plugin', $pluginname, 'name', $type)) {
                    $t = new StdClass;
                    $t->name = $type;
                    $t->plugin = $pluginname;
                    insert_record('artefact_installed_type',$t);
                }
            }
            $select = '(plugin = ? AND name NOT IN (' . implode(',', $ph) . '))';
            delete_records_select('artefact_installed_type', $select,
                                  array_merge(array($pluginname),$types));
        }
    }
Elliot Pahl's avatar
Elliot Pahl committed
511

512
513
514
    // install blocktype categories.
    if ($plugintype == 'blocktype' && get_config('installed')) {
        install_blocktype_categories_for_plugin($pluginname);
515
        install_blocktype_viewtypes_for_plugin($pluginname);
516
517
    }

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

521
522
    db_commit();
    return true;
523
524
525
526
527
528
529
}

function core_postinst() {
    $status = true;
    $pages = site_content_pages();
    $now = db_format_timestamp(time());
    foreach ($pages as $name) {
Donal McMullan's avatar
Donal McMullan committed
530
        $page = new stdClass();
531
532
533
534
535
536
537
538
        $page->name = $name;
        $page->ctime = $now;
        $page->mtime = $now;
        $page->content = get_string($page->name . 'defaultcontent', 'install');
        if (!insert_record('site_content',$page)) {
            $status = false;
        }
    }
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570

    // Attempt to create session directories
    $sessionpath = get_config('dataroot') . 'sessions';
    if (check_dir_exists($sessionpath)) {
        // Create three levels of directories, named 0-9, a-f
        $characters = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
        foreach ($characters as $c1) {
            if (check_dir_exists("$sessionpath/$c1")) {
                foreach ($characters as $c2) {
                    if (check_dir_exists("$sessionpath/$c1/$c2")) {
                        foreach ($characters as $c3) {
                            if (!check_dir_exists("$sessionpath/$c1/$c2/$c3")) {
                                $status = false;
                                break(3);
                            }
                        }
                    }
                    else {
                        $status = false;
                        break(2);
                    }
                }
            }
            else {
                $status = false;
                break;
            }
        }
    }
    else {
        $status = false;
    }
571
572
573
574

    // Set default search plugin
    set_config('searchplugin', 'internal');

575
    set_config('lang', 'en.utf8');
576
    set_config('installation_key', get_random_key());
577
    set_config('installation_time', $now);
578
    set_config('stats_installation_time', $now);
579

580
581
582
583
584
585
586
    // Pre-define SMTP settings
    set_config('smtphosts', '');
    set_config('smtpport', '');
    set_config('smtpuser', '');
    set_config('smtppass', '');
    set_config('smtpsecure', '');

587
588
589
590
591
592
593
594
595
    // 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);

596
597
598
599
600
    $table = new XMLDBTable('institution');
    $key = new XMLDBKey('logofk');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('logo'), 'artefact', array('id'));
    add_key($table, $key);

601
602
    // PostgreSQL supports indexes over functions of columns, MySQL does not. 
    // We make use if this if we can
603
    if (is_postgres()) {
604
        // Improve the username index
605
606
        execute_sql('DROP INDEX {usr_use_uix}');
        execute_sql('CREATE UNIQUE INDEX {usr_use_uix} ON {usr}(LOWER(username))');
607

608
609
610
611
612
613
614
615
616
        // 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))');

617
618
        // Only one profile view per user
        execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
619
620
    }

621
622
623
624
625
626
627
628
629
630
631
    // 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)
    )');
632
633
634
635
    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
    execute_sql('ALTER TABLE {view_access} ADD CHECK (
637
638
639
640
641
        (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)
642
    )');
643

644
    set_antispam_defaults();
645
    reload_html_filters();
646
647
648
649
650
651
652
653
654
655
656

    // Default set of sites from which iframe content can be embedded
    $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',
657
        'voki.com/php/'                            => 'Voki',
658
659
660
661
662
663
664
    );
    $iframedomains = array(
        'YouTube'      => 'www.youtube.com',
        'Vimeo'        => 'vimeo.com',
        'SlideShare'   => 'www.slideshare.net',
        'Glogster'     => 'www.glogster.com',
        'WikiEducator' => 'wikieducator.org',
665
        'Voki'         => 'voki.com',
666
667
668
    );
    update_safe_iframes($iframesources, $iframedomains);

669
    return $status;
670
671
}

672
function core_install_lastcoredata_defaults() {
673
    global $USER;
674
    db_begin();
675
    $institution = new StdClass;
676
677
678
    $institution->name = 'mahara';
    $institution->displayname = 'No Institution';
    $institution->authplugin  = 'internal';
679
    $institution->theme  = 'default';
680
    $institution->priority = 0;
681
    insert_record('institution', $institution);
682

683
    $auth_instance = new StdClass;
684
    $auth_instance->instancename  = 'Internal';
685
    $auth_instance->priority='1';
686
687
    $auth_instance->institution   = 'mahara';
    $auth_instance->authname      = 'internal';
688
689
    $auth_instance->id = insert_record('auth_instance', $auth_instance, 'id', true);

690
691
692
693
694
695
696
697
698
    // Insert the root user
    $user = new StdClass;
    $user->id = 0;
    $user->username = 'root';
    $user->password = '*';
    $user->salt = '*';
    $user->firstname = 'System';
    $user->lastname = 'User';
    $user->email = 'root@example.org';
699
    $user->quota = get_config_plugin('artefact', 'file', 'defaultquota');
700
    $user->authinstance = $auth_instance->id;
701

702
703
    if (is_mysql()) { // gratuitous mysql workaround
        $newid = insert_record('usr', $user, 'id', true);
704
        set_field('usr', 'id', 0, 'id', $newid);
705
        execute_sql('ALTER TABLE {usr} AUTO_INCREMENT=1');
706
    }
707
708
709
    else {
        insert_record('usr', $user);
    }
710

711
    require_once('group.php');
712
    install_system_profile_view();
713
    install_system_dashboard_view();
714
    install_system_grouphomepage_view();
715

716
    // Insert the admin user
717
718
    $user = new StdClass;
    $user->username = 'admin';
719
    $user->salt = auth_get_random_salt();
720
    $user->password = crypt('mahara', '$2a$' . get_config('bcrypt_cost') . '$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 22));
721
    $user->password = substr($user->password, 0, 7) . substr($user->password, 7+22);
722
    $user->authinstance = $auth_instance->id;
723
724
725
726
727
    $user->passwordchange = 1;
    $user->admin = 1;
    $user->firstname = 'Admin';
    $user->lastname = 'User';
    $user->email = 'admin@example.org';
728
    $user->quota = get_config_plugin('artefact', 'file', 'defaultquota');
729
730
731
732
    $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);
733
    handle_event('createuser', $user);
734
    activity_add_admin_defaults(array($user->id));
735
    db_commit();
736
737

    // if we're installing, set up the block categories here and then poll the plugins.
Elliot Pahl's avatar
Elliot Pahl committed
738
    // if we're upgrading this happens somewhere else.  This is because of dependency issues around
739
740
    // the order of installation stuff.

741
    install_blocktype_extras();
742
743
}

744
745
746
function core_install_firstcoredata_defaults() {
    // Install the default institution
    db_begin();
Elliot Pahl's avatar
Elliot Pahl committed
747

748
    set_config('session_timeout', 86400);
749
    set_config('sitename', 'Mahara');
750
    set_config('defaultaccountinactivewarn', 604800);
751
    set_config('creategroups', 'all');
752
    set_config('createpublicgroups', 'all');
753
    set_config('allowpublicviews', 1);
754
    set_config('allowpublicprofiles', 1);
755
    set_config('generatesitemap', 1);
756
757
758
    set_config('showselfsearchsideblock', 0);
    set_config('showtagssideblock', 1);
    set_config('tagssideblockmaxtags', 20);
759
    set_config('usersallowedmultipleinstitutions', 1);
760
761
    set_config('viewmicroheaders', 0);
    set_config('userscanchooseviewthemes', 0);
762
    set_config('anonymouscomments', 1);
763
    set_config('homepageinfo', 1);
764
    set_config('showonlineuserssideblock', 1);
765
    set_config('footerlinks', serialize(array('privacystatement', 'about', 'contactus')));
766
    set_config('searchusernames', 1);
767
    set_config('onlineuserssideblockmaxusers', 10);
768
    set_config('loggedinprofileviewaccess', 1);
769
    set_config('dropdownmenu', 0);
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796

    // install the applications
    $app = new StdClass;
    $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',
797
        'userjoinsgroup',
798
799
        'saveartefact',
        'deleteartefact',
800
        'deleteartefacts',
801
802
        'saveview',
        'deleteview',
803
        'blockinstancecommit',
804
805
806
807
        'addfriend',
        'removefriend',
        'addfriendrequest',
        'removefriendrequest',
Richard Mansfield's avatar
Richard Mansfield committed
808
        'creategroup',
809
810
811
812
813
814
815
816
    );

    foreach ($eventtypes as $et) {
        $e = new StdClass;
        $e->name = $et;
        insert_record('event_type', $e);
    }

817
818
819
820
821
    // install the core event subscriptions
    $subs = array(
        array(
            'event'        => 'createuser',
            'callfunction' => 'activity_set_defaults',
822
        ),
823
824
825
826
        array(
            'event'        => 'createuser',
            'callfunction' => 'add_user_to_autoadd_groups',
        ),
827
828
829
830
831
    );

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

833
834
835
836
837
838
839
840
841
842
    // install the activity types
    $activitytypes = array(
        array('maharamessage', 0, 0),
        array('usermessage', 0, 0),
        array('watchlist', 0, 1),
        array('viewaccess', 0, 1),
        array('contactus', 1, 1),
        array('objectionable', 1, 1),
        array('virusrepeat', 1, 1),
        array('virusrelease', 1, 1),
843
        array('institutionmessage', 0, 0),
844
        array('groupmessage', 0, 1),
845
846
847
848
849
850
851
852
853
854
855
856
    );

    foreach ($activitytypes as $at) {
        $a = new StdClass;
        $a->name = $at[0];
        $a->admin = $at[1];
        $a->delay = $at[2];
        insert_record('activity_type', $a);
    }

    // install the cronjobs...
    $cronjobs = array(
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
        'rebuild_artefact_parent_cache_dirty'       => array('*', '*', '*', '*', '*'),
        'rebuild_artefact_parent_cache_complete'    => array('0', '4', '*', '*', '*'),
        'auth_clean_partial_registrations'          => array('5', '0', '*', '*', '*'),
        'auth_handle_account_expiries'              => array('5', '10', '*', '*', '*'),
        'auth_handle_institution_expiries'          => array('5', '9', '*', '*', '*'),
        'activity_process_queue'                    => array('*/5', '*', '*', '*', '*'),
        'auth_remove_old_session_files'             => array('30', '20', '*', '*', '*'),
        'recalculate_quota'                         => array('15', '2', '*', '*', '*'),
        'import_process_queue'                      => array('*/5', '*', '*', '*', '*'),
        'cron_send_registration_data'               => array(rand(0, 59), rand(0, 23), '*', '*', rand(0, 6)),
        'export_cleanup_old_exports'                => array('0', '3,15', '*', '*', '*'),
        'import_cleanup_old_imports'                => array('0', '4,16', '*', '*', '*'),
        'cron_site_data_weekly'                     => array('55', '23', '*', '*', '6'),
        'cron_site_data_daily'                      => array('51', '23', '*', '*', '*'),
        'cron_check_for_updates'                    => array(rand(0, 59), rand(0, 23), '*', '*', '*'),
        'cron_clean_internal_activity_notifications'=> array(45, 22, '*', '*', '*'),
873
        'cron_sitemap_daily'                        => array(0, 1, '*', '*', '*'),
874
        'file_cleanup_old_cached_files'             => array(0, 1, '*', '*', '*'),
875
        'user_login_tries_to_zero'                  => array('*/5', '*', '*', '*', '*'),
876
        'cron_institution_registration_data'        => array(rand(0, 59), rand(0, 23), '*', '*', rand(0, 6)),
877
878
879
880
881
882
883
884
885
886
887
    );
    foreach ($cronjobs as $callfunction => $times) {
        $cron = new StdClass;
        $cron->callfunction = $callfunction;
        $cron->minute       = $times[0];
        $cron->hour         = $times[1];
        $cron->day          = $times[2];
        $cron->month        = $times[3];
        $cron->dayofweek    = $times[4];
        insert_record('cron', $cron);
    }
Elliot Pahl's avatar
Elliot Pahl committed
888

889
    // install the view column widths
890
    install_view_column_widths();
891

892
    $viewtypes = array('dashboard', 'portfolio', 'profile', 'grouphomepage');
893
894
895
896
897
    foreach ($viewtypes as $vt) {
        insert_record('view_type', (object)array(
            'type' => $vt,
        ));
    }
898
899
900
901
    db_commit();
}


Elliot Pahl's avatar
Elliot Pahl committed
902
903
904
/**
 * xmldb will pass us the xml file and we can perform any substitution as necessary
 */
905
function local_xmldb_contents_sub(&$contents) {
906
    // the main install.xml file needs to sub in plugintype tables.
907
908
909
910
911
912
913
914
915
    $searchstring = '<!-- PLUGIN_TYPE_SUBSTITUTION -->';
    if (strstr($contents, $searchstring) === 0) {
        return;
    }
    // ok, we're in the main file and we need to install all the plugin tables
    // get the basic skeleton structure
    $plugintables = file_get_contents(get_config('docroot') . 'lib/db/plugintables.xml');
    $tosub = '';
    foreach (plugin_types() as $plugin) {
Elliot Pahl's avatar
Elliot Pahl committed
916
        // any that want their own stuff can put it in docroot/plugintype/lib/db/plugintables.xml
917
        //- like auth is a bit special
918
919
920
        $specialcase = get_config('docroot') . $plugin . '/plugintables.xml';
        if (is_readable($specialcase)) {
            $tosub .= file_get_contents($specialcase) . "\n";
Elliot Pahl's avatar
Elliot Pahl committed
921
        }
922
        else {
923
924
925
926
927
928
929
930
            $replaced = '';
            // look for tables to put at the start...
            $pretables = get_config('docroot') . $plugin . '/beforetables.xml';
            if (is_readable($pretables)) {
                $replaced = file_get_contents($pretables) . "\n";
            }

            // perform any additional once off substitutions
931
932
            require_once(get_config('docroot') . $plugin . '/lib.php');
            if (method_exists(generate_class_name($plugin), 'extra_xmldb_substitution')) {
933
                $replaced  .= call_static_method(generate_class_name($plugin), 'extra_xmldb_substitution', $plugintables);
934
            }
935
            else {
936
                $replaced .= $plugintables;
937
            }
938
            $tosub .= str_replace('__PLUGINTYPE__', $plugin, $replaced) . "\n";
939
            // look for any tables to put at the end..
940
941
942
            $extratables = get_config('docroot') . $plugin . '/extratables.xml';
            if (is_readable($extratables)) {
                $tosub .= file_get_contents($extratables) . "\n";
943
            }
944
945
        }
    }
946
    $contents = str_replace($searchstring, $tosub, $contents);
947
948
}

949
950
951
952
953
954
955
956

/**
 * validates a plugin for installation
 * @throws InstallationException
*/
function validate_plugin($plugintype, $pluginname, $pluginpath='') {

    if (empty($pluginpath)) {
957
        $pluginpath = get_config('docroot') . $plugintype . '/' . $pluginname;
958
959
960
961
    }
    if (!file_exists($pluginpath . '/version.php')) {
        throw new InstallationException(get_string('versionphpmissing', 'error', $plugintype, $pluginname));
    }
962
963
964
965
966
967
    safe_require($plugintype, $pluginname);
    $classname = generate_class_name($plugintype, $pluginname);
    if (!class_exists($classname)) {
        throw new InstallationException(get_string('classmissing', 'error', $classname, $plugintype, $pluginname));
    }
    require_once(get_config('docroot') . $plugintype . '/lib.php');
968
969
970
971
972
    $funname = $plugintype . '_check_plugin_sanity';
    if (function_exists($funname)) {
        $funname($pluginname);
    }
}
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990

/*
* the order things are installed/upgraded in matters
*/

function sort_upgrades($k1, $k2) {
    if ($k1 == 'core') {
        return -1;
    }
    else if ($k2 == 'core') {
        return 1;
    }
    else if ($k1 == 'firstcoredata') {
        return -1;
    }
    else if ($k2 == 'firstcoredata') {
        return 1;
    }
991
992
993
994
995
996
997
998
999
1000
1001
1002
    else if ($k1 == 'localpreinst') {
        return -1;
    }
    else if ($k2 == 'localpreinst') {
        return 1;
    }
    else if ($k1 == 'localpostinst') {
        return 1;
    }
    else if ($k2 == 'localpostinst') {
        return -1;
    }
1003
1004
1005
1006
1007
1008
    else if ($k1 == 'lastcoredata') {
        return 1;
    }
    else if ($k2 == 'lastcoredata') {
        return -1;
    }
1009
1010
1011
1012
    // else obey the order plugin types returns (strip off plugintype. from the start)
    $weight1 = array_search(substr($k1, 0, strpos($k1, '.')), plugin_types());
    $weight2 = array_search(substr($k2, 0, strpos($k2, '.')), plugin_types());
    return ($weight1 > $weight2);
1013
}
1014

1015
/** blocktype categories the system exports (including artefact categories)
1016
*/
1017
function get_blocktype_categories() {
1018
    return array('fileimagevideo', 'blog', 'general', 'internal', 'resume', 'external');
1019
1020
1021
1022
1023
}

function install_blocktype_categories_for_plugin($blocktype) {
    safe_require('blocktype', $blocktype);
    $blocktype = blocktype_namespaced_to_single($blocktype);
1024
    $catsinstalled = get_column('blocktype_category', 'name');
1025
1026
1027
1028
    db_begin();
    delete_records('blocktype_installed_category', 'blocktype', $blocktype);
    if ($cats = call_static_method(generate_class_name('blocktype', $blocktype), 'get_categories')) {
        foreach ($cats as $cat) {
1029
1030
1031
1032
1033
1034
            if (in_array($cat, $catsinstalled)) {
                insert_record('blocktype_installed_category', (object)array(
                    'blocktype' => $blocktype,
                    'category' => $cat
                ));
            }
1035
1036
1037
1038
1039
        }
    }
    db_commit();
}

1040
1041
1042
function install_blocktype_viewtypes_for_plugin($blocktype) {
    safe_require('blocktype', $blocktype);
    $blocktype = blocktype_namespaced_to_single($blocktype);
1043
    $vtinstalled = get_column('view_type', 'type');
1044
1045
1046
1047
    db_begin();
    delete_records('blocktype_installed_viewtype', 'blocktype', $blocktype);
    if ($viewtypes = call_static_method(generate_class_name('blocktype', $blocktype), 'get_viewtypes')) {
        foreach($viewtypes as $vt) {
1048
1049
1050
1051
1052
1053
            if (in_array($vt, $vtinstalled)) {
                insert_record('blocktype_installed_viewtype', (object)array(
                    'blocktype' => $blocktype,
                    'viewtype'  => $vt,
                ));
            }
1054
1055
1056
1057
1058
1059
        }
    }
    db_commit();
}

function install_blocktype_extras() {
1060
1061
    db_begin();

1062
    $categories = get_blocktype_categories();
1063
    $installedcategories = get_column('blocktype_category', 'name');
1064
    $sort = empty($installedcategories) ? -1 : get_record_sql('SELECT MAX(sort) AS maxsort FROM {blocktype_category}')->maxsort;
1065
1066
1067

    if ($toinstall = array_diff($categories, $installedcategories)) {
        foreach ($toinstall as $i) {
1068
            insert_record('blocktype_category', (object)array('name' => $i, 'sort' => (++$sort)));
1069
1070
1071
1072
1073
1074
1075
        }
    }

    db_commit();


    // poll all the installed blocktype plugins and ask them what categories they export
1076
    if ($blocktypes = plugins_installed('blocktype', true)) {
1077
1078
        foreach ($blocktypes as $bt) {
            install_blocktype_categories_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
1079
            install_blocktype_viewtypes_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
1080
1081
1082
1083
        }
    }
}

1084
/**
Elliot Pahl's avatar
Elliot Pahl committed
1085
 * Installs all the allowed column widths for views. Used when installing core
1086
1087
1088
1089
 * defaults, and also when upgrading from 0.8 to 0.9
 */
function install_view_column_widths() {
    db_begin();
1090
    require_once('view.php');
1091
1092

    $layout = new StdClass;
1093
    foreach (View::$layouts as $column => $widths) {
1094
1095
1096
1097
1098
1099
1100
1101
1102
        foreach ($widths as $width) {
            $layout->columns = $column;
            $layout->widths = $width;
            insert_record('view_layout', $layout);
        }
    }
    db_commit();
}

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
/**
 * Reload htmlpurifier filters from the XML configuration file.
 */
function reload_html_filters() {
    require_once('xmlize.php');

    $newlist = xmlize(file_get_contents(get_config('libroot') . 'htmlpurifiercustom/filters.xml'));
    $filters = $newlist['filters']['#']['filter'];
    foreach ($filters as &$f) {
        $f = (object) array(
            'site' => $f['#']['site'][0]['#'],
            'file' => $f['#']['filename'][0]['#']
        );
    }
    set_config('filters', serialize($filters));
1118
    log_info('Enabled ' . count($filters) . ' HTML filters.');
1119
}
1120

1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134