PageRenderTime 69ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/weblib.php

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