PageRenderTime 82ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/weblib.php

http://github.com/moodle/moodle
PHP | 3722 lines | 1906 code | 421 blank | 1395 comment | 423 complexity | 89b73942c37686b4da2edb59f0887bc7 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  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. }
  2022. /**
  2023. * Return the right arrow with text ('next'), and optionally embedded in a link.
  2024. *
  2025. * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
  2026. * @param string $url An optional link to use in a surrounding HTML anchor.
  2027. * @param bool $accesshide True if text should be hidden (for screen readers only).
  2028. * @param string $addclass Additional class names for the link, or the arrow character.
  2029. * @return string HTML string.
  2030. */
  2031. function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
  2032. global $OUTPUT; // TODO: move to output renderer.
  2033. $arrowclass = 'arrow ';
  2034. if (!$url) {
  2035. $arrowclass .= $addclass;
  2036. }
  2037. $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
  2038. $htmltext = '';
  2039. if ($text) {
  2040. $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
  2041. if ($accesshide) {
  2042. $htmltext = get_accesshide($htmltext);
  2043. }
  2044. }
  2045. if ($url) {
  2046. $class = 'arrow_link';
  2047. if ($addclass) {
  2048. $class .= ' '.$addclass;
  2049. }
  2050. $linkparams = [
  2051. 'class' => $class,
  2052. 'href' => $url,
  2053. 'title' => preg_replace('/<.*?>/', '', $text),
  2054. ];
  2055. $linkparams += $addparams;
  2056. return html_writer::link($url, $htmltext . $arrow, $linkparams);
  2057. }
  2058. return $htmltext.$arrow;
  2059. }
  2060. /**
  2061. * Return the left arrow with text ('previous'), and optionally embedded in a link.
  2062. *
  2063. * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
  2064. * @param string $url An optional link to use in a surrounding HTML anchor.
  2065. * @param bool $accesshide True if text should be hidden (for screen readers only).
  2066. * @param string $addclass Additional class names for the link, or the arrow character.
  2067. * @return string HTML string.
  2068. */
  2069. function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
  2070. global $OUTPUT; // TODO: move to utput renderer.
  2071. $arrowclass = 'arrow ';
  2072. if (! $url) {
  2073. $arrowclass .= $addclass;
  2074. }
  2075. $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
  2076. $htmltext = '';
  2077. if ($text) {
  2078. $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
  2079. if ($accesshide) {
  2080. $htmltext = get_accesshide($htmltext);
  2081. }
  2082. }
  2083. if ($url) {
  2084. $class = 'arrow_link';
  2085. if ($addclass) {
  2086. $class .= ' '.$addclass;
  2087. }
  2088. $linkparams = [
  2089. 'class' => $class,
  2090. 'href' => $url,
  2091. 'title' => preg_replace('/<.*?>/', '', $text),
  2092. ];
  2093. $linkparams += $addparams;
  2094. return html_writer::link($url, $arrow . $htmltext, $linkparams);
  2095. }
  2096. return $arrow.$htmltext;
  2097. }
  2098. /**
  2099. * Return a HTML element with the class "accesshide", for accessibility.
  2100. *
  2101. * Please use cautiously - where possible, text should be visible!
  2102. *
  2103. * @param string $text Plain text.
  2104. * @param string $elem Lowercase element name, default "span".
  2105. * @param string $class Additional classes for the element.
  2106. * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
  2107. * @return string HTML string.
  2108. */
  2109. function get_accesshide($text, $elem='span', $class='', $attrs='') {
  2110. return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
  2111. }
  2112. /**
  2113. * Return the breadcrumb trail navigation separator.
  2114. *
  2115. * @return string HTML string.
  2116. */
  2117. function get_separator() {
  2118. // Accessibility: the 'hidden' slash is preferred for screen readers.
  2119. return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
  2120. }
  2121. /**
  2122. * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
  2123. *
  2124. * If JavaScript is off, then the region will always be expanded.
  2125. *
  2126. * @param string $contents the contents of the box.
  2127. * @param string $classes class names added to the div that is output.
  2128. * @param string $id id added to the div that is output. Must not be blank.
  2129. * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
  2130. * @param string $userpref the name of the user preference that stores the user's preferred default state.
  2131. * (May be blank if you do not wish the state to be persisted.
  2132. * @param boolean $default Initial collapsed state to use if the user_preference it not set.
  2133. * @param boolean $return if true, return the HTML as a string, rather than printing it.
  2134. * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
  2135. */
  2136. function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
  2137. $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
  2138. $output .= $contents;
  2139. $output .= print_collapsible_region_end(true);
  2140. if ($return) {
  2141. return $output;
  2142. } else {
  2143. echo $output;
  2144. }
  2145. }
  2146. /**
  2147. * Print (or return) the start of a collapsible region
  2148. *
  2149. * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
  2150. * will always be expanded.
  2151. *
  2152. * @param string $classes class names added to the div that is output.
  2153. * @param string $id id added to the div that is output. Must not be blank.
  2154. * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
  2155. * @param string $userpref the name of the user preference that stores the user's preferred default state.
  2156. * (May be blank if you do not wish the state to be persisted.
  2157. * @param boolean $default Initial collapsed state to use if the user_preference it not set.
  2158. * @param boolean $return if true, return the HTML as a string, rather than printing it.
  2159. * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
  2160. */
  2161. function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
  2162. global $PAGE;
  2163. // Work out the initial state.
  2164. if (!empty($userpref) and is_string($userpref)) {
  2165. user_preference_allow_ajax_update($userpref, PARAM_BOOL);
  2166. $collapsed = get_user_preferences($userpref, $default);
  2167. } else {
  2168. $collapsed = $default;
  2169. $userpref = false;
  2170. }
  2171. if ($collapsed) {
  2172. $classes .= ' collapsed';
  2173. }
  2174. $output = '';
  2175. $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
  2176. $output .= '<div id="' . $id . '_sizer">';
  2177. $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
  2178. $output .= $caption . ' ';
  2179. $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
  2180. $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
  2181. if ($return) {
  2182. return $output;
  2183. } else {
  2184. echo $output;
  2185. }
  2186. }
  2187. /**
  2188. * Close a region started with print_collapsible_region_start.
  2189. *
  2190. * @param boolean $return if true, return the HTML as a string, rather than printing it.
  2191. * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
  2192. */
  2193. function print_collapsible_region_end($return = false) {
  2194. $output = '</div></div></div>';
  2195. if ($return) {
  2196. return $output;
  2197. } else {
  2198. echo $output;
  2199. }
  2200. }
  2201. /**
  2202. * Print a specified group's avatar.
  2203. *
  2204. * @param array|stdClass $group A single {@link group} object OR array of groups.
  2205. * @param int $courseid The course ID.
  2206. * @param boolean $large Default small picture, or large.
  2207. * @param boolean $return If false print picture, otherwise return the output as string
  2208. * @param boolean $link Enclose image in a link to view specified course?
  2209. * @param boolean $includetoken Whether to use a user token when displaying this group image.
  2210. * True indicates to generate a token for current user, and integer value indicates to generate a token for the
  2211. * user whose id is the value indicated.
  2212. * If the group picture is included in an e-mail or some other location where the audience is a specific
  2213. * user who will not be logged in when viewing, then we use a token to authenticate the user.
  2214. * @return string|void Depending on the setting of $return
  2215. */
  2216. function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
  2217. global $CFG;
  2218. if (is_array($group)) {
  2219. $output = '';
  2220. foreach ($group as $g) {
  2221. $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
  2222. }
  2223. if ($return) {
  2224. return $output;
  2225. } else {
  2226. echo $output;
  2227. return;
  2228. }
  2229. }
  2230. $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
  2231. // If there is no picture, do nothing.
  2232. if (!isset($pictureurl)) {
  2233. return;
  2234. }
  2235. $context = context_course::instance($courseid);
  2236. $groupname = s($group->name);
  2237. $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
  2238. $output = '';
  2239. if ($link or has_capability('moodle/site:accessallgroups', $context)) {
  2240. $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
  2241. $output .= html_writer::link($linkurl, $pictureimage);
  2242. } else {
  2243. $output .= $pictureimage;
  2244. }
  2245. if ($return) {
  2246. return $output;
  2247. } else {
  2248. echo $output;
  2249. }
  2250. }
  2251. /**
  2252. * Return the url to the group picture.
  2253. *
  2254. * @param stdClass $group A group object.
  2255. * @param int $courseid The course ID for the group.
  2256. * @param bool $large A large or small group picture? Default is small.
  2257. * @param boolean $includetoken Whether to use a user token when displaying this group image.
  2258. * True indicates to generate a token for current user, and integer value indicates to generate a token for the
  2259. * user whose id is the value indicated.
  2260. * If the group picture is included in an e-mail or some other location where the audience is a specific
  2261. * user who will not be logged in when viewing, then we use a token to authenticate the user.
  2262. * @return moodle_url Returns the url for the group picture.
  2263. */
  2264. function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
  2265. global $CFG;
  2266. $context = context_course::instance($courseid);
  2267. // If there is no picture, do nothing.
  2268. if (!$group->picture) {
  2269. return;
  2270. }
  2271. // If picture is hidden, only show to those with course:managegroups.
  2272. if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
  2273. return;
  2274. }
  2275. if ($large) {
  2276. $file = 'f1';
  2277. } else {
  2278. $file = 'f2';
  2279. }
  2280. $grouppictureurl = moodle_url::make_pluginfile_url(
  2281. $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken);
  2282. $grouppictureurl->param('rev', $group->picture);
  2283. return $grouppictureurl;
  2284. }
  2285. /**
  2286. * Display a recent activity note
  2287. *
  2288. * @staticvar string $strftimerecent
  2289. * @param int $time A timestamp int.
  2290. * @param stdClass $user A user object from the database.
  2291. * @param string $text Text for display for the note
  2292. * @param string $link The link to wrap around the text
  2293. * @param bool $return If set to true the HTML is returned rather than echo'd
  2294. * @param string $viewfullnames
  2295. * @return string If $retrun was true returns HTML for a recent activity notice.
  2296. */
  2297. function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
  2298. static $strftimerecent = null;
  2299. $output = '';
  2300. if (is_null($viewfullnames)) {
  2301. $context = context_system::instance();
  2302. $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
  2303. }
  2304. if (is_null($strftimerecent)) {
  2305. $strftimerecent = get_string('strftimerecent');
  2306. }
  2307. $output .= '<div class="head">';
  2308. $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
  2309. $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
  2310. $output .= '</div>';
  2311. $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
  2312. if ($return) {
  2313. return $output;
  2314. } else {
  2315. echo $output;
  2316. }
  2317. }
  2318. /**
  2319. * Returns a popup menu with course activity modules
  2320. *
  2321. * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
  2322. * outputs a simple list structure in XHTML.
  2323. * The data is taken from the serialised array stored in the course record.
  2324. *
  2325. * @param course $course A {@link $COURSE} object.
  2326. * @param array $sections
  2327. * @param course_modinfo $modinfo
  2328. * @param string $strsection
  2329. * @param string $strjumpto
  2330. * @param int $width
  2331. * @param string $cmid
  2332. * @return string The HTML block
  2333. */
  2334. function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
  2335. global $CFG, $OUTPUT;
  2336. $section = -1;
  2337. $menu = array();
  2338. $doneheading = false;
  2339. $courseformatoptions = course_get_format($course)->get_format_options();
  2340. $coursecontext = context_course::instance($course->id);
  2341. $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
  2342. foreach ($modinfo->cms as $mod) {
  2343. if (!$mod->has_view()) {
  2344. // Don't show modules which you can't link to!
  2345. continue;
  2346. }
  2347. // For course formats using 'numsections' do not show extra sections.
  2348. if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
  2349. break;
  2350. }
  2351. if (!$mod->uservisible) { // Do not icnlude empty sections at all.
  2352. continue;
  2353. }
  2354. if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
  2355. $thissection = $sections[$mod->sectionnum];
  2356. if ($thissection->visible or
  2357. (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
  2358. has_capability('moodle/course:viewhiddensections', $coursecontext)) {
  2359. $thissection->summary = strip_tags(format_string($thissection->summary, true));
  2360. if (!$doneheading) {
  2361. $menu[] = '</ul></li>';
  2362. }
  2363. if ($course->format == 'weeks' or empty($thissection->summary)) {
  2364. $item = $strsection ." ". $mod->sectionnum;
  2365. } else {
  2366. if (core_text::strlen($thissection->summary) < ($width-3)) {
  2367. $item = $thissection->summary;
  2368. } else {
  2369. $item = core_text::substr($thissection->summary, 0, $width).'...';
  2370. }
  2371. }
  2372. $menu[] = '<li class="section"><span>'.$item.'</span>';
  2373. $menu[] = '<ul>';
  2374. $doneheading = true;
  2375. $section = $mod->sectionnum;
  2376. } else {
  2377. // No activities from this hidden section shown.
  2378. continue;
  2379. }
  2380. }
  2381. $url = $mod->modname .'/view.php?id='. $mod->id;
  2382. $mod->name = strip_tags(format_string($mod->name ,true));
  2383. if (core_text::strlen($mod->name) > ($width+5)) {
  2384. $mod->name = core_text::substr($mod->name, 0, $width).'...';
  2385. }
  2386. if (!$mod->visible) {
  2387. $mod->name = '('.$mod->name.')';
  2388. }
  2389. $class = 'activity '.$mod->modname;
  2390. $class .= ($cmid == $mod->id) ? ' selected' : '';
  2391. $menu[] = '<li class="'.$class.'">'.
  2392. $OUTPUT->image_icon('icon', '', $mod->modname).
  2393. '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
  2394. }
  2395. if ($doneheading) {
  2396. $menu[] = '</ul></li>';
  2397. }
  2398. $menu[] = '</ul></li></ul>';
  2399. return implode("\n", $menu);
  2400. }
  2401. /**
  2402. * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
  2403. *
  2404. * @todo Finish documenting this function
  2405. * @todo Deprecate: this is only used in a few contrib modules
  2406. *
  2407. * @param int $courseid The course ID
  2408. * @param string $name
  2409. * @param string $current
  2410. * @param boolean $includenograde Include those with no grades
  2411. * @param boolean $return If set to true returns rather than echo's
  2412. * @return string|bool Depending on value of $return
  2413. */
  2414. function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
  2415. global $OUTPUT;
  2416. $output = '';
  2417. $strscale = get_string('scale');
  2418. $strscales = get_string('scales');
  2419. $scales = get_scales_menu($courseid);
  2420. foreach ($scales as $i => $scalename) {
  2421. $grades[-$i] = $strscale .': '. $scalename;
  2422. }
  2423. if ($includenograde) {
  2424. $grades[0] = get_string('nograde');
  2425. }
  2426. for ($i=100; $i>=1; $i--) {
  2427. $grades[$i] = $i;
  2428. }
  2429. $output .= html_writer::select($grades, $name, $current, false);
  2430. $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
  2431. $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
  2432. $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
  2433. $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
  2434. if ($return) {
  2435. return $output;
  2436. } else {
  2437. echo $output;
  2438. }
  2439. }
  2440. /**
  2441. * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
  2442. *
  2443. * Default errorcode is 1.
  2444. *
  2445. * Very useful for perl-like error-handling:
  2446. * do_somethting() or mdie("Something went wrong");
  2447. *
  2448. * @param string $msg Error message
  2449. * @param integer $errorcode Error code to emit
  2450. */
  2451. function mdie($msg='', $errorcode=1) {
  2452. trigger_error($msg);
  2453. exit($errorcode);
  2454. }
  2455. /**
  2456. * Print a message and exit.
  2457. *
  2458. * @param string $message The message to print in the notice
  2459. * @param moodle_url|string $link The link to use for the continue button
  2460. * @param object $course A course object. Unused.
  2461. * @return void This function simply exits
  2462. */
  2463. function notice ($message, $link='', $course=null) {
  2464. global $PAGE, $OUTPUT;
  2465. $message = clean_text($message); // In case nasties are in here.
  2466. if (CLI_SCRIPT) {
  2467. echo("!!$message!!\n");
  2468. exit(1); // No success.
  2469. }
  2470. if (!$PAGE->headerprinted) {
  2471. // Header not yet printed.
  2472. $PAGE->set_title(get_string('notice'));
  2473. echo $OUTPUT->header();
  2474. } else {
  2475. echo $OUTPUT->container_end_all(false);
  2476. }
  2477. echo $OUTPUT->box($message, 'generalbox', 'notice');
  2478. echo $OUTPUT->continue_button($link);
  2479. echo $OUTPUT->footer();
  2480. exit(1); // General error code.
  2481. }
  2482. /**
  2483. * Redirects the user to another page, after printing a notice.
  2484. *
  2485. * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
  2486. *
  2487. * <strong>Good practice:</strong> You should call this method before starting page
  2488. * output by using any of the OUTPUT methods.
  2489. *
  2490. * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
  2491. * @param string $message The message to display to the user
  2492. * @param int $delay The delay before redirecting
  2493. * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
  2494. * @throws moodle_exception
  2495. */
  2496. function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
  2497. global $OUTPUT, $PAGE, $CFG;
  2498. if (CLI_SCRIPT or AJAX_SCRIPT) {
  2499. // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
  2500. throw new moodle_exception('redirecterrordetected', 'error');
  2501. }
  2502. if ($delay === null) {
  2503. $delay = -1;
  2504. }
  2505. // Prevent debug errors - make sure context is properly initialised.
  2506. if ($PAGE) {
  2507. $PAGE->set_context(null);
  2508. $PAGE->set_pagelayout('redirect'); // No header and footer needed.
  2509. $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
  2510. }
  2511. if ($url instanceof moodle_url) {
  2512. $url = $url->out(false);
  2513. }
  2514. $debugdisableredirect = false;
  2515. do {
  2516. if (defined('DEBUGGING_PRINTED')) {
  2517. // Some debugging already printed, no need to look more.
  2518. $debugdisableredirect = true;
  2519. break;
  2520. }
  2521. if (core_useragent::is_msword()) {
  2522. // Clicking a URL from MS Word sends a request to the server without cookies. If that
  2523. // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
  2524. // was clicked is opened. Because the request from Word is without cookies, it almost
  2525. // always results in a redirect to the login page, even if the user is logged in in their
  2526. // browser. This is not what we want, so prevent the redirect for requests from Word.
  2527. $debugdisableredirect = true;
  2528. break;
  2529. }
  2530. if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
  2531. // No errors should be displayed.
  2532. break;
  2533. }
  2534. if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
  2535. break;
  2536. }
  2537. if (!($lasterror['type'] & $CFG->debug)) {
  2538. // Last error not interesting.
  2539. break;
  2540. }
  2541. // Watch out here, @hidden() errors are returned from error_get_last() too.
  2542. if (headers_sent()) {
  2543. // We already started printing something - that means errors likely printed.
  2544. $debugdisableredirect = true;
  2545. break;
  2546. }
  2547. if (ob_get_level() and ob_get_contents()) {
  2548. // There is something waiting to be printed, hopefully it is the errors,
  2549. // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
  2550. $debugdisableredirect = true;
  2551. break;
  2552. }
  2553. } while (false);
  2554. // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
  2555. // (In practice browsers accept relative paths - but still, might as well do it properly.)
  2556. // This code turns relative into absolute.
  2557. if (!preg_match('|^[a-z]+:|i', $url)) {
  2558. // Get host name http://www.wherever.com.
  2559. $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
  2560. if (preg_match('|^/|', $url)) {
  2561. // URLs beginning with / are relative to web server root so we just add them in.
  2562. $url = $hostpart.$url;
  2563. } else {
  2564. // URLs not beginning with / are relative to path of current script, so add that on.
  2565. $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
  2566. }
  2567. // Replace all ..s.
  2568. while (true) {
  2569. $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
  2570. if ($newurl == $url) {
  2571. break;
  2572. }
  2573. $url = $newurl;
  2574. }
  2575. }
  2576. // Sanitise url - we can not rely on moodle_url or our URL cleaning
  2577. // because they do not support all valid external URLs.
  2578. $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
  2579. $url = str_replace('"', '%22', $url);
  2580. $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
  2581. $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
  2582. $url = str_replace('&amp;', '&', $encodedurl);
  2583. if (!empty($message)) {
  2584. if (!$debugdisableredirect && !headers_sent()) {
  2585. // A message has been provided, and the headers have not yet been sent.
  2586. // Display the message as a notification on the subsequent page.
  2587. \core\notification::add($message, $messagetype);
  2588. $message = null;
  2589. $delay = 0;
  2590. } else {
  2591. if ($delay === -1 || !is_numeric($delay)) {
  2592. $delay = 3;
  2593. }
  2594. $message = clean_text($message);
  2595. }
  2596. } else {
  2597. $message = get_string('pageshouldredirect');
  2598. $delay = 0;
  2599. }
  2600. // Make sure the session is closed properly, this prevents problems in IIS
  2601. // and also some potential PHP shutdown issues.
  2602. \core\session\manager::write_close();
  2603. if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
  2604. // This helps when debugging redirect issues like loops and it is not clear
  2605. // which layer in the stack sent the redirect header.
  2606. @header('X-Redirect-By: Moodle');
  2607. // 302 might not work for POST requests, 303 is ignored by obsolete clients.
  2608. @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
  2609. @header('Location: '.$url);
  2610. echo bootstrap_renderer::plain_redirect_message($encodedurl);
  2611. exit;
  2612. }
  2613. // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
  2614. if ($PAGE) {
  2615. $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
  2616. echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
  2617. exit;
  2618. } else {
  2619. echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
  2620. exit;
  2621. }
  2622. }
  2623. /**
  2624. * Given an email address, this function will return an obfuscated version of it.
  2625. *
  2626. * @param string $email The email address to obfuscate
  2627. * @return string The obfuscated email address
  2628. */
  2629. function obfuscate_email($email) {
  2630. $i = 0;
  2631. $length = strlen($email);
  2632. $obfuscated = '';
  2633. while ($i < $length) {
  2634. if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
  2635. $obfuscated.='%'.dechex(ord($email[$i]));
  2636. } else {
  2637. $obfuscated.=$email[$i];
  2638. }
  2639. $i++;
  2640. }
  2641. return $obfuscated;
  2642. }
  2643. /**
  2644. * This function takes some text and replaces about half of the characters
  2645. * with HTML entity equivalents. Return string is obviously longer.
  2646. *
  2647. * @param string $plaintext The text to be obfuscated
  2648. * @return string The obfuscated text
  2649. */
  2650. function obfuscate_text($plaintext) {
  2651. $i=0;
  2652. $length = core_text::strlen($plaintext);
  2653. $obfuscated='';
  2654. $prevobfuscated = false;
  2655. while ($i < $length) {
  2656. $char = core_text::substr($plaintext, $i, 1);
  2657. $ord = core_text::utf8ord($char);
  2658. $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
  2659. if ($prevobfuscated and $numerical ) {
  2660. $obfuscated.='&#'.$ord.';';
  2661. } else if (rand(0, 2)) {
  2662. $obfuscated.='&#'.$ord.';';
  2663. $prevobfuscated = true;
  2664. } else {
  2665. $obfuscated.=$char;
  2666. $prevobfuscated = false;
  2667. }
  2668. $i++;
  2669. }
  2670. return $obfuscated;
  2671. }
  2672. /**
  2673. * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
  2674. * to generate a fully obfuscated email link, ready to use.
  2675. *
  2676. * @param string $email The email address to display
  2677. * @param string $label The text to displayed as hyperlink to $email
  2678. * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
  2679. * @param string $subject The subject of the email in the mailto link
  2680. * @param string $body The content of the email in the mailto link
  2681. * @return string The obfuscated mailto link
  2682. */
  2683. function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
  2684. if (empty($label)) {
  2685. $label = $email;
  2686. }
  2687. $label = obfuscate_text($label);
  2688. $email = obfuscate_email($email);
  2689. $mailto = obfuscate_text('mailto');
  2690. $url = new moodle_url("mailto:$email");
  2691. $attrs = array();
  2692. if (!empty($subject)) {
  2693. $url->param('subject', format_string($subject));
  2694. }
  2695. if (!empty($body)) {
  2696. $url->param('body', format_string($body));
  2697. }
  2698. // Use the obfuscated mailto.
  2699. $url = preg_replace('/^mailto/', $mailto, $url->out());
  2700. if ($dimmed) {
  2701. $attrs['title'] = get_string('emaildisable');
  2702. $attrs['class'] = 'dimmed';
  2703. }
  2704. return html_writer::link($url, $label, $attrs);
  2705. }
  2706. /**
  2707. * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
  2708. * will transform it to html entities
  2709. *
  2710. * @param string $text Text to search for nolink tag in
  2711. * @return string
  2712. */
  2713. function rebuildnolinktag($text) {
  2714. $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
  2715. return $text;
  2716. }
  2717. /**
  2718. * Prints a maintenance message from $CFG->maintenance_message or default if empty.
  2719. */
  2720. function print_maintenance_message() {
  2721. global $CFG, $SITE, $PAGE, $OUTPUT;
  2722. header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
  2723. header('Status: 503 Moodle under maintenance');
  2724. header('Retry-After: 300');
  2725. $PAGE->set_pagetype('maintenance-message');
  2726. $PAGE->set_pagelayout('maintenance');
  2727. $PAGE->set_title(strip_tags($SITE->fullname));
  2728. $PAGE->set_heading($SITE->fullname);
  2729. echo $OUTPUT->header();
  2730. echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
  2731. if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
  2732. echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
  2733. echo $CFG->maintenance_message;
  2734. echo $OUTPUT->box_end();
  2735. }
  2736. echo $OUTPUT->footer();
  2737. die;
  2738. }
  2739. /**
  2740. * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
  2741. *
  2742. * It is not recommended to use this function in Moodle 2.5 but it is left for backward
  2743. * compartibility.
  2744. *
  2745. * Example how to print a single line tabs:
  2746. * $rows = array(
  2747. * new tabobject(...),
  2748. * new tabobject(...)
  2749. * );
  2750. * echo $OUTPUT->tabtree($rows, $selectedid);
  2751. *
  2752. * Multiple row tabs may not look good on some devices but if you want to use them
  2753. * you can specify ->subtree for the active tabobject.
  2754. *
  2755. * @param array $tabrows An array of rows where each row is an array of tab objects
  2756. * @param string $selected The id of the selected tab (whatever row it's on)
  2757. * @param array $inactive An array of ids of inactive tabs that are not selectable.
  2758. * @param array $activated An array of ids of other tabs that are currently activated
  2759. * @param bool $return If true output is returned rather then echo'd
  2760. * @return string HTML output if $return was set to true.
  2761. */
  2762. function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
  2763. global $OUTPUT;
  2764. $tabrows = array_reverse($tabrows);
  2765. $subtree = array();
  2766. foreach ($tabrows as $row) {
  2767. $tree = array();
  2768. foreach ($row as $tab) {
  2769. $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
  2770. $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
  2771. $tab->selected = (string)$tab->id == $selected;
  2772. if ($tab->activated || $tab->selected) {
  2773. $tab->subtree = $subtree;
  2774. }
  2775. $tree[] = $tab;
  2776. }
  2777. $subtree = $tree;
  2778. }
  2779. $output = $OUTPUT->tabtree($subtree);
  2780. if ($return) {
  2781. return $output;
  2782. } else {
  2783. print $output;
  2784. return !empty($output);
  2785. }
  2786. }
  2787. /**
  2788. * Alter debugging level for the current request,
  2789. * the change is not saved in database.
  2790. *
  2791. * @param int $level one of the DEBUG_* constants
  2792. * @param bool $debugdisplay
  2793. */
  2794. function set_debugging($level, $debugdisplay = null) {
  2795. global $CFG;
  2796. $CFG->debug = (int)$level;
  2797. $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
  2798. if ($debugdisplay !== null) {
  2799. $CFG->debugdisplay = (bool)$debugdisplay;
  2800. }
  2801. }
  2802. /**
  2803. * Standard Debugging Function
  2804. *
  2805. * Returns true if the current site debugging settings are equal or above specified level.
  2806. * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
  2807. * routing of notices is controlled by $CFG->debugdisplay
  2808. * eg use like this:
  2809. *
  2810. * 1) debugging('a normal debug notice');
  2811. * 2) debugging('something really picky', DEBUG_ALL);
  2812. * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
  2813. * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
  2814. *
  2815. * In code blocks controlled by debugging() (such as example 4)
  2816. * any output should be routed via debugging() itself, or the lower-level
  2817. * trigger_error() or error_log(). Using echo or print will break XHTML
  2818. * JS and HTTP headers.
  2819. *
  2820. * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
  2821. *
  2822. * @param string $message a message to print
  2823. * @param int $level the level at which this debugging statement should show
  2824. * @param array $backtrace use different backtrace
  2825. * @return bool
  2826. */
  2827. function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
  2828. global $CFG, $USER;
  2829. $forcedebug = false;
  2830. if (!empty($CFG->debugusers) && $USER) {
  2831. $debugusers = explode(',', $CFG->debugusers);
  2832. $forcedebug = in_array($USER->id, $debugusers);
  2833. }
  2834. if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
  2835. return false;
  2836. }
  2837. if (!isset($CFG->debugdisplay)) {
  2838. $CFG->debugdisplay = ini_get_bool('display_errors');
  2839. }
  2840. if ($message) {
  2841. if (!$backtrace) {
  2842. $backtrace = debug_backtrace();
  2843. }
  2844. $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
  2845. if (PHPUNIT_TEST) {
  2846. if (phpunit_util::debugging_triggered($message, $level, $from)) {
  2847. // We are inside test, the debug message was logged.
  2848. return true;
  2849. }
  2850. }
  2851. if (NO_DEBUG_DISPLAY) {
  2852. // Script does not want any errors or debugging in output,
  2853. // we send the info to error log instead.
  2854. error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
  2855. } else if ($forcedebug or $CFG->debugdisplay) {
  2856. if (!defined('DEBUGGING_PRINTED')) {
  2857. define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
  2858. }
  2859. if (CLI_SCRIPT) {
  2860. echo "++ $message ++\n$from";
  2861. } else {
  2862. echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
  2863. }
  2864. } else {
  2865. trigger_error($message . $from, E_USER_NOTICE);
  2866. }
  2867. }
  2868. return true;
  2869. }
  2870. /**
  2871. * Outputs a HTML comment to the browser.
  2872. *
  2873. * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
  2874. *
  2875. * <code>print_location_comment(__FILE__, __LINE__);</code>
  2876. *
  2877. * @param string $file
  2878. * @param integer $line
  2879. * @param boolean $return Whether to return or print the comment
  2880. * @return string|void Void unless true given as third parameter
  2881. */
  2882. function print_location_comment($file, $line, $return = false) {
  2883. if ($return) {
  2884. return "<!-- $file at line $line -->\n";
  2885. } else {
  2886. echo "<!-- $file at line $line -->\n";
  2887. }
  2888. }
  2889. /**
  2890. * Returns true if the user is using a right-to-left language.
  2891. *
  2892. * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
  2893. */
  2894. function right_to_left() {
  2895. return (get_string('thisdirection', 'langconfig') === 'rtl');
  2896. }
  2897. /**
  2898. * Returns swapped left<=> right if in RTL environment.
  2899. *
  2900. * Part of RTL Moodles support.
  2901. *
  2902. * @param string $align align to check
  2903. * @return string
  2904. */
  2905. function fix_align_rtl($align) {
  2906. if (!right_to_left()) {
  2907. return $align;
  2908. }
  2909. if ($align == 'left') {
  2910. return 'right';
  2911. }
  2912. if ($align == 'right') {
  2913. return 'left';
  2914. }
  2915. return $align;
  2916. }
  2917. /**
  2918. * Returns true if the page is displayed in a popup window.
  2919. *
  2920. * Gets the information from the URL parameter inpopup.
  2921. *
  2922. * @todo Use a central function to create the popup calls all over Moodle and
  2923. * In the moment only works with resources and probably questions.
  2924. *
  2925. * @return boolean
  2926. */
  2927. function is_in_popup() {
  2928. $inpopup = optional_param('inpopup', '', PARAM_BOOL);
  2929. return ($inpopup);
  2930. }
  2931. /**
  2932. * Progress trace class.
  2933. *
  2934. * Use this class from long operations where you want to output occasional information about
  2935. * what is going on, but don't know if, or in what format, the output should be.
  2936. *
  2937. * @copyright 2009 Tim Hunt
  2938. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2939. * @package core
  2940. */
  2941. abstract class progress_trace {
  2942. /**
  2943. * Output an progress message in whatever format.
  2944. *
  2945. * @param string $message the message to output.
  2946. * @param integer $depth indent depth for this message.
  2947. */
  2948. abstract public function output($message, $depth = 0);
  2949. /**
  2950. * Called when the processing is finished.
  2951. */
  2952. public function finished() {
  2953. }
  2954. }
  2955. /**
  2956. * This subclass of progress_trace does not ouput anything.
  2957. *
  2958. * @copyright 2009 Tim Hunt
  2959. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2960. * @package core
  2961. */
  2962. class null_progress_trace extends progress_trace {
  2963. /**
  2964. * Does Nothing
  2965. *
  2966. * @param string $message
  2967. * @param int $depth
  2968. * @return void Does Nothing
  2969. */
  2970. public function output($message, $depth = 0) {
  2971. }
  2972. }
  2973. /**
  2974. * This subclass of progress_trace outputs to plain text.
  2975. *
  2976. * @copyright 2009 Tim Hunt
  2977. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2978. * @package core
  2979. */
  2980. class text_progress_trace extends progress_trace {
  2981. /**
  2982. * Output the trace message.
  2983. *
  2984. * @param string $message
  2985. * @param int $depth
  2986. * @return void Output is echo'd
  2987. */
  2988. public function output($message, $depth = 0) {
  2989. mtrace(str_repeat(' ', $depth) . $message);
  2990. }
  2991. }
  2992. /**
  2993. * This subclass of progress_trace outputs as HTML.
  2994. *
  2995. * @copyright 2009 Tim Hunt
  2996. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2997. * @package core
  2998. */
  2999. class html_progress_trace extends progress_trace {
  3000. /**
  3001. * Output the trace message.
  3002. *
  3003. * @param string $message
  3004. * @param int $depth
  3005. * @return void Output is echo'd
  3006. */
  3007. public function output($message, $depth = 0) {
  3008. echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
  3009. flush();
  3010. }
  3011. }
  3012. /**
  3013. * HTML List Progress Tree
  3014. *
  3015. * @copyright 2009 Tim Hunt
  3016. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3017. * @package core
  3018. */
  3019. class html_list_progress_trace extends progress_trace {
  3020. /** @var int */
  3021. protected $currentdepth = -1;
  3022. /**
  3023. * Echo out the list
  3024. *
  3025. * @param string $message The message to display
  3026. * @param int $depth
  3027. * @return void Output is echoed
  3028. */
  3029. public function output($message, $depth = 0) {
  3030. $samedepth = true;
  3031. while ($this->currentdepth > $depth) {
  3032. echo "</li>\n</ul>\n";
  3033. $this->currentdepth -= 1;
  3034. if ($this->currentdepth == $depth) {
  3035. echo '<li>';
  3036. }
  3037. $samedepth = false;
  3038. }
  3039. while ($this->currentdepth < $depth) {
  3040. echo "<ul>\n<li>";
  3041. $this->currentdepth += 1;
  3042. $samedepth = false;
  3043. }
  3044. if ($samedepth) {
  3045. echo "</li>\n<li>";
  3046. }
  3047. echo htmlspecialchars($message);
  3048. flush();
  3049. }
  3050. /**
  3051. * Called when the processing is finished.
  3052. */
  3053. public function finished() {
  3054. while ($this->currentdepth >= 0) {
  3055. echo "</li>\n</ul>\n";
  3056. $this->currentdepth -= 1;
  3057. }
  3058. }
  3059. }
  3060. /**
  3061. * This subclass of progress_trace outputs to error log.
  3062. *
  3063. * @copyright Petr Skoda {@link http://skodak.org}
  3064. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3065. * @package core
  3066. */
  3067. class error_log_progress_trace extends progress_trace {
  3068. /** @var string log prefix */
  3069. protected $prefix;
  3070. /**
  3071. * Constructor.
  3072. * @param string $prefix optional log prefix
  3073. */
  3074. public function __construct($prefix = '') {
  3075. $this->prefix = $prefix;
  3076. }
  3077. /**
  3078. * Output the trace message.
  3079. *
  3080. * @param string $message
  3081. * @param int $depth
  3082. * @return void Output is sent to error log.
  3083. */
  3084. public function output($message, $depth = 0) {
  3085. error_log($this->prefix . str_repeat(' ', $depth) . $message);
  3086. }
  3087. }
  3088. /**
  3089. * Special type of trace that can be used for catching of output of other traces.
  3090. *
  3091. * @copyright Petr Skoda {@link http://skodak.org}
  3092. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3093. * @package core
  3094. */
  3095. class progress_trace_buffer extends progress_trace {
  3096. /** @var progres_trace */
  3097. protected $trace;
  3098. /** @var bool do we pass output out */
  3099. protected $passthrough;
  3100. /** @var string output buffer */
  3101. protected $buffer;
  3102. /**
  3103. * Constructor.
  3104. *
  3105. * @param progress_trace $trace
  3106. * @param bool $passthrough true means output and buffer, false means just buffer and no output
  3107. */
  3108. public function __construct(progress_trace $trace, $passthrough = true) {
  3109. $this->trace = $trace;
  3110. $this->passthrough = $passthrough;
  3111. $this->buffer = '';
  3112. }
  3113. /**
  3114. * Output the trace message.
  3115. *
  3116. * @param string $message the message to output.
  3117. * @param int $depth indent depth for this message.
  3118. * @return void output stored in buffer
  3119. */
  3120. public function output($message, $depth = 0) {
  3121. ob_start();
  3122. $this->trace->output($message, $depth);
  3123. $this->buffer .= ob_get_contents();
  3124. if ($this->passthrough) {
  3125. ob_end_flush();
  3126. } else {
  3127. ob_end_clean();
  3128. }
  3129. }
  3130. /**
  3131. * Called when the processing is finished.
  3132. */
  3133. public function finished() {
  3134. ob_start();
  3135. $this->trace->finished();
  3136. $this->buffer .= ob_get_contents();
  3137. if ($this->passthrough) {
  3138. ob_end_flush();
  3139. } else {
  3140. ob_end_clean();
  3141. }
  3142. }
  3143. /**
  3144. * Reset internal text buffer.
  3145. */
  3146. public function reset_buffer() {
  3147. $this->buffer = '';
  3148. }
  3149. /**
  3150. * Return internal text buffer.
  3151. * @return string buffered plain text
  3152. */
  3153. public function get_buffer() {
  3154. return $this->buffer;
  3155. }
  3156. }
  3157. /**
  3158. * Special type of trace that can be used for redirecting to multiple other traces.
  3159. *
  3160. * @copyright Petr Skoda {@link http://skodak.org}
  3161. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3162. * @package core
  3163. */
  3164. class combined_progress_trace extends progress_trace {
  3165. /**
  3166. * An array of traces.
  3167. * @var array
  3168. */
  3169. protected $traces;
  3170. /**
  3171. * Constructs a new instance.
  3172. *
  3173. * @param array $traces multiple traces
  3174. */
  3175. public function __construct(array $traces) {
  3176. $this->traces = $traces;
  3177. }
  3178. /**
  3179. * Output an progress message in whatever format.
  3180. *
  3181. * @param string $message the message to output.
  3182. * @param integer $depth indent depth for this message.
  3183. */
  3184. public function output($message, $depth = 0) {
  3185. foreach ($this->traces as $trace) {
  3186. $trace->output($message, $depth);
  3187. }
  3188. }
  3189. /**
  3190. * Called when the processing is finished.
  3191. */
  3192. public function finished() {
  3193. foreach ($this->traces as $trace) {
  3194. $trace->finished();
  3195. }
  3196. }
  3197. }
  3198. /**
  3199. * Returns a localized sentence in the current language summarizing the current password policy
  3200. *
  3201. * @todo this should be handled by a function/method in the language pack library once we have a support for it
  3202. * @uses $CFG
  3203. * @return string
  3204. */
  3205. function print_password_policy() {
  3206. global $CFG;
  3207. $message = '';
  3208. if (!empty($CFG->passwordpolicy)) {
  3209. $messages = array();
  3210. if (!empty($CFG->minpasswordlength)) {
  3211. $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
  3212. }
  3213. if (!empty($CFG->minpassworddigits)) {
  3214. $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
  3215. }
  3216. if (!empty($CFG->minpasswordlower)) {
  3217. $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
  3218. }
  3219. if (!empty($CFG->minpasswordupper)) {
  3220. $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
  3221. }
  3222. if (!empty($CFG->minpasswordnonalphanum)) {
  3223. $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
  3224. }
  3225. // Fire any additional password policy functions from plugins.
  3226. // Callbacks must return an array of message strings.
  3227. $pluginsfunction = get_plugins_with_function('print_password_policy');
  3228. foreach ($pluginsfunction as $plugintype => $plugins) {
  3229. foreach ($plugins as $pluginfunction) {
  3230. $messages = array_merge($messages, $pluginfunction());
  3231. }
  3232. }
  3233. $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
  3234. // Check if messages is empty before outputting any text.
  3235. if ($messages != '') {
  3236. $message = get_string('informpasswordpolicy', 'auth', $messages);
  3237. }
  3238. }
  3239. return $message;
  3240. }
  3241. /**
  3242. * Get the value of a help string fully prepared for display in the current language.
  3243. *
  3244. * @param string $identifier The identifier of the string to search for.
  3245. * @param string $component The module the string is associated with.
  3246. * @param boolean $ajax Whether this help is called from an AJAX script.
  3247. * This is used to influence text formatting and determines
  3248. * which format to output the doclink in.
  3249. * @param string|object|array $a An object, string or number that can be used
  3250. * within translation strings
  3251. * @return Object An object containing:
  3252. * - heading: Any heading that there may be for this help string.
  3253. * - text: The wiki-formatted help string.
  3254. * - doclink: An object containing a link, the linktext, and any additional
  3255. * CSS classes to apply to that link. Only present if $ajax = false.
  3256. * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
  3257. */
  3258. function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
  3259. global $CFG, $OUTPUT;
  3260. $sm = get_string_manager();
  3261. // Do not rebuild caches here!
  3262. // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
  3263. $data = new stdClass();
  3264. if ($sm->string_exists($identifier, $component)) {
  3265. $data->heading = format_string(get_string($identifier, $component));
  3266. } else {
  3267. // Gracefully fall back to an empty string.
  3268. $data->heading = '';
  3269. }
  3270. if ($sm->string_exists($identifier . '_help', $component)) {
  3271. $options = new stdClass();
  3272. $options->trusted = false;
  3273. $options->noclean = false;
  3274. $options->smiley = false;
  3275. $options->filter = false;
  3276. $options->para = true;
  3277. $options->newlines = false;
  3278. $options->overflowdiv = !$ajax;
  3279. // Should be simple wiki only MDL-21695.
  3280. $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
  3281. $helplink = $identifier . '_link';
  3282. if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
  3283. $link = get_string($helplink, $component);
  3284. $linktext = get_string('morehelp');
  3285. $data->doclink = new stdClass();
  3286. $url = new moodle_url(get_docs_url($link));
  3287. if ($ajax) {
  3288. $data->doclink->link = $url->out();
  3289. $data->doclink->linktext = $linktext;
  3290. $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
  3291. } else {
  3292. $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
  3293. array('class' => 'helpdoclink'));
  3294. }
  3295. }
  3296. } else {
  3297. $data->text = html_writer::tag('p',
  3298. html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
  3299. }
  3300. return $data;
  3301. }