forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weblib.php
2302 lines (1941 loc) · 77.7 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 // $Id$
///////////////////////////////////////////////////////////////////////////
// weblib.php - functions for web output
//
// Library of all general-purpose Moodle PHP functions and constants
// that produce HTML output
//
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.com //
// //
// Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
// //
// This program 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 2 of the License, or //
// (at your option) any later version. //
// //
// This program 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: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/// Constants
/// Define text formatting types ... eventually we can add Wiki, BBcode etc
define("FORMAT_MOODLE", "0"); // Does all sorts of transformations and filtering
define("FORMAT_HTML", "1"); // Plain HTML (with some tags stripped)
define("FORMAT_PLAIN", "2"); // Plain text (even tags are printed in full)
define("FORMAT_WIKI", "3"); // Wiki-formatted text
$ALLOWED_TAGS =
"<p><br><b><i><u><font><table><tbody><span><div><tr><td><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><embed><object><param><acronym><nolink><style><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>";
/// Functions
function s($var) {
/// returns $var with HTML characters (like "<", ">", etc.) properly quoted,
if (empty($var)) {
return "";
}
return htmlSpecialChars(stripslashes_safe($var));
}
function p($var) {
/// prints $var with HTML characters (like "<", ">", etc.) properly quoted,
if (empty($var)) {
echo "";
}
echo htmlSpecialChars(stripslashes_safe($var));
}
function nvl(&$var, $default="") {
/// if $var is undefined, return $default, otherwise return $var
return isset($var) ? $var : $default;
}
function strip_querystring($url) {
/// takes a URL and returns it without the querystring portion
if ($commapos = strpos($url, '?')) {
return substr($url, 0, $commapos);
} else {
return $url;
}
}
function get_referer() {
/// returns the URL of the HTTP_REFERER, less the querystring portion
return strip_querystring(nvl($_SERVER["HTTP_REFERER"]));
}
function me() {
/// 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.)
if (!empty($_SERVER["REQUEST_URI"])) {
return $_SERVER["REQUEST_URI"];
} else if (!empty($_SERVER["PHP_SELF"])) {
if (!empty($_SERVER["QUERY_STRING"])) {
return $_SERVER["PHP_SELF"]."?".$_SERVER["QUERY_STRING"];
}
return $_SERVER["PHP_SELF"];
} else if (!empty($_SERVER["SCRIPT_NAME"])) {
if (!empty($_SERVER["QUERY_STRING"])) {
return $_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
}
return $_SERVER["SCRIPT_NAME"];
} else {
notify("Warning: Could not find any of these web server variables: \$REQUEST_URI, \$PHP_SELF or \$SCRIPT_NAME");
return false;
}
}
function qualified_me() {
/// like me() but returns a full URL
if (!empty($_SERVER["HTTP_HOST"])) {
$hostname = $_SERVER["HTTP_HOST"];
} else if (!empty($_ENV["HTTP_HOST"])) {
$hostname = $_ENV["HTTP_HOST"];
} else if (!empty($_SERVER["SERVER_NAME"])) {
$hostname = $_SERVER["SERVER_NAME"];
} else if (!empty($_ENV["SERVER_NAME"])) {
$hostname = $_ENV["SERVER_NAME"];
} else {
notify("Warning: could not find the name of this server!");
return false;
}
$protocol = (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
$url_prefix = $protocol.$hostname;
return $url_prefix . me();
}
function match_referer($goodreferer = "") {
/// returns true if the referer is the same as the goodreferer. If
/// goodreferer is not specified, use qualified_me as the goodreferer
global $CFG;
if (empty($CFG->secureforms)) { // Don't bother checking referer
return true;
}
if ($goodreferer == "nomatch") { // Don't bother checking referer
return true;
}
if (empty($goodreferer)) {
$goodreferer = qualified_me();
}
return $goodreferer == get_referer();
}
function data_submitted($url="") {
/// 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 also
/// checks the referer against the given url (it uses
/// the current page if none was specified.
global $CFG;
if (empty($_POST)) {
return false;
} else {
if (match_referer($url)) {
return (object)$_POST;
} else {
if ($CFG->debug > 10) {
notice("The form did not come from this page! (referer = ".get_referer().")");
}
return false;
}
}
}
function stripslashes_safe($string) {
/// stripslashes() removes ALL backslashes even from strings
/// so C:\temp becomes C:temp ... this isn't good.
/// The following should work as a fairly safe replacement
/// to be called on quoted AND unquoted strings (to be sure)
$string = str_replace("\\'", "'", $string);
$string = str_replace('\\"', '"', $string);
//$string = str_replace('\\\\', '\\', $string); // why?
return $string;
}
function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
/// Given some normal text, this function will break up any
/// long words to a given size, by inserting the given character
$output = '';
$length = strlen($string);
$wordlength = 0;
for ($i=0; $i<$length; $i++) {
$char = $string[$i];
if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r") {
$wordlength = 0;
} else {
$wordlength++;
if ($wordlength > $maxsize) {
$output .= $cutchar;
$wordlength = 0;
}
}
$output .= $char;
}
return $output;
}
if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
function str_ireplace($find, $replace, $string) {
/// This does a search and replace, ignoring case
/// This function is only used for versions of PHP older than version 5
/// which do not have a native version of this function.
/// Taken from the PHP manual, by bradhuizenga @ softhome.net
if (!is_array($find)) {
$find = array($find);
}
if(!is_array($replace)) {
if (!is_array($find)) {
$replace = array($replace);
} else {
// this will duplicate the string into an array the size of $find
$c = count($find);
$rString = $replace;
unset($replace);
for ($i = 0; $i < $c; $i++) {
$replace[$i] = $rString;
}
}
}
foreach ($find as $fKey => $fItem) {
$between = explode(strtolower($fItem),strtolower($string));
$pos = 0;
foreach($between as $bKey => $bItem) {
$between[$bKey] = substr($string,$pos,strlen($bItem));
$pos += strlen($bItem) + strlen($fItem);
}
$string = implode($replace[$fKey],$between);
}
return ($string);
}
}
if (!function_exists('stripos')) { /// Only exists in PHP 5
function stripos($haystack, $needle, $offset=0) {
/// This function is only used for versions of PHP older than version 5
/// which do not have a native version of this function.
/// Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
return strpos(strtoupper($haystack), strtoupper($needle), $offset);
}
}
function read_template($filename, &$var) {
/// return a (big) string containing the contents of a template file with all
/// the variables interpolated. all the variables must be in the $var[] array or
/// object (whatever you decide to use).
///
/// WARNING: do not use this on big files!!
$temp = str_replace("\\", "\\\\", implode(file($filename), ""));
$temp = str_replace('"', '\"', $temp);
eval("\$template = \"$temp\";");
return $template;
}
function checked(&$var, $set_value = 1, $unset_value = 0) {
/// if variable is set, set it to the set_value otherwise set it to the
/// unset_value. used to handle checkboxes when you are expecting them from
/// a form
if (empty($var)) {
$var = $unset_value;
} else {
$var = $set_value;
}
}
function frmchecked(&$var, $true_value = "checked", $false_value = "") {
/// prints the word "checked" if a variable is true, otherwise prints nothing,
/// used for printing the word "checked" in a checkbox form input
if ($var) {
echo $true_value;
} else {
echo $false_value;
}
}
function link_to_popup_window ($url, $name="popup", $linkname="click here",
$height=400, $width=500, $title="Popup window", $options="none") {
/// This will create a HTML link that will work on both
/// Javascript and non-javascript browsers.
/// Relies on the Javascript function openpopup in javascript.php
/// $url must be relative to home page eg /mod/survey/stuff.php
global $CFG;
if ($options == "none") {
$options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height";
}
$fullscreen = 0;
echo "<a target=\"$name\" title=\"$title\" href=\"$CFG->wwwroot$url\" ".
"onClick=\"return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>\n";
}
function button_to_popup_window ($url, $name="popup", $linkname="click here",
$height=400, $width=500, $title="Popup window", $options="none") {
/// This will create a HTML link that will work on both
/// Javascript and non-javascript browsers.
/// Relies on the Javascript function openpopup in javascript.php
/// $url must be relative to home page eg /mod/survey/stuff.php
global $CFG;
if ($options == "none") {
$options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height";
}
$fullscreen = 0;
echo "<input type=\"button\" name=\"popupwindow\" title=\"$title\" value=\"$linkname ...\" ".
"onClick=\"return openpopup('$url', '$name', '$options', $fullscreen);\">\n";
}
function close_window_button() {
/// Prints a simple button to close a window
echo "<center>\n";
echo "<script>\n";
echo "<!--\n";
echo "document.write('<form>');\n";
echo "document.write('<input type=\"button\" onClick=\"self.close();\" value=\"".get_string("closewindow")."\" />');\n";
echo "document.write('</form>');\n";
echo "-->\n";
echo "</script>\n";
echo "<noscript>\n";
echo "<a href=\"".$_SERVER['HTTP_REFERER']."\"><---</a>\n";
echo "</noscript>\n";
echo "</center>\n";
}
function choose_from_menu ($options, $name, $selected="", $nothing="choose", $script="", $nothingvalue="0", $return=false) {
/// Given an array of value, creates a popup menu to be part of a form
/// $options["value"]["label"]
if ($nothing == "choose") {
$nothing = get_string("choose")."...";
}
if ($script) {
$javascript = "onChange=\"$script\"";
} else {
$javascript = "";
}
$output = "<select name=\"$name\" $javascript>\n";
if ($nothing) {
$output .= " <option value=\"$nothingvalue\"\n";
if ($nothingvalue === $selected) {
$output .= " selected=\"true\"";
}
$output .= ">$nothing</option>\n";
}
if (!empty($options)) {
foreach ($options as $value => $label) {
$output .= " <option value=\"$value\"";
if ($value == $selected) {
$output .= " selected=\"true\"";
}
if ($label === "") {
$output .= ">$value</option>\n";
} else {
$output .= ">$label</option>\n";
}
}
}
$output .= "</select>\n";
if ($return) {
return $output;
} else {
echo $output;
}
}
function popup_form ($common, $options, $formname, $selected="", $nothing="choose", $help="", $helptext="", $return=false, $targetwindow="self") {
/// Implements a complete little popup form
/// $common = the URL up to the point of the variable that changes
/// $options = A list of value-label pairs for the popup list
/// $formname = name must be unique on the page
/// $selected = the option that is already selected
/// $nothing = The label for the "no choice" option
/// $help = The name of a help page if help is required
/// $helptext = The name of the label for the help button
/// $return = Boolean indicating whether the function should return the text
/// as a string or echo it directly to the page being rendered
// TODO:
//
// * Make sure it's W3C conformant (<form name=""> has to go for example)
// * Code it in a way that doesn't require JS to be on. Example code:
// $selector .= '<form method="get" action="" style="display: inline;"><span>';
// $selector .= '<input type="hidden" name="var" value="value" />';
// if(!empty($morevars)) {
// $getarray = explode('&', $morevars);
// foreach($getarray as $thisvar) {
// $selector .= '<input type="hidden" name="'.strtok($thisvar, '=').'" value="'.strtok('=').'" />';
// }
// }
// $selector .= '<select name="" onchange="form.submit();">';
// foreach($options as $id => $text) {
// $selector .= "\n<option value='$id'";
// if($option->id == $selected) {
// $selector .= ' selected';
// }
// $selector .= '>'.$text."</option>\n";
// }
// $selector .= '</select>';
// $selector .= '<noscript id="unique_id" style="display: inline;"> <input type="submit" value="'.get_string('somestring').'" /></noscript>';
// $selector .= '<script type="text/javascript">'."\n<!--\n".'document.getElementById("unique_id").style.display = "none";'."\n<!--\n".'</script>';
// $selector .= '</span></form>';
//
global $CFG;
if ($nothing == "choose") {
$nothing = get_string("choose")."...";
}
$startoutput = "<form method=\"get\" target=\"{$CFG->framename}\" name=\"$formname\">";
$output = "<select name=\"popup\" onchange=\"$targetwindow.location=document.$formname.popup.options[document.$formname.popup.selectedIndex].value\">\n";
if ($nothing != "") {
$output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
}
foreach ($options as $value => $label) {
if (substr($label,0,1) == "-") {
$output .= " <option value=\"\"";
} else {
$output .= " <option value=\"$common$value\"";
if ($value == $selected) {
$output .= " selected=\"true\"";
}
}
if ($label) {
$output .= ">$label</option>\n";
} else {
$output .= ">$value</option>\n";
}
}
$output .= "</select>";
$output .= "</form>\n";
if ($return) {
return $startoutput.$output;
} else {
echo $startoutput;
if ($help) {
helpbutton($help, $helptext);
}
echo $output;
}
}
function formerr($error) {
/// Prints some red text
if (!empty($error)) {
echo "<font color=\"#ff0000\">$error</font>";
}
}
function validate_email ($address) {
/// Validates an email to make sure it makes sense.
return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.
'@'.
'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
$address));
}
function detect_munged_arguments($string) {
if (ereg('\.\.', $string)) { // check for parent URLs
return true;
}
if (ereg('[\|\`]', $string)) { // check for other bad characters
return true;
}
if (empty($string) or $string == '/') {
return true;
}
return false;
}
function get_slash_arguments($file="file.php") {
/// Searches the current environment variables for some slash arguments
if (!$string = me()) {
return false;
}
$pathinfo = explode($file, $string);
if (!empty($pathinfo[1])) {
return $pathinfo[1];
} else {
return false;
}
}
function parse_slash_arguments($string, $i=0) {
/// Extracts arguments from "/foo/bar/something"
/// eg http://mysite.com/script.php/foo/bar/something
if (detect_munged_arguments($string)) {
return false;
}
$args = explode("/", $string);
if ($i) { // return just the required argument
return $args[$i];
} else { // return the whole array
array_shift($args); // get rid of the empty first one
return $args;
}
}
function format_text_menu() {
/// Just returns an array of formats suitable for a popup menu
return array (FORMAT_MOODLE => get_string("formattext"),
FORMAT_HTML => get_string("formathtml"),
FORMAT_PLAIN => get_string("formatplain"),
FORMAT_WIKI => get_string("formatwiki"));
}
function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL ) {
/// Given text in a variety of format codings, this function returns
/// the text as safe HTML.
///
/// $text is raw text (originally from a user)
/// $format is one of the format constants, defined above
global $CFG, $course;
if (!empty($CFG->cachetext)) {
$time = time() - $CFG->cachetext;
$md5key = md5($text);
if ($cacheitem = get_record_select('cache_text', "md5key = '$md5key' AND timemodified > '$time'")) {
return $cacheitem->formattedtext;
}
}
if (empty($courseid)) {
if (!empty($course->id)) { // An ugly hack for better compatibility
$courseid = $course->id;
}
}
$CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
switch ($format) {
case FORMAT_HTML:
replace_smilies($text);
$text = filter_text($text, $courseid);
break;
case FORMAT_PLAIN:
$text = htmlentities($text);
$text = rebuildnolinktag($text);
$text = str_replace(" ", " ", $text);
replace_smilies($text);
$text = nl2br($text);
break;
case FORMAT_WIKI:
$text = wiki_to_html($text);
$text = rebuildnolinktag($text);
$text = filter_text($text, $courseid);
break;
default: // FORMAT_MOODLE or anything else
if (!isset($options->smiley)) {
$options->smiley=true;
}
if (!isset($options->para)) {
$options->para=true;
}
if (!isset($options->newlines)) {
$options->newlines=true;
}
$text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
$text = filter_text($text, $courseid);
break;
}
if (!empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
$newrecord->md5key = $md5key;
$newrecord->formattedtext = addslashes($text);
$newrecord->timemodified = time();
insert_record('cache_text', $newrecord);
}
return $text;
}
function format_text_email($text, $format) {
/// Given text in a variety of format codings, this function returns
/// the text as plain text suitable for plain email.
///
/// $text is raw text (originally from a user)
/// $format is one of the format constants, defined above
switch ($format) {
case FORMAT_PLAIN:
return $text;
break;
case FORMAT_WIKI:
$text = wiki_to_html($text);
/// This expression turns links into something nice in a text format. (Russell Jungwirth)
/// From: http://php.net/manual/en/function.eregi-replace.php and simplified
$text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [\\2]', $text);
return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
case FORMAT_HTML:
return html_to_text($text);
break;
default: // FORMAT_MOODLE or anything else
$text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [\\2]', $text);
return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
}
}
function filter_text($text, $courseid=NULL) {
/// Given some text in HTML format, this function will pass it
/// through any filters that have been defined in $CFG->textfilterx
/// The variable defines a filepath to a file containing the
/// filter function. The file must contain a variable called
/// $textfilter_function which contains the name of the function
/// with $courseid and $text parameters
global $CFG;
if (!empty($CFG->textfilters)) {
$textfilters = explode(',', $CFG->textfilters);
foreach ($textfilters as $textfilter) {
if (is_readable("$CFG->dirroot/$textfilter/filter.php")) {
include("$CFG->dirroot/$textfilter/filter.php");
$text = $textfilter_function($courseid, $text);
}
}
}
return $text;
}
function clean_text($text, $format=FORMAT_MOODLE) {
/// Given raw text (eg typed in by a user), this function cleans it up
/// and removes any nasty tags that could mess up Moodle pages.
global $ALLOWED_TAGS;
switch ($format) {
case FORMAT_MOODLE:
case FORMAT_HTML:
case FORMAT_WIKI:
/// Remove tags that are not allowed
$text = strip_tags($text, $ALLOWED_TAGS);
/// Munge javascript: label
$text = str_ireplace("javascript:", "Xjavascript:", $text);
/// Remove script events
$text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
$text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
return $text;
case FORMAT_PLAIN:
return $text;
}
}
function replace_smilies(&$text) {
/// Replaces all known smileys in the text with image equivalents
global $CFG;
/// this builds the mapping array only once
static $runonce = false;
static $e = array();
static $img = array();
static $emoticons = array(
':-)' => 'smiley',
':)' => 'smiley',
':-D' => 'biggrin',
';-)' => 'wink',
':-/' => 'mixed',
'V-.' => 'thoughtful',
':-P' => 'tongueout',
'B-)' => 'cool',
'^-)' => 'approve',
'8-)' => 'wideeyes',
':o)' => 'clown',
':-(' => 'sad',
':(' => 'sad',
'8-.' => 'shy',
':-I' => 'blush',
':-X' => 'kiss',
'8-o' => 'surprise',
'P-|' => 'blackeye',
'8-[' => 'angry',
'xx-P' => 'dead',
'|-.' => 'sleepy',
'}-]' => 'evil',
);
if ($runonce == false) { /// After the first time this is not run again
foreach ($emoticons as $emoticon => $image){
$alttext = get_string($image, 'pix');
$e[] = $emoticon;
$img[] = "<img alt=\"$alttext\" width=\"15\" height=\"15\" src=\"$CFG->pixpath/s/$image.gif\" />";
}
$runonce = true;
}
// Exclude from transformations all the code inside <script> tags
// Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
// Based on code from glossary fiter by Williams Castillo.
// - Eloy
// Detect all the <script> zones to take out
$excludes = array();
preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
// Take out all the <script> zones from text
foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
$excludes['<+'.$key.'+>'] = $value;
}
if ($excludes) {
$text = str_replace($excludes,array_keys($excludes),$text);
}
/// this is the meat of the code - this is run every time
$text = str_replace($e, $img, $text);
// Recover all the <script> zones to text
if ($excludes) {
$text = str_replace(array_keys($excludes),$excludes,$text);
}
}
function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
/// Given plain text, makes it into HTML as nicely as possible.
/// May contain HTML tags already
global $CFG;
/// Remove any whitespace that may be between HTML tags
$text = eregi_replace(">([[:space:]]+)<", "><", $text);
/// Remove any returns that precede or follow HTML tags
$text = eregi_replace("([\n\r])<", " <", $text);
$text = eregi_replace(">([\n\r])", "> ", $text);
convert_urls_into_links($text);
/// Make returns into HTML newlines.
if ($newlines) {
$text = nl2br($text);
}
/// Turn smileys into images.
if ($smiley) {
replace_smilies($text);
}
/// Wrap the whole thing in a paragraph tag if required
if ($para) {
return "<p>".$text."</p>";
} else {
return $text;
}
}
function wiki_to_html($text) {
/// Given Wiki formatted text, make it into XHTML using external function
global $CFG;
require_once("$CFG->libdir/wiki.php");
$wiki = new Wiki;
return $wiki->format($text);
}
function html_to_text($html) {
/// Given HTML text, make it into plain text using external function
global $CFG;
require_once("$CFG->libdir/html2text.php");
return html2text($html);
}
function convert_urls_into_links(&$text) {
/// Given some text, it converts any URLs it finds into HTML links.
/// Make lone URLs into links. eg http://moodle.com/
$text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
"\\1<a href=\"\\2://\\3\\4\" target=\"newpage\">\\2://\\3\\4</a>", $text);
/// eg www.moodle.com
$text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
"\\1<a href=\"http://www.\\2\\3\" target=\"newpage\">www.\\2\\3</a>", $text);
}
function highlight($needle, $haystack, $case=0,
$left_string="<span class=\"highlight\">", $right_string="</span>") {
/// This function will highlight search words in a given string
/// It cares about HTML and will not ruin links. It's best to use
/// this function after performing any conversions to HTML.
/// Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
if (empty($needle)) {
return $haystack;
}
$list_of_words = eregi_replace("[^-a-zA-Z0-9&']", " ", $needle);
$list_array = explode(" ", $list_of_words);
for ($i=0; $i<sizeof($list_array); $i++) {
if (strlen($list_array[$i]) == 1) {
$list_array[$i] = "";
}
}
$list_of_words = implode(" ", $list_array);
$list_of_words_cp = $list_of_words;
$final = array();
preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
foreach (array_unique($list_of_words[0]) as $key=>$value) {
$final['<|'.$key.'|>'] = $value;
}
$haystack = str_replace($final,array_keys($final),$haystack);
$list_of_words_cp = eregi_replace(" +", "|", $list_of_words_cp);
if ($list_of_words_cp{0}=="|") {
$list_of_words_cp{0} = "";
}
if ($list_of_words_cp{strlen($list_of_words_cp)-1}=="|") {
$list_of_words_cp{strlen($list_of_words_cp)-1}="";
}
$list_of_words_cp = "(".trim($list_of_words_cp).")";
if (!$case){
$haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
} else {
$haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
}
$haystack = str_replace(array_keys($final),$final,$haystack);
return stripslashes($haystack);
}
function highlightfast($needle, $haystack) {
/// This function will highlight instances of $needle in $haystack
/// It's faster that the above function and doesn't care about
/// HTML or anything.
$parts = explode(strtolower($needle), strtolower($haystack));
$pos = 0;
foreach ($parts as $key => $part) {
$parts[$key] = substr($haystack, $pos, strlen($part));
$pos += strlen($part);
$parts[$key] .= "<span class=\"highlight\">".substr($haystack, $pos, strlen($needle))."</span>";
$pos += strlen($needle);
}
return (join('', $parts));
}
/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
function print_header ($title="", $heading="", $navigation="", $focus="", $meta="",
$cache=true, $button=" ", $menu="", $usexml=false) {
// $title - appears top of window
// $heading - appears top of page
// $navigation - premade navigation string
// $focus - indicates form element eg inputform.password
// $meta - meta tags in the header
// $cache - should this page be cacheable?
// $button - HTML code for a button (usually for module editing)
// $menu - HTML code for a popup menu
// $usexml - use XML for this page
global $USER, $CFG, $THEME, $SESSION;
global $course; // This is a bit of an ugly hack to be gotten rid of later
if (!empty($course->lang)) {
$CFG->courselang = $course->lang;
}
if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.php")) {
$styles = $CFG->stylesheet;
} else {
$styles = "$CFG->wwwroot/theme/standard/styles.php";
}
if ($navigation == "home") {
$home = true;
$navigation = "";
} else {
$home = false;
}
if ($button == "") {
$button = " ";
}
if (!$menu and $navigation) {
if (isset($USER->id)) {
$menu = "<font size=\"2\"><a target=\"$CFG->framename\" href=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</a></font>";
} else {
$menu = "<font size=\"2\"><a target=\"$CFG->framename\" href=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</a></font>";
}
}
// Add a stylesheet for the HTML editor
$meta = "<style type=\"text/css\">@import url($CFG->wwwroot/lib/editor/htmlarea.css);</style>\n$meta\n";
if (!empty($CFG->unicode)) {
$encoding = "utf-8";
} else if (!empty($SESSION->encoding) and empty($CFG->courselang)) {
$encoding = $SESSION->encoding;
} else {
$encoding = get_string("thischarset");
$SESSION->encoding = $encoding;
}
$meta = "<meta http-equiv=\"content-type\" content=\"text/html; charset=$encoding\" />\n$meta\n";
if ( get_string("thisdirection") == "rtl" ) {
$direction = " dir=\"rtl\"";
} else {
$direction = " dir=\"ltr\"";
}
if (!$cache) { // Do everything we can to prevent clients and proxies caching
@header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
@header("Pragma: no-cache");
$meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
$meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
}
if ($usexml) { // Added by Gustav Delius / Mad Alex for MathML output
$currentlanguage = current_language();
@header("Content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n";
if (!empty($CFG->xml_stylesheets)) {
$stylesheets = explode(";", $CFG->xml_stylesheets);
foreach ($stylesheets as $stylesheet) {
echo "<?xml-stylesheet type=\"text/xsl\" href=\"$CFG->wwwroot/$stylesheet\" ?>\n";
}
}
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1";
if (!empty($CFG->xml_doctype_extra)) {
echo " plus $CFG->xml_doctype_extra";
}
echo "//" . strtoupper($currentlanguage) . "\" \"$CFG->xml_dtd\">\n";