[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/lib/ -> weblib.php (source)

   1  <?php // $Id$
   2  
   3  ///////////////////////////////////////////////////////////////////////////
   4  //                                                                       //
   5  // NOTICE OF COPYRIGHT                                                   //
   6  //                                                                       //
   7  // Moodle - Modular Object-Oriented Dynamic Learning Environment         //
   8  //          http://moodle.com                                            //
   9  //                                                                       //
  10  // Copyright (C) 1999 onwards Martin Dougiamas  http://dougiamas.com     //
  11  //                                                                       //
  12  // This program is free software; you can redistribute it and/or modify  //
  13  // it under the terms of the GNU General Public License as published by  //
  14  // the Free Software Foundation; either version 2 of the License, or     //
  15  // (at your option) any later version.                                   //
  16  //                                                                       //
  17  // This program is distributed in the hope that it will be useful,       //
  18  // but WITHOUT ANY WARRANTY; without even the implied warranty of        //
  19  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
  20  // GNU General Public License for more details:                          //
  21  //                                                                       //
  22  //          http://www.gnu.org/copyleft/gpl.html                         //
  23  //                                                                       //
  24  ///////////////////////////////////////////////////////////////////////////
  25  
  26  /**
  27   * Library of functions for web output
  28   *
  29   * Library of all general-purpose Moodle PHP functions and constants
  30   * that produce HTML output
  31   *
  32   * Other main libraries:
  33   * - datalib.php - functions that access the database.
  34   * - moodlelib.php - general-purpose Moodle functions.
  35   * @author Martin Dougiamas
  36   * @version  $Id$
  37   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  38   * @package moodlecore
  39   */
  40  
  41  /// We are going to uses filterlib functions here
  42  require_once("$CFG->libdir/filterlib.php");
  43  
  44  require_once("$CFG->libdir/ajax/ajaxlib.php");
  45  
  46  /// Constants
  47  
  48  /// Define text formatting types ... eventually we can add Wiki, BBcode etc
  49  
  50  /**
  51   * Does all sorts of transformations and filtering
  52   */
  53  define('FORMAT_MOODLE',   '0');   // Does all sorts of transformations and filtering
  54  
  55  /**
  56   * Plain HTML (with some tags stripped)
  57   */
  58  define('FORMAT_HTML',     '1');   // Plain HTML (with some tags stripped)
  59  
  60  /**
  61   * Plain text (even tags are printed in full)
  62   */
  63  define('FORMAT_PLAIN',    '2');   // Plain text (even tags are printed in full)
  64  
  65  /**
  66   * Wiki-formatted text
  67   * Deprecated: left here just to note that '3' is not used (at the moment)
  68   * and to catch any latent wiki-like text (which generates an error)
  69   */
  70  define('FORMAT_WIKI',     '3');   // Wiki-formatted text
  71  
  72  /**
  73   * Markdown-formatted text http://daringfireball.net/projects/markdown/
  74   */
  75  define('FORMAT_MARKDOWN', '4');   // Markdown-formatted text http://daringfireball.net/projects/markdown/
  76  
  77  /**
  78   * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
  79   */
  80  define('TRUSTTEXT', '#####TRUSTTEXT#####');
  81  
  82  
  83  /**
  84   * Javascript related defines
  85   */
  86  define('REQUIREJS_BEFOREHEADER', 0);
  87  define('REQUIREJS_INHEADER',     1);
  88  define('REQUIREJS_AFTERHEADER',  2);
  89  
  90  /**
  91   * Allowed tags - string of html tags that can be tested against for safe html tags
  92   * @global string $ALLOWED_TAGS
  93   */
  94  global $ALLOWED_TAGS;
  95  $ALLOWED_TAGS =
  96  '<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
  97  
  98  /**
  99   * Allowed protocols - array of protocols that are safe to use in links and so on
 100   * @global string $ALLOWED_PROTOCOLS
 101   */
 102  $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
 103                             'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
 104                             'border', 'margin', 'padding', 'background', 'text-decoration');   // CSS as well to get through kses
 105  
 106  
 107  /// Functions
 108  
 109  /**
 110   * Add quotes to HTML characters
 111   *
 112   * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
 113   * This function is very similar to {@link p()}
 114   *
 115   * @param string $var the string potentially containing HTML characters
 116   * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
 117   *                true should be used to print data from forms and false for data from DB.
 118   * @return string
 119   */
 120  function s($var, $strip=false) {
 121  
 122      if ($var == '0') {  // for integer 0, boolean false, string '0'
 123          return '0';
 124      }
 125  
 126      if ($strip) {
 127          return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
 128      } else {
 129          return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
 130      }
 131  }
 132  
 133  /**
 134   * Add quotes to HTML characters
 135   *
 136   * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
 137   * This function is very similar to {@link s()}
 138   *
 139   * @param string $var the string potentially containing HTML characters
 140   * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
 141   *                true should be used to print data from forms and false for data from DB.
 142   * @return string
 143   */
 144  function p($var, $strip=false) {
 145      echo s($var, $strip);
 146  }
 147  
 148  /**
 149   * Does proper javascript quoting.
 150   * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
 151   *
 152   * @since 1.8 - 22/02/2007
 153   * @param mixed value
 154   * @return mixed quoted result
 155   */
 156  function addslashes_js($var) {
 157      if (is_string($var)) {
 158          $var = str_replace('\\', '\\\\', $var);
 159          $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
 160          $var = str_replace('</', '<\/', $var);   // XHTML compliance
 161      } else if (is_array($var)) {
 162          $var = array_map('addslashes_js', $var);
 163      } else if (is_object($var)) {
 164          $a = get_object_vars($var);
 165          foreach ($a as $key=>$value) {
 166            $a[$key] = addslashes_js($value);
 167          }
 168          $var = (object)$a;
 169      }
 170      return $var;
 171  }
 172  
 173  /**
 174   * Remove query string from url
 175   *
 176   * Takes in a URL and returns it without the querystring portion
 177   *
 178   * @param string $url the url which may have a query string attached
 179   * @return string
 180   */
 181   function strip_querystring($url) {
 182  
 183      if ($commapos = strpos($url, '?')) {
 184          return substr($url, 0, $commapos);
 185      } else {
 186          return $url;
 187      }
 188  }
 189  
 190  /**
 191   * Returns the URL of the HTTP_REFERER, less the querystring portion if required
 192   * @param boolean $stripquery if true, also removes the query part of the url.
 193   * @return string
 194   */
 195  function get_referer($stripquery=true) {
 196      if (isset($_SERVER['HTTP_REFERER'])) {
 197          if ($stripquery) {
 198              return strip_querystring($_SERVER['HTTP_REFERER']);
 199          } else {
 200              return $_SERVER['HTTP_REFERER'];
 201          }
 202      } else {
 203          return '';
 204      }
 205  }
 206  
 207  
 208  /**
 209   * Returns the name of the current script, WITH the querystring portion.
 210   * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
 211   * return different things depending on a lot of things like your OS, Web
 212   * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
 213   * <b>NOTE:</b> This function returns false if the global variables needed are not set.
 214   *
 215   * @return string
 216   */
 217   function me() {
 218  
 219      if (!empty($_SERVER['REQUEST_URI'])) {
 220          return $_SERVER['REQUEST_URI'];
 221  
 222      } else if (!empty($_SERVER['PHP_SELF'])) {
 223          if (!empty($_SERVER['QUERY_STRING'])) {
 224              return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
 225          }
 226          return $_SERVER['PHP_SELF'];
 227  
 228      } else if (!empty($_SERVER['SCRIPT_NAME'])) {
 229          if (!empty($_SERVER['QUERY_STRING'])) {
 230              return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
 231          }
 232          return $_SERVER['SCRIPT_NAME'];
 233  
 234      } else if (!empty($_SERVER['URL'])) {     // May help IIS (not well tested)
 235          if (!empty($_SERVER['QUERY_STRING'])) {
 236              return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
 237          }
 238          return $_SERVER['URL'];
 239  
 240      } else {
 241          notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
 242          return false;
 243      }
 244  }
 245  
 246  /**
 247   * Like {@link me()} but returns a full URL
 248   * @see me()
 249   * @return string
 250   */
 251  function qualified_me() {
 252  
 253      global $CFG;
 254  
 255      if (!empty($CFG->wwwroot)) {
 256          $url = parse_url($CFG->wwwroot);
 257      }
 258  
 259      if (!empty($url['host'])) {
 260          $hostname = $url['host'];
 261      } else if (!empty($_SERVER['SERVER_NAME'])) {
 262          $hostname = $_SERVER['SERVER_NAME'];
 263      } else if (!empty($_ENV['SERVER_NAME'])) {
 264          $hostname = $_ENV['SERVER_NAME'];
 265      } else if (!empty($_SERVER['HTTP_HOST'])) {
 266          $hostname = $_SERVER['HTTP_HOST'];
 267      } else if (!empty($_ENV['HTTP_HOST'])) {
 268          $hostname = $_ENV['HTTP_HOST'];
 269      } else {
 270          notify('Warning: could not find the name of this server!');
 271          return false;
 272      }
 273  
 274      if (!empty($url['port'])) {
 275          $hostname .= ':'.$url['port'];
 276      } else if (!empty($_SERVER['SERVER_PORT'])) {
 277          if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
 278              $hostname .= ':'.$_SERVER['SERVER_PORT'];
 279          }
 280      }
 281  
 282      // TODO, this does not work in the situation described in MDL-11061, but
 283      // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
 284      // the server reports.
 285      if (isset($_SERVER['HTTPS'])) {
 286          $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
 287      } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
 288          $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
 289      } else {
 290          $protocol = 'http://';
 291      }
 292  
 293      $url_prefix = $protocol.$hostname;
 294      return $url_prefix . me();
 295  }
 296  
 297  
 298  /**
 299   * Class for creating and manipulating urls.
 300   *
 301   * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
 302   */
 303  class moodle_url {
 304      var $scheme = '';// e.g. http
 305      var $host = '';
 306      var $port = '';
 307      var $user = '';
 308      var $pass = '';
 309      var $path = '';
 310      var $fragment = '';
 311      var $params = array(); //associative array of query string params
 312  
 313      /**
 314       * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
 315       *
 316       * @param string $url url default null means use this page url with no query string
 317       *                      empty string means empty url.
 318       *                      if you pass any other type of url it will be parsed into it's bits, including query string
 319       * @param array $params these params override anything in the query string where params have the same name.
 320       */
 321      function moodle_url($url = null, $params = array()){
 322          global $FULLME;
 323          if ($url !== ''){
 324              if ($url === null){
 325                  $url = strip_querystring($FULLME);
 326              }
 327              $parts = parse_url($url);
 328              if ($parts === FALSE){
 329                  error('invalidurl');
 330              }
 331              if (isset($parts['query'])){
 332                  parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
 333              }
 334              unset($parts['query']);
 335              foreach ($parts as $key => $value){
 336                  $this->$key = $value;
 337              }
 338              $this->params($params);
 339          }
 340      }
 341      /**
 342       * Add an array of params to the params for this page. The added params override existing ones if they
 343       * have the same name.
 344       *
 345       * @param array $params
 346       */
 347      function params($params){
 348          $this->params = $params + $this->params;
 349      }
 350  
 351      /**
 352       * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
 353       *
 354       * @param string $arg1
 355       * @param string $arg2
 356       * @param string $arg3
 357       */
 358      function remove_params(){
 359          if ($thisargs = func_get_args()){
 360              foreach ($thisargs as $arg){
 361                  if (isset($this->params[$arg])){
 362                      unset($this->params[$arg]);
 363                  }
 364              }
 365          } else { // no args
 366              $this->params = array();
 367          }
 368      }
 369  
 370      /**
 371       * Add a param to the params for this page. The added param overrides existing one if they
 372       * have the same name.
 373       *
 374       * @param string $paramname name
 375       * @param string $param value
 376       */
 377      function param($paramname, $param){
 378          $this->params = array($paramname => $param) + $this->params;
 379      }
 380  
 381  
 382      function get_query_string($overrideparams = array()){
 383          $arr = array();
 384          $params = $overrideparams + $this->params;
 385          foreach ($params as $key => $val){
 386             $arr[] = urlencode($key)."=".urlencode($val);
 387          }
 388          return implode($arr, "&amp;");
 389      }
 390      /**
 391       * Outputs params as hidden form elements.
 392       *
 393       * @param  array $exclude params to ignore
 394       * @param integer $indent indentation
 395       * @param array $overrideparams params to add to the output params, these
 396       * override existing ones with the same name.
 397       * @return string html for form elements.
 398       */
 399      function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
 400          $tabindent = str_repeat("\t", $indent);
 401          $str = '';
 402          $params = $overrideparams + $this->params;
 403          foreach ($params as $key => $val){
 404              if (FALSE === array_search($key, $exclude)) {
 405                  $val = s($val);
 406                  $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
 407              }
 408          }
 409          return $str;
 410      }
 411      /**
 412       * Output url
 413       *
 414       * @param boolean $noquerystring whether to output page params as a query string in the url.
 415       * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
 416       * @return string url
 417       */
 418      function out($noquerystring = false, $overrideparams = array()) {
 419          $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
 420          $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
 421          $uri .= $this->host ? $this->host : '';
 422          $uri .= $this->port ? ':'.$this->port : '';
 423          $uri .= $this->path ? $this->path : '';
 424          if (!$noquerystring){
 425              $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
 426          }
 427          $uri .= $this->fragment ? '#'.$this->fragment : '';
 428          return $uri;
 429      }
 430      /**
 431       * Output action url with sesskey
 432       *
 433       * @param boolean $noquerystring whether to output page params as a query string in the url.
 434       * @return string url
 435       */
 436      function out_action($overrideparams = array()) {
 437          $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
 438          return $this->out(false, $overrideparams);
 439      }
 440  }
 441  
 442  /**
 443   * Determine if there is data waiting to be processed from a form
 444   *
 445   * Used on most forms in Moodle to check for data
 446   * Returns the data as an object, if it's found.
 447   * This object can be used in foreach loops without
 448   * casting because it's cast to (array) automatically
 449   *
 450   * Checks that submitted POST data exists and returns it as object.
 451   *
 452   * @param string $url not used anymore
 453   * @return mixed false or object
 454   */
 455  function data_submitted($url='') {
 456  
 457      if (empty($_POST)) {
 458          return false;
 459      } else {
 460          return (object)$_POST;
 461      }
 462  }
 463  
 464  /**
 465   * Moodle replacement for php stripslashes() function,
 466   * works also for objects and arrays.
 467   *
 468   * The standard php stripslashes() removes ALL backslashes
 469   * even from strings - so  C:\temp becomes C:temp - this isn't good.
 470   * This function should work as a fairly safe replacement
 471   * to be called on quoted AND unquoted strings (to be sure)
 472   *
 473   * @param mixed something to remove unsafe slashes from
 474   * @return mixed
 475   */
 476  function stripslashes_safe($mixed) {
 477      // there is no need to remove slashes from int, float and bool types
 478      if (empty($mixed)) {
 479          //nothing to do...
 480      } else if (is_string($mixed)) {
 481          if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
 482              $mixed = str_replace("''", "'", $mixed);
 483          } else { //the rest, simple and double quotes and backslashes
 484              $mixed = str_replace("\\'", "'", $mixed);
 485              $mixed = str_replace('\\"', '"', $mixed);
 486              $mixed = str_replace('\\\\', '\\', $mixed);
 487          }
 488      } else if (is_array($mixed)) {
 489          foreach ($mixed as $key => $value) {
 490              $mixed[$key] = stripslashes_safe($value);
 491          }
 492      } else if (is_object($mixed)) {
 493          $vars = get_object_vars($mixed);
 494          foreach ($vars as $key => $value) {
 495              $mixed->$key = stripslashes_safe($value);
 496          }
 497      }
 498  
 499      return $mixed;
 500  }
 501  
 502  /**
 503   * Recursive implementation of stripslashes()
 504   *
 505   * This function will allow you to strip the slashes from a variable.
 506   * If the variable is an array or object, slashes will be stripped
 507   * from the items (or properties) it contains, even if they are arrays
 508   * or objects themselves.
 509   *
 510   * @param mixed the variable to remove slashes from
 511   * @return mixed
 512   */
 513  function stripslashes_recursive($var) {
 514      if (is_object($var)) {
 515          $new_var = new object();
 516          $properties = get_object_vars($var);
 517          foreach($properties as $property => $value) {
 518              $new_var->$property = stripslashes_recursive($value);
 519          }
 520  
 521      } else if(is_array($var)) {
 522          $new_var = array();
 523          foreach($var as $property => $value) {
 524              $new_var[$property] = stripslashes_recursive($value);
 525          }
 526  
 527      } else if(is_string($var)) {
 528          $new_var = stripslashes($var);
 529  
 530      } else {
 531          $new_var = $var;
 532      }
 533  
 534      return $new_var;
 535  }
 536  
 537  /**
 538   * Recursive implementation of addslashes()
 539   *
 540   * This function will allow you to add the slashes from a variable.
 541   * If the variable is an array or object, slashes will be added
 542   * to the items (or properties) it contains, even if they are arrays
 543   * or objects themselves.
 544   *
 545   * @param mixed the variable to add slashes from
 546   * @return mixed
 547   */
 548  function addslashes_recursive($var) {
 549      if (is_object($var)) {
 550          $new_var = new object();
 551          $properties = get_object_vars($var);
 552          foreach($properties as $property => $value) {
 553              $new_var->$property = addslashes_recursive($value);
 554          }
 555  
 556      } else if (is_array($var)) {
 557          $new_var = array();
 558          foreach($var as $property => $value) {
 559              $new_var[$property] = addslashes_recursive($value);
 560          }
 561  
 562      } else if (is_string($var)) {
 563          $new_var = addslashes($var);
 564  
 565      } else { // nulls, integers, etc.
 566          $new_var = $var;
 567      }
 568  
 569      return $new_var;
 570  }
 571  
 572  /**
 573   * Given some normal text this function will break up any
 574   * long words to a given size by inserting the given character
 575   *
 576   * It's multibyte savvy and doesn't change anything inside html tags.
 577   *
 578   * @param string $string the string to be modified
 579   * @param int $maxsize maximum length of the string to be returned
 580   * @param string $cutchar the string used to represent word breaks
 581   * @return string
 582   */
 583  function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
 584  
 585  /// Loading the textlib singleton instance. We are going to need it.
 586      $textlib = textlib_get_instance();
 587  
 588  /// First of all, save all the tags inside the text to skip them
 589      $tags = array();
 590      filter_save_tags($string,$tags);
 591  
 592  /// Process the string adding the cut when necessary
 593      $output = '';
 594      $length = $textlib->strlen($string);
 595      $wordlength = 0;
 596  
 597      for ($i=0; $i<$length; $i++) {
 598          $char = $textlib->substr($string, $i, 1);
 599          if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
 600              $wordlength = 0;
 601          } else {
 602              $wordlength++;
 603              if ($wordlength > $maxsize) {
 604                  $output .= $cutchar;
 605                  $wordlength = 0;
 606              }
 607          }
 608          $output .= $char;
 609      }
 610  
 611  /// Finally load the tags back again
 612      if (!empty($tags)) {
 613          $output = str_replace(array_keys($tags), $tags, $output);
 614      }
 615  
 616      return $output;
 617  }
 618  
 619  /**
 620   * This does a search and replace, ignoring case
 621   * This function is only used for versions of PHP older than version 5
 622   * which do not have a native version of this function.
 623   * Taken from the PHP manual, by bradhuizenga @ softhome.net
 624   *
 625   * @param string $find the string to search for
 626   * @param string $replace the string to replace $find with
 627   * @param string $string the string to search through
 628   * return string
 629   */
 630  if (!function_exists('str_ireplace')) {    /// Only exists in PHP 5
 631      function str_ireplace($find, $replace, $string) {
 632  
 633          if (!is_array($find)) {
 634              $find = array($find);
 635          }
 636  
 637          if(!is_array($replace)) {
 638              if (!is_array($find)) {
 639                  $replace = array($replace);
 640              } else {
 641                  // this will duplicate the string into an array the size of $find
 642                  $c = count($find);
 643                  $rString = $replace;
 644                  unset($replace);
 645                  for ($i = 0; $i < $c; $i++) {
 646                      $replace[$i] = $rString;
 647                  }
 648              }
 649          }
 650  
 651          foreach ($find as $fKey => $fItem) {
 652              $between = explode(strtolower($fItem),strtolower($string));
 653              $pos = 0;
 654              foreach($between as $bKey => $bItem) {
 655                  $between[$bKey] = substr($string,$pos,strlen($bItem));
 656                  $pos += strlen($bItem) + strlen($fItem);
 657              }
 658              $string = implode($replace[$fKey],$between);
 659          }
 660          return ($string);
 661      }
 662  }
 663  
 664  /**
 665   * Locate the position of a string in another string
 666   *
 667   * This function is only used for versions of PHP older than version 5
 668   * which do not have a native version of this function.
 669   * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
 670   *
 671   * @param string $haystack The string to be searched
 672   * @param string $needle The string to search for
 673   * @param int $offset The position in $haystack where the search should begin.
 674   */
 675  if (!function_exists('stripos')) {    /// Only exists in PHP 5
 676      function stripos($haystack, $needle, $offset=0) {
 677  
 678          return strpos(strtoupper($haystack), strtoupper($needle), $offset);
 679      }
 680  }
 681  
 682  /**
 683   * This function will print a button/link/etc. form element
 684   * that will work on both Javascript and non-javascript browsers.
 685   * Relies on the Javascript function openpopup in javascript.php
 686   *
 687   * All parameters default to null, only $type and $url are mandatory.
 688   *
 689   * $url must be relative to home page  eg /mod/survey/stuff.php
 690   * @param string $url Web link relative to home page
 691   * @param string $name Name to be assigned to the popup window (this is used by
 692   *   client-side scripts to "talk" to the popup window)
 693   * @param string $linkname Text to be displayed as web link
 694   * @param int $height Height to assign to popup window
 695   * @param int $width Height to assign to popup window
 696   * @param string $title Text to be displayed as popup page title
 697   * @param string $options List of additional options for popup window
 698   * @param string $return If true, return as a string, otherwise print
 699   * @param string $id id added to the element
 700   * @param string $class class added to the element
 701   * @return string
 702   * @uses $CFG
 703   */
 704  function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
 705                                    $height=400, $width=500, $title=null,
 706                                    $options=null, $return=false, $id=null, $class=null) {
 707  
 708      if (is_null($url)) {
 709          debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
 710      }
 711  
 712      global $CFG;
 713  
 714      if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
 715          $options = null;
 716      }
 717  
 718      // add some sane default options for popup windows
 719      if (!$options) {
 720          $options = 'menubar=0,location=0,scrollbars,resizable';
 721      }
 722      if ($width) {
 723          $options .= ',width='. $width;
 724      }
 725      if ($height) {
 726          $options .= ',height='. $height;
 727      }
 728      if ($id) {
 729          $id = ' id="'.$id.'" ';
 730      }
 731      if ($class) {
 732          $class = ' class="'.$class.'" ';
 733      }
 734      if ($name) {
 735          $_name = $name;
 736          if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
 737              debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
 738          }
 739      } else {
 740          $name = 'popup';
 741      }
 742  
 743      // get some default string, using the localized version of legacy defaults
 744      if (is_null($linkname) || $linkname === '') {
 745          $linkname = get_string('clickhere');
 746      }
 747      if (!$title) {
 748          $title = get_string('popupwindowname');
 749      }
 750  
 751      $fullscreen = 0; // must be passed to openpopup
 752      $element = '';
 753  
 754      switch ($type) {
 755          case 'button' :
 756              $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
 757                         "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
 758              break;
 759          case 'link' :
 760              // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
 761              if (!(strpos($url,$CFG->wwwroot) === false)) {
 762                  $url = substr($url, strlen($CFG->wwwroot));
 763              }
 764              $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
 765                         "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
 766              break;
 767          default :
 768              error('Undefined element - can\'t create popup window.');
 769              break;
 770      }
 771  
 772      if ($return) {
 773          return $element;
 774      } else {
 775          echo $element;
 776      }
 777  }
 778  
 779  /**
 780   * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
 781   *
 782   * @return string html code to display a link to a popup window.
 783   * @see element_to_popup_window()
 784   */
 785  function link_to_popup_window ($url, $name=null, $linkname=null,
 786                                 $height=400, $width=500, $title=null,
 787                                 $options=null, $return=false) {
 788  
 789      return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
 790  }
 791  
 792  /**
 793   * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
 794   *
 795   * @return string html code to display a button to a popup window.
 796   * @see element_to_popup_window()
 797   */
 798  function button_to_popup_window ($url, $name=null, $linkname=null,
 799                                   $height=400, $width=500, $title=null, $options=null, $return=false,
 800                                   $id=null, $class=null) {
 801  
 802      return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
 803  }
 804  
 805  
 806  /**
 807   * Prints a simple button to close a window
 808   * @param string $name name of the window to close
 809   * @param boolean $return whether this function should return a string or output it
 810   * @return string if $return is true, nothing otherwise
 811   */
 812  function close_window_button($name='closewindow', $return=false) {
 813      global $CFG;
 814  
 815      $output = '';
 816  
 817      $output .= '<div class="closewindow">' . "\n";
 818      $output .= '<form action="#"><div>';
 819      $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
 820      $output .= '</div></form>';
 821      $output .= '</div>' . "\n";
 822  
 823      if ($return) {
 824          return $output;
 825      } else {
 826          echo $output;
 827      }
 828  }
 829  
 830  /*
 831   * Try and close the current window immediately using Javascript
 832   * @param int $delay the delay in seconds before closing the window
 833   */
 834  function close_window($delay=0) {
 835  ?>
 836  <script type="text/javascript">
 837  //<![CDATA[
 838      function close_this_window() {
 839          self.close();
 840      }
 841      setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
 842  //]]>
 843  </script>
 844  <noscript><center>
 845  <?php print_string('pleaseclose') ?>
 846  </center></noscript>
 847  <?php
 848      die;
 849  }
 850  
 851  
 852  /**
 853   * Given an array of values, output the HTML for a select element with those options.
 854   * Normally, you only need to use the first few parameters.
 855   *
 856   * @param array $options The options to offer. An array of the form
 857   *      $options[{value}] = {text displayed for that option};
 858   * @param string $name the name of this form control, as in &lt;select name="..." ...
 859   * @param string $selected the option to select initially, default none.
 860   * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
 861   *      Set this to '' if you don't want a 'nothing is selected' option.
 862   * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
 863   * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
 864   * @param boolean $return if false (the default) the the output is printed directly, If true, the
 865   *      generated HTML is returned as a string.
 866   * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
 867   * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
 868   * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
 869   *      then a suitable one is constructed.
 870   */
 871  function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
 872                             $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
 873  
 874      if ($nothing == 'choose') {
 875          $nothing = get_string('choose') .'...';
 876      }
 877  
 878      $attributes = ($script) ? 'onchange="'. $script .'"' : '';
 879      if ($disabled) {
 880          $attributes .= ' disabled="disabled"';
 881      }
 882  
 883      if ($tabindex) {
 884          $attributes .= ' tabindex="'.$tabindex.'"';
 885      }
 886  
 887      if ($id ==='') {
 888          $id = 'menu'.$name;
 889           // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
 890          $id = str_replace('[', '', $id);
 891          $id = str_replace(']', '', $id);
 892      }
 893  
 894      $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
 895      if ($nothing) {
 896          $output .= '   <option value="'. s($nothingvalue) .'"'. "\n";
 897          if ($nothingvalue === $selected) {
 898              $output .= ' selected="selected"';
 899          }
 900          $output .= '>'. $nothing .'</option>' . "\n";
 901      }
 902      if (!empty($options)) {
 903          foreach ($options as $value => $label) {
 904              $output .= '   <option value="'. s($value) .'"';
 905              if ((string)$value == (string)$selected) {
 906                  $output .= ' selected="selected"';
 907              }
 908              if ($label === '') {
 909                  $output .= '>'. $value .'</option>' . "\n";
 910              } else {
 911                  $output .= '>'. $label .'</option>' . "\n";
 912              }
 913          }
 914      }
 915      $output .= '</select>' . "\n";
 916  
 917      if ($return) {
 918          return $output;
 919      } else {
 920          echo $output;
 921      }
 922  }
 923  
 924  /**
 925   * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
 926   * Other options like choose_from_menu.
 927   * @param string $name
 928   * @param string $selected
 929   * @param string $string (defaults to '')
 930   * @param boolean $return whether this function should return a string or output it (defaults to false)
 931   * @param boolean $disabled (defaults to false)
 932   * @param int $tabindex
 933   */
 934  function choose_from_menu_yesno($name, $selected, $script = '',
 935          $return = false, $disabled = false, $tabindex = 0) {
 936      return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
 937              $selected, '', $script, '0', $return, $disabled, $tabindex);
 938  }
 939  
 940  /**
 941   * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
 942   * including option headings with the first level.
 943   */
 944  function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
 945                                   $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
 946  
 947     if ($nothing == 'choose') {
 948          $nothing = get_string('choose') .'...';
 949      }
 950  
 951      $attributes = ($script) ? 'onchange="'. $script .'"' : '';
 952      if ($disabled) {
 953          $attributes .= ' disabled="disabled"';
 954      }
 955  
 956      if ($tabindex) {
 957          $attributes .= ' tabindex="'.$tabindex.'"';
 958      }
 959  
 960      $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
 961      if ($nothing) {
 962          $output .= '   <option value="'. $nothingvalue .'"'. "\n";
 963          if ($nothingvalue === $selected) {
 964              $output .= ' selected="selected"';
 965          }
 966          $output .= '>'. $nothing .'</option>' . "\n";
 967      }
 968      if (!empty($options)) {
 969          foreach ($options as $section => $values) {
 970  
 971              $output .= '   <optgroup label="'. s(format_string($section)) .'">'."\n";
 972              foreach ($values as $value => $label) {
 973                  $output .= '   <option value="'. format_string($value) .'"';
 974                  if ((string)$value == (string)$selected) {
 975                      $output .= ' selected="selected"';
 976                  }
 977                  if ($label === '') {
 978                      $output .= '>'. $value .'</option>' . "\n";
 979                  } else {
 980                      $output .= '>'. $label .'</option>' . "\n";
 981                  }
 982              }
 983              $output .= '   </optgroup>'."\n";
 984          }
 985      }
 986      $output .= '</select>' . "\n";
 987  
 988      if ($return) {
 989          return $output;
 990      } else {
 991          echo $output;
 992      }
 993  }
 994  
 995  
 996  /**
 997   * Given an array of values, creates a group of radio buttons to be part of a form
 998   *
 999   * @param array  $options  An array of value-label pairs for the radio group (values as keys)
1000   * @param string $name     Name of the radiogroup (unique in the form)
1001   * @param string $checked  The value that is already checked
1002   */
1003  function choose_from_radio ($options, $name, $checked='', $return=false) {
1004  
1005      static $idcounter = 0;
1006  
1007      if (!$name) {
1008          $name = 'unnamed';
1009      }
1010  
1011      $output = '<span class="radiogroup '.$name."\">\n";
1012  
1013      if (!empty($options)) {
1014          $currentradio = 0;
1015          foreach ($options as $value => $label) {
1016              $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1017              $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1018              $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1019              if ($value == $checked) {
1020                  $output .= ' checked="checked"';
1021              }
1022              if ($label === '') {
1023                  $output .= ' /> <label for="'.$htmlid.'">'.  $value .'</label></span>' .  "\n";
1024              } else {
1025                  $output .= ' /> <label for="'.$htmlid.'">'.  $label .'</label></span>' .  "\n";
1026              }
1027              $currentradio = ($currentradio + 1) % 2;
1028          }
1029      }
1030  
1031      $output .= '</span>' .  "\n";
1032  
1033      if ($return) {
1034          return $output;
1035      } else {
1036          echo $output;
1037      }
1038  }
1039  
1040  /** Display an standard html checkbox with an optional label
1041   *
1042   * @param string  $name    The name of the checkbox
1043   * @param string  $value   The valus that the checkbox will pass when checked
1044   * @param boolean $checked The flag to tell the checkbox initial state
1045   * @param string  $label   The label to be showed near the checkbox
1046   * @param string  $alt     The info to be inserted in the alt tag
1047   */
1048  function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1049  
1050      static $idcounter = 0;
1051  
1052      if (!$name) {
1053          $name = 'unnamed';
1054      }
1055  
1056      if ($alt) {
1057          $alt = strip_tags($alt);
1058      } else {
1059          $alt = 'checkbox';
1060      }
1061  
1062      if ($checked) {
1063          $strchecked = ' checked="checked"';
1064      } else {
1065          $strchecked = '';
1066      }
1067  
1068      $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1069      $output  = '<span class="checkbox '.$name."\">";
1070      $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1071      if(!empty($label)) {
1072          $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1073      }
1074      $output .= '</span>'."\n";
1075  
1076      if (empty($return)) {
1077          echo $output;
1078      } else {
1079          return $output;
1080      }
1081  
1082  }
1083  
1084  /** Display an standard html text field with an optional label
1085   *
1086   * @param string  $name    The name of the text field
1087   * @param string  $value   The value of the text field
1088   * @param string  $label   The label to be showed near the text field
1089   * @param string  $alt     The info to be inserted in the alt tag
1090   */
1091  function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1092  
1093      static $idcounter = 0;
1094  
1095      if (empty($name)) {
1096          $name = 'unnamed';
1097      }
1098  
1099      if (empty($alt)) {
1100          $alt = 'textfield';
1101      }
1102  
1103      if (!empty($maxlength)) {
1104          $maxlength = ' maxlength="'.$maxlength.'" ';
1105      }
1106  
1107      $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1108      $output  = '<span class="textfield '.$name."\">";
1109      $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1110  
1111      $output .= '</span>'."\n";
1112  
1113      if (empty($return)) {
1114          echo $output;
1115      } else {
1116          return $output;
1117      }
1118  
1119  }
1120  
1121  
1122  /**
1123   * Implements a complete little popup form
1124   *
1125   * @uses $CFG
1126   * @param string $common  The URL up to the point of the variable that changes
1127   * @param array $options  Alist of value-label pairs for the popup list
1128   * @param string $formid Id must be unique on the page (originaly $formname)
1129   * @param string $selected The option that is already selected
1130   * @param string $nothing The label for the "no choice" option
1131   * @param string $help The name of a help page if help is required
1132   * @param string $helptext The name of the label for the help button
1133   * @param boolean $return Indicates whether the function should return the text
1134   *         as a string or echo it directly to the page being rendered
1135   * @param string $targetwindow The name of the target page to open the linked page in.
1136   * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1137   * @param array $optionsextra TODO, an array?
1138   * @return string If $return is true then the entire form is returned as a string.
1139   * @todo Finish documenting this function<br>
1140   */
1141  function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1142  $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1143  
1144      global $CFG;
1145      static $go, $choose;   /// Locally cached, in case there's lots on a page
1146  
1147      if (empty($options)) {
1148          return '';
1149      }
1150  
1151      if (!isset($go)) {
1152          $go = get_string('go');
1153      }
1154  
1155      if ($nothing == 'choose') {
1156          if (!isset($choose)) {
1157              $choose = get_string('choose');
1158          }
1159          $nothing = $choose.'...';
1160      }
1161  
1162      // changed reference to document.getElementById('id_abc') instead of document.abc
1163      // MDL-7861
1164      $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1165                          ' method="get" '.
1166                           $CFG->frametarget.
1167                          ' id="'.$formid.'"'.
1168                          ' class="popupform">';
1169      if ($help) {
1170          $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1171      } else {
1172          $button = '';
1173      }
1174  
1175      if ($selectlabel) {
1176          $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1177      }
1178  
1179      //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1180      //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1181      //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1182      //so we do not fix the Opera behavior on Linux
1183      if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1184          $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1185      }
1186      //Other browser
1187      else {
1188          $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
1189      }
1190  
1191      if ($nothing != '') {
1192          $output .= "   <option value=\"javascript:void(0)\">$nothing</option>\n";
1193      }
1194  
1195      $inoptgroup = false;
1196  
1197      foreach ($options as $value => $label) {
1198  
1199          if ($label == '--') { /// we are ending previous optgroup
1200              /// Check to see if we already have a valid open optgroup
1201              /// XHTML demands that there be at least 1 option within an optgroup
1202              if ($inoptgroup and (count($optgr) > 1) ) {
1203                  $output .= implode('', $optgr);
1204                  $output .= '   </optgroup>';
1205              }
1206              $optgr = array();
1207              $inoptgroup = false;
1208              continue;
1209          } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1210  
1211              /// Check to see if we already have a valid open optgroup
1212              /// XHTML demands that there be at least 1 option within an optgroup
1213              if ($inoptgroup and (count($optgr) > 1) ) {
1214                  $output .= implode('', $optgr);
1215                  $output .= '   </optgroup>';
1216              }
1217  
1218              unset($optgr);
1219              $optgr = array();
1220  
1221              $optgr[]  = '   <optgroup label="'. s(format_string(substr($label,2))) .'">';   // Plain labels
1222  
1223              $inoptgroup = true; /// everything following will be in an optgroup
1224              continue;
1225  
1226          } else {
1227             if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1228              {
1229                  $url=sid_process_url( $common . $value );
1230              } else
1231              {
1232                  $url=$common . $value;
1233              }
1234              $optstr = '   <option value="' . $url . '"';
1235  
1236              if ($value == $selected) {
1237                  $optstr .= ' selected="selected"';
1238              }
1239  
1240              if (!empty($optionsextra[$value])) {
1241                  $optstr .= ' '.$optionsextra[$value];
1242              }
1243  
1244              if ($label) {
1245                  $optstr .= '>'. $label .'</option>' . "\n";
1246              } else {
1247                  $optstr .= '>'. $value .'</option>' . "\n";
1248              }
1249  
1250              if ($inoptgroup) {
1251                  $optgr[] = $optstr;
1252              } else {
1253                  $output .= $optstr;
1254              }
1255          }
1256  
1257      }
1258  
1259      /// catch the final group if not closed
1260      if ($inoptgroup and count($optgr) > 1) {
1261          $output .= implode('', $optgr);
1262          $output .= '    </optgroup>';
1263      }
1264  
1265      $output .= '</select>';
1266      $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1267      $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1268      $output .= '<input type="submit" value="'.$go.'" /></div>';
1269      $output .= '<script type="text/javascript">'.
1270                 "\n//<![CDATA[\n".
1271                 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1272                 "\n//]]>\n".'</script>';
1273      $output .= '</div>';
1274      $output .= '</form>';
1275  
1276      if ($return) {
1277          return $output;
1278      } else {
1279          echo $output;
1280      }
1281  }
1282  
1283  
1284  /**
1285   * Prints some red text
1286   *
1287   * @param string $error The text to be displayed in red
1288   */
1289  function formerr($error) {
1290  
1291      if (!empty($error)) {
1292          echo '<span class="error">'. $error .'</span>';
1293      }
1294  }
1295  
1296  /**
1297   * Validates an email to make sure it makes sense.
1298   *
1299   * @param string $address The email address to validate.
1300   * @return boolean
1301   */
1302  function validate_email($address) {
1303  
1304      return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1305                   '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1306                    '@'.
1307                    '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1308                    '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1309                    $address));
1310  }
1311  
1312  /**
1313   * Extracts file argument either from file parameter or PATH_INFO
1314   *
1315   * @param string $scriptname name of the calling script
1316   * @return string file path (only safe characters)
1317   */
1318  function get_file_argument($scriptname) {
1319      global $_SERVER;
1320  
1321      $relativepath = FALSE;
1322  
1323      // first try normal parameter (compatible method == no relative links!)
1324      $relativepath = optional_param('file', FALSE, PARAM_PATH);
1325      if ($relativepath === '/testslasharguments') {
1326          echo 'test -1      : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1327          die;
1328      }
1329  
1330      // then try extract file from PATH_INFO (slasharguments method)
1331      if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1332          $path_info = $_SERVER['PATH_INFO'];
1333          // check that PATH_INFO works == must not contain the script name
1334          if (!strpos($path_info, $scriptname)) {
1335              $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1336              if ($relativepath === '/testslasharguments') {
1337                  echo 'test 1      : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1338                  die;
1339              }
1340          }
1341      }
1342  
1343      // now if both fail try the old way
1344      // (for compatibility with misconfigured or older buggy php implementations)
1345      if (!$relativepath) {
1346          $arr = explode($scriptname, me());
1347          if (!empty($arr[1])) {
1348              $path_info = strip_querystring($arr[1]);
1349              $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1350              if ($relativepath === '/testslasharguments') {
1351                  echo 'test 2      : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
1352                  die;
1353              }
1354          }
1355      }
1356  
1357      return $relativepath;
1358  }
1359  
1360  /**
1361   * Searches the current environment variables for some slash arguments
1362   *
1363   * @param string $file ?
1364   * @todo Finish documenting this function
1365   */
1366  function get_slash_arguments($file='file.php') {
1367  
1368      if (!$string = me()) {
1369          return false;
1370      }
1371  
1372      $pathinfo = explode($file, $string);
1373  
1374      if (!empty($pathinfo[1])) {
1375          return addslashes($pathinfo[1]);
1376      } else {
1377          return false;
1378      }
1379  }
1380  
1381  /**
1382   * Extracts arguments from "/foo/bar/something"
1383   * eg http://mysite.com/script.php/foo/bar/something
1384   *
1385   * @param string $string ?
1386   * @param int $i ?
1387   * @return array|string
1388   * @todo Finish documenting this function
1389   */
1390  function parse_slash_arguments($string, $i=0) {
1391  
1392      if (detect_munged_arguments($string)) {
1393          return false;
1394      }
1395      $args = explode('/', $string);
1396  
1397      if ($i) {     // return just the required argument
1398          return $args[$i];
1399  
1400      } else {      // return the whole array
1401          array_shift($args);  // get rid of the empty first one
1402          return $args;
1403      }
1404  }
1405  
1406  /**
1407   * Just returns an array of text formats suitable for a popup menu
1408   *
1409   * @uses FORMAT_MOODLE
1410   * @uses FORMAT_HTML
1411   * @uses FORMAT_PLAIN
1412   * @uses FORMAT_MARKDOWN
1413   * @return array
1414   */
1415  function format_text_menu() {
1416  
1417      return array (FORMAT_MOODLE => get_string('formattext'),
1418                    FORMAT_HTML   => get_string('formathtml'),
1419                    FORMAT_PLAIN  => get_string('formatplain'),
1420                    FORMAT_MARKDOWN  => get_string('formatmarkdown'));
1421  }
1422  
1423  /**
1424   * Given text in a variety of format codings, this function returns
1425   * the text as safe HTML.
1426   *
1427   * This function should mainly be used for long strings like posts,
1428   * answers, glossary items etc. For short strings @see format_string().
1429   *
1430   * @uses $CFG
1431   * @uses FORMAT_MOODLE
1432   * @uses FORMAT_HTML
1433   * @uses FORMAT_PLAIN
1434   * @uses FORMAT_WIKI
1435   * @uses FORMAT_MARKDOWN
1436   * @param string $text The text to be formatted. This is raw text originally from user input.
1437   * @param int $format Identifier of the text format to be used
1438   *            (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1439   * @param  array $options ?
1440   * @param int $courseid ?
1441   * @return string
1442   * @todo Finish documenting this function
1443   */
1444  function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1445  
1446      global $CFG, $COURSE;
1447  
1448      static $croncache = array();
1449  
1450      if ($text === '') {
1451          return ''; // no need to do any filters and cleaning
1452      }
1453  
1454      if (!isset($options->trusttext)) {
1455          $options->trusttext = false;
1456      }
1457  
1458      if (!isset($options->noclean)) {
1459          $options->noclean=false;
1460      }
1461      if (!isset($options->nocache)) {
1462          $options->nocache=false;
1463      }
1464      if (!isset($options->smiley)) {
1465          $options->smiley=true;
1466      }
1467      if (!isset($options->filter)) {
1468          $options->filter=true;
1469      }
1470      if (!isset($options->para)) {
1471          $options->para=true;
1472      }
1473      if (!isset($options->newlines)) {
1474          $options->newlines=true;
1475      }
1476  
1477      if (empty($courseid)) {
1478          $courseid = $COURSE->id;
1479      }
1480  
1481      if (!empty($CFG->cachetext) and empty($options->nocache)) {
1482          $time = time() - $CFG->cachetext;
1483          $md5key = md5($text.'-'.(int)$courseid.'-'.current_language().'-'.(int)$format.(int)$options->trusttext.(int)$options->noclean.(int)$options->smiley.(int)$options->filter.(int)$options->para.(int)$options->newlines);
1484  
1485          if (defined('FULLME') and FULLME == 'cron') {
1486              if (isset($croncache[$md5key])) {
1487                  return $croncache[$md5key];
1488              }
1489          }
1490  
1491          if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1492              if ($oldcacheitem->timemodified >= $time) {
1493                  if (defined('FULLME') and FULLME == 'cron') {
1494                      if (count($croncache) > 150) {
1495                          reset($croncache);
1496                          $key = key($croncache);
1497                          unset($croncache[$key]);
1498                      }
1499                      $croncache[$md5key] = $oldcacheitem->formattedtext;
1500                  }
1501                  return $oldcacheitem->formattedtext;
1502              }
1503          }
1504      }
1505  
1506      // trusttext overrides the noclean option!
1507      if ($options->trusttext) {
1508          if (trusttext_present($text)) {
1509              $text = trusttext_strip($text);
1510              if (!empty($CFG->enabletrusttext)) {
1511                  $options->noclean = true;
1512              } else {
1513                  $options->noclean = false;
1514              }
1515          } else {
1516              $options->noclean = false;
1517          }
1518      } else if (!debugging('', DEBUG_DEVELOPER)) {
1519          // strip any forgotten trusttext in non-developer mode
1520          // do not forget to disable text cache when debugging trusttext!!
1521          $text = trusttext_strip($text);
1522      }
1523  
1524      $CFG->currenttextiscacheable = true;   // Default status - can be changed by any filter
1525  
1526      switch ($format) {
1527          case FORMAT_HTML:
1528              if ($options->smiley) {
1529                  replace_smilies($text);
1530              }
1531              if (!$options->noclean) {
1532                  $text = clean_text($text, FORMAT_HTML);
1533              }
1534              if ($options->filter) {
1535                  $text = filter_text($text, $courseid);
1536              }
1537              break;
1538  
1539          case FORMAT_PLAIN:
1540              $text = s($text); // cleans dangerous JS
1541              $text = rebuildnolinktag($text);
1542              $text = str_replace('  ', '&nbsp; ', $text);
1543              $text = nl2br($text);
1544              break;
1545  
1546          case FORMAT_WIKI:
1547              // this format is deprecated
1548              $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle.  You should not be seeing
1549                       this message as all texts should have been converted to Markdown format instead.
1550                       Please post a bug report to http://moodle.org/bugs with information about where you
1551                       saw this message.</p>'.s($text);
1552              break;
1553  
1554          case FORMAT_MARKDOWN:
1555              $text = markdown_to_html($text);
1556              if ($options->smiley) {
1557                  replace_smilies($text);
1558              }
1559              if (!$options->noclean) {
1560                  $text = clean_text($text, FORMAT_HTML);
1561              }
1562  
1563              if ($options->filter) {
1564                  $text = filter_text($text, $courseid);
1565              }
1566              break;
1567  
1568          default:  // FORMAT_MOODLE or anything else
1569              $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1570              if (!$options->noclean) {
1571                  $text = clean_text($text, FORMAT_HTML);
1572              }
1573  
1574              if ($options->filter) {
1575                  $text = filter_text($text, $courseid);
1576              }
1577              break;
1578      }
1579  
1580      if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1581          if (defined('FULLME') and FULLME == 'cron') {
1582              // special static cron cache - no need to store it in db if its not already there
1583              if (count($croncache) > 150) {
1584                  reset($croncache);
1585                  $key = key($croncache);
1586                  unset($croncache[$key]);
1587              }
1588              $croncache[$md5key] = $text;
1589              return $text;
1590          }
1591  
1592          $newcacheitem = new object();
1593          $newcacheitem->md5key = $md5key;
1594          $newcacheitem->formattedtext = addslashes($text);
1595          $newcacheitem->timemodified = time();
1596          if ($oldcacheitem) {                               // See bug 4677 for discussion
1597              $newcacheitem->id = $oldcacheitem->id;
1598              @update_record('cache_text', $newcacheitem);   // Update existing record in the cache table
1599                                                             // It's unlikely that the cron cache cleaner could have
1600                                                             // deleted this entry in the meantime, as it allows
1601                                                             // some extra time to cover these cases.
1602          } else {
1603              @insert_record('cache_text', $newcacheitem);   // Insert a new record in the cache table
1604                                                             // Again, it's possible that another user has caused this
1605                                                             // record to be created already in the time that it took
1606                                                             // to traverse this function.  That's OK too, as the
1607                                                             // call above handles duplicate entries, and eventually
1608                                                             // the cron cleaner will delete them.
1609          }
1610      }
1611  
1612      return $text;
1613  }
1614  
1615  /** Converts the text format from the value to the 'internal'
1616   *  name or vice versa. $key can either be the value or the name
1617   *  and you get the other back.
1618   *
1619   *  @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1620   *  @return mixed as above but the other way around!
1621   */
1622  function text_format_name( $key ) {
1623    $lookup = array();
1624    $lookup[FORMAT_MOODLE] = 'moodle';
1625    $lookup[FORMAT_HTML] = 'html';
1626    $lookup[FORMAT_PLAIN] = 'plain';
1627    $lookup[FORMAT_MARKDOWN] = 'markdown';
1628    $value = "error";
1629    if (!is_numeric($key)) {
1630      $key = strtolower( $key );
1631      $value = array_search( $key, $lookup );
1632    }
1633    else {
1634      if (isset( $lookup[$key] )) {
1635        $value =  $lookup[ $key ];
1636      }
1637    }
1638    return $value;
1639  }
1640  
1641  /**
1642   * Resets all data related to filters, called during upgrade or when filter settings change.
1643   * @return void
1644   */
1645  function reset_text_filters_cache() {
1646      global $CFG;
1647  
1648      delete_records('cache_text');
1649      $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1650      remove_dir($purifdir, true);
1651  }
1652  
1653  /** Given a simple string, this function returns the string
1654   *  processed by enabled string filters if $CFG->filterall is enabled
1655   *
1656   *  This function should be used to print short strings (non html) that
1657   *  need filter processing e.g. activity titles, post subjects,
1658   *  glossary concepts.
1659   *
1660   *  @param string  $string     The string to be filtered.
1661   *  @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1662   *  @param int     $courseid   Current course as filters can, potentially, use it
1663   *  @return string
1664   */
1665  function format_string ($string, $striplinks=true, $courseid=NULL ) {
1666  
1667      global $CFG, $COURSE;
1668  
1669      //We'll use a in-memory cache here to speed up repeated strings
1670      static $strcache = false;
1671  
1672      if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1673          $strcache = array();
1674      }
1675  
1676      //init course id
1677      if (empty($courseid)) {
1678          $courseid = $COURSE->id;
1679      }
1680  
1681      //Calculate md5
1682      $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1683  
1684      //Fetch from cache if possible
1685      if (isset($strcache[$md5])) {
1686          return $strcache[$md5];
1687      }
1688  
1689      // First replace all ampersands not followed by html entity code
1690      $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1691  
1692      if (!empty($CFG->filterall)) {
1693          $string = filter_string($string, $courseid);
1694      }
1695  
1696      // If the site requires it, strip ALL tags from this string
1697      if (!empty($CFG->formatstringstriptags)) {
1698          $string = strip_tags($string);
1699  
1700      } else {
1701          // Otherwise strip just links if that is required (default)
1702          if ($striplinks) {  //strip links in string
1703              $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1704          }
1705          $string = clean_text($string);
1706      }
1707  
1708      //Store to cache
1709      $strcache[$md5] = $string;
1710  
1711      return $string;
1712  }
1713  
1714  /**
1715   * Given text in a variety of format codings, this function returns
1716   * the text as plain text suitable for plain email.
1717   *
1718   * @uses FORMAT_MOODLE
1719   * @uses FORMAT_HTML
1720   * @uses FORMAT_PLAIN
1721   * @uses FORMAT_WIKI
1722   * @uses FORMAT_MARKDOWN
1723   * @param string $text The text to be formatted. This is raw text originally from user input.
1724   * @param int $format Identifier of the text format to be used
1725   *            (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1726   * @return string
1727   */
1728  function format_text_email($text, $format) {
1729  
1730      switch ($format) {
1731  
1732          case FORMAT_PLAIN:
1733              return $text;
1734              break;
1735  
1736          case FORMAT_WIKI:
1737              $text = wiki_to_html($text);
1738          /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1739          /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1740              $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1741              return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1742              break;
1743  
1744          case FORMAT_HTML:
1745              return html_to_text($text);
1746              break;
1747  
1748          case FORMAT_MOODLE:
1749          case FORMAT_MARKDOWN:
1750          default:
1751              $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1752              return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1753              break;
1754      }
1755  }
1756  
1757  /**
1758   * Given some text in HTML format, this function will pass it
1759   * through any filters that have been defined in $CFG->textfilterx
1760   * The variable defines a filepath to a file containing the
1761   * filter function.  The file must contain a variable called
1762   * $textfilter_function which contains the name of the function
1763   * with $courseid and $text parameters
1764   *
1765   * @param string $text The text to be passed through format filters
1766   * @param int $courseid ?
1767   * @return string
1768   * @todo Finish documenting this function
1769   */
1770  function filter_text($text, $courseid=NULL) {
1771      global $CFG, $COURSE;
1772  
1773      if (empty($courseid)) {
1774          $courseid = $COURSE->id;       // (copied from format_text)
1775      }
1776  
1777      if (!empty($CFG->textfilters)) {
1778          require_once($CFG->libdir.'/filterlib.php');
1779          $textfilters = explode(',', $CFG->textfilters);
1780          foreach ($textfilters as $textfilter) {
1781              if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1782                  include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1783                  $functionname = basename($textfilter).'_filter';
1784                  if (function_exists($functionname)) {
1785                      $text = $functionname($courseid, $text);
1786                  }
1787              }
1788          }
1789      }
1790  
1791      /// <nolink> tags removed for XHTML compatibility
1792      $text = str_replace('<nolink>', '', $text);
1793      $text = str_replace('</nolink>', '', $text);
1794  
1795      return $text;
1796  }
1797  
1798  
1799  /**
1800   * Given a string (short text) in HTML format, this function will pass it
1801   * through any filters that have been defined in $CFG->stringfilters
1802   * The variable defines a filepath to a file containing the
1803   * filter function.  The file must contain a variable called
1804   * $textfilter_function which contains the name of the function
1805   * with $courseid and $text parameters
1806   *
1807   * @param string $string The text to be passed through format filters
1808   * @param int $courseid The id of a course
1809   * @return string
1810   */
1811  function filter_string($string, $courseid=NULL) {
1812      global $CFG, $COURSE;
1813  
1814      if (empty($CFG->textfilters)) {             // All filters are disabled anyway so quit
1815          return $string;
1816      }
1817  
1818      if (empty($courseid)) {
1819          $courseid = $COURSE->id;
1820      }
1821  
1822      require_once($CFG->libdir.'/filterlib.php');
1823  
1824      if (isset($CFG->stringfilters)) {               // We have a predefined list to use, great!
1825          if (empty($CFG->stringfilters)) {                    // but it's blank, so finish now
1826              return $string;
1827          }
1828          $stringfilters = explode(',', $CFG->stringfilters);  // ..use the list we have
1829  
1830      } else {                                        // Otherwise try to derive a list from textfilters
1831          if (strpos($CFG->textfilters, 'filter/multilang') !== false) {  // Multilang is here
1832              $stringfilters = array('filter/multilang');       // Let's use just that
1833              $CFG->stringfilters = 'filter/multilang';         // Save it for next time through
1834          } else {
1835              $CFG->stringfilters = '';                         // Save the result and return
1836              return $string;
1837          }
1838      }
1839  
1840  
1841      foreach ($stringfilters as $stringfilter) {
1842          if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1843              include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1844              $functionname = basename($stringfilter).'_filter';
1845              if (function_exists($functionname)) {
1846                  $string = $functionname($courseid, $string);
1847              }
1848          }
1849      }
1850  
1851      /// <nolink> tags removed for XHTML compatibility
1852      $string = str_replace('<nolink>', '', $string);
1853      $string = str_replace('</nolink>', '', $string);
1854  
1855      return $string;
1856  }
1857  
1858  /**
1859   * Is the text marked as trusted?
1860   *
1861   * @param string $text text to be searched for TRUSTTEXT marker
1862   * @return boolean
1863   */
1864  function trusttext_present($text) {
1865      if (strpos($text, TRUSTTEXT) !== FALSE) {
1866          return true;
1867      } else {
1868          return false;
1869      }
1870  }
1871  
1872  /**
1873   * This funtion MUST be called before the cleaning or any other
1874   * function that modifies the data! We do not know the origin of trusttext
1875   * in database, if it gets there in tweaked form we must not convert it
1876   * to supported form!!!
1877   *
1878   * Please be carefull not to use stripslashes on data from database
1879   * or twice stripslashes when processing data recieved from user.
1880   *
1881   * @param string $text text that may contain TRUSTTEXT marker
1882   * @return text without any TRUSTTEXT marker
1883   */
1884  function trusttext_strip($text) {
1885      global $CFG;
1886  
1887      while (true) { //removing nested TRUSTTEXT
1888          $orig = $text;
1889          $text = str_replace(TRUSTTEXT, '', $text);
1890          if (strcmp($orig, $text) === 0) {
1891              return $text;
1892          }
1893      }
1894  }
1895  
1896  /**
1897   * Mark text as trusted, such text may contain any HTML tags because the
1898   * normal text cleaning will be bypassed.
1899   * Please make sure that the text comes from trusted user before storing
1900   * it into database!
1901   */
1902  function trusttext_mark($text) {
1903      global $CFG;
1904      if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1905          return TRUSTTEXT.$text;
1906      } else {
1907          return $text;
1908      }
1909  }
1910  function trusttext_after_edit(&$text, $context) {
1911      if (has_capability('moodle/site:trustcontent', $context)) {
1912          $text = trusttext_strip($text);
1913          $text = trusttext_mark($text);
1914      } else {
1915          $text = trusttext_strip($text);
1916      }
1917  }
1918  
1919  function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1920      global $CFG;
1921  
1922      $options = new object();
1923      $options->smiley = false;
1924      $options->filter = false;
1925      if (!empty($CFG->enabletrusttext)
1926           and has_capability('moodle/site:trustcontent', $context)
1927           and trusttext_present($text)) {
1928          $options->noclean = true;
1929      } else {
1930          $options->noclean = false;
1931      }
1932      $text = trusttext_strip($text);
1933      if ($usehtmleditor) {
1934          $text = format_text($text, $format, $options);
1935          $format = FORMAT_HTML;
1936      } else if (!$options->noclean){
1937          $text = clean_text($text, $format);
1938      }
1939  }
1940  
1941  /**
1942   * Given raw text (eg typed in by a user), this function cleans it up
1943   * and removes any nasty tags that could mess up Moodle pages.
1944   *
1945   * @uses FORMAT_MOODLE
1946   * @uses FORMAT_PLAIN
1947   * @uses ALLOWED_TAGS
1948   * @param string $text The text to be cleaned
1949   * @param int $format Identifier of the text format to be used
1950   *            (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1951   * @return string The cleaned up text
1952   */
1953  function clean_text($text, $format=FORMAT_MOODLE) {
1954  
1955      global $ALLOWED_TAGS, $CFG;
1956  
1957      if (empty($text) or is_numeric($text)) {
1958         return (string)$text;
1959      }
1960  
1961      switch ($format) {
1962          case FORMAT_PLAIN:
1963          case FORMAT_MARKDOWN:
1964              return $text;
1965  
1966          default:
1967  
1968              if (!empty($CFG->enablehtmlpurifier)) {
1969                  $text = purify_html($text);
1970              } else {
1971              /// Fix non standard entity notations
1972                  $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1973                  $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1974  
1975              /// Remove tags that are not allowed
1976                  $text = strip_tags($text, $ALLOWED_TAGS);
1977  
1978              /// Clean up embedded scripts and , using kses
1979                  $text = cleanAttributes($text);
1980  
1981              /// Again remove tags that are not allowed
1982                  $text = strip_tags($text, $ALLOWED_TAGS);
1983  
1984              }
1985  
1986          /// Remove potential script events - some extra protection for undiscovered bugs in our code
1987              $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1988              $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1989  
1990              return $text;
1991      }
1992  }
1993  
1994  /**
1995   * KSES replacement cleaning function - uses HTML Purifier.
1996   */
1997  function purify_html($text) {
1998      global $CFG;
1999  
2000      // this can not be done only once because we sometimes need to reset the cache
2001      $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
2002      $status = check_dir_exists($cachedir, true, true);
2003  
2004      static $purifier = false;
2005      if ($purifier === false) {
2006          require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
2007          $config = HTMLPurifier_Config::createDefault();
2008          $config->set('Core', 'AcceptFullDocuments', false);
2009          $config->set('Core', 'Encoding', 'UTF-8');
2010          $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2011          $config->set('Cache', 'SerializerPath', $cachedir);
2012          $config->set('URI', 'AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
2013          $config->set('Attr', 'AllowedFrameTargets', array('_blank'));
2014          $purifier = new HTMLPurifier($config);
2015      }
2016      return $purifier->purify($text);
2017  }
2018  
2019  /**
2020   * This function takes a string and examines it for HTML tags.
2021   * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2022   *  which checks for attributes and filters them for malicious content
2023   *         17/08/2004              ::          Eamon DOT Costello AT dcu DOT ie
2024   *
2025   * @param string $str The string to be examined for html tags
2026   * @return string
2027   */
2028  function cleanAttributes($str){
2029      $result = preg_replace_callback(
2030              '%(<[^>]*(>|$)|>)%m', #search for html tags
2031              "cleanAttributes2",
2032              $str
2033              );
2034      return  $result;
2035  }
2036  
2037  /**
2038   * This function takes a string with an html tag and strips out any unallowed
2039   * protocols e.g. javascript:
2040   * It calls ancillary functions in kses which are prefixed by kses
2041  *        17/08/2004              ::          Eamon DOT Costello AT dcu DOT ie
2042   *
2043   * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2044   *              element the html to be cleared
2045   * @return string
2046   */
2047  function cleanAttributes2($htmlArray){
2048  
2049      global $CFG, $ALLOWED_PROTOCOLS;
2050      require_once($CFG->libdir .'/kses.php');
2051  
2052      $htmlTag = $htmlArray[1];
2053      if (substr($htmlTag, 0, 1) != '<') {
2054          return '&gt;';  //a single character ">" detected
2055      }
2056      if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2057          return ''; // It's seriously malformed
2058      }
2059      $slash = trim($matches[1]); //trailing xhtml slash
2060      $elem = $matches[2];    //the element name
2061      $attrlist = $matches[3]; // the list of attributes as a string
2062  
2063      $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2064  
2065      $attStr = '';
2066      foreach ($attrArray as $arreach) {
2067          $arreach['name'] = strtolower($arreach['name']);
2068          if ($arreach['name'] == 'style') {
2069              $value = $arreach['value'];
2070              while (true) {
2071                  $prevvalue = $value;
2072                  $value = kses_no_null($value);
2073                  $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2074                  $value = kses_decode_entities($value);
2075                  $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2076                  $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2077                  if ($value === $prevvalue) {
2078                      $arreach['value'] = $value;
2079                      break;
2080                  }
2081              }
2082              $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
2083              $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
2084              $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2085          } else if ($arreach['name'] == 'href') {
2086              //Adobe Acrobat Reader XSS protection
2087              $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2088          }
2089          $attStr .=  ' '.$arreach['name'].'="'.$arreach['value'].'"';
2090      }
2091  
2092      $xhtml_slash = '';
2093      if (preg_match('%/\s*$%', $attrlist)) {
2094          $xhtml_slash = ' /';
2095      }
2096      return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2097  }
2098  
2099  /**
2100   * Replaces all known smileys in the text with image equivalents
2101   *
2102   * @uses $CFG
2103   * @param string $text Passed by reference. The string to search for smily strings.
2104   * @return string
2105   */
2106  function replace_smilies(&$text) {
2107  
2108      global $CFG;
2109  
2110      if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2111          return;
2112      }
2113  
2114      $lang = current_language();
2115      $emoticonstring = $CFG->emoticons;
2116      static $e = array();
2117      static $img = array();
2118      static $emoticons = null;
2119  
2120      if (is_null($emoticons)) {
2121          $emoticons = array();
2122          if ($emoticonstring) {
2123              $items = explode('{;}', $CFG->emoticons);
2124              foreach ($items as $item) {
2125                 $item = explode('{:}', $item);
2126                $emoticons[$item[0]] = $item[1];
2127              }
2128          }
2129      }
2130  
2131  
2132      if (empty($img[$lang])) {  /// After the first time this is not run again
2133          $e[$lang] = array();
2134          $img[$lang] = array();
2135          foreach ($emoticons as $emoticon => $image){
2136              $alttext = get_string($image, 'pix');
2137              $e[$lang][] = $emoticon;
2138              $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2139          }
2140      }
2141  
2142      // Exclude from transformations all the code inside <script> tags
2143      // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2144      // Based on code from glossary fiter by Williams Castillo.
2145      //       - Eloy
2146  
2147      // Detect all the <script> zones to take out
2148      $excludes = array();
2149      preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2150  
2151      // Take out all the <script> zones from text
2152      foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2153          $excludes['<+'.$key.'+>'] = $value;
2154      }
2155      if ($excludes) {
2156          $text = str_replace($excludes,array_keys($excludes),$text);
2157      }
2158  
2159  /// this is the meat of the code - this is run every time
2160      $text = str_replace($e[$lang], $img[$lang], $text);
2161  
2162      // Recover all the <script> zones to text
2163      if ($excludes) {
2164          $text = str_replace(array_keys($excludes),$excludes,$text);
2165      }
2166  }
2167  
2168  /**
2169   * Given plain text, makes it into HTML as nicely as possible.
2170   * May contain HTML tags already
2171   *
2172   * @uses $CFG
2173   * @param string $text The string to convert.
2174   * @param boolean $smiley Convert any smiley characters to smiley images?
2175   * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2176   * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2177   * @return string
2178   */
2179  
2180  function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2181  ///
2182  
2183      global $CFG;
2184  
2185  /// Remove any whitespace that may be between HTML tags
2186      $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2187  
2188  /// Remove any returns that precede or follow HTML tags
2189      $text = eregi_replace("([\n\r])<", " <", $text);
2190      $text = eregi_replace(">([\n\r])", "> ", $text);
2191  
2192      convert_urls_into_links($text);
2193  
2194  /// Make returns into HTML newlines.
2195      if ($newlines) {
2196          $text = nl2br($text);
2197      }
2198  
2199  /// Turn smileys into images.
2200      if ($smiley) {
2201          replace_smilies($text);
2202      }
2203  
2204  /// Wrap the whole thing in a paragraph tag if required
2205      if ($para) {
2206          return '<p>'.$text.'</p>';
2207      } else {
2208          return $text;
2209      }
2210  }
2211  
2212  /**
2213   * Given Markdown formatted text, make it into XHTML using external function
2214   *
2215   * @uses $CFG
2216   * @param string $text The markdown formatted text to be converted.
2217   * @return string Converted text
2218   */
2219  function markdown_to_html($text) {
2220      global $CFG;
2221  
2222      require_once($CFG->libdir .'/markdown.php');
2223  
2224      return Markdown($text);
2225  }
2226  
2227  /**
2228   * Given HTML text, make it into plain text using external function
2229   *
2230   * @uses $CFG
2231   * @param string $html The text to be converted.
2232   * @return string
2233   */
2234  function html_to_text($html) {
2235  
2236      global $CFG;
2237  
2238      require_once($CFG->libdir .'/html2text.php');
2239  
2240      $result = html2text($html);
2241  
2242      // html2text does not fix numerical entities so handle those here.
2243      $tl=textlib_get_instance();
2244      $result = $tl->entities_to_utf8($result,false);
2245  
2246      return $result;
2247  }
2248  
2249  /**
2250   * Given some text this function converts any URLs it finds into HTML links
2251   *
2252   * @param string $text Passed in by reference. The string to be searched for urls.
2253   */
2254  function convert_urls_into_links(&$text) {
2255  /// Make lone URLs into links.   eg http://moodle.com/
2256      $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2257                            "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2258  
2259  /// eg www.moodle.com
2260      $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2261                            "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2262  }
2263  
2264  /**
2265   * This function will highlight search words in a given string
2266   * It cares about HTML and will not ruin links.  It's best to use
2267   * this function after performing any conversions to HTML.
2268   * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2269   *
2270   * @param string $needle The string to search for
2271   * @param string $haystack The string to search for $needle in
2272   * @param int $case whether to do case-sensitive or insensitive matching.
2273   * @return string
2274   * @todo Finish documenting this function
2275   */
2276  function highlight($needle, $haystack, $case=0,
2277                      $left_string='<span class="highlight">', $right_string='</span>') {
2278  
2279      if (empty($needle) or empty($haystack)) {
2280          return $haystack;
2281      }
2282  
2283      //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle);  // bug 3101
2284      $list_of_words = $needle;
2285      $list_array = explode(' ', $list_of_words);
2286      for ($i=0; $i<sizeof($list_array); $i++) {
2287          if (strlen($list_array[$i]) == 1) {
2288              $list_array[$i] = '';
2289          }
2290      }
2291      $list_of_words = implode(' ', $list_array);
2292      $list_of_words_cp =