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