-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.php
1571 lines (1336 loc) · 54.1 KB
/
lib.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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* lib.php
*
* General library for vmoodle.
*
* @package local_vmoodle
* @category local
* @author Bruce Bujon ([email protected])
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/local/vmoodle/bootlib.php');
require_once($CFG->dirroot.'/local/vmoodle/filesystemlib.php');
/* Define constants */
define('VMOODLE_LIBS_DIR', $CFG->dirroot.'/local/vmoodle/plugins/');
define('VMOODLE_PLUGINS_DIR', $CFG->dirroot.'/local/vmoodle/plugins/');
if (!defined('RPC_SUCCESS')) {
define('RPC_TEST', 100);
define('RPC_SUCCESS', 200);
define('RPC_FAILURE', 500);
define('RPC_FAILURE_USER', 501);
define('RPC_FAILURE_CONFIG', 502);
define('RPC_FAILURE_DATA', 503);
define('RPC_FAILURE_CAPABILITY', 510);
define('MNET_FAILURE', 511);
define('RPC_FAILURE_RECORD', 520);
define('RPC_FAILURE_RUN', 521);
}
/* Define commands' constants */
$vmcommandconstants = array('prefix' => $CFG->prefix,
'wwwroot' => $CFG->wwwroot);
// Loading plugin librairies.
$pluginlibs = glob($CFG->dirroot.'/local/vmoodle/plugins/*/lib.php');
foreach ($pluginlibs as $lib) {
require_once($lib);
}
/**
* Implements the generic community/pro packaging switch.
* Tells wether a feature is supported or not. Gives back the
* implementation path where to fetch resources.
* @param string $feature a feature key to be tested.
*/
function local_vmoodle_supports_feature($feature = null, $getsupported = false) {
global $CFG;
static $supports;
if (!during_initial_install()) {
$config = get_config('local_vmoodle');
}
if (!isset($supports)) {
$supports = array(
'pro' => array(
'admin' => array('sadmin', 'mnetinit'),
'vcron' => array('clustering'),
'instances' => array('tools')
),
'community' => array(
),
);
$prefer = array();
}
if ($getsupported) {
return $supports;
}
// Check existance of the 'pro' dir in plugin.
if (is_dir(__DIR__.'/pro')) {
if ($feature == 'emulate/community') {
return 'pro';
}
if (empty($config->emulatecommunity)) {
$versionkey = 'pro';
} else {
$versionkey = 'community';
}
} else {
$versionkey = 'community';
}
if (empty($feature)) {
// Just return version.
return $versionkey;
}
list($feat, $subfeat) = explode('/', $feature);
if (!array_key_exists($feat, $supports[$versionkey])) {
return false;
}
if (!in_array($subfeat, $supports[$versionkey][$feat])) {
return false;
}
if (array_key_exists($feat, $supports['community'])) {
if (in_array($subfeat, $supports['community'][$feat])) {
// If community exists, default path points community code.
if (isset($prefer[$feat][$subfeat])) {
// Configuration tells which location to prefer if explicit.
$versionkey = $prefer[$feat][$subfeat];
} else {
$versionkey = 'community';
}
}
}
return $versionkey;
}
/**
* Provides an adequate renderer depending on distribution possibilities.
*/
function local_vmoodle_get_renderer() {
global $PAGE, $CFG, $OUTPUT;
if (local_vmoodle_supports_feature() == 'pro') {
include_once($CFG->dirroot.'/local/vmoodle/pro/locallib.php');
include_once($CFG->dirroot.'/local/vmoodle/pro/renderer.php');
$renderer = new local_vmoodle_renderer_extended($PAGE, 'html');
$renderer->set_output($OUTPUT);
return $renderer;
}
return $PAGE->get_renderer('local/vmoodle');
}
/**
* get the list of available vmoodles
* @return an array of vmoodle objects
*/
function vmoodle_get_vmoodles() {
global $DB;
if ($vmoodles = $DB->get_records('local_vmoodle')) {
return $vmoodles;
}
return array();
}
/**
* This function is for multicluster repartition of the vcron duty. Usually,
* Usually we use one single server with a single vcron task that operates all
* vmoodle crons in a round robin or last gap strategy.
*
* If more than one cluster is used, the vmoodle register is spread into subsets and
* each clusters consumes a part of the bulk load.
*
* Note that the cluster ix comes from an evaluation of the 'clusterix' config key of the local_vmoodle
* plugin. there should be provision to force the clusterix from a local $CFG->forced_plugin_settings[(vmoodle']['clusterix']
* key being distinct for each cluster.
*
* @param int $clusters the number of clusters
* @param int $clusterix the cluster Id
*/
function vmoodle_get_vmoodleset($clusters = 1, $clusterix = 1) {
global $DB;
$allvhosts = $DB->get_records('local_vmoodle', array('enabled' => 1));
if ($clusters < 2) {
return $allvhosts;
}
$vhostset = array();
$i = 0;
foreach ($allvhosts as $vh) {
if ($i == $clusterix - 1) {
$vhostset[$vh->id] = $vh;
}
$i = ($i + 1) % $clusters;
}
return $vhostset;
}
/**
* drop a vmoodle database
* @param objectref $vmoodle
* @param handle $cnx
*/
function vmoodle_drop_database(&$vmoodle, $cnx = null) {
// Try to delete database.
$localcnx = 0;
if (!$cnx) {
$localcnx = 1;
$cnx = vmoodle_make_connection($vmoodle);
}
if (!$cnx) {
$erroritem->message = get_string('couldnotconnecttodb', 'local_vmoodle');
$erroritem->on = 'db';
return $erroritem;
} else {
if ($vmoodle->vdbtype == 'mysql') {
$sql = "
DROP DATABASE `{$vmoodle->vdbname}`
";
} else if ($vmoodle->vdbtype == 'postgres') {
$sql = "
DROP DATABASE {$vmoodle->vdbname}
";
} else {
echo "vmoodle_drop_database : Database not supported<br/>";
}
$res = vmoodle_execute_query($vmoodle, $sql, $cnx);
if (!$res) {
$erroritem->message = get_string('couldnotdropdb', 'local_vmoodle');
$erroritem->on = 'db';
return $erroritem;
}
if ($localcnx) {
vmoodle_close_connection($vmoodle, $cnx);
}
}
return false;
}
/**
* DEPRECATED / Not used any more.
* load a bulk template in databse
* @param object $vmoodle
* @param string $bulfile a bulk file of queries to process on the database
* @param handle $cnx
* @param array $vars an array of vars to inject in the bulk file before processing
*/
function vmoodle_load_db_template(&$vmoodle, $bulkfile, $cnx = null, $vars = null, $filter = null) {
global $CFG;
$localcnx = 0;
if (is_null($cnx) || $vmoodle->vdbtype == 'postgres') {
// Postgress MUST make a new connection to ensure db is bound to handle.
$cnx = vmoodle_make_connection($vmoodle, true);
$localcnx = 1;
}
// Get dump file.
if (file_exists($bulkfile)) {
$sql = file($bulkfile);
// Converts into an array of text lines.
$dumpfile = implode("", $sql);
if ($filter) {
foreach ($filter as $from => $to) {
$dumpfile = mb_ereg_replace(preg_quote($from), $to, $dumpfile);
}
}
// Insert any external vars.
if (!empty($vars)) {
foreach ($vars as $key => $value) {
$dumpfile = str_replace("<%%$key%%>", $value, $dumpfile);
}
}
$sql = explode ("\n", $dumpfile);
// Cleanup unuseful things.
if ($vmoodle->vdbtype == 'mysql') {
$sql = preg_replace("/^--.*/", "", $sql);
$sql = preg_replace("/^\/\*.*/", "", $sql);
}
$dumpfile = implode("\n", $sql);
} else {
echo "vmoodle_load_db_template : Bulk file not found";
return false;
}
// Split into single queries.
$dumpfile = str_replace("\r\n", "\n", $dumpfile); // Translates to Unix LF.
$queries = preg_split("/;\n/", $dumpfile);
// Feed queries in database.
$i = 0;
$j = 0;
if (!empty($queries)) {
foreach ($queries as $query) {
$query = trim($query); // Get rid of trailing spaces and returns.
if ($query == '') {
continue; // Avoid empty queries.
}
$query = mb_convert_encoding($query, 'iso-8859-1', 'auto');
if (!$res = vmoodle_execute_query($vmoodle, $query, $cnx)) {
echo "<hr/>load error on <br/>" . $cnx . "<hr/>";
$j++;
} else {
$i++;
}
}
}
echo "loaded : $i queries succeeded, $j queries failed<br/>";
if ($localcnx) {
vmoodle_close_connection($vmoodle, $cnx);
}
return false;
}
/**
* Get available platforms to send Command.
* @return array The availables platforms based on MNET or Vmoodle table.
*/
function get_available_platforms() {
global $CFG, $DB;
$config = get_config('local_vmoodle');
// Getting description of master host.
$masterhost = $DB->get_record('course', array('id' => 1));
// Setting available platforms.
$aplatforms = array();
if (@$config->host_source == 'vmoodle') {
$id = 'vhostname';
$records = $DB->get_records('local_vmoodle', array(), 'name', $id.', name');
} else {
$id = 'wwwroot';
$moodleapplication = $DB->get_record('mnet_application', array('name' => 'moodle'));
$params = array('deleted' => 0, 'applicationid' => $moodleapplication->id);
$records = $DB->get_records('mnet_host', $params, 'name', $id.', name');
foreach ($records as $key => $record) {
if ($record->name == '' || $record->name == 'All Hosts') {
unset($records[$key]);
}
}
}
if ($records) {
foreach ($records as $record) {
$aplatforms[$record->$id] = $record->name;
}
asort($aplatforms);
}
return $aplatforms;
}
/**
* Return html help icon from library help files.
* @param string $library The vmoodle library to display help file.
* @param string $helpitem The help item to display.
* @param string $title The title of help.
* @return string Html span with help icon.
*/
function help_button_vml($library, $helpitem, $title) {
global $OUTPUT;
// WAFA: help icon no longer take links.
return '';
}
/**
* Get the parameters' values from the placeholders.
* We return both canonic name of the variable and replacement value
* @param array $matches The placeholders found.
* @param array $data The parameters' values to insert.
* @param bool $parameters_replace True if variables should be replaced (optional).
* @param bool $contants_replace True if constants should be replaced (optional).
* @return string The parameters' values.
*/
function replace_parameters_values($matches, $params, $parametersreplace = true, $constantsreplace = true) {
global $vmcommandconstants;
// Parsing constants.
if ($constantsreplace
&& empty($matches[1])
&& array_key_exists($matches[2], $vmcommandconstants)) {
$value = $vmcommandconstants[$matches[2]];
// Parsing parameter.
} else if ($parametersreplace && !empty($matches[1]) && array_key_exists($matches[2], $params)) {
$value = $params[$matches[2]]->get_value();
} else {
// Leave untouched.
return array($matches[2], $matches[0]);
}
if (isset($matches[3]) && is_array($value)) {
// Checking if member is asked.
$value = $value[$matches[3]];
}
return array($matches[2], $value);
}
/**
* Load a vmoodle plugin and cache it.
* @param string $pluginname The plugin name.
* @return Command_Category The category plugin.
*/
function load_vmplugin($pluginname) {
global $CFG;
static $plugins = array();
if (!array_key_exists($pluginname, $plugins)) {
$plugins[$pluginname] = include_once($CFG->dirroot.'/local/vmoodle/plugins/'.$pluginname.'/config.php');
}
return $plugins[$pluginname];
}
/**
* Get available templates for defining a new virtual host.
* @return array The availables templates, or EMPTY array.
*/
function vmoodle_get_available_templates() {
global $CFG;
// Scans the templates.
if (!filesystem_file_exists('vmoodle', $CFG->dataroot)) {
mkdir($CFG->dataroot.'/vmoodle');
}
$dirs = filesystem_scan_dir('vmoodle', FS_IGNORE_HIDDEN, FS_ONLY_DIRS, $CFG->dataroot);
$vtemplates = preg_grep("/^(.*)_vmoodledata$/", $dirs);
// Retrieves template(s) name(s).
$templatesarray = array();
if ($vtemplates) {
foreach ($vtemplates as $vtemplatedir) {
preg_match("/^(.*)_vmoodledata/", $vtemplatedir, $matches);
$templatesarray[$matches[1]] = $matches[1];
if (!isset($first)) {
$first = $matches[1];
}
}
}
$templatesarray[0] = get_string('reactiveorregistertemplate', 'local_vmoodle');
return $templatesarray;
}
/**
* Make a fake vmoodle that represents the current host database configuration.
* @uses $CFG
* @return object The current host's database configuration.
*/
function vmoodle_make_this() {
global $CFG;
$thismoodle = new StdClass;
$thismoodle->vdbtype = $CFG->dbtype;
$thismoodle->vdbhost = $CFG->dbhost;
$thismoodle->vdblogin = $CFG->dbuser;
$thismoodle->vdbpass = $CFG->dbpass;
$thismoodle->vdbname = $CFG->dbname;
$thismoodle->vdbprefix = $CFG->prefix;
return $thismoodle;
}
/**
* Executes a query on a Vmoodle database. Query must return no results,
* so it may be an INSERT or an UPDATE or a DELETE.
* @param object $vmoodle The Vmoodle object.
* @param string $sql The SQL request.
* @param handle $cnx The connection to the Vmoodle database.
* @return boolean true if the request is well-executed, false otherwise.
*/
function vmoodle_execute_query($vmoodle, $sql, $cnx) {
// If database is MySQL typed.
if (($vmoodle->vdbtype == 'mysql')) {
if (!($res = mysql_query($sql, $cnx))) {
echo "vmoodle_execute_query() : ".mysql_error($cnx)."<br/>";
return false;
}
if ($newid = mysql_insert_id($cnx)) {
// Get the last insert id in case of an INSERT.
$res = $newid;
}
} else if (($vmoodle->vdbtype == 'mysqli') || ($vmoodle->vdbtype == 'mariadb')) {
if (!($res = mysqli_query($cnx, $sql))) {
echo "vmoodle_execute_query() : ".mysqli_error($cnx)."<br/>";
return false;
}
if ($newid = mysqli_insert_id($cnx)) {
// Get the last insert id in case of an INSERT.
$res = $newid;
}
} else if ($vmoodle->vdbtype == 'postgres') {
// If database is PostgresSQL typed.
if (!($res = pg_query($cnx, $sql))) {
echo "vmoodle_execute_query() : ".pg_last_error($cnx)."<br/>";
return false;
}
if ($newid = pg_last_oid($res)) {
// Get the last insert id in case of an INSERT.
$res = $newid;
}
} else {
// If database not supported.
echo "vmoodle_execute_query() : Database not supported<br/>";
return false;
}
return $res;
}
/**
* Closes a connection to a Vmoodle database.
* @param object $vmoodle The Vmoodle object.
* @param handle $cnx The connection to the database.
* @return boolean If true, closing the connection is well-executed.
*/
function vmoodle_close_connection($vmoodle, $cnx) {
if (($vmoodle->vdbtype == 'mysqli') || ($vmoodle->vdbtype == 'mariadb')) {
$res = mysqli_close($cnx);
} else if ($vmoodle->vdbtype == 'postgres') {
$res = pg_close($cnx);
} else {
echo "vmoodle_close_connection() : Database not supported<br/>";
$res = false;
}
return $res;
}
/**
* Dumps a SQL database for having a snapshot.
* @param object $vmoodle The Vmoodle object.
* @param string $outputfile The output SQL file.
* @return bool If TRUE, dumping database was a success, otherwise FALSE.
*/
function vmoodle_dump_database($vmoodle, $outputfile) {
global $CFG;
$config = get_config('local_vmoodle');
// Separating host and port, if sticked.
if (strstr($vmoodle->vdbhost, ':') !== false) {
list($host, $port) = explode(':', $vmoodle->vdbhost);
} else {
$host = $vmoodle->vdbhost;
}
// By default, empty password.
$pass = '';
$pgm = null;
if ($vmoodle->vdbtype == 'mysql' || $vmoodle->vdbtype == 'mysqli' || $vmoodle->vdbtype == 'mariadb') {
// Default port.
if (empty($port)) {
$port = 3306;
}
// Password.
if (!empty($vmoodle->vdbpass) && ($CFG->ostype != 'WINDOWS')) {
$pass = "-p".escapeshellarg($vmoodle->vdbpass);
} else {
$pass = "-p".$vmoodle->vdbpass;
}
// Making the command.
if ($CFG->ostype == 'WINDOWS') {
$cmd = "-h{$host} -P{$port} -u{$vmoodle->vdblogin} {$pass} {$vmoodle->vdbname}";
$cmd .= " > " . $outputfile;
} else {
$cmd = "-h{$host} -P{$port} -u{$vmoodle->vdblogin} {$pass} {$vmoodle->vdbname}";
$cmd .= " > " . escapeshellarg($outputfile);
}
// MySQL application (see 'vconfig.php').
$pgm = (!empty($config->cmd_mysqldump)) ? stripslashes($config->cmd_mysqldump) : false;
} else if ($vmoodle->vdbtype == 'postgres') {
// PostgreSQL.
// Default port.
if (empty($port)) {
$port = 5432;
}
// Password.
if (!empty($vmoodle->vdbpass)) {
$pass = '"'.$vmoodle->vdbpass.'"';
}
// Making the command, (if needed, a password prompt will be displayed).
if ($CFG->ostype == 'WINDOWS') {
$cmd = " -d -b -Fc -h {$host} -p {$port} -U {$vmoodle->vdblogin} {$vmoodle->vdbname}";
$cmd .= " > " . $outputfile;
} else {
$cmd = " -d -b -Fc -h {$host} -p {$port} -U {$vmoodle->vdblogin} {$vmoodle->vdbname}";
$cmd .= " > " . escapeshellarg($outputfile);
}
// PostgreSQL application (see 'vconfig.php').
$pgm = (!empty($config->cmd_pgsqldump)) ? $config->cmd_pgsqldump : false;
}
if (!$pgm) {
print_error('dbdumpnotavailable', 'local_vmoodle');
return false;
} else {
$phppgm = str_replace("\\", '/', $pgm);
$phppgm = str_replace("\"", '', $phppgm);
$pgm = str_replace('/', DIRECTORY_SEPARATOR, $pgm);
if (!is_executable($phppgm)) {
print_error('dbcommanderror', 'local_vmoodle', '', $phppgm);
return false;
}
// Final command.
$cmd = $pgm.' '.$cmd;
// Prints log messages in the page and in 'cmd.log'.
if ($log = fopen(dirname($outputfile).'/cmd.log', 'a')) {
fwrite($log, $cmd."\n");
}
// Executes the SQL command.
exec($cmd, $execoutput, $returnvalue);
if ($log) {
foreach ($execoutput as $execline) {
fwrite($log, $execline."\n");
}
fwrite($log, $returnvalue."\n");
fclose($log);
}
}
// End with success.
return true;
}
/**
* Loads a complete database dump from a template, and does some update.
* @uses $CFG, $DB
* @param object $vmoodledata All the Host_form data.
* @param array $outputfile The variables to inject in setup template SQL.
* @return bool If true, loading database from template was sucessful, otherwise false.
*/
function vmoodle_load_database_from_template($vmoodledata) {
global $CFG, $DB;
// Gets the HTTP adress scheme (http, https, etc...) if not specified.
// Use the main site scheme as default.
if (is_null(parse_url($vmoodledata->vhostname, PHP_URL_SCHEME))) {
$vmoodledata->vhostname = parse_url($CFG->wwwroot, PHP_URL_SCHEME).'://'.$vmoodledata->vhostname;
}
$manifest = vmoodle_get_vmanifest($vmoodledata->vtemplate);
$hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
$description = $DB->get_field('course', 'fullname', array('id' => SITEID));
$cfgipaddress = gethostbyname($hostname);
// SQL files paths.
$templatesqlfilepath = $CFG->dataroot.'/vmoodle/'.$vmoodledata->vtemplate.'_sql/vmoodle_master.sql';
// Create temporaries files for replacing data.
$temporarysqlfilepath = $CFG->dataroot.'/vmoodle/'.$vmoodledata->vtemplate.'_sql/vmoodle_master.temp.sql';
// Retrieves files contents into strings.
if (!($dumptxt = file_get_contents($templatesqlfilepath))) {
print_error('nosql', 'local_vmoodle');
return false;
}
// Change the tables prefix if required prefix does not match manifest's one (sql template).
if ($manifest['templatevdbprefix'] != $vmoodledata->vdbprefix) {
$dumptxt = str_replace($manifest['templatevdbprefix'], $vmoodledata->vdbprefix, $dumptxt);
}
// Fix special case on adodb_logsql table if prefix has a schema part (PostgreSQL).
if (preg_match('/(.*)\./', $vmoodledata->vdbprefix, $matches)) {
// We have schema, thus relocate adodb_logsql table within schema.
$dumptxt = str_replace('adodb_logsql', $matches[1].'.adodb_logsql', $dumptxt);
}
// Puts strings into the temporary files.
if (!file_put_contents($temporarysqlfilepath, $dumptxt)) {
print_error('nooutputfortransformedsql', 'local_vmoodle');
return false;
}
$sqlcmd = vmoodle_get_database_dump_cmd($vmoodledata);
// Make final commands to execute, depending on the database type.
$import = $sqlcmd.$temporarysqlfilepath;
// Execute the command.
if (!defined('CLI_SCRIPT')) {
putenv('LANG=en_US.utf-8');
}
// Ensure utf8 is correctly handled by php exec().
// @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input.
exec($import, $output, $return);
if ($return == 1) {
print_error("Could not load database content. ");
}
// End.
return true;
}
/**
* Creates a database for Moodle. Database will be created on host given for the vmoodle instance.
* Check that user/passwrod couple has database creation permissions on that host.
* @param object $vmoodledata
*/
function vmoodle_create_database($vmoodledata) {
global $DB;
// Don't bind to db, it might not yet exist.
$sidecnx = vmoodle_make_connection($vmoodledata, false);
// Availability of SQL commands.
// Checks if paths commands have been properly defined in 'vconfig.php'.
if ($vmoodledata->vdbtype == 'mysql') {
$createstatement = 'CREATE DATABASE IF NOT EXISTS %DATABASE% DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ';
} else if (($vmoodledata->vdbtype == 'mysqli') || ($vmoodledata->vdbtype == 'mariadb')) {
$createstatement = 'CREATE DATABASE IF NOT EXISTS %DATABASE% DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ';
} else if ($vmoodledata->vdbtype == 'postgres') {
$createstatement = 'CREATE SCHEMA IF NOT EXISTS %DATABASE% ';
}
// Creates the new database before importing the data.
$sql = str_replace('%DATABASE%', $vmoodledata->vdbname, $createstatement);
vmoodle_execute_query($vmoodledata, $sql, $sidecnx);
}
/**
* Loads a complete database dump from a template, and does some update.
* @uses $CFG
* @param object $vmoodledata All the Host_form data.
* @param object $thisashost The mnet_host record that represents the master.
* @return bool If true, fixing database from template was sucessful, otherwise false.
*/
function vmoodle_fix_database($vmoodledata, $thisashost) {
global $CFG, $SITE, $DB;
$manifest = vmoodle_get_vmanifest($vmoodledata->vtemplate);
$hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
$cfgipaddress = gethostbyname($hostname);
// SQL files paths.
$temporarysetup_path = $CFG->dataroot.'/vmoodle/'.$vmoodledata->vtemplate.'_sql/vmoodle_setup_template.temp.sql';
if (!$file = fopen($temporarysetup_path, 'wb')) {
print_error('couldnotwritethesetupscript', 'local_vmoodle');
return false;
}
$prefix = $vmoodledata->vdbprefix;
$vmoodledata->description = str_replace("'", "''", $vmoodledata->description);
// Setup moodle name and description.
$sql = "UPDATE {$prefix}course SET fullname='{$vmoodledata->name}', shortname='{$vmoodledata->shortname}',";
$sql .= " summary='{$vmoodledata->description}' WHERE category = 0 AND id = 1;\n";
fwrite($file, $sql);
// Setup a suitable cookie name.
$cookiename = clean_param($vmoodledata->shortname, PARAM_ALPHANUM);
fwrite($file, "UPDATE {$prefix}config SET value='{$cookiename}' WHERE name = 'sessioncookie';\n\n");
// Delete all logs.
fwrite($file, "DELETE FROM {$prefix}log;\n\n");
fwrite($file, "DELETE FROM {$prefix}mnet_log;\n\n");
fwrite($file, "DELETE FROM {$prefix}mnet_session;\n\n"); // Purge mnet logs and sessions.
/*
* we need :
* clean host to service
* clean mnet_hosts unless All Hosts and self record
* rebind self record to new wwwroot, ip and cleaning public key
*/
fwrite($file, "--\n-- Cleans all mnet tables but keeping service configuration in place \n--\n");
// We first remove all services. Services will be next rebuild based on template or minimal strategy.
// We expect all service declaraton are ok in the template DB as the template comes from homothetic installation.
fwrite($file, "DELETE FROM {$prefix}mnet_host2service;\n\n");
// We first remove all services. Services will be next rebuild based on template or minimal strategy.
fwrite($file, "DELETE FROM {$prefix}mnet_host WHERE wwwroot != '' AND wwwroot != '{$manifest['templatewwwroot']}';\n\n");
$vmoodlenodename = str_replace("'", "''", $vmoodledata->name);
$sql = "UPDATE {$prefix}mnet_host SET id = 1, wwwroot = '{$vmoodledata->vhostname}', name = '{$vmoodlenodename}',";
$sql .= " public_key = '', public_key_expires = 0, ip_address = '{$cfgipaddress}' ";
$sql .= "WHERE wwwroot = '{$manifest['templatewwwroot']}';\n\n";
fwrite($file, $sql);
// Ensure consistance.
fwrite($file, "UPDATE {$prefix}config SET value = 1 WHERE name = 'mnet_localhost_id';\n\n");
// Disable all mnet users.
fwrite($file, "UPDATE {$prefix}user SET deleted = 1 WHERE auth = 'mnet' AND username != 'admin';\n\n");
/*
* this is necessary when using a template from another location or deployment target as
* the salt may have changed. We would like that all primary admins be the same techn admin.
*/
// Get primary ID of moodle master.
$params = array('username' => 'admin', 'mnethostid' => $CFG->mnet_localhost_id);
$localadmin = $DB->get_record('user', $params);
if (!$localadmin) {
throw new moodle_exception('No local admin account');
}
fputs($file, "--\n-- Force physical admin with same credentials than in master. \n--\n");
$sql = "UPDATE {$prefix}user SET password = '{$localadmin->password}' WHERE auth = 'manual' AND username = 'admin';\n\n";
fwrite($file, $sql);
if (@$vmoodledata->mnet == -1) { // NO MNET AT ALL.
/*
* we need :
* disable mnet
*/
fputs($file, "UPDATE {$prefix}config SET value = 'off' WHERE name = 'mnet_dispatcher_mode';\n\n");
} else {
// ALL OTHER CASES.
/*
* we need :
* enable mnet
* push our master identity in mnet_host table
*/
fputs($file, "UPDATE {$prefix}config SET value = 'strict' WHERE name = 'mnet_dispatcher_mode';\n\n");
$sql = "INSERT INTO {$prefix}mnet_host (wwwroot, ip_address, name, public_key, applicationid, public_key_expires) ";
$sql .= "VALUES ('{$thisashost->wwwroot}', '{$thisashost->ip_address}', '{$SITE->fullname}', '{$thisashost->public_key}', ";
$sql .= "{$thisashost->applicationid}, '{$thisashost->public_key_expires}');\n\n";
fputs($file, $sql);
fputs($file, "--\n-- Enable the service 'mnetadmin, sso_sp and sso_ip' with host which creates this host. \n--\n");
$sql = "INSERT INTO {$prefix}mnet_host2service VALUES (null, (SELECT id FROM {$prefix}mnet_host ";
$sql .= "WHERE wwwroot LIKE '{$thisashost->wwwroot}'), ";
$sql .= "(SELECT id FROM {$prefix}mnet_service WHERE name LIKE 'mnetadmin'), 1, 0);\n\n";
fputs($file, $sql);
$sql = "INSERT INTO {$prefix}mnet_host2service VALUES (null, (SELECT id FROM {$prefix}mnet_host ";
$sql .= "WHERE wwwroot LIKE '{$thisashost->wwwroot}'), ";
$sql .= "(SELECT id FROM {$prefix}mnet_service WHERE name LIKE 'sso_sp'), 1, 0);\n\n";
fputs($file, $sql);
$sql = "INSERT INTO {$prefix}mnet_host2service VALUES (null, (SELECT id FROM {$prefix}mnet_host ";
$sql .= "WHERE wwwroot LIKE '{$thisashost->wwwroot}'), ";
$sql .= "(SELECT id FROM {$prefix}mnet_service WHERE name LIKE 'sso_idp'), 0, 1);\n\n";
fputs($file, $sql);
fputs($file, "--\n-- Insert master host user admin. \n--\n");
$sql = "INSERT INTO {$prefix}user (auth, confirmed, policyagreed, deleted, mnethostid, username, password) ";
$sql .= "VALUES ('mnet', 1, 0, 0, (SELECT id FROM {$prefix}mnet_host ";
$sql .= "WHERE wwwroot LIKE '{$thisashost->wwwroot}'), 'admin', '');\n\n";
fputs($file, $sql);
fputs($file, "--\n-- Links role and capabilites for master host admin. \n--\n");
$roleid = "(SELECT id FROM {$prefix}role WHERE shortname LIKE 'manager')";
$contextid = 1;
$userid = "(SELECT id FROM {$prefix}user WHERE auth LIKE 'mnet' AND username = 'admin' AND ";
$userid .= "mnethostid = (SELECT id FROM {$prefix}mnet_host WHERE wwwroot LIKE '{$thisashost->wwwroot}'))";
$timemodified = time();
$modifierid = $userid;
$component = "''";
$itemid = 0;
$sortorder = 1;
$sql = "INSERT INTO {$prefix}role_assignments(id,roleid,contextid,userid,timemodified,modifierid,component,itemid,sortorder)";
$sql .= " VALUES (0, $roleid, $contextid, $userid, $timemodified, $modifierid, $component, $itemid, $sortorder);\n\n";
fputs($file, $sql);
fputs($file, "--\n-- Add new network admin to local siteadmins. \n--\n");
$adminidsql = "(SELECT id FROM {$prefix}user WHERE auth LIKE 'mnet' AND username = 'admin' AND ";
$adminidsql .= "mnethostid = (SELECT id FROM {$prefix}mnet_host WHERE wwwroot LIKE '{$thisashost->wwwroot}'))";
fputs($file, "UPDATE {$prefix}config SET value = CONCAT(value, ',', $adminidsql) WHERE name = 'siteadmins';\n");
fputs($file, "--\n-- Create a disposable key for renewing new host's keys. \n--\n");
fputs($file, "INSERT INTO {$prefix}config (name, value) VALUES ('bootstrap_init', '{$thisashost->wwwroot}');\n");
}
fclose($file);
$sqlcmd = vmoodle_get_database_dump_cmd($vmoodledata);
// Make final commands to execute, depending on the database type.
$import = $sqlcmd.' '.$temporarysetup_path.' 2>&1';
/*
* Ensure utf8 is correctly handled by php exec().
* @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
* this is required only with PHP exec through a web access.
*/
if (!CLI_SCRIPT) {
putenv('LANG=en_US.utf-8');
}
// Execute the command.
exec($import, $output, $return);
if ($LOG = fopen($CFG->dataroot.'/vmoodle/'.$vmoodledata->vtemplate.'_sql/cmd.log', 'a')) {
fputs($LOG, $import."\n");
fputs($LOG, implode("\n", $output)."\n");
fclose($LOG);
}
// End.
return true;
}
function vmoodle_destroy($vmoodledata) {
global $DB, $OUTPUT;
if (!$vmoodledata) {
return;
}
// Checks if paths commands have been properly defined in 'vconfig.php'.
if ($vmoodledata->vdbtype == 'mysql') {
$dropstatement = 'DROP DATABASE IF EXISTS';
$sqlescape = "`";
} else if (($vmoodledata->vdbtype == 'mysqli') || ($vmoodledata->vdbtype == 'mariadb')) {
$dropstatement = 'DROP DATABASE IF EXISTS';
$sqlescape = "`";
} else if ($vmoodledata->vdbtype == 'postgres') {
$dropstatement = 'DROP SCHEMA';
$sqlescape = "'";
}
// Drop the database.
$sql = "$dropstatement {$sqlescape}{$vmoodledata->vdbname}{$sqlescape}";
if (function_exists('debug_trace')) {
debug_trace("destroy_database : executing drop sql");
}
try {
$DB->execute($sql);
} catch (Exception $e) {
$e = new StdClass;
$e->sql = $sql;
$e->error = $DB->get_last_error();
print_error('noexecutionfor', 'local_vmoodle', '', $e);
}
// Destroy moodledata.
if ($CFG->ostype == 'WINDOWS') {
$cmd = " RMDIR \"$vmoodledata->vdatapath\" ";
} else {
$cmd = " rm -rf \"$vmoodledata->vdatapath\" ";
}
exec($cmd);
// Delete vmoodle instance.
$DB->delete_records('local_vmoodle', array('vhostname' => $vmoodledata->vhostname));
// Delete all related mnet_hosts info.
if ($mnethost = $DB->get_record('mnet_host', array('wwwroot' => $vmoodledata->vhostname))) {
$DB->delete_records('mnet_host', array('wwwroot' => $mnethost->wwwroot));
$DB->delete_records('mnet_host2service', array('hostid' => $mnethost->id));
$DB->delete_records('mnetservice_enrol_courses', array('hostid' => $mnethost->id));
$DB->delete_records('mnetservice_enrol_enrolments', array('hostid' => $mnethost->id));
$DB->delete_records('mnet_log', array('hostid' => $mnethost->id));
$DB->delete_records('mnet_session', array('mnethostid' => $mnethost->id));
$DB->delete_records('mnet_sso_access_control', array('mnet_host_id' => $mnethost->id));
}
// If using domain subpath, add the subpath symlink (Linux only).
if (!empty($CFG->vmoodleusesubpaths)) {
vmoodle_del_subpath($vmoodledata);
}
}
/**
* get a proper SQLDump command
* @param object $vmoodledata the complete new host information
* @return string the shell command
*/
function vmoodle_get_database_dump_cmd($vmoodledata) {
global $CFG;
$config = get_config('local_vmoodle');
// Checks if paths commands have been properly defined in 'vconfig.php'.
if ($vmoodledata->vdbtype == 'mysql') {
$pgm = (!empty($config->cmd_mysql)) ? stripslashes($config->cmd_mysql) : false;
} else if (($vmoodledata->vdbtype == 'mysqli') || ($vmoodledata->vdbtype == 'mariadb')) {
$pgm = (!empty($config->cmd_mysql)) ? stripslashes($config->cmd_mysql) : false;
} else if ($vmoodledata->vdbtype == 'postgres') {
// Needs to point the pg_restore command.
$pgm = (!empty($config->cmd_pgsql)) ? stripslashes($config->cmd_pgsql) : false;
}
// Checks the needed program.
if (!$pgm){
print_error('dbcommandnotconfigured', 'local_vmoodle');
return false;