-
Notifications
You must be signed in to change notification settings - Fork 88
/
locallib.php
1206 lines (1146 loc) · 30.7 KB
/
locallib.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 VPL for Moodle - http://vpl.dis.ulpgc.es/
//
// VPL for 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.
//
// VPL for 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 VPL for Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Common functions of VPL
*
* @package mod_vpl
* @copyright 2012 Juan Carlos Rodríguez-del-Pino
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Juan Carlos Rodríguez-del-Pino <[email protected]>
*/
defined('MOODLE_INTERNAL') || die();
require_once(dirname(__FILE__).'/locallib_consts.php');
require_once(dirname(__FILE__).'/vpl.class.php');
/**
* @codeCoverageIgnore
*
* Set get vpl session var
*
* @param string $varname
* name of the session var without 'vpl_'
* @param string $default
* default value
* @param string $parname
* optional parameter name
* @return $varname/param value
*/
function vpl_get_set_session_var($varname, $default, $parname = null) {
global $SESSION;
if ($parname == null) {
$parname = $varname;
}
$res = $default;
$fullname = 'vpl_' . $varname;
if (isset( $SESSION->$fullname )) {
$res = $SESSION->$fullname;
}
$res = optional_param( $parname, $res, PARAM_RAW );
$SESSION->$fullname = $res;
return $res;
}
/**
* @codeCoverageIgnore
*
* Create directory if not exist
*
* @param $dir string path to directory
*/
function vpl_create_dir($dir) {
global $CFG;
if (! file_exists( $dir )) { // Create dir?
if (! mkdir( $dir, $CFG->directorypermissions, true ) ) {
throw new file_exception('storedfileproblem', 'Error creating a directory to save files in VPL');
}
}
}
/**
* @codeCoverageIgnore
*
* Open/create a file and its dir
*
* @param $filename string path to file
* @return Object file descriptor
*/
function vpl_fopen($filename) {
if (! file_exists( $filename )) { // Exists file?
$dir = dirname( $filename );
vpl_create_dir($dir);
}
$fp = fopen( $filename, 'w+b' );
if ($fp === false) {
if (DIRECTORY_SEPARATOR == '\\' ) {
$pathparts = pathinfo($filename);
$name = $pathparts['filename'];
if (preg_match( '/(^aux$)|(^con$)|(^prn$)|(^nul$)|(^com\d$)|(^lpt\d$)/i' , $name) == 1) {
$patchedfilename = $pathparts['dirname'] . '\\_n_p_' . $pathparts['basename'];
return vpl_fopen($patchedfilename);
}
}
}
if ($fp === false) {
debugging( "Error creating file in VPL '$filename'.", DEBUG_NORMAL );
throw new file_exception('storedfileproblem', "Error creating file in VPL.");
}
return $fp;
}
/**
* @codeCoverageIgnore
*
* Open/create a file and its dir and write contents
*
* @param string $filename. Path to the file to open
* @param string $contents. Contents to write into the file
* @exception file_exception
* @return void
*/
function vpl_fwrite($filename, $contents) {
if ( is_file($filename) ) {
unlink($filename);
}
$fd = vpl_fopen( $filename );
$res = ftruncate ( $fd, 0);
$res = $res && (fwrite( $fd, $contents ) !== false);
$res = fclose( $fd ) && $res;
if ($res === false) {
throw new file_exception('storedfileproblem', 'Error writing a file in VPL');
}
}
/**
* @codeCoverageIgnore
*
* Recursively delete a directory
*
* @return bool All delete
*/
function vpl_delete_dir($dirname) {
$ret = false;
if (file_exists( $dirname )) {
$ret = true;
if (is_dir( $dirname )) {
$dd = opendir( $dirname );
if (! $dd) {
return false;
}
$list = [];
while ( $name = readdir( $dd ) ) {
if ($name != '.' && $name != '..') {
$list[] = $name;
}
}
closedir( $dd );
foreach ($list as $name) {
$ret = vpl_delete_dir( $dirname . '/' . $name ) && $ret;
}
$ret = rmdir( $dirname ) && $ret;
} else {
$ret = unlink( $dirname );
}
}
return $ret;
}
/**
* @codeCoverageIgnore
*
* Outputs a zip file and removes it. Must be called before any other output
*
* @param string $zipfilename. Name of the ZIP file with the data
* @param string $name of file to be shown, without '.zip'
*
*/
function vpl_output_zip($zipfilename, $name) {
if (! file_exists($zipfilename)) {
debugging("Zip file not found " . $zipfilename, DEBUG_DEVELOPER);
throw new moodle_exception('error:zipnotfound', 'mod_vpl');
}
// Send zipdata.
$blocksize = 1000 * 1024;
$size = filesize( $zipfilename );
$cname = rawurlencode( $name . '.zip' );
$contentdisposition = 'Content-Disposition: attachment;';
$contentdisposition .= ' filename="' . $name . '.zip";';
$contentdisposition .= ' filename*=utf-8\'\'' . $cname;
@header( 'Content-Length: ' . $size );
@header( 'Content-Type: application/zip; charset=utf-8' );
@header( $contentdisposition );
@header( 'Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0' );
@header( 'Content-Transfer-Encoding: binary' );
@header( 'Expires: 0' );
@header( 'Pragma: no-cache' );
@header( 'Accept-Ranges: none' );
// Get zip data.
$offset = 0;
while ($offset < $size) {
echo file_get_contents( $zipfilename, false, null, $offset, $blocksize);
$offset += $blocksize;
}
// Remove zip file.
unlink( $zipfilename );
}
/**
* @codeCoverageIgnore
*
* Get lang code @parm $bashadapt true adapt lang to bash LANG (default true)
*
* @return string
*/
function vpl_get_lang($bashadapt = true) {
global $SESSION, $USER, $CFG;
$commonlangs = [
'aa' => 'DJ',
'af' => 'ZA',
'am' => 'ET',
'an' => 'ES',
'az' => 'AZ',
'ber' => 'DZ',
'bg' => 'BG',
'ca' => 'ES',
'cs' => 'CZ',
'da' => 'DK',
'de' => 'DE',
'dz' => 'BT',
'en' => 'US',
'es' => 'ES',
'et' => 'EE',
'fa' => 'IR',
'fi' => 'FI',
'fr' => 'FR',
'he' => 'IL',
'hu' => 'HU',
'ig' => 'NG',
'it' => 'IT',
'is' => 'IS',
'ja' => 'JP',
'km' => 'KH',
'ko' => 'KR',
'lo' => 'LA',
'lv' => 'LV',
'pt' => 'PT',
'ro' => 'RO',
'ru' => 'RU',
'se' => 'NO',
'sk' => 'sk',
'so' => 'SO',
'sv' => 'SE',
'or' => 'IN',
'th' => 'th',
'ti' => 'ET',
'tk' => 'TM',
'tr' => 'TR',
'uk' => 'UA',
'yo' => 'NG',
];
if (isset( $SESSION->lang )) {
$lang = $SESSION->lang;
} else if (isset( $USER->lang )) {
$lang = $USER->lang;
} else if (isset( $CFG->lang )) {
$lang = $CFG->lang;
} else {
return "en";
}
if ($bashadapt) {
$parts = explode( '_', $lang );
if (count($parts) == 2) {
$lang = $parts[0];
}
if (isset($commonlangs[$lang])) {
$lang = $lang . '_' . $commonlangs[$lang];
}
$lang .= '.UTF-8';
}
return $lang;
}
/**
* @codeCoverageIgnore
*
* generate URL to page with params
*
* @param $page string
* page from wwwroot
* @param $var1 string
* var1 name optional
* @param $value1 string
* value of var1 optional
* @param $var2 string
* var2 name optional
* @param $value2 string
* value of var2 optional
* @param
* ...
*/
function vpl_abs_href() {
global $CFG;
$parms = func_get_args();
$l = count( $parms );
$href = $CFG->wwwroot . $parms[0];
for ($p = 1; $p < $l - 1; $p += 2) {
$href .= ($p > 1 ? '&' : '?') . urlencode( $parms[$p] ) . '=' . urlencode( $parms[$p + 1] );
}
return $href;
}
/**
* @codeCoverageIgnore
*
* generate URL to page with params
*
* @param $page string
* page from wwwroot/mod/vpl/
* @param $var1 string
* var1 name optional
* @param $value1 string
* value of var1 optional
* @param $var2 string
* var2 name optional
* @param $value2 string
* value of var2 optional
* @param
* ...
*/
function vpl_mod_href() {
global $CFG;
$parms = func_get_args();
$l = count( $parms );
$href = $CFG->wwwroot . '/mod/vpl/' . $parms[0];
for ($p = 1; $p < $l - 1; $p += 2) {
$href .= ($p > 1 ? '&' : '?') . urlencode( $parms[$p] ) . '=' . urlencode( $parms[$p + 1] );
}
return $href;
}
/**
* @codeCoverageIgnore
*
* @todo This function is to be remove when Moodle 3.10 be not supported by VPL.
* Return 'gradeoun' or 'grade' for backward compatibility.
* @return string
*/
function vpl_get_gradenoun_str() {
if (get_string_manager()->string_exists('gradenoun', 'core')) {
return 'gradenoun';
}
return 'grade';
}
/**
* @codeCoverageIgnore
*
* generate URL relative page with params
*
* @param $page string
* page relative
* @param $var1 string
* var1 name optional
* @param $value1 string
* value of var1 optional
* @param $var2 string
* var2 name optional
* @param $value2 string
* value of var2 optional
* @param
* ...
*/
function vpl_rel_url() {
$parms = func_get_args();
$l = count( $parms );
$url = $parms[0];
for ($p = 1; $p < $l - 1; $p += 2) {
$url .= ($p > 1 ? '&' : '?') . urlencode( $parms[$p] ) . '=' . urlencode( $parms[$p + 1] );
}
return $url;
}
/**
* @codeCoverageIgnore
*
* Add a parm to a url
*
* @param $url string
* @param $parm string
* name
* @param $value string
* value of parm
*/
function vpl_url_add_param($url, $parm, $value) {
if (strpos( $url, '?' )) {
return $url . '&' . urlencode( $parm ) . '=' . urlencode( $value );
} else {
return $url . '?' . urlencode( $parm ) . '=' . urlencode( $value );
}
}
/**
* @codeCoverageIgnore
*
* Print a message and redirect
*
* @param string $link. The URL to redirect to
* @param string $message to be print
* @param string $type of message (success, info, warning, error). Default = info
* @return void
*/
function vpl_redirect($link, $message, $type = 'info', $errorcode='') {
global $OUTPUT;
if (! mod_vpl::header_is_out()) {
echo $OUTPUT->header();
}
echo $OUTPUT->notification($message, $type);
echo $OUTPUT->continue_button($link);
echo $OUTPUT->footer();
die();
}
/**
* @codeCoverageIgnore
*
* Inmediate redirect
*
* @param string $url URL to redirect to
* @return void
*/
function vpl_inmediate_redirect($url) {
global $OUTPUT;
if (! mod_vpl::header_is_out()) {
echo $OUTPUT->header();
}
static $idcount = 0;
$idcount ++;
$text = '<div class="continuebutton"><a id="vpl_red' . $idcount . '" href="';
$text .= $url. '">' . get_string( 'continue' ) . '</a></div>';
$deco = urldecode( $url);
$deco = html_entity_decode( $deco );
echo vpl_include_js( 'window.location.replace("' . $deco . '");' );
echo $text;
echo $OUTPUT->footer();
die();
}
/**
* @codeCoverageIgnore
*
* Set JavaScript file from subdir jscript to be load
*
* @param $file string
* name of file to load
* @param $defer boolean
* optional set if the load is inmediate or deffered
* @return void
*/
function vpl_include_jsfile($file, $defer = true) {
global $PAGE;
$PAGE->requires->js( new moodle_url( '/mod/vpl/jscript/' . $file ), ! $defer );
}
/**
* @codeCoverageIgnore
*
* Set JavaScript code to be included
*
* @param $jscript string
* JavaScript code
* @return void
*/
function vpl_include_js($jscript) {
if ($jscript == '') {
return '';
}
$ret = '<script type="text/javascript">';
$ret .= "\n//<![CDATA[\n";
$ret .= $jscript;
$ret .= "\n//]]>\n</script>\n";
return $ret;
}
/**
* @codeCoverageIgnore
*
* Popup message box to show text
*
* @param string $text to show. It use s() to sanitize text
* @param boolean $print or not
* @return void
*/
function vpl_js_alert($text, $print = true) {
$aux = addslashes( $text ); // Sanitize text.
$aux = str_replace( "\n", "\\n", $aux ); // Add \n to show multiline text.
$aux = str_replace( "\r", "", $aux ); // Remove \r.
$ret = vpl_include_js( 'alert("' . $aux . '");' );
if ($print) {
echo $ret;
@ob_flush();
flush();
} else {
return $ret;
}
}
/**
* @codeCoverageIgnore
*/
function vpl_get_select_time($maximum = null) {
$minute = 60;
if ($maximum === null) { // Default value.
$maximum = 35 * $minute;
}
$ret = [
0 => get_string( 'select' ),
];
if ($maximum <= 0) {
return $ret;
}
$value = 1;
if ($maximum < $value) {
$value = $maximum;
}
while ( $value <= $maximum ) {
if ($value < $minute) {
$ret[$value] = get_string( 'numseconds', '', $value );
} else {
$num = ( int ) ($value / $minute);
$ret[$num * $minute] = get_string( 'numminutes', '', $num );
$value = $num * $minute;
}
$value *= 2;
}
return $ret;
}
/**
* @codeCoverageIgnore
*
* Converts a size in byte to string in Kb, Mb, Gb and Tb.
* Follows IEC "Prefixes for binary multiples".
*
* @param int $size Size in bytes
*
* @return string
*/
function vpl_conv_size_to_string($size) {
static $measure = [
1024,
1048576,
1073741824,
1099511627776,
PHP_INT_MAX,
];
static $measurename = [
'KiB',
'MiB',
'GiB',
'TiB',
];
for ($i = 0; $i < count( $measure ) - 1; $i ++) {
if ($measure[$i] <= 0) { // Check for int overflow.
$num = $size / $measure[$i - 1];
return sprintf( '%.2f %s', $num, $measurename[$i - 1] );
}
if ($size < $measure[$i + 1]) {
$num = $size / $measure[$i];
if ($num >= 3 || $size % $measure[$i] == 0) {
return sprintf( '%4d %s', $num, $measurename[$i] );
} else {
return sprintf( '%.2f %s', $num, $measurename[$i] );
}
}
}
}
/**
* @codeCoverageIgnore
*
* Return the array key after or equal to value
*
* @param $array
* @param int $value of key to search >=
* @return int key found
*/
function vpl_get_array_key($array, int $value) {
reset($array);
$last = 0;
while (($key = key($array)) !== null) {
if ($key >= $value) {
reset($array);
return $key;
}
$last = $key;
next($array);
}
reset($array);
return $last;
}
/**
* @codeCoverageIgnore
*
* Returns un array with the format [size in bytes] => size in text.
* The first element is [0] => select.
*
* @param int $minimum the initial value
* @param int $maximum the limit of values generates
*
* @return array Key value => Text value
*/
function vpl_get_select_sizes(int $minimum = 0, int $maximum = PHP_INT_MAX): array {
$maximum = ( int ) $maximum;
if ($maximum < 0) {
$maximum = PHP_INT_MAX;
}
if ($maximum > 17.0e9) {
$maximum = 16 * 1073741824;
}
$ret = [
0 => get_string( 'select' ),
];
if ($minimum > 0) {
$value = $minimum;
} else {
$value = 256 * 1024;
}
$pre = 0;
$increment = $value / 4;
while ( $value <= $maximum && $value > 0 ) { // Avoid int overflow.
$ret[$value] = vpl_conv_size_to_string( $value );
$pre = $value;
$value += $increment;
$value = ( int ) $value;
if ($pre >= $value) { // Check for loop end.
break;
}
if ($value >= 8 * $increment) {
$increment = $value / 4;
}
}
if ($pre < $maximum) { // Show limit value.
$ret[$maximum] = vpl_conv_size_to_string($maximum);
}
return $ret;
}
/**
* @codeCoverageIgnore
*
* Detects end of line separator.
*
* @param string& $data Text to check.
*
* @return string Newline separator "\r\n", "\n", "\r".
*/
function vpl_detect_newline(&$data) {
// Detect text newline chars.
if (strrpos( $data, "\r\n" ) !== false) {
return "\r\n"; // Windows.
} else if (strrpos($data, "\n") !== false) {
return "\n"; // UNIX.
} else if (strrpos($data, "\r") !== false) {
return "\r"; // Mac.
} else {
return "\n"; // Default Unix.
}
}
/**
* @codeCoverageIgnore
*/
function vpl_notice(string $text, $type = 'success') {
global $OUTPUT;
echo $OUTPUT->notification($text, $type);
}
/**
* @codeCoverageIgnore
*
* Remove trailing right zeros from a float as string
*
* @param string $value float to remove right zeros
*
* @return string
*/
function vpl_rtzeros($value) {
if (strpos($value, '.') || strpos($value, ',')) {
return rtrim(rtrim($value, '0'), '.,');
}
return $value;
}
/**
* @codeCoverageIgnore
*
* Generate an array with index an values $url.index
*
* @param string $url base
* @param $array array of index
* @return array with index as key and url as value
*/
function vpl_select_index($url, $array) {
$ret = [];
foreach ($array as $value) {
$ret[$value] = $url . $value;
}
return $ret;
}
/**
* @codeCoverageIgnore
*
* Generate an array ready to be use in $OUTPUT->select_url
*
* @param string $url base
* @param array $array of values
* @return array with url as key and text as value
*/
function vpl_select_array($url, $array) {
$ret = [];
foreach ($array as $value) {
$ret[$url . $value] = get_string( $value, VPL );
}
return $ret;
}
/**
* @codeCoverageIgnore
*/
function vpl_fileextension($filename) {
return pathinfo( $filename, PATHINFO_EXTENSION );
}
/**
* @codeCoverageIgnore
*
* Get if filename has image extension
* @param string $filename
* @return boolean
*/
function vpl_is_image($filename) {
return preg_match( '/^(gif|jpg|jpeg|png|ico)$/i', vpl_fileextension( $filename ) ) == 1;
}
/**
* @codeCoverageIgnore
*
* Get if filename has binary extension or binary data
* @param string $filename
* @param string &$data file contents
* @return boolean
*/
function vpl_is_binary($filename, &$data = false) {
if ( vpl_is_image( $filename ) ) {
return true;
}
$fileext = 'zip|jar|pdf|tar|bin|7z|arj|deb|gzip|';
$fileext .= 'rar|rpm|dat|db|dll|rtf|doc|docx|odt|exe|com';
if ( preg_match( '/^(' . $fileext . ')$/i', vpl_fileextension( $filename ) ) == 1 ) {
return true;
}
if ($data === false) {
return false;
}
return mb_detect_encoding( $data, 'UTF-8', true ) != 'UTF-8';
}
/**
* @codeCoverageIgnore
*
* Return data encoded to base64
* @param string $filename
* @param string &$data file contents
* @return string
*/
function vpl_encode_binary($filename, &$data) {
return base64_encode( $data );
}
/**
* @codeCoverageIgnore
*
* Return data decoded from base64
* @param string $filename
* @param string &$data file contents
* @return string
*/
function vpl_decode_binary($filename, $data) {
return base64_decode( $data );
}
/**
* @codeCoverageIgnore
*
* Return if path is valid
* @param string $path
* @return boolean
*/
function vpl_is_valid_path_name($path) {
if (strlen( $path ) > 256) {
return false;
}
$dirs = explode( '/', $path );
for ($i = 0; $i < count( $dirs ); $i ++) {
if (! vpl_is_valid_file_name( $dirs[$i] )) {
return false;
}
}
return true;
}
/**
* @codeCoverageIgnore
*
* Return if file or directory name is valid
* @param string $name
* @return boolean
*/
function vpl_is_valid_file_name($name) {
$backtick = chr( 96 ); // Avoid warnning in codecheck.
$regexp = '/[\x00-\x1f]|[:-@]|[{-~]|\\\\|\[|\]|[\/\^';
$regexp .= $backtick . '´]|^\-|^ | $|^\.$|^\.\.$/';
if (strlen( $name ) < 1) {
return false;
}
if (strlen( $name ) > 128) {
return false;
}
return preg_match( $regexp, $name ) === 0;
}
/**
* @codeCoverageIgnore
*
* Truncate string to the limit passed
* @param string &$string
* @param int $limit
*/
function vpl_truncate_string(&$string, $limit) {
if (strlen( $string ) <= $limit) {
return;
}
$string = substr( $string, 0, $limit - 3 ) . '...';
}
/**
* @codeCoverageIgnore
*/
function vpl_bash_export($var, $value) {
if ( is_int($value) ) {
$ret = "export $var=$value\n";
} else if (is_array($value)) {
$ret = "export $var=( ";
foreach ($value as $data) {
$ret .= '"' . str_replace('"', '\"', $data) . '" ';
}
$ret .= ")\n";
} else {
$ret = "export $var=\"";
$ret .= str_replace('"', '\"', $value);
$ret .= "\"\n";
}
return $ret;
}
/**
* @codeCoverageIgnore
*
* For debug purpose
* Return content of vars ready to HTML
*/
function vpl_s() {
$var = func_get_args();
ob_start();
call_user_func_array('var_dump', $var);
$content = ob_get_contents();
ob_end_clean();
return htmlspecialchars($content, ENT_QUOTES);
}
/**
* @codeCoverageIgnore
*
* Truncate string fields of the VPL table
* @param $instance object with the record
* @return void
*/
function vpl_truncate_vpl($instance) {
if (isset($instance->password)) {
$instance->password = trim($instance->password);
}
if (property_exists($instance, 'jailservers') && $instance->jailservers == null) {
$instance->jailservers = '';
}
foreach (['name', 'requirednet', 'password', 'variationtitle'] as $field) {
if (isset($instance->$field)) {
vpl_truncate_string( $instance->$field, 255 );
}
}
}
/**
* @codeCoverageIgnore
*
* Truncate string fields of the variations table
* @param $instance object with the record
* @return void
*/
function vpl_truncate_variations($instance) {
vpl_truncate_string( $instance->identification, 40 );
}
/**
* @codeCoverageIgnore
*
* Truncate string fields of the running_processes table
* @param $instance object with the record
* @return void
*/
function vpl_truncate_running_processes($instance) {
vpl_truncate_string( $instance->server, 255 );
}
/**
* @codeCoverageIgnore
*
* Truncate string fields of the jailservers table
* @param $instance object with the record
* @return void
*/
function vpl_truncate_jailservers($instance) {
vpl_truncate_string( $instance->laststrerror, 255 );
vpl_truncate_string( $instance->server, 255 );
}
/**
* @codeCoverageIgnore
*
* Check if IP is within networks
*
* @param $networks string with conma separate networks
* @param $ip string optional with the IP to check, if omited then remote IP
*
* @return boolean true found
*/
function vpl_check_network($networks, $ip = false) {
$networks = trim($networks);
if ($networks == '') {
return true;
}
if ($ip === false) {
$ip = getremoteaddr();
}
return address_in_subnet( $ip, $networks );
}
/**
* @codeCoverageIgnore
*
* Get awesome icon for action
* @param String $id
* @return string
*/
function vpl_get_awesome_icon($str, $classes = '') {
$icon = 'mod_vpl:' . $str;
$imap = mod_vpl_get_fontawesome_icon_map();
if ( isset( $imap[$icon]) ) {
$ficon = $imap[$icon];
return '<i class="fa ' . $ficon . $classes . '"></i> ';
}
return '';
}
/**
* @codeCoverageIgnore
*
* Create a new tabobject for navigation
* @param String $id
* @param string|moodle_url $href
* @param string $str to be i18n
* @param string $comp component
* @return tabobject
*/
function vpl_create_tabobject($id, $href, $str, $comp = 'mod_vpl') {
$stri18n = get_string( $str, $comp);
$strdescription = vpl_get_awesome_icon($str) . $stri18n;
return new tabobject( $id, $href, $strdescription, $stri18n );
}
/**
* @codeCoverageIgnore
*
* Get version string
* @return string
*/
function vpl_get_version() {
static $version = '';
if ($version === '' && false) { // Removed version information.
$plugin = new stdClass();
require_once(dirname( __FILE__ ) . '/version.php');
$version = $plugin->release;
}
return $version;