forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcliupgrade.php
1331 lines (1099 loc) · 52.2 KB
/
cliupgrade.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
/**
* cliupgrade.php
* Command Line Installer and Upgrader for Moodle
* @author Dilan Anuruddha
*
*/
//Intruders OUT!!!
if (!empty($_SERVER['GATEWAY_INTERFACE'])){
error_log("cli-installer should not be called from apache!");
echo 'This script is not accessible from the webserver';
exit;
}
/**
* BEFORE YOU ADD/EDIT/DELETE ANYTHING IN THIS DOCUMENT PLEASE READ
*
* When you add some code that print something on to standard out always wrap it around if clause with $verbose
* argument check. If the $verbose is CLI_NO, you shouldn't print anything. If $verboser is CLI_SEMI it's ok to print a
* summarized version. If $verbose is CLI_FULL you can print anything you want.
*
* When you add a code that read input from the standard input you should wrap it with appropriate if clause, allowing
* required level of interaction. Also remember to add the same option as a command line argument list.
* In CLI_FULL interaction mode, whether you have set the argument in commandline or not you
* should prompt for user input. In CLI_SEMI interaction only the arguments which are not set are prompted for user input.
* No interaction mode doesn't prompt user for anyinput. If any argument is not specified then the default value should be assumed.
* So do the appropriate thing considering this when you edit or delete this code
*
*/
//=============================================================================//
// Set values for initial structures
//Suppress all errors
error_reporting(E_ALL);
//define constants
define('CLI_VAL_OPT',0);
define('CLI_VAL_REQ',1);
define('CLI_NO',0);
define('CLI_SEMI',1);
define('CLI_FULL',2);
define('CLI_UPGRADE',1);
/// Default array contain default values for all installation options
/// Please see after library inclusion for more default values - which require libraries
$DEFAULT=array();
// Set default values
$DEFAULT['lang'] = 'en_utf8';
$DEFAULT['dbhost'] = 'localhost';
$DEFAULT['dbuser'] = '';
$DEFAULT['dbpass'] = '';
$DEFAULT['dbtype'] = 'mysql';
$DEFAULT['dbname'] = 'moodle';
$DEFAULT['prefix'] = 'mdl_';
$DEFAULT['downloadlangpack']= false;
$DEFAULT['wwwroot'] = '';
$DEFAULT['dirroot'] = dirname(dirname((__FILE__)));
$DEFAULT['dataroot'] = dirname(dirname(dirname(__FILE__))) . '/moodledata';
$DEFAULT['admindirname'] = 'admin';
$DEFAULT['verbose'] = CLI_SEMI;
$DEFAULT['interactivelevel']= CLI_SEMI;
$DEFAULT['agreelicense'] = true;
$DEFAULT['confirmrelease'] = true;
$DEFAULT['sitefullname'] = 'Moodle Site (Please Change Site Name!!)';
$DEFAULT['siteshortname'] = 'moodle';
$DEFAULT['sitesummary'] = 'Brief Description of the site';
$DEFAULT['sitenewsitems'] = 3;
$DEFAULT['adminusername'] = 'admin';
$DEFAULT['adminpassword'] = 'admin';
$DEFAULT['adminemail'] = 'root@localhost';
///set valid long options ans state whether value for options is required or optional
/// Example :If value is required it would be legal to write the script like $php cliupgrade --lang=en_utf8
/// but writing the script like $php cliupgrade --lang would be illegal.
/// As you may have already seen $php cliupgrade --help is valid since hep argument had CLI_VAL_OPT set
$LONG_OPTIONS = array(
'lang' =>CLI_VAL_REQ,
'webaddr' =>CLI_VAL_REQ,
'moodledir' =>CLI_VAL_REQ,
'datadir' =>CLI_VAL_REQ,
'dbtype' =>CLI_VAL_REQ,
'dbhost' =>CLI_VAL_REQ,
'dbname' =>CLI_VAL_REQ,
'dbuser' =>CLI_VAL_REQ,
'dbpass' =>CLI_VAL_REQ,
'prefix' =>CLI_VAL_REQ,
'agreelicense' =>CLI_VAL_REQ,
'confirmrelease' =>CLI_VAL_REQ,
'sitefullname' =>CLI_VAL_REQ,
'siteshortname' =>CLI_VAL_REQ,
'sitesummary' =>CLI_VAL_REQ,
'sitenewsitems' =>CLI_VAL_REQ,
'adminfirstname' =>CLI_VAL_REQ,
'adminlastname' =>CLI_VAL_REQ,
'adminusername' =>CLI_VAL_REQ,
'adminpassword' =>CLI_VAL_REQ,
'adminemail' =>CLI_VAL_REQ,
'verbose' =>CLI_VAL_REQ,
'interactivelevel' =>CLI_VAL_REQ,
'help' =>CLI_VAL_OPT);
//Initialize the intall array
$INSTALL=array();
$SESSION->lang = $DEFAULT['lang'];
$CFG->dirroot = $DEFAULT['dirroot'];
$CFG->libdir = $DEFAULT['dirroot'].'/lib';
$CFG->dataroot = $DEFAULT['dataroot'];
$CFG->admin = $DEFAULT['admindirname'];
$CFG->directorypermissions = 00777;
$CFG->running_installer = true;
$COURSE->id = 0;
// include standard Moodle libraries
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/setuplib.php');
require_once($CFG->libdir.'/moodlelib.php');
require_once($CFG->libdir.'/weblib.php');
require_once($CFG->libdir.'/adodb/adodb.inc.php');
require_once($CFG->libdir.'/environmentlib.php');
require_once($CFG->libdir.'/xmlize.php');
require_once($CFG->libdir.'/componentlib.class.php');
require_once($CFG->libdir.'/installlib.php'); //cli-library
require_once($CFG->dirroot.'/version.php');
//include PEAR Console libraries
set_include_path($CFG->libdir . PATH_SEPARATOR . $CFG->libdir . '/pear/');
require_once('Console/Getopt.php');
/// Set default values - things that require the libraries
$DEFAULT['adminfirstname'] = get_string('admin');
$DEFAULT['adminlastname'] = get_string('user');
/// Set version and release
$INSTALL['version'] = $version;
$INSTALL['release'] = $release;
//========================================================================================//
//Command line option processing//
//fetch arguments
$args = Console_Getopt::readPHPArgv();
//checking errors for argument fetching
if (PEAR::isError($args)) {
console_write(STDOUT,'pearargerror','install');
die();
}
//short options
$short_opts = '';
//long options
$long_opts = create_long_options($LONG_OPTIONS);
//get the argumets to options array
if ( realpath($_SERVER['argv'][0]) == __FILE__ && count($args)>1) {
$console_opt = Console_Getopt::getOpt($args,$short_opts,$long_opts);
} else {
$console_opt = Console_Getopt::getOpt($args,$short_opts,$long_opts);
}
//detect erros in the options
if (PEAR::isError($console_opt)) {
console_write(STDOUT,'invalidargumenthelp');
console_write(STDOUT, "\n", '', false);
die();
}
//Get the option values to an array of option keys and values
$options=get_options($console_opt);
// if user want help print the help without validating option values
if (is_array($options)) {
if(array_key_exists('help',$options)){
console_write(STDOUT,'usagehelp');
console_write(STDOUT, "\n", '', false);
die ;
}
}
//check for validity of options and exit if errors found
validate_option_values($options);
// insert options array options into INSTALL array
foreach ( $options as $key=>$value) {
//map input argument value to INSTALL array values, Argument names kept bcoz they make sense!!!
if ( $key == 'moodledir') {
$key='dirroot';
} else if ($key == 'webaddr'){
$key='wwwroot';
} else if ($key == 'datadir') {
$key = 'dataroot';
}
$INSTALL[$key]=$value;
}
// if verbose is not set at commandline assume default values
if (!isset($INSTALL['verbose'])) {
$INSTALL['verbose']=$DEFAULT['verbose'];
}
//if interactive level is not set at commandline assume default value
if (!isset($INSTALL['interactivelevel'])) {
$INSTALL['interactivelevel'] = $DEFAULT['interactivelevel'];
}
// set references for interactive level and verbose install array
$interactive = &$INSTALL['interactivelevel'];
$verbose = &$INSTALL['verbose'];
if (!file_exists(dirname(dirname(__FILE__)) . '/config.php')) {
$configfile = dirname(dirname(__FILE__)) . '/config.php';
//welcome message
if ($verbose > CLI_NO) {
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'welcometext','install');
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
}
//============================================================================//
//Language selection for the installation
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['lang'])) ) ) {
$langs=get_installer_list_of_languages();
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'selectlanguage','install');
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'availablelangs','install');
console_write(STDOUT, "\n", '', false);
//output available languages
foreach ( $langs as $language ) {
console_write(STDOUT,"\t",'',false);
console_write(STDOUT,$language,'',false);
console_write(STDOUT,"\n",'',false);
}
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'yourchoice','install');
$short_code_langs = get_short_codes($langs);
$INSTALL['lang']=read_element($short_code_langs);
$SESSION->lang = $INSTALL['lang'];
}
//==============================================================================//
//Checking PHP settings
$silent=false;
if ($verbose == CLI_NO) {
$silent=true;
}else{
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'checkingphpsettings','install');
console_write(STDOUT, "\n", '', false);
}
/// Check that PHP is of a sufficient version
check_compatibility(inst_check_php_version(), get_string('phpversion', 'install'), get_string('php52versionerror', 'install'),false,$silent);
/// Check session auto start
check_compatibility(!ini_get_bool('session.auto_start'), get_string('sessionautostart', 'install'), get_string('sessionautostarterror', 'install'),false,$silent);
/// Check magic quotes
check_compatibility(!ini_get_bool('magic_quotes_runtime'), get_string('magicquotesruntime', 'install'), get_string('magicquotesruntimeerror', 'install'),false,$silent);
/// Check unsupported PHP configuration
check_compatibility(ini_get_bool('magic_quotes_gpc') || (!ini_get_bool('register_globals')), get_string('globalsquotes', 'install'), get_string('globalsquoteserror', 'install'),false,$silent);
/// Check safe mode
check_compatibility(!ini_get_bool('safe_mode'), get_string('safemode', 'install'), get_string('safemodeerror', 'install'), true,$silent);
/// Check file uploads
check_compatibility(ini_get_bool('file_uploads'), get_string('fileuploads', 'install'), get_string('fileuploadserror', 'install'), true,$silent);
/// Check GD version
check_compatibility(check_gd_version(), get_string('gdversion', 'install'), get_string('gdversionerror', 'install'), true,$silent);
/// Check memory limit
check_compatibility(check_memory_limit(), get_string('memorylimit', 'install'), get_string('memorylimiterror', 'install'), true,$silent);
//================================================================================//
// Moodle directories and web address
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dirroot']) || !isset($INSTALL['wwwroot']) || !isset($INSTALL['dataroot']) ) ) ) {
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'locationanddirectories','install');
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
}
//input the web directory
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dirroot'])) ) ) {
console_write(STDOUT,'inputwebdirectory','install');
//if directories validation lib is found change this to read_dir() and
//edit read_dir() in lib/installlib.php to point to validation code
$INSTALL['dirroot']=read();
}
//input the web adress
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['wwwroot'])) ) ) {
console_write(STDOUT,'inputwebadress','install');
$INSTALL['wwwroot']=read_url();
}
//input data directory
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dataroot'])) ) ) {
console_write(STDOUT,'inputdatadirectory','install');
//if directories validation lib is found change this to read_dir() and
//edit read_dir() in lib/installlib.php to point to validation code
$INSTALL['dataroot']=read();
}
/// check wwwroot
if (ini_get('allow_url_fopen') && false) { /// This was not reliable
if (($fh = @fopen($INSTALL['wwwroot'].'/admin/cliupgrade.php', 'r')) === false) {
console_write(STDERR,get_string('wwwrooterror'),'install',false);
}
}
if (isset($fh)) fclose($fh);
/// check dirroot
if (($fh = @fopen($INSTALL['dirroot'].'/admin/cliupgrade.php', 'r')) === false ) {
console_write(STDERR,get_string('dirrooterror'),'install',false);
}
if (isset($fh)) fclose($fh);
/// check dataroot
$CFG->dataroot = $INSTALL['dataroot'];
if (make_upload_directory('sessions', false) === false ) {
console_write(STDERR,get_string('datarooterror'),'install',false);
}
//================================================================================//
// Database settings Moodle database
// Database section heading
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbhost']) || !isset($INSTALL['dbname']) || !isset($INSTALL['dbtype']) || !isset($INSTALL['dbuser']) || !isset($INSTALL['dbpass']) || !isset($INSTALL['prefix']) ) ) ) {
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'databasesettingsformoodle','install');
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
}
//Input dialogs
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbhost']) ))) {
console_write(STDOUT,'databasehost','install');
$INSTALL['dbhost']=read(); // localhost
}
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbname']) ))) {
console_write(STDOUT,'databasename','install');
$INSTALL['dbname']=read(); //'moodletest3';
}
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbtype']) ))) {
$dbtypes=array('mysql','oci8po','postgres7','mssql','mssql_n','odbc_mssql');
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'availabledbtypes','install');
console_write(STDOUT, "\n", '', false);
foreach ($dbtypes as $dbtype) {
console_write(STDOUT,"\t",'',false);
console_write(STDOUT,$dbtype,'install');
console_write(STDOUT,"\n",'',false);
}
console_write(STDOUT,'yourchoice','install');
$INSTALL['dbtype']=read_element($dbtypes);//'mysql';//
}
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbuser']) ))) {
console_write(STDOUT,'databaseuser','install');
$INSTALL['dbuser']=read();//'root';
}
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbpass']) ))) {
console_write(STDOUT,'databasepass','install');
$INSTALL['dbpass']=read();//'';
}
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['prefix']) ))) {
console_write(STDOUT,'tableprefix','install');
$INSTALL['prefix']=read();//'mdl_';//
}
// Running validation tests
/// different format for postgres7 by socket
if ($INSTALL['dbtype'] == 'postgres7' and ($INSTALL['dbhost'] == 'localhost' || $INSTALL['dbhost'] == '127.0.0.1')) {
$INSTALL['dbhost'] = "user='{$INSTALL['dbuser']}' password='{$INSTALL['dbpass']}' dbname='{$INSTALL['dbname']}'";
$INSTALL['dbuser'] = '';
$INSTALL['dbpass'] = '';
$INSTALL['dbname'] = '';
if ($INSTALL['prefix'] == '') { /// must have a prefix
$INSTALL['prefix'] = 'mdl_';
}
}
if ($INSTALL['dbtype'] == 'mysql') { /// Check MySQL extension is present
if (!extension_loaded('mysql')) {
$errormsg = get_string('mysqlextensionisnotpresentinphp', 'install');
}
}
if ($INSTALL['dbtype'] == 'postgres7') { /// Check PostgreSQL extension is present
if (!extension_loaded('pgsql')) {
$errormsg = get_string('pgsqlextensionisnotpresentinphp', 'install');
}
}
if ($INSTALL['dbtype'] == 'mssql') { /// Check MSSQL extension is present
if (!function_exists('mssql_connect')) {
$errormsg = get_string('mssqlextensionisnotpresentinphp', 'install');
}
}
if ($INSTALL['dbtype'] == 'mssql_n') { /// Check MSSQL extension is present
if (!function_exists('mssql_connect')) {
$errormsg = get_string('mssqlextensionisnotpresentinphp', 'install');
}
}
if ($INSTALL['dbtype'] == 'odbc_mssql') { /// Check ODBC extension is present
if (!extension_loaded('odbc')) {
$errormsg = get_string('odbcextensionisnotpresentinphp', 'install');
}
}
if ($INSTALL['dbtype'] == 'oci8po') { /// Check OCI extension is present
if (!extension_loaded('oci8')) {
$errormsg = get_string('ociextensionisnotpresentinphp', 'install');
}
}
if (empty($INSTALL['prefix']) && $INSTALL['dbtype'] != 'mysql') { // All DBs but MySQL require prefix (reserv. words)
$errormsg = get_string('dbwrongprefix', 'install');
}
if ($INSTALL['dbtype'] == 'oci8po' && strlen($INSTALL['prefix']) > 2) { // Oracle max prefix = 2cc (30cc limit)
$errormsg = get_string('dbwrongprefix', 'install');
}
if ($INSTALL['dbtype'] == 'oci8po' && !empty($INSTALL['dbhost'])) { // Oracle host must be blank (tnsnames.ora has it)
$errormsg = get_string('dbwronghostserver', 'install');
}
if (empty($errormsg)) {
/// Have the $db object ready because we are going to use it often
// fnarg
if (empty($CFG->dbtype)) {
$CFG->dbtype = $INSTALL['dbtype'];
$resetcfgdb = true;
}
preconfigure_dbconnection();
if (!empty($resetcfgdb)) {
$CFG->dbtype = false;
}
$db = &ADONewConnection($INSTALL['dbtype']);
$db->SetFetchMode(ADODB_FETCH_ASSOC);
if (! $dbconnected = $db->Connect($INSTALL['dbhost'],$INSTALL['dbuser'],$INSTALL['dbpass'],$INSTALL['dbname'])) {
$errormsg= get_string('cannotconnecttodb','install') . "\n";
} else {
/// We have been able to connect properly, just test the database encoding now.
/// It must be Unicode for 1.8 installations.
$encoding = '';
switch ($INSTALL['dbtype']) {
case 'mysql':
/// Get MySQL character_set_database value
$rs = $db->Execute("SHOW VARIABLES LIKE 'character_set_database'");
if ($rs && $rs->RecordCount() > 0) {
$records = $rs->GetAssoc(true);
$encoding = $records['character_set_database']['Value'];
if (strtoupper($encoding) != 'UTF8') {
/// Try to set the encoding now!
if (! $db->Metatables()) { // We have no tables so go ahead
$db->Execute("ALTER DATABASE `".$INSTALL['dbname']."` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
$rs = $db->Execute("SHOW VARIABLES LIKE 'character_set_database'"); // this works
}
}
/// If conversion fails, skip, let environment testing do the job
}
break;
case 'postgres7':
/// Skip, let environment testing do the job
break;
case 'oci8po':
/// Skip, let environment testing do the job
break;
}
}
}
// check for errors in db section
if (isset($errormsg)) {
console_write(STDERR,$errormsg,'',false);
}
//==========================================================================//
// Check the environment
//check connection to database
$dbconnected = $db->Connect($INSTALL['dbhost'],$INSTALL['dbuser'],$INSTALL['dbpass'],$INSTALL['dbname']);
if ($dbconnected) {
/// Execute environment check, printing results
if (!check_moodle_environment($INSTALL['release'], $environment_results, false)) {
$errormsg = get_string('errorsinenvironment', 'install') . "\n";
}
} else {
/// We never should reach this because DB has been tested before arriving here
$errormsg = get_string('dbconnectionerror', 'install');
}
// check for errors in environment
if (isset($errormsg)) {
console_write(STDERR,$errormsg,'',false);
}
// Print Environment Status
if ($verbose > CLI_NO) {
print_environment_status($environment_results);
}
//==============================================================================//
//download the language pack if it doesn't exist
if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['downloadlangaugepack']) ))) {
$site_langs=get_list_of_languages();
if (!key_exists($INSTALL['lang'],$site_langs)) {
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
console_write(STDOUT,'downloadlanguagepack','install');
$download_lang_pack=read_yes_no();
if($download_lang_pack == 'yes'){
$downloadsuccess = false;
/// Create necessary lang dir
if (!make_upload_directory('lang', false)) {
console_write(STDERR,get_string('cannotcreatelangdir','error'),false);
}
/// Download and install component
if (($cd = new component_installer('http://download.moodle.org', 'lang16',
$INSTALL['lang'].'.zip', 'languages.md5', 'lang')) && empty($errormsg)) {
$status = $cd->install(); //returns ERROR | UPTODATE | INSTALLED
switch ($status) {
case ERROR:
if ($cd->get_error() == 'remotedownloadnotallowed') {
$a = new stdClass();
$a->url = 'http://download.moodle.org/lang16/'.$pack.'.zip';
$a->dest= $CFG->dataroot.'/lang';
console_write(STDOUT,get_string($cd->get_error(), 'error', $a),false);
} else {
$downloaderror = get_string($cd->get_error(), 'error');
console_write(STDOUT,get_string($cd->get_error(), 'error'),false);
}
break;
case UPTODATE:
case INSTALLED:
$downloadsuccess = true;
break;
default:
//We shouldn't reach this point
}
} else {
//We shouldn't reach this point
}
}
}
}
if ( $verbose > CLI_NO && !empty($downloadsuccess)) {
//print success message if language pack download is successful
console_write(STDOUT,'downloadsuccess');
print_newline();
}
$CONFFILE = array();
//==================================================================================//
//set INSTALL array values to CONFFILE array
foreach ($INSTALL as $key => $value) {
$CONFFILE[$key] = $value;
}
//==================================================================================//
//if any value is not set, set default values
foreach ($DEFAULT as $key => $value){
if (!isset($INSTALL[$key])){
$CONFFILE[$key]=$value;
}
}
//==================================================================================//
//create configuration file depending on the previous settings
if ($verbose > CLI_NO) {
console_write(STDOUT,'creatingconfigfile','install');
console_write(STDOUT, "\n", '', false);
}
$str = '<?php /// Moodle Configuration File '."\r\n";
$str .= "\r\n";
$str .= 'unset($CFG);'."\r\n";
$str .= "\r\n";
$str .= '$CFG->dbtype = \''.$CONFFILE['dbtype']."';\r\n";
$str .= '$CFG->dbhost = \''.addslashes($CONFFILE['dbhost'])."';\r\n";
if (!empty($CONFFILE['dbname'])) {
$str .= '$CFG->dbname = \''.$CONFFILE['dbname']."';\r\n";
$str .= '$CFG->dbuser = \''.$CONFFILE['dbuser']."';\r\n";
$str .= '$CFG->dbpass = \''.$CONFFILE['dbpass']."';\r\n";
}
$str .= '$CFG->dbpersist = false;'."\r\n";
$str .= '$CFG->prefix = \''.$CONFFILE['prefix']."';\r\n";
$str .= "\r\n";
$str .= '$CFG->wwwroot = \''.s($CONFFILE['wwwroot'],true)."';\r\n";
$str .= '$CFG->dirroot = \''.s($CONFFILE['dirroot'],true)."';\r\n";
$str .= '$CFG->dataroot = \''.s($CONFFILE['dataroot'],true)."';\r\n";
$str .= '$CFG->admin = \''.s($CONFFILE['admindirname'],true)."';\r\n";
$str .= "\r\n";
$str .= '$CFG->directorypermissions = 00777; // try 02777 on a server in Safe Mode'."\r\n";
$str .= "\r\n";
$str .= 'require_once("$CFG->dirroot/lib/setup.php");'."\r\n";
$str .= '// MAKE SURE WHEN YOU EDIT THIS FILE THAT THERE ARE NO SPACES, BLANK LINES,'."\r\n";
$str .= '// RETURNS, OR ANYTHING ELSE AFTER THE TWO CHARACTERS ON THE NEXT LINE.'."\r\n";
$str .= '?>';
umask(0133);
//save the configuration file
if (( $configsuccess = ($fh = @fopen($configfile, 'w')) ) !== false) {
fwrite($fh, $str);
fclose($fh);
if ($verbose > CLI_NO) {
console_write(STDOUT,'configfilecreated','install');
console_write(STDOUT, "\n", '', false);
}
} else {
console_write(STDOUT,'configfilenotwritten','install');
console_write(STDOUT, "\n", '', false);
console_write(STDOUT, "\n", '', false);
console_write(STDERR, $str, '', false);
}
if ( $verbose ) {
console_write(STDOUT,'installationiscomplete','install');
console_write(STDOUT, "\n", '', false);
}
}
if ( file_exists(dirname(dirname(__FILE__)) . '/config.php')) {
// This is what happens if there is no upgrade....
//console_write(STDERR,'configurationfileexist','install');
//console_write(STDOUT, "\n", '', false);
//die;
// If the configuration file does not exists exit, this should never occur !!
if (!file_exists(dirname(dirname(__FILE__)) . '/config.php')) {
console_write(STDERR,'configfiledoesnotexist','install');
}
/// Check that PHP is of a sufficient version
/// Moved here because older versions do not allow while(@ob_end_clean());
if (version_compare(phpversion(), "5.2.0") < 0) {
$phpversion = phpversion();
console_write(STDERR,"Sorry, Moodle requires PHP 5.2.0 or later (currently using version $phpversion)",'',false);
}
/// Turn off time limits and try to flush everything all the time, sometimes upgrades can be slow.
@set_time_limit(0);
@ob_implicit_flush(true);
//check with someone who know? that does this do?
// while(@ob_end_clean()); // ob_end_flush prevents sending of headers
//unset();
require_once(dirname(dirname(__FILE__)) . '/config.php');
require_once($CFG->libdir.'/adminlib.php'); // Contains various admin-only functions
require_once($CFG->libdir.'/ddllib.php'); // Install/upgrade related db functions
/**
* @todo check upgrade status, if upgrader is running already, notify user and exit.
* existing thing might work for this with some modifications
*
*/
///check PHP Settings
if (ini_get_bool('session.auto_start')) {
console_write(STDERR,"The PHP server variable 'session.auto_start' should be Off ",'',false);
}
if (ini_get_bool('magic_quotes_runtime')) {
console_write(STDERR,"The PHP server variable 'magic_quotes_runtime' should be Off ",'',false);
}
if (!ini_get_bool('file_uploads')) {
console_write(STDERR,"The PHP server variable 'file_uploads' is not turned On" ,'',false);
}
if (empty($CFG->prefix) && $CFG->dbfamily != 'mysql') { //Enforce prefixes for everybody but mysql
console_write(STDERR,'$CFG->prefix can\'t be empty for your target DB (' . $CFG->dbtype . ')','',false);
}
if ($CFG->dbfamily == 'oracle' && strlen($CFG->prefix) > 2) { //Max prefix length for Oracle is 2cc
console_write(STDERR,'$CFG->prefix maximum allowed length for Oracle DBs is 2cc.','',false);
}
/// Check that config.php has been edited
if ($CFG->wwwroot == "http://example.com/moodle") {
console_write(STDERR,"Moodle has not been configured yet. You need to edit config.php first.",'',false);
}
/// Check settings in config.php
$dirroot = dirname(realpath("../index.php"));
if (!empty($dirroot) and $dirroot != $CFG->dirroot) {
console_write(STDERR,"Please fix your settings in config.php:
\nYou have:
\n\$CFG->dirroot = \"".addslashes($CFG->dirroot)."\";
\nbut it should be:
\n\$CFG->dirroot = \"".addslashes($dirroot)."\";",'',false);
}
/// Set some necessary variables during set-up to avoid PHP warnings later on this page
if (!isset($CFG->release)) {
$CFG->release = "";
}
if (!isset($CFG->version)) {
$CFG->version = "";
}
if (is_readable("$CFG->dirroot/version.php")) {
include_once("$CFG->dirroot/version.php"); # defines $version
}
if (!$version or !$release) {
console_write(STDERR,'Main version.php was not readable or specified','',false);# without version, stop
}
if ( $verbose == CLI_NO ) {
$db->debug = false;
} else if ( $verbose == CLI_FULL ) {
$db->debug = true;
}
/// Check if the main tables have been installed yet or not.
if (! $tables = $db->Metatables() ) { // No tables yet at all.
$maintables = false;
} else { // Check for missing main tables
$maintables = true;
$mtables = array("config", "course", "course_categories", "course_modules",
"course_sections", "log", "log_display", "modules",
"user");
foreach ($mtables as $mtable) {
if (!in_array($CFG->prefix.$mtable, $tables)) {
$maintables = false;
break;
}
}
}
if (! $maintables) {
/// hide errors from headers in case debug enabled in config.php
$origdebug = $CFG->debug;
$CFG->debug = DEBUG_MINIMAL;
error_reporting($CFG->debug);
if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && (!isset($INSTALL['agreelicense']) || empty($INSTALL['agreelicense']))) ) {
//Print copyright notice and ask to continue
console_write(STDOUT,get_string('copyrightnotice'),'',false);
print_newline();
console_write(STDOUT,get_string('gpl'),'',false);
print_newline();
console_write(STDOUT,'doyouagree','install',true);
$agreelicense = read_boolean();
}
if ( !isset($agreelicense)) {
$agreelicense = $DEFAULT['agreelicense'];
}
if (!$agreelicense) {
console_write(STDERR,'disagreelicense');
}
if ( $interactive == CLI_FULL || ( $interactive == CLI_SEMI && (!isset($INSTALL['confirmrelease']) || empty($INSTALL['confirmrelease'])))) {
console_write(STDOUT,get_string("currentrelease"),'',false);
print_newline();
console_write(STDOUT,"Moodle $release",'',false);
print_newline();
console_write(STDOUT,'askcontinue');
$confirmrelease = read_boolean();
}
if (!isset($confirmrelease)) {
$confirmrelease = $DEFAULT['confirmrelease'];
}
if (!$confirmrelease) {
console_write(STDERR,'versionerror');
}
$autopilot = 1 ;
$strdatabasesetup = get_string("databasesetup");
$strdatabasesuccess = get_string("databasesuccess");
// print_header($strdatabasesetup, $strdatabasesetup, $strdatabasesetup,
// "", upgrade_get_javascript(), false, " ", " ");
/// return to original debugging level
$CFG->debug = $origdebug;
error_reporting($CFG->debug);
upgrade_log_start();
/// Both old .sql files and new install.xml are supported
/// But we prioritise install.xml (XMLDB) if present
if (!$DB->setup_is_unicodedb()) {
if (!$DB->change_db_encoding()) {
// If could not convert successfully, throw error, and prevent installation
console_write(STDERR,'unicoderequired', 'admin');
}
}
$status = false;
if (file_exists("$CFG->libdir/db/install.xml")) {
$status = $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml"); //New method
} else {
console_write(STDERR,"Error: Your database ($CFG->dbtype) is not yet fully supported by Moodle or install.xml is not present. See the lib/db directory.",'',false);
}
// all new installs are in unicode - keep for backwards compatibility and 1.8 upgrade checks
set_config('unicodedb', 1);
/// Continue with the instalation
if ($status) {
// Install the roles system.
moodle_install_roles();
// Write default settings unconditionally (i.e. even if a setting is already set, overwrite it)
// (this should only have any effect during initial install).
$adminroot = admin_get_root();
$adminroot->prune('backups'); // backup settings table not created yet
admin_apply_default_settings($adminroot);
/// This is used to handle any settings that must exist in $CFG but which do not exist in
/// admin_get_root()/$ADMIN as admin_setting objects (there are some exceptions).
apply_default_exception_settings(array('alternateloginurl' => '',
'auth' => 'email',
'auth_pop3mailbox' => 'INBOX',
'changepassword' => '',
'enrol' => 'manual',
'enrol_plugins_enabled' => 'manual',
'guestloginbutton' => 1,
'registerauth' => 'email',
'style' => 'default',
'template' => 'default',
'theme' => 'standardwhite',
'filter_multilang_converted' => 1));
notify($strdatabasesuccess, "green");
require_once $CFG->dirroot.'/mnet/lib.php';
} else {
console_write(STDERR,"Error: Main databases NOT set up successfully",'');
}
}
/// Check version of Moodle code on disk compared with database
/// and upgrade if possible.
if (file_exists("$CFG->dirroot/lib/db/upgrade.php")) {
include_once("$CFG->dirroot/lib/db/upgrade.php"); # defines new upgrades
}
$stradministration = get_string("administration");
if ($CFG->version) {
if ($version > $CFG->version) { // upgrade
/// If the database is not already Unicode then we do not allow upgrading!
/// Instead, we print an error telling them to upgrade to 1.7 first. MDL-6857
if (empty($CFG->unicodedb)) {
console_write(STDERR,'unicodeupgradeerror', 'error');
}
$a->oldversion = "$CFG->release ($CFG->version)";
$a->newversion = "$release ($version)";
$strdatabasechecking = get_string("databasechecking", "", $a);
// hide errors from headers in case debug is enabled
$origdebug = $CFG->debug;
$CFG->debug = DEBUG_MINIMAL;
error_reporting($CFG->debug);
// logout in case we are upgrading from pre 1.7 version - prevention of weird session problems
if ($CFG->version < 2006050600) {
require_logout();
}
if (empty($confirmupgrade)) {
if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['confirmupgrade']))) {
print_newline();
console_write(STDOUT,$strdatabasechecking,'',false);
print_newline();
console_write(STDOUT,'askcontinue');
$confirmupgrade = read_boolean();
}
}
if (empty($confirmrelease)) {
if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['confirmrelease']))) {
$strcurrentrelease = get_string("currentrelease");
console_write(STDOUT,$strcurrentrelease,'',false);
print_newline();
console_write(STDOUT,"Moodle $release",'',false);
print_newline();
console_write(STDOUT,get_string('releasenoteslink', 'install', 'http://docs.moodle.org/en/Release_Notes'),'',false);
print_newline();
console_write(STDOUT,'askcontinue');
$confirmrelease = read_boolean();
}
require_once($CFG->libdir.'/environmentlib.php');
console_write(STDOUT,'environment', 'admin');
if (!check_moodle_environment($release, $environment_results, false)) {
// Print Environment Status
if ($verbose > CLI_NO) {
print_newline();
print_environment_status_detailed($environment_results);
print_newline();
console_write(STDOUT,'environmenterrorupgrade', 'admin');
}
if(!read_boolean()){
console_write(STDERR,'','',false);
}
} else {
if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['autopilot']))) {
console_write(STDOUT,'environmentok', 'admin');
console_write(STDOUT,'unattendedoperation','admin');
$autopilot = read_boolean();
}
}
}
$strdatabasesuccess = get_string("databasesuccess");