forked from vfremaux/moodle-local_vmoodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.php
1550 lines (1346 loc) · 57.5 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
*/
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 MySQL and PostgreSQL paths for commands.
*/
// Windows.
if ($CFG->ostype == 'WINDOWS') {
$CFG->vmoodle_cmd_mysql = '';
$CFG->vmoodle_cmd_mysqldump = '';
$CFG->vmoodle_cmd_pgsql = '';
$CFG->vmoodle_cmd_pgsqldump = '';
} else {
// Linux.
$CFG->vmoodle_cmd_mysql = '/usr/bin/mysql';
$CFG->vmoodle_cmd_mysqldump = '/usr/bin/mysqldump';
$CFG->vmoodle_cmd_pgsql = '/usr/bin/pgsql';
$CFG->vmoodle_cmd_pgsqldump = '/usr/bin/pgsqldump';
}
/** Define commands' constants */
$vmcommands_constants = array(
'prefix' => $CFG->prefix,
'wwwroot' => $CFG->wwwroot,
);
// Loading plugin librairies
$plugin_libs = glob($CFG->dirroot.'/local/vmoodle/plugins/*/lib.php');
foreach ($plugin_libs as $lib) {
require_once $lib;
}
/**
* 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();
}
/**
* setup and configure a mnet environment that describes this vmoodle
* @uses $USER for generating keys
* @uses $CFG
* @param object $vmoodle
* @param handle $cnx a connection
*/
function vmoodle_setup_mnet_environment($vmoodle, $cnx) {
global $USER, $CFG;
// Make an empty mnet environment.
$mnet_env = new mnet_environment();
$mnet_env->wwwroot = $vmoodle->vhostname;
$mnet_env->ip_address = $CFG->local_vmoodle_vmoodleip;
$mnet_env->keypair = array();
$mnet_env->keypair = mnet_generate_keypair(null);
$mnet_env->public_key = $mnet_env->keypair['certificate'];
$details = openssl_x509_parse($mnet_env->public_key);
$mnet_env->public_key_expires = $details['validTo_time_t'];
return $mnet_env;
}
/**
* setup services for a given mnet environment in a database
* @uses $CFG
* @param object $mnet_env an environment with valid id
* @param handle $cnx a connection to the target bdd
* @param object $services an object that holds service setup data
*/
function vmoodle_add_services(&$vmoodle, $mnet_env, $cnx, $services) {
if (!$mnet_env->id) {
return false;
}
if ($services) {
foreach ($services as $service => $keys) {
$sql = "
INSERT INTO
{$vmoodle->vdbprefix}mnet_host2service(
hostid,
serviceid,
publish,
subscribe)
VALUES (
{$mnet_env->id},
$service,
{$keys['publish']},
{$keys['subscribe']}
)
";
vmoodle_execute_query($vmoodle, $sql, $cnx);
}
}
}
/**
* get available services in the master
* @return array of service descriptors.
*/
function vmoodle_get_service_desc() {
global $DB;
$services = $DB->get_records('mnet_service', array('offer' => 1));
$service_descriptor = array();
if ($services) {
foreach ($services as $service) {
$service_descriptor[$service->id]['publish'] = 1;
$service_descriptor[$service->id]['subscribe'] = 1;
}
}
return $service_descriptor;
}
/**
* given a complete mnet_environment record, and a connection
* record this mnet host in remote database. If the record is
* a new one, gives back a completed env with valid remote id.
* @param object $mnet_env
* @param handle $cnx
* @return the inserted mnet_env object
*/
function vmoodle_register_mnet_peer(&$vmoodle, $mnet_env, $cnx) {
$mnet_array = get_object_vars($mnet_env);
if (empty($mnet_env->id)) {
foreach($mnet_array as $key => $value) {
if ($key == 'id') {
continue;
}
$keylist[] = $key;
$valuelist[] = "'$value'";
}
$keyset = implode(',', $keylist);
$valueset = implode(',', $valuelist);
$sql = "
INSERT INTO
{$vmoodle->vdbprefix}mnet_host(
{$keyset}
)
VALUES(
{$valueset}
)
";
$mnet_env->id = vmoodle_execute_query($vmoodle, $sql, $cnx);
} else {
foreach($mnet_array as $key => $value) {
$valuelist[] = "$key = '$value'";
}
unset($valuelist['id']);
$valueset = implode(',', $valuelist);
$sql = "
UPDATE
{$vmoodle->vdbprefix}mnet_host
SET
{$valueset}
WHERE
id = {$mnet_array['id']}
";
vmoodle_execute_query($vmoodle, $sql, $cnx);
}
return $mnet_env;
}
/**
* get the mnet_env record for an host
* @param object $vmoodle
* @return object a mnet_host record
*/
function vmoodle_get_mnet_env(&$vmoodle) {
global $DB;
$mnet_env = $DB->get_record('mnet_host', array('wwwroot' => $vmoodle->vhostname));
return $mnet_env;
}
/**
* unregister a vmoodle from the whole remaining network
* @uses $CFG
* $param object $vmoodle
* @param handle $cnx
* @param object $fromvmoodle
*/
function vmoodle_unregister_mnet(&$vmoodle, $fromvmoodle ) {
global $CFG;
if ($fromvmoodle) {
$vdbprefix = $fromvmoodle->vdbprefix;
} else {
$vdbprefix = $CFG->prefix;
}
$cnx = vmoodle_make_connection($fromvmoodle, true);
// cleanup all services for the deleted host
$sql = "
DELETE FROM
{$vmoodle->vdbprefix}mnet_host2service
WHERE
hostid = (SELECT
id
FROM
{$vdbprefix}mnet_host
WHERE
wwwroot = '{$vmoodle->vhostname}')
";
vmoodle_execute_query($vmoodle, $sql, $cnx);
// Delete the host.
$sql = "
DELETE FROM
{$vmoodle->vdbprefix}mnet_host
WHERE
wwwroot = '{$vmoodle->vhostname}'
";
vmoodle_execute_query($vmoodle, $sql, $cnx);
}
/**
* drop a vmoodle database
* @param object $vmoodle
* @param handle $side_cnx
*/
function vmoodle_drop_database(&$vmoodle, $cnx = null) {
// Try to delete database.
$local_cnx = 0;
if (!$cnx) {
$local_cnx = 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}`
";
} elseif($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 ($local_cnx) {
vmoodle_close_connection($vmoodle, $cnx);
}
}
return false;
}
/**
* 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;
$local_cnx = 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);
$local_cnx = 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 ($local_cnx) {
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;
// Getting description of master host.
$master_host = $DB->get_record('course', array('id' => 1));
// Setting available platforms.
$aplatforms = array();
if (@$CFG->local_vmoodle_host_source == 'vmoodle') {
$id = 'vhostname';
$records = $DB->get_records('local_vmoodle', array(), 'name', $id.', name');
if (!empty($CFG->vmoodledefault)) {
$records[] = (object) array($id => $CFG->wwwroot, 'name' => $master_host->fullname);
}
} else {
$id = 'wwwroot';
$moodleapplication = $DB->get_record('mnet_application', array('name' => 'moodle'));
$records = $DB->get_records('mnet_host', array('deleted' => 0, 'applicationid' => $moodleapplication->id), 'name', $id.', name');
foreach ($records as $key => $record) {
if ($record->name == '' || $record->name == 'All Hosts')
unset($records[$key]);
}
$records[] = (object) array($id => $CFG->wwwroot, 'name' => $master_host->fullname);
}
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, it now takes identifiers to
//return $OUTPUT->help_icon('helprouter.html&library='.$library.'&helpitem='.$helpitem, 'local_vmoodle', false);
return "";//$OUTPUT->help_icon('helprouter.html&library='.$library.'&helpitem='.$helpitem, 'local_vmoodle', false);
}
/**
* 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, $parameters_replace = true, $constants_replace = true) {
global $vmcommands_constants;
// Parsing constants.
if ($constants_replace
&& empty($matches[1])
&& array_key_exists($matches[2], $vmcommands_constants)) {
$value = $vmcommands_constants[$matches[2]];
// Parsing parameter
} else if ($parameters_replace && !empty($matches[1]) && array_key_exists($matches[2], $params)) {
$value = $params[$matches[2]]->getValue();
/*
$paramtype = $params[$matches[2]]->getType();
if ($paramtype == 'text' || $paramtype == 'ltext'){
// probably obsolete when transferring to Moodle placeholders
// $value = str_replace("'", "''", $params[$matches[2]]->getValue());
$value = $params[$matches[2]]->getValue();
} else {
$value = $params[$matches[2]]->getValue();
}
*/
// Leave untouched
} else {
return array($matches[2], $matches[0]);
}
// Checking if member is asked.
if (isset($matches[3]) && is_array($value)) {
$value = $value[$matches[3]];
}
return array($matches[2], $value);
}
/**
* Print the start of a collapsable block.
* @param string $id The id of the block.
* @param string $caption The caption of the block.
* @param string $classes The CSS classes of the block.
* @param string $displayed True if the block is displayed by default, false otherwise.
*/
function print_collapsable_bloc_start($id, $caption, $classes = '', $displayed = true) {
global $CFG, $OUTPUT;
$caption = strip_tags($caption);
$pixpath = ($displayed) ? '/t/switch_minus' : '/t/switch_plus';
echo '<div id="vmblock_'.$id.'">'.
'<div class="header">'.
'<div class="title">'.
'<input '.
'type="image" class="hide-show-image" '.
'onclick="elementToggleHide(this, false, function(el) {
return findParentNode(el, \'DIV\', \'bvmc\');
}, \''.get_string('show').' '.$caption.'\', \''.get_string('hide').' '.$caption.'\'); return false;" '.
'src="'.$OUTPUT->pix_url($pixpath).'" '.
'alt="'.get_string('show').' '.strip_tags($caption).'" '.
'title="'.get_string('show').' '.strip_tags($caption).'"/>'.
'<h2>'.strip_tags($caption).'</h2>'.
'</div>'.
'</div>';
$hidden = ($displayed) ? '' : ' hidden';
echo '<div class="content bvmc '.$hidden.'">';
}
/**
* Print the end of a collapsable block.
*/
function print_collapsable_block_end() {
echo '</div></div>';
}
/**
* Load a vmoodle plugin and cache it.
* @param string $plugin_name The plugin name.
* @return Command_Category The category plugin.
*/
function load_vmplugin($plugin_name) {
global $CFG;
static $plugins = array();
if (!array_key_exists($plugin_name, $plugins)) {
$plugins[$plugin_name] = include_once($CFG->dirroot.'/local/vmoodle/plugins/'.$plugin_name.'/config.php');
}
return $plugins[$plugin_name];
}
/**
* 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[] = get_string('reactivetemplate', '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->vdbpersist = $CFG->dbpersist; //not available in 2.2
$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)) {
$res = $newid; // get the last insert id in case of an INSERT
}
}
// If database is PostgresSQL typed.
elseif ($vmoodle->vdbtype == 'postgres') {
if (!($res = pg_query($cnx, $sql))) {
echo "vmoodle_execute_query() : ".pg_last_error($cnx)."<br/>";
return false;
}
if ($newid = pg_last_oid($res)) {
$res = $newid; // Get the last insert id in case of an INSERT.
}
}
// If database not supported.
else {
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 == 'mysql') {
$res = mysql_close($cnx);
} elseif($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;
// Separating host and port, if sticked.
if (strstr($vmoodle->vdbhost, ':') !== false) {
list($host, $port) = split(':', $vmoodle->vdbhost);
} else {
$host = $vmoodle->vdbhost;
}
// By default, empty password.
$pass = '';
$pgm = null;
if ($vmoodle->vdbtype == 'mysql' || $vmoodle->vdbtype == 'mysqli') { // MysQL.
// Default port.
if (empty($port)) {
$port = 3306;
}
// Password.
if (!empty($vmoodle->vdbpass)) {
$pass = "-p".escapeshellarg($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($CFG->local_vmoodle_cmd_mysqldump)) ? stripslashes($CFG->local_vmoodle_cmd_mysqldump) : false;
} elseif ($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($CFG->local_vmoodle_cmd_pgsqldump)) ? $CFG->vmoodle_cmd_pgsqldump : false;
}
if (!$pgm) {
error("Database dump command not available");
return false;
} else {
$phppgm = str_replace("\\", '/', $pgm);
$phppgm = str_replace("\"", '', $phppgm);
$pgm = str_replace('/', DIRECTORY_SEPARATOR, $pgm);
if (!is_executable($phppgm)) {
error("Database dump command $phppgm does not match any executable");
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.
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);
// 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 utf8 COLLATE utf8_general_ci ';
} elseif ($vmoodledata->vdbtype == 'mysqli') {
$createstatement = 'CREATE DATABASE IF NOT EXISTS %DATABASE% DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ';
} elseif ($vmoodledata->vdbtype == 'postgres') {
$createstatement = 'CREATE SCHEMA %DATABASE% ';
}
// SQL files paths.
$templatesqlfile_path = $CFG->dataroot.'/vmoodle/'.$vmoodledata->vtemplate.'_sql/vmoodle_master.sql';
// Create temporaries files for replacing data.
$temporarysqlfile_path = $CFG->dataroot.'/vmoodle/'.$vmoodledata->vtemplate.'_sql/vmoodle_master.temp.sql';
// Retrieves files contents into strings.
// debug_trace("load_database_from_dump : getting sql content");
if (!($dumptxt = file_get_contents($templatesqlfile_path))) {
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.
// debug_trace("load_database_from_dump : writing modified sql");
if (!file_put_contents($temporarysqlfile_path, $dumptxt)) {
print_error('nooutputfortransformedsql', 'local_vmoodle');
return false;
}
// Creates the new database before importing the data.
$sql = str_replace('%DATABASE%', $vmoodledata->vdbname, $createstatement);
// debug_trace("load_database_from_dump : executing creation sql");
if (!$DB->execute($sql)) {
print_error('noexecutionfor','local_vmoodle', $sql);
return false;
}
$sqlcmd = vmoodle_get_database_dump_cmd($vmoodledata);
// Make final commands to execute, depending on the database type.
$import = $sqlcmd.$temporarysqlfile_path;
// Execute the command.
// debug_trace("load_database_from_dump : executing feeding sql");
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);
// debug_trace(implode("\n", $output)."\n");
// Remove temporary files.
// if(!unlink($temporarysqlfile_path))){
// return false;
// }
// End.
// debug_trace("load_database_from_dump : OUT");
return true;
}
/**
* Loads a complete database dump from a template, and does some update.
* @uses $CFG
* @param object $vmoodledata All the Host_form data.
* @param object $this_as_host 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, $this_as_host) {
global $CFG, $SITE;
// debug_trace('fixing_database ; IN');
$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';
// debug_trace('fixing_database ; opening setup script file');
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.
fwrite($FILE, "UPDATE {$PREFIX}course SET fullname='{$vmoodledata->name}', shortname='{$vmoodledata->shortname}', summary='{$vmoodledata->description}' WHERE category = 0 AND id = 1;\n");
// 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);
fwrite($FILE, "UPDATE {$PREFIX}mnet_host SET id = 1, wwwroot = '{$vmoodledata->vhostname}', name = '{$vmoodlenodename}' , public_key = '', public_key_expires = 0, ip_address = '{$cfgipaddress}' WHERE wwwroot = '{$manifest['templatewwwroot']}';\n\n");
fwrite($FILE, "UPDATE {$PREFIX}config SET value = 1 WHERE name = 'mnet_localhost_id';\n\n"); // ensure consistance
fwrite($FILE, "UPDATE {$PREFIX}user SET deleted = 1 WHERE auth = 'mnet' AND username != 'admin';\n\n"); // disable all mnet users
/*
* 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.
*/
$localadmin = get_admin();
fputs($FILE, "--\n-- Force physical admin with same credentials than in master. \n--\n");
fwrite($FILE, "UPDATE {$PREFIX}user SET password = '{$localadmin->password}' WHERE auth = 'manual' AND username = 'admin';\n\n");
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");
fputs($FILE, "INSERT INTO {$PREFIX}mnet_host (wwwroot, ip_address, name, public_key, applicationid, public_key_expires) VALUES ('{$this_as_host->wwwroot}', '{$this_as_host->ip_address}', '{$SITE->fullname}', '{$this_as_host->public_key}', {$this_as_host->applicationid}, '{$this_as_host->public_key_expires}');\n\n");
fputs($FILE, "--\n-- Enable the service 'mnetadmin, sso_sp and sso_ip' with host which creates this host. \n--\n");
fputs($FILE, "INSERT INTO {$PREFIX}mnet_host2service VALUES (null, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'mnetadmin'), 1, 0);\n\n");
fputs($FILE, "INSERT INTO {$PREFIX}mnet_host2service VALUES (null, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'sso_sp'), 1, 0);\n\n");
fputs($FILE, "INSERT INTO {$PREFIX}mnet_host2service VALUES (null, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'sso_idp'), 0, 1);\n\n");
fputs($FILE, "--\n-- Insert master host user admin. \n--\n");
fputs($FILE, "INSERT INTO {$PREFIX}user (auth, confirmed, policyagreed, deleted, mnethostid, username, password) VALUES ('mnet', 1, 0, 0, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), 'admin', '');\n\n");
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 mnethostid = (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'))";
$timemodified = time();
$modifierid = $userid;
$component = "''";
$itemid = 0;
$sortorder = 1;
fputs($FILE, "INSERT INTO {$PREFIX}role_assignments(id,roleid,contextid,userid,timemodified,modifierid,component,itemid,sortorder) VALUES (0, $roleid, $contextid, $userid, $timemodified, $modifierid, $component, $itemid, $sortorder);\n\n");
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 mnethostid = (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->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', '{$this_as_host->wwwroot}');\n");
}
fclose($FILE);
// debug_trace('fixing_database ; setup script written');
$sqlcmd = vmoodle_get_database_dump_cmd($vmoodledata);
// Make final commands to execute, depending on the database type.
$import = $sqlcmd.$temporarysetup_path;
// Prints log messages in the page and in 'cmd.log'.
// debug_trace("fixing_database ; executing $import ");
// 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);
// debug_trace(implode("\n", $output)."\n");
// Remove temporary files.
// if(!unlink($temporarysetup_path)){
// return false;
// }
// 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';
} elseif ($vmoodledata->vdbtype == 'mysqli') {
$dropstatement = 'DROP DATABASE IF EXISTS';
} elseif ($vmoodledata->vdbtype == 'postgres') {
$dropstatement = 'DROP SCHEMA';
}
// Drop the database.
$sql = "$dropstatement $vmoodledata->vdbname";
debug_trace("destroy_database : executing drop sql");
try {