Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/lib/ -> weblib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

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