forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adminlib.php
4853 lines (4230 loc) · 169 KB
/
adminlib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
571
572
573
574
575
576
577
578
579
580
581
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
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
797
798
799
800
801
802
803
804
805
806
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* adminlib.php - Contains functions that only administrators will ever need to use
*
* @author Martin Dougiamas and many others
* @version $Id$
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
function upgrade_main_savepoint($result, $version) {
global $CFG;
if ($result) {
if ($CFG->version >= $version) {
// something really wrong is going on in main upgrade script
print_error('cannotdowngrade', 'debug', '', array($CFG->version, $version));
}
set_config('version', $version);
} else {
notify ("Upgrade savepoint: Error during main upgrade to version $version");
}
}
function upgrade_mod_savepoint($result, $version, $type) {
//TODO
}
function upgrade_plugin_savepoint($result, $version, $type, $dir) {
//TODO
}
function upgrade_backup_savepoint($result, $version) {
//TODO
}
function upgrade_blocks_savepoint($result, $version, $type) {
//TODO
}
/**
* Upgrade plugins
*
* @uses $CFG
* @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
* @param string $dir The directory where the plugins are located (e.g. 'question/questiontypes')
* @param string $return The url to prompt the user to continue to
*/
function upgrade_plugins($type, $dir, $return) {
global $CFG, $interactive, $DB;
/// Let's know if the header has been printed, so the funcion is being called embedded in an outer page
$embedded = defined('HEADER_PRINTED');
$plugs = get_list_of_plugins($dir);
$updated_plugins = false;
$strpluginsetup = get_string('pluginsetup');
foreach ($plugs as $plug) {
$fullplug = $CFG->dirroot .'/'.$dir.'/'. $plug;
unset($plugin);
if (is_readable($fullplug .'/version.php')) {
include_once($fullplug .'/version.php'); // defines $plugin with version etc
} else {
continue; // Nothing to do.
}
$newupgrade = false;
if (is_readable($fullplug . '/db/upgrade.php')) {
include_once($fullplug . '/db/upgrade.php'); // defines new upgrading function
$newupgrade = true;
}
if (!isset($plugin)) {
continue;
}
if (!empty($plugin->requires)) {
if ($plugin->requires > $CFG->version) {
$info = new object();
$info->pluginname = $plug;
$info->pluginversion = $plugin->version;
$info->currentmoodle = $CFG->version;
$info->requiremoodle = $plugin->requires;
if (!$updated_plugins && !$embedded) {
print_header($strpluginsetup, $strpluginsetup,
build_navigation(array(array('name' => $strpluginsetup, 'link' => null, 'type' => 'misc'))), '',
upgrade_get_javascript(), false, ' ', ' ');
}
upgrade_log_start();
notify(get_string('pluginrequirementsnotmet', 'error', $info));
$updated_plugins = true;
continue;
}
}
$plugin->name = $plug; // The name MUST match the directory
$pluginversion = $type.'_'.$plug.'_version';
if (!isset($CFG->$pluginversion)) {
set_config($pluginversion, 0);
}
if ($CFG->$pluginversion == $plugin->version) {
// do nothing
} else if ($CFG->$pluginversion < $plugin->version) {
if (!$updated_plugins && !$embedded) {
print_header($strpluginsetup, $strpluginsetup,
build_navigation(array(array('name' => $strpluginsetup, 'link' => null, 'type' => 'misc'))), '',
upgrade_get_javascript(), false, ' ', ' ');
}
$updated_plugins = true;
upgrade_log_start();
print_heading($dir.'/'. $plugin->name .' plugin needs upgrading');
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(true);
}
@set_time_limit(0); // To allow slow databases to complete the long SQL
if ($CFG->$pluginversion == 0) { // It's a new install of this plugin
/// Both old .sql files and new install.xml are supported
/// but we priorize install.xml (XMLDB) if present
$status = false;
if (file_exists($fullplug . '/db/install.xml')) {
$status = $DB->get_manager()->install_from_xmldb_file($fullplug . '/db/install.xml'); //New method
} else {
$status = true;
}
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(false);
}
/// Continue with the instalation, roles and other stuff
if ($status) {
/// OK so far, now update the plugins record
set_config($pluginversion, $plugin->version);
/// Install capabilities
if (!update_capabilities($type.'/'.$plug)) {
print_error('cannotsetupcapforplugin', '', '', $plugin->name);
}
/// Install events
events_update_definition($type.'/'.$plug);
/// Run local install function if there is one
if (is_readable($fullplug .'/lib.php')) {
include_once($fullplug .'/lib.php');
$installfunction = $plugin->name.'_install';
if (function_exists($installfunction)) {
if (! $installfunction() ) {
notify('Encountered a problem running install function for '.$module->name.'!');
}
}
}
notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess');
} else {
notify('Installing '. $plugin->name .' FAILED!');
}
} else { // Upgrade existing install
/// Run de old and new upgrade functions for the module
$newupgrade_function = 'xmldb_' . $type.'_'.$plugin->name .'_upgrade';
/// Then, the new function if exists and the old one was ok
$newupgrade_status = true;
if ($newupgrade && function_exists($newupgrade_function)) {
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(true);
}
$newupgrade_status = $newupgrade_function($CFG->$pluginversion);
} else if ($newupgrade) {
notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
$fullplug . '/db/upgrade.php');
}
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(false);
}
/// Now analyze upgrade results
if ($newupgrade_status) { // No upgrading failed
// OK so far, now update the plugins record
set_config($pluginversion, $plugin->version);
if (!update_capabilities($type.'/'.$plug)) {
print_error('cannotupdateplugincap', '', '', $plugin->name);
}
events_update_definition($type.'/'.$plug);
notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess');
} else {
notify('Upgrading '. $plugin->name .' from '. $CFG->$pluginversion .' to '. $plugin->version .' FAILED!');
}
}
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
echo '<hr />';
}
} else {
upgrade_log_start();
print_error('cannotdowngrade', 'debug', '', array($CFG->pluginversion, $plugin->version));
}
}
upgrade_log_finish();
if ($updated_plugins && !$embedded) {
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
print_continue($return);
print_footer('none');
die;
} else if (CLI_UPGRADE && ($interactive > CLI_SEMI )) {
console_write(STDOUT,'askcontinue');
if (read_boolean()){
return ;
}else {
console_write(STDERR,'','',false);
}
}
}
}
/**
* Find and check all modules and load them up or upgrade them if necessary
*
* @uses $CFG
* @param string $return The url to prompt the user to continue to
* @todo Finish documenting this function
*/
function upgrade_activity_modules($return) {
global $CFG, $interactive, $DB;
if (!$mods = get_list_of_plugins('mod') ) {
print_error('nomodules', 'debug');
}
$updated_modules = false;
$strmodulesetup = get_string('modulesetup');
foreach ($mods as $mod) {
if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
continue;
}
$fullmod = $CFG->dirroot .'/mod/'. $mod;
unset($module);
if ( is_readable($fullmod .'/version.php')) {
include_once($fullmod .'/version.php'); // defines $module with version etc
} else {
notify('Module '. $mod .': '. $fullmod .'/version.php was not readable');
continue;
}
$newupgrade = false;
if ( is_readable($fullmod . '/db/upgrade.php')) {
include_once($fullmod . '/db/upgrade.php'); // defines new upgrading function
$newupgrade = true;
}
if (!isset($module)) {
continue;
}
if (!empty($module->requires)) {
if ($module->requires > $CFG->version) {
$info = new object();
$info->modulename = $mod;
$info->moduleversion = $module->version;
$info->currentmoodle = $CFG->version;
$info->requiremoodle = $module->requires;
if (!$updated_modules) {
print_header($strmodulesetup, $strmodulesetup,
build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '',
upgrade_get_javascript(), false, ' ', ' ');
}
upgrade_log_start();
notify(get_string('modulerequirementsnotmet', 'error', $info));
$updated_modules = true;
continue;
}
}
$module->name = $mod; // The name MUST match the directory
include_once($fullmod.'/lib.php'); // defines upgrading and/or installing functions
if ($currmodule = $DB->get_record('modules', array('name'=>$module->name))) {
if ($currmodule->version == $module->version) {
// do nothing
} else if ($currmodule->version < $module->version) {
/// If versions say that we need to upgrade but no upgrade files are available, notify and continue
if (!$newupgrade) {
notify('Upgrade file ' . $mod . ': ' . $fullmod . '/db/upgrade.php is not readable');
continue;
}
if (!$updated_modules) {
print_header($strmodulesetup, $strmodulesetup,
build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '',
upgrade_get_javascript(), false, ' ', ' ');
}
upgrade_log_start();
print_heading($module->name .' module needs upgrading');
/// Run de old and new upgrade functions for the module
$newupgrade_function = 'xmldb_' . $module->name . '_upgrade';
/// Then, the new function if exists and the old one was ok
$newupgrade_status = true;
if ($newupgrade && function_exists($newupgrade_function)) {
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(true);
}
$newupgrade_status = $newupgrade_function($currmodule->version, $module);
} else if ($newupgrade) {
notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
$mod . ': ' . $fullmod . '/db/upgrade.php');
}
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(false);
}
/// Now analyze upgrade results
if ($newupgrade_status) { // No upgrading failed
// OK so far, now update the modules record
$module->id = $currmodule->id;
if (!$DB->update_record('modules', $module)) {
print_error('cannotupdatemod', '', '', $module->name);
}
remove_dir($CFG->dataroot . '/cache', true); // flush cache
notify(get_string('modulesuccess', '', $module->name), 'notifysuccess');
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) {
echo '<hr />';
}
} else {
notify('Upgrading '. $module->name .' from '. $currmodule->version .' to '. $module->version .' FAILED!');
}
/// Update the capabilities table?
if (!update_capabilities('mod/'.$module->name)) {
print_error('cannotupdatemodcap', '', '', $module->name);
}
events_update_definition('mod/'.$module->name);
$updated_modules = true;
} else {
upgrade_log_start();
print_error('cannotdowngrade', 'debug', '', array($currmodule->version, $module->version));
}
} else { // module not installed yet, so install it
if (!$updated_modules) {
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
print_header($strmodulesetup, $strmodulesetup,
build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '',
upgrade_get_javascript(), false, ' ', ' ');
}
}
upgrade_log_start();
print_heading($module->name);
$updated_modules = true;
// To avoid unnecessary output from the SQL queries in the CLI version
if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE ) {
$DB->set_debug(true);
}
@set_time_limit(0); // To allow slow databases to complete the long SQL
/// Both old .sql files and new install.xml are supported
/// but we priorize install.xml (XMLDB) if present
if (file_exists($fullmod . '/db/install.xml')) {
$status = $DB->get_manager()->install_from_xmldb_file($fullmod . '/db/install.xml'); //New method
}
if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) {
$DB->set_debug(false);
}
/// Continue with the installation, roles and other stuff
if ($status) {
if ($module->id = $DB->insert_record('modules', $module)) {
/// Capabilities
if (!update_capabilities('mod/'.$module->name)) {
print_error('cannotsetupcapformod', '', '', $module->name);
}
/// Events
events_update_definition('mod/'.$module->name);
/// Run local install function if there is one
$installfunction = $module->name.'_install';
if (function_exists($installfunction)) {
if (! $installfunction() ) {
notify('Encountered a problem running install function for '.$module->name.'!');
}
}
notify(get_string('modulesuccess', '', $module->name), 'notifysuccess');
if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE ) {
echo '<hr />';
}
} else {
print_error($module->name .' module could not be added to the module list!');
}
} else {
print_error($module->name .' tables could NOT be set up successfully!');
}
}
/// Check submodules of this module if necessary
$submoduleupgrade = $module->name.'_upgrade_submodules';
if (function_exists($submoduleupgrade)) {
$submoduleupgrade();
}
/// Run any defaults or final code that is necessary for this module
if ( is_readable($fullmod .'/defaults.php')) {
// Insert default values for any important configuration variables
unset($defaults);
include($fullmod .'/defaults.php'); // include here means execute, not library include
if (!empty($defaults)) {
foreach ($defaults as $name => $value) {
if (!isset($CFG->$name)) {
set_config($name, $value);
}
}
}
}
}
upgrade_log_finish(); // finish logging if started
if ($updated_modules) {
if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE ) {
print_continue($return);
print_footer('none');
die;
} else if ( CLI_UPGRADE && ($interactive > CLI_SEMI) ) {
console_write(STDOUT,'askcontinue');
if (read_boolean()){
return ;
}else {
console_write(STDERR,'','',false);
}
}
}
}
/**
* Try to obtain or release the cron lock.
*
* @param string $name name of lock
* @param int $until timestamp when this lock considered stale, null means remove lock unconditionaly
* @param bool $ignorecurrent ignore current lock state, usually entend previous lock
* @return bool true if lock obtained
*/
function set_cron_lock($name, $until, $ignorecurrent=false) {
global $DB;
if (empty($name)) {
debugging("Tried to get a cron lock for a null fieldname");
return false;
}
// remove lock by force == remove from config table
if (is_null($until)) {
set_config($name, null);
return true;
}
if (!$ignorecurrent) {
// read value from db - other processes might have changed it
$value = $DB->get_field('config', 'value', array('name'=>$name));
if ($value and $value > time()) {
//lock active
return false;
}
}
set_config($name, $until);
return true;
}
function print_progress($done, $total, $updatetime=5, $sleeptime=1, $donetext='') {
static $thisbarid;
static $starttime;
static $lasttime;
if ($total < 2) { // No need to show anything
return;
}
// Are we done?
if ($done >= $total) {
$done = $total;
if (!empty($thisbarid)) {
$donetext .= ' ('.$done.'/'.$total.') '.get_string('success');
print_progress_redraw($thisbarid, $done, $total, 500, $donetext);
$thisbarid = $starttime = $lasttime = NULL;
}
return;
}
if (empty($starttime)) {
$starttime = $lasttime = time();
$lasttime = $starttime - $updatetime;
$thisbarid = uniqid();
echo '<table width="500" cellpadding="0" cellspacing="0" align="center"><tr><td width="500">';
echo '<div id="bar'.$thisbarid.'" style="border-style:solid;border-width:1px;width:500px;height:50px;">';
echo '<div id="slider'.$thisbarid.'" style="border-style:solid;border-width:1px;height:48px;width:10px;background-color:green;"></div>';
echo '</div>';
echo '<div id="text'.$thisbarid.'" align="center" style="width:500px;"></div>';
echo '</td></tr></table>';
echo '</div>';
}
$now = time();
if ($done && (($now - $lasttime) >= $updatetime)) {
$elapsedtime = $now - $starttime;
$projectedtime = (int)(((float)$total / (float)$done) * $elapsedtime) - $elapsedtime;
$percentage = round((float)$done / (float)$total, 2);
$width = (int)(500 * $percentage);
if ($projectedtime > 10) {
$projectedtext = ' Ending: '.format_time($projectedtime);
} else {
$projectedtext = '';
}
$donetext .= ' ('.$done.'/'.$total.') '.$projectedtext;
print_progress_redraw($thisbarid, $done, $total, $width, $donetext);
$lasttime = $now;
}
}
// Don't call this function directly, it's called from print_progress.
function print_progress_redraw($thisbarid, $done, $total, $width, $donetext='') {
if (empty($thisbarid)) {
return;
}
echo '<script>';
echo 'document.getElementById("text'.$thisbarid.'").innerHTML = "'.addslashes($donetext).'";'."\n";
echo 'document.getElementById("slider'.$thisbarid.'").style.width = \''.$width.'px\';'."\n";
echo '</script>';
}
function upgrade_get_javascript() {
global $CFG;
if (!empty($_SESSION['installautopilot'])) {
$linktoscrolltoerrors = '<script type="text/javascript">var installautopilot = true;</script>'."\n";
} else {
$linktoscrolltoerrors = '<script type="text/javascript">var installautopilot = false;</script>'."\n";
}
$linktoscrolltoerrors .= '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>';
return $linktoscrolltoerrors;
}
function create_admin_user($user_input=NULL) {
global $CFG, $USER, $DB;
if (empty($CFG->rolesactive)) { // No admin user yet.
$user = new object();
$user->auth = 'manual';
$user->firstname = get_string('admin');
$user->lastname = get_string('user');
$user->username = 'admin';
$user->password = hash_internal_user_password('admin');
$user->email = 'root@localhost';
$user->confirmed = 1;
$user->mnethostid = $CFG->mnet_localhost_id;
$user->lang = $CFG->lang;
$user->maildisplay = 1;
$user->timemodified = time();
if ($user_input) {
$user = $user_input;
}
if (!$user->id = $DB->insert_record('user', $user)) {
print_error('cannotcreateadminuser', 'debug');
}
if (!$user = $DB->get_record('user', array('id'=>$user->id))) { // Double check.
print_error('invaliduserid');
}
// Assign the default admin roles to the new user.
if (!$adminroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW)) {
print_error('noadminrole', 'debug');
}
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
foreach ($adminroles as $adminrole) {
role_assign($adminrole->id, $user->id, 0, $sitecontext->id);
}
set_config('rolesactive', 1);
// Log the user in.
$USER = get_complete_user_data('username', 'admin');
$USER->newadminuser = 1;
load_all_capabilities();
if (!defined('CLI_UPGRADE')||!CLI_UPGRADE) {
redirect("$CFG->wwwroot/user/editadvanced.php?id=$user->id"); // Edit thyself
}
} else {
print_error('cannotcreateadminuser', 'debug');
}
}
////////////////////////////////////////////////
/// upgrade logging functions
////////////////////////////////////////////////
$upgradeloghandle = false;
$upgradelogbuffer = '';
// I did not find out how to use static variable in callback function,
// the problem was that I could not flush the static buffer :-(
global $upgradeloghandle, $upgradelogbuffer;
/**
* Check if upgrade is already running.
*
* If anything goes wrong due to missing call to upgrade_log_finish()
* just restart the browser.
*
* @param string warning message indicating upgrade is already running
* @param int page reload timeout
*/
function upgrade_check_running($message, $timeout) {
if (!empty($_SESSION['upgraderunning'])) {
print_header();
redirect(me(), $message, $timeout);
}
}
/**
* Start logging of output into file (if not disabled) and
* prevent aborting and concurrent execution of upgrade script.
*
* Please note that you can not write into session variables after calling this function!
*
* This function may be called repeatedly.
*/
function upgrade_log_start() {
global $CFG, $upgradeloghandle;
if (!empty($_SESSION['upgraderunning'])) {
return; // logging already started
}
@ignore_user_abort(true); // ignore if user stops or otherwise aborts page loading
$_SESSION['upgraderunning'] = 1; // set upgrade indicator
if (empty($CFG->dbsessions)) { // workaround for bug in adodb, db session can not be restarted
session_write_close(); // from now on user can reload page - will be displayed warning
}
make_upload_directory('upgradelogs');
ob_start('upgrade_log_callback', 2); // function for logging to disk; flush each line of text ASAP
register_shutdown_function('upgrade_log_finish'); // in case somebody forgets to stop logging
}
/**
* Terminate logging of output, flush all data, allow script aborting
* and reopen session for writing. Function print_error() does terminate the logging too.
*
* Please make sure that each upgrade_log_start() is properly terminated by
* this function or print_error().
*
* This function may be called repeatedly.
*/
function upgrade_log_finish() {
global $CFG, $upgradeloghandle, $upgradelogbuffer;
if (empty($_SESSION['upgraderunning'])) {
return; // logging already terminated
}
@ob_end_flush();
if ($upgradelogbuffer !== '') {
@fwrite($upgradeloghandle, $upgradelogbuffer);
$upgradelogbuffer = '';
}
if ($upgradeloghandle and ($upgradeloghandle !== 'error')) {
@fclose($upgradeloghandle);
$upgradeloghandle = false;
}
if (empty($CFG->dbsessions)) {
@session_start(); // ignore header errors, we only need to reopen session
}
$_SESSION['upgraderunning'] = 0; // clear upgrade indicator
if (connection_aborted()) {
die;
}
@ignore_user_abort(false);
}
/**
* Callback function for logging into files. Not more than one file is created per minute,
* upgrade session (terminated by upgrade_log_finish()) is always stored in one file.
*
* This function must not output any characters or throw warnigns and errors!
*/
function upgrade_log_callback($string) {
global $CFG, $upgradeloghandle, $upgradelogbuffer;
if (empty($CFG->disableupgradelogging) and ($string != '') and ($upgradeloghandle !== 'error')) {
if ($upgradeloghandle or ($upgradeloghandle = @fopen($CFG->dataroot.'/upgradelogs/upg_'.date('Ymd-Hi').'.html', 'a'))) {
$upgradelogbuffer .= $string;
if (strlen($upgradelogbuffer) > 2048) { // 2kB write buffer
@fwrite($upgradeloghandle, $upgradelogbuffer);
$upgradelogbuffer = '';
}
} else {
$upgradeloghandle = 'error';
}
}
return $string;
}
/**
* Try to verify that dataroot is not accessible from web.
* It is not 100% correct but might help to reduce number of vulnerable sites.
*
* Protection from httpd.conf and .htaccess is not detected properly.
*/
function is_dataroot_insecure() {
global $CFG;
$siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
$rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
$rp = strrev(trim($rp, '/'));
$rp = explode('/', $rp);
foreach($rp as $r) {
if (strpos($siteroot, '/'.$r.'/') === 0) {
$siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
} else {
break; // probably alias root
}
}
$siteroot = strrev($siteroot);
$dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
if (strpos($dataroot, $siteroot) === 0) {
return true;
}
return false;
}
/// =============================================================================================================
/// administration tree classes and functions
// n.b. documentation is still in progress for this code
/// INTRODUCTION
/// This file performs the following tasks:
/// -it defines the necessary objects and interfaces to build the Moodle
/// admin hierarchy
/// -it defines the admin_externalpage_setup(), admin_externalpage_print_header(),
/// and admin_externalpage_print_footer() functions used on admin pages
/// ADMIN_SETTING OBJECTS
/// Moodle settings are represented by objects that inherit from the admin_setting
/// class. These objects encapsulate how to read a setting, how to write a new value
/// to a setting, and how to appropriately display the HTML to modify the setting.
/// ADMIN_SETTINGPAGE OBJECTS
/// The admin_setting objects are then grouped into admin_settingpages. The latter
/// appear in the Moodle admin tree block. All interaction with admin_settingpage
/// objects is handled by the admin/settings.php file.
/// ADMIN_EXTERNALPAGE OBJECTS
/// There are some settings in Moodle that are too complex to (efficiently) handle
/// with admin_settingpages. (Consider, for example, user management and displaying
/// lists of users.) In this case, we use the admin_externalpage object. This object
/// places a link to an external PHP file in the admin tree block.
/// If you're using an admin_externalpage object for some settings, you can take
/// advantage of the admin_externalpage_* functions. For example, suppose you wanted
/// to add a foo.php file into admin. First off, you add the following line to
/// admin/settings/first.php (at the end of the file) or to some other file in
/// admin/settings:
/// $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
/// $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
/// Next, in foo.php, your file structure would resemble the following:
/// require_once('.../config.php');
/// require_once($CFG->libdir.'/adminlib.php');
/// admin_externalpage_setup('foo');
/// // functionality like processing form submissions goes here
/// admin_externalpage_print_header();
/// // your HTML goes here
/// admin_externalpage_print_footer();
/// The admin_externalpage_setup() function call ensures the user is logged in,
/// and makes sure that they have the proper role permission to access the page.
/// The admin_externalpage_print_header() function prints the header (it figures
/// out what category and subcategories the page is classified under) and ensures
/// that you're using the admin pagelib (which provides the admin tree block and
/// the admin bookmarks block).
/// The admin_externalpage_print_footer() function properly closes the tables
/// opened up by the admin_externalpage_print_header() function and prints the
/// standard Moodle footer.
/// ADMIN_CATEGORY OBJECTS
/// Above and beyond all this, we have admin_category objects. These objects
/// appear as folders in the admin tree block. They contain admin_settingpage's,
/// admin_externalpage's, and other admin_category's.
/// OTHER NOTES
/// admin_settingpage's, admin_externalpage's, and admin_category's all inherit
/// from part_of_admin_tree (a pseudointerface). This interface insists that
/// a class has a check_access method for access permissions, a locate method
/// used to find a specific node in the admin tree and find parent path.
/// admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
/// interface ensures that the class implements a recursive add function which
/// accepts a part_of_admin_tree object and searches for the proper place to
/// put it. parentable_part_of_admin_tree implies part_of_admin_tree.
/// Please note that the $this->name field of any part_of_admin_tree must be
/// UNIQUE throughout the ENTIRE admin tree.
/// The $this->name field of an admin_setting object (which is *not* part_of_
/// admin_tree) must be unique on the respective admin_settingpage where it is
/// used.
/// CLASS DEFINITIONS /////////////////////////////////////////////////////////
/**
* Pseudointerface for anything appearing in the admin tree
*
* The pseudointerface that is implemented by anything that appears in the admin tree
* block. It forces inheriting classes to define a method for checking user permissions
* and methods for finding something in the admin tree.
*
* @author Vincenzo K. Marcovecchio
* @package admin
*/
class part_of_admin_tree {
/**
* Finds a named part_of_admin_tree.
*
* Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
* and not parentable_part_of_admin_tree, then this function should only check if
* $this->name matches $name. If it does, it should return a reference to $this,
* otherwise, it should return a reference to NULL.
*
* If a class inherits parentable_part_of_admin_tree, this method should be called
* recursively on all child objects (assuming, of course, the parent object's name
* doesn't match the search criterion).
*
* @param string $name The internal name of the part_of_admin_tree we're searching for.
* @return mixed An object reference or a NULL reference.
*/
function &locate($name) {
trigger_error('Admin class does not implement method <strong>locate()</strong>', E_USER_WARNING);
return;
}
/**
* Removes named part_of_admin_tree.
*
* @param string $name The internal name of the part_of_admin_tree we want to remove.
* @return bool success.
*/
function prune($name) {
trigger_error('Admin class does not implement method <strong>prune()</strong>', E_USER_WARNING);
return;
}
/**
* Search using query
* @param strin query
* @return mixed array-object structure of found settings and pages
*/
function search($query) {
trigger_error('Admin class does not implement method <strong>search()</strong>', E_USER_WARNING);
return;
}
/**
* Verifies current user's access to this part_of_admin_tree.
*
* Used to check if the current user has access to this part of the admin tree or
* not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
* then this method is usually just a call to has_capability() in the site context.
*
* If a class inherits parentable_part_of_admin_tree, this method should return the
* logical OR of the return of check_access() on all child objects.
*
* @return bool True if the user has access, false if she doesn't.
*/
function check_access() {
trigger_error('Admin class does not implement method <strong>check_access()</strong>', E_USER_WARNING);
return;
}
/**
* Mostly usefull for removing of some parts of the tree in admin tree block.
*
* @return True is hidden from normal list view
*/
function is_hidden() {
trigger_error('Admin class does not implement method <strong>is_hidden()</strong>', E_USER_WARNING);
return;
}
}
/**
* Pseudointerface implemented by any part_of_admin_tree that has children.
*
* The pseudointerface implemented by any part_of_admin_tree that can be a parent
* to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
* from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
* include an add method for adding other part_of_admin_tree objects as children.
*
* @author Vincenzo K. Marcovecchio
* @package admin
*/
class parentable_part_of_admin_tree extends part_of_admin_tree {
/**
* Adds a part_of_admin_tree object to the admin tree.
*
* Used to add a part_of_admin_tree object to this object or a child of this
* object. $something should only be added if $destinationname matches
* $this->name. If it doesn't, add should be called on child objects that are
* also parentable_part_of_admin_tree's.
*
* @param string $destinationname The internal name of the new parent for $something.
* @param part_of_admin_tree &$something The object to be added.
* @return bool True on success, false on failure.
*/
function add($destinationname, $something) {
trigger_error('Admin class does not implement method <strong>add()</strong>', E_USER_WARNING);
return;
}
}
/**
* The object used to represent folders (a.k.a. categories) in the admin tree block.
*
* Each admin_category object contains a number of part_of_admin_tree objects.
*
* @author Vincenzo K. Marcovecchio
* @package admin
*/
class admin_category extends parentable_part_of_admin_tree {
/**
* @var mixed An array of part_of_admin_tree objects that are this object's children
*/
var $children;
/**
* @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
*/
var $name;
/**
* @var string The displayed name for this category. Usually obtained through get_string()
*/
var $visiblename;
/**
* @var bool Should this category be hidden in admin tree block?
*/
var $hidden;
/**
* paths
*/
var $path;
var $visiblepath;
/**