upgrade.php 29.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
/**
 * This program is part of Mahara
 *
 *  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 2 of the License, or
 *  (at your option) any later version.
 *
 *  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.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    mahara
20
21
 * @subpackage core
 * @author     Penny Leach <penny@catalyst.net.nz>
22
23
24
25
26
27
28
29
30
31
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006,2007 Catalyst IT Ltd http://catalyst.net.nz
 *
 */

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

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


/**
36
37
38
39
40
 * This function checks core and plugins for which need to be upgraded/installed
 *
 * @param string $name The name of the plugin to check. If no name is specified,
 *                     all plugins are checked.
 * @return array of objects
41
 */
42
function check_upgrades($name=null) {
43

44
45
46
47
    $pluginstocheck = plugin_types();

    $toupgrade = array();
    $installing = false;
48
    $disablelogin = false;
49
50

    require('version.php');
51
52
53
    if (isset($config->disablelogin) && !empty($config->disablelogin)) {
        $disablelogin = true;
    }
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    // check core first...
    if (empty($name) || $name == 'core') {
        try {
            $coreversion = get_config('version');
        } 
        catch (Exception $e) {
            $coreversion = 0;
        }
        if (empty($coreversion)) {
            $core = new StdClass;
            $core->install = true;
            $core->to = $config->version;
            $core->torelease = $config->release;
            $toupgrade['core'] = $core;
            $installing = true;
        } 
        else if ($config->version > $coreversion) {
71
72
73
            $corerelease = get_config('release');
            if (isset($config->minupgradefrom) && isset($config->minupgraderelease) 
                && $coreversion < $config->minupgradefrom) {
74
                throw new ConfigSanityException("Must upgrade to $config->minupgradefrom "
75
76
                                          . "($config->minupgraderelease) first "
                                          . " (you have $coreversion ($corerelease)");
77
            }
78
79
80
            $core = new StdClass;
            $core->upgrade = true;
            $core->from = $coreversion;
81
            $core->fromrelease = $corerelease;
82
83
84
85
86
87
            $core->to = $config->version;
            $core->torelease = $config->release;
            $toupgrade['core'] = $core;
        }
    }

88
    // If we were just checking if the core needed to be upgraded, we can stop here
89
    if ($name == 'core') {
90
        $toupgrade['core']->disablelogin = $disablelogin;
91
92
93
94
95
        return $toupgrade['core'];
    }

    $plugins = array();
    if (!empty($name)) {
96
97
98
99
100
101
        try {
            $bits = explode('.', $name);
            $pt = $bits[0];
            $pn = $bits[1];
            $pp = null;
            if ($pt == 'blocktype' && strpos($pn, '/') !== false) {
102
                $bits = explode('/', $pn);
103
104
105
106
107
108
                $pp = get_config('docroot') . 'artefact/' . $bits[0]  . '/blocktype/' . $bits[1];
            }
            validate_plugin($pt, $pn, $pp);
            $plugins[] = explode('.', $name);
        }
        catch (InstallationException $_e) {
109
            log_warn("Plugin $pt $pn is not installable: " . $_e->GetMessage());
110
        }
111
112
113
114
115
116
117
118
119
120
121
    }
    else {
        foreach ($pluginstocheck as $plugin) {
            $dirhandle = opendir(get_config('docroot') . $plugin);
            while (false !== ($dir = readdir($dirhandle))) {
                if (strpos($dir, '.') === 0) {
                    continue;
                }
                if (!is_dir(get_config('docroot') . $plugin . '/' . $dir)) {
                    continue;
                }
122
123
124
125
126
                try {
                    validate_plugin($plugin, $dir);
                    $plugins[] = array($plugin, $dir);
                }
                catch (InstallationException $_e) {
127
                    log_warn("Plugin $plugin $dir is not installable: " . $_e->GetMessage());
128
129
130
                }

                if ($plugin == 'artefact') { // go check it for blocks as well
131
                    $btlocation = get_config('docroot') . $plugin . '/' . $dir . '/blocktype';
132
                    if (!is_dir($btlocation)) {
133
                        continue;
134
135
136
137
138
139
                    }   
                    $btdirhandle = opendir($btlocation);
                    while (false !== ($btdir = readdir($btdirhandle))) {
                        if (strpos($btdir, '.') === 0) {
                            continue;
                        }
140
                        if (!is_dir(get_config('docroot') . $plugin . '/' . $dir . '/blocktype/' . $btdir)) {
141
142
143
                            continue;
                        }
                        $plugins[] = array('blocktype', $dir . '/' . $btdir);
144
145
                    }
                }
146
147
148
149
150
151
152
153
154
155
            }
        }
    }

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

156
157
158
159
160
161
        if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
            // sigh.. we're a bit special...
            $bits = explode('/', $pluginname);
            $pluginpath = 'artefact/' . $bits[0] . '/blocktype/' . $bits[1];
        }

162
163
164
        // Don't try to get the plugin info if we are installing - it will
        // definitely fail
        $pluginversion = 0;
165
166
167
168
169
170
171
172
173
        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) {
174
175
176
                $pluginversion = $installed->version;
                $pluginrelease =  $installed->release;
            }
177
        }
178
179

        $config = new StdClass;
180
181
182
        require(get_config('docroot') . $pluginpath . '/version.php');
        if (isset($config->disablelogin) && !empty($config->disablelogin)) {
            $disablelogin = true;
183
184
185
        }

        if (empty($pluginversion)) {
186
187
188
            if (empty($installing) && $pluginkey != $name) {
                continue;
            }
189
190
191
192
            $plugininfo = new StdClass;
            $plugininfo->install = true;
            $plugininfo->to = $config->version;
            $plugininfo->torelease = $config->release;
193
194
195
196
197
198
            if (property_exists($config, 'requires_config')) {
                $plugininfo->requires_config = $config->requires_config;
            }
            if (property_exists($config, 'requires_parent')) {
                $plugininfo->requires_parent = $config->requires_parent;
            }
199
200
201
            $toupgrade[$pluginkey] = $plugininfo;
        }
        else if ($config->version > $pluginversion) {
202
203
204
205
206
            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))");
207
            }
208
209
210
211
212
213
            $plugininfo = new StdClass;
            $plugininfo->upgrade = true;
            $plugininfo->from = $pluginversion;
            $plugininfo->fromrelease = $pluginrelease;
            $plugininfo->to = $config->version;
            $plugininfo->torelease = $config->release;
214
215
216
217
218
219
            if (property_exists($config, 'requires_config')) {
                $plugininfo->requires_config = $config->requires_config;
            }
            if (property_exists($config, 'requires_parent')) {
                $plugininfo->requires_parent = $config->requires_parent;
            }
220
221
222
223
224
225
226
227
228
229
230
            $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;
        }
231
        $upgrade->disablelogin = $disablelogin;
232
233
        return $upgrade;
    }
234
    $toupgrade['disablelogin'] = $disablelogin;
235
236
237
    if (count($toupgrade) == 1) {
        $toupgrade = array();
    }
238
    uksort($toupgrade, 'sort_upgrades');
239
240
241
    return $toupgrade;
}

242
243
244
245
246
/**
 * Upgrades the core system to given upgrade version.
 *
 * @param object $upgrade   The version to upgrade to
 * @return bool             Whether the upgrade succeeded or not
247
 * @throws SQLException     If the upgrade failed due to a database error
248
 */
249
250
251
function upgrade_core($upgrade) {
    global $db;

252
    $location = get_config('libroot') . 'db/';
Penny Leach's avatar
Penny Leach committed
253
254

    db_begin();
255
256

    if (!empty($upgrade->install)) {
Penny Leach's avatar
Penny Leach committed
257
        if (!install_from_xmldb_file($location . 'install.xml')) {
Penny Leach's avatar
Penny Leach committed
258
            throw new SQLException("Failed to upgrade core (check logs for xmldb errors)");
Penny Leach's avatar
Penny Leach committed
259
        }
260
261
262
    }
    else {
        require_once($location . 'upgrade.php');
Penny Leach's avatar
Penny Leach committed
263
        xmldb_core_upgrade($upgrade->from);
264
265
    }

Penny Leach's avatar
Penny Leach committed
266
267
    set_config('version', $upgrade->to);
    set_config('release', $upgrade->torelease);
268
269
    
    if (!empty($upgrade->install)) {
Penny Leach's avatar
Penny Leach committed
270
        core_postinst();
271
    }
272

Penny Leach's avatar
Penny Leach committed
273
274
    db_commit();
    return true;
275
276
}

277
278
279
280
281
/**
 * Upgrades the plugin to a new version
 *
 * @param object $upgrade   Information about the plugin to upgrade
 * @return bool             Whether the upgrade succeeded or not
282
 * @throws SQLException     If the upgrade failed due to a database error
283
 */
284
285
286
287
288
289
290
291
function upgrade_plugin($upgrade) {
    global $db;

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

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

292
293
294
295
    if ($plugintype == 'blocktype' && strpos($pluginname, '/') !== false) {
        list($artefactplugin, $blocktypename) = explode('/', $pluginname);
    }   

296
    $location = get_config('docroot') . $plugintype . '/' . $pluginname . '/db/';
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
    $db->StartTrans();

    if (!empty($upgrade->install)) {
        if (is_readable($location . 'install.xml')) {
            $status = install_from_xmldb_file($location . 'install.xml');
        }
        else {
            $status = true;
        }
    }
    else {
        if (is_readable($location .  'upgrade.php')) {
            require_once($location . 'upgrade.php');
            $function = 'xmldb_' . $plugintype . '_' . $pluginname . '_upgrade';
            $status = $function($upgrade->from);
        }
        else {
            $status = true;
        }
    }
    if (!$status || $db->HasFailedTrans()) {
        $db->CompleteTrans();
Penny Leach's avatar
Penny Leach committed
319
        throw new SQLException("Failed to upgrade $upgrade->name (check logs for xmldb errors)");
320
321
322
323
324
325
    }

    $installed = new StdClass;
    $installed->name = $pluginname;
    $installed->version = $upgrade->to;
    $installed->release = $upgrade->torelease;
326
327
328
329
330
331
332
333
    if ($plugintype == 'blocktype') {
        if (!empty($blocktypename)) {
            $installed->name = $blocktypename;
        }
        if (!empty($artefactplugin)) { // blocks come from artefactplugins.
            $installed->artefactplugin = $artefactplugin;
        }
    }
334
335
336
337
338
339
    if (property_exists($upgrade, 'requires_config')) {
        $installed->requires_config = $upgrade->requires_config;
    }
    if (property_exists($upgrade, 'requires_parent')) {
        $installed->requires_parent = $upgrade->requires_parent;
    }
340
    $installtable = $plugintype . '_installed';
341
342
343
344
345
346
347
348
349

    if (!empty($upgrade->install)) {
        insert_record($installtable,$installed);
    } 
    else {
        update_record($installtable, $installed, 'name');
    }

    // postinst stuff...
Nigel McNie's avatar
Nigel McNie committed
350
    safe_require($plugintype, $pluginname);
351
    $pcname = generate_class_name($plugintype, $installed->name);
352
353
354
355
356
357
358
359
360
361
362
363
364

    if ($crons = call_static_method($pcname, 'get_cron')) {
        foreach ($crons as $cron) {
            $cron = (object)$cron;
            if (empty($cron->callfunction)) {
                $db->RollbackTrans();
                throw new InstallationException("cron for $pcname didn't supply function name");
            }
            if (!is_callable(array($pcname, $cron->callfunction))) {
                $db->RollbackTrans();
                throw new InstallationException("cron $cron->callfunction for $pcname supplied but wasn't callable");
            }
            $new = false;
365
            $table = $plugintype . '_cron';
366
367
368
            if (!empty($upgrade->install)) {
                $new = true;
            }
369
            else if (!record_exists($table, 'plugin', $pluginname, 'callfunction', $cron->callfunction)) {
370
371
372
373
                $new = true;
            }
            $cron->plugin = $pluginname;
            if (!empty($new)) {
374
                insert_record($table, $cron);
375
376
            }
            else {
377
                update_record($table, $cron, array('plugin', 'callfunction'));
378
379
380
381
382
383
384
385
            }
        }
    }
    
    if ($events = call_static_method($pcname, 'get_event_subscriptions')) {
        foreach ($events as $event) {
            $event = (object)$event;

386
            if (!record_exists('event_type', 'name', $event->event)) {
387
388
389
390
391
392
393
394
395
396
397
398
                $db->RollbackTrans();
                throw new InstallationException("event $event->event for $pcname doesn't exist!");
            }
            if (empty($event->callfunction)) {
                $db->RollbackTrans();
                throw new InstallationException("event $event->event for $pcname didn't supply function name");
            }
            if (!is_callable(array($pcname, $event->callfunction))) {
                $db->RollbackTrans();
                throw new InstallationException("event $event->event with function $event->callfunction for $pcname supplied but wasn't callable");
            }
            $exists = false;
399
            $table = $plugintype . '_event_subscription';
400
            if (empty($upgrade->install)) {
401
                $exists = get_record($table, 'plugin' , $pluginname, 'event', $event->event);
402
403
404
            }
            $event->plugin = $pluginname;
            if (empty($exists)) {
405
                insert_record($table, $event);
406
407
            }
            else {
408
                update_record($table, $event, array('id' => $exists->id));
409
410
411
412
            }
        }
    }

413
414
     // install artefact types
    if ($plugintype == 'artefact') {
415
416
417
        if (!is_callable(array($pcname, 'get_artefact_types'))) {
            throw new InstallationException("Artefact plugin $pcname must implement get_artefact_types and doesn't");
        }
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
        $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));
        }
434
435
436
437
        // install a blocktype category for this plugin
        if (get_config('installed') && !record_exists('blocktype_category', 'name', $pluginname)) {
            insert_record('blocktype_category', (object)array('name' => $pluginname));
        }
438
    }
439
    
440
441
442
443
444
    // install blocktype categories.
    if ($plugintype == 'blocktype' && get_config('installed')) {
        install_blocktype_categories_for_plugin($pluginname);
    }

445
446
    $prevversion = (empty($upgrade->install)) ? $upgrade->from : 0;
    call_static_method($pcname, 'postinst', $prevversion);
447
448
449
450
451
    
    if ($db->HasFailedTrans()) {
        $status = false;
    }
    $db->CompleteTrans();
452

453
    /*  they do themselves already
454
455
456
457
458
    // we have to do this after committing the current transaction because we call ourselves recursively...
    if ($plugintype == 'artefact' && get_config('installed')) {
        // only install associated blocktype plugins if we're not in the process of installing 
        if ($blocktypes = call_static_method($pcname, 'get_block_types')) {
            foreach ($blocktypes as $bt) {
459
460
461
                if ($upgrade = check_upgrades('blocktype.' . $pluginname . '/' . $bt)) {
                    upgrade_plugin($upgrade); 
                }
462
463
464
            }
        }
    }
465
    */
466
467
    
    return $status;
468
469
470
471
472
473
474
475

}

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
476
        $page = new stdClass();
477
478
479
480
481
482
483
484
        $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;
        }
    }
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516

    // 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;
    }
517
518
519
520

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

521
    set_config('lang', 'en.utf8');
522
    return $status;
523
524
}

525
function core_install_lastcoredata_defaults() {
526
    db_begin();
527
    $auth_instance = new StdClass;
528
529
530
531
    $institution->name = 'mahara';
    $institution->displayname = 'No Institution';
    $institution->authplugin  = 'internal';
    insert_record('institution', $institution);
532
533

    $auth_instance->instancename  = 'internal';
534
    $auth_instance->priority='1';
535
536
    $auth_instance->institution   = 'mahara';
    $auth_instance->authname      = 'internal';
537
    $auth_instance->id = insert_record('auth_instance', $auth_instance, 'id', true);
538
    $institution = new StdClass;
539

540
541
542
543
544
545
546
547
548
549
    // Insert the root user
    $user = new StdClass;
    $user->id = 0;
    $user->username = 'root';
    $user->password = '*';
    $user->salt = '*';
    $user->institution = 'mahara';
    $user->firstname = 'System';
    $user->lastname = 'User';
    $user->email = 'root@example.org';
550
    $user->quota = get_config_plugin('artefact', 'file', 'defaultquota');
551
552
    $user->authinstance = $auth_instance->id;
    $newid = insert_record('usr', $user, 'id', true);
553
554
555
556

    if ($newid > 0 && get_config('dbtype') == 'mysql') { // gratuitous mysql workaround
        set_field('usr', 'id', 0, 'id', $newid);
    }
557
558
559
560
561

    $user = new StdClass;
    $user->username = 'admin';
    $user->password = 'mahara';
    $user->institution = 'mahara';
562
    $user->authinstance = $auth_instance->id;
563
564
565
566
567
    $user->passwordchange = 1;
    $user->admin = 1;
    $user->firstname = 'Admin';
    $user->lastname = 'User';
    $user->email = 'admin@example.org';
568
    $user->quota = get_config_plugin('artefact', 'file', 'defaultquota');
569
570
571
572
573
574
    $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);
    set_config('installed', true);
    db_commit();
575
576
577
578
579
580
581

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

    install_blocktype_categories();

582
583
}

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
function core_install_firstcoredata_defaults() {
    // Install the default institution
    db_begin();
    
    set_config('session_timeout', 1800);
    set_config('sitename', 'Mahara');
    set_config('pathtofile', '/usr/bin/file');

    // 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',
        'saveartefact',
        'deleteartefact',
        'saveview',
        'deleteview',
    );

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

    // install the activity types
    $activitytypes = array(
        array('maharamessage', 0, 0),
        array('usermessage', 0, 0),
        array('feedback', 0, 0),
        array('watchlist', 0, 1),
        array('newview', 0, 1),
        array('viewaccess', 0, 1),
        array('contactus', 1, 1),
        array('objectionable', 1, 1),
        array('virusrepeat', 1, 1),
        array('virusrelease', 1, 1),
    );

    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(
        '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', '*', '*', '*'),
        'activity_process_queue'                 => array('*/5', '*', '*', '*', '*'),
    );
    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);
    }
    
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    // install the view column widths
    $layouts = array(
        2 => array(
            '50,50',
            '67,33',
            '33,67',
            ),
        3 => array(
            '33,33,33',
            '25,50,25',
            '15,70,15',
            ),
        4 => array(
            '25,25,25,25',
            '20,30,30,20',
            ),
    );
688

689
690
691
692
693
694
695
696
    $layout = new StdClass;
    foreach ($layouts as $column => $widths) {
        foreach ($widths as $width) {
            $layout->columns = $column;
            $layout->widths = $width;
            insert_record('view_layout', $layout);
        }
    }
697
698
699
700
701
702
703
    db_commit();
}


/** 
* xmldb will pass us the xml file and we can perform any substitution as necessary
*/ 
704
function local_xmldb_contents_sub(&$contents) {
705
    // the main install.xml file needs to sub in plugintype tables.
706
707
708
709
710
711
712
713
714
    $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) {
715
716
        // any that want their own stuff can put it in docroot/plugintype/lib/db/plugintables.xml 
        //- like auth is a bit special
717
718
719
720
721
        $specialcase = get_config('docroot') . $plugin . '/plugintables.xml';
        if (is_readable($specialcase)) {
            $tosub .= file_get_contents($specialcase) . "\n";
        } 
        else {
722
723
724
725
726
727
728
729
            $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
730
731
            require_once(get_config('docroot') . $plugin . '/lib.php');
            if (method_exists(generate_class_name($plugin), 'extra_xmldb_substitution')) {
732
                $replaced  .= call_static_method(generate_class_name($plugin), 'extra_xmldb_substitution', $plugintables);
733
            }
734
            else {
735
                $replaced .= $plugintables;
736
            }
737
            $tosub .= str_replace('__PLUGINTYPE__', $plugin, $replaced) . "\n";
738
            // look for any tables to put at the end..
739
740
741
            $extratables = get_config('docroot') . $plugin . '/extratables.xml';
            if (is_readable($extratables)) {
                $tosub .= file_get_contents($extratables) . "\n";
742
            }
743
744
        }
    }
745
    $contents = str_replace($searchstring, $tosub, $contents);
746
747
}

748
749
750
751
752
753
754
755

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

    if (empty($pluginpath)) {
756
        $pluginpath = get_config('docroot') . $plugintype . '/' . $pluginname;
757
758
759
760
    }
    if (!file_exists($pluginpath . '/version.php')) {
        throw new InstallationException(get_string('versionphpmissing', 'error', $plugintype, $pluginname));
    }
761
762
763
764
765
766
    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');
767
768
769
770
771
    $funname = $plugintype . '_check_plugin_sanity';
    if (function_exists($funname)) {
        $funname($pluginname);
    }
}
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795

/*
* 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;
    }
    else if ($k1 == 'lastcoredata') {
        return 1;
    }
    else if ($k2 == 'lastcoredata') {
        return -1;
    }
796
797
798
799
    // 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);
800
}
801
802
803
804
805

/** core blocktype categories the system exports
* (eg not tied to artefact plugins)
*/
function get_core_blocktype_categories() {
806
    return array('general', 'images', 'multimedia', 'feeds');
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
}

function install_blocktype_categories_for_plugin($blocktype) {
    safe_require('blocktype', $blocktype);
    $blocktype = blocktype_namespaced_to_single($blocktype);
    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) {
            insert_record('blocktype_installed_category', (object)array(
                'blocktype' => $blocktype,
                'category' => $cat
            ));
        }
    }
    db_commit();
}

function install_blocktype_categories() {
    db_begin();

    if ($artefacts = plugins_installed('artefact')) {
        $artefacts = array_map(create_function('$a', 'return $a->name;'), $artefacts);
    }
    else {
        $artefacts = array();
    }
    $categories = array_merge(get_core_blocktype_categories(), $artefacts);
    $installedcategories = get_column('blocktype_category', 'name');

    if ($toinstall = array_diff($categories, $installedcategories)) {
        foreach ($toinstall as $i) {
            insert_record('blocktype_category', (object)array('name' => $i));
        }
    }

    db_commit();


    // poll all the installed blocktype plugins and ask them what categories they export
    if ($blocktypes = plugins_installed('blocktype')) {
        foreach ($blocktypes as $bt) {
            install_blocktype_categories_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
        }
    }
}

854
?>