Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]
1 <?php 2 // This file is part of Moodle - http://moodle.org/ 3 // 4 // Moodle is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Moodle is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17 /** 18 * Library of functions for web output 19 * 20 * Library of all general-purpose Moodle PHP functions and constants 21 * that produce HTML output 22 * 23 * Other main libraries: 24 * - datalib.php - functions that access the database. 25 * - moodlelib.php - general-purpose Moodle functions. 26 * 27 * @package core 28 * @subpackage lib 29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 31 */ 32 33 defined('MOODLE_INTERNAL') || die(); 34 35 // Constants. 36 37 // Define text formatting types ... eventually we can add Wiki, BBcode etc. 38 39 /** 40 * Does all sorts of transformations and filtering. 41 */ 42 define('FORMAT_MOODLE', '0'); 43 44 /** 45 * Plain HTML (with some tags stripped). 46 */ 47 define('FORMAT_HTML', '1'); 48 49 /** 50 * Plain text (even tags are printed in full). 51 */ 52 define('FORMAT_PLAIN', '2'); 53 54 /** 55 * Wiki-formatted text. 56 * Deprecated: left here just to note that '3' is not used (at the moment) 57 * and to catch any latent wiki-like text (which generates an error) 58 * @deprecated since 2005! 59 */ 60 define('FORMAT_WIKI', '3'); 61 62 /** 63 * Markdown-formatted text http://daringfireball.net/projects/markdown/ 64 */ 65 define('FORMAT_MARKDOWN', '4'); 66 67 /** 68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored. 69 */ 70 define('URL_MATCH_BASE', 0); 71 72 /** 73 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2. 74 */ 75 define('URL_MATCH_PARAMS', 1); 76 77 /** 78 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params. 79 */ 80 define('URL_MATCH_EXACT', 2); 81 82 // Functions. 83 84 /** 85 * Add quotes to HTML characters. 86 * 87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted. 88 * Related function {@link p()} simply prints the output of this function. 89 * 90 * @param string $var the string potentially containing HTML characters 91 * @return string 92 */ 93 function s($var) { 94 if ($var === false) { 95 return '0'; 96 } 97 98 if ($var === null || $var === '') { 99 return ''; 100 } 101 102 return preg_replace( 103 '/&#(\d+|x[0-9a-f]+);/i', '&#$1;', 104 htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE) 105 ); 106 } 107 108 /** 109 * Add quotes to HTML characters. 110 * 111 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted. 112 * This function simply calls & displays {@link s()}. 113 * @see s() 114 * 115 * @param string $var the string potentially containing HTML characters 116 */ 117 function p($var) { 118 echo s($var); 119 } 120 121 /** 122 * Does proper javascript quoting. 123 * 124 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled. 125 * 126 * @param mixed $var String, Array, or Object to add slashes to 127 * @return mixed quoted result 128 */ 129 function addslashes_js($var) { 130 if (is_string($var)) { 131 $var = str_replace('\\', '\\\\', $var); 132 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var); 133 $var = str_replace('</', '<\/', $var); // XHTML compliance. 134 } else if (is_array($var)) { 135 $var = array_map('addslashes_js', $var); 136 } else if (is_object($var)) { 137 $a = get_object_vars($var); 138 foreach ($a as $key => $value) { 139 $a[$key] = addslashes_js($value); 140 } 141 $var = (object)$a; 142 } 143 return $var; 144 } 145 146 /** 147 * Remove query string from url. 148 * 149 * Takes in a URL and returns it without the querystring portion. 150 * 151 * @param string $url the url which may have a query string attached. 152 * @return string The remaining URL. 153 */ 154 function strip_querystring($url) { 155 if ($url === null || $url === '') { 156 return ''; 157 } 158 159 if ($commapos = strpos($url, '?')) { 160 return substr($url, 0, $commapos); 161 } else { 162 return $url; 163 } 164 } 165 166 /** 167 * Returns the name of the current script, WITH the querystring portion. 168 * 169 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME 170 * return different things depending on a lot of things like your OS, Web 171 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.) 172 * <b>NOTE:</b> This function returns false if the global variables needed are not set. 173 * 174 * @return mixed String or false if the global variables needed are not set. 175 */ 176 function me() { 177 global $ME; 178 return $ME; 179 } 180 181 /** 182 * Guesses the full URL of the current script. 183 * 184 * This function is using $PAGE->url, but may fall back to $FULLME which 185 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME 186 * 187 * @return mixed full page URL string or false if unknown 188 */ 189 function qualified_me() { 190 global $FULLME, $PAGE, $CFG; 191 192 if (isset($PAGE) and $PAGE->has_set_url()) { 193 // This is the only recommended way to find out current page. 194 return $PAGE->url->out(false); 195 196 } else { 197 if ($FULLME === null) { 198 // CLI script most probably. 199 return false; 200 } 201 if (!empty($CFG->sslproxy)) { 202 // Return only https links when using SSL proxy. 203 return preg_replace('/^http:/', 'https:', $FULLME, 1); 204 } else { 205 return $FULLME; 206 } 207 } 208 } 209 210 /** 211 * Determines whether or not the Moodle site is being served over HTTPS. 212 * 213 * This is done simply by checking the value of $CFG->wwwroot, which seems 214 * to be the only reliable method. 215 * 216 * @return boolean True if site is served over HTTPS, false otherwise. 217 */ 218 function is_https() { 219 global $CFG; 220 221 return (strpos($CFG->wwwroot, 'https://') === 0); 222 } 223 224 /** 225 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required. 226 * 227 * @param bool $stripquery if true, also removes the query part of the url. 228 * @return string The resulting referer or empty string. 229 */ 230 function get_local_referer($stripquery = true) { 231 if (isset($_SERVER['HTTP_REFERER'])) { 232 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL); 233 if ($stripquery) { 234 return strip_querystring($referer); 235 } else { 236 return $referer; 237 } 238 } else { 239 return ''; 240 } 241 } 242 243 /** 244 * Class for creating and manipulating urls. 245 * 246 * It can be used in moodle pages where config.php has been included without any further includes. 247 * 248 * It is useful for manipulating urls with long lists of params. 249 * One situation where it will be useful is a page which links to itself to perform various actions 250 * and / or to process form data. A moodle_url object : 251 * can be created for a page to refer to itself with all the proper get params being passed from page call to 252 * page call and methods can be used to output a url including all the params, optionally adding and overriding 253 * params and can also be used to 254 * - output the url without any get params 255 * - and output the params as hidden fields to be output within a form 256 * 257 * @copyright 2007 jamiesensei 258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 259 * @package core 260 */ 261 class moodle_url { 262 263 /** 264 * Scheme, ex.: http, https 265 * @var string 266 */ 267 protected $scheme = ''; 268 269 /** 270 * Hostname. 271 * @var string 272 */ 273 protected $host = ''; 274 275 /** 276 * Port number, empty means default 80 or 443 in case of http. 277 * @var int 278 */ 279 protected $port = ''; 280 281 /** 282 * Username for http auth. 283 * @var string 284 */ 285 protected $user = ''; 286 287 /** 288 * Password for http auth. 289 * @var string 290 */ 291 protected $pass = ''; 292 293 /** 294 * Script path. 295 * @var string 296 */ 297 protected $path = ''; 298 299 /** 300 * Optional slash argument value. 301 * @var string 302 */ 303 protected $slashargument = ''; 304 305 /** 306 * Anchor, may be also empty, null means none. 307 * @var string 308 */ 309 protected $anchor = null; 310 311 /** 312 * Url parameters as associative array. 313 * @var array 314 */ 315 protected $params = array(); 316 317 /** 318 * Create new instance of moodle_url. 319 * 320 * @param moodle_url|string $url - moodle_url means make a copy of another 321 * moodle_url and change parameters, string means full url or shortened 322 * form (ex.: '/course/view.php'). It is strongly encouraged to not include 323 * query string because it may result in double encoded values. Use the 324 * $params instead. For admin URLs, just use /admin/script.php, this 325 * class takes care of the $CFG->admin issue. 326 * @param array $params these params override current params or add new 327 * @param string $anchor The anchor to use as part of the URL if there is one. 328 * @throws moodle_exception 329 */ 330 public function __construct($url, array $params = null, $anchor = null) { 331 global $CFG; 332 333 if ($url instanceof moodle_url) { 334 $this->scheme = $url->scheme; 335 $this->host = $url->host; 336 $this->port = $url->port; 337 $this->user = $url->user; 338 $this->pass = $url->pass; 339 $this->path = $url->path; 340 $this->slashargument = $url->slashargument; 341 $this->params = $url->params; 342 $this->anchor = $url->anchor; 343 344 } else { 345 $url = $url ?? ''; 346 // Detect if anchor used. 347 $apos = strpos($url, '#'); 348 if ($apos !== false) { 349 $anchor = substr($url, $apos); 350 $anchor = ltrim($anchor, '#'); 351 $this->set_anchor($anchor); 352 $url = substr($url, 0, $apos); 353 } 354 355 // Normalise shortened form of our url ex.: '/course/view.php'. 356 if (strpos($url, '/') === 0) { 357 $url = $CFG->wwwroot.$url; 358 } 359 360 if ($CFG->admin !== 'admin') { 361 if (strpos($url, "$CFG->wwwroot/admin/") === 0) { 362 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url); 363 } 364 } 365 366 // Parse the $url. 367 $parts = parse_url($url); 368 if ($parts === false) { 369 throw new moodle_exception('invalidurl'); 370 } 371 if (isset($parts['query'])) { 372 // Note: the values may not be correctly decoded, url parameters should be always passed as array. 373 parse_str(str_replace('&', '&', $parts['query']), $this->params); 374 } 375 unset($parts['query']); 376 foreach ($parts as $key => $value) { 377 $this->$key = $value; 378 } 379 380 // Detect slashargument value from path - we do not support directory names ending with .php. 381 $pos = strpos($this->path, '.php/'); 382 if ($pos !== false) { 383 $this->slashargument = substr($this->path, $pos + 4); 384 $this->path = substr($this->path, 0, $pos + 4); 385 } 386 } 387 388 $this->params($params); 389 if ($anchor !== null) { 390 $this->anchor = (string)$anchor; 391 } 392 } 393 394 /** 395 * Add an array of params to the params for this url. 396 * 397 * The added params override existing ones if they have the same name. 398 * 399 * @param array $params Defaults to null. If null then returns all params. 400 * @return array Array of Params for url. 401 * @throws coding_exception 402 */ 403 public function params(array $params = null) { 404 $params = (array)$params; 405 406 foreach ($params as $key => $value) { 407 if (is_int($key)) { 408 throw new coding_exception('Url parameters can not have numeric keys!'); 409 } 410 if (!is_string($value)) { 411 if (is_array($value)) { 412 throw new coding_exception('Url parameters values can not be arrays!'); 413 } 414 if (is_object($value) and !method_exists($value, '__toString')) { 415 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!'); 416 } 417 } 418 $this->params[$key] = (string)$value; 419 } 420 return $this->params; 421 } 422 423 /** 424 * Remove all params if no arguments passed. 425 * Remove selected params if arguments are passed. 426 * 427 * Can be called as either remove_params('param1', 'param2') 428 * or remove_params(array('param1', 'param2')). 429 * 430 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args. 431 * @return array url parameters 432 */ 433 public function remove_params($params = null) { 434 if (!is_array($params)) { 435 $params = func_get_args(); 436 } 437 foreach ($params as $param) { 438 unset($this->params[$param]); 439 } 440 return $this->params; 441 } 442 443 /** 444 * Remove all url parameters. 445 * 446 * @todo remove the unused param. 447 * @param array $params Unused param 448 * @return void 449 */ 450 public function remove_all_params($params = null) { 451 $this->params = array(); 452 $this->slashargument = ''; 453 } 454 455 /** 456 * Add a param to the params for this url. 457 * 458 * The added param overrides existing one if they have the same name. 459 * 460 * @param string $paramname name 461 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added 462 * @return mixed string parameter value, null if parameter does not exist 463 */ 464 public function param($paramname, $newvalue = '') { 465 if (func_num_args() > 1) { 466 // Set new value. 467 $this->params(array($paramname => $newvalue)); 468 } 469 if (isset($this->params[$paramname])) { 470 return $this->params[$paramname]; 471 } else { 472 return null; 473 } 474 } 475 476 /** 477 * Merges parameters and validates them 478 * 479 * @param array $overrideparams 480 * @return array merged parameters 481 * @throws coding_exception 482 */ 483 protected function merge_overrideparams(array $overrideparams = null) { 484 $overrideparams = (array)$overrideparams; 485 $params = $this->params; 486 foreach ($overrideparams as $key => $value) { 487 if (is_int($key)) { 488 throw new coding_exception('Overridden parameters can not have numeric keys!'); 489 } 490 if (is_array($value)) { 491 throw new coding_exception('Overridden parameters values can not be arrays!'); 492 } 493 if (is_object($value) and !method_exists($value, '__toString')) { 494 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!'); 495 } 496 $params[$key] = (string)$value; 497 } 498 return $params; 499 } 500 501 /** 502 * Get the params as as a query string. 503 * 504 * This method should not be used outside of this method. 505 * 506 * @param bool $escaped Use & as params separator instead of plain & 507 * @param array $overrideparams params to add to the output params, these 508 * override existing ones with the same name. 509 * @return string query string that can be added to a url. 510 */ 511 public function get_query_string($escaped = true, array $overrideparams = null) { 512 $arr = array(); 513 if ($overrideparams !== null) { 514 $params = $this->merge_overrideparams($overrideparams); 515 } else { 516 $params = $this->params; 517 } 518 foreach ($params as $key => $val) { 519 if (is_array($val)) { 520 foreach ($val as $index => $value) { 521 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value); 522 } 523 } else { 524 if (isset($val) && $val !== '') { 525 $arr[] = rawurlencode($key)."=".rawurlencode($val); 526 } else { 527 $arr[] = rawurlencode($key); 528 } 529 } 530 } 531 if ($escaped) { 532 return implode('&', $arr); 533 } else { 534 return implode('&', $arr); 535 } 536 } 537 538 /** 539 * Get the url params as an array of key => value pairs. 540 * 541 * This helps in handling cases where url params contain arrays. 542 * 543 * @return array params array for templates. 544 */ 545 public function export_params_for_template(): array { 546 $data = []; 547 foreach ($this->params as $key => $val) { 548 if (is_array($val)) { 549 foreach ($val as $index => $value) { 550 $data[] = ['name' => $key.'['.$index.']', 'value' => $value]; 551 } 552 } else { 553 $data[] = ['name' => $key, 'value' => $val]; 554 } 555 } 556 return $data; 557 } 558 559 /** 560 * Shortcut for printing of encoded URL. 561 * 562 * @return string 563 */ 564 public function __toString() { 565 return $this->out(true); 566 } 567 568 /** 569 * Output url. 570 * 571 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use 572 * the returned URL in HTTP headers, you want $escaped=false. 573 * 574 * @param bool $escaped Use & as params separator instead of plain & 575 * @param array $overrideparams params to add to the output url, these override existing ones with the same name. 576 * @return string Resulting URL 577 */ 578 public function out($escaped = true, array $overrideparams = null) { 579 580 global $CFG; 581 582 if (!is_bool($escaped)) { 583 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.'); 584 } 585 586 $url = $this; 587 588 // Allow url's to be rewritten by a plugin. 589 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) { 590 $class = $CFG->urlrewriteclass; 591 $pluginurl = $class::url_rewrite($url); 592 if ($pluginurl instanceof moodle_url) { 593 $url = $pluginurl; 594 } 595 } 596 597 return $url->raw_out($escaped, $overrideparams); 598 599 } 600 601 /** 602 * Output url without any rewrites 603 * 604 * This is identical in signature and use to out() but doesn't call the rewrite handler. 605 * 606 * @param bool $escaped Use & as params separator instead of plain & 607 * @param array $overrideparams params to add to the output url, these override existing ones with the same name. 608 * @return string Resulting URL 609 */ 610 public function raw_out($escaped = true, array $overrideparams = null) { 611 if (!is_bool($escaped)) { 612 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.'); 613 } 614 615 $uri = $this->out_omit_querystring().$this->slashargument; 616 617 $querystring = $this->get_query_string($escaped, $overrideparams); 618 if ($querystring !== '') { 619 $uri .= '?' . $querystring; 620 } 621 if (!is_null($this->anchor)) { 622 $uri .= '#'.$this->anchor; 623 } 624 625 return $uri; 626 } 627 628 /** 629 * Returns url without parameters, everything before '?'. 630 * 631 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned? 632 * @return string 633 */ 634 public function out_omit_querystring($includeanchor = false) { 635 636 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): ''; 637 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':''; 638 $uri .= $this->host ? $this->host : ''; 639 $uri .= $this->port ? ':'.$this->port : ''; 640 $uri .= $this->path ? $this->path : ''; 641 if ($includeanchor and !is_null($this->anchor)) { 642 $uri .= '#' . $this->anchor; 643 } 644 645 return $uri; 646 } 647 648 /** 649 * Compares this moodle_url with another. 650 * 651 * See documentation of constants for an explanation of the comparison flags. 652 * 653 * @param moodle_url $url The moodle_url object to compare 654 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT) 655 * @return bool 656 */ 657 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) { 658 659 $baseself = $this->out_omit_querystring(); 660 $baseother = $url->out_omit_querystring(); 661 662 // Append index.php if there is no specific file. 663 if (substr($baseself, -1) == '/') { 664 $baseself .= 'index.php'; 665 } 666 if (substr($baseother, -1) == '/') { 667 $baseother .= 'index.php'; 668 } 669 670 // Compare the two base URLs. 671 if ($baseself != $baseother) { 672 return false; 673 } 674 675 if ($matchtype == URL_MATCH_BASE) { 676 return true; 677 } 678 679 $urlparams = $url->params(); 680 foreach ($this->params() as $param => $value) { 681 if ($param == 'sesskey') { 682 continue; 683 } 684 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) { 685 return false; 686 } 687 } 688 689 if ($matchtype == URL_MATCH_PARAMS) { 690 return true; 691 } 692 693 foreach ($urlparams as $param => $value) { 694 if ($param == 'sesskey') { 695 continue; 696 } 697 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) { 698 return false; 699 } 700 } 701 702 if ($url->anchor !== $this->anchor) { 703 return false; 704 } 705 706 return true; 707 } 708 709 /** 710 * Sets the anchor for the URI (the bit after the hash) 711 * 712 * @param string $anchor null means remove previous 713 */ 714 public function set_anchor($anchor) { 715 if (is_null($anchor)) { 716 // Remove. 717 $this->anchor = null; 718 } else if ($anchor === '') { 719 // Special case, used as empty link. 720 $this->anchor = ''; 721 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) { 722 // Match the anchor against the NMTOKEN spec. 723 $this->anchor = $anchor; 724 } else { 725 // Bad luck, no valid anchor found. 726 $this->anchor = null; 727 } 728 } 729 730 /** 731 * Sets the scheme for the URI (the bit before ://) 732 * 733 * @param string $scheme 734 */ 735 public function set_scheme($scheme) { 736 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1. 737 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) { 738 $this->scheme = $scheme; 739 } else { 740 throw new coding_exception('Bad URL scheme.'); 741 } 742 } 743 744 /** 745 * Sets the url slashargument value. 746 * 747 * @param string $path usually file path 748 * @param string $parameter name of page parameter if slasharguments not supported 749 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers 750 * @return void 751 */ 752 public function set_slashargument($path, $parameter = 'file', $supported = null) { 753 global $CFG; 754 if (is_null($supported)) { 755 $supported = !empty($CFG->slasharguments); 756 } 757 758 if ($supported) { 759 $parts = explode('/', $path); 760 $parts = array_map('rawurlencode', $parts); 761 $path = implode('/', $parts); 762 $this->slashargument = $path; 763 unset($this->params[$parameter]); 764 765 } else { 766 $this->slashargument = ''; 767 $this->params[$parameter] = $path; 768 } 769 } 770 771 // Static factory methods. 772 773 /** 774 * General moodle file url. 775 * 776 * @param string $urlbase the script serving the file 777 * @param string $path 778 * @param bool $forcedownload 779 * @return moodle_url 780 */ 781 public static function make_file_url($urlbase, $path, $forcedownload = false) { 782 $params = array(); 783 if ($forcedownload) { 784 $params['forcedownload'] = 1; 785 } 786 $url = new moodle_url($urlbase, $params); 787 $url->set_slashargument($path); 788 return $url; 789 } 790 791 /** 792 * Factory method for creation of url pointing to plugin file. 793 * 794 * Please note this method can be used only from the plugins to 795 * create urls of own files, it must not be used outside of plugins! 796 * 797 * @param int $contextid 798 * @param string $component 799 * @param string $area 800 * @param int $itemid 801 * @param string $pathname 802 * @param string $filename 803 * @param bool $forcedownload 804 * @param mixed $includetoken Whether to use a user token when displaying this group image. 805 * True indicates to generate a token for current user, and integer value indicates to generate a token for the 806 * user whose id is the value indicated. 807 * If the group picture is included in an e-mail or some other location where the audience is a specific 808 * user who will not be logged in when viewing, then we use a token to authenticate the user. 809 * @return moodle_url 810 */ 811 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, 812 $forcedownload = false, $includetoken = false) { 813 global $CFG, $USER; 814 815 $path = []; 816 817 if ($includetoken) { 818 $urlbase = "$CFG->wwwroot/tokenpluginfile.php"; 819 $userid = $includetoken === true ? $USER->id : $includetoken; 820 $token = get_user_key('core_files', $userid); 821 if ($CFG->slasharguments) { 822 $path[] = $token; 823 } 824 } else { 825 $urlbase = "$CFG->wwwroot/pluginfile.php"; 826 } 827 $path[] = $contextid; 828 $path[] = $component; 829 $path[] = $area; 830 831 if ($itemid !== null) { 832 $path[] = $itemid; 833 } 834 835 $path = "/" . implode('/', $path) . "{$pathname}{$filename}"; 836 837 $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken); 838 if ($includetoken && empty($CFG->slasharguments)) { 839 $url->param('token', $token); 840 } 841 return $url; 842 } 843 844 /** 845 * Factory method for creation of url pointing to plugin file. 846 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script. 847 * It should be used only in external functions. 848 * 849 * @since 2.8 850 * @param int $contextid 851 * @param string $component 852 * @param string $area 853 * @param int $itemid 854 * @param string $pathname 855 * @param string $filename 856 * @param bool $forcedownload 857 * @return moodle_url 858 */ 859 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, 860 $forcedownload = false) { 861 global $CFG; 862 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php"; 863 if ($itemid === null) { 864 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload); 865 } else { 866 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload); 867 } 868 } 869 870 /** 871 * Factory method for creation of url pointing to draft file of current user. 872 * 873 * @param int $draftid draft item id 874 * @param string $pathname 875 * @param string $filename 876 * @param bool $forcedownload 877 * @return moodle_url 878 */ 879 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) { 880 global $CFG, $USER; 881 $urlbase = "$CFG->wwwroot/draftfile.php"; 882 $context = context_user::instance($USER->id); 883 884 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload); 885 } 886 887 /** 888 * Factory method for creating of links to legacy course files. 889 * 890 * @param int $courseid 891 * @param string $filepath 892 * @param bool $forcedownload 893 * @return moodle_url 894 */ 895 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) { 896 global $CFG; 897 898 $urlbase = "$CFG->wwwroot/file.php"; 899 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload); 900 } 901 902 /** 903 * Checks if URL is relative to $CFG->wwwroot. 904 * 905 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false. 906 */ 907 public function is_local_url() : bool { 908 global $CFG; 909 910 $url = $this->out(); 911 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot. 912 return ( ($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0) ); 913 } 914 915 /** 916 * Returns URL as relative path from $CFG->wwwroot 917 * 918 * Can be used for passing around urls with the wwwroot stripped 919 * 920 * @param boolean $escaped Use & as params separator instead of plain & 921 * @param array $overrideparams params to add to the output url, these override existing ones with the same name. 922 * @return string Resulting URL 923 * @throws coding_exception if called on a non-local url 924 */ 925 public function out_as_local_url($escaped = true, array $overrideparams = null) { 926 global $CFG; 927 928 // URL should be relative to wwwroot. If not then throw exception. 929 if ($this->is_local_url()) { 930 $url = $this->out($escaped, $overrideparams); 931 $localurl = substr($url, strlen($CFG->wwwroot)); 932 return !empty($localurl) ? $localurl : ''; 933 } else { 934 throw new coding_exception('out_as_local_url called on a non-local URL'); 935 } 936 } 937 938 /** 939 * Returns the 'path' portion of a URL. For example, if the URL is 940 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will 941 * return '/my/file/is/here.txt'. 942 * 943 * By default the path includes slash-arguments (for example, 944 * '/myfile.php/extra/arguments') so it is what you would expect from a 945 * URL path. If you don't want this behaviour, you can opt to exclude the 946 * slash arguments. (Be careful: if the $CFG variable slasharguments is 947 * disabled, these URLs will have a different format and you may need to 948 * look at the 'file' parameter too.) 949 * 950 * @param bool $includeslashargument If true, includes slash arguments 951 * @return string Path of URL 952 */ 953 public function get_path($includeslashargument = true) { 954 return $this->path . ($includeslashargument ? $this->slashargument : ''); 955 } 956 957 /** 958 * Returns a given parameter value from the URL. 959 * 960 * @param string $name Name of parameter 961 * @return string Value of parameter or null if not set 962 */ 963 public function get_param($name) { 964 if (array_key_exists($name, $this->params)) { 965 return $this->params[$name]; 966 } else { 967 return null; 968 } 969 } 970 971 /** 972 * Returns the 'scheme' portion of a URL. For example, if the URL is 973 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will 974 * return 'http' (without the colon). 975 * 976 * @return string Scheme of the URL. 977 */ 978 public function get_scheme() { 979 return $this->scheme; 980 } 981 982 /** 983 * Returns the 'host' portion of a URL. For example, if the URL is 984 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will 985 * return 'www.example.org'. 986 * 987 * @return string Host of the URL. 988 */ 989 public function get_host() { 990 return $this->host; 991 } 992 993 /** 994 * Returns the 'port' portion of a URL. For example, if the URL is 995 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will 996 * return '447'. 997 * 998 * @return string Port of the URL. 999 */ 1000 public function get_port() { 1001 return $this->port; 1002 } 1003 } 1004 1005 /** 1006 * Determine if there is data waiting to be processed from a form 1007 * 1008 * Used on most forms in Moodle to check for data 1009 * Returns the data as an object, if it's found. 1010 * This object can be used in foreach loops without 1011 * casting because it's cast to (array) automatically 1012 * 1013 * Checks that submitted POST data exists and returns it as object. 1014 * 1015 * @return mixed false or object 1016 */ 1017 function data_submitted() { 1018 1019 if (empty($_POST)) { 1020 return false; 1021 } else { 1022 return (object)fix_utf8($_POST); 1023 } 1024 } 1025 1026 /** 1027 * Given some normal text this function will break up any 1028 * long words to a given size by inserting the given character 1029 * 1030 * It's multibyte savvy and doesn't change anything inside html tags. 1031 * 1032 * @param string $string the string to be modified 1033 * @param int $maxsize maximum length of the string to be returned 1034 * @param string $cutchar the string used to represent word breaks 1035 * @return string 1036 */ 1037 function break_up_long_words($string, $maxsize=20, $cutchar=' ') { 1038 1039 // First of all, save all the tags inside the text to skip them. 1040 $tags = array(); 1041 filter_save_tags($string, $tags); 1042 1043 // Process the string adding the cut when necessary. 1044 $output = ''; 1045 $length = core_text::strlen($string); 1046 $wordlength = 0; 1047 1048 for ($i=0; $i<$length; $i++) { 1049 $char = core_text::substr($string, $i, 1); 1050 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") { 1051 $wordlength = 0; 1052 } else { 1053 $wordlength++; 1054 if ($wordlength > $maxsize) { 1055 $output .= $cutchar; 1056 $wordlength = 0; 1057 } 1058 } 1059 $output .= $char; 1060 } 1061 1062 // Finally load the tags back again. 1063 if (!empty($tags)) { 1064 $output = str_replace(array_keys($tags), $tags, $output); 1065 } 1066 1067 return $output; 1068 } 1069 1070 /** 1071 * Try and close the current window using JavaScript, either immediately, or after a delay. 1072 * 1073 * Echo's out the resulting XHTML & javascript 1074 * 1075 * @param integer $delay a delay in seconds before closing the window. Default 0. 1076 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try 1077 * to reload the parent window before this one closes. 1078 */ 1079 function close_window($delay = 0, $reloadopener = false) { 1080 global $PAGE, $OUTPUT; 1081 1082 if (!$PAGE->headerprinted) { 1083 $PAGE->set_title(get_string('closewindow')); 1084 echo $OUTPUT->header(); 1085 } else { 1086 $OUTPUT->container_end_all(false); 1087 } 1088 1089 if ($reloadopener) { 1090 // Trigger the reload immediately, even if the reload is after a delay. 1091 $PAGE->requires->js_function_call('window.opener.location.reload', array(true)); 1092 } 1093 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess'); 1094 1095 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay); 1096 1097 echo $OUTPUT->footer(); 1098 exit; 1099 } 1100 1101 /** 1102 * Returns a string containing a link to the user documentation for the current page. 1103 * 1104 * Also contains an icon by default. Shown to teachers and admin only. 1105 * 1106 * @param string $text The text to be displayed for the link 1107 * @return string The link to user documentation for this current page 1108 */ 1109 function page_doc_link($text='') { 1110 global $OUTPUT, $PAGE; 1111 $path = page_get_doc_link_path($PAGE); 1112 if (!$path) { 1113 return ''; 1114 } 1115 return $OUTPUT->doc_link($path, $text); 1116 } 1117 1118 /** 1119 * Returns the path to use when constructing a link to the docs. 1120 * 1121 * @since Moodle 2.5.1 2.6 1122 * @param moodle_page $page 1123 * @return string 1124 */ 1125 function page_get_doc_link_path(moodle_page $page) { 1126 global $CFG; 1127 1128 if (empty($CFG->docroot) || during_initial_install()) { 1129 return ''; 1130 } 1131 if (!has_capability('moodle/site:doclinks', $page->context)) { 1132 return ''; 1133 } 1134 1135 $path = $page->docspath; 1136 if (!$path) { 1137 return ''; 1138 } 1139 return $path; 1140 } 1141 1142 1143 /** 1144 * Validates an email to make sure it makes sense. 1145 * 1146 * @param string $address The email address to validate. 1147 * @return boolean 1148 */ 1149 function validate_email($address) { 1150 global $CFG; 1151 1152 if ($address === null || $address === false || $address === '') { 1153 return false; 1154 } 1155 1156 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php"); 1157 1158 return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address); 1159 } 1160 1161 /** 1162 * Extracts file argument either from file parameter or PATH_INFO 1163 * 1164 * Note: $scriptname parameter is not needed anymore 1165 * 1166 * @return string file path (only safe characters) 1167 */ 1168 function get_file_argument() { 1169 global $SCRIPT; 1170 1171 $relativepath = false; 1172 $hasforcedslashargs = false; 1173 1174 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) { 1175 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/' 1176 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm. 1177 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false) 1178 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) { 1179 // Exclude edge cases like '/pluginfile.php/?file='. 1180 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/')); 1181 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea. 1182 } 1183 } 1184 if (!$hasforcedslashargs) { 1185 $relativepath = optional_param('file', false, PARAM_PATH); 1186 } 1187 1188 if ($relativepath !== false and $relativepath !== '') { 1189 return $relativepath; 1190 } 1191 $relativepath = false; 1192 1193 // Then try extract file from the slasharguments. 1194 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) { 1195 // NOTE: IIS tends to convert all file paths to single byte DOS encoding, 1196 // we can not use other methods because they break unicode chars, 1197 // the only ways are to use URL rewriting 1198 // OR 1199 // to properly set the 'FastCGIUtf8ServerVariables' registry key. 1200 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') { 1201 // Check that PATH_INFO works == must not contain the script name. 1202 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) { 1203 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH); 1204 } 1205 } 1206 } else { 1207 // All other apache-like servers depend on PATH_INFO. 1208 if (isset($_SERVER['PATH_INFO'])) { 1209 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) { 1210 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME'])); 1211 } else { 1212 $relativepath = $_SERVER['PATH_INFO']; 1213 } 1214 $relativepath = clean_param($relativepath, PARAM_PATH); 1215 } 1216 } 1217 1218 return $relativepath; 1219 } 1220 1221 /** 1222 * Just returns an array of text formats suitable for a popup menu 1223 * 1224 * @return array 1225 */ 1226 function format_text_menu() { 1227 return array (FORMAT_MOODLE => get_string('formattext'), 1228 FORMAT_HTML => get_string('formathtml'), 1229 FORMAT_PLAIN => get_string('formatplain'), 1230 FORMAT_MARKDOWN => get_string('formatmarkdown')); 1231 } 1232 1233 /** 1234 * Given text in a variety of format codings, this function returns the text as safe HTML. 1235 * 1236 * This function should mainly be used for long strings like posts, 1237 * answers, glossary items etc. For short strings {@link format_string()}. 1238 * 1239 * <pre> 1240 * Options: 1241 * trusted : If true the string won't be cleaned. Default false required noclean=true. 1242 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true. 1243 * nocache : If true the strign will not be cached and will be formatted every call. Default false. 1244 * filter : If true the string will be run through applicable filters as well. Default true. 1245 * para : If true then the returned string will be wrapped in div tags. Default true. 1246 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true. 1247 * context : The context that will be used for filtering. 1248 * overflowdiv : If set to true the formatted text will be encased in a div 1249 * with the class no-overflow before being returned. Default false. 1250 * allowid : If true then id attributes will not be removed, even when 1251 * using htmlpurifier. Default false. 1252 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified. 1253 * </pre> 1254 * 1255 * @staticvar array $croncache 1256 * @param string $text The text to be formatted. This is raw text originally from user input. 1257 * @param int $format Identifier of the text format to be used 1258 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN] 1259 * @param stdClass|array $options text formatting options 1260 * @param int $courseiddonotuse deprecated course id, use context option instead 1261 * @return string 1262 */ 1263 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) { 1264 global $CFG, $DB, $PAGE; 1265 1266 if ($text === '' || is_null($text)) { 1267 // No need to do any filters and cleaning. 1268 return ''; 1269 } 1270 1271 if ($options instanceof \core\context) { 1272 // A common mistake has been to call this function with a context object. 1273 // This has never been expected, nor supported. 1274 debugging( 1275 'The options argument should not be a context object directly. ' . 1276 ' Please pass an array with a context key instead.', 1277 DEBUG_DEVELOPER, 1278 ); 1279 $options = ['context' => $options]; 1280 } 1281 1282 // Detach object, we can not modify it. 1283 $options = (array)$options; 1284 1285 if (!isset($options['trusted'])) { 1286 $options['trusted'] = false; 1287 } 1288 if ($format == FORMAT_MARKDOWN) { 1289 // Markdown format cannot be trusted in trusttext areas, 1290 // because we do not know how to sanitise it before editing. 1291 $options['trusted'] = false; 1292 } 1293 if (!isset($options['noclean'])) { 1294 if ($options['trusted'] and trusttext_active()) { 1295 // No cleaning if text trusted and noclean not specified. 1296 $options['noclean'] = true; 1297 } else { 1298 $options['noclean'] = false; 1299 } 1300 } 1301 if (!empty($CFG->forceclean)) { 1302 // Whatever the caller claims, the admin wants all content cleaned anyway. 1303 $options['noclean'] = false; 1304 } 1305 if (!isset($options['nocache'])) { 1306 $options['nocache'] = false; 1307 } 1308 if (!isset($options['filter'])) { 1309 $options['filter'] = true; 1310 } 1311 if (!isset($options['para'])) { 1312 $options['para'] = true; 1313 } 1314 if (!isset($options['newlines'])) { 1315 $options['newlines'] = true; 1316 } 1317 if (!isset($options['overflowdiv'])) { 1318 $options['overflowdiv'] = false; 1319 } 1320 $options['blanktarget'] = !empty($options['blanktarget']); 1321 1322 // Calculate best context. 1323 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) { 1324 // Do not filter anything during installation or before upgrade completes. 1325 $context = null; 1326 1327 } else if (isset($options['context'])) { // First by explicit passed context option. 1328 if (is_object($options['context'])) { 1329 $context = $options['context']; 1330 } else { 1331 $context = context::instance_by_id($options['context']); 1332 } 1333 } else if ($courseiddonotuse) { 1334 // Legacy courseid. 1335 $context = context_course::instance($courseiddonotuse); 1336 } else { 1337 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(. 1338 $context = $PAGE->context; 1339 } 1340 1341 if (!$context) { 1342 // Either install/upgrade or something has gone really wrong because context does not exist (yet?). 1343 $options['nocache'] = true; 1344 $options['filter'] = false; 1345 } 1346 1347 if ($options['filter']) { 1348 $filtermanager = filter_manager::instance(); 1349 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have. 1350 $filteroptions = array( 1351 'originalformat' => $format, 1352 'noclean' => $options['noclean'], 1353 ); 1354 } else { 1355 $filtermanager = new null_filter_manager(); 1356 $filteroptions = array(); 1357 } 1358 1359 switch ($format) { 1360 case FORMAT_HTML: 1361 $filteroptions['stage'] = 'pre_format'; 1362 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1363 // Text is already in HTML format, so just continue to the next filtering stage. 1364 $filteroptions['stage'] = 'pre_clean'; 1365 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1366 if (!$options['noclean']) { 1367 $text = clean_text($text, FORMAT_HTML, $options); 1368 } 1369 $filteroptions['stage'] = 'post_clean'; 1370 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1371 break; 1372 1373 case FORMAT_PLAIN: 1374 $text = s($text); // Cleans dangerous JS. 1375 $text = rebuildnolinktag($text); 1376 $text = str_replace(' ', ' ', $text); 1377 $text = nl2br($text); 1378 break; 1379 1380 case FORMAT_WIKI: 1381 // This format is deprecated. 1382 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing 1383 this message as all texts should have been converted to Markdown format instead. 1384 Please post a bug report to http://moodle.org/bugs with information about where you 1385 saw this message.</p>'.s($text); 1386 break; 1387 1388 case FORMAT_MARKDOWN: 1389 $filteroptions['stage'] = 'pre_format'; 1390 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1391 $text = markdown_to_html($text); 1392 $filteroptions['stage'] = 'pre_clean'; 1393 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1394 if (!$options['noclean']) { 1395 $text = clean_text($text, FORMAT_HTML, $options); 1396 } 1397 $filteroptions['stage'] = 'post_clean'; 1398 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1399 break; 1400 1401 default: // FORMAT_MOODLE or anything else. 1402 $filteroptions['stage'] = 'pre_format'; 1403 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1404 $text = text_to_html($text, null, $options['para'], $options['newlines']); 1405 $filteroptions['stage'] = 'pre_clean'; 1406 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1407 if (!$options['noclean']) { 1408 $text = clean_text($text, FORMAT_HTML, $options); 1409 } 1410 $filteroptions['stage'] = 'post_clean'; 1411 $text = $filtermanager->filter_text($text, $context, $filteroptions); 1412 break; 1413 } 1414 if ($options['filter']) { 1415 // At this point there should not be any draftfile links any more, 1416 // this happens when developers forget to post process the text. 1417 // The only potential problem is that somebody might try to format 1418 // the text before storing into database which would be itself big bug.. 1419 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text); 1420 1421 if ($CFG->debugdeveloper) { 1422 if (strpos($text, '@@PLUGINFILE@@/') !== false) { 1423 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()', 1424 DEBUG_DEVELOPER); 1425 } 1426 } 1427 } 1428 1429 if (!empty($options['overflowdiv'])) { 1430 $text = html_writer::tag('div', $text, array('class' => 'no-overflow')); 1431 } 1432 1433 if ($options['blanktarget']) { 1434 $domdoc = new DOMDocument(); 1435 libxml_use_internal_errors(true); 1436 $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text); 1437 libxml_clear_errors(); 1438 foreach ($domdoc->getElementsByTagName('a') as $link) { 1439 if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) { 1440 continue; 1441 } 1442 $link->setAttribute('target', '_blank'); 1443 if (strpos($link->getAttribute('rel'), 'noreferrer') === false) { 1444 $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer')); 1445 } 1446 } 1447 1448 // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so: 1449 // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like some libxml 1450 // versions don't work properly and end up leaving <html><body>, so I'm forced to use 1451 // this regex to remove those tags as a preventive measure. 1452 $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement))); 1453 } 1454 1455 return $text; 1456 } 1457 1458 /** 1459 * Resets some data related to filters, called during upgrade or when general filter settings change. 1460 * 1461 * @param bool $phpunitreset true means called from our PHPUnit integration test reset 1462 * @return void 1463 */ 1464 function reset_text_filters_cache($phpunitreset = false) { 1465 global $CFG, $DB; 1466 1467 if ($phpunitreset) { 1468 // HTMLPurifier does not change, DB is already reset to defaults, 1469 // nothing to do here, the dataroot was cleared too. 1470 return; 1471 } 1472 1473 // The purge_all_caches() deals with cachedir and localcachedir purging, 1474 // the individual filter caches are invalidated as necessary elsewhere. 1475 1476 // Update $CFG->filterall cache flag. 1477 if (empty($CFG->stringfilters)) { 1478 set_config('filterall', 0); 1479 return; 1480 } 1481 $installedfilters = core_component::get_plugin_list('filter'); 1482 $filters = explode(',', $CFG->stringfilters); 1483 foreach ($filters as $filter) { 1484 if (isset($installedfilters[$filter])) { 1485 set_config('filterall', 1); 1486 return; 1487 } 1488 } 1489 set_config('filterall', 0); 1490 } 1491 1492 /** 1493 * Given a simple string, this function returns the string 1494 * processed by enabled string filters if $CFG->filterall is enabled 1495 * 1496 * This function should be used to print short strings (non html) that 1497 * need filter processing e.g. activity titles, post subjects, 1498 * glossary concepts. 1499 * 1500 * @staticvar bool $strcache 1501 * @param string $string The string to be filtered. Should be plain text, expect 1502 * possibly for multilang tags. 1503 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713 1504 * @param array $options options array/object or courseid 1505 * @return string 1506 */ 1507 function format_string($string, $striplinks = true, $options = null) { 1508 global $CFG, $PAGE; 1509 1510 if ($string === '' || is_null($string)) { 1511 // No need to do any filters and cleaning. 1512 return ''; 1513 } 1514 1515 // We'll use a in-memory cache here to speed up repeated strings. 1516 static $strcache = false; 1517 1518 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) { 1519 // Do not filter anything during installation or before upgrade completes. 1520 return $string = strip_tags($string); 1521 } 1522 1523 if ($strcache === false or count($strcache) > 2000) { 1524 // This number might need some tuning to limit memory usage in cron. 1525 $strcache = array(); 1526 } 1527 1528 // This method only expects either: 1529 // - an array of options; 1530 // - a stdClass of options to be cast to an array; or 1531 // - an integer courseid. 1532 if ($options === null) { 1533 $options = []; 1534 } else if (is_numeric($options)) { 1535 // Legacy courseid usage. 1536 $options = ['context' => \core\context\course::instance($options)]; 1537 } else if ($options instanceof \core\context) { 1538 // A common mistake has been to call this function with a context object. 1539 // This has never been expected, or nor supported. 1540 debugging( 1541 'The options argument should not be a context object directly. ' . 1542 ' Please pass an array with a context key instead.', 1543 DEBUG_DEVELOPER, 1544 ); 1545 $options = ['context' => $options]; 1546 } else if (is_array($options) || is_a($options, \stdClass::class)) { 1547 // Re-cast to array to prevent modifications to the original object. 1548 $options = (array) $options; 1549 } else { 1550 // Something else was passed, so we'll just use an empty array. 1551 // Attempt to cast to array since we always used to, but throw in some debugging. 1552 debugging(sprintf( 1553 'The options argument should be an Array, or stdclass. %s passed.', 1554 gettype($options), 1555 ), DEBUG_DEVELOPER); 1556 $options = (array) $options; 1557 } 1558 1559 if (empty($options['context'])) { 1560 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(. 1561 $options['context'] = $PAGE->context; 1562 } else if (is_numeric($options['context'])) { 1563 $options['context'] = context::instance_by_id($options['context']); 1564 } 1565 if (!isset($options['filter'])) { 1566 $options['filter'] = true; 1567 } 1568 1569 $options['escape'] = !isset($options['escape']) || $options['escape']; 1570 1571 if (!$options['context']) { 1572 // We did not find any context? weird. 1573 return $string = strip_tags($string); 1574 } 1575 1576 // Calculate md5. 1577 $cachekeys = array($string, $striplinks, $options['context']->id, 1578 $options['escape'], current_language(), $options['filter']); 1579 $md5 = md5(implode('<+>', $cachekeys)); 1580 1581 // Fetch from cache if possible. 1582 if (isset($strcache[$md5])) { 1583 return $strcache[$md5]; 1584 } 1585 1586 // First replace all ampersands not followed by html entity code 1587 // Regular expression moved to its own method for easier unit testing. 1588 $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string; 1589 1590 if (!empty($CFG->filterall) && $options['filter']) { 1591 $filtermanager = filter_manager::instance(); 1592 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have. 1593 $string = $filtermanager->filter_string($string, $options['context']); 1594 } 1595 1596 // If the site requires it, strip ALL tags from this string. 1597 if (!empty($CFG->formatstringstriptags)) { 1598 if ($options['escape']) { 1599 $string = str_replace(array('<', '>'), array('<', '>'), strip_tags($string)); 1600 } else { 1601 $string = strip_tags($string); 1602 } 1603 } else { 1604 // Otherwise strip just links if that is required (default). 1605 if ($striplinks) { 1606 // Strip links in string. 1607 $string = strip_links($string); 1608 } 1609 $string = clean_text($string); 1610 } 1611 1612 // Store to cache. 1613 $strcache[$md5] = $string; 1614 1615 return $string; 1616 } 1617 1618 /** 1619 * Given a string, performs a negative lookahead looking for any ampersand character 1620 * that is not followed by a proper HTML entity. If any is found, it is replaced 1621 * by &. The string is then returned. 1622 * 1623 * @param string $string 1624 * @return string 1625 */ 1626 function replace_ampersands_not_followed_by_entity($string) { 1627 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string ?? ''); 1628 } 1629 1630 /** 1631 * Given a string, replaces all <a>.*</a> by .* and returns the string. 1632 * 1633 * @param string $string 1634 * @return string 1635 */ 1636 function strip_links($string) { 1637 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string); 1638 } 1639 1640 /** 1641 * This expression turns links into something nice in a text format. (Russell Jungwirth) 1642 * 1643 * @param string $string 1644 * @return string 1645 */ 1646 function wikify_links($string) { 1647 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string); 1648 } 1649 1650 /** 1651 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email. 1652 * 1653 * @param string $text The text to be formatted. This is raw text originally from user input. 1654 * @param int $format Identifier of the text format to be used 1655 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN] 1656 * @return string 1657 */ 1658 function format_text_email($text, $format) { 1659 1660 switch ($format) { 1661 1662 case FORMAT_PLAIN: 1663 return $text; 1664 break; 1665 1666 case FORMAT_WIKI: 1667 // There should not be any of these any more! 1668 $text = wikify_links($text); 1669 return core_text::entities_to_utf8(strip_tags($text), true); 1670 break; 1671 1672 case FORMAT_HTML: 1673 return html_to_text($text); 1674 break; 1675 1676 case FORMAT_MOODLE: 1677 case FORMAT_MARKDOWN: 1678 default: 1679 $text = wikify_links($text); 1680 return core_text::entities_to_utf8(strip_tags($text), true); 1681 break; 1682 } 1683 } 1684 1685 /** 1686 * Formats activity intro text 1687 * 1688 * @param string $module name of module 1689 * @param object $activity instance of activity 1690 * @param int $cmid course module id 1691 * @param bool $filter filter resulting html text 1692 * @return string 1693 */ 1694 function format_module_intro($module, $activity, $cmid, $filter=true) { 1695 global $CFG; 1696 require_once("$CFG->libdir/filelib.php"); 1697 $context = context_module::instance($cmid); 1698 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true); 1699 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null); 1700 return trim(format_text($intro, $activity->introformat, $options, null)); 1701 } 1702 1703 /** 1704 * Removes the usage of Moodle files from a text. 1705 * 1706 * In some rare cases we need to re-use a text that already has embedded links 1707 * to some files hosted within Moodle. But the new area in which we will push 1708 * this content does not support files... therefore we need to remove those files. 1709 * 1710 * @param string $source The text 1711 * @return string The stripped text 1712 */ 1713 function strip_pluginfile_content($source) { 1714 $baseurl = '@@PLUGINFILE@@'; 1715 // Looking for something like < .* "@@pluginfile@@.*" .* > 1716 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$'; 1717 $stripped = preg_replace($pattern, '', $source); 1718 // Use purify html to rebalence potentially mismatched tags and generally cleanup. 1719 return purify_html($stripped); 1720 } 1721 1722 /** 1723 * Legacy function, used for cleaning of old forum and glossary text only. 1724 * 1725 * @param string $text text that may contain legacy TRUSTTEXT marker 1726 * @return string text without legacy TRUSTTEXT marker 1727 */ 1728 function trusttext_strip($text) { 1729 if (!is_string($text)) { 1730 // This avoids the potential for an endless loop below. 1731 throw new coding_exception('trusttext_strip parameter must be a string'); 1732 } 1733 while (true) { // Removing nested TRUSTTEXT. 1734 $orig = $text; 1735 $text = str_replace('#####TRUSTTEXT#####', '', $text); 1736 if (strcmp($orig, $text) === 0) { 1737 return $text; 1738 } 1739 } 1740 } 1741 1742 /** 1743 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed. 1744 * 1745 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields 1746 * @param string $field name of text field 1747 * @param context $context active context 1748 * @return stdClass updated $object 1749 */ 1750 function trusttext_pre_edit($object, $field, $context) { 1751 $trustfield = $field.'trust'; 1752 $formatfield = $field.'format'; 1753 1754 if ($object->$formatfield == FORMAT_MARKDOWN) { 1755 // We do not have a way to sanitise Markdown texts, 1756 // luckily editors for this format should not have XSS problems. 1757 return $object; 1758 } 1759 1760 if (!$object->$trustfield or !trusttext_trusted($context)) { 1761 $object->$field = clean_text($object->$field, $object->$formatfield); 1762 } 1763 1764 return $object; 1765 } 1766 1767 /** 1768 * Is current user trusted to enter no dangerous XSS in this context? 1769 * 1770 * Please note the user must be in fact trusted everywhere on this server!! 1771 * 1772 * @param context $context 1773 * @return bool true if user trusted 1774 */ 1775 function trusttext_trusted($context) { 1776 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context)); 1777 } 1778 1779 /** 1780 * Is trusttext feature active? 1781 * 1782 * @return bool 1783 */ 1784 function trusttext_active() { 1785 global $CFG; 1786 1787 return !empty($CFG->enabletrusttext); 1788 } 1789 1790 /** 1791 * Cleans raw text removing nasties. 1792 * 1793 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up 1794 * Moodle pages through XSS attacks. 1795 * 1796 * The result must be used as a HTML text fragment, this function can not cleanup random 1797 * parts of html tags such as url or src attributes. 1798 * 1799 * NOTE: the format parameter was deprecated because we can safely clean only HTML. 1800 * 1801 * @param string $text The text to be cleaned 1802 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE 1803 * @param array $options Array of options; currently only option supported is 'allowid' (if true, 1804 * does not remove id attributes when cleaning) 1805 * @return string The cleaned up text 1806 */ 1807 function clean_text($text, $format = FORMAT_HTML, $options = array()) { 1808 $text = (string)$text; 1809 1810 if ($format != FORMAT_HTML and $format != FORMAT_HTML) { 1811 // TODO: we need to standardise cleanup of text when loading it into editor first. 1812 // debugging('clean_text() is designed to work only with html');. 1813 } 1814 1815 if ($format == FORMAT_PLAIN) { 1816 return $text; 1817 } 1818 1819 if (is_purify_html_necessary($text)) { 1820 $text = purify_html($text, $options); 1821 } 1822 1823 // Originally we tried to neutralise some script events here, it was a wrong approach because 1824 // it was trivial to work around that (for example using style based XSS exploits). 1825 // We must not give false sense of security here - all developers MUST understand how to use 1826 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!! 1827 1828 return $text; 1829 } 1830 1831 /** 1832 * Is it necessary to use HTMLPurifier? 1833 * 1834 * @private 1835 * @param string $text 1836 * @return bool false means html is safe and valid, true means use HTMLPurifier 1837 */ 1838 function is_purify_html_necessary($text) { 1839 if ($text === '') { 1840 return false; 1841 } 1842 1843 if ($text === (string)((int)$text)) { 1844 return false; 1845 } 1846 1847 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) { 1848 // We need to normalise entities or other tags except p, em, strong and br present. 1849 return true; 1850 } 1851 1852 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true); 1853 if ($altered === $text) { 1854 // No < > or other special chars means this must be safe. 1855 return false; 1856 } 1857 1858 // Let's try to convert back some safe html tags. 1859 $altered = preg_replace('|<p>(.*?)</p>|m', '<p>$1</p>', $altered); 1860 if ($altered === $text) { 1861 return false; 1862 } 1863 $altered = preg_replace('|<em>([^<>]+?)</em>|m', '<em>$1</em>', $altered); 1864 if ($altered === $text) { 1865 return false; 1866 } 1867 $altered = preg_replace('|<strong>([^<>]+?)</strong>|m', '<strong>$1</strong>', $altered); 1868 if ($altered === $text) { 1869 return false; 1870 } 1871 $altered = str_replace('<br />', '<br />', $altered); 1872 if ($altered === $text) { 1873 return false; 1874 } 1875 1876 return true; 1877 } 1878 1879 /** 1880 * KSES replacement cleaning function - uses HTML Purifier. 1881 * 1882 * @param string $text The (X)HTML string to purify 1883 * @param array $options Array of options; currently only option supported is 'allowid' (if set, 1884 * does not remove id attributes when cleaning) 1885 * @return string 1886 */ 1887 function purify_html($text, $options = array()) { 1888 global $CFG; 1889 1890 $text = (string)$text; 1891 1892 static $purifiers = array(); 1893 static $caches = array(); 1894 1895 // Purifier code can change only during major version upgrade. 1896 $version = empty($CFG->version) ? 0 : $CFG->version; 1897 $cachedir = "$CFG->localcachedir/htmlpurifier/$version"; 1898 if (!file_exists($cachedir)) { 1899 // Purging of caches may remove the cache dir at any time, 1900 // luckily file_exists() results should be cached for all existing directories. 1901 $purifiers = array(); 1902 $caches = array(); 1903 gc_collect_cycles(); 1904 1905 make_localcache_directory('htmlpurifier', false); 1906 check_dir_exists($cachedir); 1907 } 1908 1909 $allowid = empty($options['allowid']) ? 0 : 1; 1910 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1; 1911 1912 $type = 'type_'.$allowid.'_'.$allowobjectembed; 1913 1914 if (!array_key_exists($type, $caches)) { 1915 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type)); 1916 } 1917 $cache = $caches[$type]; 1918 1919 // Add revision number and all options to the text key so that it is compatible with local cluster node caches. 1920 $key = "|$version|$allowobjectembed|$allowid|$text"; 1921 $filteredtext = $cache->get($key); 1922 1923 if ($filteredtext === true) { 1924 // The filtering did not change the text last time, no need to filter anything again. 1925 return $text; 1926 } else if ($filteredtext !== false) { 1927 return $filteredtext; 1928 } 1929 1930 if (empty($purifiers[$type])) { 1931 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php'; 1932 require_once $CFG->libdir.'/htmlpurifier/locallib.php'; 1933 $config = HTMLPurifier_Config::createDefault(); 1934 1935 $config->set('HTML.DefinitionID', 'moodlehtml'); 1936 $config->set('HTML.DefinitionRev', 7); 1937 $config->set('Cache.SerializerPath', $cachedir); 1938 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions); 1939 $config->set('Core.NormalizeNewlines', false); 1940 $config->set('Core.ConvertDocumentToFragment', true); 1941 $config->set('Core.Encoding', 'UTF-8'); 1942 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); 1943 $config->set('URI.AllowedSchemes', array( 1944 'http' => true, 1945 'https' => true, 1946 'ftp' => true, 1947 'irc' => true, 1948 'nntp' => true, 1949 'news' => true, 1950 'rtsp' => true, 1951 'rtmp' => true, 1952 'teamspeak' => true, 1953 'gopher' => true, 1954 'mms' => true, 1955 'mailto' => true 1956 )); 1957 $config->set('Attr.AllowedFrameTargets', array('_blank')); 1958 1959 if ($allowobjectembed) { 1960 $config->set('HTML.SafeObject', true); 1961 $config->set('Output.FlashCompat', true); 1962 $config->set('HTML.SafeEmbed', true); 1963 } 1964 1965 if ($allowid) { 1966 $config->set('Attr.EnableID', true); 1967 } 1968 1969 if ($def = $config->maybeGetRawHTMLDefinition()) { 1970 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside. 1971 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$. 1972 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@. 1973 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute. 1974 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang. 1975 1976 // Media elements. 1977 // https://html.spec.whatwg.org/#the-video-element 1978 $def->addElement('video', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [ 1979 'src' => 'URI', 1980 'crossorigin' => 'Enum#anonymous,use-credentials', 1981 'poster' => 'URI', 1982 'preload' => 'Enum#auto,metadata,none', 1983 'autoplay' => 'Bool', 1984 'playsinline' => 'Bool', 1985 'loop' => 'Bool', 1986 'muted' => 'Bool', 1987 'controls' => 'Bool', 1988 'width' => 'Length', 1989 'height' => 'Length', 1990 ]); 1991 // https://html.spec.whatwg.org/#the-audio-element 1992 $def->addElement('audio', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [ 1993 'src' => 'URI', 1994 'crossorigin' => 'Enum#anonymous,use-credentials', 1995 'preload' => 'Enum#auto,metadata,none', 1996 'autoplay' => 'Bool', 1997 'loop' => 'Bool', 1998 'muted' => 'Bool', 1999 'controls' => 'Bool' 2000 ]); 2001 // https://html.spec.whatwg.org/#the-source-element 2002 $def->addElement('source', false, 'Empty', null, [ 2003 'src' => 'URI', 2004 'type' => 'Text' 2005 ]); 2006 // https://html.spec.whatwg.org/#the-track-element 2007 $def->addElement('track', false, 'Empty', null, [ 2008 'src' => 'URI', 2009 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata', 2010 'srclang' => 'Text', 2011 'label' => 'Text', 2012 'default' => 'Bool', 2013 ]); 2014 2015 // Use the built-in Ruby module to add annotation support. 2016 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby()); 2017 } 2018 2019 $purifier = new HTMLPurifier($config); 2020 $purifiers[$type] = $purifier; 2021 } else { 2022 $purifier = $purifiers[$type]; 2023 } 2024 2025 $multilang = (strpos($text, 'class="multilang"') !== false); 2026 2027 $filteredtext = $text; 2028 if ($multilang) { 2029 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/'; 2030 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="$2}">', $filteredtext); 2031 } 2032 $filteredtext = (string)$purifier->purify($filteredtext); 2033 if ($multilang) { 2034 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="$1}" class="multilang">', $filteredtext); 2035 } 2036 2037 if ($text === $filteredtext) { 2038 // No need to store the filtered text, next time we will just return unfiltered text 2039 // because it was not changed by purifying. 2040 $cache->set($key, true); 2041 } else { 2042 $cache->set($key, $filteredtext); 2043 } 2044 2045 return $filteredtext; 2046 } 2047 2048 /** 2049 * Given plain text, makes it into HTML as nicely as possible. 2050 * 2051 * May contain HTML tags already. 2052 * 2053 * Do not abuse this function. It is intended as lower level formatting feature used 2054 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed 2055 * to call format_text() in most of cases. 2056 * 2057 * @param string $text The string to convert. 2058 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now 2059 * @param boolean $para If true then the returned string will be wrapped in div tags 2060 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks. 2061 * @return string 2062 */ 2063 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) { 2064 // Remove any whitespace that may be between HTML tags. 2065 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text); 2066 2067 // Remove any returns that precede or follow HTML tags. 2068 $text = preg_replace("~([\n\r])<~i", " <", $text); 2069 $text = preg_replace("~>([\n\r])~i", "> ", $text); 2070 2071 // Make returns into HTML newlines. 2072 if ($newlines) { 2073 $text = nl2br($text); 2074 } 2075 2076 // Wrap the whole thing in a div if required. 2077 if ($para) { 2078 // In 1.9 this was changed from a p => div. 2079 return '<div class="text_to_html">'.$text.'</div>'; 2080 } else { 2081 return $text; 2082 } 2083 } 2084 2085 /** 2086 * Given Markdown formatted text, make it into XHTML using external function 2087 * 2088 * @param string $text The markdown formatted text to be converted. 2089 * @return string Converted text 2090 */ 2091 function markdown_to_html($text) { 2092 global $CFG; 2093 2094 if ($text === '' or $text === null) { 2095 return $text; 2096 } 2097 2098 require_once($CFG->libdir .'/markdown/MarkdownInterface.php'); 2099 require_once($CFG->libdir .'/markdown/Markdown.php'); 2100 require_once($CFG->libdir .'/markdown/MarkdownExtra.php'); 2101 2102 return \Michelf\MarkdownExtra::defaultTransform($text); 2103 } 2104 2105 /** 2106 * Given HTML text, make it into plain text using external function 2107 * 2108 * @param string $html The text to be converted. 2109 * @param integer $width Width to wrap the text at. (optional, default 75 which 2110 * is a good value for email. 0 means do not limit line length.) 2111 * @param boolean $dolinks By default, any links in the HTML are collected, and 2112 * printed as a list at the end of the HTML. If you don't want that, set this 2113 * argument to false. 2114 * @return string plain text equivalent of the HTML. 2115 */ 2116 function html_to_text($html, $width = 75, $dolinks = true) { 2117 global $CFG; 2118 2119 require_once($CFG->libdir .'/html2text/lib.php'); 2120 2121 $options = array( 2122 'width' => $width, 2123 'do_links' => 'table', 2124 ); 2125 2126 if (empty($dolinks)) { 2127 $options['do_links'] = 'none'; 2128 } 2129 $h2t = new core_html2text($html, $options); 2130 $result = $h2t->getText(); 2131 2132 return $result; 2133 } 2134 2135 /** 2136 * Converts texts or strings to plain text. 2137 * 2138 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually 2139 * do in format_text. 2140 * - When this function is used for strings that are usually passed through format_string before displaying them 2141 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if 2142 * multilang filter is applied to headings. 2143 * 2144 * @param string $content The text as entered by the user 2145 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN 2146 * @return string Plain text. 2147 */ 2148 function content_to_text($content, $contentformat) { 2149 2150 switch ($contentformat) { 2151 case FORMAT_PLAIN: 2152 // Nothing here. 2153 break; 2154 case FORMAT_MARKDOWN: 2155 $content = markdown_to_html($content); 2156 $content = html_to_text($content, 75, false); 2157 break; 2158 default: 2159 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through 2160 // format_string, we need to convert them from html because they can contain HTML (multilang filter). 2161 $content = html_to_text($content, 75, false); 2162 } 2163 2164 return trim($content, "\r\n "); 2165 } 2166 2167 /** 2168 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text 2169 * is required; other file fields may be passed to filter. 2170 * 2171 * @param string $text Some html content. 2172 * @param bool $forcehttps force https urls. 2173 * @param int $contextid This parameter and the next three identify the file area to save to. 2174 * @param string $component The component name. 2175 * @param string $filearea The filearea. 2176 * @param int $itemid The item id for the filearea. 2177 * @param string $filename The specific filename of the file. 2178 * @return array 2179 */ 2180 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null, 2181 $filearea = null, $itemid = null, $filename = null) { 2182 global $CFG; 2183 2184 $wwwroot = $CFG->wwwroot; 2185 if ($forcehttps) { 2186 $wwwroot = str_replace('http://', 'https://', $wwwroot); 2187 } 2188 $urlstring = '/' . preg_quote($wwwroot, '/'); 2189 2190 $urlbase = preg_quote('draftfile.php'); 2191 $urlstring .= "\/(?<urlbase>{$urlbase})"; 2192 2193 if (is_null($contextid)) { 2194 $contextid = '[0-9]+'; 2195 } 2196 $urlstring .= "\/(?<contextid>{$contextid})"; 2197 2198 if (is_null($component)) { 2199 $component = '[a-z_]+'; 2200 } 2201 $urlstring .= "\/(?<component>{$component})"; 2202 2203 if (is_null($filearea)) { 2204 $filearea = '[a-z_]+'; 2205 } 2206 $urlstring .= "\/(?<filearea>{$filearea})"; 2207 2208 if (is_null($itemid)) { 2209 $itemid = '[0-9]+'; 2210 } 2211 $urlstring .= "\/(?<itemid>{$itemid})"; 2212 2213 // Filename matching magic based on file_rewrite_urls_to_pluginfile(). 2214 if (is_null($filename)) { 2215 $filename = '[^\'\",&<>|`\s:\\\\]+'; 2216 } 2217 $urlstring .= "\/(?<filename>{$filename})/"; 2218 2219 // Regular expression which matches URLs and returns their components. 2220 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER); 2221 return $urls; 2222 } 2223 2224 /** 2225 * This function will highlight search words in a given string 2226 * 2227 * It cares about HTML and will not ruin links. It's best to use 2228 * this function after performing any conversions to HTML. 2229 * 2230 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly. 2231 * @param string $haystack The string (HTML) within which to highlight the search terms. 2232 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive. 2233 * @param string $prefix the string to put before each search term found. 2234 * @param string $suffix the string to put after each search term found. 2235 * @return string The highlighted HTML. 2236 */ 2237 function highlight($needle, $haystack, $matchcase = false, 2238 $prefix = '<span class="highlight">', $suffix = '</span>') { 2239 2240 // Quick bail-out in trivial cases. 2241 if (empty($needle) or empty($haystack)) { 2242 return $haystack; 2243 } 2244 2245 // Break up the search term into words, discard any -words and build a regexp. 2246 $words = preg_split('/ +/', trim($needle)); 2247 foreach ($words as $index => $word) { 2248 if (strpos($word, '-') === 0) { 2249 unset($words[$index]); 2250 } else if (strpos($word, '+') === 0) { 2251 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word. 2252 } else { 2253 $words[$index] = preg_quote($word, '/'); 2254 } 2255 } 2256 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching. 2257 if (!$matchcase) { 2258 $regexp .= 'i'; 2259 } 2260 2261 // Another chance to bail-out if $search was only -words. 2262 if (empty($words)) { 2263 return $haystack; 2264 } 2265 2266 // Split the string into HTML tags and real content. 2267 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE); 2268 2269 // We have an array of alternating blocks of text, then HTML tags, then text, ... 2270 // Loop through replacing search terms in the text, and leaving the HTML unchanged. 2271 $ishtmlchunk = false; 2272 $result = ''; 2273 foreach ($chunks as $chunk) { 2274 if ($ishtmlchunk) { 2275 $result .= $chunk; 2276 } else { 2277 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk); 2278 } 2279 $ishtmlchunk = !$ishtmlchunk; 2280 } 2281 2282 return $result; 2283 } 2284 2285 /** 2286 * This function will highlight instances of $needle in $haystack 2287 * 2288 * It's faster that the above function {@link highlight()} and doesn't care about 2289 * HTML or anything. 2290 * 2291 * @param string $needle The string to search for 2292 * @param string $haystack The string to search for $needle in 2293 * @return string The highlighted HTML 2294 */ 2295 function highlightfast($needle, $haystack) { 2296 2297 if (empty($needle) or empty($haystack)) { 2298 return $haystack; 2299 } 2300 2301 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack)); 2302 2303 if (count($parts) === 1) { 2304 return $haystack; 2305 } 2306 2307 $pos = 0; 2308 2309 foreach ($parts as $key => $part) { 2310 $parts[$key] = substr($haystack, $pos, strlen($part)); 2311 $pos += strlen($part); 2312 2313 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>'; 2314 $pos += strlen($needle); 2315 } 2316 2317 return str_replace('<span class="highlight"></span>', '', join('', $parts)); 2318 } 2319 2320 /** 2321 * Converts a language code to hyphen-separated format in accordance to the 2322 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}. 2323 * 2324 * For additional information, check out 2325 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}. 2326 * 2327 * @param string $langcode The language code to convert. 2328 * @return string 2329 */ 2330 function get_html_lang_attribute_value(string $langcode): string { 2331 $langcode = clean_param($langcode, PARAM_LANG); 2332 if ($langcode === '') { 2333 return 'en'; 2334 } 2335 2336 // Grab language ISO code from lang config. If it differs from English, then it's been specified and we can return it. 2337 $langiso = (string) (new lang_string('iso6391', 'core_langconfig', null, $langcode)); 2338 if ($langiso !== 'en') { 2339 return $langiso; 2340 } 2341 2342 // Where we cannot determine the value from lang config, use the first two characters from the lang code. 2343 return substr($langcode, 0, 2); 2344 } 2345 2346 /** 2347 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes. 2348 * 2349 * Internationalisation, for print_header and backup/restorelib. 2350 * 2351 * @param bool $dir Default false 2352 * @return string Attributes 2353 */ 2354 function get_html_lang($dir = false) { 2355 global $CFG; 2356 2357 $currentlang = current_language(); 2358 if (isset($CFG->lang) && $currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) { 2359 // Use the default site language when the current language is not available. 2360 $currentlang = $CFG->lang; 2361 // Fix the current language. 2362 fix_current_language($currentlang); 2363 } 2364 2365 $direction = ''; 2366 if ($dir) { 2367 if (right_to_left()) { 2368 $direction = ' dir="rtl"'; 2369 } else { 2370 $direction = ' dir="ltr"'; 2371 } 2372 } 2373 2374 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag. 2375 $language = get_html_lang_attribute_value($currentlang); 2376 @header('Content-Language: '.$language); 2377 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"'); 2378 } 2379 2380 2381 // STANDARD WEB PAGE PARTS. 2382 2383 /** 2384 * Send the HTTP headers that Moodle requires. 2385 * 2386 * There is a backwards compatibility hack for legacy code 2387 * that needs to add custom IE compatibility directive. 2388 * 2389 * Example: 2390 * <code> 2391 * if (!isset($CFG->additionalhtmlhead)) { 2392 * $CFG->additionalhtmlhead = ''; 2393 * } 2394 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />'; 2395 * header('X-UA-Compatible: IE=8'); 2396 * echo $OUTPUT->header(); 2397 * </code> 2398 * 2399 * Please note the $CFG->additionalhtmlhead alone might not work, 2400 * you should send the IE compatibility header() too. 2401 * 2402 * @param string $contenttype 2403 * @param bool $cacheable Can this page be cached on back? 2404 * @return void, sends HTTP headers 2405 */ 2406 function send_headers($contenttype, $cacheable = true) { 2407 global $CFG; 2408 2409 @header('Content-Type: ' . $contenttype); 2410 @header('Content-Script-Type: text/javascript'); 2411 @header('Content-Style-Type: text/css'); 2412 2413 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) { 2414 @header('X-UA-Compatible: IE=edge'); 2415 } 2416 2417 if ($cacheable) { 2418 // Allow caching on "back" (but not on normal clicks). 2419 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform'); 2420 @header('Pragma: no-cache'); 2421 @header('Expires: '); 2422 } else { 2423 // Do everything we can to always prevent clients and proxies caching. 2424 @header('Cache-Control: no-store, no-cache, must-revalidate'); 2425 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false); 2426 @header('Pragma: no-cache'); 2427 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT'); 2428 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); 2429 } 2430 @header('Accept-Ranges: none'); 2431 2432 // The Moodle app must be allowed to embed content always. 2433 if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) { 2434 @header('X-Frame-Options: sameorigin'); 2435 } 2436 2437 // If referrer policy is set, add a referrer header. 2438 if (!empty($CFG->referrerpolicy) && ($CFG->referrerpolicy !== 'default')) { 2439 @header('Referrer-Policy: ' . $CFG->referrerpolicy); 2440 } 2441 } 2442 2443 /** 2444 * Return the right arrow with text ('next'), and optionally embedded in a link. 2445 * 2446 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases). 2447 * @param string $url An optional link to use in a surrounding HTML anchor. 2448 * @param bool $accesshide True if text should be hidden (for screen readers only). 2449 * @param string $addclass Additional class names for the link, or the arrow character. 2450 * @return string HTML string. 2451 */ 2452 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) { 2453 global $OUTPUT; // TODO: move to output renderer. 2454 $arrowclass = 'arrow '; 2455 if (!$url) { 2456 $arrowclass .= $addclass; 2457 } 2458 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->rarrow().'</span>'; 2459 $htmltext = ''; 2460 if ($text) { 2461 $htmltext = '<span class="arrow_text">'.$text.'</span> '; 2462 if ($accesshide) { 2463 $htmltext = get_accesshide($htmltext); 2464 } 2465 } 2466 if ($url) { 2467 $class = 'arrow_link'; 2468 if ($addclass) { 2469 $class .= ' '.$addclass; 2470 } 2471 2472 $linkparams = [ 2473 'class' => $class, 2474 'href' => $url, 2475 'title' => preg_replace('/<.*?>/', '', $text), 2476 ]; 2477 2478 $linkparams += $addparams; 2479 2480 return html_writer::link($url, $htmltext . $arrow, $linkparams); 2481 } 2482 return $htmltext.$arrow; 2483 } 2484 2485 /** 2486 * Return the left arrow with text ('previous'), and optionally embedded in a link. 2487 * 2488 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases). 2489 * @param string $url An optional link to use in a surrounding HTML anchor. 2490 * @param bool $accesshide True if text should be hidden (for screen readers only). 2491 * @param string $addclass Additional class names for the link, or the arrow character. 2492 * @return string HTML string. 2493 */ 2494 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) { 2495 global $OUTPUT; // TODO: move to utput renderer. 2496 $arrowclass = 'arrow '; 2497 if (! $url) { 2498 $arrowclass .= $addclass; 2499 } 2500 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->larrow().'</span>'; 2501 $htmltext = ''; 2502 if ($text) { 2503 $htmltext = ' <span class="arrow_text">'.$text.'</span>'; 2504 if ($accesshide) { 2505 $htmltext = get_accesshide($htmltext); 2506 } 2507 } 2508 if ($url) { 2509 $class = 'arrow_link'; 2510 if ($addclass) { 2511 $class .= ' '.$addclass; 2512 } 2513 2514 $linkparams = [ 2515 'class' => $class, 2516 'href' => $url, 2517 'title' => preg_replace('/<.*?>/', '', $text), 2518 ]; 2519 2520 $linkparams += $addparams; 2521 2522 return html_writer::link($url, $arrow . $htmltext, $linkparams); 2523 } 2524 return $arrow.$htmltext; 2525 } 2526 2527 /** 2528 * Return a HTML element with the class "accesshide", for accessibility. 2529 * 2530 * Please use cautiously - where possible, text should be visible! 2531 * 2532 * @param string $text Plain text. 2533 * @param string $elem Lowercase element name, default "span". 2534 * @param string $class Additional classes for the element. 2535 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'" 2536 * @return string HTML string. 2537 */ 2538 function get_accesshide($text, $elem='span', $class='', $attrs='') { 2539 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>"; 2540 } 2541 2542 /** 2543 * Return the breadcrumb trail navigation separator. 2544 * 2545 * @return string HTML string. 2546 */ 2547 function get_separator() { 2548 // Accessibility: the 'hidden' slash is preferred for screen readers. 2549 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' '; 2550 } 2551 2552 /** 2553 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region. 2554 * 2555 * If JavaScript is off, then the region will always be expanded. 2556 * 2557 * @param string $contents the contents of the box. 2558 * @param string $classes class names added to the div that is output. 2559 * @param string $id id added to the div that is output. Must not be blank. 2560 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract. 2561 * @param string $userpref the name of the user preference that stores the user's preferred default state. 2562 * (May be blank if you do not wish the state to be persisted. 2563 * @param boolean $default Initial collapsed state to use if the user_preference it not set. 2564 * @param boolean $return if true, return the HTML as a string, rather than printing it. 2565 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML. 2566 */ 2567 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) { 2568 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true); 2569 $output .= $contents; 2570 $output .= print_collapsible_region_end(true); 2571 2572 if ($return) { 2573 return $output; 2574 } else { 2575 echo $output; 2576 } 2577 } 2578 2579 /** 2580 * Print (or return) the start of a collapsible region 2581 * 2582 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region 2583 * will always be expanded. 2584 * 2585 * @param string $classes class names added to the div that is output. 2586 * @param string $id id added to the div that is output. Must not be blank. 2587 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract. 2588 * @param string $userpref the name of the user preference that stores the user's preferred default state. 2589 * (May be blank if you do not wish the state to be persisted. 2590 * @param boolean $default Initial collapsed state to use if the user_preference it not set. 2591 * @param boolean $return if true, return the HTML as a string, rather than printing it. 2592 * @param string $extracontent the extra content will show next to caption, eg.Help icon. 2593 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML. 2594 */ 2595 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false, 2596 $extracontent = null) { 2597 global $PAGE; 2598 2599 // Work out the initial state. 2600 if (!empty($userpref) and is_string($userpref)) { 2601 user_preference_allow_ajax_update($userpref, PARAM_BOOL); 2602 $collapsed = get_user_preferences($userpref, $default); 2603 } else { 2604 $collapsed = $default; 2605 $userpref = false; 2606 } 2607 2608 if ($collapsed) { 2609 $classes .= ' collapsed'; 2610 } 2611 2612 $output = ''; 2613 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">'; 2614 $output .= '<div id="' . $id . '_sizer">'; 2615 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">'; 2616 $output .= $caption . ' </div>'; 2617 if ($extracontent) { 2618 $output .= html_writer::div($extracontent, 'collapsibleregionextracontent'); 2619 } 2620 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">'; 2621 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow'))); 2622 2623 if ($return) { 2624 return $output; 2625 } else { 2626 echo $output; 2627 } 2628 } 2629 2630 /** 2631 * Close a region started with print_collapsible_region_start. 2632 * 2633 * @param boolean $return if true, return the HTML as a string, rather than printing it. 2634 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML. 2635 */ 2636 function print_collapsible_region_end($return = false) { 2637 $output = '</div></div></div>'; 2638 2639 if ($return) { 2640 return $output; 2641 } else { 2642 echo $output; 2643 } 2644 } 2645 2646 /** 2647 * Print a specified group's avatar. 2648 * 2649 * @param array|stdClass $group A single {@link group} object OR array of groups. 2650 * @param int $courseid The course ID. 2651 * @param boolean $large Default small picture, or large. 2652 * @param boolean $return If false print picture, otherwise return the output as string 2653 * @param boolean $link Enclose image in a link to view specified course? 2654 * @param boolean $includetoken Whether to use a user token when displaying this group image. 2655 * True indicates to generate a token for current user, and integer value indicates to generate a token for the 2656 * user whose id is the value indicated. 2657 * If the group picture is included in an e-mail or some other location where the audience is a specific 2658 * user who will not be logged in when viewing, then we use a token to authenticate the user. 2659 * @return string|void Depending on the setting of $return 2660 */ 2661 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) { 2662 global $CFG; 2663 2664 if (is_array($group)) { 2665 $output = ''; 2666 foreach ($group as $g) { 2667 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken); 2668 } 2669 if ($return) { 2670 return $output; 2671 } else { 2672 echo $output; 2673 return; 2674 } 2675 } 2676 2677 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken); 2678 2679 // If there is no picture, do nothing. 2680 if (!isset($pictureurl)) { 2681 return; 2682 } 2683 2684 $context = context_course::instance($courseid); 2685 2686 $groupname = s($group->name); 2687 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]); 2688 2689 $output = ''; 2690 if ($link or has_capability('moodle/site:accessallgroups', $context)) { 2691 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]); 2692 $output .= html_writer::link($linkurl, $pictureimage); 2693 } else { 2694 $output .= $pictureimage; 2695 } 2696 2697 if ($return) { 2698 return $output; 2699 } else { 2700 echo $output; 2701 } 2702 } 2703 2704 /** 2705 * Return the url to the group picture. 2706 * 2707 * @param stdClass $group A group object. 2708 * @param int $courseid The course ID for the group. 2709 * @param bool $large A large or small group picture? Default is small. 2710 * @param boolean $includetoken Whether to use a user token when displaying this group image. 2711 * True indicates to generate a token for current user, and integer value indicates to generate a token for the 2712 * user whose id is the value indicated. 2713 * If the group picture is included in an e-mail or some other location where the audience is a specific 2714 * user who will not be logged in when viewing, then we use a token to authenticate the user. 2715 * @return moodle_url Returns the url for the group picture. 2716 */ 2717 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) { 2718 global $CFG; 2719 2720 $context = context_course::instance($courseid); 2721 2722 // If there is no picture, do nothing. 2723 if (!$group->picture) { 2724 return; 2725 } 2726 2727 if ($large) { 2728 $file = 'f1'; 2729 } else { 2730 $file = 'f2'; 2731 } 2732 2733 $grouppictureurl = moodle_url::make_pluginfile_url( 2734 $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken); 2735 $grouppictureurl->param('rev', $group->picture); 2736 return $grouppictureurl; 2737 } 2738 2739 2740 /** 2741 * Display a recent activity note 2742 * 2743 * @staticvar string $strftimerecent 2744 * @param int $time A timestamp int. 2745 * @param stdClass $user A user object from the database. 2746 * @param string $text Text for display for the note 2747 * @param string $link The link to wrap around the text 2748 * @param bool $return If set to true the HTML is returned rather than echo'd 2749 * @param string $viewfullnames 2750 * @return string If $retrun was true returns HTML for a recent activity notice. 2751 */ 2752 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) { 2753 static $strftimerecent = null; 2754 $output = ''; 2755 2756 if (is_null($viewfullnames)) { 2757 $context = context_system::instance(); 2758 $viewfullnames = has_capability('moodle/site:viewfullnames', $context); 2759 } 2760 2761 if (is_null($strftimerecent)) { 2762 $strftimerecent = get_string('strftimerecent'); 2763 } 2764 2765 $output .= '<div class="head">'; 2766 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>'; 2767 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>'; 2768 $output .= '</div>'; 2769 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>'; 2770 2771 if ($return) { 2772 return $output; 2773 } else { 2774 echo $output; 2775 } 2776 } 2777 2778 /** 2779 * Returns a popup menu with course activity modules 2780 * 2781 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu 2782 * outputs a simple list structure in XHTML. 2783 * The data is taken from the serialised array stored in the course record. 2784 * 2785 * @param stdClass $course A course object. 2786 * @param array $sections 2787 * @param course_modinfo $modinfo 2788 * @param string $strsection 2789 * @param string $strjumpto 2790 * @param int $width 2791 * @param string $cmid 2792 * @return string The HTML block 2793 */ 2794 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) { 2795 2796 global $CFG, $OUTPUT; 2797 2798 $section = -1; 2799 $menu = array(); 2800 $doneheading = false; 2801 2802 $courseformatoptions = course_get_format($course)->get_format_options(); 2803 $coursecontext = context_course::instance($course->id); 2804 2805 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>'; 2806 foreach ($modinfo->cms as $mod) { 2807 if (!$mod->has_view()) { 2808 // Don't show modules which you can't link to! 2809 continue; 2810 } 2811 2812 // For course formats using 'numsections' do not show extra sections. 2813 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) { 2814 break; 2815 } 2816 2817 if (!$mod->uservisible) { // Do not icnlude empty sections at all. 2818 continue; 2819 } 2820 2821 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) { 2822 $thissection = $sections[$mod->sectionnum]; 2823 2824 if ($thissection->visible or 2825 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or 2826 has_capability('moodle/course:viewhiddensections', $coursecontext)) { 2827 $thissection->summary = strip_tags(format_string($thissection->summary, true)); 2828 if (!$doneheading) { 2829 $menu[] = '</ul></li>'; 2830 } 2831 if ($course->format == 'weeks' or empty($thissection->summary)) { 2832 $item = $strsection ." ". $mod->sectionnum; 2833 } else { 2834 if (core_text::strlen($thissection->summary) < ($width-3)) { 2835 $item = $thissection->summary; 2836 } else { 2837 $item = core_text::substr($thissection->summary, 0, $width).'...'; 2838 } 2839 } 2840 $menu[] = '<li class="section"><span>'.$item.'</span>'; 2841 $menu[] = '<ul>'; 2842 $doneheading = true; 2843 2844 $section = $mod->sectionnum; 2845 } else { 2846 // No activities from this hidden section shown. 2847 continue; 2848 } 2849 } 2850 2851 $url = $mod->modname .'/view.php?id='. $mod->id; 2852 $mod->name = strip_tags(format_string($mod->name ,true)); 2853 if (core_text::strlen($mod->name) > ($width+5)) { 2854 $mod->name = core_text::substr($mod->name, 0, $width).'...'; 2855 } 2856 if (!$mod->visible) { 2857 $mod->name = '('.$mod->name.')'; 2858 } 2859 $class = 'activity '.$mod->modname; 2860 $class .= ($cmid == $mod->id) ? ' selected' : ''; 2861 $menu[] = '<li class="'.$class.'">'. 2862 $OUTPUT->image_icon('monologo', '', $mod->modname). 2863 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>'; 2864 } 2865 2866 if ($doneheading) { 2867 $menu[] = '</ul></li>'; 2868 } 2869 $menu[] = '</ul></li></ul>'; 2870 2871 return implode("\n", $menu); 2872 } 2873 2874 /** 2875 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales. 2876 * 2877 * @todo Finish documenting this function 2878 * @todo Deprecate: this is only used in a few contrib modules 2879 * 2880 * @param int $courseid The course ID 2881 * @param string $name 2882 * @param string $current 2883 * @param boolean $includenograde Include those with no grades 2884 * @param boolean $return If set to true returns rather than echo's 2885 * @return string|bool Depending on value of $return 2886 */ 2887 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) { 2888 global $OUTPUT; 2889 2890 $output = ''; 2891 $strscale = get_string('scale'); 2892 $strscales = get_string('scales'); 2893 2894 $scales = get_scales_menu($courseid); 2895 foreach ($scales as $i => $scalename) { 2896 $grades[-$i] = $strscale .': '. $scalename; 2897 } 2898 if ($includenograde) { 2899 $grades[0] = get_string('nograde'); 2900 } 2901 for ($i=100; $i>=1; $i--) { 2902 $grades[$i] = $i; 2903 } 2904 $output .= html_writer::select($grades, $name, $current, false); 2905 2906 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>'; 2907 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1)); 2908 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500)); 2909 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales)); 2910 2911 if ($return) { 2912 return $output; 2913 } else { 2914 echo $output; 2915 } 2916 } 2917 2918 /** 2919 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts. 2920 * 2921 * Default errorcode is 1. 2922 * 2923 * Very useful for perl-like error-handling: 2924 * do_somethting() or mdie("Something went wrong"); 2925 * 2926 * @param string $msg Error message 2927 * @param integer $errorcode Error code to emit 2928 */ 2929 function mdie($msg='', $errorcode=1) { 2930 trigger_error($msg); 2931 exit($errorcode); 2932 } 2933 2934 /** 2935 * Print a message and exit. 2936 * 2937 * @param string $message The message to print in the notice 2938 * @param moodle_url|string $link The link to use for the continue button 2939 * @param object $course A course object. Unused. 2940 * @return void This function simply exits 2941 */ 2942 function notice ($message, $link='', $course=null) { 2943 global $PAGE, $OUTPUT; 2944 2945 $message = clean_text($message); // In case nasties are in here. 2946 2947 if (CLI_SCRIPT) { 2948 echo("!!$message!!\n"); 2949 exit(1); // No success. 2950 } 2951 2952 if (!$PAGE->headerprinted) { 2953 // Header not yet printed. 2954 $PAGE->set_title(get_string('notice')); 2955 echo $OUTPUT->header(); 2956 } else { 2957 echo $OUTPUT->container_end_all(false); 2958 } 2959 2960 echo $OUTPUT->box($message, 'generalbox', 'notice'); 2961 echo $OUTPUT->continue_button($link); 2962 2963 echo $OUTPUT->footer(); 2964 exit(1); // General error code. 2965 } 2966 2967 /** 2968 * Redirects the user to another page, after printing a notice. 2969 * 2970 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens. 2971 * 2972 * <strong>Good practice:</strong> You should call this method before starting page 2973 * output by using any of the OUTPUT methods. 2974 * 2975 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted! 2976 * @param string $message The message to display to the user 2977 * @param int $delay The delay before redirecting 2978 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification. 2979 * @throws moodle_exception 2980 */ 2981 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) { 2982 global $OUTPUT, $PAGE, $CFG; 2983 2984 if (CLI_SCRIPT or AJAX_SCRIPT) { 2985 // This is wrong - developers should not use redirect in these scripts but it should not be very likely. 2986 throw new moodle_exception('redirecterrordetected', 'error'); 2987 } 2988 2989 if ($delay === null) { 2990 $delay = -1; 2991 } 2992 2993 // Prevent debug errors - make sure context is properly initialised. 2994 if ($PAGE) { 2995 $PAGE->set_context(null); 2996 $PAGE->set_pagelayout('redirect'); // No header and footer needed. 2997 $PAGE->set_title(get_string('pageshouldredirect', 'moodle')); 2998 } 2999 3000 if ($url instanceof moodle_url) { 3001 $url = $url->out(false); 3002 } 3003 3004 $debugdisableredirect = false; 3005 do { 3006 if (defined('DEBUGGING_PRINTED')) { 3007 // Some debugging already printed, no need to look more. 3008 $debugdisableredirect = true; 3009 break; 3010 } 3011 3012 if (core_useragent::is_msword()) { 3013 // Clicking a URL from MS Word sends a request to the server without cookies. If that 3014 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that 3015 // was clicked is opened. Because the request from Word is without cookies, it almost 3016 // always results in a redirect to the login page, even if the user is logged in in their 3017 // browser. This is not what we want, so prevent the redirect for requests from Word. 3018 $debugdisableredirect = true; 3019 break; 3020 } 3021 3022 if (empty($CFG->debugdisplay) or empty($CFG->debug)) { 3023 // No errors should be displayed. 3024 break; 3025 } 3026 3027 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) { 3028 break; 3029 } 3030 3031 if (!($lasterror['type'] & $CFG->debug)) { 3032 // Last error not interesting. 3033 break; 3034 } 3035 3036 // Watch out here, @hidden() errors are returned from error_get_last() too. 3037 if (headers_sent()) { 3038 // We already started printing something - that means errors likely printed. 3039 $debugdisableredirect = true; 3040 break; 3041 } 3042 3043 if (ob_get_level() and ob_get_contents()) { 3044 // There is something waiting to be printed, hopefully it is the errors, 3045 // but it might be some error hidden by @ too - such as the timezone mess from setup.php. 3046 $debugdisableredirect = true; 3047 break; 3048 } 3049 } while (false); 3050 3051 // Technically, HTTP/1.1 requires Location: header to contain the absolute path. 3052 // (In practice browsers accept relative paths - but still, might as well do it properly.) 3053 // This code turns relative into absolute. 3054 if (!preg_match('|^[a-z]+:|i', $url)) { 3055 // Get host name http://www.wherever.com. 3056 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot); 3057 if (preg_match('|^/|', $url)) { 3058 // URLs beginning with / are relative to web server root so we just add them in. 3059 $url = $hostpart.$url; 3060 } else { 3061 // URLs not beginning with / are relative to path of current script, so add that on. 3062 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url; 3063 } 3064 // Replace all ..s. 3065 while (true) { 3066 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url); 3067 if ($newurl == $url) { 3068 break; 3069 } 3070 $url = $newurl; 3071 } 3072 } 3073 3074 // Sanitise url - we can not rely on moodle_url or our URL cleaning 3075 // because they do not support all valid external URLs. 3076 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url); 3077 $url = str_replace('"', '%22', $url); 3078 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url); 3079 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML)); 3080 $url = str_replace('&', '&', $encodedurl); 3081 3082 if (!empty($message)) { 3083 if (!$debugdisableredirect && !headers_sent()) { 3084 // A message has been provided, and the headers have not yet been sent. 3085 // Display the message as a notification on the subsequent page. 3086 \core\notification::add($message, $messagetype); 3087 $message = null; 3088 $delay = 0; 3089 } else { 3090 if ($delay === -1 || !is_numeric($delay)) { 3091 $delay = 3; 3092 } 3093 $message = clean_text($message); 3094 } 3095 } else { 3096 $message = get_string('pageshouldredirect'); 3097 $delay = 0; 3098 } 3099 3100 // Make sure the session is closed properly, this prevents problems in IIS 3101 // and also some potential PHP shutdown issues. 3102 \core\session\manager::write_close(); 3103 3104 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) { 3105 3106 // This helps when debugging redirect issues like loops and it is not clear 3107 // which layer in the stack sent the redirect header. If debugging is on 3108 // then the file and line is also shown. 3109 $redirectby = 'Moodle'; 3110 if (debugging('', DEBUG_DEVELOPER)) { 3111 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]; 3112 $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line']; 3113 } 3114 @header("X-Redirect-By: $redirectby"); 3115 3116 // 302 might not work for POST requests, 303 is ignored by obsolete clients. 3117 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); 3118 @header('Location: '.$url); 3119 echo bootstrap_renderer::plain_redirect_message($encodedurl); 3120 exit; 3121 } 3122 3123 // Include a redirect message, even with a HTTP redirect, because that is recommended practice. 3124 if ($PAGE) { 3125 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page. 3126 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype); 3127 exit; 3128 } else { 3129 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay); 3130 exit; 3131 } 3132 } 3133 3134 /** 3135 * Given an email address, this function will return an obfuscated version of it. 3136 * 3137 * @param string $email The email address to obfuscate 3138 * @return string The obfuscated email address 3139 */ 3140 function obfuscate_email($email) { 3141 $i = 0; 3142 $length = strlen($email); 3143 $obfuscated = ''; 3144 while ($i < $length) { 3145 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @. 3146 $obfuscated.='%'.dechex(ord($email[$i])); 3147 } else { 3148 $obfuscated.=$email[$i]; 3149 } 3150 $i++; 3151 } 3152 return $obfuscated; 3153 } 3154 3155 /** 3156 * This function takes some text and replaces about half of the characters 3157 * with HTML entity equivalents. Return string is obviously longer. 3158 * 3159 * @param string $plaintext The text to be obfuscated 3160 * @return string The obfuscated text 3161 */ 3162 function obfuscate_text($plaintext) { 3163 $i=0; 3164 $length = core_text::strlen($plaintext); 3165 $obfuscated=''; 3166 $prevobfuscated = false; 3167 while ($i < $length) { 3168 $char = core_text::substr($plaintext, $i, 1); 3169 $ord = core_text::utf8ord($char); 3170 $numerical = ($ord >= ord('0')) && ($ord <= ord('9')); 3171 if ($prevobfuscated and $numerical ) { 3172 $obfuscated.='&#'.$ord.';'; 3173 } else if (rand(0, 2)) { 3174 $obfuscated.='&#'.$ord.';'; 3175 $prevobfuscated = true; 3176 } else { 3177 $obfuscated.=$char; 3178 $prevobfuscated = false; 3179 } 3180 $i++; 3181 } 3182 return $obfuscated; 3183 } 3184 3185 /** 3186 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()} 3187 * to generate a fully obfuscated email link, ready to use. 3188 * 3189 * @param string $email The email address to display 3190 * @param string $label The text to displayed as hyperlink to $email 3191 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink 3192 * @param string $subject The subject of the email in the mailto link 3193 * @param string $body The content of the email in the mailto link 3194 * @return string The obfuscated mailto link 3195 */ 3196 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') { 3197 3198 if (empty($label)) { 3199 $label = $email; 3200 } 3201 3202 $label = obfuscate_text($label); 3203 $email = obfuscate_email($email); 3204 $mailto = obfuscate_text('mailto'); 3205 $url = new moodle_url("mailto:$email"); 3206 $attrs = array(); 3207 3208 if (!empty($subject)) { 3209 $url->param('subject', format_string($subject)); 3210 } 3211 if (!empty($body)) { 3212 $url->param('body', format_string($body)); 3213 } 3214 3215 // Use the obfuscated mailto. 3216 $url = preg_replace('/^mailto/', $mailto, $url->out()); 3217 3218 if ($dimmed) { 3219 $attrs['title'] = get_string('emaildisable'); 3220 $attrs['class'] = 'dimmed'; 3221 } 3222 3223 return html_writer::link($url, $label, $attrs); 3224 } 3225 3226 /** 3227 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI) 3228 * will transform it to html entities 3229 * 3230 * @param string $text Text to search for nolink tag in 3231 * @return string 3232 */ 3233 function rebuildnolinktag($text) { 3234 3235 $text = preg_replace('/<(\/*nolink)>/i', '<$1>', $text); 3236 3237 return $text; 3238 } 3239 3240 /** 3241 * Prints a maintenance message from $CFG->maintenance_message or default if empty. 3242 */ 3243 function print_maintenance_message() { 3244 global $CFG, $SITE, $PAGE, $OUTPUT; 3245 3246 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance'); 3247 header('Status: 503 Moodle under maintenance'); 3248 header('Retry-After: 300'); 3249 3250 $PAGE->set_pagetype('maintenance-message'); 3251 $PAGE->set_pagelayout('maintenance'); 3252 $PAGE->set_heading($SITE->fullname); 3253 echo $OUTPUT->header(); 3254 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin')); 3255 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) { 3256 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter'); 3257 echo $CFG->maintenance_message; 3258 echo $OUTPUT->box_end(); 3259 } 3260 echo $OUTPUT->footer(); 3261 die; 3262 } 3263 3264 /** 3265 * Returns a string containing a nested list, suitable for formatting into tabs with CSS. 3266 * 3267 * It is not recommended to use this function in Moodle 2.5 but it is left for backward 3268 * compartibility. 3269 * 3270 * Example how to print a single line tabs: 3271 * $rows = array( 3272 * new tabobject(...), 3273 * new tabobject(...) 3274 * ); 3275 * echo $OUTPUT->tabtree($rows, $selectedid); 3276 * 3277 * Multiple row tabs may not look good on some devices but if you want to use them 3278 * you can specify ->subtree for the active tabobject. 3279 * 3280 * @param array $tabrows An array of rows where each row is an array of tab objects 3281 * @param string $selected The id of the selected tab (whatever row it's on) 3282 * @param array $inactive An array of ids of inactive tabs that are not selectable. 3283 * @param array $activated An array of ids of other tabs that are currently activated 3284 * @param bool $return If true output is returned rather then echo'd 3285 * @return string HTML output if $return was set to true. 3286 */ 3287 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) { 3288 global $OUTPUT; 3289 3290 $tabrows = array_reverse($tabrows); 3291 $subtree = array(); 3292 foreach ($tabrows as $row) { 3293 $tree = array(); 3294 3295 foreach ($row as $tab) { 3296 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive); 3297 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated); 3298 $tab->selected = (string)$tab->id == $selected; 3299 3300 if ($tab->activated || $tab->selected) { 3301 $tab->subtree = $subtree; 3302 } 3303 $tree[] = $tab; 3304 } 3305 $subtree = $tree; 3306 } 3307 $output = $OUTPUT->tabtree($subtree); 3308 if ($return) { 3309 return $output; 3310 } else { 3311 print $output; 3312 return !empty($output); 3313 } 3314 } 3315 3316 /** 3317 * Alter debugging level for the current request, 3318 * the change is not saved in database. 3319 * 3320 * @param int $level one of the DEBUG_* constants 3321 * @param bool $debugdisplay 3322 */ 3323 function set_debugging($level, $debugdisplay = null) { 3324 global $CFG; 3325 3326 $CFG->debug = (int)$level; 3327 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER); 3328 3329 if ($debugdisplay !== null) { 3330 $CFG->debugdisplay = (bool)$debugdisplay; 3331 } 3332 } 3333 3334 /** 3335 * Standard Debugging Function 3336 * 3337 * Returns true if the current site debugging settings are equal or above specified level. 3338 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The 3339 * routing of notices is controlled by $CFG->debugdisplay 3340 * eg use like this: 3341 * 3342 * 1) debugging('a normal debug notice'); 3343 * 2) debugging('something really picky', DEBUG_ALL); 3344 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER); 3345 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) } 3346 * 3347 * In code blocks controlled by debugging() (such as example 4) 3348 * any output should be routed via debugging() itself, or the lower-level 3349 * trigger_error() or error_log(). Using echo or print will break XHTML 3350 * JS and HTTP headers. 3351 * 3352 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log. 3353 * 3354 * @param string $message a message to print 3355 * @param int $level the level at which this debugging statement should show 3356 * @param array $backtrace use different backtrace 3357 * @return bool 3358 */ 3359 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) { 3360 global $CFG, $USER; 3361 3362 $forcedebug = false; 3363 if (!empty($CFG->debugusers) && $USER) { 3364 $debugusers = explode(',', $CFG->debugusers); 3365 $forcedebug = in_array($USER->id, $debugusers); 3366 } 3367 3368 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) { 3369 return false; 3370 } 3371 3372 if (!isset($CFG->debugdisplay)) { 3373 $CFG->debugdisplay = ini_get_bool('display_errors'); 3374 } 3375 3376 if ($message) { 3377 if (!$backtrace) { 3378 $backtrace = debug_backtrace(); 3379 } 3380 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY); 3381 if (PHPUNIT_TEST) { 3382 if (phpunit_util::debugging_triggered($message, $level, $from)) { 3383 // We are inside test, the debug message was logged. 3384 return true; 3385 } 3386 } 3387 3388 if (NO_DEBUG_DISPLAY) { 3389 // Script does not want any errors or debugging in output, 3390 // we send the info to error log instead. 3391 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from); 3392 3393 } else if ($forcedebug or $CFG->debugdisplay) { 3394 if (!defined('DEBUGGING_PRINTED')) { 3395 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something. 3396 } 3397 if (CLI_SCRIPT) { 3398 echo "++ $message ++\n$from"; 3399 } else { 3400 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>'; 3401 } 3402 3403 } else { 3404 trigger_error($message . $from, E_USER_NOTICE); 3405 } 3406 } 3407 return true; 3408 } 3409 3410 /** 3411 * Outputs a HTML comment to the browser. 3412 * 3413 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks). 3414 * 3415 * <code>print_location_comment(__FILE__, __LINE__);</code> 3416 * 3417 * @param string $file 3418 * @param integer $line 3419 * @param boolean $return Whether to return or print the comment 3420 * @return string|void Void unless true given as third parameter 3421 */ 3422 function print_location_comment($file, $line, $return = false) { 3423 if ($return) { 3424 return "<!-- $file at line $line -->\n"; 3425 } else { 3426 echo "<!-- $file at line $line -->\n"; 3427 } 3428 } 3429 3430 3431 /** 3432 * Returns true if the user is using a right-to-left language. 3433 * 3434 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc) 3435 */ 3436 function right_to_left() { 3437 return (get_string('thisdirection', 'langconfig') === 'rtl'); 3438 } 3439 3440 3441 /** 3442 * Returns swapped left<=> right if in RTL environment. 3443 * 3444 * Part of RTL Moodles support. 3445 * 3446 * @param string $align align to check 3447 * @return string 3448 */ 3449 function fix_align_rtl($align) { 3450 if (!right_to_left()) { 3451 return $align; 3452 } 3453 if ($align == 'left') { 3454 return 'right'; 3455 } 3456 if ($align == 'right') { 3457 return 'left'; 3458 } 3459 return $align; 3460 } 3461 3462 3463 /** 3464 * Returns true if the page is displayed in a popup window. 3465 * 3466 * Gets the information from the URL parameter inpopup. 3467 * 3468 * @todo Use a central function to create the popup calls all over Moodle and 3469 * In the moment only works with resources and probably questions. 3470 * 3471 * @return boolean 3472 */ 3473 function is_in_popup() { 3474 $inpopup = optional_param('inpopup', '', PARAM_BOOL); 3475 3476 return ($inpopup); 3477 } 3478 3479 /** 3480 * Progress trace class. 3481 * 3482 * Use this class from long operations where you want to output occasional information about 3483 * what is going on, but don't know if, or in what format, the output should be. 3484 * 3485 * @copyright 2009 Tim Hunt 3486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3487 * @package core 3488 */ 3489 abstract class progress_trace { 3490 /** 3491 * Output an progress message in whatever format. 3492 * 3493 * @param string $message the message to output. 3494 * @param integer $depth indent depth for this message. 3495 */ 3496 abstract public function output($message, $depth = 0); 3497 3498 /** 3499 * Called when the processing is finished. 3500 */ 3501 public function finished() { 3502 } 3503 } 3504 3505 /** 3506 * This subclass of progress_trace does not ouput anything. 3507 * 3508 * @copyright 2009 Tim Hunt 3509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3510 * @package core 3511 */ 3512 class null_progress_trace extends progress_trace { 3513 /** 3514 * Does Nothing 3515 * 3516 * @param string $message 3517 * @param int $depth 3518 * @return void Does Nothing 3519 */ 3520 public function output($message, $depth = 0) { 3521 } 3522 } 3523 3524 /** 3525 * This subclass of progress_trace outputs to plain text. 3526 * 3527 * @copyright 2009 Tim Hunt 3528 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3529 * @package core 3530 */ 3531 class text_progress_trace extends progress_trace { 3532 /** 3533 * Output the trace message. 3534 * 3535 * @param string $message 3536 * @param int $depth 3537 * @return void Output is echo'd 3538 */ 3539 public function output($message, $depth = 0) { 3540 mtrace(str_repeat(' ', $depth) . $message); 3541 } 3542 } 3543 3544 /** 3545 * This subclass of progress_trace outputs as HTML. 3546 * 3547 * @copyright 2009 Tim Hunt 3548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3549 * @package core 3550 */ 3551 class html_progress_trace extends progress_trace { 3552 /** 3553 * Output the trace message. 3554 * 3555 * @param string $message 3556 * @param int $depth 3557 * @return void Output is echo'd 3558 */ 3559 public function output($message, $depth = 0) { 3560 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message, ENT_COMPAT), "</p>\n"; 3561 flush(); 3562 } 3563 } 3564 3565 /** 3566 * HTML List Progress Tree 3567 * 3568 * @copyright 2009 Tim Hunt 3569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3570 * @package core 3571 */ 3572 class html_list_progress_trace extends progress_trace { 3573 /** @var int */ 3574 protected $currentdepth = -1; 3575 3576 /** 3577 * Echo out the list 3578 * 3579 * @param string $message The message to display 3580 * @param int $depth 3581 * @return void Output is echoed 3582 */ 3583 public function output($message, $depth = 0) { 3584 $samedepth = true; 3585 while ($this->currentdepth > $depth) { 3586 echo "</li>\n</ul>\n"; 3587 $this->currentdepth -= 1; 3588 if ($this->currentdepth == $depth) { 3589 echo '<li>'; 3590 } 3591 $samedepth = false; 3592 } 3593 while ($this->currentdepth < $depth) { 3594 echo "<ul>\n<li>"; 3595 $this->currentdepth += 1; 3596 $samedepth = false; 3597 } 3598 if ($samedepth) { 3599 echo "</li>\n<li>"; 3600 } 3601 echo htmlspecialchars($message, ENT_COMPAT); 3602 flush(); 3603 } 3604 3605 /** 3606 * Called when the processing is finished. 3607 */ 3608 public function finished() { 3609 while ($this->currentdepth >= 0) { 3610 echo "</li>\n</ul>\n"; 3611 $this->currentdepth -= 1; 3612 } 3613 } 3614 } 3615 3616 /** 3617 * This subclass of progress_trace outputs to error log. 3618 * 3619 * @copyright Petr Skoda {@link http://skodak.org} 3620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3621 * @package core 3622 */ 3623 class error_log_progress_trace extends progress_trace { 3624 /** @var string log prefix */ 3625 protected $prefix; 3626 3627 /** 3628 * Constructor. 3629 * @param string $prefix optional log prefix 3630 */ 3631 public function __construct($prefix = '') { 3632 $this->prefix = $prefix; 3633 } 3634 3635 /** 3636 * Output the trace message. 3637 * 3638 * @param string $message 3639 * @param int $depth 3640 * @return void Output is sent to error log. 3641 */ 3642 public function output($message, $depth = 0) { 3643 error_log($this->prefix . str_repeat(' ', $depth) . $message); 3644 } 3645 } 3646 3647 /** 3648 * Special type of trace that can be used for catching of output of other traces. 3649 * 3650 * @copyright Petr Skoda {@link http://skodak.org} 3651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3652 * @package core 3653 */ 3654 class progress_trace_buffer extends progress_trace { 3655 /** @var progress_trace */ 3656 protected $trace; 3657 /** @var bool do we pass output out */ 3658 protected $passthrough; 3659 /** @var string output buffer */ 3660 protected $buffer; 3661 3662 /** 3663 * Constructor. 3664 * 3665 * @param progress_trace $trace 3666 * @param bool $passthrough true means output and buffer, false means just buffer and no output 3667 */ 3668 public function __construct(progress_trace $trace, $passthrough = true) { 3669 $this->trace = $trace; 3670 $this->passthrough = $passthrough; 3671 $this->buffer = ''; 3672 } 3673 3674 /** 3675 * Output the trace message. 3676 * 3677 * @param string $message the message to output. 3678 * @param int $depth indent depth for this message. 3679 * @return void output stored in buffer 3680 */ 3681 public function output($message, $depth = 0) { 3682 ob_start(); 3683 $this->trace->output($message, $depth); 3684 $this->buffer .= ob_get_contents(); 3685 if ($this->passthrough) { 3686 ob_end_flush(); 3687 } else { 3688 ob_end_clean(); 3689 } 3690 } 3691 3692 /** 3693 * Called when the processing is finished. 3694 */ 3695 public function finished() { 3696 ob_start(); 3697 $this->trace->finished(); 3698 $this->buffer .= ob_get_contents(); 3699 if ($this->passthrough) { 3700 ob_end_flush(); 3701 } else { 3702 ob_end_clean(); 3703 } 3704 } 3705 3706 /** 3707 * Reset internal text buffer. 3708 */ 3709 public function reset_buffer() { 3710 $this->buffer = ''; 3711 } 3712 3713 /** 3714 * Return internal text buffer. 3715 * @return string buffered plain text 3716 */ 3717 public function get_buffer() { 3718 return $this->buffer; 3719 } 3720 } 3721 3722 /** 3723 * Special type of trace that can be used for redirecting to multiple other traces. 3724 * 3725 * @copyright Petr Skoda {@link http://skodak.org} 3726 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3727 * @package core 3728 */ 3729 class combined_progress_trace extends progress_trace { 3730 3731 /** 3732 * An array of traces. 3733 * @var array 3734 */ 3735 protected $traces; 3736 3737 /** 3738 * Constructs a new instance. 3739 * 3740 * @param array $traces multiple traces 3741 */ 3742 public function __construct(array $traces) { 3743 $this->traces = $traces; 3744 } 3745 3746 /** 3747 * Output an progress message in whatever format. 3748 * 3749 * @param string $message the message to output. 3750 * @param integer $depth indent depth for this message. 3751 */ 3752 public function output($message, $depth = 0) { 3753 foreach ($this->traces as $trace) { 3754 $trace->output($message, $depth); 3755 } 3756 } 3757 3758 /** 3759 * Called when the processing is finished. 3760 */ 3761 public function finished() { 3762 foreach ($this->traces as $trace) { 3763 $trace->finished(); 3764 } 3765 } 3766 } 3767 3768 /** 3769 * Returns a localized sentence in the current language summarizing the current password policy 3770 * 3771 * @todo this should be handled by a function/method in the language pack library once we have a support for it 3772 * @uses $CFG 3773 * @return string 3774 */ 3775 function print_password_policy() { 3776 global $CFG; 3777 3778 $message = ''; 3779 if (!empty($CFG->passwordpolicy)) { 3780 $messages = array(); 3781 if (!empty($CFG->minpasswordlength)) { 3782 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength); 3783 } 3784 if (!empty($CFG->minpassworddigits)) { 3785 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits); 3786 } 3787 if (!empty($CFG->minpasswordlower)) { 3788 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower); 3789 } 3790 if (!empty($CFG->minpasswordupper)) { 3791 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper); 3792 } 3793 if (!empty($CFG->minpasswordnonalphanum)) { 3794 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum); 3795 } 3796 3797 // Fire any additional password policy functions from plugins. 3798 // Callbacks must return an array of message strings. 3799 $pluginsfunction = get_plugins_with_function('print_password_policy'); 3800 foreach ($pluginsfunction as $plugintype => $plugins) { 3801 foreach ($plugins as $pluginfunction) { 3802 $messages = array_merge($messages, $pluginfunction()); 3803 } 3804 } 3805 3806 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet... 3807 // Check if messages is empty before outputting any text. 3808 if ($messages != '') { 3809 $message = get_string('informpasswordpolicy', 'auth', $messages); 3810 } 3811 } 3812 return $message; 3813 } 3814 3815 /** 3816 * Get the value of a help string fully prepared for display in the current language. 3817 * 3818 * @param string $identifier The identifier of the string to search for. 3819 * @param string $component The module the string is associated with. 3820 * @param boolean $ajax Whether this help is called from an AJAX script. 3821 * This is used to influence text formatting and determines 3822 * which format to output the doclink in. 3823 * @param string|object|array $a An object, string or number that can be used 3824 * within translation strings 3825 * @return stdClass An object containing: 3826 * - heading: Any heading that there may be for this help string. 3827 * - text: The wiki-formatted help string. 3828 * - doclink: An object containing a link, the linktext, and any additional 3829 * CSS classes to apply to that link. Only present if $ajax = false. 3830 * - completedoclink: A text representation of the doclink. Only present if $ajax = true. 3831 */ 3832 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) { 3833 global $CFG, $OUTPUT; 3834 $sm = get_string_manager(); 3835 3836 // Do not rebuild caches here! 3837 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache. 3838 3839 $data = new stdClass(); 3840 3841 if ($sm->string_exists($identifier, $component)) { 3842 $data->heading = format_string(get_string($identifier, $component)); 3843 } else { 3844 // Gracefully fall back to an empty string. 3845 $data->heading = ''; 3846 } 3847 3848 if ($sm->string_exists($identifier . '_help', $component)) { 3849 $options = new stdClass(); 3850 $options->trusted = false; 3851 $options->noclean = false; 3852 $options->smiley = false; 3853 $options->filter = false; 3854 $options->para = true; 3855 $options->newlines = false; 3856 $options->overflowdiv = !$ajax; 3857 3858 // Should be simple wiki only MDL-21695. 3859 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options); 3860 3861 $helplink = $identifier . '_link'; 3862 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs. 3863 $link = get_string($helplink, $component); 3864 $linktext = get_string('morehelp'); 3865 3866 $data->doclink = new stdClass(); 3867 $url = new moodle_url(get_docs_url($link)); 3868 if ($ajax) { 3869 $data->doclink->link = $url->out(); 3870 $data->doclink->linktext = $linktext; 3871 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : ''; 3872 } else { 3873 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext), 3874 array('class' => 'helpdoclink')); 3875 } 3876 } 3877 } else { 3878 $data->text = html_writer::tag('p', 3879 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]"); 3880 } 3881 return $data; 3882 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body