mirrored from git://git.moodle.org/moodle.git
/
weblib.php
4072 lines (3627 loc) · 135 KB
/
weblib.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/>.
/**
* Library of functions for web output
*
* Library of all general-purpose Moodle PHP functions and constants
* that produce HTML output
*
* Other main libraries:
* - datalib.php - functions that access the database.
* - moodlelib.php - general-purpose Moodle functions.
*
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/// Constants
/// Define text formatting types ... eventually we can add Wiki, BBcode etc
/**
* Does all sorts of transformations and filtering
*/
define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
/**
* Plain HTML (with some tags stripped)
*/
define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
/**
* Plain text (even tags are printed in full)
*/
define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
/**
* Wiki-formatted text
* Deprecated: left here just to note that '3' is not used (at the moment)
* and to catch any latent wiki-like text (which generates an error)
*/
define('FORMAT_WIKI', '3'); // Wiki-formatted text
/**
* Markdown-formatted text http://daringfireball.net/projects/markdown/
*/
define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
/**
* TRUSTTEXT marker - if present in text, text cleaning should be bypassed
*/
define('TRUSTTEXT', '#####TRUSTTEXT#####');
/**
* A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
*/
define('URL_MATCH_BASE', 0);
/**
* A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2
*/
define('URL_MATCH_PARAMS', 1);
/**
* A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
*/
define('URL_MATCH_EXACT', 2);
/**
* Allowed tags - string of html tags that can be tested against for safe html tags
* @global string $ALLOWED_TAGS
* @name $ALLOWED_TAGS
*/
global $ALLOWED_TAGS;
$ALLOWED_TAGS =
'<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
/**
* Allowed protocols - array of protocols that are safe to use in links and so on
* @global string $ALLOWED_PROTOCOLS
* @name $ALLOWED_PROTOCOLS
*/
$ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
/// Functions
/**
* Add quotes to HTML characters
*
* Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
* This function is very similar to {@link p()}
*
* @todo Remove obsolete param $obsolete if not used anywhere
*
* @param string $var the string potentially containing HTML characters
* @param boolean $obsolete no longer used.
* @return string
*/
function s($var, $obsolete = false) {
if ($var == '0') { // for integer 0, boolean false, string '0'
return '0';
}
return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars($var));
}
/**
* Add quotes to HTML characters
*
* Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
* This function simply calls {@link s()}
* @see s()
*
* @todo Remove obsolete param $obsolete if not used anywhere
*
* @param string $var the string potentially containing HTML characters
* @param boolean $obsolete no longer used.
* @return string
*/
function p($var, $obsolete = false) {
echo s($var, $obsolete);
}
/**
* Does proper javascript quoting.
*
* Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
*
* @param mixed $var String, Array, or Object to add slashes to
* @return mixed quoted result
*/
function addslashes_js($var) {
if (is_string($var)) {
$var = str_replace('\\', '\\\\', $var);
$var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
$var = str_replace('</', '<\/', $var); // XHTML compliance
} else if (is_array($var)) {
$var = array_map('addslashes_js', $var);
} else if (is_object($var)) {
$a = get_object_vars($var);
foreach ($a as $key=>$value) {
$a[$key] = addslashes_js($value);
}
$var = (object)$a;
}
return $var;
}
/**
* Remove query string from url
*
* Takes in a URL and returns it without the querystring portion
*
* @param string $url the url which may have a query string attached
* @return string The remaining URL
*/
function strip_querystring($url) {
if ($commapos = strpos($url, '?')) {
return substr($url, 0, $commapos);
} else {
return $url;
}
}
/**
* Returns the URL of the HTTP_REFERER, less the querystring portion if required
*
* @uses $_SERVER
* @param boolean $stripquery if true, also removes the query part of the url.
* @return string The resulting referer or emtpy string
*/
function get_referer($stripquery=true) {
if (isset($_SERVER['HTTP_REFERER'])) {
if ($stripquery) {
return strip_querystring($_SERVER['HTTP_REFERER']);
} else {
return $_SERVER['HTTP_REFERER'];
}
} else {
return '';
}
}
/**
* Returns the name of the current script, WITH the querystring portion.
*
* This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
* return different things depending on a lot of things like your OS, Web
* server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
* <b>NOTE:</b> This function returns false if the global variables needed are not set.
*
* @global string
* @return mixed String, or false if the global variables needed are not set
*/
function me() {
global $ME;
return $ME;
}
/**
* Returns the name of the current script, WITH the full URL.
*
* This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
* return different things depending on a lot of things like your OS, Web
* server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.
* <b>NOTE:</b> This function returns false if the global variables needed are not set.
*
* Like {@link me()} but returns a full URL
* @see me()
*
* @global string
* @return mixed String, or false if the global variables needed are not set
*/
function qualified_me() {
global $FULLME;
return $FULLME;
}
/**
* Class for creating and manipulating urls.
*
* It can be used in moodle pages where config.php has been included without any further includes.
*
* It is useful for manipulating urls with long lists of params.
* One situation where it will be useful is a page which links to itself to perfrom various actions
* and / or to process form data. A moodle_url object :
* can be created for a page to refer to itself with all the proper get params being passed from page call to
* page call and methods can be used to output a url including all the params, optionally adding and overriding
* params and can also be used to
* - output the url without any get params
* - and output the params as hidden fields to be output within a form
*
* One important usage note is that data passed to methods out, out_action, get_query_string and
* hidden_params_out affect what is returned by the function and do not change the data stored in the object.
* This is to help with typical usage of these objects where one object is used to output urls
* in many places in a page.
*
* @link http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url See short write up here
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package moodlecore
*/
class moodle_url {
/**
* @var string
* @access protected
*/
protected $scheme = ''; // e.g. http
protected $host = '';
protected $port = '';
protected $user = '';
protected $pass = '';
protected $path = '';
protected $fragment = '';
/**
* @var array
* @access protected
*/
protected $params = array(); // Associative array of query string params
/**
* Pass no arguments to create a url that refers to this page.
* Use empty string to create empty url.
*
* @global string
* @param mixed $url a number of different forms are accespted:
* null - create a URL that is the same as the URL used to load this page, but with no query string
* '' - and empty URL
* string - a URL, will be parsed into it's bits, including query string
* array - as returned from the PHP function parse_url
* moodle_url - make a copy of another moodle_url
* @param array $params these params override anything in the query string
* where params have the same name.
*/
public function __construct($url = null, $params = array()) {
if ($url === '') {
// Leave URL blank.
} else if (is_a($url, 'moodle_url')) {
$this->scheme = $url->scheme;
$this->host = $url->host;
$this->port = $url->port;
$this->user = $url->user;
$this->pass = $url->pass;
$this->path = $url->path;
$this->fragment = $url->fragment;
$this->params = $url->params;
} else {
if ($url === null) {
global $ME;
$url = $ME;
}
if (is_string($url)) {
$url = parse_url($url);
}
$parts = $url;
if ($parts === FALSE) {
throw new moodle_exception('invalidurl');
}
if (isset($parts['query'])) {
parse_str(str_replace('&', '&', $parts['query']), $this->params);
}
unset($parts['query']);
foreach ($parts as $key => $value) {
$this->$key = $value;
}
}
$this->params($params);
}
/**
* Add an array of params to the params for this page.
*
* The added params override existing ones if they have the same name.
*
* @param array $params Defaults to null. If null then returns all params.
* @return array Array of Params for url.
*/
public function params($params = null) {
if (!is_null($params)) {
return $this->params = $params + $this->params;
} else {
return $this->params;
}
}
/**
* Remove all params if no arguments passed.
* Remove selected params if arguments are passed.
*
* Can be called as either remove_params('param1', 'param2')
* or remove_params(array('param1', 'param2')).
*
* @param mixed $params either an array of param names, or a string param name,
* @param string $params,... any number of additional param names.
*/
public function remove_params($params = NULL) {
if (empty($params)) {
$this->params = array();
return;
}
if (!is_array($params)) {
$params = func_get_args();
}
foreach ($params as $param) {
if (isset($this->params[$param])) {
unset($this->params[$param]);
}
}
}
/**
* Add a param to the params for this page.
*
* The added param overrides existing one if theyhave the same name.
*
* @param string $paramname name
* @param string $param Param value. Defaults to null. If null then return value of param 'name'
* @return void|string If $param was null then the value of $paramname was returned
* (null is returned if that param does not exist).
*/
public function param($paramname, $param = null) {
if (!is_null($param)) {
$this->params = array($paramname => $param) + $this->params;
} else if (array_key_exists($paramname, $this->params)) {
return $this->params[$paramname];
} else {
return null;
}
}
/**
* Get the params as as a query string.
*
* @param array $overrideparams params to add to the output params, these
* override existing ones with the same name.
* @param boolean $escaped Use & as params separator instead of plain &
* @return string query string that can be added to a url.
*/
public function get_query_string($overrideparams = array(), $escaped = true) {
$arr = array();
$params = $overrideparams + $this->params;
foreach ($params as $key => $val) {
$arr[] = urlencode($key)."=".urlencode($val);
}
if ($escaped) {
return implode('&', $arr);
} else {
return implode('&', $arr);
}
}
/**
* Outputs params as hidden form elements.
*
* @param array $exclude params to ignore
* @param integer $indent indentation
* @param array $overrideparams params to add to the output params, these
* override existing ones with the same name.
* @return string html for form elements.
*/
public function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()) {
$tabindent = str_repeat("\t", $indent);
$str = '';
$params = $overrideparams + $this->params;
foreach ($params as $key => $val) {
if (FALSE === array_search($key, $exclude)) {
$val = s($val);
$str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
}
}
return $str;
}
/**
* Output url
*
* If you use the returned URL in HTML code, you want the escaped ampersands. If you use
* the returned URL in HTTP headers, you want $escaped=false.
*
* @param boolean $omitquerystring whether to output page params as a query string in the url.
* @param array $overrideparams params to add to the output url, these override existing ones with the same name.
* @param boolean $escaped Use & as params separator instead of plain &
* @return string Resulting URL
*/
public function out($omitquerystring = false, $overrideparams = array(), $escaped = true) {
$uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
$uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
$uri .= $this->host ? $this->host : '';
$uri .= $this->port ? ':'.$this->port : '';
$uri .= $this->path ? $this->path : '';
if (!$omitquerystring) {
$querystring = $this->get_query_string($overrideparams, $escaped);
if ($querystring) {
$uri .= '?' . $querystring;
}
}
$uri .= $this->fragment ? '#'.$this->fragment : '';
return $uri;
}
/**
* Return a URL relative to $CFG->wwwroot.
*
* Throws an exception if this URL does not start with $CFG->wwwroot.
*
* The main use for this is when you want to pass a returnurl from one script to another.
* In this case the returnurl should be relative to $CFG->wwwroot for two reasons.
* First, it is shorter. More imporatantly, some web servers (e.g. IIS by default)
* give a 'security' error if you try to pass a full URL as a GET parameter in another URL.
*
* @return string the URL relative to $CFG->wwwroot. Note, you will need to urlencode
* this result if you are outputting a URL manually (but not if you are adding
* it to another moodle_url).
*/
public function out_returnurl() {
global $CFG;
$fulluri = $this->out(false, array(), false);
$uri = str_replace($CFG->wwwroot . '/', '', $fulluri);
if ($uri == $fulluri) {
throw new coding_exception('This URL (' . $fulluri . ') is not relative to $CFG->wwwroot.');
}
return $uri;
}
/**
* Output action url with sesskey
*
* Adds sesskey and overriderparams then calls {@link out()}
* @see out()
*
* @param array $overrideparams Allows you to override params
* @return string url
*/
public function out_action($overrideparams = array()) {
$overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
return $this->out(false, $overrideparams);
}
/**
* Compares this moodle_url with another
* See documentation of constants for an explanation of the comparison flags.
* @param moodle_url $url The moodle_url object to compare
* @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
* @return boolean
*/
public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
if ($this->out(true) != $url->out(true)) {
return false;
}
if ($matchtype == URL_MATCH_BASE) {
return true;
}
$urlparams = $url->params();
foreach ($this->params() as $param => $value) {
if ($param == 'sesskey') {
continue;
}
if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
return false;
}
}
if ($matchtype == URL_MATCH_PARAMS) {
return true;
}
foreach ($urlparams as $param => $value) {
if ($param == 'sesskey') {
continue;
}
if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
return false;
}
}
return true;
}
}
/**
* Given an unknown $url type (string or moodle_url), returns a string URL.
* A relative URL is handled with $PAGE->url but gives a debugging error.
*
* @param mixed $url The URL (moodle_url or string)
* @param bool $stripformparams Whether or not to strip the query params from the URL
* @return string the URL. &s are unescaped. You must use s(...) to output this to XHTML. ($OUTPUT normally does this automatically.)
*/
function prepare_url($url, $stripformparams=false) {
global $CFG, $PAGE;
$output = $url;
if ($url instanceof moodle_url) {
$output = $url->out($stripformparams, array(), false);
}
// Handle relative URLs
if (substr($output, 0, 4) != 'http' && substr($output, 0, 1) != '/') {
if (preg_match('/(.*)\/([A-Za-z0-9-_]*\.php)$/', $PAGE->url->out(true), $matches)) {
return $matches[1] . "/$output";
} else if ($output == '') {
return $PAGE->url->out(false, array(), false) . '#';
} else {
throw new coding_exception('Your page uses bizarre relative URLs which Moodle cannot handle. Please use absolute URLs.');
}
}
// Add wwwroot only if the URL does not already start with http:// or https://
if (!preg_match('|https?://|', $output) ) {
$output = $CFG->wwwroot . $output;
}
return $output;
}
/**
* Determine if there is data waiting to be processed from a form
*
* Used on most forms in Moodle to check for data
* Returns the data as an object, if it's found.
* This object can be used in foreach loops without
* casting because it's cast to (array) automatically
*
* Checks that submitted POST data exists and returns it as object.
*
* @uses $_POST
* @return mixed false or object
*/
function data_submitted() {
if (empty($_POST)) {
return false;
} else {
return (object)$_POST;
}
}
/**
* Given some normal text this function will break up any
* long words to a given size by inserting the given character
*
* It's multibyte savvy and doesn't change anything inside html tags.
*
* @param string $string the string to be modified
* @param int $maxsize maximum length of the string to be returned
* @param string $cutchar the string used to represent word breaks
* @return string
*/
function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
/// Loading the textlib singleton instance. We are going to need it.
$textlib = textlib_get_instance();
/// First of all, save all the tags inside the text to skip them
$tags = array();
filter_save_tags($string,$tags);
/// Process the string adding the cut when necessary
$output = '';
$length = $textlib->strlen($string);
$wordlength = 0;
for ($i=0; $i<$length; $i++) {
$char = $textlib->substr($string, $i, 1);
if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
$wordlength = 0;
} else {
$wordlength++;
if ($wordlength > $maxsize) {
$output .= $cutchar;
$wordlength = 0;
}
}
$output .= $char;
}
/// Finally load the tags back again
if (!empty($tags)) {
$output = str_replace(array_keys($tags), $tags, $output);
}
return $output;
}
/*
* Try and close the current window using JavaScript, either immediately, or after a delay.
*
* Echo's out the resulting XHTML & javascript
*
* @global object
* @global object
* @param integer $delay a delay in seconds before closing the window. Default 0.
* @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
* to reload the parent window before this one closes.
*/
function close_window($delay = 0, $reloadopener = false) {
global $THEME, $PAGE, $OUTPUT;
if (!$PAGE->headerprinted) {
print_header(get_string('closewindow'));
} else {
print_container_end_all(false, $THEME->open_header_containers);
}
if ($reloadopener) {
$function = 'close_window_reloading_opener';
} else {
$function = 'close_window';
}
echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
$PAGE->requires->js_function_call($function)->after_delay($delay);
echo $OUTPUT->footer();
exit;
}
/**
* Returns a string containing a link to the user documentation for the current
* page. Also contains an icon by default. Shown to teachers and admin only.
*
* @global object
* @global object
* @param string $text The text to be displayed for the link
* @param string $iconpath The path to the icon to be displayed
* @return string The link to user documentation for this current page
*/
function page_doc_link($text='', $iconpath='') {
global $CFG, $PAGE, $OUTPUT;
if (empty($CFG->docroot) || during_initial_install()) {
return '';
}
if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
return '';
}
$path = $PAGE->docspath;
if (!$path) {
return '';
}
return $OUTPUT->doc_link($path, $text, $iconpath);
}
/**
* Validates an email to make sure it makes sense.
*
* @param string $address The email address to validate.
* @return boolean
*/
function validate_email($address) {
return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
'(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
'@'.
'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
$address));
}
/**
* Extracts file argument either from file parameter or PATH_INFO
* Note: $scriptname parameter is not needed anymore
*
* @global string
* @uses $_SERVER
* @uses PARAM_PATH
* @return string file path (only safe characters)
*/
function get_file_argument() {
global $SCRIPT;
$relativepath = optional_param('file', FALSE, PARAM_PATH);
// then try extract file from PATH_INFO (slasharguments method)
if ($relativepath === false and isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
// check that PATH_INFO works == must not contain the script name
if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
$relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
}
}
// note: we are not using any other way because they are not compatible with unicode file names ;-)
return $relativepath;
}
/**
* Just returns an array of text formats suitable for a popup menu
*
* @uses FORMAT_MOODLE
* @uses FORMAT_HTML
* @uses FORMAT_PLAIN
* @uses FORMAT_MARKDOWN
* @return array
*/
function format_text_menu() {
return array (FORMAT_MOODLE => get_string('formattext'),
FORMAT_HTML => get_string('formathtml'),
FORMAT_PLAIN => get_string('formatplain'),
FORMAT_MARKDOWN => get_string('formatmarkdown'));
}
/**
* Given text in a variety of format codings, this function returns
* the text as safe HTML.
*
* This function should mainly be used for long strings like posts,
* answers, glossary items etc. For short strings @see format_string().
*
* @todo Finish documenting this function
*
* @global object
* @global object
* @global object
* @global object
* @uses FORMAT_MOODLE
* @uses FORMAT_HTML
* @uses FORMAT_PLAIN
* @uses FORMAT_WIKI
* @uses FORMAT_MARKDOWN
* @uses CLI_SCRIPT
* @staticvar array $croncache
* @param string $text The text to be formatted. This is raw text originally from user input.
* @param int $format Identifier of the text format to be used
* [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
* @param object $options ?
* @param int $courseid The courseid to use, defaults to $COURSE->courseid
* @return string
*/
function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
global $CFG, $COURSE, $DB, $PAGE;
static $croncache = array();
$hashstr = '';
if ($text === '') {
return ''; // no need to do any filters and cleaning
}
if (!empty($options->comments) && !empty($CFG->usecomments)) {
require_once($CFG->libdir . '/commentlib.php');
$comment = new comment($options->comments);
$cmt = $comment->init(true);
} else {
$cmt = '';
}
if (!isset($options->trusted)) {
$options->trusted = false;
}
if (!isset($options->noclean)) {
if ($options->trusted and trusttext_active()) {
// no cleaning if text trusted and noclean not specified
$options->noclean=true;
} else {
$options->noclean=false;
}
}
if (!isset($options->nocache)) {
$options->nocache=false;
}
if (!isset($options->smiley)) {
$options->smiley=true;
}
if (!isset($options->filter)) {
$options->filter=true;
}
if (!isset($options->para)) {
$options->para=true;
}
if (!isset($options->newlines)) {
$options->newlines=true;
}
if (empty($courseid)) {
$courseid = $COURSE->id;
}
if ($options->filter) {
$filtermanager = filter_manager::instance();
} else {
$filtermanager = new null_filter_manager();
}
$context = $PAGE->context;
if (!empty($CFG->cachetext) and empty($options->nocache)) {
$hashstr .= $text.'-'.$filtermanager->text_filtering_hash($context, $courseid).'-'.(int)$courseid.'-'.current_language().'-'.
(int)$format.(int)$options->trusted.(int)$options->noclean.(int)$options->smiley.
(int)$options->filter.(int)$options->para.(int)$options->newlines;
$time = time() - $CFG->cachetext;
$md5key = md5($hashstr);
if (CLI_SCRIPT) {
if (isset($croncache[$md5key])) {
return $croncache[$md5key].$cmt;
}
}
if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
if ($oldcacheitem->timemodified >= $time) {
if (CLI_SCRIPT) {
if (count($croncache) > 150) {
reset($croncache);
$key = key($croncache);
unset($croncache[$key]);
}
$croncache[$md5key] = $oldcacheitem->formattedtext;
}
return $oldcacheitem->formattedtext.$cmt;
}
}
}
switch ($format) {
case FORMAT_HTML:
if ($options->smiley) {
replace_smilies($text);
}
if (!$options->noclean) {
$text = clean_text($text, FORMAT_HTML);
}
$text = $filtermanager->filter_text($text, $context, $courseid);
break;
case FORMAT_PLAIN:
$text = s($text); // cleans dangerous JS
$text = rebuildnolinktag($text);
$text = str_replace(' ', ' ', $text);
$text = nl2br($text);
break;
case FORMAT_WIKI:
// this format is deprecated
$text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
this message as all texts should have been converted to Markdown format instead.
Please post a bug report to http://moodle.org/bugs with information about where you
saw this message.</p>'.s($text);
break;
case FORMAT_MARKDOWN:
$text = markdown_to_html($text);
if ($options->smiley) {
replace_smilies($text);
}
if (!$options->noclean) {
$text = clean_text($text, FORMAT_HTML);
}
$text = $filtermanager->filter_text($text, $context, $courseid);
break;
default: // FORMAT_MOODLE or anything else
$text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
if (!$options->noclean) {
$text = clean_text($text, FORMAT_HTML);
}
$text = $filtermanager->filter_text($text, $context, $courseid);
break;
}
// Warn people that we have removed this old mechanism, just in case they
// were stupid enough to rely on it.
if (isset($CFG->currenttextiscacheable)) {
debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
'called $CFG->currenttextiscacheable. The good news is that this no ' .
'longer exists. The bad news is that you seem to be using a filter that '.
'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
}
if (empty($options->nocache) and !empty($CFG->cachetext)) {
if (CLI_SCRIPT) {
// special static cron cache - no need to store it in db if its not already there
if (count($croncache) > 150) {
reset($croncache);
$key = key($croncache);
unset($croncache[$key]);
}
$croncache[$md5key] = $text;
return $text.$cmt;
}
$newcacheitem = new object();
$newcacheitem->md5key = $md5key;
$newcacheitem->formattedtext = $text;
$newcacheitem->timemodified = time();
if ($oldcacheitem) { // See bug 4677 for discussion
$newcacheitem->id = $oldcacheitem->id;
try {
$DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
} catch (dml_exception $e) {
// It's unlikely that the cron cache cleaner could have
// deleted this entry in the meantime, as it allows
// some extra time to cover these cases.
}
} else {
try {
$DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
} catch (dml_exception $e) {
// Again, it's possible that another user has caused this
// record to be created already in the time that it took
// to traverse this function. That's OK too, as the
// call above handles duplicate entries, and eventually
// the cron cleaner will delete them.
}
}
}
return $text.$cmt;
}
/**
* Converts the text format from the value to the 'internal'
* name or vice versa.
*
* $key can either be the value or the name and you get the other back.
*
* @uses FORMAT_MOODLE
* @uses FORMAT_HTML
* @uses FORMAT_PLAIN
* @uses FORMAT_MARKDOWN
* @param mixed $key int 0-4 or string one of 'moodle','html','plain','markdown'
* @return mixed as above but the other way around!
*/
function text_format_name( $key ) {
$lookup = array();
$lookup[FORMAT_MOODLE] = 'moodle';
$lookup[FORMAT_HTML] = 'html';
$lookup[FORMAT_PLAIN] = 'plain';
$lookup[FORMAT_MARKDOWN] = 'markdown';
$value = "error";
if (!is_numeric($key)) {
$key = strtolower( $key );
$value = array_search( $key, $lookup );
}
else {
if (isset( $lookup[$key] )) {
$value = $lookup[ $key ];