locallib.php 26.3 KB
Newer Older
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
<?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 <jcrodriguez@dis.ulpgc.es>
 */
defined('MOODLE_INTERNAL') || die();

define( 'VPL', 'vpl' );
define( 'VPL_SUBMISSIONS', 'vpl_submissions' );
define( 'VPL_JAILSERVERS', 'vpl_jailservers' );
define( 'VPL_RUNNING_PROCESSES', 'vpl_running_processes' );
define( 'VPL_VARIATIONS', 'vpl_variations' );
define( 'VPL_ASSIGNED_VARIATIONS', 'vpl_assigned_variations' );
define( 'VPL_GRADE_CAPABILITY', 'mod/vpl:grade' );
define( 'VPL_VIEW_CAPABILITY', 'mod/vpl:view' );
define( 'VPL_SUBMIT_CAPABILITY', 'mod/vpl:submit' );
define( 'VPL_SIMILARITY_CAPABILITY', 'mod/vpl:similarity' );
define( 'VPL_ADDINSTANCE_CAPABILITY', 'mod/vpl:addinstance' );
define( 'VPL_SETJAILS_CAPABILITY', 'mod/vpl:setjails' );
39
define( 'VPL_MANAGE_VIA_WS_CAPABILITY', 'mod/vpl:manageviaws' );
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
define( 'VPL_MANAGE_CAPABILITY', 'mod/vpl:manage' );

require_once(dirname(__FILE__).'/vpl.class.php');

/**
 * 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 )) { // Exists var?
        $res = $SESSION->$fullname;
    }
65
    $res = optional_param( $parname, $res, PARAM_RAW );
66
67
68
69
    $SESSION->$fullname = $res;
    return $res;
}

70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
 * 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');
        }
    }
}

84
85
86
87
88
89
90
91
92
/**
 * Open/create a file and its dir
 *
 * @param string $filename. Path to the file to open
 * @return resource file descriptor
 */
function vpl_fopen($filename) {
    if (! file_exists( $filename )) { // Exists file?
        $dir = dirname( $filename );
93
        vpl_create_dir($dir);
94
    }
95
    $fp = fopen( $filename, 'w+b' );
96
    if ($fp === false) {
97
98
99
100
101
102
103
104
105
106
107
108
        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.");
109
    }
110
111
112
    return $fp;
}

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/**
 * 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 = $res && fclose( $fd );
    if ($res === false) {
        throw new file_exception('storedfileproblem', 'Error writing a file in VPL');
    }
}

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
/**
 * 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 = array ();
            while ( $name = readdir( $dd ) ) {
                if ($name != '.' && $name != '..') {
                    $list [] = $name;
                }
            }
            closedir( $dd );
            foreach ($list as $name) {
                $ret = vpl_delete_dir( $dirname . '/' . $name ) and $ret;
            }
            $ret = rmdir( $dirname ) and $ret;
        } else {
            $ret = unlink( $dirname );
        }
    }
    return $ret;
}

/**
 * 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)) {
        print_error("Zip file not found");
        die;
    }
    // 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 );
}

/**
 * Get lang code @parm $bashadapt true adapt lang to bash LANG (default false)
 *
 * @return string
 */
function vpl_get_lang($bashadapt = false) {
    global $SESSION, $USER, $CFG;
    $commonlangs = array (
            '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',
            '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 {
        $lang = '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;
}

/**
 * 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 ? '&amp;' : '?') . urlencode( $parms [$p] ) . '=' . urlencode( $parms [$p + 1] );
    }
    return $href;
}

/**
 * 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 ? '&amp;' : '?') . urlencode( $parms [$p] ) . '=' . urlencode( $parms [$p + 1] );
    }
    return $href;
}

/**
 * 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 ? '&amp;' : '?') . urlencode( $parms [$p] ) . '=' . urlencode( $parms [$p + 1] );
    }
    return $url;
}
/**
 * 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 . '&amp;' . urlencode( $parm ) . '=' . urlencode( $value );
    } else {
        return $url . '?' . urlencode( $parm ) . '=' . urlencode( $value );
    }
}

/**
 * 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;
382
    if (!$OUTPUT->has_started()) {
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        echo $OUTPUT->header();
    }
    echo $OUTPUT->notification($message, $type);
    echo $OUTPUT->continue_button($link);
    echo $OUTPUT->footer();
    die();
}

/**
 * Inmediate redirect
 *
 * @param string $url URL to redirect to
 * @return void
 */
function vpl_inmediate_redirect($url) {
398
    echo vpl_include_js( 'window.location.replace("' . html_entity_decode(urldecode($url)) . '");' );
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
    die();
}
/**
 * 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 );
}

/**
 * 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;
}

/**
 * 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;
    }
}
function vpl_get_select_time($maximum = null) {
    $minute = 60;
    if ($maximum === null) { // Default value.
        $maximum = 35 * $minute;
    }
    $ret = array (
            0 => get_string( 'select' )
    );
    if ($maximum <= 0) {
        return $ret;
    }
    $value = 4;
    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;
}

/**
 * Return the post_max_size PHP config option in bytes
 *
 * @return int max size in bytes
 */
function vpl_get_max_post_size() {
    $maxs = trim( ini_get( 'post_max_size' ) );
    $len = strlen( $maxs );
489
    $max = ( int ) $maxs;
490
491
492
493
494
495
496
497
    $last = strtolower( $maxs [$len - 1] );
    if ($last == 'k') {
        $max *= 1024;
    } else if ($last == 'm') {
        $max *= 1024 * 1024;
    } else if ($last == 'g') {
        $max *= 1024 * 1024 * 1000;
    }
498
499
500
    if ($maxs === '0') {
        $max = PHP_INT_MAX;
    }
501
502
503
504
    return $max;
}

/**
505
506
507
508
 * 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
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
 *
 * @return string
 */
function vpl_conv_size_to_string($size) {
    static $measure = array (
            1024,
            1048576,
            1073741824,
            1099511627776,
            PHP_INT_MAX
    );
    static $measurename = array (
            '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] );
            }
        }
    }
}

/**
 * Return the array key after or equal to value
 *
 * @param $array
546
547
 * @param int $value of key to search >=
 * @return int key found
548
549
 */
function vpl_get_array_key($array, $value) {
550
551
552
    reset($array);
    $last = 0;
    while (($key = key($array)) !== null) {
553
        if ($key >= $value) {
554
            reset($array);
555
556
            return $key;
        }
557
558
        $last = $key;
        next($array);
559
    }
560
561
    reset($array);
    return $last;
562
563
564
}

/**
565
566
 * Returns an array with the format [size in bytes]=> size in text.
 * The first element is [0] => select.
567
568
569
 *
 * @param int $minimum the initial value
 * @param int $maximum the limit of values generates
570
571
 *
 * @return array Key value => Text value
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
 */
function vpl_get_select_sizes($minimum = 0, $maximum = PHP_INT_MAX) {
    $maximum = ( int ) $maximum;
    if ($maximum < 0) {
        $maximum = PHP_INT_MAX;
    }
    if ($maximum > 17.0e9) {
        $maximum = 16 * 1073741824;
    }
    $ret = array (
            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;
}

/**
610
 * Detects end of line separator.
611
 *
612
613
614
 * @param string& $data Text to check.
 *
 * @return string Newline separator "\r\n", "\n", "\r".
615
616
617
618
619
620
621
622
623
624
625
626
627
628
 */
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.
    }
}

629
function vpl_notice(string $text, $type = 'success') {
630
631
632
633
634
    global $OUTPUT;
    echo $OUTPUT->notification( $text, $type );
}

/**
635
636
637
 * Remove trailing right zeros from a float as string
 *
 * @param string $value float to remove right zeros
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
 *
 * @return string
 */
function vpl_rtzeros($value) {
    if (strpos( $value, '.' ) || strpos( $value, ',' )) {
        return rtrim( rtrim( $value, '0' ), '.,' );
    }
    return $value;
}

/**
 * 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 = array ();
    foreach ($array as $value) {
        $ret [$value] = $url . $value;
    }
    return $ret;
}

/**
 * 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 = array ();
    foreach ($array as $value) {
        $ret [$url . $value] = get_string( $value, VPL );
    }
    return $ret;
}
function vpl_fileextension($filename) {
    return pathinfo( $filename, PATHINFO_EXTENSION );
}


/**
 * 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;
}

/**
 * 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|';
702
    $fileext .= 'rar|rpm|db|dll|rtf|doc|docx|odt|xls|xlsx';
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
    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';
}

/**
 * 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 );
}

/**
 * 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 );
}

/**
 * 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;
}

/**
 * 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;
}

/**
 * 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 ) . '...';
}

function vpl_bash_export($var, $value) {
    if ( is_int($value) ) {
        return 'export ' . $var . '=' . $value . "\n";
    } else {
        return 'export ' . $var . "='" . str_replace( "'", "'\"'\"'", $value ) . "'\n";
    }
}

/**
 * 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);
}

/**
 * Truncate string fields of the VPL table
 * @param $instance object with the record
 * @return void
 */
function vpl_truncate_vpl($instance) {
    vpl_truncate_string( $instance->name, 255 );
    vpl_truncate_string( $instance->requirednet, 255 );
    vpl_truncate_string( $instance->password, 255 );
    vpl_truncate_string( $instance->variationtitle, 255 );
}

/**
 * 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 );
}

/**
 * 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 );
}

/**
 * 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 );
}

/**
 * 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 );
}

/**
 * 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 '';
}


/**
 * 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 );
}

/**
 * Get version string
 * @return string
 */
function vpl_get_version() {
895
    static $version;
896
897
    if (! isset( $version )) {
        $plugin = new stdClass();
898
        require(dirname( __FILE__ ) . '/version.php');
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
        $version = $plugin->release;
    }
    return $version;
}

function vpl_get_webservice_available() {
    global $DB, $USER, $CFG;
    if ($USER->id <= 2) {
        return false;
    }
    if (! $CFG->enablewebservices) {
        return false;
    }
    $service = $DB->get_record( 'external_services', array (
            'shortname' => 'mod_vpl_edit',
            'enabled' => 1
    ) );
    return ! empty( $service );
}
function vpl_get_webservice_token($vpl) {
919
    global $DB, $USER, $CFG;
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
    $now = time();
    if ($USER->id <= 2) {
        return '';
    }
    if (! $CFG->enablewebservices) {
        return '';
    }
    $service = $DB->get_record( 'external_services', array (
            'shortname' => 'mod_vpl_edit',
            'enabled' => 1
    ) );
    if (empty( $service )) {
        return '';
    }
    $tokenrecord = $DB->get_record( 'external_tokens', array (
            'userid' => $USER->id,
            'externalserviceid' => $service->id
    ) );
938
    if (! empty( $tokenrecord ) and $tokenrecord->validuntil > 0 and $tokenrecord->validuntil < $now) {
939
        unset( $tokenrecord ); // Will be deleted before creating a new one.
940
941
    }
    if (empty( $tokenrecord )) {
942
943
944
945
946
        $webservice = new webservice();
        $webservice->generate_user_ws_tokens($USER->id);
        $tokenrecord = $DB->get_record( 'external_tokens', array (
                'userid' => $USER->id,
                'externalserviceid' => $service->id
947
        ) );
948
949
950
        if (empty( $tokenrecord )) {
            return '';
        }
951
952
953
954
955
956
957
958
959
    }
    return $tokenrecord->token;
}
function vpl_get_webservice_urlbase($vpl) {
    global $CFG;
    $token = vpl_get_webservice_token( $vpl );
    if ($token == '') {
        return '';
    }
960
    return $CFG->wwwroot . '/webservice/rest/server.php?moodlewsrestformat=json'
961
962
           . '&wstoken=' . $token . '&id=' . $vpl->get_course_module()->id . '&wsfunction=';
}
963

964
965
function vpl_timestamp_to_midday($timestamp) {
    return $timestamp - ($timestamp + date('Z')) % 86400 + 43200;
966
967
968
969
970
971
972
973
974
975
}

function vpl_get_name_fields_display() {
    // Load name display format.
    $nameformat = new stdClass();
    foreach (get_all_user_name_fields() as $namefield) {
        $nameformat->$namefield = get_string( $namefield ) . ' / ';
    }
    $strname = trim(fullname($nameformat));
    return substr($strname, 0, strlen($strname) - 2);
Astor Bizard's avatar
Astor Bizard committed
976
977
978
979
980
981
982
983
984
985
986
987
}

/**
 * Return action_menu_link for menu in list
 * @param string $str
 * @param moodle_url $link
 * @param string $comp value for get_string
 * @return action_menu_link_secondary
 */
function vpl_get_menu_action_link($str, $link, $comp = 'mod_vpl') {
    $stri18n = get_string($str, $comp);
    return new action_menu_link_secondary($link, new pix_icon($str, '', 'mod_vpl'),  $stri18n);
988
}