PageRenderTime 37ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/mod/url/locallib.php

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