Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Private url module utility functions
  20   *
  21   * @package    mod_url
  22   * @copyright  2009 Petr Skoda  {@link http://skodak.org}
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die;
  27  
  28  require_once("$CFG->libdir/filelib.php");
  29  require_once("$CFG->libdir/resourcelib.php");
  30  require_once("$CFG->dirroot/mod/url/lib.php");
  31  
  32  /**
  33   * This methods does weak url validation, we are looking for major problems only,
  34   * no strict RFE validation.
  35   *
  36   * @param $url
  37   * @return bool true is seems valid, false if definitely not valid URL
  38   */
  39  function url_appears_valid_url($url) {
  40      if (preg_match('/^(\/|https?:|ftp:)/i', $url)) {
  41          // note: this is not exact validation, we look for severely malformed URLs only
  42          return (bool) preg_match('/^[a-z]+:\/\/([^:@\s]+:[^@\s]+@)?[^ @]+(:[0-9]+)?(\/[^#]*)?(#.*)?$/i', $url);
  43      } else {
  44          return (bool)preg_match('/^[a-z]+:\/\/...*$/i', $url);
  45      }
  46  }
  47  
  48  /**
  49   * Fix common URL problems that we want teachers to see fixed
  50   * the next time they edit the resource.
  51   *
  52   * This function does not include any XSS protection.
  53   *
  54   * @param string $url
  55   * @return string
  56   */
  57  function url_fix_submitted_url($url) {
  58      // note: empty urls are prevented in form validation
  59      $url = trim($url);
  60  
  61      // remove encoded entities - we want the raw URI here
  62      $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
  63  
  64      if (!preg_match('|^[a-z]+:|i', $url) and !preg_match('|^/|', $url)) {
  65          // invalid URI, try to fix it by making it normal URL,
  66          // please note relative urls are not allowed, /xx/yy links are ok
  67          $url = 'http://'.$url;
  68      }
  69  
  70      return $url;
  71  }
  72  
  73  /**
  74   * Return full url with all extra parameters
  75   *
  76   * This function does not include any XSS protection.
  77   *
  78   * @param string $url
  79   * @param object $cm
  80   * @param object $course
  81   * @param object $config
  82   * @return string url with & encoded as &amp;
  83   */
  84  function url_get_full_url($url, $cm, $course, $config=null) {
  85  
  86      $parameters = empty($url->parameters) ? [] : (array) unserialize_array($url->parameters);
  87  
  88      // make sure there are no encoded entities, it is ok to do this twice
  89      $fullurl = html_entity_decode($url->externalurl, ENT_QUOTES, 'UTF-8');
  90  
  91      $letters = '\pL';
  92      $latin = 'a-zA-Z';
  93      $digits = '0-9';
  94      $symbols = '\x{20E3}\x{00AE}\x{00A9}\x{203C}\x{2047}\x{2048}\x{2049}\x{3030}\x{303D}\x{2139}\x{2122}\x{3297}\x{3299}' .
  95                 '\x{2300}-\x{23FF}\x{2600}-\x{27BF}\x{2B00}-\x{2BF0}';
  96      $arabic = '\x{FE00}-\x{FEFF}';
  97      $math = '\x{2190}-\x{21FF}\x{2900}-\x{297F}';
  98      $othernumbers = '\x{2460}-\x{24FF}';
  99      $geometric = '\x{25A0}-\x{25FF}';
 100      $emojis = '\x{1F000}-\x{1F6FF}';
 101  
 102      if (preg_match('/^(\/|https?:|ftp:)/i', $fullurl) or preg_match('|^/|', $fullurl)) {
 103          // encode extra chars in URLs - this does not make it always valid, but it helps with some UTF-8 problems
 104          // Thanks to 💩.la emojis count as valid, too.
 105          $allowed = "[" . $letters . $latin . $digits . $symbols . $arabic . $math . $othernumbers . $geometric .
 106              $emojis . "]" . preg_quote(';/?:@=&$_.+!*(),-#%', '/');
 107          $fullurl = preg_replace_callback("/[^$allowed]/u", 'url_filter_callback', $fullurl);
 108      } else {
 109          // encode special chars only
 110          $fullurl = str_replace('"', '%22', $fullurl);
 111          $fullurl = str_replace('\'', '%27', $fullurl);
 112          $fullurl = str_replace(' ', '%20', $fullurl);
 113          $fullurl = str_replace('<', '%3C', $fullurl);
 114          $fullurl = str_replace('>', '%3E', $fullurl);
 115      }
 116  
 117      // add variable url parameters
 118      if (!empty($parameters)) {
 119          if (!$config) {
 120              $config = get_config('url');
 121          }
 122          $paramvalues = url_get_variable_values($url, $cm, $course, $config);
 123  
 124          foreach ($parameters as $parse=>$parameter) {
 125              if (isset($paramvalues[$parameter])) {
 126                  $parameters[$parse] = rawurlencode($parse).'='.rawurlencode($paramvalues[$parameter]);
 127              } else {
 128                  unset($parameters[$parse]);
 129              }
 130          }
 131  
 132          if (!empty($parameters)) {
 133              if (stripos($fullurl, 'teamspeak://') === 0) {
 134                  $fullurl = $fullurl.'?'.implode('?', $parameters);
 135              } else {
 136                  $join = (strpos($fullurl, '?') === false) ? '?' : '&';
 137                  $fullurl = $fullurl.$join.implode('&', $parameters);
 138              }
 139          }
 140      }
 141  
 142      // encode all & to &amp; entity
 143      $fullurl = str_replace('&', '&amp;', $fullurl);
 144  
 145      return $fullurl;
 146  }
 147  
 148  /**
 149   * Unicode encoding helper callback
 150   * @internal
 151   * @param array $matches
 152   * @return string
 153   */
 154  function url_filter_callback($matches) {
 155      return rawurlencode($matches[0]);
 156  }
 157  
 158  /**
 159   * Print url header.
 160   * @param object $url
 161   * @param object $cm
 162   * @param object $course
 163   * @return void
 164   */
 165  function url_print_header($url, $cm, $course) {
 166      global $PAGE, $OUTPUT;
 167  
 168      $PAGE->set_title($course->shortname.': '.$url->name);
 169      $PAGE->set_heading($course->fullname);
 170      $PAGE->set_activity_record($url);
 171      echo $OUTPUT->header();
 172  }
 173  
 174  /**
 175   * Print url heading.
 176   * @param object $url
 177   * @param object $cm
 178   * @param object $course
 179   * @param bool $notused This variable is no longer used.
 180   * @return void
 181   */
 182  function url_print_heading($url, $cm, $course, $notused = false) {
 183      global $OUTPUT;
 184      echo $OUTPUT->heading(format_string($url->name), 2);
 185  }
 186  
 187  /**
 188   * Print url introduction.
 189   * @param object $url
 190   * @param object $cm
 191   * @param object $course
 192   * @param bool $ignoresettings print even if not specified in modedit
 193   * @return void
 194   */
 195  function url_print_intro($url, $cm, $course, $ignoresettings=false) {
 196      global $OUTPUT;
 197  
 198      $options = empty($url->displayoptions) ? [] : (array) unserialize_array($url->displayoptions);
 199      if ($ignoresettings or !empty($options['printintro'])) {
 200          if (trim(strip_tags($url->intro))) {
 201              echo $OUTPUT->box_start('mod_introbox', 'urlintro');
 202              echo format_module_intro('url', $url, $cm->id);
 203              echo $OUTPUT->box_end();
 204          }
 205      }
 206  }
 207  
 208  /**
 209   * Display url frames.
 210   * @param object $url
 211   * @param object $cm
 212   * @param object $course
 213   * @return does not return
 214   */
 215  function url_display_frame($url, $cm, $course) {
 216      global $PAGE, $OUTPUT, $CFG;
 217  
 218      $frame = optional_param('frameset', 'main', PARAM_ALPHA);
 219  
 220      if ($frame === 'top') {
 221          $PAGE->set_pagelayout('frametop');
 222          url_print_header($url, $cm, $course);
 223          url_print_heading($url, $cm, $course);
 224          url_print_intro($url, $cm, $course);
 225          echo $OUTPUT->footer();
 226          die;
 227  
 228      } else {
 229          $config = get_config('url');
 230          $context = context_module::instance($cm->id);
 231          $exteurl = url_get_full_url($url, $cm, $course, $config);
 232          $navurl = "$CFG->wwwroot/mod/url/view.php?id=$cm->id&amp;frameset=top";
 233          $coursecontext = context_course::instance($course->id);
 234          $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
 235          $title = strip_tags($courseshortname.': '.format_string($url->name));
 236          $framesize = $config->framesize;
 237          $modulename = s(get_string('modulename','url'));
 238          $contentframetitle = s(format_string($url->name));
 239          $dir = get_string('thisdirection', 'langconfig');
 240  
 241          $extframe = <<<EOF
 242  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
 243  <html dir="$dir">
 244    <head>
 245      <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 246      <title>$title</title>
 247    </head>
 248    <frameset rows="$framesize,*">
 249      <frame src="$navurl" title="$modulename"/>
 250      <frame src="$exteurl" title="$contentframetitle"/>
 251    </frameset>
 252  </html>
 253  EOF;
 254  
 255          @header('Content-Type: text/html; charset=utf-8');
 256          echo $extframe;
 257          die;
 258      }
 259  }
 260  
 261  /**
 262   * Print url info and link.
 263   * @param object $url
 264   * @param object $cm
 265   * @param object $course
 266   * @return does not return
 267   */
 268  function url_print_workaround($url, $cm, $course) {
 269      global $OUTPUT;
 270  
 271      url_print_header($url, $cm, $course);
 272      url_print_heading($url, $cm, $course, true);
 273      url_print_intro($url, $cm, $course, true);
 274  
 275      $fullurl = url_get_full_url($url, $cm, $course);
 276  
 277      $display = url_get_final_display_type($url);
 278      if ($display == RESOURCELIB_DISPLAY_POPUP) {
 279          $jsfullurl = addslashes_js($fullurl);
 280          $options = empty($url->displayoptions) ? [] : (array) unserialize_array($url->displayoptions);
 281          $width  = empty($options['popupwidth'])  ? 620 : $options['popupwidth'];
 282          $height = empty($options['popupheight']) ? 450 : $options['popupheight'];
 283          $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes";
 284          $extra = "onclick=\"window.open('$jsfullurl', '', '$wh'); return false;\"";
 285  
 286      } else if ($display == RESOURCELIB_DISPLAY_NEW) {
 287          $extra = "onclick=\"this.target='_blank';\"";
 288  
 289      } else {
 290          $extra = '';
 291      }
 292  
 293      echo '<div class="urlworkaround">';
 294      print_string('clicktoopen', 'url', "<a href=\"$fullurl\" $extra>$fullurl</a>");
 295      echo '</div>';
 296  
 297      echo $OUTPUT->footer();
 298      die;
 299  }
 300  
 301  /**
 302   * Display embedded url file.
 303   * @param object $url
 304   * @param object $cm
 305   * @param object $course
 306   * @return does not return
 307   */
 308  function url_display_embed($url, $cm, $course) {
 309      global $CFG, $PAGE, $OUTPUT;
 310  
 311      $mimetype = resourcelib_guess_url_mimetype($url->externalurl);
 312      $fullurl  = url_get_full_url($url, $cm, $course);
 313      $title    = $url->name;
 314  
 315      $link = html_writer::tag('a', $fullurl, array('href'=>str_replace('&amp;', '&', $fullurl)));
 316      $clicktoopen = get_string('clicktoopen', 'url', $link);
 317      $moodleurl = new moodle_url($fullurl);
 318  
 319      $extension = resourcelib_get_extension($url->externalurl);
 320  
 321      $mediamanager = core_media_manager::instance($PAGE);
 322      $embedoptions = array(
 323          core_media_manager::OPTION_TRUSTED => true,
 324          core_media_manager::OPTION_BLOCK => true
 325      );
 326  
 327      if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) {  // It's an image
 328          $code = resourcelib_embed_image($fullurl, $title);
 329  
 330      } else if ($mediamanager->can_embed_url($moodleurl, $embedoptions)) {
 331          // Media (audio/video) file.
 332          $code = $mediamanager->embed_url($moodleurl, $title, 0, 0, $embedoptions);
 333  
 334      } else {
 335          // anything else - just try object tag enlarged as much as possible
 336          $code = resourcelib_embed_general($fullurl, $title, $clicktoopen, $mimetype);
 337      }
 338  
 339      url_print_header($url, $cm, $course);
 340      url_print_heading($url, $cm, $course);
 341  
 342      echo $code;
 343  
 344      url_print_intro($url, $cm, $course);
 345  
 346      echo $OUTPUT->footer();
 347      die;
 348  }
 349  
 350  /**
 351   * Decide the best display format.
 352   * @param object $url
 353   * @return int display type constant
 354   */
 355  function url_get_final_display_type($url) {
 356      global $CFG;
 357  
 358      if ($url->display != RESOURCELIB_DISPLAY_AUTO) {
 359          return $url->display;
 360      }
 361  
 362      // detect links to local moodle pages
 363      if (strpos($url->externalurl, $CFG->wwwroot) === 0) {
 364          if (strpos($url->externalurl, 'file.php') === false and strpos($url->externalurl, '.php') !== false ) {
 365              // most probably our moodle page with navigation
 366              return RESOURCELIB_DISPLAY_OPEN;
 367          }
 368      }
 369  
 370      // Binaries and other formats that are known to cause trouble for external links.
 371      static $download = ['application/zip', 'application/x-tar', 'application/g-zip',
 372                          'application/pdf', 'text/html', 'document/unknown'];
 373      static $embed    = array('image/gif', 'image/jpeg', 'image/png', 'image/svg+xml',         // images
 374                               'application/x-shockwave-flash', 'video/x-flv', 'video/x-ms-wm', // video formats
 375                               'video/quicktime', 'video/mpeg', 'video/mp4',
 376                               'audio/mp3', 'audio/x-realaudio-plugin', 'x-realaudio-plugin',   // audio formats,
 377                              );
 378  
 379      $mimetype = resourcelib_guess_url_mimetype($url->externalurl);
 380  
 381      if (in_array($mimetype, $download)) {
 382          return RESOURCELIB_DISPLAY_DOWNLOAD;
 383      }
 384      if (in_array($mimetype, $embed)) {
 385          return RESOURCELIB_DISPLAY_EMBED;
 386      }
 387  
 388      // let the browser deal with it somehow
 389      return RESOURCELIB_DISPLAY_OPEN;
 390  }
 391  
 392  /**
 393   * Get the parameters that may be appended to URL
 394   * @param object $config url module config options
 395   * @return array array describing opt groups
 396   */
 397  function url_get_variable_options($config) {
 398      global $CFG;
 399  
 400      $options = array();
 401      $options[''] = array('' => get_string('chooseavariable', 'url'));
 402  
 403      $options[get_string('course')] = array(
 404          'courseid'        => 'id',
 405          'coursefullname'  => get_string('fullnamecourse'),
 406          'courseshortname' => get_string('shortnamecourse'),
 407          'courseidnumber'  => get_string('idnumbercourse'),
 408          'coursesummary'   => get_string('summary'),
 409          'courseformat'    => get_string('format'),
 410      );
 411  
 412      $options[get_string('modulename', 'url')] = array(
 413          'urlinstance'     => 'id',
 414          'urlcmid'         => 'cmid',
 415          'urlname'         => get_string('name'),
 416          'urlidnumber'     => get_string('idnumbermod'),
 417      );
 418  
 419      $options[get_string('miscellaneous')] = array(
 420          'sitename'        => get_string('fullsitename'),
 421          'serverurl'       => get_string('serverurl', 'url'),
 422          'currenttime'     => get_string('time'),
 423          'lang'            => get_string('language'),
 424      );
 425      if (!empty($config->secretphrase)) {
 426          $options[get_string('miscellaneous')]['encryptedcode'] = get_string('encryptedcode');
 427      }
 428  
 429      $options[get_string('user')] = array(
 430          'userid'          => 'id',
 431          'userusername'    => get_string('username'),
 432          'useridnumber'    => get_string('idnumber'),
 433          'userfirstname'   => get_string('firstname'),
 434          'userlastname'    => get_string('lastname'),
 435          'userfullname'    => get_string('fullnameuser'),
 436          'useremail'       => get_string('email'),
 437          'usericq'         => get_string('icqnumber'),
 438          'userphone1'      => get_string('phone1'),
 439          'userphone2'      => get_string('phone2'),
 440          'userinstitution' => get_string('institution'),
 441          'userdepartment'  => get_string('department'),
 442          'useraddress'     => get_string('address'),
 443          'usercity'        => get_string('city'),
 444          'usertimezone'    => get_string('timezone'),
 445          'userurl'         => get_string('webpage'),
 446      );
 447  
 448      if ($config->rolesinparams) {
 449          $roles = role_fix_names(get_all_roles());
 450          $roleoptions = array();
 451          foreach ($roles as $role) {
 452              $roleoptions['course'.$role->shortname] = get_string('yourwordforx', '', $role->localname);
 453          }
 454          $options[get_string('roles')] = $roleoptions;
 455      }
 456  
 457      return $options;
 458  }
 459  
 460  /**
 461   * Get the parameter values that may be appended to URL
 462   * @param object $url module instance
 463   * @param object $cm
 464   * @param object $course
 465   * @param object $config module config options
 466   * @return array of parameter values
 467   */
 468  function url_get_variable_values($url, $cm, $course, $config) {
 469      global $USER, $CFG;
 470  
 471      $site = get_site();
 472  
 473      $coursecontext = context_course::instance($course->id);
 474  
 475      $values = array (
 476          'courseid'        => $course->id,
 477          'coursefullname'  => format_string($course->fullname, true, array('context' => $coursecontext)),
 478          'courseshortname' => format_string($course->shortname, true, array('context' => $coursecontext)),
 479          'courseidnumber'  => $course->idnumber,
 480          'coursesummary'   => $course->summary,
 481          'courseformat'    => $course->format,
 482          'lang'            => current_language(),
 483          'sitename'        => format_string($site->fullname, true, array('context' => $coursecontext)),
 484          'serverurl'       => $CFG->wwwroot,
 485          'currenttime'     => time(),
 486          'urlinstance'     => $url->id,
 487          'urlcmid'         => $cm->id,
 488          'urlname'         => format_string($url->name, true, array('context' => $coursecontext)),
 489          'urlidnumber'     => $cm->idnumber,
 490      );
 491  
 492      if (isloggedin()) {
 493          $values['userid']          = $USER->id;
 494          $values['userusername']    = $USER->username;
 495          $values['useridnumber']    = $USER->idnumber;
 496          $values['userfirstname']   = $USER->firstname;
 497          $values['userlastname']    = $USER->lastname;
 498          $values['userfullname']    = fullname($USER);
 499          $values['useremail']       = $USER->email;
 500          $values['usericq']         = $USER->icq;
 501          $values['userphone1']      = $USER->phone1;
 502          $values['userphone2']      = $USER->phone2;
 503          $values['userinstitution'] = $USER->institution;
 504          $values['userdepartment']  = $USER->department;
 505          $values['useraddress']     = $USER->address;
 506          $values['usercity']        = $USER->city;
 507          $now = new DateTime('now', core_date::get_user_timezone_object());
 508          $values['usertimezone']    = $now->getOffset() / 3600.0; // Value in hours for BC.
 509          $values['userurl']         = $USER->url;
 510      }
 511  
 512      // weak imitation of Single-Sign-On, for backwards compatibility only
 513      // NOTE: login hack is not included in 2.0 any more, new contrib auth plugin
 514      //       needs to be createed if somebody needs the old functionality!
 515      if (!empty($config->secretphrase)) {
 516          $values['encryptedcode'] = url_get_encrypted_parameter($url, $config);
 517      }
 518  
 519      //hmm, this is pretty fragile and slow, why do we need it here??
 520      if ($config->rolesinparams) {
 521          $coursecontext = context_course::instance($course->id);
 522          $roles = role_fix_names(get_all_roles($coursecontext), $coursecontext, ROLENAME_ALIAS);
 523          foreach ($roles as $role) {
 524              $values['course'.$role->shortname] = $role->localname;
 525          }
 526      }
 527  
 528      return $values;
 529  }
 530  
 531  /**
 532   * BC internal function
 533   * @param object $url
 534   * @param object $config
 535   * @return string
 536   */
 537  function url_get_encrypted_parameter($url, $config) {
 538      global $CFG;
 539  
 540      if (file_exists("$CFG->dirroot/local/externserverfile.php")) {
 541          require_once("$CFG->dirroot/local/externserverfile.php");
 542          if (function_exists('extern_server_file')) {
 543              return extern_server_file($url, $config);
 544          }
 545      }
 546      return md5(getremoteaddr().$config->secretphrase);
 547  }
 548  
 549  /**
 550   * Optimised mimetype detection from general URL
 551   * @param $fullurl
 552   * @param int $size of the icon.
 553   * @return string|null mimetype or null when the filetype is not relevant.
 554   */
 555  function url_guess_icon($fullurl, $size = null) {
 556      global $CFG;
 557      require_once("$CFG->libdir/filelib.php");
 558  
 559      if (substr_count($fullurl, '/') < 3 or substr($fullurl, -1) === '/') {
 560          // Most probably default directory - index.php, index.html, etc. Return null because
 561          // we want to use the default module icon instead of the HTML file icon.
 562          return null;
 563      }
 564  
 565      try {
 566          // There can be some cases where the url is invalid making parse_url() to return false.
 567          // That will make moodle_url class to throw an exception, so we need to catch the exception to prevent errors.
 568          $moodleurl = new moodle_url($fullurl);
 569          $fullurl = $moodleurl->out_omit_querystring();
 570      } catch (\moodle_exception $e) {
 571          // If an exception is thrown, means the url is invalid. No need to log exception.
 572          return null;
 573      }
 574  
 575      $icon = file_extension_icon($fullurl, $size);
 576      $htmlicon = file_extension_icon('.htm', $size);
 577      $unknownicon = file_extension_icon('', $size);
 578  
 579      // We do not want to return those icon types, the module icon is more appropriate.
 580      if ($icon === $unknownicon || $icon === $htmlicon) {
 581          return null;
 582      }
 583  
 584      return $icon;
 585  }