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