/lib/weblib.php

https://bitbucket.org/ceu/moodle_demo · PHP · 7269 lines · 5119 code · 743 blank · 1407 comment · 932 complexity · bbefc14d9291c58240eb05d7ec3c25a9 MD5 · raw file

  1. <?php // $Id$
  2. ///////////////////////////////////////////////////////////////////////////
  3. // //
  4. // NOTICE OF COPYRIGHT //
  5. // //
  6. // Moodle - Modular Object-Oriented Dynamic Learning Environment //
  7. // http://moodle.com //
  8. // //
  9. // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
  10. // //
  11. // This program is free software; you can redistribute it and/or modify //
  12. // it under the terms of the GNU General Public License as published by //
  13. // the Free Software Foundation; either version 2 of the License, or //
  14. // (at your option) any later version. //
  15. // //
  16. // This program is distributed in the hope that it will be useful, //
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of //
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
  19. // GNU General Public License for more details: //
  20. // //
  21. // http://www.gnu.org/copyleft/gpl.html //
  22. // //
  23. ///////////////////////////////////////////////////////////////////////////
  24. /**
  25. * Library of functions for web output
  26. *
  27. * Library of all general-purpose Moodle PHP functions and constants
  28. * that produce HTML output
  29. *
  30. * Other main libraries:
  31. * - datalib.php - functions that access the database.
  32. * - moodlelib.php - general-purpose Moodle functions.
  33. * @author Martin Dougiamas
  34. * @version $Id$
  35. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  36. * @package moodlecore
  37. */
  38. /// We are going to uses filterlib functions here
  39. require_once("$CFG->libdir/filterlib.php");
  40. require_once("$CFG->libdir/ajax/ajaxlib.php");
  41. /// Constants
  42. /// Define text formatting types ... eventually we can add Wiki, BBcode etc
  43. /**
  44. * Does all sorts of transformations and filtering
  45. */
  46. define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
  47. /**
  48. * Plain HTML (with some tags stripped)
  49. */
  50. define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
  51. /**
  52. * Plain text (even tags are printed in full)
  53. */
  54. define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
  55. /**
  56. * Wiki-formatted text
  57. * Deprecated: left here just to note that '3' is not used (at the moment)
  58. * and to catch any latent wiki-like text (which generates an error)
  59. */
  60. define('FORMAT_WIKI', '3'); // Wiki-formatted text
  61. /**
  62. * Markdown-formatted text http://daringfireball.net/projects/markdown/
  63. */
  64. define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
  65. /**
  66. * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
  67. */
  68. define('TRUSTTEXT', '#####TRUSTTEXT#####');
  69. /**
  70. * Javascript related defines
  71. */
  72. define('REQUIREJS_BEFOREHEADER', 0);
  73. define('REQUIREJS_INHEADER', 1);
  74. define('REQUIREJS_AFTERHEADER', 2);
  75. /**
  76. * Allowed tags - string of html tags that can be tested against for safe html tags
  77. * @global string $ALLOWED_TAGS
  78. */
  79. global $ALLOWED_TAGS;
  80. $ALLOWED_TAGS =
  81. '<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
  82. /**
  83. * Allowed protocols - array of protocols that are safe to use in links and so on
  84. * @global string $ALLOWED_PROTOCOLS
  85. */
  86. $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
  87. 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
  88. 'border', 'border-bottom', 'border-left', 'border-top', 'border-right', 'margin', 'margin-bottom', 'margin-left', 'margin-top', 'margin-right',
  89. 'padding', 'padding-bottom', 'padding-left', 'padding-top', 'padding-right', 'vertical-align',
  90. 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
  91. /// Functions
  92. /**
  93. * Add quotes to HTML characters
  94. *
  95. * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
  96. * This function is very similar to {@link p()}
  97. *
  98. * @param string $var the string potentially containing HTML characters
  99. * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
  100. * true should be used to print data from forms and false for data from DB.
  101. * @return string
  102. */
  103. function s($var, $strip=false) {
  104. if ($var === '0' or $var === false or $var === 0) {
  105. return '0';
  106. }
  107. if ($strip) {
  108. return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
  109. } else {
  110. return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
  111. }
  112. }
  113. /**
  114. * Add quotes to HTML characters
  115. *
  116. * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
  117. * This function is very similar to {@link s()}
  118. *
  119. * @param string $var the string potentially containing HTML characters
  120. * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
  121. * true should be used to print data from forms and false for data from DB.
  122. * @return string
  123. */
  124. function p($var, $strip=false) {
  125. echo s($var, $strip);
  126. }
  127. /**
  128. * Does proper javascript quoting.
  129. * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
  130. *
  131. * @since 1.8 - 22/02/2007
  132. * @param mixed value
  133. * @return mixed quoted result
  134. */
  135. function addslashes_js($var) {
  136. if (is_string($var)) {
  137. $var = str_replace('\\', '\\\\', $var);
  138. $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
  139. $var = str_replace('</', '<\/', $var); // XHTML compliance
  140. } else if (is_array($var)) {
  141. $var = array_map('addslashes_js', $var);
  142. } else if (is_object($var)) {
  143. $a = get_object_vars($var);
  144. foreach ($a as $key=>$value) {
  145. $a[$key] = addslashes_js($value);
  146. }
  147. $var = (object)$a;
  148. }
  149. return $var;
  150. }
  151. /**
  152. * Remove query string from url
  153. *
  154. * Takes in a URL and returns it without the querystring portion
  155. *
  156. * @param string $url the url which may have a query string attached
  157. * @return string
  158. */
  159. function strip_querystring($url) {
  160. if ($commapos = strpos($url, '?')) {
  161. return substr($url, 0, $commapos);
  162. } else {
  163. return $url;
  164. }
  165. }
  166. /**
  167. * Returns the URL of the HTTP_REFERER, less the querystring portion if required
  168. * @param boolean $stripquery if true, also removes the query part of the url.
  169. * @return string
  170. */
  171. function get_referer($stripquery=true) {
  172. if (isset($_SERVER['HTTP_REFERER'])) {
  173. if ($stripquery) {
  174. return strip_querystring($_SERVER['HTTP_REFERER']);
  175. } else {
  176. return $_SERVER['HTTP_REFERER'];
  177. }
  178. } else {
  179. return '';
  180. }
  181. }
  182. /**
  183. * Returns the name of the current script, WITH the querystring portion.
  184. * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
  185. * return different things depending on a lot of things like your OS, Web
  186. * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
  187. * <b>NOTE:</b> This function returns false if the global variables needed are not set.
  188. *
  189. * @return string
  190. */
  191. function me() {
  192. if (!empty($_SERVER['REQUEST_URI'])) {
  193. $return = $_SERVER['REQUEST_URI'];
  194. } else if (!empty($_SERVER['PHP_SELF'])) {
  195. if (!empty($_SERVER['QUERY_STRING'])) {
  196. $return = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
  197. } else {
  198. $return = $_SERVER['PHP_SELF'];
  199. }
  200. } else if (!empty($_SERVER['SCRIPT_NAME'])) {
  201. if (!empty($_SERVER['QUERY_STRING'])) {
  202. $return = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
  203. } else {
  204. $return = $_SERVER['SCRIPT_NAME'];
  205. }
  206. } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
  207. if (!empty($_SERVER['QUERY_STRING'])) {
  208. $return = $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
  209. } else {
  210. $return = $_SERVER['URL'];
  211. }
  212. } else {
  213. notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
  214. return false;
  215. }
  216. // sanitize the url a bit more, the encoding style may be different in vars above
  217. $return = str_replace('"', '%22', $return);
  218. $return = str_replace('\'', '%27', $return);
  219. return $return;
  220. }
  221. /**
  222. * Like {@link me()} but returns a full URL
  223. * @see me()
  224. * @return string
  225. */
  226. function qualified_me() {
  227. global $CFG;
  228. if (!empty($CFG->wwwroot)) {
  229. $url = parse_url($CFG->wwwroot);
  230. }
  231. if (!empty($url['host'])) {
  232. $hostname = $url['host'];
  233. } else if (!empty($_SERVER['SERVER_NAME'])) {
  234. $hostname = $_SERVER['SERVER_NAME'];
  235. } else if (!empty($_ENV['SERVER_NAME'])) {
  236. $hostname = $_ENV['SERVER_NAME'];
  237. } else if (!empty($_SERVER['HTTP_HOST'])) {
  238. $hostname = $_SERVER['HTTP_HOST'];
  239. } else if (!empty($_ENV['HTTP_HOST'])) {
  240. $hostname = $_ENV['HTTP_HOST'];
  241. } else {
  242. notify('Warning: could not find the name of this server!');
  243. return false;
  244. }
  245. if (!empty($url['port'])) {
  246. $hostname .= ':'.$url['port'];
  247. } else if (!empty($_SERVER['SERVER_PORT'])) {
  248. if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
  249. $hostname .= ':'.$_SERVER['SERVER_PORT'];
  250. }
  251. }
  252. // TODO, this does not work in the situation described in MDL-11061, but
  253. // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
  254. // the server reports.
  255. if (isset($_SERVER['HTTPS'])) {
  256. $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
  257. } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
  258. $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
  259. } else {
  260. $protocol = 'http://';
  261. }
  262. $url_prefix = $protocol.$hostname;
  263. return $url_prefix . me();
  264. }
  265. /**
  266. * Class for creating and manipulating urls.
  267. *
  268. * See short write up here http://docs.moodle.org/dev/lib/weblib.php_moodle_url
  269. */
  270. class moodle_url {
  271. var $scheme = '';// e.g. http
  272. var $host = '';
  273. var $port = '';
  274. var $user = '';
  275. var $pass = '';
  276. var $path = '';
  277. var $fragment = '';
  278. var $params = array(); //associative array of query string params
  279. /**
  280. * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
  281. *
  282. * @param string $url url default null means use this page url with no query string
  283. * empty string means empty url.
  284. * if you pass any other type of url it will be parsed into it's bits, including query string
  285. * @param array $params these params override anything in the query string where params have the same name.
  286. */
  287. function moodle_url($url = null, $params = array()){
  288. global $FULLME;
  289. if ($url !== ''){
  290. if ($url === null){
  291. $url = strip_querystring($FULLME);
  292. }
  293. $parts = parse_url($url);
  294. if ($parts === FALSE){
  295. error('invalidurl');
  296. }
  297. if (isset($parts['query'])){
  298. parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
  299. }
  300. unset($parts['query']);
  301. foreach ($parts as $key => $value){
  302. $this->$key = $value;
  303. }
  304. $this->params($params);
  305. }
  306. }
  307. /**
  308. * Add an array of params to the params for this page.
  309. *
  310. * The added params override existing ones if they have the same name.
  311. *
  312. * @param array $params Defaults to null. If null then return value of param 'name'.
  313. * @return array Array of Params for url.
  314. */
  315. function params($params = null) {
  316. if (!is_null($params)) {
  317. return $this->params = $params + $this->params;
  318. } else {
  319. return $this->params;
  320. }
  321. }
  322. /**
  323. * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
  324. *
  325. * @param string $arg1
  326. * @param string $arg2
  327. * @param string $arg3
  328. */
  329. function remove_params(){
  330. if ($thisargs = func_get_args()){
  331. foreach ($thisargs as $arg){
  332. if (isset($this->params[$arg])){
  333. unset($this->params[$arg]);
  334. }
  335. }
  336. } else { // no args
  337. $this->params = array();
  338. }
  339. }
  340. /**
  341. * Add a param to the params for this page. The added param overrides existing one if they
  342. * have the same name.
  343. *
  344. * @param string $paramname name
  345. * @param string $param value
  346. */
  347. function param($paramname, $param){
  348. $this->params = array($paramname => $param) + $this->params;
  349. }
  350. function get_query_string($overrideparams = array()){
  351. $arr = array();
  352. $params = $overrideparams + $this->params;
  353. foreach ($params as $key => $val){
  354. $arr[] = urlencode($key)."=".urlencode($val);
  355. }
  356. return implode($arr, "&amp;");
  357. }
  358. /**
  359. * Outputs params as hidden form elements.
  360. *
  361. * @param array $exclude params to ignore
  362. * @param integer $indent indentation
  363. * @param array $overrideparams params to add to the output params, these
  364. * override existing ones with the same name.
  365. * @return string html for form elements.
  366. */
  367. function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
  368. $tabindent = str_repeat("\t", $indent);
  369. $str = '';
  370. $params = $overrideparams + $this->params;
  371. foreach ($params as $key => $val){
  372. if (FALSE === array_search($key, $exclude)) {
  373. $val = s($val);
  374. $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
  375. }
  376. }
  377. return $str;
  378. }
  379. /**
  380. * Output url
  381. *
  382. * @param boolean $noquerystring whether to output page params as a query string in the url.
  383. * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
  384. * @return string url
  385. */
  386. function out($noquerystring = false, $overrideparams = array()) {
  387. $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
  388. $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
  389. $uri .= $this->host ? $this->host : '';
  390. $uri .= $this->port ? ':'.$this->port : '';
  391. $uri .= $this->path ? $this->path : '';
  392. if (!$noquerystring){
  393. $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
  394. }
  395. $uri .= $this->fragment ? '#'.$this->fragment : '';
  396. return $uri;
  397. }
  398. /**
  399. * Output action url with sesskey
  400. *
  401. * @param boolean $noquerystring whether to output page params as a query string in the url.
  402. * @return string url
  403. */
  404. function out_action($overrideparams = array()) {
  405. $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
  406. return $this->out(false, $overrideparams);
  407. }
  408. }
  409. /**
  410. * Determine if there is data waiting to be processed from a form
  411. *
  412. * Used on most forms in Moodle to check for data
  413. * Returns the data as an object, if it's found.
  414. * This object can be used in foreach loops without
  415. * casting because it's cast to (array) automatically
  416. *
  417. * Checks that submitted POST data exists and returns it as object.
  418. *
  419. * @param string $url not used anymore
  420. * @return mixed false or object
  421. */
  422. function data_submitted($url='') {
  423. if (empty($_POST)) {
  424. return false;
  425. } else {
  426. return (object)$_POST;
  427. }
  428. }
  429. /**
  430. * Moodle replacement for php stripslashes() function,
  431. * works also for objects and arrays.
  432. *
  433. * The standard php stripslashes() removes ALL backslashes
  434. * even from strings - so C:\temp becomes C:temp - this isn't good.
  435. * This function should work as a fairly safe replacement
  436. * to be called on quoted AND unquoted strings (to be sure)
  437. *
  438. * @param mixed something to remove unsafe slashes from
  439. * @return mixed
  440. */
  441. function stripslashes_safe($mixed) {
  442. // there is no need to remove slashes from int, float and bool types
  443. if (empty($mixed)) {
  444. //nothing to do...
  445. } else if (is_string($mixed)) {
  446. if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
  447. $mixed = str_replace("''", "'", $mixed);
  448. } else { //the rest, simple and double quotes and backslashes
  449. $mixed = str_replace("\\'", "'", $mixed);
  450. $mixed = str_replace('\\"', '"', $mixed);
  451. $mixed = str_replace('\\\\', '\\', $mixed);
  452. }
  453. } else if (is_array($mixed)) {
  454. foreach ($mixed as $key => $value) {
  455. $mixed[$key] = stripslashes_safe($value);
  456. }
  457. } else if (is_object($mixed)) {
  458. $vars = get_object_vars($mixed);
  459. foreach ($vars as $key => $value) {
  460. $mixed->$key = stripslashes_safe($value);
  461. }
  462. }
  463. return $mixed;
  464. }
  465. /**
  466. * Recursive implementation of stripslashes()
  467. *
  468. * This function will allow you to strip the slashes from a variable.
  469. * If the variable is an array or object, slashes will be stripped
  470. * from the items (or properties) it contains, even if they are arrays
  471. * or objects themselves.
  472. *
  473. * @param mixed the variable to remove slashes from
  474. * @return mixed
  475. */
  476. function stripslashes_recursive($var) {
  477. if (is_object($var)) {
  478. $new_var = new object();
  479. $properties = get_object_vars($var);
  480. foreach($properties as $property => $value) {
  481. $new_var->$property = stripslashes_recursive($value);
  482. }
  483. } else if(is_array($var)) {
  484. $new_var = array();
  485. foreach($var as $property => $value) {
  486. $new_var[$property] = stripslashes_recursive($value);
  487. }
  488. } else if(is_string($var)) {
  489. $new_var = stripslashes($var);
  490. } else {
  491. $new_var = $var;
  492. }
  493. return $new_var;
  494. }
  495. /**
  496. * Recursive implementation of addslashes()
  497. *
  498. * This function will allow you to add the slashes from a variable.
  499. * If the variable is an array or object, slashes will be added
  500. * to the items (or properties) it contains, even if they are arrays
  501. * or objects themselves.
  502. *
  503. * @param mixed the variable to add slashes from
  504. * @return mixed
  505. */
  506. function addslashes_recursive($var) {
  507. if (is_object($var)) {
  508. $new_var = new object();
  509. $properties = get_object_vars($var);
  510. foreach($properties as $property => $value) {
  511. $new_var->$property = addslashes_recursive($value);
  512. }
  513. } else if (is_array($var)) {
  514. $new_var = array();
  515. foreach($var as $property => $value) {
  516. $new_var[$property] = addslashes_recursive($value);
  517. }
  518. } else if (is_string($var)) {
  519. $new_var = addslashes($var);
  520. } else { // nulls, integers, etc.
  521. $new_var = $var;
  522. }
  523. return $new_var;
  524. }
  525. /**
  526. * Given some normal text this function will break up any
  527. * long words to a given size by inserting the given character
  528. *
  529. * It's multibyte savvy and doesn't change anything inside html tags.
  530. *
  531. * @param string $string the string to be modified
  532. * @param int $maxsize maximum length of the string to be returned
  533. * @param string $cutchar the string used to represent word breaks
  534. * @return string
  535. */
  536. function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
  537. /// Loading the textlib singleton instance. We are going to need it.
  538. $textlib = textlib_get_instance();
  539. /// First of all, save all the tags inside the text to skip them
  540. $tags = array();
  541. filter_save_tags($string,$tags);
  542. /// Process the string adding the cut when necessary
  543. $output = '';
  544. $length = $textlib->strlen($string);
  545. $wordlength = 0;
  546. for ($i=0; $i<$length; $i++) {
  547. $char = $textlib->substr($string, $i, 1);
  548. if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
  549. $wordlength = 0;
  550. } else {
  551. $wordlength++;
  552. if ($wordlength > $maxsize) {
  553. $output .= $cutchar;
  554. $wordlength = 0;
  555. }
  556. }
  557. $output .= $char;
  558. }
  559. /// Finally load the tags back again
  560. if (!empty($tags)) {
  561. $output = str_replace(array_keys($tags), $tags, $output);
  562. }
  563. return $output;
  564. }
  565. /**
  566. * This does a search and replace, ignoring case
  567. * This function is only used for versions of PHP older than version 5
  568. * which do not have a native version of this function.
  569. * Taken from the PHP manual, by bradhuizenga @ softhome.net
  570. *
  571. * @param string $find the string to search for
  572. * @param string $replace the string to replace $find with
  573. * @param string $string the string to search through
  574. * return string
  575. */
  576. if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
  577. function str_ireplace($find, $replace, $string) {
  578. if (!is_array($find)) {
  579. $find = array($find);
  580. }
  581. if(!is_array($replace)) {
  582. if (!is_array($find)) {
  583. $replace = array($replace);
  584. } else {
  585. // this will duplicate the string into an array the size of $find
  586. $c = count($find);
  587. $rString = $replace;
  588. unset($replace);
  589. for ($i = 0; $i < $c; $i++) {
  590. $replace[$i] = $rString;
  591. }
  592. }
  593. }
  594. foreach ($find as $fKey => $fItem) {
  595. $between = explode(strtolower($fItem),strtolower($string));
  596. $pos = 0;
  597. foreach($between as $bKey => $bItem) {
  598. $between[$bKey] = substr($string,$pos,strlen($bItem));
  599. $pos += strlen($bItem) + strlen($fItem);
  600. }
  601. $string = implode($replace[$fKey],$between);
  602. }
  603. return ($string);
  604. }
  605. }
  606. /**
  607. * Locate the position of a string in another string
  608. *
  609. * This function is only used for versions of PHP older than version 5
  610. * which do not have a native version of this function.
  611. * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
  612. *
  613. * @param string $haystack The string to be searched
  614. * @param string $needle The string to search for
  615. * @param int $offset The position in $haystack where the search should begin.
  616. */
  617. if (!function_exists('stripos')) { /// Only exists in PHP 5
  618. function stripos($haystack, $needle, $offset=0) {
  619. return strpos(strtoupper($haystack), strtoupper($needle), $offset);
  620. }
  621. }
  622. /**
  623. * This function will print a button/link/etc. form element
  624. * that will work on both Javascript and non-javascript browsers.
  625. * Relies on the Javascript function openpopup in javascript.php
  626. *
  627. * All parameters default to null, only $type and $url are mandatory.
  628. *
  629. * $url must be relative to home page eg /mod/survey/stuff.php
  630. * @param string $url Web link relative to home page
  631. * @param string $name Name to be assigned to the popup window (this is used by
  632. * client-side scripts to "talk" to the popup window)
  633. * @param string $linkname Text to be displayed as web link
  634. * @param int $height Height to assign to popup window
  635. * @param int $width Height to assign to popup window
  636. * @param string $title Text to be displayed as popup page title
  637. * @param string $options List of additional options for popup window
  638. * @param string $return If true, return as a string, otherwise print
  639. * @param string $id id added to the element
  640. * @param string $class class added to the element
  641. * @return string
  642. * @uses $CFG
  643. */
  644. function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
  645. $height=400, $width=500, $title=null,
  646. $options=null, $return=false, $id=null, $class=null) {
  647. if (is_null($url)) {
  648. debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
  649. }
  650. global $CFG;
  651. if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
  652. $options = null;
  653. }
  654. // add some sane default options for popup windows
  655. if (!$options) {
  656. $options = 'menubar=0,location=0,scrollbars,resizable';
  657. }
  658. if ($width) {
  659. $options .= ',width='. $width;
  660. }
  661. if ($height) {
  662. $options .= ',height='. $height;
  663. }
  664. if ($id) {
  665. $id = ' id="'.$id.'" ';
  666. }
  667. if ($class) {
  668. $class = ' class="'.$class.'" ';
  669. }
  670. if ($name) {
  671. $_name = $name;
  672. if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
  673. debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
  674. }
  675. } else {
  676. $name = 'popup';
  677. }
  678. // get some default string, using the localized version of legacy defaults
  679. if (is_null($linkname) || $linkname === '') {
  680. $linkname = get_string('clickhere');
  681. }
  682. if (!$title) {
  683. $title = get_string('popupwindowname');
  684. }
  685. $fullscreen = 0; // must be passed to openpopup
  686. $element = '';
  687. switch ($type) {
  688. case 'button' :
  689. $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
  690. "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
  691. break;
  692. case 'link' :
  693. // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
  694. if (!(strpos($url,$CFG->wwwroot) === false)) {
  695. $url = substr($url, strlen($CFG->wwwroot));
  696. }
  697. $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
  698. "$CFG->frametarget onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
  699. break;
  700. default :
  701. error('Undefined element - can\'t create popup window.');
  702. break;
  703. }
  704. if ($return) {
  705. return $element;
  706. } else {
  707. echo $element;
  708. }
  709. }
  710. /**
  711. * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
  712. *
  713. * @return string html code to display a link to a popup window.
  714. * @see element_to_popup_window()
  715. */
  716. function link_to_popup_window ($url, $name=null, $linkname=null,
  717. $height=400, $width=500, $title=null,
  718. $options=null, $return=false) {
  719. return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
  720. }
  721. /**
  722. * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
  723. *
  724. * @return string html code to display a button to a popup window.
  725. * @see element_to_popup_window()
  726. */
  727. function button_to_popup_window ($url, $name=null, $linkname=null,
  728. $height=400, $width=500, $title=null, $options=null, $return=false,
  729. $id=null, $class=null) {
  730. return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
  731. }
  732. /**
  733. * Prints a simple button to close a window
  734. * @param string $name name of the window to close
  735. * @param boolean $return whether this function should return a string or output it
  736. * @return string if $return is true, nothing otherwise
  737. */
  738. function close_window_button($name='closewindow', $return=false) {
  739. global $CFG;
  740. $output = '';
  741. $output .= '<div class="closewindow">' . "\n";
  742. $output .= '<form action="#"><div>';
  743. $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
  744. $output .= '</div></form>';
  745. $output .= '</div>' . "\n";
  746. if ($return) {
  747. return $output;
  748. } else {
  749. echo $output;
  750. }
  751. }
  752. /*
  753. * Try and close the current window immediately using Javascript
  754. * @param int $delay the delay in seconds before closing the window
  755. */
  756. function close_window($delay=0) {
  757. ?>
  758. <script type="text/javascript">
  759. //<![CDATA[
  760. function close_this_window() {
  761. self.close();
  762. }
  763. setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
  764. //]]>
  765. </script>
  766. <noscript><center>
  767. <?php print_string('pleaseclose') ?>
  768. </center></noscript>
  769. <?php
  770. die;
  771. }
  772. /**
  773. * Given an array of values, output the HTML for a select element with those options.
  774. * Normally, you only need to use the first few parameters.
  775. *
  776. * @param array $options The options to offer. An array of the form
  777. * $options[{value}] = {text displayed for that option};
  778. * @param string $name the name of this form control, as in &lt;select name="..." ...
  779. * @param string $selected the option to select initially, default none.
  780. * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
  781. * Set this to '' if you don't want a 'nothing is selected' option.
  782. * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
  783. * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
  784. * @param boolean $return if false (the default) the the output is printed directly, If true, the
  785. * generated HTML is returned as a string.
  786. * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
  787. * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
  788. * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
  789. * then a suitable one is constructed.
  790. * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
  791. * By default, the list box will have a number of rows equal to min(10, count($options)), but if
  792. * $listbox is an integer, that number is used for size instead.
  793. * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
  794. * when $listbox display is enabled
  795. * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
  796. * then a suitable one is constructed.
  797. */
  798. function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
  799. $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
  800. $id='', $listbox=false, $multiple=false, $class='') {
  801. if ($nothing == 'choose') {
  802. $nothing = get_string('choose') .'...';
  803. }
  804. $attributes = ($script) ? 'onchange="'. $script .'"' : '';
  805. if ($disabled) {
  806. $attributes .= ' disabled="disabled"';
  807. }
  808. if ($tabindex) {
  809. $attributes .= ' tabindex="'.$tabindex.'"';
  810. }
  811. if ($id ==='') {
  812. $id = 'menu'.$name;
  813. // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
  814. $id = str_replace('[', '', $id);
  815. $id = str_replace(']', '', $id);
  816. }
  817. if ($class ==='') {
  818. $class = 'menu'.$name;
  819. // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
  820. $class = str_replace('[', '', $class);
  821. $class = str_replace(']', '', $class);
  822. }
  823. $class = 'select ' . $class; /// Add 'select' selector always
  824. if ($listbox) {
  825. if (is_integer($listbox)) {
  826. $size = $listbox;
  827. } else {
  828. $numchoices = count($options);
  829. if ($nothing) {
  830. $numchoices += 1;
  831. }
  832. $size = min(10, $numchoices);
  833. }
  834. $attributes .= ' size="' . $size . '"';
  835. if ($multiple) {
  836. $attributes .= ' multiple="multiple"';
  837. }
  838. }
  839. $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
  840. if ($nothing) {
  841. $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
  842. if ($nothingvalue === $selected) {
  843. $output .= ' selected="selected"';
  844. }
  845. $output .= '>'. $nothing .'</option>' . "\n";
  846. }
  847. if (!empty($options)) {
  848. foreach ($options as $value => $label) {
  849. $output .= ' <option value="'. s($value) .'"';
  850. if ((string)$value == (string)$selected ||
  851. (is_array($selected) && in_array($value, $selected))) {
  852. $output .= ' selected="selected"';
  853. }
  854. if ($label === '') {
  855. $output .= '>'. $value .'</option>' . "\n";
  856. } else {
  857. $output .= '>'. $label .'</option>' . "\n";
  858. }
  859. }
  860. }
  861. $output .= '</select>' . "\n";
  862. if ($return) {
  863. return $output;
  864. } else {
  865. echo $output;
  866. }
  867. }
  868. /**
  869. * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
  870. * Other options like choose_from_menu.
  871. * @param string $name
  872. * @param string $selected
  873. * @param string $string (defaults to '')
  874. * @param boolean $return whether this function should return a string or output it (defaults to false)
  875. * @param boolean $disabled (defaults to false)
  876. * @param int $tabindex
  877. */
  878. function choose_from_menu_yesno($name, $selected, $script = '',
  879. $return = false, $disabled = false, $tabindex = 0) {
  880. return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
  881. $selected, '', $script, '0', $return, $disabled, $tabindex);
  882. }
  883. /**
  884. * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
  885. * including option headings with the first level.
  886. */
  887. function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
  888. $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
  889. if ($nothing == 'choose') {
  890. $nothing = get_string('choose') .'...';
  891. }
  892. $attributes = ($script) ? 'onchange="'. $script .'"' : '';
  893. if ($disabled) {
  894. $attributes .= ' disabled="disabled"';
  895. }
  896. if ($tabindex) {
  897. $attributes .= ' tabindex="'.$tabindex.'"';
  898. }
  899. $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
  900. if ($nothing) {
  901. $output .= ' <option value="'. $nothingvalue .'"'. "\n";
  902. if ($nothingvalue === $selected) {
  903. $output .= ' selected="selected"';
  904. }
  905. $output .= '>'. $nothing .'</option>' . "\n";
  906. }
  907. if (!empty($options)) {
  908. foreach ($options as $section => $values) {
  909. $output .= ' <optgroup label="'. s(strip_tags(format_string($section))) .'">'."\n";
  910. foreach ($values as $value => $label) {
  911. $output .= ' <option value="'. format_string($value) .'"';
  912. if ((string)$value == (string)$selected) {
  913. $output .= ' selected="selected"';
  914. }
  915. if ($label === '') {
  916. $output .= '>'. $value .'</option>' . "\n";
  917. } else {
  918. $output .= '>'. $label .'</option>' . "\n";
  919. }
  920. }
  921. $output .= ' </optgroup>'."\n";
  922. }
  923. }
  924. $output .= '</select>' . "\n";
  925. if ($return) {
  926. return $output;
  927. } else {
  928. echo $output;
  929. }
  930. }
  931. /**
  932. * Given an array of values, creates a group of radio buttons to be part of a form
  933. *
  934. * @param array $options An array of value-label pairs for the radio group (values as keys)
  935. * @param string $name Name of the radiogroup (unique in the form)
  936. * @param string $checked The value that is already checked
  937. */
  938. function choose_from_radio ($options, $name, $checked='', $return=false) {
  939. static $idcounter = 0;
  940. if (!$name) {
  941. $name = 'unnamed';
  942. }
  943. $output = '<span class="radiogroup '.$name."\">\n";
  944. if (!empty($options)) {
  945. $currentradio = 0;
  946. foreach ($options as $value => $label) {
  947. $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
  948. $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
  949. $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
  950. if ($value == $checked) {
  951. $output .= ' checked="checked"';
  952. }
  953. if ($label === '') {
  954. $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
  955. } else {
  956. $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
  957. }
  958. $currentradio = ($currentradio + 1) % 2;
  959. }
  960. }
  961. $output .= '</span>' . "\n";
  962. if ($return) {
  963. return $output;
  964. } else {
  965. echo $output;
  966. }
  967. }
  968. /** Display an standard html checkbox with an optional label
  969. *
  970. * @param string $name The name of the checkbox
  971. * @param string $value The valus that the checkbox will pass when checked
  972. * @param boolean $checked The flag to tell the checkbox initial state
  973. * @param string $label The label to be showed near the checkbox
  974. * @param string $alt The info to be inserted in the alt tag
  975. */
  976. function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
  977. static $idcounter = 0;
  978. if (!$name) {
  979. $name = 'unnamed';
  980. }
  981. if ($alt) {
  982. $alt = strip_tags($alt);
  983. } else {
  984. $alt = 'checkbox';
  985. }
  986. if ($checked) {
  987. $strchecked = ' checked="checked"';
  988. } else {
  989. $strchecked = '';
  990. }
  991. $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
  992. $output = '<span class="checkbox '.$name."\">";
  993. $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
  994. if(!empty($label)) {
  995. $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
  996. }
  997. $output .= '</span>'."\n";
  998. if (empty($return)) {
  999. echo $output;
  1000. } else {
  1001. return $output;
  1002. }
  1003. }
  1004. /** Display an standard html text field with an optional label
  1005. *
  1006. * @param string $name The name of the text field
  1007. * @param string $value The value of the text field
  1008. * @param string $label The label to be showed near the text field
  1009. * @param string $alt The info to be inserted in the alt tag
  1010. */
  1011. function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
  1012. static $idcounter = 0;
  1013. if (empty($name)) {
  1014. $name = 'unnamed';
  1015. }
  1016. if (empty($alt)) {
  1017. $alt = 'textfield';
  1018. }
  1019. if (!empty($maxlength)) {
  1020. $maxlength = ' maxlength="'.$maxlength.'" ';
  1021. }
  1022. $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
  1023. $output = '<span class="textfield '.$name."\">";
  1024. $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
  1025. $output .= '</span>'."\n";
  1026. if (empty($return)) {
  1027. echo $output;
  1028. } else {
  1029. return $output;
  1030. }
  1031. }
  1032. /**
  1033. * Implements a complete little popup form
  1034. *
  1035. * @uses $CFG
  1036. * @param string $common The URL up to the point of the variable that changes
  1037. * @param array $options Alist of value-label pairs for the popup list
  1038. * @param string $formid Id must be unique on the page (originaly $formname)
  1039. * @param string $selected The option that is already selected
  1040. * @param string $nothing The label for the "no choice" option
  1041. * @param string $help The name of a help page if help is required
  1042. * @param string $helptext The name of the label for the help button
  1043. * @param boolean $return Indicates whether the function should return the text
  1044. * as a string or echo it directly to the page being rendered
  1045. * @param string $targetwindow The name of the target page to open the linked page in.
  1046. * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
  1047. * @param array $optionsextra TODO, an array?
  1048. * @param mixed $gobutton If set, this turns off the JavaScript and uses a 'go'
  1049. * button instead (as is always included for JS-disabled users). Set to true
  1050. * for a literal 'Go' button, or to a string to change the name of the button.
  1051. * @return string If $return is true then the entire form is returned as a string.
  1052. * @todo Finish documenting this function<br>
  1053. */
  1054. function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
  1055. $targetwindow='self', $selectlabel='', $optionsextra=NULL, $gobutton=NULL) {
  1056. global $CFG;
  1057. static $go, $choose; /// Locally cached, in case there's lots on a page
  1058. if (empty($options)) {
  1059. return '';
  1060. }
  1061. if (!isset($go)) {
  1062. $go = get_string('go');
  1063. }
  1064. if ($nothing == 'choose') {
  1065. if (!isset($choose)) {
  1066. $choose = get_string('choose');
  1067. }
  1068. $nothing = $choose.'...';
  1069. }
  1070. // changed reference to document.getElementById('id_abc') instead of document.abc
  1071. // MDL-7861
  1072. $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
  1073. ' method="get" '.
  1074. $CFG->frametarget.
  1075. ' id="'.$formid.'"'.
  1076. ' class="popupform">';
  1077. if ($help) {
  1078. $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
  1079. } else {
  1080. $button = '';
  1081. }
  1082. if ($selectlabel) {
  1083. $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
  1084. }
  1085. if ($gobutton) {
  1086. // Using the no-JavaScript version
  1087. $javascript = '';
  1088. } else if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
  1089. //IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
  1090. //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
  1091. //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
  1092. //so we do not fix the Opera behavior on Linux
  1093. $javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
  1094. } else {
  1095. //Other browser
  1096. $javascript = ' onchange="'.$targetwindow.
  1097. '.location=document.getElementById(\''.$formid.
  1098. '\').jump.options[document.getElementById(\''.
  1099. $formid.'\').jump.selectedIndex].value;"';
  1100. }
  1101. $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.'>'."\n";
  1102. if ($nothing != '') {
  1103. $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
  1104. }
  1105. $inoptgroup = false;
  1106. foreach ($options as $value => $label) {
  1107. if ($label == '--') { /// we are ending previous optgroup
  1108. /// Check to see if we already have a valid open optgroup
  1109. /// XHTML demands that there be at least 1 option within an optgroup
  1110. if ($inoptgroup and (count($optgr) > 1) ) {
  1111. $output .= implode('', $optgr);
  1112. $output .= ' </optgroup>';
  1113. }
  1114. $optgr = array();
  1115. $inoptgroup = false;
  1116. continue;
  1117. } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
  1118. /// Check to see if we already have a valid open optgroup
  1119. /// XHTML demands that there be at least 1 option within an optgroup
  1120. if ($inoptgroup and (count($optgr) > 1) ) {
  1121. $output .= implode('', $optgr);
  1122. $output .= ' </optgroup>';
  1123. }
  1124. unset($optgr);
  1125. $optgr = array();
  1126. $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
  1127. $inoptgroup = true; /// everything following will be in an optgroup
  1128. continue;
  1129. } else {
  1130. if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
  1131. {
  1132. $url=sid_process_url( $common . $value );
  1133. } else
  1134. {
  1135. $url=$common . $value;
  1136. }
  1137. $optstr = ' <option value="' . $url . '"';
  1138. if ($value == $selected) {
  1139. $optstr .= ' selected="selected"';
  1140. }
  1141. if (!empty($optionsextra[$value])) {
  1142. $optstr .= ' '.$optionsextra[$value];
  1143. }
  1144. if ($label) {
  1145. $optstr .= '>'. $label .'</option>' . "\n";
  1146. } else {
  1147. $optstr .= '>'. $value .'</option>' . "\n";
  1148. }
  1149. if ($inoptgroup) {
  1150. $optgr[] = $optstr;
  1151. } else {
  1152. $output .= $optstr;
  1153. }
  1154. }
  1155. }
  1156. /// catch the final group if not closed
  1157. if ($inoptgroup and count($optgr) > 1) {
  1158. $output .= implode('', $optgr);
  1159. $output .= ' </optgroup>';
  1160. }
  1161. $output .= '</select>';
  1162. $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
  1163. if ($gobutton) {
  1164. $output .= '<input type="submit" value="'.
  1165. ($gobutton===true ? $go : $gobutton).'" />';
  1166. } else {
  1167. $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
  1168. $output .= '<input type="submit" value="'.$go.'" /></div>';
  1169. $output .= '<script type="text/javascript">'.
  1170. "\n//<![CDATA[\n".
  1171. 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
  1172. "\n//]]>\n".'</script>';
  1173. }
  1174. $output .= '</div></form>';
  1175. if ($return) {
  1176. return $output;
  1177. } else {
  1178. echo $output;
  1179. }
  1180. }
  1181. /**
  1182. * Prints some red text
  1183. *
  1184. * @param string $error The text to be displayed in red
  1185. */
  1186. function formerr($error) {
  1187. if (!empty($error)) {
  1188. echo '<span class="error">'. $error .'</span>';
  1189. }
  1190. }
  1191. /**
  1192. * Validates an email to make sure it makes sense.
  1193. *
  1194. * @param string $address The email address to validate.
  1195. * @return boolean
  1196. */
  1197. function validate_email($address) {
  1198. return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
  1199. '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
  1200. '@'.
  1201. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
  1202. '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
  1203. $address));
  1204. }
  1205. /**
  1206. * Extracts file argument either from file parameter or PATH_INFO
  1207. *
  1208. * @param string $scriptname name of the calling script
  1209. * @return string file path (only safe characters)
  1210. */
  1211. function get_file_argument($scriptname) {
  1212. global $_SERVER;
  1213. $relativepath = FALSE;
  1214. // first try normal parameter (compatible method == no relative links!)
  1215. $relativepath = optional_param('file', FALSE, PARAM_PATH);
  1216. if ($relativepath === '/testslasharguments') {
  1217. echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
  1218. die;
  1219. }
  1220. // then try extract file from PATH_INFO (slasharguments method)
  1221. if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
  1222. $path_info = $_SERVER['PATH_INFO'];
  1223. // check that PATH_INFO works == must not contain the script name
  1224. if (!strpos($path_info, $scriptname)) {
  1225. $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
  1226. if ($relativepath === '/testslasharguments') {
  1227. echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
  1228. die;
  1229. }
  1230. }
  1231. }
  1232. // now if both fail try the old way
  1233. // (for compatibility with misconfigured or older buggy php implementations)
  1234. if (!$relativepath) {
  1235. $arr = explode($scriptname, me());
  1236. if (!empty($arr[1])) {
  1237. $path_info = strip_querystring($arr[1]);
  1238. $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
  1239. if ($relativepath === '/testslasharguments') {
  1240. echo 'test 2 : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
  1241. die;
  1242. }
  1243. }
  1244. }
  1245. return $relativepath;
  1246. }
  1247. /**
  1248. * Searches the current environment variables for some slash arguments
  1249. *
  1250. * @param string $file ?
  1251. * @todo Finish documenting this function
  1252. */
  1253. function get_slash_arguments($file='file.php') {
  1254. if (!$string = me()) {
  1255. return false;
  1256. }
  1257. $pathinfo = explode($file, $string);
  1258. if (!empty($pathinfo[1])) {
  1259. return addslashes($pathinfo[1]);
  1260. } else {
  1261. return false;
  1262. }
  1263. }
  1264. /**
  1265. * Extracts arguments from "/foo/bar/something"
  1266. * eg http://mysite.com/script.php/foo/bar/something
  1267. *
  1268. * @param string $string ?
  1269. * @param int $i ?
  1270. * @return array|string
  1271. * @todo Finish documenting this function
  1272. */
  1273. function parse_slash_arguments($string, $i=0) {
  1274. if (detect_munged_arguments($string)) {
  1275. return false;
  1276. }
  1277. $args = explode('/', $string);
  1278. if ($i) { // return just the required argument
  1279. return $args[$i];
  1280. } else { // return the whole array
  1281. array_shift($args); // get rid of the empty first one
  1282. return $args;
  1283. }
  1284. }
  1285. /**
  1286. * Just returns an array of text formats suitable for a popup menu
  1287. *
  1288. * @uses FORMAT_MOODLE
  1289. * @uses FORMAT_HTML
  1290. * @uses FORMAT_PLAIN
  1291. * @uses FORMAT_MARKDOWN
  1292. * @return array
  1293. */
  1294. function format_text_menu() {
  1295. return array (FORMAT_MOODLE => get_string('formattext'),
  1296. FORMAT_HTML => get_string('formathtml'),
  1297. FORMAT_PLAIN => get_string('formatplain'),
  1298. FORMAT_MARKDOWN => get_string('formatmarkdown'));
  1299. }
  1300. /**
  1301. * Given text in a variety of format codings, this function returns
  1302. * the text as safe HTML.
  1303. *
  1304. * This function should mainly be used for long strings like posts,
  1305. * answers, glossary items etc. For short strings @see format_string().
  1306. *
  1307. * @uses $CFG
  1308. * @uses FORMAT_MOODLE
  1309. * @uses FORMAT_HTML
  1310. * @uses FORMAT_PLAIN
  1311. * @uses FORMAT_WIKI
  1312. * @uses FORMAT_MARKDOWN
  1313. * @param string $text The text to be formatted. This is raw text originally from user input.
  1314. * @param int $format Identifier of the text format to be used
  1315. * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
  1316. * @param array $options ?
  1317. * @param int $courseid ?
  1318. * @return string
  1319. * @todo Finish documenting this function
  1320. */
  1321. function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
  1322. global $CFG, $COURSE;
  1323. static $croncache = array();
  1324. if ($text === '' || is_null($text)) {
  1325. return ''; // no need to do any filters and cleaning
  1326. }
  1327. if (!isset($options->trusttext)) {
  1328. $options->trusttext = false;
  1329. }
  1330. if (!isset($options->noclean)) {
  1331. $options->noclean=false;
  1332. }
  1333. if (!isset($options->nocache)) {
  1334. $options->nocache=false;
  1335. }
  1336. if (!isset($options->smiley)) {
  1337. $options->smiley=true;
  1338. }
  1339. if (!isset($options->filter)) {
  1340. $options->filter=true;
  1341. }
  1342. if (!isset($options->para)) {
  1343. $options->para=true;
  1344. }
  1345. if (!isset($options->newlines)) {
  1346. $options->newlines=true;
  1347. }
  1348. if (empty($courseid)) {
  1349. $courseid = $COURSE->id;
  1350. }
  1351. if (!empty($CFG->cachetext) and empty($options->nocache)) {
  1352. $time = time() - $CFG->cachetext;
  1353. $md5key = md5($text.'-'.(int)$courseid.'-'.current_language().'-'.(int)$format.(int)$options->trusttext.(int)$options->noclean.(int)$options->smiley.(int)$options->filter.(int)$options->para.(int)$options->newlines);
  1354. if (defined('FULLME') and FULLME == 'cron') {
  1355. if (isset($croncache[$md5key])) {
  1356. return $croncache[$md5key];
  1357. }
  1358. }
  1359. if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
  1360. if ($oldcacheitem->timemodified >= $time) {
  1361. if (defined('FULLME') and FULLME == 'cron') {
  1362. if (count($croncache) > 150) {
  1363. reset($croncache);
  1364. $key = key($croncache);
  1365. unset($croncache[$key]);
  1366. }
  1367. $croncache[$md5key] = $oldcacheitem->formattedtext;
  1368. }
  1369. return $oldcacheitem->formattedtext;
  1370. }
  1371. }
  1372. }
  1373. // trusttext overrides the noclean option!
  1374. if ($options->trusttext) {
  1375. if (trusttext_present($text)) {
  1376. $text = trusttext_strip($text);
  1377. if (!empty($CFG->enabletrusttext)) {
  1378. $options->noclean = true;
  1379. } else {
  1380. $options->noclean = false;
  1381. }
  1382. } else {
  1383. $options->noclean = false;
  1384. }
  1385. } else if (!debugging('', DEBUG_DEVELOPER)) {
  1386. // strip any forgotten trusttext in non-developer mode
  1387. // do not forget to disable text cache when debugging trusttext!!
  1388. $text = trusttext_strip($text);
  1389. }
  1390. $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
  1391. switch ($format) {
  1392. case FORMAT_HTML:
  1393. if ($options->smiley) {
  1394. replace_smilies($text);
  1395. }
  1396. if (!$options->noclean) {
  1397. $text = clean_text($text, FORMAT_HTML);
  1398. }
  1399. if ($options->filter) {
  1400. $text = filter_text($text, $courseid);
  1401. }
  1402. break;
  1403. case FORMAT_PLAIN:
  1404. $text = s($text); // cleans dangerous JS
  1405. $text = rebuildnolinktag($text);
  1406. $text = str_replace(' ', '&nbsp; ', $text);
  1407. $text = nl2br($text);
  1408. break;
  1409. case FORMAT_WIKI:
  1410. // this format is deprecated
  1411. $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
  1412. this message as all texts should have been converted to Markdown format instead.
  1413. Please post a bug report to http://moodle.org/bugs with information about where you
  1414. saw this message.</p>'.s($text);
  1415. break;
  1416. case FORMAT_MARKDOWN:
  1417. $text = markdown_to_html($text);
  1418. if ($options->smiley) {
  1419. replace_smilies($text);
  1420. }
  1421. if (!$options->noclean) {
  1422. $text = clean_text($text, FORMAT_HTML);
  1423. }
  1424. if ($options->filter) {
  1425. $text = filter_text($text, $courseid);
  1426. }
  1427. break;
  1428. default: // FORMAT_MOODLE or anything else
  1429. $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
  1430. if (!$options->noclean) {
  1431. $text = clean_text($text, FORMAT_HTML);
  1432. }
  1433. if ($options->filter) {
  1434. $text = filter_text($text, $courseid);
  1435. }
  1436. break;
  1437. }
  1438. if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
  1439. if (defined('FULLME') and FULLME == 'cron') {
  1440. // special static cron cache - no need to store it in db if its not already there
  1441. if (count($croncache) > 150) {
  1442. reset($croncache);
  1443. $key = key($croncache);
  1444. unset($croncache[$key]);
  1445. }
  1446. $croncache[$md5key] = $text;
  1447. return $text;
  1448. }
  1449. $newcacheitem = new object();
  1450. $newcacheitem->md5key = $md5key;
  1451. $newcacheitem->formattedtext = addslashes($text);
  1452. $newcacheitem->timemodified = time();
  1453. if ($oldcacheitem) { // See bug 4677 for discussion
  1454. $newcacheitem->id = $oldcacheitem->id;
  1455. @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
  1456. // It's unlikely that the cron cache cleaner could have
  1457. // deleted this entry in the meantime, as it allows
  1458. // some extra time to cover these cases.
  1459. } else {
  1460. @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
  1461. // Again, it's possible that another user has caused this
  1462. // record to be created already in the time that it took
  1463. // to traverse this function. That's OK too, as the
  1464. // call above handles duplicate entries, and eventually
  1465. // the cron cleaner will delete them.
  1466. }
  1467. }
  1468. return $text;
  1469. }
  1470. /** Converts the text format from the value to the 'internal'
  1471. * name or vice versa. $key can either be the value or the name
  1472. * and you get the other back.
  1473. *
  1474. * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
  1475. * @return mixed as above but the other way around!
  1476. */
  1477. function text_format_name( $key ) {
  1478. $lookup = array();
  1479. $lookup[FORMAT_MOODLE] = 'moodle';
  1480. $lookup[FORMAT_HTML] = 'html';
  1481. $lookup[FORMAT_PLAIN] = 'plain';
  1482. $lookup[FORMAT_MARKDOWN] = 'markdown';
  1483. $value = "error";
  1484. if (!is_numeric($key)) {
  1485. $key = strtolower( $key );
  1486. $value = array_search( $key, $lookup );
  1487. }
  1488. else {
  1489. if (isset( $lookup[$key] )) {
  1490. $value = $lookup[ $key ];
  1491. }
  1492. }
  1493. return $value;
  1494. }
  1495. /**
  1496. * Resets all data related to filters, called during upgrade or when filter settings change.
  1497. * @return void
  1498. */
  1499. function reset_text_filters_cache() {
  1500. global $CFG;
  1501. delete_records('cache_text');
  1502. $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
  1503. remove_dir($purifdir, true);
  1504. }
  1505. /** Given a simple string, this function returns the string
  1506. * processed by enabled string filters if $CFG->filterall is enabled
  1507. *
  1508. * This function should be used to print short strings (non html) that
  1509. * need filter processing e.g. activity titles, post subjects,
  1510. * glossary concepts.
  1511. *
  1512. * @param string $string The string to be filtered.
  1513. * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
  1514. * @param int $courseid Current course as filters can, potentially, use it
  1515. * @return string
  1516. */
  1517. function format_string ($string, $striplinks=true, $courseid=NULL ) {
  1518. global $CFG, $COURSE;
  1519. //We'll use a in-memory cache here to speed up repeated strings
  1520. static $strcache = false;
  1521. if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
  1522. $strcache = array();
  1523. }
  1524. //init course id
  1525. if (empty($courseid)) {
  1526. $courseid = $COURSE->id;
  1527. }
  1528. //Calculate md5
  1529. $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
  1530. //Fetch from cache if possible
  1531. if (isset($strcache[$md5])) {
  1532. return $strcache[$md5];
  1533. }
  1534. // First replace all ampersands not followed by html entity code
  1535. $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
  1536. if (!empty($CFG->filterall)) {
  1537. $string = filter_string($string, $courseid);
  1538. }
  1539. // If the site requires it, strip ALL tags from this string
  1540. if (!empty($CFG->formatstringstriptags)) {
  1541. $string = strip_tags($string);
  1542. } else {
  1543. // Otherwise strip just links if that is required (default)
  1544. if ($striplinks) { //strip links in string
  1545. $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
  1546. }
  1547. $string = clean_text($string);
  1548. }
  1549. //Store to cache
  1550. $strcache[$md5] = $string;
  1551. return $string;
  1552. }
  1553. /**
  1554. * Given text in a variety of format codings, this function returns
  1555. * the text as plain text suitable for plain email.
  1556. *
  1557. * @uses FORMAT_MOODLE
  1558. * @uses FORMAT_HTML
  1559. * @uses FORMAT_PLAIN
  1560. * @uses FORMAT_WIKI
  1561. * @uses FORMAT_MARKDOWN
  1562. * @param string $text The text to be formatted. This is raw text originally from user input.
  1563. * @param int $format Identifier of the text format to be used
  1564. * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
  1565. * @return string
  1566. */
  1567. function format_text_email($text, $format) {
  1568. switch ($format) {
  1569. case FORMAT_PLAIN:
  1570. return $text;
  1571. break;
  1572. case FORMAT_WIKI:
  1573. // there should not be any of these any more!
  1574. /// This expression turns links into something nice in a text format. (Russell Jungwirth)
  1575. /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
  1576. $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
  1577. return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
  1578. break;
  1579. case FORMAT_HTML:
  1580. return html_to_text($text);
  1581. break;
  1582. case FORMAT_MOODLE:
  1583. case FORMAT_MARKDOWN:
  1584. default:
  1585. $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
  1586. return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
  1587. break;
  1588. }
  1589. }
  1590. /**
  1591. * Given some text in HTML format, this function will pass it
  1592. * through any filters that have been defined in $CFG->textfilterx
  1593. * The variable defines a filepath to a file containing the
  1594. * filter function. The file must contain a variable called
  1595. * $textfilter_function which contains the name of the function
  1596. * with $courseid and $text parameters
  1597. *
  1598. * @param string $text The text to be passed through format filters
  1599. * @param int $courseid ?
  1600. * @return string
  1601. * @todo Finish documenting this function
  1602. */
  1603. function filter_text($text, $courseid=NULL) {
  1604. global $CFG, $COURSE;
  1605. if (empty($courseid)) {
  1606. $courseid = $COURSE->id; // (copied from format_text)
  1607. }
  1608. if (!empty($CFG->textfilters)) {
  1609. require_once($CFG->libdir.'/filterlib.php');
  1610. $textfilters = explode(',', $CFG->textfilters);
  1611. foreach ($textfilters as $textfilter) {
  1612. if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
  1613. include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
  1614. $functionname = basename($textfilter).'_filter';
  1615. if (function_exists($functionname)) {
  1616. $text = $functionname($courseid, $text);
  1617. }
  1618. }
  1619. }
  1620. }
  1621. /// <nolink> tags removed for XHTML compatibility
  1622. $text = str_replace('<nolink>', '', $text);
  1623. $text = str_replace('</nolink>', '', $text);
  1624. return $text;
  1625. }
  1626. /**
  1627. * Given a string (short text) in HTML format, this function will pass it
  1628. * through any filters that have been defined in $CFG->stringfilters
  1629. * The variable defines a filepath to a file containing the
  1630. * filter function. The file must contain a variable called
  1631. * $textfilter_function which contains the name of the function
  1632. * with $courseid and $text parameters
  1633. *
  1634. * @param string $string The text to be passed through format filters
  1635. * @param int $courseid The id of a course
  1636. * @return string
  1637. */
  1638. function filter_string($string, $courseid=NULL) {
  1639. global $CFG, $COURSE;
  1640. if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
  1641. return $string;
  1642. }
  1643. if (empty($courseid)) {
  1644. $courseid = $COURSE->id;
  1645. }
  1646. require_once($CFG->libdir.'/filterlib.php');
  1647. if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
  1648. if (empty($CFG->stringfilters)) { // but it's blank, so finish now
  1649. return $string;
  1650. }
  1651. $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
  1652. } else { // Otherwise try to derive a list from textfilters
  1653. if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
  1654. $stringfilters = array('filter/multilang'); // Let's use just that
  1655. $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
  1656. } else {
  1657. $CFG->stringfilters = ''; // Save the result and return
  1658. return $string;
  1659. }
  1660. }
  1661. foreach ($stringfilters as $stringfilter) {
  1662. if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
  1663. include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
  1664. $functionname = basename($stringfilter).'_filter';
  1665. if (function_exists($functionname)) {
  1666. $string = $functionname($courseid, $string);
  1667. }
  1668. }
  1669. }
  1670. /// <nolink> tags removed for XHTML compatibility
  1671. $string = str_replace('<nolink>', '', $string);
  1672. $string = str_replace('</nolink>', '', $string);
  1673. return $string;
  1674. }
  1675. /**
  1676. * Is the text marked as trusted?
  1677. *
  1678. * @param string $text text to be searched for TRUSTTEXT marker
  1679. * @return boolean
  1680. */
  1681. function trusttext_present($text) {
  1682. if (strpos($text, TRUSTTEXT) !== FALSE) {
  1683. return true;
  1684. } else {
  1685. return false;
  1686. }
  1687. }
  1688. /**
  1689. * This funtion MUST be called before the cleaning or any other
  1690. * function that modifies the data! We do not know the origin of trusttext
  1691. * in database, if it gets there in tweaked form we must not convert it
  1692. * to supported form!!!
  1693. *
  1694. * Please be carefull not to use stripslashes on data from database
  1695. * or twice stripslashes when processing data recieved from user.
  1696. *
  1697. * @param string $text text that may contain TRUSTTEXT marker
  1698. * @return text without any TRUSTTEXT marker
  1699. */
  1700. function trusttext_strip($text) {
  1701. global $CFG;
  1702. while (true) { //removing nested TRUSTTEXT
  1703. $orig = $text;
  1704. $text = str_replace(TRUSTTEXT, '', $text);
  1705. if (strcmp($orig, $text) === 0) {
  1706. return $text;
  1707. }
  1708. }
  1709. }
  1710. /**
  1711. * Mark text as trusted, such text may contain any HTML tags because the
  1712. * normal text cleaning will be bypassed.
  1713. * Please make sure that the text comes from trusted user before storing
  1714. * it into database!
  1715. */
  1716. function trusttext_mark($text) {
  1717. global $CFG;
  1718. if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
  1719. return TRUSTTEXT.$text;
  1720. } else {
  1721. return $text;
  1722. }
  1723. }
  1724. function trusttext_after_edit(&$text, $context) {
  1725. if (has_capability('moodle/site:trustcontent', $context)) {
  1726. $text = trusttext_strip($text);
  1727. $text = trusttext_mark($text);
  1728. } else {
  1729. $text = trusttext_strip($text);
  1730. }
  1731. }
  1732. function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
  1733. global $CFG;
  1734. $options = new object();
  1735. $options->smiley = false;
  1736. $options->filter = false;
  1737. if (!empty($CFG->enabletrusttext)
  1738. and has_capability('moodle/site:trustcontent', $context)
  1739. and trusttext_present($text)) {
  1740. $options->noclean = true;
  1741. } else {
  1742. $options->noclean = false;
  1743. }
  1744. $text = trusttext_strip($text);
  1745. if ($usehtmleditor) {
  1746. $text = format_text($text, $format, $options);
  1747. $format = FORMAT_HTML;
  1748. } else if (!$options->noclean){
  1749. $text = clean_text($text, $format);
  1750. }
  1751. }
  1752. /**
  1753. * Given raw text (eg typed in by a user), this function cleans it up
  1754. * and removes any nasty tags that could mess up Moodle pages.
  1755. *
  1756. * @uses FORMAT_MOODLE
  1757. * @uses FORMAT_PLAIN
  1758. * @uses ALLOWED_TAGS
  1759. * @param string $text The text to be cleaned
  1760. * @param int $format Identifier of the text format to be used
  1761. * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
  1762. * @return string The cleaned up text
  1763. */
  1764. function clean_text($text, $format=FORMAT_MOODLE) {
  1765. global $ALLOWED_TAGS, $CFG;
  1766. if (empty($text) or is_numeric($text)) {
  1767. return (string)$text;
  1768. }
  1769. switch ($format) {
  1770. case FORMAT_PLAIN:
  1771. return $text;
  1772. default:
  1773. if (!empty($CFG->enablehtmlpurifier)) {
  1774. //this is PHP5 only, the lib/setup.php contains a disabler for PHP4
  1775. $text = purify_html($text);
  1776. } else {
  1777. /// Fix non standard entity notations
  1778. $text = preg_replace('/&#0*([0-9]+);?/', "&#\\1;", $text);
  1779. $text = preg_replace('/&#x0*([0-9a-fA-F]+);?/', "&#x\\1;", $text);
  1780. $text = preg_replace('[\x00-\x08\x0b-\x0c\x0e-\x1f]', '', $text);
  1781. /// Remove tags that are not allowed
  1782. $text = strip_tags($text, $ALLOWED_TAGS);
  1783. /// Clean up embedded scripts and , using kses
  1784. $text = cleanAttributes($text);
  1785. /// Again remove tags that are not allowed
  1786. $text = strip_tags($text, $ALLOWED_TAGS);
  1787. }
  1788. /// Remove potential script events - some extra protection for undiscovered bugs in our code
  1789. $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
  1790. $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
  1791. return $text;
  1792. }
  1793. }
  1794. /**
  1795. * KSES replacement cleaning function - uses HTML Purifier.
  1796. *
  1797. * @global object
  1798. * @param string $text The (X)HTML string to purify
  1799. */
  1800. function purify_html($text) {
  1801. global $CFG;
  1802. // this can not be done only once because we sometimes need to reset the cache
  1803. $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
  1804. check_dir_exists($cachedir);
  1805. static $purifier = false;
  1806. if ($purifier === false) {
  1807. require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
  1808. $config = HTMLPurifier_Config::createDefault();
  1809. $config->set('HTML.DefinitionID', 'moodlehtml');
  1810. $config->set('HTML.DefinitionRev', 1);
  1811. $config->set('Cache.SerializerPath', $cachedir);
  1812. //$config->set('Cache.SerializerPermission', $CFG->directorypermissions); // it would be nice to get this upstream
  1813. $config->set('Core.NormalizeNewlines', false);
  1814. $config->set('Core.ConvertDocumentToFragment', true);
  1815. $config->set('Core.Encoding', 'UTF-8');
  1816. $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
  1817. $config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true));
  1818. $config->set('Attr.AllowedFrameTargets', array('_blank'));
  1819. if (!empty($CFG->allowobjectembed)) {
  1820. $config->set('HTML.SafeObject', true);
  1821. $config->set('Output.FlashCompat', true);
  1822. $config->set('HTML.SafeEmbed', true);
  1823. }
  1824. $def = $config->getHTMLDefinition(true);
  1825. $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
  1826. $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
  1827. $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
  1828. $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old anf future style multilang - only our hacked lang attribute
  1829. $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
  1830. $purifier = new HTMLPurifier($config);
  1831. }
  1832. $multilang = (strpos($text, 'class="multilang"') !== false);
  1833. if ($multilang) {
  1834. $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
  1835. }
  1836. $text = $purifier->purify($text);
  1837. if ($multilang) {
  1838. $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
  1839. }
  1840. return $text;
  1841. }
  1842. /**
  1843. * This function takes a string and examines it for HTML tags.
  1844. * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
  1845. * which checks for attributes and filters them for malicious content
  1846. * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
  1847. *
  1848. * @param string $str The string to be examined for html tags
  1849. * @return string
  1850. */
  1851. function cleanAttributes($str){
  1852. $result = preg_replace_callback(
  1853. '%(<[^>]*(>|$)|>)%m', #search for html tags
  1854. "cleanAttributes2",
  1855. $str
  1856. );
  1857. return $result;
  1858. }
  1859. /**
  1860. * This function takes a string with an html tag and strips out any unallowed
  1861. * protocols e.g. javascript:
  1862. * It calls ancillary functions in kses which are prefixed by kses
  1863. * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
  1864. *
  1865. * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
  1866. * element the html to be cleared
  1867. * @return string
  1868. */
  1869. function cleanAttributes2($htmlArray){
  1870. global $CFG, $ALLOWED_PROTOCOLS;
  1871. require_once($CFG->libdir .'/kses.php');
  1872. $htmlTag = $htmlArray[1];
  1873. if (substr($htmlTag, 0, 1) != '<') {
  1874. return '&gt;'; //a single character ">" detected
  1875. }
  1876. if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
  1877. return ''; // It's seriously malformed
  1878. }
  1879. $slash = trim($matches[1]); //trailing xhtml slash
  1880. $elem = $matches[2]; //the element name
  1881. $attrlist = $matches[3]; // the list of attributes as a string
  1882. $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
  1883. $attStr = '';
  1884. foreach ($attrArray as $arreach) {
  1885. $arreach['name'] = strtolower($arreach['name']);
  1886. if ($arreach['name'] == 'style') {
  1887. $value = $arreach['value'];
  1888. while (true) {
  1889. $prevvalue = $value;
  1890. $value = kses_no_null($value);
  1891. $value = preg_replace("/\/\*.*\*\//Us", '', $value);
  1892. $value = kses_decode_entities($value);
  1893. $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
  1894. $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
  1895. if ($value === $prevvalue) {
  1896. $arreach['value'] = $value;
  1897. break;
  1898. }
  1899. }
  1900. $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
  1901. $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
  1902. $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
  1903. $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
  1904. } else if ($arreach['name'] == 'href') {
  1905. //Adobe Acrobat Reader XSS protection
  1906. $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
  1907. }
  1908. $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
  1909. }
  1910. $xhtml_slash = '';
  1911. if (preg_match('%/\s*$%', $attrlist)) {
  1912. $xhtml_slash = ' /';
  1913. }
  1914. return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
  1915. }
  1916. /**
  1917. * Replaces all known smileys in the text with image equivalents
  1918. *
  1919. * @uses $CFG
  1920. * @param string $text Passed by reference. The string to search for smily strings.
  1921. * @return string
  1922. */
  1923. function replace_smilies(&$text) {
  1924. global $CFG;
  1925. if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
  1926. return;
  1927. }
  1928. $lang = current_language();
  1929. $emoticonstring = $CFG->emoticons;
  1930. static $e = array();
  1931. static $img = array();
  1932. static $emoticons = null;
  1933. if (is_null($emoticons)) {
  1934. $emoticons = array();
  1935. if ($emoticonstring) {
  1936. $items = explode('{;}', $CFG->emoticons);
  1937. foreach ($items as $item) {
  1938. $item = explode('{:}', $item);
  1939. $emoticons[$item[0]] = $item[1];
  1940. }
  1941. }
  1942. }
  1943. if (empty($img[$lang])) { /// After the first time this is not run again
  1944. $e[$lang] = array();
  1945. $img[$lang] = array();
  1946. foreach ($emoticons as $emoticon => $image){
  1947. $alttext = get_string($image, 'pix');
  1948. $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
  1949. $e[$lang][] = $emoticon;
  1950. $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
  1951. }
  1952. }
  1953. // Exclude from transformations all the code inside <script> tags
  1954. // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
  1955. // Based on code from glossary fiter by Williams Castillo.
  1956. // - Eloy
  1957. // Detect all the <script> zones to take out
  1958. $excludes = array();
  1959. preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
  1960. // Take out all the <script> zones from text
  1961. foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
  1962. $excludes['<+'.$key.'+>'] = $value;
  1963. }
  1964. if ($excludes) {
  1965. $text = str_replace($excludes,array_keys($excludes),$text);
  1966. }
  1967. /// this is the meat of the code - this is run every time
  1968. $text = str_replace($e[$lang], $img[$lang], $text);
  1969. // Recover all the <script> zones to text
  1970. if ($excludes) {
  1971. $text = str_replace(array_keys($excludes),$excludes,$text);
  1972. }
  1973. }
  1974. /**
  1975. * Given plain text, makes it into HTML as nicely as possible.
  1976. * May contain HTML tags already
  1977. *
  1978. * @uses $CFG
  1979. * @param string $text The string to convert.
  1980. * @param boolean $smiley Convert any smiley characters to smiley images?
  1981. * @param boolean $para If true then the returned string will be wrapped in paragraph tags
  1982. * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
  1983. * @return string
  1984. */
  1985. function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
  1986. ///
  1987. global $CFG;
  1988. /// Remove any whitespace that may be between HTML tags
  1989. $text = eregi_replace(">([[:space:]]+)<", "><", $text);
  1990. /// Remove any returns that precede or follow HTML tags
  1991. $text = eregi_replace("([\n\r])<", " <", $text);
  1992. $text = eregi_replace(">([\n\r])", "> ", $text);
  1993. convert_urls_into_links($text);
  1994. /// Make returns into HTML newlines.
  1995. if ($newlines) {
  1996. $text = nl2br($text);
  1997. }
  1998. /// Turn smileys into images.
  1999. if ($smiley) {
  2000. replace_smilies($text);
  2001. }
  2002. /// Wrap the whole thing in a paragraph tag if required
  2003. if ($para) {
  2004. return '<p>'.$text.'</p>';
  2005. } else {
  2006. return $text;
  2007. }
  2008. }
  2009. /**
  2010. * Given Markdown formatted text, make it into XHTML using external function
  2011. *
  2012. * @uses $CFG
  2013. * @param string $text The markdown formatted text to be converted.
  2014. * @return string Converted text
  2015. */
  2016. function markdown_to_html($text) {
  2017. global $CFG;
  2018. require_once($CFG->libdir .'/markdown.php');
  2019. return Markdown($text);
  2020. }
  2021. /**
  2022. * Given HTML text, make it into plain text using external function
  2023. *
  2024. * @param string $html The text to be converted.
  2025. * @param integer $width Width to wrap the text at. (optional, default 75 which
  2026. * is a good value for email. 0 means do not limit line length.)
  2027. * @return string plain text equivalent of the HTML.
  2028. */
  2029. function html_to_text($html, $width = 75) {
  2030. global $CFG;
  2031. require_once($CFG->libdir .'/html2text.php');
  2032. $h2t = new html2text($html, false, true, $width);
  2033. $result = $h2t->get_text();
  2034. return $result;
  2035. }
  2036. /**
  2037. * Given some text this function converts any URLs it finds into HTML links
  2038. *
  2039. * @param string $text Passed in by reference. The string to be searched for urls.
  2040. */
  2041. function convert_urls_into_links(&$text) {
  2042. //I've added img tags to this list of tags to ignore.
  2043. //See MDL-21168 for more info. A better way to ignore tags whether or not
  2044. //they are escaped partially or completely would be desirable. For example:
  2045. //<a href="blah">
  2046. //&lt;a href="blah"&gt;
  2047. //&lt;a href="blah">
  2048. $filterignoretagsopen = array('<a\s[^>]+?>');
  2049. $filterignoretagsclose = array('</a>');
  2050. filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
  2051. // Check if we support unicode modifiers in regular expressions. Cache it.
  2052. // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
  2053. // chars are going to arrive to URLs officially really soon (2010?)
  2054. // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
  2055. // Various ideas from: http://alanstorm.com/url_regex_explained
  2056. // Unicode check, negative assertion and other bits from Moodle.
  2057. static $unicoderegexp;
  2058. if (!isset($unicoderegexp)) {
  2059. $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silenty, returning false,
  2060. }
  2061. $unicoderegexp = false;//force non use of unicode modifiers. MDL-21296
  2062. if ($unicoderegexp) { //We can use unicode modifiers
  2063. $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
  2064. '<a href="\\1" target="_blank">\\1</a>', $text);
  2065. $text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
  2066. '<a href="http://\\1" target="_blank">\\1</a>', $text);
  2067. } else { //We cannot use unicode modifiers
  2068. $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
  2069. '<a href="\\1" target="_blank">\\1</a>', $text);
  2070. $text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
  2071. '<a href="http://\\1" target="_blank">\\1</a>', $text);
  2072. }
  2073. if (!empty($ignoretags)) {
  2074. $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
  2075. $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
  2076. }
  2077. }
  2078. /**
  2079. * This function will highlight search words in a given string
  2080. * It cares about HTML and will not ruin links. It's best to use
  2081. * this function after performing any conversions to HTML.
  2082. *
  2083. * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
  2084. * @param string $haystack The string (HTML) within which to highlight the search terms.
  2085. * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
  2086. * @param string $prefix the string to put before each search term found.
  2087. * @param string $suffix the string to put after each search term found.
  2088. * @return string The highlighted HTML.
  2089. */
  2090. function highlight($needle, $haystack, $matchcase = false,
  2091. $prefix = '<span class="highlight">', $suffix = '</span>') {
  2092. /// Quick bail-out in trivial cases.
  2093. if (empty($needle) or empty($haystack)) {
  2094. return $haystack;
  2095. }
  2096. /// Break up the search term into words, discard any -words and build a regexp.
  2097. $words = preg_split('/ +/', trim($needle));
  2098. foreach ($words as $index => $word) {
  2099. if (strpos($word, '-') === 0) {
  2100. unset($words[$index]);
  2101. } else if (strpos($word, '+') === 0) {
  2102. $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
  2103. } else {
  2104. $words[$index] = preg_quote($word, '/');
  2105. }
  2106. }
  2107. $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
  2108. if (!$matchcase) {
  2109. $regexp .= 'i';
  2110. }
  2111. /// Another chance to bail-out if $search was only -words
  2112. if (empty($words)) {
  2113. return $haystack;
  2114. }
  2115. /// Find all the HTML tags in the input, and store them in a placeholders array.
  2116. $placeholders = array();
  2117. $matches = array();
  2118. preg_match_all('/<[^>]*>/', $haystack, $matches);
  2119. foreach (array_unique($matches[0]) as $key => $htmltag) {
  2120. $placeholders['<|' . $key . '|>'] = $htmltag;
  2121. }
  2122. /// In $hastack, replace each HTML tag with the corresponding placeholder.
  2123. $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
  2124. /// In the resulting string, Do the highlighting.
  2125. $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
  2126. /// Turn the placeholders back into HTML tags.
  2127. $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
  2128. return $haystack;
  2129. }
  2130. /**
  2131. * This function will highlight instances of $needle in $haystack
  2132. * It's faster that the above function and doesn't care about
  2133. * HTML or anything.
  2134. *
  2135. * @param string $needle The string to search for
  2136. * @param string $haystack The string to search for $needle in
  2137. * @return string
  2138. */
  2139. function highlightfast($needle, $haystack) {
  2140. if (empty($needle) or empty($haystack)) {
  2141. return $haystack;
  2142. }
  2143. $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
  2144. if (count($parts) === 1) {
  2145. return $haystack;
  2146. }
  2147. $pos = 0;
  2148. foreach ($parts as $key => $part) {
  2149. $parts[$key] = substr($haystack, $pos, strlen($part));
  2150. $pos += strlen($part);
  2151. $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
  2152. $pos += strlen($needle);
  2153. }
  2154. return str_replace('<span class="highlight"></span>', '', join('', $parts));
  2155. }
  2156. /**
  2157. * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
  2158. * Internationalisation, for print_header and backup/restorelib.
  2159. * @param $dir Default false.
  2160. * @return string Attributes.
  2161. */
  2162. function get_html_lang($dir = false) {
  2163. $direction = '';
  2164. if ($dir) {
  2165. if (get_string('thisdirection') == 'rtl') {
  2166. $direction = ' dir="rtl"';
  2167. } else {
  2168. $direction = ' dir="ltr"';
  2169. }
  2170. }
  2171. //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
  2172. $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
  2173. @header('Content-Language: '.$language);
  2174. return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
  2175. }
  2176. /**
  2177. * Return the markup for the destination of the 'Skip to main content' links.
  2178. * Accessibility improvement for keyboard-only users.
  2179. * Used in course formats, /index.php and /course/index.php
  2180. * @return string HTML element.
  2181. */
  2182. function skip_main_destination() {
  2183. return '<span id="maincontent"></span>';
  2184. }
  2185. /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
  2186. /**
  2187. * Print a standard header
  2188. *
  2189. * @uses $USER
  2190. * @uses $CFG
  2191. * @uses $SESSION
  2192. * @param string $title Appears at the top of the window
  2193. * @param string $heading Appears at the top of the page
  2194. * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
  2195. * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
  2196. * @param string $meta Meta tags to be added to the header
  2197. * @param boolean $cache Should this page be cacheable?
  2198. * @param string $button HTML code for a button (usually for module editing)
  2199. * @param string $menu HTML code for a popup menu
  2200. * @param boolean $usexml use XML for this page
  2201. * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
  2202. * @param bool $return If true, return the visible elements of the header instead of echoing them.
  2203. */
  2204. function print_header ($title='', $heading='', $navigation='', $focus='',
  2205. $meta='', $cache=true, $button='&nbsp;', $menu='',
  2206. $usexml=false, $bodytags='', $return=false) {
  2207. global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
  2208. if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
  2209. debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
  2210. . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
  2211. }
  2212. $heading = format_string($heading); // Fix for MDL-8582
  2213. /// This makes sure that the header is never repeated twice on a page
  2214. if (defined('HEADER_PRINTED')) {
  2215. debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().');
  2216. return;
  2217. }
  2218. define('HEADER_PRINTED', 'true');
  2219. /// Perform a browser environment check for the flash version. Should only run once per login session.
  2220. if (isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
  2221. // Unfortunately we can't use require_js here and keep it all clean in 1.9 ...
  2222. // require_js(array('yui_yahoo', 'yui_event', 'yui_connection', $CFG->httpswwwroot."/lib/swfobject/swfobject.js"));
  2223. $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/yahoo/yahoo-min.js"></script>';
  2224. $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/event/event-min.js"></script>';
  2225. $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/connection/connection-min.js"></script>';
  2226. $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/swfobject/swfobject.js"></script>';
  2227. $meta .=
  2228. "<script type=\"text/javascript\">\n".
  2229. "//<![CDATA[\n".
  2230. " var flashversion = swfobject.getFlashPlayerVersion();\n".
  2231. " YAHOO.util.Connect.asyncRequest('GET','".$CFG->httpswwwroot."/login/environment.php?sesskey=".sesskey()."&flashversion='+flashversion.major+'.'+flashversion.minor+'.'+flashversion.release);\n".
  2232. "//]]>\n".
  2233. "</script>";
  2234. }
  2235. /// Add the required stylesheets
  2236. $stylesheetshtml = '';
  2237. foreach ($CFG->stylesheets as $stylesheet) {
  2238. $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
  2239. }
  2240. $meta = $stylesheetshtml.$meta;
  2241. /// Add the meta page from the themes if any were requested
  2242. $metapage = '';
  2243. if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
  2244. ob_start();
  2245. include_once($CFG->dirroot.'/theme/standard/meta.php');
  2246. $metapage .= ob_get_contents();
  2247. ob_end_clean();
  2248. }
  2249. if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
  2250. if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
  2251. ob_start();
  2252. include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
  2253. $metapage .= ob_get_contents();
  2254. ob_end_clean();
  2255. }
  2256. }
  2257. if (!isset($THEME->metainclude) || $THEME->metainclude) {
  2258. if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
  2259. ob_start();
  2260. include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
  2261. $metapage .= ob_get_contents();
  2262. ob_end_clean();
  2263. }
  2264. }
  2265. $meta = $meta."\n".$metapage;
  2266. $meta .= "\n".require_js('',1);
  2267. /// Set up some navigation variables
  2268. if (is_newnav($navigation)){
  2269. $home = false;
  2270. } else {
  2271. if ($navigation == 'home') {
  2272. $home = true;
  2273. $navigation = '';
  2274. } else {
  2275. $home = false;
  2276. }
  2277. }
  2278. /// This is another ugly hack to make navigation elements available to print_footer later
  2279. $THEME->title = $title;
  2280. $THEME->heading = $heading;
  2281. $THEME->navigation = $navigation;
  2282. $THEME->button = $button;
  2283. $THEME->menu = $menu;
  2284. $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
  2285. if ($button == '') {
  2286. $button = '&nbsp;';
  2287. }
  2288. if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
  2289. $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
  2290. if(!empty($title)) {
  2291. $title .= ' - ';
  2292. }
  2293. $title .= get_string('maintenancemode', 'admin');
  2294. }
  2295. if (!$menu and $navigation) {
  2296. if (empty($CFG->loginhttps)) {
  2297. $wwwroot = $CFG->wwwroot;
  2298. } else {
  2299. $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
  2300. }
  2301. $menu = user_login_string($COURSE);
  2302. }
  2303. if (isset($SESSION->justloggedin)) {
  2304. unset($SESSION->justloggedin);
  2305. if (!empty($CFG->displayloginfailures)) {
  2306. if (!empty($USER->username) and $USER->username != 'guest') {
  2307. if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
  2308. $menu .= '&nbsp;<font size="1">';
  2309. if (empty($count->accounts)) {
  2310. $menu .= get_string('failedloginattempts', '', $count);
  2311. } else {
  2312. $menu .= get_string('failedloginattemptsall', '', $count);
  2313. }
  2314. if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
  2315. $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
  2316. '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
  2317. }
  2318. $menu .= '</font>';
  2319. }
  2320. }
  2321. }
  2322. }
  2323. $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
  2324. "\n" . $meta . "\n";
  2325. if (!$usexml) {
  2326. @header('Content-Type: text/html; charset=utf-8');
  2327. }
  2328. @header('Content-Script-Type: text/javascript');
  2329. @header('Content-Style-Type: text/css');
  2330. //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
  2331. $direction = get_html_lang($dir=true);
  2332. if ($cache) { // Allow caching on "back" (but not on normal clicks)
  2333. @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
  2334. @header('Pragma: no-cache');
  2335. @header('Expires: ');
  2336. } else { // Do everything we can to always prevent clients and proxies caching
  2337. @header('Cache-Control: no-store, no-cache, must-revalidate');
  2338. @header('Cache-Control: post-check=0, pre-check=0', false);
  2339. @header('Pragma: no-cache');
  2340. @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
  2341. @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  2342. $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
  2343. $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
  2344. }
  2345. @header('Accept-Ranges: none');
  2346. $currentlanguage = current_language();
  2347. if (empty($usexml)) {
  2348. $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
  2349. } else {
  2350. $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
  2351. if(!$mathplayer) {
  2352. header('Content-Type: application/xhtml+xml');
  2353. }
  2354. echo '<?xml version="1.0" ?>'."\n";
  2355. if (!empty($CFG->xml_stylesheets)) {
  2356. $stylesheets = explode(';', $CFG->xml_stylesheets);
  2357. foreach ($stylesheets as $stylesheet) {
  2358. echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
  2359. }
  2360. }
  2361. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
  2362. if (!empty($CFG->xml_doctype_extra)) {
  2363. echo ' plus '. $CFG->xml_doctype_extra;
  2364. }
  2365. echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
  2366. $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
  2367. xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
  2368. xmlns:xlink=\"http://www.w3.org/1999/xlink\"
  2369. $direction";
  2370. if($mathplayer) {
  2371. $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
  2372. $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
  2373. $meta .= '</object>'."\n";
  2374. $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
  2375. }
  2376. }
  2377. // Clean up the title
  2378. $title = format_string($title); // fix for MDL-8582
  2379. $title = str_replace('"', '&quot;', $title);
  2380. // Create class and id for this page
  2381. page_id_and_class($pageid, $pageclass);
  2382. $pageclass .= ' course-'.$COURSE->id;
  2383. if (!isloggedin()) {
  2384. $pageclass .= ' notloggedin';
  2385. }
  2386. if (!empty($USER->editing)) {
  2387. $pageclass .= ' editing';
  2388. }
  2389. if (!empty($CFG->blocksdrag)) {
  2390. $pageclass .= ' drag';
  2391. }
  2392. $pageclass .= ' dir-'.get_string('thisdirection');
  2393. $pageclass .= ' lang-'.s($currentlanguage);
  2394. $bodytags .= ' class="'.s($pageclass).'" id="'.s($pageid).'"';
  2395. ob_start();
  2396. include($CFG->header);
  2397. $output = ob_get_contents();
  2398. ob_end_clean();
  2399. // container debugging info
  2400. $THEME->open_header_containers = open_containers();
  2401. // Skip to main content, see skip_main_destination().
  2402. if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
  2403. $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
  2404. if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
  2405. preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
  2406. }
  2407. $output = $matches[1]."\n". $skiplink .$matches[2];
  2408. }
  2409. $output = force_strict_header($output);
  2410. if (!empty($CFG->messaging)) {
  2411. $output .= message_popup_window();
  2412. }
  2413. // Add in any extra JavaScript libraries that occurred during the header
  2414. $output .= require_js('', 2);
  2415. if ($return) {
  2416. return $output;
  2417. } else {
  2418. echo $output;
  2419. }
  2420. }
  2421. /**
  2422. * Used to include JavaScript libraries.
  2423. *
  2424. * When the $lib parameter is given, the function will ensure that the
  2425. * named library is loaded onto the page - either in the HTML <head>,
  2426. * just after the header, or at an arbitrary later point in the page,
  2427. * depending on where this function is called.
  2428. *
  2429. * Libraries will not be included more than once, so this works like
  2430. * require_once in PHP.
  2431. *
  2432. * There are two special-case calls to this function which are both used only
  2433. * by weblib print_header:
  2434. * $extracthtml = 1: this is used before printing the header.
  2435. * It returns the script tag code that should go inside the <head>.
  2436. * $extracthtml = 2: this is used after printing the header and handles any
  2437. * require_js calls that occurred within the header itself.
  2438. *
  2439. * @param mixed $lib - string or array of strings
  2440. * string(s) should be the shortname for the library or the
  2441. * full path to the library file.
  2442. * @param int $extracthtml Do not set this parameter usually (leave 0), only
  2443. * weblib should set this to 1 or 2 in print_header function.
  2444. * @return mixed No return value, except when using $extracthtml it returns the html code.
  2445. */
  2446. function require_js($lib,$extracthtml=0) {
  2447. global $CFG;
  2448. static $loadlibs = array();
  2449. static $state = REQUIREJS_BEFOREHEADER;
  2450. static $latecode = '';
  2451. if (!empty($lib)) {
  2452. // Add the lib to the list of libs to be loaded, if it isn't already
  2453. // in the list.
  2454. if (is_array($lib)) {
  2455. foreach($lib as $singlelib) {
  2456. require_js($singlelib);
  2457. }
  2458. } else {
  2459. $libpath = ajax_get_lib($lib);
  2460. if (array_search($libpath, $loadlibs) === false) {
  2461. $loadlibs[] = $libpath;
  2462. // For state other than 0 we need to take action as well as just
  2463. // adding it to loadlibs
  2464. if($state != REQUIREJS_BEFOREHEADER) {
  2465. // Get the script statement for this library
  2466. $scriptstatement=get_require_js_code(array($libpath));
  2467. if($state == REQUIREJS_AFTERHEADER) {
  2468. // After the header, print it immediately
  2469. print $scriptstatement;
  2470. } else {
  2471. // Haven't finished the header yet. Add it after the
  2472. // header
  2473. $latecode .= $scriptstatement;
  2474. }
  2475. }
  2476. }
  2477. }
  2478. } else if($extracthtml==1) {
  2479. if($state !== REQUIREJS_BEFOREHEADER) {
  2480. debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
  2481. } else {
  2482. $state = REQUIREJS_INHEADER;
  2483. }
  2484. return get_require_js_code($loadlibs);
  2485. } else if($extracthtml==2) {
  2486. if($state !== REQUIREJS_INHEADER) {
  2487. debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
  2488. return '';
  2489. } else {
  2490. $state = REQUIREJS_AFTERHEADER;
  2491. return $latecode;
  2492. }
  2493. } else {
  2494. debugging('Unexpected value for $extracthtml');
  2495. }
  2496. }
  2497. /**
  2498. * Should not be called directly - use require_js. This function obtains the code
  2499. * (script tags) needed to include JavaScript libraries.
  2500. * @param array $loadlibs Array of library files to include
  2501. * @return string HTML code to include them
  2502. */
  2503. function get_require_js_code($loadlibs) {
  2504. global $CFG;
  2505. // Return the html needed to load the JavaScript files defined in
  2506. // our list of libs to be loaded.
  2507. $output = '';
  2508. foreach ($loadlibs as $loadlib) {
  2509. $output .= '<script type="text/javascript" ';
  2510. $output .= " src=\"$loadlib\"></script>\n";
  2511. if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
  2512. // Special case, we need the CSS too.
  2513. $output .= '<link type="text/css" rel="stylesheet" ';
  2514. $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
  2515. }
  2516. }
  2517. return $output;
  2518. }
  2519. /**
  2520. * Debugging aid: serve page as 'application/xhtml+xml' where possible,
  2521. * and substitute the XHTML strict document type.
  2522. * Note, requires the 'xmlns' fix in function print_header above.
  2523. * See: http://tracker.moodle.org/browse/MDL-7883
  2524. * TODO:
  2525. */
  2526. function force_strict_header($output) {
  2527. global $CFG;
  2528. $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  2529. $xsl = '/lib/xhtml.xsl';
  2530. if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
  2531. $ctype = 'Content-Type: ';
  2532. $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
  2533. if (isset($_SERVER['HTTP_ACCEPT'])
  2534. && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
  2535. //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
  2536. // Firefox et al.
  2537. $ctype .= 'application/xhtml+xml';
  2538. $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
  2539. } else if (file_exists($CFG->dirroot.$xsl)
  2540. && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
  2541. // XSL hack for IE 5+ on Windows.
  2542. //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
  2543. $www_xsl = $CFG->wwwroot .$xsl;
  2544. $ctype .= 'application/xml';
  2545. $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
  2546. $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
  2547. } else {
  2548. //ELSE: Mac/IE, old/non-XML browsers.
  2549. $ctype .= 'text/html';
  2550. $prolog = '';
  2551. }
  2552. @header($ctype.'; charset=utf-8');
  2553. $output = $prolog . $output;
  2554. // Test parser error-handling.
  2555. if (isset($_GET['error'])) {
  2556. $output .= "__ TEST: XML well-formed error < __\n";
  2557. }
  2558. }
  2559. $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
  2560. return $output;
  2561. }
  2562. /**
  2563. * This version of print_header is simpler because the course name does not have to be
  2564. * provided explicitly in the strings. It can be used on the site page as in courses
  2565. * Eventually all print_header could be replaced by print_header_simple
  2566. *
  2567. * @param string $title Appears at the top of the window
  2568. * @param string $heading Appears at the top of the page
  2569. * @param string $navigation Premade navigation string (for use as breadcrumbs links)
  2570. * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
  2571. * @param string $meta Meta tags to be added to the header
  2572. * @param boolean $cache Should this page be cacheable?
  2573. * @param string $button HTML code for a button (usually for module editing)
  2574. * @param string $menu HTML code for a popup menu
  2575. * @param boolean $usexml use XML for this page
  2576. * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
  2577. * @param bool $return If true, return the visible elements of the header instead of echoing them.
  2578. */
  2579. function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
  2580. $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
  2581. global $COURSE, $CFG;
  2582. // if we have no navigation specified, build it
  2583. if( empty($navigation) ){
  2584. $navigation = build_navigation('');
  2585. }
  2586. // If old style nav prepend course short name otherwise leave $navigation object alone
  2587. if (!is_newnav($navigation)) {
  2588. if ($COURSE->id != SITEID) {
  2589. $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
  2590. $navigation = $shortname.' '.$navigation;
  2591. }
  2592. }
  2593. $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
  2594. $cache, $button, $menu, $usexml, $bodytags, true);
  2595. if ($return) {
  2596. return $output;
  2597. } else {
  2598. echo $output;
  2599. }
  2600. }
  2601. /**
  2602. * Can provide a course object to make the footer contain a link to
  2603. * to the course home page, otherwise the link will go to the site home
  2604. * @uses $USER
  2605. * @param mixed $course course object, used for course link button or
  2606. * 'none' means no user link, only docs link
  2607. * 'empty' means nothing printed in footer
  2608. * 'home' special frontpage footer
  2609. * @param object $usercourse course used in user link
  2610. * @param boolean $return output as string
  2611. * @return mixed string or void
  2612. */
  2613. function print_footer($course=NULL, $usercourse=NULL, $return=false) {
  2614. global $USER, $CFG, $THEME, $COURSE;
  2615. if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
  2616. admin_externalpage_print_footer();
  2617. return;
  2618. }
  2619. /// Course links or special footer
  2620. if ($course) {
  2621. if ($course === 'empty') {
  2622. // special hack - sometimes we do not want even the docs link in footer
  2623. $output = '';
  2624. if (!empty($THEME->open_header_containers)) {
  2625. for ($i=0; $i<$THEME->open_header_containers; $i++) {
  2626. $output .= print_container_end_all(); // containers opened from header
  2627. }
  2628. } else {
  2629. //1.8 theme compatibility
  2630. $output .= "\n</div>"; // content div
  2631. }
  2632. $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
  2633. if ($return) {
  2634. return $output;
  2635. } else {
  2636. echo $output;
  2637. return;
  2638. }
  2639. } else if ($course === 'none') { // Don't print any links etc
  2640. $homelink = '';
  2641. $loggedinas = '';
  2642. $home = false;
  2643. } else if ($course === 'home') { // special case for site home page - please do not remove
  2644. $course = get_site();
  2645. $homelink = '<div class="sitelink">'.
  2646. '<a title="Moodle" href="http://moodle.org/">'.
  2647. '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
  2648. $home = true;
  2649. } else {
  2650. $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
  2651. '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
  2652. $home = false;
  2653. }
  2654. } else {
  2655. $course = get_site(); // Set course as site course by default
  2656. $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
  2657. $home = false;
  2658. }
  2659. /// Set up some other navigation links (passed from print_header by ugly hack)
  2660. $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
  2661. $title = isset($THEME->title) ? $THEME->title : '';
  2662. $button = isset($THEME->button) ? $THEME->button : '';
  2663. $heading = isset($THEME->heading) ? $THEME->heading : '';
  2664. $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
  2665. $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
  2666. /// Set the user link if necessary
  2667. if (!$usercourse and is_object($course)) {
  2668. $usercourse = $course;
  2669. }
  2670. if (!isset($loggedinas)) {
  2671. $loggedinas = user_login_string($usercourse, $USER);
  2672. }
  2673. if ($loggedinas == $menu) {
  2674. $menu = '';
  2675. }
  2676. /// there should be exactly the same number of open containers as after the header
  2677. if ($THEME->open_header_containers != open_containers()) {
  2678. debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
  2679. }
  2680. /// Provide some performance info if required
  2681. $performanceinfo = '';
  2682. if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
  2683. $perf = get_performance_info();
  2684. if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
  2685. error_log("PERF: " . $perf['txt']);
  2686. }
  2687. if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
  2688. $performanceinfo = $perf['html'];
  2689. }
  2690. }
  2691. /// Include the actual footer file
  2692. ob_start();
  2693. include($CFG->footer);
  2694. $output = ob_get_contents();
  2695. ob_end_clean();
  2696. if ($return) {
  2697. return $output;
  2698. } else {
  2699. echo $output;
  2700. }
  2701. }
  2702. /**
  2703. * Returns the name of the current theme
  2704. *
  2705. * @uses $CFG
  2706. * @uses $USER
  2707. * @uses $SESSION
  2708. * @uses $COURSE
  2709. * @uses $FULLME
  2710. * @return string
  2711. */
  2712. function current_theme() {
  2713. global $CFG, $USER, $SESSION, $COURSE, $FULLME;
  2714. if (empty($CFG->themeorder)) {
  2715. $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
  2716. } else {
  2717. $themeorder = $CFG->themeorder;
  2718. }
  2719. if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
  2720. require_once($CFG->dirroot.'/mnet/peer.php');
  2721. $mnet_peer = new mnet_peer();
  2722. $mnet_peer->set_id($USER->mnethostid);
  2723. }
  2724. $theme = '';
  2725. foreach ($themeorder as $themetype) {
  2726. if (!empty($theme)) continue;
  2727. switch ($themetype) {
  2728. case 'page': // Page theme is for special page-only themes set by code
  2729. if (!empty($CFG->pagetheme)) {
  2730. $theme = $CFG->pagetheme;
  2731. }
  2732. break;
  2733. case 'course':
  2734. if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
  2735. $theme = $COURSE->theme;
  2736. }
  2737. break;
  2738. case 'category':
  2739. if (!empty($CFG->allowcategorythemes)) {
  2740. /// Nasty hack to check if we're in a category page
  2741. if (stripos($FULLME, 'course/category.php') !== false) {
  2742. global $id;
  2743. if (!empty($id)) {
  2744. $theme = current_category_theme($id);
  2745. }
  2746. /// Otherwise check if we're in a course that has a category theme set
  2747. } else if (!empty($COURSE->category)) {
  2748. $theme = current_category_theme($COURSE->category);
  2749. }
  2750. }
  2751. break;
  2752. case 'session':
  2753. if (!empty($SESSION->theme)) {
  2754. $theme = $SESSION->theme;
  2755. }
  2756. break;
  2757. case 'user':
  2758. if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
  2759. if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
  2760. $theme = $mnet_peer->theme;
  2761. } else {
  2762. $theme = $USER->theme;
  2763. }
  2764. }
  2765. break;
  2766. case 'site':
  2767. if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
  2768. $theme = $mnet_peer->theme;
  2769. } else {
  2770. $theme = $CFG->theme;
  2771. }
  2772. break;
  2773. default:
  2774. /// do nothing
  2775. }
  2776. }
  2777. /// A final check in case 'site' was not included in $CFG->themeorder
  2778. if (empty($theme)) {
  2779. $theme = $CFG->theme;
  2780. }
  2781. return $theme;
  2782. }
  2783. /**
  2784. * Retrieves the category theme if one exists, otherwise checks the parent categories.
  2785. * Recursive function.
  2786. *
  2787. * @uses $COURSE
  2788. * @param integer $categoryid id of the category to check
  2789. * @return string theme name
  2790. */
  2791. function current_category_theme($categoryid=0) {
  2792. global $COURSE;
  2793. /// Use the COURSE global if the categoryid not set
  2794. if (empty($categoryid)) {
  2795. if (!empty($COURSE->category)) {
  2796. $categoryid = $COURSE->category;
  2797. } else {
  2798. return false;
  2799. }
  2800. }
  2801. /// Retrieve the current category
  2802. if ($category = get_record('course_categories', 'id', $categoryid)) {
  2803. /// Return the category theme if it exists
  2804. if (!empty($category->theme)) {
  2805. return $category->theme;
  2806. /// Otherwise try the parent category if one exists
  2807. } else if (!empty($category->parent)) {
  2808. return current_category_theme($category->parent);
  2809. }
  2810. /// Return false if we can't find the category record
  2811. } else {
  2812. return false;
  2813. }
  2814. }
  2815. /**
  2816. * This function is called by stylesheets to set up the header
  2817. * approriately as well as the current path
  2818. *
  2819. * @uses $CFG
  2820. * @param int $lastmodified ?
  2821. * @param int $lifetime ?
  2822. * @param string $thename ?
  2823. */
  2824. function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
  2825. global $CFG, $THEME;
  2826. // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
  2827. $lastmodified = time();
  2828. header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
  2829. header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
  2830. header('Cache-Control: max-age='. $lifetime);
  2831. header('Pragma: ');
  2832. header('Content-type: text/css'); // Correct MIME type
  2833. $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
  2834. if (empty($themename)) {
  2835. $themename = current_theme(); // So we have something. Normally not needed.
  2836. } else {
  2837. $themename = clean_param($themename, PARAM_SAFEDIR);
  2838. }
  2839. if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
  2840. unset($THEME);
  2841. include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
  2842. }
  2843. /// If this is the standard theme calling us, then find out what sheets we need
  2844. if ($themename == 'standard') {
  2845. if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
  2846. $THEME->sheets = $DEFAULT_SHEET_LIST;
  2847. } else if (empty($THEME->standardsheets)) { // We can stop right now!
  2848. echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
  2849. exit;
  2850. } else { // Use the provided subset only
  2851. $THEME->sheets = $THEME->standardsheets;
  2852. }
  2853. /// If we are a parent theme, then check for parent definitions
  2854. } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
  2855. if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
  2856. $THEME->sheets = $DEFAULT_SHEET_LIST;
  2857. } else if (empty($THEME->parentsheets)) { // We can stop right now!
  2858. echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
  2859. exit;
  2860. } else { // Use the provided subset only
  2861. $THEME->sheets = $THEME->parentsheets;
  2862. }
  2863. }
  2864. /// Work out the last modified date for this theme
  2865. foreach ($THEME->sheets as $sheet) {
  2866. if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
  2867. $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
  2868. if ($sheetmodified > $lastmodified) {
  2869. $lastmodified = $sheetmodified;
  2870. }
  2871. }
  2872. }
  2873. /// Get a list of all the files we want to include
  2874. $files = array();
  2875. foreach ($THEME->sheets as $sheet) {
  2876. $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
  2877. }
  2878. if ($themename == 'standard') { // Add any standard styles included in any modules
  2879. if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
  2880. if ($mods = get_list_of_plugins('mod')) {
  2881. foreach ($mods as $mod) {
  2882. if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
  2883. $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
  2884. }
  2885. }
  2886. }
  2887. }
  2888. if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
  2889. if ($mods = get_list_of_plugins('blocks')) {
  2890. foreach ($mods as $mod) {
  2891. if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
  2892. $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
  2893. }
  2894. }
  2895. }
  2896. }
  2897. if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
  2898. if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
  2899. foreach ($mods as $mod) {
  2900. if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
  2901. $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
  2902. }
  2903. }
  2904. }
  2905. }
  2906. if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
  2907. if ($reports = get_list_of_plugins('grade/report')) {
  2908. foreach ($reports as $report) {
  2909. if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
  2910. $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
  2911. }
  2912. }
  2913. }
  2914. }
  2915. if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
  2916. if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
  2917. $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
  2918. }
  2919. }
  2920. }
  2921. if ($files) {
  2922. /// Produce a list of all the files first
  2923. echo '/**************************************'."\n";
  2924. echo ' * THEME NAME: '.$themename."\n *\n";
  2925. echo ' * Files included in this sheet:'."\n *\n";
  2926. foreach ($files as $file) {
  2927. echo ' * '.$file[1]."\n";
  2928. }
  2929. echo ' **************************************/'."\n\n";
  2930. /// check if csscobstants is set
  2931. if (!empty($THEME->cssconstants)) {
  2932. require_once("$CFG->libdir/cssconstants.php");
  2933. /// Actually collect all the files in order.
  2934. $css = '';
  2935. foreach ($files as $file) {
  2936. $css .= '/***** '.$file[1].' start *****/'."\n\n";
  2937. $css .= file_get_contents($file[0].'/'.$file[1]);
  2938. $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
  2939. }
  2940. /// replace css_constants with their values
  2941. echo replace_cssconstants($css);
  2942. } else {
  2943. /// Actually output all the files in order.
  2944. if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
  2945. foreach ($files as $file) {
  2946. echo '/***** '.$file[1].' start *****/'."\n\n";
  2947. @include_once($file[0].'/'.$file[1]);
  2948. echo '/***** '.$file[1].' end *****/'."\n\n";
  2949. }
  2950. } else {
  2951. foreach ($files as $file) {
  2952. echo '/* @group '.$file[1].' */'."\n\n";
  2953. if (strstr($file[1], '.css') !== FALSE) {
  2954. echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
  2955. } else {
  2956. @include_once($file[0].'/'.$file[1]);
  2957. }
  2958. echo '/* @end */'."\n\n";
  2959. }
  2960. }
  2961. }
  2962. }
  2963. return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
  2964. }
  2965. function theme_setup($theme = '', $params=NULL) {
  2966. /// Sets up global variables related to themes
  2967. global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
  2968. /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
  2969. if (defined('HEADER_PRINTED')) {
  2970. return;
  2971. }
  2972. if (empty($theme)) {
  2973. $theme = current_theme();
  2974. }
  2975. /// If the theme doesn't exist for some reason then revert to standardwhite
  2976. if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
  2977. $CFG->theme = $theme = 'standardwhite';
  2978. }
  2979. /// Load up the theme config
  2980. $THEME = NULL; // Just to be sure
  2981. include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
  2982. /// Put together the parameters
  2983. if (!$params) {
  2984. $params = array();
  2985. }
  2986. if ($theme != $CFG->theme) {
  2987. $params[] = 'forceconfig='.$theme;
  2988. }
  2989. /// Force language too if required
  2990. if (!empty($THEME->langsheets)) {
  2991. $params[] = 'lang='.current_language();
  2992. }
  2993. /// Convert params to string
  2994. if ($params) {
  2995. $paramstring = '?'.implode('&', $params);
  2996. } else {
  2997. $paramstring = '';
  2998. }
  2999. /// Set up image paths
  3000. if(isset($CFG->smartpix) && $CFG->smartpix==1) {
  3001. if($CFG->slasharguments) { // Use this method if possible for better caching
  3002. $extra='';
  3003. } else {
  3004. $extra='?file=';
  3005. }
  3006. $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
  3007. $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
  3008. } else if (empty($THEME->custompix)) { // Could be set in the above file
  3009. $CFG->pixpath = $CFG->wwwroot .'/pix';
  3010. $CFG->modpixpath = $CFG->wwwroot .'/mod';
  3011. } else {
  3012. $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
  3013. $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
  3014. }
  3015. /// Header and footer paths
  3016. $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
  3017. $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
  3018. /// Define stylesheet loading order
  3019. $CFG->stylesheets = array();
  3020. if ($theme != 'standard') { /// The standard sheet is always loaded first
  3021. $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
  3022. }
  3023. if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
  3024. $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
  3025. }
  3026. $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
  3027. /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
  3028. if (!empty($HTTPSPAGEREQUIRED)) {
  3029. $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
  3030. $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
  3031. $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
  3032. foreach ($CFG->stylesheets as $key => $stylesheet) {
  3033. $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
  3034. }
  3035. }
  3036. // RTL support - only for RTL languages, add RTL CSS
  3037. if (get_string('thisdirection') == 'rtl') {
  3038. $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
  3039. $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
  3040. }
  3041. }
  3042. /**
  3043. * Returns text to be displayed to the user which reflects their login status
  3044. *
  3045. * @uses $CFG
  3046. * @uses $USER
  3047. * @param course $course {@link $COURSE} object containing course information
  3048. * @param user $user {@link $USER} object containing user information
  3049. * @return string
  3050. */
  3051. function user_login_string($course=NULL, $user=NULL) {
  3052. global $USER, $CFG, $SITE;
  3053. if (empty($user) and !empty($USER->id)) {
  3054. $user = $USER;
  3055. }
  3056. if (empty($course)) {
  3057. $course = $SITE;
  3058. }
  3059. if (!empty($user->realuser)) {
  3060. if ($realuser = get_record('user', 'id', $user->realuser)) {
  3061. $fullname = fullname($realuser, true);
  3062. $realuserinfo = " [<a $CFG->frametarget
  3063. href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
  3064. }
  3065. } else {
  3066. $realuserinfo = '';
  3067. }
  3068. if (empty($CFG->loginhttps)) {
  3069. $wwwroot = $CFG->wwwroot;
  3070. } else {
  3071. $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
  3072. }
  3073. if (empty($course->id)) {
  3074. // $course->id is not defined during installation
  3075. return '';
  3076. } else if (!empty($user->id)) {
  3077. $context = get_context_instance(CONTEXT_COURSE, $course->id);
  3078. $fullname = fullname($user, true);
  3079. $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
  3080. if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
  3081. $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
  3082. }
  3083. if (isset($user->username) && $user->username == 'guest') {
  3084. $loggedinas = $realuserinfo.get_string('loggedinasguest').
  3085. " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
  3086. } else if (!empty($user->access['rsw'][$context->path])) {
  3087. $rolename = '';
  3088. if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
  3089. $rolename = join("", role_fix_names(array($role->id=>$role->name), $context));
  3090. $rolename = ': '.format_string($rolename);
  3091. }
  3092. $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
  3093. " (<a $CFG->frametarget
  3094. href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
  3095. } else {
  3096. $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
  3097. " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
  3098. }
  3099. } else {
  3100. $loggedinas = get_string('loggedinnot', 'moodle').
  3101. " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
  3102. }
  3103. return '<div class="logininfo">'.$loggedinas.'</div>';
  3104. }
  3105. /**
  3106. * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
  3107. * If not it applies sensible defaults.
  3108. *
  3109. * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
  3110. * search forum block, etc. Important: these are 'silent' in a screen-reader
  3111. * (unlike &gt; &raquo;), and must be accompanied by text.
  3112. * @uses $THEME
  3113. */
  3114. function check_theme_arrows() {
  3115. global $THEME;
  3116. if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
  3117. // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
  3118. // Also OK in Win 9x/2K/IE 5.x
  3119. $THEME->rarrow = '&#x25BA;';
  3120. $THEME->larrow = '&#x25C4;';
  3121. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  3122. $uagent = '';
  3123. } else {
  3124. $uagent = $_SERVER['HTTP_USER_AGENT'];
  3125. }
  3126. if (false !== strpos($uagent, 'Opera')
  3127. || false !== strpos($uagent, 'Mac')) {
  3128. // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
  3129. // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
  3130. $THEME->rarrow = '&#x25B6;';
  3131. $THEME->larrow = '&#x25C0;';
  3132. }
  3133. elseif (false !== strpos($uagent, 'Konqueror')) {
  3134. $THEME->rarrow = '&rarr;';
  3135. $THEME->larrow = '&larr;';
  3136. }
  3137. elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
  3138. && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
  3139. // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
  3140. // To be safe, non-Unicode browsers!
  3141. $THEME->rarrow = '&gt;';
  3142. $THEME->larrow = '&lt;';
  3143. }
  3144. /// RTL support - in RTL languages, swap r and l arrows
  3145. if (right_to_left()) {
  3146. $t = $THEME->rarrow;
  3147. $THEME->rarrow = $THEME->larrow;
  3148. $THEME->larrow = $t;
  3149. }
  3150. }
  3151. }
  3152. /**
  3153. * Return the right arrow with text ('next'), and optionally embedded in a link.
  3154. * See function above, check_theme_arrows.
  3155. * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
  3156. * @param string $url An optional link to use in a surrounding HTML anchor.
  3157. * @param bool $accesshide True if text should be hidden (for screen readers only).
  3158. * @param string $addclass Additional class names for the link, or the arrow character.
  3159. * @return string HTML string.
  3160. */
  3161. function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
  3162. global $THEME;
  3163. check_theme_arrows();
  3164. $arrowclass = 'arrow ';
  3165. if (! $url) {
  3166. $arrowclass .= $addclass;
  3167. }
  3168. $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
  3169. $htmltext = '';
  3170. if ($text) {
  3171. $htmltext = $text.'&nbsp;';
  3172. if ($accesshide) {
  3173. $htmltext = get_accesshide($htmltext);
  3174. }
  3175. }
  3176. if ($url) {
  3177. $class = '';
  3178. if ($addclass) {
  3179. $class =" class=\"$addclass\"";
  3180. }
  3181. return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
  3182. }
  3183. return $htmltext.$arrow;
  3184. }
  3185. /**
  3186. * Return the left arrow with text ('previous'), and optionally embedded in a link.
  3187. * See function above, check_theme_arrows.
  3188. * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
  3189. * @param string $url An optional link to use in a surrounding HTML anchor.
  3190. * @param bool $accesshide True if text should be hidden (for screen readers only).
  3191. * @param string $addclass Additional class names for the link, or the arrow character.
  3192. * @return string HTML string.
  3193. */
  3194. function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
  3195. global $THEME;
  3196. check_theme_arrows();
  3197. $arrowclass = 'arrow ';
  3198. if (! $url) {
  3199. $arrowclass .= $addclass;
  3200. }
  3201. $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
  3202. $htmltext = '';
  3203. if ($text) {
  3204. $htmltext = '&nbsp;'.$text;
  3205. if ($accesshide) {
  3206. $htmltext = get_accesshide($htmltext);
  3207. }
  3208. }
  3209. if ($url) {
  3210. $class = '';
  3211. if ($addclass) {
  3212. $class =" class=\"$addclass\"";
  3213. }
  3214. return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
  3215. }
  3216. return $arrow.$htmltext;
  3217. }
  3218. /**
  3219. * Return a HTML element with the class "accesshide", for accessibility.
  3220. * Please use cautiously - where possible, text should be visible!
  3221. * @param string $text Plain text.
  3222. * @param string $elem Lowercase element name, default "span".
  3223. * @param string $class Additional classes for the element.
  3224. * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
  3225. * @return string HTML string.
  3226. */
  3227. function get_accesshide($text, $elem='span', $class='', $attrs='') {
  3228. return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
  3229. }
  3230. /**
  3231. * Return the breadcrumb trail navigation separator.
  3232. * @return string HTML string.
  3233. */
  3234. function get_separator() {
  3235. //Accessibility: the 'hidden' slash is preferred for screen readers.
  3236. return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
  3237. }
  3238. /**
  3239. * Prints breadcrumb trail of links, called in theme/-/header.html
  3240. *
  3241. * @uses $CFG
  3242. * @param mixed $navigation The breadcrumb navigation string to be printed
  3243. * @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
  3244. * @param boolean $return False to echo the breadcrumb string (default), true to return it.
  3245. * @return string or null, depending on $return.
  3246. */
  3247. function print_navigation ($navigation, $separator=0, $return=false) {
  3248. global $CFG, $THEME;
  3249. $output = '';
  3250. if (0 === $separator) {
  3251. $separator = get_separator();
  3252. }
  3253. else {
  3254. $separator = '<span class="sep">'. $separator .'</span>';
  3255. }
  3256. if ($navigation) {
  3257. if (is_newnav($navigation)) {
  3258. if ($return) {
  3259. return($navigation['navlinks']);
  3260. } else {
  3261. echo $navigation['navlinks'];
  3262. return;
  3263. }
  3264. } else {
  3265. debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
  3266. }
  3267. if (!is_array($navigation)) {
  3268. $ar = explode('->', $navigation);
  3269. $navigation = array();
  3270. foreach ($ar as $a) {
  3271. if (strpos($a, '</a>') === false) {
  3272. $navigation[] = array('title' => $a, 'url' => '');
  3273. } else {
  3274. if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
  3275. $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
  3276. }
  3277. }
  3278. }
  3279. }
  3280. if (! $site = get_site()) {
  3281. $site = new object();
  3282. $site->shortname = get_string('home');
  3283. }
  3284. //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
  3285. $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
  3286. $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
  3287. .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
  3288. && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
  3289. ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
  3290. foreach ($navigation as $navitem) {
  3291. $title = trim(strip_tags(format_string($navitem['title'], false)));
  3292. $url = $navitem['url'];
  3293. if (empty($url)) {
  3294. $output .= '<li>'."$separator $title</li>\n";
  3295. } else {
  3296. $output .= '<li>'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
  3297. .$url.'">'."$title</a>\n</li>\n";
  3298. }
  3299. }
  3300. $output .= "</ul>\n";
  3301. }
  3302. if ($return) {
  3303. return $output;
  3304. } else {
  3305. echo $output;
  3306. }
  3307. }
  3308. /**
  3309. * This function will build the navigation string to be used by print_header
  3310. * and others.
  3311. *
  3312. * It automatically generates the site and course level (if appropriate) links.
  3313. *
  3314. * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
  3315. * and activityinstances (e.g. 'General Developer Forum') navigation levels.
  3316. *
  3317. * If you want to add any further navigation links after the ones this function generates,
  3318. * the pass an array of extra link arrays like this:
  3319. * array(
  3320. * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
  3321. * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
  3322. * )
  3323. * The normal case is to just add one further link, for example 'Editing forum' after
  3324. * 'General Developer Forum', with no link.
  3325. * To do that, you need to pass
  3326. * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
  3327. * However, becuase this is a very common case, you can use a shortcut syntax, and just
  3328. * pass the string 'Editing forum', instead of an array as $extranavlinks.
  3329. *
  3330. * At the moment, the link types only have limited significance. Type 'activity' is
  3331. * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
  3332. * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
  3333. * This really needs to be documented better. In the mean time, try to be consistent, it will
  3334. * enable people to customise the navigation more in future.
  3335. *
  3336. * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
  3337. * If you get the $cm object using the function get_coursemodule_from_instance or
  3338. * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
  3339. * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
  3340. * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
  3341. * warning is printed in developer debug mode.
  3342. *
  3343. * @uses $CFG
  3344. * @uses $THEME
  3345. *
  3346. * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
  3347. * only want one extra item with no link, you can pass a string instead. If you don't want
  3348. * any extra links, pass an empty string.
  3349. * @param mixed $cm - optionally the $cm object, if you want this function to generate the
  3350. * activity and activityinstance levels of navigation too.
  3351. *
  3352. * @return $navigation as an object so it can be differentiated from old style
  3353. * navigation strings.
  3354. */
  3355. function build_navigation($extranavlinks, $cm = null) {
  3356. global $CFG, $COURSE;
  3357. if (is_string($extranavlinks)) {
  3358. if ($extranavlinks == '') {
  3359. $extranavlinks = array();
  3360. } else {
  3361. $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
  3362. }
  3363. }
  3364. $navlinks = array();
  3365. //Site name
  3366. if ($site = get_site()) {
  3367. $navlinks[] = array(
  3368. 'name' => format_string($site->shortname),
  3369. 'link' => "$CFG->wwwroot/",
  3370. 'type' => 'home');
  3371. }
  3372. // Course name, if appropriate.
  3373. if (isset($COURSE) && $COURSE->id != SITEID) {
  3374. $navlinks[] = array(
  3375. 'name' => format_string($COURSE->shortname),
  3376. 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
  3377. 'type' => 'course');
  3378. }
  3379. // Activity type and instance, if appropriate.
  3380. if (is_object($cm)) {
  3381. if (!isset($cm->modname)) {
  3382. debugging('The field $cm->modname should be set if you call build_navigation with '.
  3383. 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
  3384. 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
  3385. if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
  3386. error('Cannot get the module type in build navigation.');
  3387. }
  3388. }
  3389. if (!isset($cm->name)) {
  3390. debugging('The field $cm->name should be set if you call build_navigation with '.
  3391. 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
  3392. 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
  3393. if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
  3394. error('Cannot get the module name in build navigation.');
  3395. }
  3396. }
  3397. $navlinks[] = array(
  3398. 'name' => get_string('modulenameplural', $cm->modname),
  3399. 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
  3400. 'type' => 'activity');
  3401. $navlinks[] = array(
  3402. 'name' => format_string($cm->name),
  3403. 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
  3404. 'type' => 'activityinstance');
  3405. }
  3406. //Merge in extra navigation links
  3407. $navlinks = array_merge($navlinks, $extranavlinks);
  3408. // Work out whether we should be showing the activity (e.g. Forums) link.
  3409. // Note: build_navigation() is called from many places --
  3410. // install & upgrade for example -- where we cannot count on the
  3411. // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
  3412. if (!isset($CFG->hideactivitytypenavlink)) {
  3413. $CFG->hideactivitytypenavlink = 0;
  3414. }
  3415. if ($CFG->hideactivitytypenavlink == 2) {
  3416. $hideactivitylink = true;
  3417. } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
  3418. !empty($COURSE->id) && $COURSE->id != SITEID) {
  3419. if (!isset($COURSE->context)) {
  3420. $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
  3421. }
  3422. $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
  3423. } else {
  3424. $hideactivitylink = false;
  3425. }
  3426. //Construct an unordered list from $navlinks
  3427. //Accessibility: heading hidden from visual browsers by default.
  3428. $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
  3429. $lastindex = count($navlinks) - 1;
  3430. $i = -1; // Used to count the times, so we know when we get to the last item.
  3431. $first = true;
  3432. foreach ($navlinks as $navlink) {
  3433. $i++;
  3434. $last = ($i == $lastindex);
  3435. if (!is_array($navlink)) {
  3436. continue;
  3437. }
  3438. if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
  3439. continue;
  3440. }
  3441. if ($first) {
  3442. $navigation .= '<li class="first">';
  3443. } else {
  3444. $navigation .= '<li>';
  3445. }
  3446. if (!$first) {
  3447. $navigation .= get_separator();
  3448. }
  3449. if ((!empty($navlink['link'])) && !$last) {
  3450. $navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
  3451. }
  3452. $navigation .= "{$navlink['name']}";
  3453. if ((!empty($navlink['link'])) && !$last) {
  3454. $navigation .= "</a>";
  3455. }
  3456. $navigation .= "</li>";
  3457. $first = false;
  3458. }
  3459. $navigation .= "</ul>";
  3460. return(array('newnav' => true, 'navlinks' => $navigation));
  3461. }
  3462. /**
  3463. * Prints a string in a specified size (retained for backward compatibility)
  3464. *
  3465. * @param string $text The text to be displayed
  3466. * @param int $size The size to set the font for text display.
  3467. */
  3468. function print_headline($text, $size=2, $return=false) {
  3469. $output = print_heading($text, '', $size, true);
  3470. if ($return) {
  3471. return $output;
  3472. } else {
  3473. echo $output;
  3474. }
  3475. }
  3476. /**
  3477. * Prints text in a format for use in headings.
  3478. *
  3479. * @param string $text The text to be displayed
  3480. * @param string $align The alignment of the printed paragraph of text
  3481. * @param int $size The size to set the font for text display.
  3482. */
  3483. function print_heading($text, $align='', $size=2, $class='main', $return=false) {
  3484. if ($align) {
  3485. $align = ' style="text-align:'.$align.';"';
  3486. }
  3487. if ($class) {
  3488. $class = ' class="'.$class.'"';
  3489. }
  3490. $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
  3491. if ($return) {
  3492. return $output;
  3493. } else {
  3494. echo $output;
  3495. }
  3496. }
  3497. /**
  3498. * Centered heading with attached help button (same title text)
  3499. * and optional icon attached
  3500. *
  3501. * @param string $text The text to be displayed
  3502. * @param string $helppage The help page to link to
  3503. * @param string $module The module whose help should be linked to
  3504. * @param string $icon Image to display if needed
  3505. */
  3506. function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
  3507. $output = '';
  3508. $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
  3509. $output .= helpbutton($helppage, $text, $module, true, false, '', true);
  3510. $output .= '</h2>';
  3511. if ($return) {
  3512. return $output;
  3513. } else {
  3514. echo $output;
  3515. }
  3516. }
  3517. function print_heading_block($heading, $class='', $return=false) {
  3518. //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
  3519. $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
  3520. if ($return) {
  3521. return $output;
  3522. } else {
  3523. echo $output;
  3524. }
  3525. }
  3526. /**
  3527. * Print a link to continue on to another page.
  3528. *
  3529. * @uses $CFG
  3530. * @param string $link The url to create a link to.
  3531. */
  3532. function print_continue($link, $return=false) {
  3533. global $CFG;
  3534. // in case we are logging upgrade in admin/index.php stop it
  3535. if (function_exists('upgrade_log_finish')) {
  3536. upgrade_log_finish();
  3537. }
  3538. $output = '';
  3539. if ($link == '') {
  3540. if (!empty($_SERVER['HTTP_REFERER'])) {
  3541. $link = $_SERVER['HTTP_REFERER'];
  3542. $link = str_replace('&', '&amp;', $link); // make it valid XHTML
  3543. } else {
  3544. $link = $CFG->wwwroot .'/';
  3545. }
  3546. }
  3547. $options = array();
  3548. $linkparts = parse_url(str_replace('&amp;', '&', $link));
  3549. if (isset($linkparts['query'])) {
  3550. parse_str($linkparts['query'], $options);
  3551. }
  3552. $output .= '<div class="continuebutton">';
  3553. $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
  3554. $output .= '</div>'."\n";
  3555. if ($return) {
  3556. return $output;
  3557. } else {
  3558. echo $output;
  3559. }
  3560. }
  3561. /**
  3562. * Print a message in a standard themed box.
  3563. * Replaces print_simple_box (see deprecatedlib.php)
  3564. *
  3565. * @param string $message, the content of the box
  3566. * @param string $classes, space-separated class names.
  3567. * @param string $idbase
  3568. * @param boolean $return, return as string or just print it
  3569. * @return mixed string or void
  3570. */
  3571. function print_box($message, $classes='generalbox', $ids='', $return=false) {
  3572. $output = print_box_start($classes, $ids, true);
  3573. $output .= stripslashes_safe($message);
  3574. $output .= print_box_end(true);
  3575. if ($return) {
  3576. return $output;
  3577. } else {
  3578. echo $output;
  3579. }
  3580. }
  3581. /**
  3582. * Starts a box using divs
  3583. * Replaces print_simple_box_start (see deprecatedlib.php)
  3584. *
  3585. * @param string $classes, space-separated class names.
  3586. * @param string $idbase
  3587. * @param boolean $return, return as string or just print it
  3588. * @return mixed string or void
  3589. */
  3590. function print_box_start($classes='generalbox', $ids='', $return=false) {
  3591. global $THEME;
  3592. if (strpos($classes, 'clearfix') !== false) {
  3593. $clearfix = true;
  3594. $classes = trim(str_replace('clearfix', '', $classes));
  3595. } else {
  3596. $clearfix = false;
  3597. }
  3598. if (!empty($THEME->customcorners)) {
  3599. $classes .= ' ccbox box';
  3600. } else {
  3601. $classes .= ' box';
  3602. }
  3603. return print_container_start($clearfix, $classes, $ids, $return);
  3604. }
  3605. /**
  3606. * Simple function to end a box (see above)
  3607. * Replaces print_simple_box_end (see deprecatedlib.php)
  3608. *
  3609. * @param boolean $return, return as string or just print it
  3610. */
  3611. function print_box_end($return=false) {
  3612. return print_container_end($return);
  3613. }
  3614. /**
  3615. * Print a message in a standard themed container.
  3616. *
  3617. * @param string $message, the content of the container
  3618. * @param boolean $clearfix clear both sides
  3619. * @param string $classes, space-separated class names.
  3620. * @param string $idbase
  3621. * @param boolean $return, return as string or just print it
  3622. * @return string or void
  3623. */
  3624. function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
  3625. $output = print_container_start($clearfix, $classes, $idbase, true);
  3626. $output .= stripslashes_safe($message);
  3627. $output .= print_container_end(true);
  3628. if ($return) {
  3629. return $output;
  3630. } else {
  3631. echo $output;
  3632. }
  3633. }
  3634. /**
  3635. * Starts a container using divs
  3636. *
  3637. * @param boolean $clearfix clear both sides
  3638. * @param string $classes, space-separated class names.
  3639. * @param string $idbase
  3640. * @param boolean $return, return as string or just print it
  3641. * @return mixed string or void
  3642. */
  3643. function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
  3644. global $THEME;
  3645. if (!isset($THEME->open_containers)) {
  3646. $THEME->open_containers = array();
  3647. }
  3648. $THEME->open_containers[] = $idbase;
  3649. if (!empty($THEME->customcorners)) {
  3650. $output = _print_custom_corners_start($clearfix, $classes, $idbase);
  3651. } else {
  3652. if ($idbase) {
  3653. $id = ' id="'.$idbase.'"';
  3654. } else {
  3655. $id = '';
  3656. }
  3657. if ($clearfix) {
  3658. $clearfix = ' clearfix';
  3659. } else {
  3660. $clearfix = '';
  3661. }
  3662. if ($classes or $clearfix) {
  3663. $class = ' class="'.$classes.$clearfix.'"';
  3664. } else {
  3665. $class = '';
  3666. }
  3667. $output = '<div'.$id.$class.'>';
  3668. }
  3669. if ($return) {
  3670. return $output;
  3671. } else {
  3672. echo $output;
  3673. }
  3674. }
  3675. /**
  3676. * Simple function to end a container (see above)
  3677. * @param boolean $return, return as string or just print it
  3678. * @return mixed string or void
  3679. */
  3680. function print_container_end($return=false) {
  3681. global $THEME;
  3682. if (empty($THEME->open_containers)) {
  3683. debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
  3684. $idbase = '';
  3685. } else {
  3686. $idbase = array_pop($THEME->open_containers);
  3687. }
  3688. if (!empty($THEME->customcorners)) {
  3689. $output = _print_custom_corners_end($idbase);
  3690. } else {
  3691. $output = '</div>';
  3692. }
  3693. if ($return) {
  3694. return $output;
  3695. } else {
  3696. echo $output;
  3697. }
  3698. }
  3699. /**
  3700. * Returns number of currently open containers
  3701. * @return int number of open containers
  3702. */
  3703. function open_containers() {
  3704. global $THEME;
  3705. if (!isset($THEME->open_containers)) {
  3706. $THEME->open_containers = array();
  3707. }
  3708. return count($THEME->open_containers);
  3709. }
  3710. /**
  3711. * Force closing of open containers
  3712. * @param boolean $return, return as string or just print it
  3713. * @param int $keep number of containers to be kept open - usually theme or page containers
  3714. * @return mixed string or void
  3715. */
  3716. function print_container_end_all($return=false, $keep=0) {
  3717. $output = '';
  3718. while (open_containers() > $keep) {
  3719. $output .= print_container_end($return);
  3720. }
  3721. if ($return) {
  3722. return $output;
  3723. } else {
  3724. echo $output;
  3725. }
  3726. }
  3727. /**
  3728. * Internal function - do not use directly!
  3729. * Starting part of the surrounding divs for custom corners
  3730. *
  3731. * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
  3732. * @param string $classes
  3733. * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
  3734. * @return string
  3735. */
  3736. function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
  3737. /// Analise if we want ids for the custom corner elements
  3738. $id = '';
  3739. $idbt = '';
  3740. $idi1 = '';
  3741. $idi2 = '';
  3742. $idi3 = '';
  3743. if ($idbase) {
  3744. $id = 'id="'.$idbase.'" ';
  3745. $idbt = 'id="'.$idbase.'-bt" ';
  3746. $idi1 = 'id="'.$idbase.'-i1" ';
  3747. $idi2 = 'id="'.$idbase.'-i2" ';
  3748. $idi3 = 'id="'.$idbase.'-i3" ';
  3749. }
  3750. /// Calculate current level
  3751. $level = open_containers();
  3752. /// Output begins
  3753. $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
  3754. $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
  3755. $output .= "\n";
  3756. $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
  3757. $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
  3758. return $output;
  3759. }
  3760. /**
  3761. * Internal function - do not use directly!
  3762. * Ending part of the surrounding divs for custom corners
  3763. * @param string $idbase
  3764. * @return string
  3765. */
  3766. function _print_custom_corners_end($idbase) {
  3767. /// Analise if we want ids for the custom corner elements
  3768. $idbb = '';
  3769. if ($idbase) {
  3770. $idbb = 'id="' . $idbase . '-bb" ';
  3771. }
  3772. /// Output begins
  3773. $output = '</div></div></div>';
  3774. $output .= "\n";
  3775. $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
  3776. $output .= '</div>';
  3777. return $output;
  3778. }
  3779. /**
  3780. * Print a self contained form with a single submit button.
  3781. *
  3782. * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
  3783. * @param array $options these become hidden form fields, so these options get passed to the script at $link.
  3784. * @param string $label the caption that appears on the button.
  3785. * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
  3786. * @param string $target no longer used.
  3787. * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
  3788. * @param string $tooltip a tooltip to add to the button as a title attribute.
  3789. * @param boolean $disabled if true, the button will be disabled.
  3790. * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
  3791. * @return string / nothing depending on the $return paramter.
  3792. */
  3793. function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
  3794. $output = '';
  3795. $link = str_replace('"', '&quot;', $link); //basic XSS protection
  3796. $output .= '<div class="singlebutton">';
  3797. // taking target out, will need to add later target="'.$target.'"
  3798. $output .= '<form action="'. $link .'" method="'. $method .'">';
  3799. $output .= '<div>';
  3800. if ($options) {
  3801. foreach ($options as $name => $value) {
  3802. $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
  3803. }
  3804. }
  3805. if ($tooltip) {
  3806. $tooltip = 'title="' . s($tooltip) . '"';
  3807. } else {
  3808. $tooltip = '';
  3809. }
  3810. if ($disabled) {
  3811. $disabled = 'disabled="disabled"';
  3812. } else {
  3813. $disabled = '';
  3814. }
  3815. if ($jsconfirmmessage){
  3816. $jsconfirmmessage = addslashes_js($jsconfirmmessage);
  3817. $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
  3818. }
  3819. $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
  3820. if ($return) {
  3821. return $output;
  3822. } else {
  3823. echo $output;
  3824. }
  3825. }
  3826. /**
  3827. * Print a spacer image with the option of including a line break.
  3828. *
  3829. * @param int $height ?
  3830. * @param int $width ?
  3831. * @param boolean $br ?
  3832. * @todo Finish documenting this function
  3833. */
  3834. function print_spacer($height=1, $width=1, $br=true, $return=false) {
  3835. global $CFG;
  3836. $output = '';
  3837. $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
  3838. if ($br) {
  3839. $output .= '<br />'."\n";
  3840. }
  3841. if ($return) {
  3842. return $output;
  3843. } else {
  3844. echo $output;
  3845. }
  3846. }
  3847. /**
  3848. * Given the path to a picture file in a course, or a URL,
  3849. * this function includes the picture in the page.
  3850. *
  3851. * @param string $path ?
  3852. * @param int $courseid ?
  3853. * @param int $height ?
  3854. * @param int $width ?
  3855. * @param string $link ?
  3856. * @todo Finish documenting this function
  3857. */
  3858. function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
  3859. global $CFG;
  3860. $output = '';
  3861. if ($height) {
  3862. $height = 'height="'. $height .'"';
  3863. }
  3864. if ($width) {
  3865. $width = 'width="'. $width .'"';
  3866. }
  3867. if ($link) {
  3868. $output .= '<a href="'. $link .'">';
  3869. }
  3870. if (substr(strtolower($path), 0, 7) == 'http://') {
  3871. $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
  3872. } else if ($courseid) {
  3873. $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
  3874. require_once($CFG->libdir.'/filelib.php');
  3875. $output .= get_file_url("$courseid/$path");
  3876. $output .= '" />';
  3877. } else {
  3878. $output .= 'Error: must pass URL or course';
  3879. }
  3880. if ($link) {
  3881. $output .= '</a>';
  3882. }
  3883. if ($return) {
  3884. return $output;
  3885. } else {
  3886. echo $output;
  3887. }
  3888. }
  3889. /**
  3890. * Print the specified user's avatar.
  3891. *
  3892. * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
  3893. * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
  3894. * if at all possible, particularly for reports. It is very bad for performance.
  3895. * @param int $courseid The course id. Used when constructing the link to the user's profile.
  3896. * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
  3897. * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
  3898. * @param boolean $return If false print picture to current page, otherwise return the output as string
  3899. * @param boolean $link enclose printed image in a link the user's profile (default true).
  3900. * @param string $target link target attribute. Makes the profile open in a popup window.
  3901. * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
  3902. * decorative images, or where the username will be printed anyway.)
  3903. * @return string or nothing, depending on $return.
  3904. */
  3905. function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
  3906. global $CFG;
  3907. $needrec = false;
  3908. // only touch the DB if we are missing data...
  3909. if (is_object($user)) {
  3910. // Note - both picture and imagealt _can_ be empty
  3911. // what we are trying to see here is if they have been fetched
  3912. // from the DB. We should use isset() _except_ that some installs
  3913. // have those fields as nullable, and isset() will return false
  3914. // on null. The only safe thing is to ask array_key_exists()
  3915. // which works on objects. property_exists() isn't quite
  3916. // what we want here...
  3917. if (! (array_key_exists('picture', $user)
  3918. && ($alttext && array_key_exists('imagealt', $user)
  3919. || (isset($user->firstname) && isset($user->lastname)))) ) {
  3920. $needrec = true;
  3921. $user = $user->id;
  3922. }
  3923. } else {
  3924. if ($alttext) {
  3925. // we need firstname, lastname, imagealt, can't escape...
  3926. $needrec = true;
  3927. } else {
  3928. $userobj = new StdClass; // fake it to save DB traffic
  3929. $userobj->id = $user;
  3930. $userobj->picture = $picture;
  3931. $user = clone($userobj);
  3932. unset($userobj);
  3933. }
  3934. }
  3935. if ($needrec) {
  3936. $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
  3937. }
  3938. if ($link) {
  3939. $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
  3940. if ($target) {
  3941. $target='onclick="return openpopup(\''.$url.'\');"';
  3942. }
  3943. $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
  3944. } else {
  3945. $output = '';
  3946. }
  3947. if (empty($size)) {
  3948. $file = 'f2';
  3949. $size = 35;
  3950. } else if ($size === true or $size == 1) {
  3951. $file = 'f1';
  3952. $size = 100;
  3953. } else if ($size >= 50) {
  3954. $file = 'f1';
  3955. } else {
  3956. $file = 'f2';
  3957. }
  3958. $class = "userpicture";
  3959. if (is_null($picture) and !empty($user->picture)) {
  3960. $picture = $user->picture;
  3961. }
  3962. if ($picture) { // Print custom user picture
  3963. require_once($CFG->libdir.'/filelib.php');
  3964. $src = get_file_url($user->id.'/'.$file.'.jpg', null, 'user');
  3965. } else { // Print default user pictures (use theme version if available)
  3966. $class .= " defaultuserpic";
  3967. $src = "$CFG->pixpath/u/$file.png";
  3968. }
  3969. $imagealt = '';
  3970. if ($alttext) {
  3971. if (!empty($user->imagealt)) {
  3972. $imagealt = $user->imagealt;
  3973. } else {
  3974. $imagealt = get_string('pictureof','',fullname($user));
  3975. }
  3976. }
  3977. $output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" title=\"".s($imagealt)."\" alt=\"".s($imagealt).'" />';
  3978. if ($link) {
  3979. $output .= '</a>';
  3980. }
  3981. if ($return) {
  3982. return $output;
  3983. } else {
  3984. echo $output;
  3985. }
  3986. }
  3987. /**
  3988. * Prints a summary of a user in a nice little box.
  3989. *
  3990. * @uses $CFG
  3991. * @uses $USER
  3992. * @param user $user A {@link $USER} object representing a user
  3993. * @param course $course A {@link $COURSE} object representing a course
  3994. */
  3995. function print_user($user, $course, $messageselect=false, $return=false) {
  3996. global $CFG, $USER;
  3997. $output = '';
  3998. static $string;
  3999. static $datestring;
  4000. static $countries;
  4001. $context = get_context_instance(CONTEXT_COURSE, $course->id);
  4002. if (isset($user->context->id)) {
  4003. $usercontext = $user->context;
  4004. } else {
  4005. $usercontext = get_context_instance(CONTEXT_USER, $user->id);
  4006. }
  4007. if (empty($string)) { // Cache all the strings for the rest of the page
  4008. $string->email = get_string('email');
  4009. $string->city = get_string('city');
  4010. $string->lastaccess = get_string('lastaccess');
  4011. $string->activity = get_string('activity');
  4012. $string->unenrol = get_string('unenrol');
  4013. $string->loginas = get_string('loginas');
  4014. $string->fullprofile = get_string('fullprofile');
  4015. $string->role = get_string('role');
  4016. $string->name = get_string('name');
  4017. $string->never = get_string('never');
  4018. $datestring->day = get_string('day');
  4019. $datestring->days = get_string('days');
  4020. $datestring->hour = get_string('hour');
  4021. $datestring->hours = get_string('hours');
  4022. $datestring->min = get_string('min');
  4023. $datestring->mins = get_string('mins');
  4024. $datestring->sec = get_string('sec');
  4025. $datestring->secs = get_string('secs');
  4026. $datestring->year = get_string('year');
  4027. $datestring->years = get_string('years');
  4028. $countries = get_list_of_countries();
  4029. }
  4030. /// Get the hidden field list
  4031. if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
  4032. $hiddenfields = array();
  4033. } else {
  4034. $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
  4035. }
  4036. $output .= '<table class="userinfobox">';
  4037. $output .= '<tr>';
  4038. $output .= '<td class="left side">';
  4039. $output .= print_user_picture($user, $course->id, $user->picture, true, true);
  4040. $output .= '</td>';
  4041. $output .= '<td class="content">';
  4042. $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
  4043. $output .= '<div class="info">';
  4044. if (!empty($user->role) and ($user->role <> $course->teacher)) {
  4045. $output .= $string->role .': '. $user->role .'<br />';
  4046. }
  4047. if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
  4048. has_capability('moodle/course:viewhiddenuserfields', $context)) {
  4049. $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
  4050. }
  4051. if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
  4052. $output .= $string->city .': ';
  4053. if ($user->city && !isset($hiddenfields['city'])) {
  4054. $output .= $user->city;
  4055. }
  4056. if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
  4057. if ($user->city && !isset($hiddenfields['city'])) {
  4058. $output .= ', ';
  4059. }
  4060. $output .= $countries[$user->country];
  4061. }
  4062. $output .= '<br />';
  4063. }
  4064. if (!isset($hiddenfields['lastaccess'])) {
  4065. if ($user->lastaccess) {
  4066. $output .= $string->lastaccess .': '. userdate($user->lastaccess);
  4067. $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
  4068. } else {
  4069. $output .= $string->lastaccess .': '. $string->never;
  4070. }
  4071. }
  4072. $output .= '</div></td><td class="links">';
  4073. //link to blogs
  4074. if ($CFG->bloglevel > 0) {
  4075. $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
  4076. }
  4077. //link to notes
  4078. if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
  4079. $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
  4080. }
  4081. if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
  4082. $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
  4083. }
  4084. if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) { // I can unassing and user has some role
  4085. $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
  4086. }
  4087. if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
  4088. ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
  4089. $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
  4090. }
  4091. $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
  4092. if (!empty($messageselect)) {
  4093. $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
  4094. }
  4095. $output .= '</td></tr></table>';
  4096. if ($return) {
  4097. return $output;
  4098. } else {
  4099. echo $output;
  4100. }
  4101. }
  4102. /**
  4103. * Print a specified group's avatar.
  4104. *
  4105. * @param group $group A single {@link group} object OR array of groups.
  4106. * @param int $courseid The course ID.
  4107. * @param boolean $large Default small picture, or large.
  4108. * @param boolean $return If false print picture, otherwise return the output as string
  4109. * @param boolean $link Enclose image in a link to view specified course?
  4110. * @return string
  4111. * @todo Finish documenting this function
  4112. */
  4113. function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
  4114. global $CFG;
  4115. if (is_array($group)) {
  4116. $output = '';
  4117. foreach($group as $g) {
  4118. $output .= print_group_picture($g, $courseid, $large, true, $link);
  4119. }
  4120. if ($return) {
  4121. return $output;
  4122. } else {
  4123. echo $output;
  4124. return;
  4125. }
  4126. }
  4127. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  4128. // If there is no picture, do nothing
  4129. if (!$group->picture) {
  4130. return '';
  4131. }
  4132. // If picture is hidden, only show to those with course:managegroups
  4133. if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
  4134. return '';
  4135. }
  4136. if ($link or has_capability('moodle/site:accessallgroups', $context)) {
  4137. $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
  4138. } else {
  4139. $output = '';
  4140. }
  4141. if ($large) {
  4142. $file = 'f1';
  4143. } else {
  4144. $file = 'f2';
  4145. }
  4146. // Print custom group picture
  4147. require_once($CFG->libdir.'/filelib.php');
  4148. $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
  4149. $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
  4150. ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
  4151. if ($link or has_capability('moodle/site:accessallgroups', $context)) {
  4152. $output .= '</a>';
  4153. }
  4154. if ($return) {
  4155. return $output;
  4156. } else {
  4157. echo $output;
  4158. }
  4159. }
  4160. /**
  4161. * Print a png image.
  4162. *
  4163. * @param string $url ?
  4164. * @param int $sizex ?
  4165. * @param int $sizey ?
  4166. * @param boolean $return ?
  4167. * @param string $parameters ?
  4168. * @todo Finish documenting this function
  4169. */
  4170. function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
  4171. global $CFG;
  4172. static $recentIE;
  4173. if (!isset($recentIE)) {
  4174. $recentIE = check_browser_version('MSIE', '5.0');
  4175. }
  4176. if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
  4177. $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
  4178. ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
  4179. ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
  4180. "'$url', sizingMethod='scale') ".
  4181. ' '. $parameters .' />';
  4182. } else {
  4183. $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
  4184. }
  4185. if ($return) {
  4186. return $output;
  4187. } else {
  4188. echo $output;
  4189. }
  4190. }
  4191. /**
  4192. * Print a nicely formatted table.
  4193. *
  4194. * @param array $table is an object with several properties.
  4195. * <ul>
  4196. * <li>$table->head - An array of heading names.
  4197. * <li>$table->align - An array of column alignments
  4198. * <li>$table->size - An array of column sizes
  4199. * <li>$table->wrap - An array of "nowrap"s or nothing
  4200. * <li>$table->data[] - An array of arrays containing the data.
  4201. * <li>$table->width - A percentage of the page
  4202. * <li>$table->tablealign - Align the whole table
  4203. * <li>$table->cellpadding - Padding on each cell
  4204. * <li>$table->cellspacing - Spacing between cells
  4205. * <li>$table->class - class attribute to put on the table
  4206. * <li>$table->id - id attribute to put on the table.
  4207. * <li>$table->rowclass[] - classes to add to particular rows.
  4208. * <li>$table->summary - Description of the contents for screen readers.
  4209. * </ul>
  4210. * @param bool $return whether to return an output string or echo now
  4211. * @return boolean or $string
  4212. * @todo Finish documenting this function
  4213. */
  4214. function print_table($table, $return=false) {
  4215. $output = '';
  4216. if (isset($table->align)) {
  4217. foreach ($table->align as $key => $aa) {
  4218. if ($aa) {
  4219. $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
  4220. } else {
  4221. $align[$key] = '';
  4222. }
  4223. }
  4224. }
  4225. if (isset($table->size)) {
  4226. foreach ($table->size as $key => $ss) {
  4227. if ($ss) {
  4228. $size[$key] = ' width:'. $ss .';';
  4229. } else {
  4230. $size[$key] = '';
  4231. }
  4232. }
  4233. }
  4234. if (isset($table->wrap)) {
  4235. foreach ($table->wrap as $key => $ww) {
  4236. if ($ww) {
  4237. $wrap[$key] = ' white-space:nowrap;';
  4238. } else {
  4239. $wrap[$key] = '';
  4240. }
  4241. }
  4242. }
  4243. if (empty($table->width)) {
  4244. $table->width = '80%';
  4245. }
  4246. if (empty($table->tablealign)) {
  4247. $table->tablealign = 'center';
  4248. }
  4249. if (!isset($table->cellpadding)) {
  4250. $table->cellpadding = '5';
  4251. }
  4252. if (!isset($table->cellspacing)) {
  4253. $table->cellspacing = '1';
  4254. }
  4255. if (empty($table->class)) {
  4256. $table->class = 'generaltable';
  4257. }
  4258. $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
  4259. $output .= '<table width="'.$table->width.'" ';
  4260. if (!empty($table->summary)) {
  4261. $output .= " summary=\"$table->summary\"";
  4262. }
  4263. $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
  4264. $countcols = 0;
  4265. if (!empty($table->head)) {
  4266. $countcols = count($table->head);
  4267. $output .= '<tr>';
  4268. $keys=array_keys($table->head);
  4269. $lastkey = end($keys);
  4270. foreach ($table->head as $key => $heading) {
  4271. if (!isset($size[$key])) {
  4272. $size[$key] = '';
  4273. }
  4274. if (!isset($align[$key])) {
  4275. $align[$key] = '';
  4276. }
  4277. if ($key == $lastkey) {
  4278. $extraclass = ' lastcol';
  4279. } else {
  4280. $extraclass = '';
  4281. }
  4282. $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
  4283. }
  4284. $output .= '</tr>'."\n";
  4285. }
  4286. if (!empty($table->data)) {
  4287. $oddeven = 1;
  4288. $keys=array_keys($table->data);
  4289. $lastrowkey = end($keys);
  4290. foreach ($table->data as $key => $row) {
  4291. $oddeven = $oddeven ? 0 : 1;
  4292. if (!isset($table->rowclass[$key])) {
  4293. $table->rowclass[$key] = '';
  4294. }
  4295. if ($key == $lastrowkey) {
  4296. $table->rowclass[$key] .= ' lastrow';
  4297. }
  4298. $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
  4299. if ($row == 'hr' and $countcols) {
  4300. $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
  4301. } else { /// it's a normal row of data
  4302. $keys2=array_keys($row);
  4303. $lastkey = end($keys2);
  4304. foreach ($row as $key => $item) {
  4305. if (!isset($size[$key])) {
  4306. $size[$key] = '';
  4307. }
  4308. if (!isset($align[$key])) {
  4309. $align[$key] = '';
  4310. }
  4311. if (!isset($wrap[$key])) {
  4312. $wrap[$key] = '';
  4313. }
  4314. if ($key == $lastkey) {
  4315. $extraclass = ' lastcol';
  4316. } else {
  4317. $extraclass = '';
  4318. }
  4319. $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
  4320. }
  4321. }
  4322. $output .= '</tr>'."\n";
  4323. }
  4324. }
  4325. $output .= '</table>'."\n";
  4326. if ($return) {
  4327. return $output;
  4328. }
  4329. echo $output;
  4330. return true;
  4331. }
  4332. function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
  4333. static $strftimerecent = null;
  4334. $output = '';
  4335. if (is_null($viewfullnames)) {
  4336. $context = get_context_instance(CONTEXT_SYSTEM);
  4337. $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
  4338. }
  4339. if (is_null($strftimerecent)) {
  4340. $strftimerecent = get_string('strftimerecent');
  4341. }
  4342. $output .= '<div class="head">';
  4343. $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
  4344. $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
  4345. $output .= '</div>';
  4346. $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
  4347. if ($return) {
  4348. return $output;
  4349. } else {
  4350. echo $output;
  4351. }
  4352. }
  4353. /**
  4354. * Prints a basic textarea field.
  4355. *
  4356. * @uses $CFG
  4357. * @param boolean $usehtmleditor ?
  4358. * @param int $rows ?
  4359. * @param int $cols ?
  4360. * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
  4361. * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
  4362. * @param string $name ?
  4363. * @param string $value ?
  4364. * @param int $courseid ?
  4365. * @todo Finish documenting this function
  4366. */
  4367. function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
  4368. /// $width and height are legacy fields and no longer used as pixels like they used to be.
  4369. /// However, you can set them to zero to override the mincols and minrows values below.
  4370. global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
  4371. static $scriptcount = 0; // For loading the htmlarea script only once.
  4372. $mincols = 65;
  4373. $minrows = 10;
  4374. $str = '';
  4375. if ($id === '') {
  4376. $id = 'edit-'.$name;
  4377. }
  4378. if ( empty($CFG->editorsrc) ) { // for backward compatibility.
  4379. if (empty($courseid)) {
  4380. $courseid = $COURSE->id;
  4381. }
  4382. if ($usehtmleditor) {
  4383. if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
  4384. $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
  4385. // needed for course file area browsing in image insert plugin
  4386. $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
  4387. $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
  4388. } else {
  4389. $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
  4390. $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
  4391. $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
  4392. }
  4393. $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
  4394. $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php?id='.$courseid.'"></script>'."\n" : '';
  4395. $scriptcount++;
  4396. if ($height) { // Usually with legacy calls
  4397. if ($rows < $minrows) {
  4398. $rows = $minrows;
  4399. }
  4400. }
  4401. if ($width) { // Usually with legacy calls
  4402. if ($cols < $mincols) {
  4403. $cols = $mincols;
  4404. }
  4405. }
  4406. }
  4407. }
  4408. $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
  4409. if ($usehtmleditor) {
  4410. $str .= htmlspecialchars($value); // needed for editing of cleaned text!
  4411. } else {
  4412. $str .= s($value);
  4413. }
  4414. $str .= '</textarea>'."\n";
  4415. if ($usehtmleditor) {
  4416. // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
  4417. $str .= '<script type="text/javascript">
  4418. //<![CDATA[
  4419. document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
  4420. //]]>
  4421. </script>';
  4422. }
  4423. if ($return) {
  4424. return $str;
  4425. }
  4426. echo $str;
  4427. }
  4428. /**
  4429. * Sets up the HTML editor on textareas in the current page.
  4430. * If a field name is provided, then it will only be
  4431. * applied to that field - otherwise it will be used
  4432. * on every textarea in the page.
  4433. *
  4434. * In most cases no arguments need to be supplied
  4435. *
  4436. * @param string $name Form element to replace with HTMl editor by name
  4437. */
  4438. function use_html_editor($name='', $editorhidebuttons='', $id='') {
  4439. global $THEME;
  4440. $editor = 'editor_'.md5($name); //name might contain illegal characters
  4441. if ($id === '') {
  4442. $id = 'edit-'.$name;
  4443. }
  4444. echo "\n".'<script type="text/javascript" defer="defer">'."\n";
  4445. echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
  4446. echo "$editor = new HTMLArea('$id');\n";
  4447. echo "var config = $editor.config;\n";
  4448. echo print_editor_config($editorhidebuttons);
  4449. if (empty($THEME->htmleditorpostprocess)) {
  4450. if (empty($name)) {
  4451. echo "\nHTMLArea.replaceAll($editor.config);\n";
  4452. } else {
  4453. echo "\n$editor.generate();\n";
  4454. }
  4455. } else {
  4456. if (empty($name)) {
  4457. echo "\nvar HTML_name = '';";
  4458. } else {
  4459. echo "\nvar HTML_name = \"$name;\"";
  4460. }
  4461. echo "\nvar HTML_editor = $editor;";
  4462. }
  4463. echo '//]]>'."\n";
  4464. echo '</script>'."\n";
  4465. }
  4466. function print_editor_config($editorhidebuttons='', $return=false) {
  4467. global $CFG;
  4468. $str = "config.pageStyle = \"body {";
  4469. if (!(empty($CFG->editorbackgroundcolor))) {
  4470. $str .= " background-color: $CFG->editorbackgroundcolor;";
  4471. }
  4472. if (!(empty($CFG->editorfontfamily))) {
  4473. $str .= " font-family: $CFG->editorfontfamily;";
  4474. }
  4475. if (!(empty($CFG->editorfontsize))) {
  4476. $str .= " font-size: $CFG->editorfontsize;";
  4477. }
  4478. $str .= " }\";\n";
  4479. $str .= "config.killWordOnPaste = ";
  4480. $str .= (empty($CFG->editorkillword)) ? "false":"true";
  4481. $str .= ';'."\n";
  4482. $str .= 'config.fontname = {'."\n";
  4483. $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
  4484. $i = 1; // Counter is used to get rid of the last comma.
  4485. foreach ($fontlist as $fontline) {
  4486. if (!empty($fontline)) {
  4487. if ($i > 1) {
  4488. $str .= ','."\n";
  4489. }
  4490. list($fontkey, $fontvalue) = split(':', $fontline);
  4491. $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
  4492. $i++;
  4493. }
  4494. }
  4495. $str .= '};';
  4496. if (!empty($editorhidebuttons)) {
  4497. $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
  4498. } else if (!empty($CFG->editorhidebuttons)) {
  4499. $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
  4500. }
  4501. if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
  4502. $str .= print_speller_code($CFG->htmleditor, true);
  4503. }
  4504. if ($return) {
  4505. return $str;
  4506. }
  4507. echo $str;
  4508. }
  4509. /**
  4510. * Returns a turn edit on/off button for course in a self contained form.
  4511. * Used to be an icon, but it's now a simple form button
  4512. *
  4513. * Note that the caller is responsible for capchecks.
  4514. *
  4515. * @uses $CFG
  4516. * @uses $USER
  4517. * @param int $courseid The course to update by id as found in 'course' table
  4518. * @return string
  4519. */
  4520. function update_course_icon($courseid) {
  4521. global $CFG, $USER;
  4522. if (!empty($USER->editing)) {
  4523. $string = get_string('turneditingoff');
  4524. $edit = '0';
  4525. } else {
  4526. $string = get_string('turneditingon');
  4527. $edit = '1';
  4528. }
  4529. return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
  4530. '<div>'.
  4531. '<input type="hidden" name="id" value="'.$courseid.'" />'.
  4532. '<input type="hidden" name="edit" value="'.$edit.'" />'.
  4533. '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
  4534. '<input type="submit" value="'.$string.'" />'.
  4535. '</div></form>';
  4536. }
  4537. /**
  4538. * Returns a little popup menu for switching roles
  4539. *
  4540. * @uses $CFG
  4541. * @uses $USER
  4542. * @param int $courseid The course to update by id as found in 'course' table
  4543. * @return string
  4544. */
  4545. function switchroles_form($courseid) {
  4546. global $CFG, $USER;
  4547. if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
  4548. return '';
  4549. }
  4550. if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
  4551. $options = array();
  4552. $options['id'] = $courseid;
  4553. $options['sesskey'] = sesskey();
  4554. $options['switchrole'] = 0;
  4555. return print_single_button($CFG->wwwroot.'/course/view.php', $options,
  4556. get_string('switchrolereturn'), 'post', '_self', true);
  4557. }
  4558. if (has_capability('moodle/role:switchroles', $context)) {
  4559. if (!$roles = get_assignable_roles_for_switchrole($context)) {
  4560. return ''; // Nothing to show!
  4561. }
  4562. // unset default user role - it would not work
  4563. unset($roles[$CFG->guestroleid]);
  4564. return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
  4565. $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
  4566. }
  4567. return '';
  4568. }
  4569. /**
  4570. * Returns a turn edit on/off button for course in a self contained form.
  4571. * Used to be an icon, but it's now a simple form button
  4572. *
  4573. * @uses $CFG
  4574. * @uses $USER
  4575. * @param int $courseid The course to update by id as found in 'course' table
  4576. * @return string
  4577. */
  4578. function update_mymoodle_icon() {
  4579. global $CFG, $USER;
  4580. if (!empty($USER->editing)) {
  4581. $string = get_string('updatemymoodleoff');
  4582. $edit = '0';
  4583. } else {
  4584. $string = get_string('updatemymoodleon');
  4585. $edit = '1';
  4586. }
  4587. return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
  4588. "<div>".
  4589. "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
  4590. "<input type=\"submit\" value=\"$string\" /></div></form>";
  4591. }
  4592. /**
  4593. * Returns a turn edit on/off button for tag in a self contained form.
  4594. *
  4595. * @uses $CFG
  4596. * @uses $USER
  4597. * @return string
  4598. */
  4599. function update_tag_button($tagid) {
  4600. global $CFG, $USER;
  4601. if (!empty($USER->editing)) {
  4602. $string = get_string('turneditingoff');
  4603. $edit = '0';
  4604. } else {
  4605. $string = get_string('turneditingon');
  4606. $edit = '1';
  4607. }
  4608. return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
  4609. "<div>".
  4610. "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
  4611. "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
  4612. "<input type=\"submit\" value=\"$string\" /></div></form>";
  4613. }
  4614. /**
  4615. * Prints the editing button on a module "view" page
  4616. *
  4617. * @uses $CFG
  4618. * @param type description
  4619. * @todo Finish documenting this function
  4620. */
  4621. function update_module_button($moduleid, $courseid, $string) {
  4622. global $CFG, $USER;
  4623. if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
  4624. $string = get_string('updatethis', '', $string);
  4625. return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/mod.php\" onsubmit=\"this.target='{$CFG->framename}'; return true\">".//hack to allow edit on framed resources
  4626. "<div>".
  4627. "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
  4628. "<input type=\"hidden\" name=\"return\" value=\"true\" />".
  4629. "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
  4630. "<input type=\"submit\" value=\"$string\" /></div></form>";
  4631. } else {
  4632. return '';
  4633. }
  4634. }
  4635. /**
  4636. * Prints the editing button on search results listing
  4637. * For bulk move courses to another category
  4638. */
  4639. function update_categories_search_button($search,$page,$perpage) {
  4640. global $CFG, $USER;
  4641. // not sure if this capability is the best here
  4642. if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
  4643. if (!empty($USER->categoryediting)) {
  4644. $string = get_string("turneditingoff");
  4645. $edit = "off";
  4646. $perpage = 30;
  4647. } else {
  4648. $string = get_string("turneditingon");
  4649. $edit = "on";
  4650. }
  4651. return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
  4652. '<div>'.
  4653. "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
  4654. "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
  4655. "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
  4656. "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
  4657. "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
  4658. "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
  4659. }
  4660. }
  4661. /**
  4662. * Given a course and a (current) coursemodule
  4663. * This function returns a small popup menu with all the
  4664. * course activity modules in it, as a navigation menu
  4665. * The data is taken from the serialised array stored in
  4666. * the course record
  4667. *
  4668. * @param course $course A {@link $COURSE} object.
  4669. * @param course $cm A {@link $COURSE} object.
  4670. * @param string $targetwindow ?
  4671. * @return string
  4672. * @todo Finish documenting this function
  4673. */
  4674. function navmenu($course, $cm=NULL, $targetwindow='self') {
  4675. global $CFG, $THEME, $USER;
  4676. if (empty($THEME->navmenuwidth)) {
  4677. $width = 50;
  4678. } else {
  4679. $width = $THEME->navmenuwidth;
  4680. }
  4681. if ($cm) {
  4682. $cm = $cm->id;
  4683. }
  4684. if ($course->format == 'weeks') {
  4685. $strsection = get_string('week');
  4686. } else {
  4687. $strsection = get_string('topic');
  4688. }
  4689. $strjumpto = get_string('jumpto');
  4690. $modinfo = get_fast_modinfo($course);
  4691. $context = get_context_instance(CONTEXT_COURSE, $course->id);
  4692. $section = -1;
  4693. $selected = '';
  4694. $url = '';
  4695. $previousmod = NULL;
  4696. $backmod = NULL;
  4697. $nextmod = NULL;
  4698. $selectmod = NULL;
  4699. $logslink = NULL;
  4700. $flag = false;
  4701. $menu = array();
  4702. $menustyle = array();
  4703. $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
  4704. if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
  4705. $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
  4706. }
  4707. foreach ($modinfo->cms as $mod) {
  4708. if ($mod->modname == 'label') {
  4709. continue;
  4710. }
  4711. if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
  4712. break;
  4713. }
  4714. if (!$mod->uservisible) { // do not icnlude empty sections at all
  4715. continue;
  4716. }
  4717. if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
  4718. $thissection = $sections[$mod->sectionnum];
  4719. if ($thissection->visible or !$course->hiddensections or
  4720. has_capability('moodle/course:viewhiddensections', $context)) {
  4721. $thissection->summary = strip_tags(format_string($thissection->summary,true));
  4722. if ($course->format == 'weeks' or empty($thissection->summary)) {
  4723. $menu[] = '--'.$strsection ." ". $mod->sectionnum;
  4724. } else {
  4725. if (strlen($thissection->summary) < ($width-3)) {
  4726. $menu[] = '--'.$thissection->summary;
  4727. } else {
  4728. $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
  4729. }
  4730. }
  4731. $section = $mod->sectionnum;
  4732. } else {
  4733. // no activities from this hidden section shown
  4734. continue;
  4735. }
  4736. }
  4737. $url = $mod->modname.'/view.php?id='. $mod->id;
  4738. if ($flag) { // the current mod is the "next" mod
  4739. $nextmod = $mod;
  4740. $flag = false;
  4741. }
  4742. $localname = $mod->name;
  4743. if ($cm == $mod->id) {
  4744. $selected = $url;
  4745. $selectmod = $mod;
  4746. $backmod = $previousmod;
  4747. $flag = true; // set flag so we know to use next mod for "next"
  4748. $localname = $strjumpto;
  4749. $strjumpto = '';
  4750. } else {
  4751. $localname = strip_tags(format_string($localname,true));
  4752. $tl=textlib_get_instance();
  4753. if ($tl->strlen($localname) > ($width+5)) {
  4754. $localname = $tl->substr($localname, 0, $width).'...';
  4755. }
  4756. if (!$mod->visible) {
  4757. $localname = '('.$localname.')';
  4758. }
  4759. }
  4760. $menu[$url] = $localname;
  4761. if (empty($THEME->navmenuiconshide)) {
  4762. $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
  4763. }
  4764. $previousmod = $mod;
  4765. }
  4766. //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
  4767. if ($selectmod and has_capability('coursereport/log:view', $context)) {
  4768. $logstext = get_string('alllogs');
  4769. $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
  4770. $CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
  4771. $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
  4772. $course->id.'&amp;modid='.$selectmod->id.'">'.
  4773. '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
  4774. }
  4775. if ($backmod) {
  4776. $backtext= get_string('activityprev', 'access');
  4777. $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.$CFG->frametarget.' '.
  4778. 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
  4779. '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
  4780. '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
  4781. '</button></fieldset></form></li>';
  4782. }
  4783. if ($nextmod) {
  4784. $nexttext= get_string('activitynext', 'access');
  4785. $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.$CFG->frametarget.' '.
  4786. 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
  4787. '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
  4788. '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
  4789. '</button></fieldset></form></li>';
  4790. }
  4791. return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
  4792. '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
  4793. '', '', true, $targetwindow, '', $menustyle).'</li>'.
  4794. $nextmod . '</ul>'."\n".'</div>';
  4795. }
  4796. /**
  4797. * Given a course
  4798. * This function returns a small popup menu with all the
  4799. * course activity modules in it, as a navigation menu
  4800. * outputs a simple list structure in XHTML
  4801. * The data is taken from the serialised array stored in
  4802. * the course record
  4803. *
  4804. * @param course $course A {@link $COURSE} object.
  4805. * @return string
  4806. * @todo Finish documenting this function
  4807. */
  4808. function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
  4809. global $CFG;
  4810. $section = -1;
  4811. $url = '';
  4812. $menu = array();
  4813. $doneheading = false;
  4814. $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
  4815. $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
  4816. foreach ($modinfo->cms as $mod) {
  4817. if ($mod->modname == 'label') {
  4818. continue;
  4819. }
  4820. if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
  4821. break;
  4822. }
  4823. if (!$mod->uservisible) { // do not icnlude empty sections at all
  4824. continue;
  4825. }
  4826. if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
  4827. $thissection = $sections[$mod->sectionnum];
  4828. if ($thissection->visible or !$course->hiddensections or
  4829. has_capability('moodle/course:viewhiddensections', $coursecontext)) {
  4830. $thissection->summary = strip_tags(format_string($thissection->summary,true));
  4831. if (!$doneheading) {
  4832. $menu[] = '</ul></li>';
  4833. }
  4834. if ($course->format == 'weeks' or empty($thissection->summary)) {
  4835. $item = $strsection ." ". $mod->sectionnum;
  4836. } else {
  4837. if (strlen($thissection->summary) < ($width-3)) {
  4838. $item = $thissection->summary;
  4839. } else {
  4840. $item = substr($thissection->summary, 0, $width).'...';
  4841. }
  4842. }
  4843. $menu[] = '<li class="section"><span>'.$item.'</span>';
  4844. $menu[] = '<ul>';
  4845. $doneheading = true;
  4846. $section = $mod->sectionnum;
  4847. } else {
  4848. // no activities from this hidden section shown
  4849. continue;
  4850. }
  4851. }
  4852. $url = $mod->modname .'/view.php?id='. $mod->id;
  4853. $mod->name = strip_tags(format_string(urldecode($mod->name),true));
  4854. if (strlen($mod->name) > ($width+5)) {
  4855. $mod->name = substr($mod->name, 0, $width).'...';
  4856. }
  4857. if (!$mod->visible) {
  4858. $mod->name = '('.$mod->name.')';
  4859. }
  4860. $class = 'activity '.$mod->modname;
  4861. $class .= ($cmid == $mod->id) ? ' selected' : '';
  4862. $menu[] = '<li class="'.$class.'">'.
  4863. '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
  4864. '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
  4865. }
  4866. if ($doneheading) {
  4867. $menu[] = '</ul></li>';
  4868. }
  4869. $menu[] = '</ul></li></ul>';
  4870. return implode("\n", $menu);
  4871. }
  4872. /**
  4873. * Prints form items with the names $day, $month and $year
  4874. *
  4875. * @param string $day fieldname
  4876. * @param string $month fieldname
  4877. * @param string $year fieldname
  4878. * @param int $currenttime A default timestamp in GMT
  4879. * @param boolean $return
  4880. */
  4881. function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
  4882. if (!$currenttime) {
  4883. $currenttime = time();
  4884. }
  4885. $currentdate = usergetdate($currenttime);
  4886. for ($i=1; $i<=31; $i++) {
  4887. $days[$i] = $i;
  4888. }
  4889. for ($i=1; $i<=12; $i++) {
  4890. $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
  4891. }
  4892. for ($i=1970; $i<=2020; $i++) {
  4893. $years[$i] = $i;
  4894. }
  4895. // Build or print result
  4896. $result='';
  4897. // Note: There should probably be a fieldset around these fields as they are
  4898. // clearly grouped. However this causes problems with display. See Mozilla
  4899. // bug 474415
  4900. $result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
  4901. $result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
  4902. $result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
  4903. $result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
  4904. $result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
  4905. $result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
  4906. if ($return) {
  4907. return $result;
  4908. } else {
  4909. echo $result;
  4910. }
  4911. }
  4912. /**
  4913. *Prints form items with the names $hour and $minute
  4914. *
  4915. * @param string $hour fieldname
  4916. * @param string ? $minute fieldname
  4917. * @param $currenttime A default timestamp in GMT
  4918. * @param int $step minute spacing
  4919. * @param boolean $return
  4920. */
  4921. function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
  4922. if (!$currenttime) {
  4923. $currenttime = time();
  4924. }
  4925. $currentdate = usergetdate($currenttime);
  4926. if ($step != 1) {
  4927. $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
  4928. }
  4929. for ($i=0; $i<=23; $i++) {
  4930. $hours[$i] = sprintf("%02d",$i);
  4931. }
  4932. for ($i=0; $i<=59; $i+=$step) {
  4933. $minutes[$i] = sprintf("%02d",$i);
  4934. }
  4935. // Build or print result
  4936. $result='';
  4937. // Note: There should probably be a fieldset around these fields as they are
  4938. // clearly grouped. However this causes problems with display. See Mozilla
  4939. // bug 474415
  4940. $result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
  4941. $result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
  4942. $result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
  4943. $result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
  4944. if ($return) {
  4945. return $result;
  4946. } else {
  4947. echo $result;
  4948. }
  4949. }
  4950. /**
  4951. * Prints time limit value selector
  4952. *
  4953. * @uses $CFG
  4954. * @param int $timelimit default
  4955. * @param string $unit
  4956. * @param string $name
  4957. * @param boolean $return
  4958. */
  4959. function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
  4960. global $CFG;
  4961. if ($unit) {
  4962. $unit = ' '.$unit;
  4963. }
  4964. // Max timelimit is sessiontimeout - 10 minutes.
  4965. $maxvalue = ($CFG->sessiontimeout / 60) - 10;
  4966. for ($i=1; $i<=$maxvalue; $i++) {
  4967. $minutes[$i] = $i.$unit;
  4968. }
  4969. return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
  4970. }
  4971. /**
  4972. * Prints a grade menu (as part of an existing form) with help
  4973. * Showing all possible numerical grades and scales
  4974. *
  4975. * @uses $CFG
  4976. * @param int $courseid ?
  4977. * @param string $name ?
  4978. * @param string $current ?
  4979. * @param boolean $includenograde ?
  4980. * @todo Finish documenting this function
  4981. */
  4982. function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
  4983. global $CFG;
  4984. $output = '';
  4985. $strscale = get_string('scale');
  4986. $strscales = get_string('scales');
  4987. $scales = get_scales_menu($courseid);
  4988. foreach ($scales as $i => $scalename) {
  4989. $grades[-$i] = $strscale .': '. $scalename;
  4990. }
  4991. if ($includenograde) {
  4992. $grades[0] = get_string('nograde');
  4993. }
  4994. for ($i=100; $i>=1; $i--) {
  4995. $grades[$i] = $i;
  4996. }
  4997. $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
  4998. $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
  4999. $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
  5000. $linkobject, 400, 500, $strscales, 'none', true);
  5001. if ($return) {
  5002. return $output;
  5003. } else {
  5004. echo $output;
  5005. }
  5006. }
  5007. /**
  5008. * Prints a scale menu (as part of an existing form) including help button
  5009. * Just like {@link print_grade_menu()} but without the numeric grades
  5010. *
  5011. * @param int $courseid ?
  5012. * @param string $name ?
  5013. * @param string $current ?
  5014. * @todo Finish documenting this function
  5015. */
  5016. function print_scale_menu($courseid, $name, $current, $return=false) {
  5017. global $CFG;
  5018. $output = '';
  5019. $strscales = get_string('scales');
  5020. $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
  5021. $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
  5022. $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
  5023. $linkobject, 400, 500, $strscales, 'none', true);
  5024. if ($return) {
  5025. return $output;
  5026. } else {
  5027. echo $output;
  5028. }
  5029. }
  5030. /**
  5031. * Prints a help button about a scale
  5032. *
  5033. * @uses $CFG
  5034. * @param id $courseid ?
  5035. * @param object $scale ?
  5036. * @todo Finish documenting this function
  5037. */
  5038. function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
  5039. global $CFG;
  5040. $output = '';
  5041. $strscales = get_string('scales');
  5042. $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
  5043. $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
  5044. $linkobject, 400, 500, $scale->name, 'none', true);
  5045. if ($return) {
  5046. return $output;
  5047. } else {
  5048. echo $output;
  5049. }
  5050. }
  5051. /**
  5052. * Print an error page displaying an error message. New method - use this for new code.
  5053. *
  5054. * @uses $SESSION
  5055. * @uses $CFG
  5056. * @param string $errorcode The name of the string from error.php (or other specified file) to print
  5057. * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
  5058. * @param object $a Extra words and phrases that might be required in the error string
  5059. * @param array $extralocations An array of strings with other locations to look for string files
  5060. * @return does not return, terminates script
  5061. */
  5062. function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
  5063. global $CFG, $SESSION, $THEME;
  5064. if (empty($module) || $module === 'moodle' || $module === 'core') {
  5065. $module = 'error';
  5066. }
  5067. $message = get_string($errorcode, $module, $a, $extralocations);
  5068. if ($module === 'error' and strpos($message, '[[') === 0) {
  5069. //search in moodle file if error specified - needed for backwards compatibility
  5070. $message = get_string($errorcode, 'moodle', $a, $extralocations);
  5071. }
  5072. if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
  5073. if ( !empty($SESSION->fromurl) ) {
  5074. $link = $SESSION->fromurl;
  5075. unset($SESSION->fromurl);
  5076. } else {
  5077. $link = $CFG->wwwroot .'/';
  5078. }
  5079. }
  5080. // when printing an error the continue button should never link offsite
  5081. if (stripos($link, $CFG->wwwroot) === false &&
  5082. stripos($link, $CFG->httpswwwroot) === false) {
  5083. $link = $CFG->wwwroot.'/';
  5084. }
  5085. if (!empty($CFG->errordocroot)) {
  5086. $errordoclink = $CFG->errordocroot.'/en';
  5087. } else {
  5088. $errordoclink = get_doc_root();
  5089. if (is_null($errordoclink)) {
  5090. $lang = current_language();
  5091. $errordoclink = 'http://docs.moodle.org/19/'.$lang; //no doc links set. point to default.
  5092. }
  5093. }
  5094. if (defined('FULLME') && FULLME == 'cron') {
  5095. // Errors in cron should be mtrace'd.
  5096. mtrace($message);
  5097. die;
  5098. }
  5099. if ($module === 'error') {
  5100. $modulelink = 'moodle';
  5101. } else {
  5102. $modulelink = $module;
  5103. }
  5104. $message = clean_text('<p class="errormessage">'.$message.'</p>'.
  5105. '<p class="errorcode">'.
  5106. '<a href="'.$errordoclink.'/error/'.$modulelink.'/'.$errorcode.'">'.
  5107. get_string('moreinformation').'</a></p>');
  5108. if (! defined('HEADER_PRINTED')) {
  5109. //header not yet printed
  5110. @header('HTTP/1.0 404 Not Found');
  5111. print_header(get_string('error'));
  5112. } else {
  5113. print_container_end_all(false, $THEME->open_header_containers);
  5114. }
  5115. echo '<br />';
  5116. print_simple_box($message, '', '', '', '', 'errorbox');
  5117. debugging('Stack trace:', DEBUG_DEVELOPER);
  5118. // in case we are logging upgrade in admin/index.php stop it
  5119. if (function_exists('upgrade_log_finish')) {
  5120. upgrade_log_finish();
  5121. }
  5122. if (!empty($link)) {
  5123. print_continue($link);
  5124. }
  5125. print_footer();
  5126. for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
  5127. echo ' ';
  5128. }
  5129. die;
  5130. }
  5131. /**
  5132. * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
  5133. * Default errorcode is 1.
  5134. *
  5135. * Very useful for perl-like error-handling:
  5136. *
  5137. * do_somethting() or mdie("Something went wrong");
  5138. *
  5139. * @param string $msg Error message
  5140. * @param integer $errorcode Error code to emit
  5141. */
  5142. function mdie($msg='', $errorcode=1) {
  5143. trigger_error($msg);
  5144. exit($errorcode);
  5145. }
  5146. /**
  5147. * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
  5148. * Should be used only with htmleditor or textarea.
  5149. * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
  5150. * helpbutton.
  5151. * @return string
  5152. */
  5153. function editorhelpbutton(){
  5154. global $CFG, $SESSION;
  5155. $items = func_get_args();
  5156. $i = 1;
  5157. $urlparams = array();
  5158. $titles = array();
  5159. foreach ($items as $item){
  5160. if (is_array($item)){
  5161. $urlparams[] = "keyword$i=".urlencode($item[0]);
  5162. $urlparams[] = "title$i=".urlencode($item[1]);
  5163. if (isset($item[2])){
  5164. $urlparams[] = "module$i=".urlencode($item[2]);
  5165. }
  5166. $titles[] = trim($item[1], ". \t");
  5167. }elseif (is_string($item)){
  5168. $urlparams[] = "button$i=".urlencode($item);
  5169. switch ($item){
  5170. case 'reading' :
  5171. $titles[] = get_string("helpreading");
  5172. break;
  5173. case 'writing' :
  5174. $titles[] = get_string("helpwriting");
  5175. break;
  5176. case 'questions' :
  5177. $titles[] = get_string("helpquestions");
  5178. break;
  5179. case 'emoticons' :
  5180. $titles[] = get_string("helpemoticons");
  5181. break;
  5182. case 'richtext' :
  5183. $titles[] = get_string('helprichtext');
  5184. break;
  5185. case 'text' :
  5186. $titles[] = get_string('helptext');
  5187. break;
  5188. default :
  5189. error('Unknown help topic '.$item);
  5190. }
  5191. }
  5192. $i++;
  5193. }
  5194. if (count($titles)>1){
  5195. //join last two items with an 'and'
  5196. $a = new object();
  5197. $a->one = $titles[count($titles) - 2];
  5198. $a->two = $titles[count($titles) - 1];
  5199. $titles[count($titles) - 2] = get_string('and', '', $a);
  5200. unset($titles[count($titles) - 1]);
  5201. }
  5202. $alttag = join (', ', $titles);
  5203. $paramstring = join('&', $urlparams);
  5204. $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
  5205. return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
  5206. }
  5207. /**
  5208. * Print a help button.
  5209. *
  5210. * @uses $CFG
  5211. * @param string $page The keyword that defines a help page
  5212. * @param string $title The title of links, rollover tips, alt tags etc
  5213. * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
  5214. * @param string $module Which module is the page defined in
  5215. * @param mixed $image Use a help image for the link? (true/false/"both")
  5216. * @param boolean $linktext If true, display the title next to the help icon.
  5217. * @param string $text If defined then this text is used in the page, and
  5218. * the $page variable is ignored.
  5219. * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
  5220. * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
  5221. * @return string
  5222. * @todo Finish documenting this function
  5223. */
  5224. function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
  5225. $imagetext='') {
  5226. global $CFG, $COURSE;
  5227. //warning if ever $text parameter is used
  5228. //$text option won't work properly because the text needs to be always cleaned and,
  5229. // when cleaned... html tags always break, so it's unusable.
  5230. if ( isset($text) && $text!='') {
  5231. debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER);
  5232. }
  5233. // fix for MDL-7734
  5234. if (!empty($COURSE->lang)) {
  5235. $forcelang = $COURSE->lang;
  5236. } else {
  5237. $forcelang = '';
  5238. }
  5239. if ($module == '') {
  5240. $module = 'moodle';
  5241. }
  5242. if ($title == '' && $linktext == '') {
  5243. debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
  5244. }
  5245. // Warn users about new window for Accessibility
  5246. $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
  5247. $linkobject = '';
  5248. if ($image) {
  5249. if ($linktext) {
  5250. // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
  5251. $linkobject .= $title.'&nbsp;';
  5252. $tooltip = get_string('helpwiththis');
  5253. }
  5254. if ($imagetext) {
  5255. $linkobject .= $imagetext;
  5256. } else {
  5257. $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
  5258. $CFG->pixpath .'/help.gif" />';
  5259. }
  5260. } else {
  5261. $linkobject .= $tooltip;
  5262. }
  5263. // fix for MDL-7734
  5264. if ($text) {
  5265. $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
  5266. } else {
  5267. $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
  5268. }
  5269. $link = '<span class="helplink">'.
  5270. link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
  5271. '</span>';
  5272. if ($return) {
  5273. return $link;
  5274. } else {
  5275. echo $link;
  5276. }
  5277. }
  5278. /**
  5279. * Print a help button.
  5280. *
  5281. * Prints a special help button that is a link to the "live" emoticon popup
  5282. * @uses $CFG
  5283. * @uses $SESSION
  5284. * @param string $form ?
  5285. * @param string $field ?
  5286. * @todo Finish documenting this function
  5287. */
  5288. function emoticonhelpbutton($form, $field, $return = false) {
  5289. global $CFG, $SESSION;
  5290. $SESSION->inserttextform = $form;
  5291. $SESSION->inserttextfield = $field;
  5292. $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
  5293. $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
  5294. if (!$return){
  5295. echo $help;
  5296. } else {
  5297. return $help;
  5298. }
  5299. }
  5300. /**
  5301. * Print a help button.
  5302. *
  5303. * Prints a special help button for html editors (htmlarea in this case)
  5304. * @uses $CFG
  5305. */
  5306. function editorshortcutshelpbutton() {
  5307. global $CFG;
  5308. $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
  5309. get_string('editorshortcutkeys').'" class="iconkbhelp" />';
  5310. return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
  5311. }
  5312. /**
  5313. * Print a message and exit.
  5314. *
  5315. * @uses $CFG
  5316. * @param string $message ?
  5317. * @param string $link ?
  5318. * @todo Finish documenting this function
  5319. */
  5320. function notice ($message, $link='', $course=NULL) {
  5321. global $CFG, $SITE, $THEME, $COURSE;
  5322. $message = clean_text($message); // In case nasties are in here
  5323. if (defined('FULLME') && FULLME == 'cron') {
  5324. // notices in cron should be mtrace'd.
  5325. mtrace($message);
  5326. die;
  5327. }
  5328. if (! defined('HEADER_PRINTED')) {
  5329. //header not yet printed
  5330. print_header(get_string('notice'));
  5331. } else {
  5332. print_container_end_all(false, $THEME->open_header_containers);
  5333. }
  5334. print_box($message, 'generalbox', 'notice');
  5335. print_continue($link);
  5336. if (empty($course)) {
  5337. print_footer($COURSE);
  5338. } else {
  5339. print_footer($course);
  5340. }
  5341. exit;
  5342. }
  5343. /**
  5344. * Print a message along with "Yes" and "No" links for the user to continue.
  5345. *
  5346. * @param string $message The text to display
  5347. * @param string $linkyes The link to take the user to if they choose "Yes"
  5348. * @param string $linkno The link to take the user to if they choose "No"
  5349. * TODO Document remaining arguments
  5350. */
  5351. function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
  5352. global $CFG;
  5353. $message = clean_text($message);
  5354. $linkyes = clean_text($linkyes);
  5355. $linkno = clean_text($linkno);
  5356. print_box_start('generalbox', 'notice');
  5357. echo '<p>'. $message .'</p>';
  5358. echo '<div class="buttons">';
  5359. print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
  5360. print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
  5361. echo '</div>';
  5362. print_box_end();
  5363. }
  5364. /**
  5365. * Provide an definition of error_get_last for PHP before 5.2.0. This simply
  5366. * returns NULL, since there is not way to get the right answer.
  5367. */
  5368. if (!function_exists('error_get_last')) {
  5369. // the eval is needed to prevent PHP 5.2+ from getting a parse error!
  5370. eval('
  5371. function error_get_last() {
  5372. return NULL;
  5373. }
  5374. ');
  5375. }
  5376. /**
  5377. * Redirects the user to another page, after printing a notice
  5378. *
  5379. * @param string $url The url to take the user to
  5380. * @param string $message The text message to display to the user about the redirect, if any
  5381. * @param string $delay How long before refreshing to the new page at $url?
  5382. * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
  5383. * however, this is not true for javascript. Therefore we
  5384. * first decode all entities in $url (since we cannot rely on)
  5385. * the correct input) and then encode for where it's needed
  5386. * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
  5387. */
  5388. function redirect($url, $message='', $delay=-1) {
  5389. global $CFG, $THEME;
  5390. if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
  5391. $url = sid_process_url($url);
  5392. }
  5393. $message = clean_text($message);
  5394. // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
  5395. // (In practice browsers accept relative paths - but still, might as well do it properly.)
  5396. // This code turns relative into absolute.
  5397. if (!preg_match('|^[a-z]+:|', $url)) {
  5398. // Get host name http://www.wherever.com
  5399. $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
  5400. if (preg_match('|^/|', $url)) {
  5401. // URLs beginning with / are relative to web server root so we just add them in
  5402. $url = $hostpart.$url;
  5403. } else {
  5404. // URLs not beginning with / are relative to path of current script, so add that on.
  5405. $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
  5406. }
  5407. // Replace all ..s
  5408. while (true) {
  5409. $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
  5410. if ($newurl == $url) {
  5411. break;
  5412. }
  5413. $url = $newurl;
  5414. }
  5415. }
  5416. // Sanitise url - we can not rely on our URL cleaning
  5417. // because it does not support all valid external URLs
  5418. $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
  5419. $url = str_replace('"', '%22', $url);
  5420. $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
  5421. $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
  5422. $url = str_replace('&amp;', '&', $encodedurl);
  5423. /// At developer debug level. Don't redirect if errors have been printed on screen.
  5424. /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
  5425. $lasterror = error_get_last();
  5426. $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
  5427. $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
  5428. if ($errorprinted) {
  5429. $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
  5430. }
  5431. $performanceinfo = '';
  5432. if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
  5433. if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
  5434. $perf = get_performance_info();
  5435. error_log("PERF: " . $perf['txt']);
  5436. }
  5437. }
  5438. /// when no message and header printed yet, try to redirect
  5439. if (empty($message) and !defined('HEADER_PRINTED')) {
  5440. $delay = 0;
  5441. //try header redirection first
  5442. @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
  5443. @header('Location: '.$url);
  5444. //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
  5445. echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
  5446. echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
  5447. die;
  5448. }
  5449. if ($delay == -1) {
  5450. $delay = 3; // if no delay specified wait 3 seconds
  5451. }
  5452. if (! defined('HEADER_PRINTED')) {
  5453. // this type of redirect might not be working in some browsers - such as lynx :-(
  5454. print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
  5455. $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
  5456. } else {
  5457. print_container_end_all(false, $THEME->open_header_containers);
  5458. }
  5459. echo '<div id="redirect">';
  5460. echo '<div id="message">' . $message . '</div>';
  5461. echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
  5462. echo '</div>';
  5463. if (!$errorprinted) {
  5464. ?>
  5465. <script type="text/javascript">
  5466. //<![CDATA[
  5467. function redirect() {
  5468. document.location.replace('<?php echo addslashes_js($url) ?>');
  5469. }
  5470. setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
  5471. //]]>
  5472. </script>
  5473. <?php
  5474. }
  5475. $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
  5476. print_footer('none');
  5477. die;
  5478. }
  5479. /**
  5480. * Print a bold message in an optional color.
  5481. *
  5482. * @param string $message The message to print out
  5483. * @param string $style Optional style to display message text in
  5484. * @param string $align Alignment option
  5485. * @param bool $return whether to return an output string or echo now
  5486. */
  5487. function notify($message, $style='notifyproblem', $align='center', $return=false) {
  5488. if ($style == 'green') {
  5489. $style = 'notifysuccess'; // backward compatible with old color system
  5490. }
  5491. $message = clean_text($message);
  5492. $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
  5493. if ($return) {
  5494. return $output;
  5495. }
  5496. echo $output;
  5497. }
  5498. /**
  5499. * Given an email address, this function will return an obfuscated version of it
  5500. *
  5501. * @param string $email The email address to obfuscate
  5502. * @return string
  5503. */
  5504. function obfuscate_email($email) {
  5505. $i = 0;
  5506. $length = strlen($email);
  5507. $obfuscated = '';
  5508. while ($i < $length) {
  5509. if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
  5510. $obfuscated.='%'.dechex(ord($email{$i}));
  5511. } else {
  5512. $obfuscated.=$email{$i};
  5513. }
  5514. $i++;
  5515. }
  5516. return $obfuscated;
  5517. }
  5518. /**
  5519. * This function takes some text and replaces about half of the characters
  5520. * with HTML entity equivalents. Return string is obviously longer.
  5521. *
  5522. * @param string $plaintext The text to be obfuscated
  5523. * @return string
  5524. */
  5525. function obfuscate_text($plaintext) {
  5526. $i=0;
  5527. $length = strlen($plaintext);
  5528. $obfuscated='';
  5529. $prev_obfuscated = false;
  5530. while ($i < $length) {
  5531. $c = ord($plaintext{$i});
  5532. $numerical = ($c >= ord('0')) && ($c <= ord('9'));
  5533. if ($prev_obfuscated and $numerical ) {
  5534. $obfuscated.='&#'.ord($plaintext{$i}).';';
  5535. } else if (rand(0,2)) {
  5536. $obfuscated.='&#'.ord($plaintext{$i}).';';
  5537. $prev_obfuscated = true;
  5538. } else {
  5539. $obfuscated.=$plaintext{$i};
  5540. $prev_obfuscated = false;
  5541. }
  5542. $i++;
  5543. }
  5544. return $obfuscated;
  5545. }
  5546. /**
  5547. * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
  5548. * to generate a fully obfuscated email link, ready to use.
  5549. *
  5550. * @param string $email The email address to display
  5551. * @param string $label The text to dispalyed as hyperlink to $email
  5552. * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
  5553. * @return string
  5554. */
  5555. function obfuscate_mailto($email, $label='', $dimmed=false) {
  5556. if (empty($label)) {
  5557. $label = $email;
  5558. }
  5559. if ($dimmed) {
  5560. $title = get_string('emaildisable');
  5561. $dimmed = ' class="dimmed"';
  5562. } else {
  5563. $title = '';
  5564. $dimmed = '';
  5565. }
  5566. return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
  5567. obfuscate_text('mailto'), obfuscate_email($email),
  5568. obfuscate_text($label));
  5569. }
  5570. /**
  5571. * Prints a single paging bar to provide access to other pages (usually in a search)
  5572. *
  5573. * @param int $totalcount Thetotal number of entries available to be paged through
  5574. * @param int $page The page you are currently viewing
  5575. * @param int $perpage The number of entries that should be shown per page
  5576. * @param mixed $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
  5577. * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
  5578. * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
  5579. * @param bool $nocurr do not display the current page as a link
  5580. * @param bool $return whether to return an output string or echo now
  5581. * @return bool or string
  5582. */
  5583. function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
  5584. $maxdisplay = 18;
  5585. $output = '';
  5586. if ($totalcount > $perpage) {
  5587. $output .= '<div class="paging">';
  5588. $output .= get_string('page') .':';
  5589. if ($page > 0) {
  5590. $pagenum = $page - 1;
  5591. if (!is_a($baseurl, 'moodle_url')){
  5592. $output .= '&nbsp;(<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
  5593. } else {
  5594. $output .= '&nbsp;(<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
  5595. }
  5596. }
  5597. if ($perpage > 0) {
  5598. $lastpage = ceil($totalcount / $perpage);
  5599. } else {
  5600. $lastpage = 1;
  5601. }
  5602. if ($page > 15) {
  5603. $startpage = $page - 10;
  5604. if (!is_a($baseurl, 'moodle_url')){
  5605. $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
  5606. } else {
  5607. $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
  5608. }
  5609. } else {
  5610. $startpage = 0;
  5611. }
  5612. $currpage = $startpage;
  5613. $displaycount = $displaypage = 0;
  5614. while ($displaycount < $maxdisplay and $currpage < $lastpage) {
  5615. $displaypage = $currpage+1;
  5616. if ($page == $currpage && empty($nocurr)) {
  5617. $output .= '&nbsp;&nbsp;'. $displaypage;
  5618. } else {
  5619. if (!is_a($baseurl, 'moodle_url')){
  5620. $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
  5621. } else {
  5622. $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
  5623. }
  5624. }
  5625. $displaycount++;
  5626. $currpage++;
  5627. }
  5628. if ($currpage < $lastpage) {
  5629. $lastpageactual = $lastpage - 1;
  5630. if (!is_a($baseurl, 'moodle_url')){
  5631. $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
  5632. } else {
  5633. $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
  5634. }
  5635. }
  5636. $pagenum = $page + 1;
  5637. if ($pagenum != $displaypage) {
  5638. if (!is_a($baseurl, 'moodle_url')){
  5639. $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
  5640. } else {
  5641. $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
  5642. }
  5643. }
  5644. $output .= '</div>';
  5645. }
  5646. if ($return) {
  5647. return $output;
  5648. }
  5649. echo $output;
  5650. return true;
  5651. }
  5652. /**
  5653. * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
  5654. * will transform it to html entities
  5655. *
  5656. * @param string $text Text to search for nolink tag in
  5657. * @return string
  5658. */
  5659. function rebuildnolinktag($text) {
  5660. $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
  5661. return $text;
  5662. }
  5663. /**
  5664. * Prints a nice side block with an optional header. The content can either
  5665. * be a block of HTML or a list of text with optional icons.
  5666. *
  5667. * @param string $heading Block $title embedded in HTML tags, for example <h2>.
  5668. * @param string $content ?
  5669. * @param array $list ?
  5670. * @param array $icons ?
  5671. * @param string $footer ?
  5672. * @param array $attributes ?
  5673. * @param string $title Plain text title, as embedded in the $heading.
  5674. * @todo Finish documenting this function. Show example of various attributes, etc.
  5675. */
  5676. function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
  5677. //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
  5678. static $block_id = 0;
  5679. $block_id++;
  5680. $skip_text = get_string('skipa', 'access', strip_tags($title));
  5681. $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
  5682. $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
  5683. $strip_title = strip_tags($title);
  5684. if (! empty($strip_title)) {
  5685. echo $skip_link;
  5686. }
  5687. //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
  5688. print_side_block_start($heading, $attributes);
  5689. if ($content) {
  5690. echo $content;
  5691. if ($footer) {
  5692. echo '<div class="footer">'. $footer .'</div>';
  5693. }
  5694. } else {
  5695. if ($list) {
  5696. $row = 0;
  5697. //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
  5698. echo "\n<ul class='list'>\n";
  5699. foreach ($list as $key => $string) {
  5700. echo '<li class="r'. $row .'">';
  5701. if ($icons) {
  5702. echo '<div class="icon column c0">'. $icons[$key] .'</div>';
  5703. }
  5704. echo '<div class="column c1">' . $string . '</div>';
  5705. echo "</li>\n";
  5706. $row = $row ? 0:1;
  5707. }
  5708. echo "</ul>\n";
  5709. }
  5710. if ($footer) {
  5711. echo '<div class="footer">'. $footer .'</div>';
  5712. }
  5713. }
  5714. print_side_block_end($attributes, $title);
  5715. echo $skip_dest;
  5716. }
  5717. /**
  5718. * Starts a nice side block with an optional header.
  5719. *
  5720. * @param string $heading ?
  5721. * @param array $attributes ?
  5722. * @todo Finish documenting this function
  5723. */
  5724. function print_side_block_start($heading='', $attributes = array()) {
  5725. global $CFG, $THEME;
  5726. // If there are no special attributes, give a default CSS class
  5727. if (empty($attributes) || !is_array($attributes)) {
  5728. $attributes = array('class' => 'sideblock');
  5729. } else if(!isset($attributes['class'])) {
  5730. $attributes['class'] = 'sideblock';
  5731. } else if(!strpos($attributes['class'], 'sideblock')) {
  5732. $attributes['class'] .= ' sideblock';
  5733. }
  5734. // OK, the class is surely there and in addition to anything
  5735. // else, it's tagged as a sideblock
  5736. /*
  5737. // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
  5738. // If there is a cookie to hide this thing, start it hidden
  5739. if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
  5740. $attributes['class'] = 'hidden '.$attributes['class'];
  5741. }
  5742. */
  5743. $attrtext = '';
  5744. foreach ($attributes as $attr => $val) {
  5745. $attrtext .= ' '.$attr.'="'.$val.'"';
  5746. }
  5747. echo '<div '.$attrtext.'>';
  5748. if (!empty($THEME->customcorners)) {
  5749. echo '<div class="wrap">'."\n";
  5750. }
  5751. if ($heading) {
  5752. //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
  5753. echo '<div class="header">';
  5754. if (!empty($THEME->customcorners)) {
  5755. echo '<div class="bt"><div>&nbsp;</div></div>';
  5756. echo '<div class="i1"><div class="i2">';
  5757. echo '<div class="i3">';
  5758. }
  5759. echo $heading;
  5760. if (!empty($THEME->customcorners)) {
  5761. echo '</div></div></div>';
  5762. }
  5763. echo '</div>';
  5764. } else {
  5765. if (!empty($THEME->customcorners)) {
  5766. echo '<div class="bt"><div>&nbsp;</div></div>';
  5767. }
  5768. }
  5769. if (!empty($THEME->customcorners)) {
  5770. echo '<div class="i1"><div class="i2">';
  5771. echo '<div class="i3">';
  5772. }
  5773. echo '<div class="content">';
  5774. }
  5775. /**
  5776. * Print table ending tags for a side block box.
  5777. */
  5778. function print_side_block_end($attributes = array(), $title='') {
  5779. global $CFG, $THEME;
  5780. echo '</div>';
  5781. if (!empty($THEME->customcorners)) {
  5782. echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
  5783. }
  5784. echo '</div>';
  5785. $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
  5786. $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
  5787. // IE workaround: if I do it THIS way, it works! WTF?
  5788. if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
  5789. echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
  5790. '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
  5791. }
  5792. }
  5793. /**
  5794. * Prints out code needed for spellchecking.
  5795. * Original idea by Ludo (Marc Alier).
  5796. *
  5797. * Opening CDATA and <script> are output by weblib::use_html_editor()
  5798. * @uses $CFG
  5799. * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
  5800. * @param boolean $return If false, echos the code instead of returning it
  5801. * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
  5802. */
  5803. function print_speller_code ($usehtmleditor=false, $return=false) {
  5804. global $CFG;
  5805. $str = '';
  5806. if(!$usehtmleditor) {
  5807. $str .= 'function openSpellChecker() {'."\n";
  5808. $str .= "\tvar speller = new spellChecker();\n";
  5809. $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
  5810. $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
  5811. $str .= "\tspeller.spellCheckAll();\n";
  5812. $str .= '}'."\n";
  5813. } else {
  5814. $str .= "function spellClickHandler(editor, buttonId) {\n";
  5815. $str .= "\teditor._textArea.value = editor.getHTML();\n";
  5816. $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
  5817. $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
  5818. $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
  5819. $str .= "\tspeller._moogle_edit=1;\n";
  5820. $str .= "\tspeller._editor=editor;\n";
  5821. $str .= "\tspeller.openChecker();\n";
  5822. $str .= '}'."\n";
  5823. }
  5824. if ($return) {
  5825. return $str;
  5826. }
  5827. echo $str;
  5828. }
  5829. /**
  5830. * Print button for spellchecking when editor is disabled
  5831. */
  5832. function print_speller_button () {
  5833. echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
  5834. }
  5835. function page_id_and_class(&$getid, &$getclass) {
  5836. // Create class and id for this page
  5837. global $CFG, $ME;
  5838. static $class = NULL;
  5839. static $id = NULL;
  5840. if (empty($CFG->pagepath)) {
  5841. $CFG->pagepath = $ME;
  5842. }
  5843. if (empty($class) || empty($id)) {
  5844. $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
  5845. $path = str_replace('.php', '', $path);
  5846. if (substr($path, -1) == '/') {
  5847. $path .= 'index';
  5848. }
  5849. if (empty($path) || $path == 'index') {
  5850. $id = 'site-index';
  5851. $class = 'course';
  5852. } else if (substr($path, 0, 5) == 'admin') {
  5853. $id = str_replace('/', '-', $path);
  5854. $class = 'admin';
  5855. } else {
  5856. $id = str_replace('/', '-', $path);
  5857. $class = explode('-', $id);
  5858. array_pop($class);
  5859. $class = implode('-', $class);
  5860. }
  5861. }
  5862. $getid = $id;
  5863. $getclass = $class;
  5864. }
  5865. /**
  5866. * Prints a maintenance message from /maintenance.html
  5867. */
  5868. function print_maintenance_message () {
  5869. global $CFG, $SITE;
  5870. $CFG->pagepath = "index.php";
  5871. print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
  5872. print_box_start();
  5873. print_heading(get_string('sitemaintenance', 'admin'));
  5874. @include($CFG->dataroot.'/'.SITEID.'/maintenance.html');
  5875. print_box_end();
  5876. print_footer();
  5877. }
  5878. /**
  5879. * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
  5880. */
  5881. function adjust_allowed_tags() {
  5882. global $CFG, $ALLOWED_TAGS;
  5883. if (!empty($CFG->allowobjectembed)) {
  5884. $ALLOWED_TAGS .= '<embed><object>';
  5885. }
  5886. }
  5887. /// Some code to print tabs
  5888. /// A class for tabs
  5889. class tabobject {
  5890. var $id;
  5891. var $link;
  5892. var $text;
  5893. var $linkedwhenselected;
  5894. /// A constructor just because I like constructors
  5895. function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
  5896. $this->id = $id;
  5897. $this->link = $link;
  5898. $this->text = $text;
  5899. $this->title = $title ? $title : $text;
  5900. $this->linkedwhenselected = $linkedwhenselected;
  5901. }
  5902. }
  5903. /**
  5904. * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
  5905. *
  5906. * @param array $tabrows An array of rows where each row is an array of tab objects
  5907. * @param string $selected The id of the selected tab (whatever row it's on)
  5908. * @param array $inactive An array of ids of inactive tabs that are not selectable.
  5909. * @param array $activated An array of ids of other tabs that are currently activated
  5910. **/
  5911. function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
  5912. global $CFG;
  5913. /// $inactive must be an array
  5914. if (!is_array($inactive)) {
  5915. $inactive = array();
  5916. }
  5917. /// $activated must be an array
  5918. if (!is_array($activated)) {
  5919. $activated = array();
  5920. }
  5921. /// Convert the tab rows into a tree that's easier to process
  5922. if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
  5923. return false;
  5924. }
  5925. /// Print out the current tree of tabs (this function is recursive)
  5926. $output = convert_tree_to_html($tree);
  5927. $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
  5928. /// We're done!
  5929. if ($return) {
  5930. return $output;
  5931. }
  5932. echo $output;
  5933. }
  5934. function convert_tree_to_html($tree, $row=0) {
  5935. $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
  5936. $first = true;
  5937. $count = count($tree);
  5938. foreach ($tree as $tab) {
  5939. $count--; // countdown to zero
  5940. $liclass = '';
  5941. if ($first && ($count == 0)) { // Just one in the row
  5942. $liclass = 'first last';
  5943. $first = false;
  5944. } else if ($first) {
  5945. $liclass = 'first';
  5946. $first = false;
  5947. } else if ($count == 0) {
  5948. $liclass = 'last';
  5949. }
  5950. if ((empty($tab->subtree)) && (!empty($tab->selected))) {
  5951. $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
  5952. }
  5953. if ($tab->inactive || $tab->active || $tab->selected) {
  5954. if ($tab->selected) {
  5955. $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
  5956. } else if ($tab->active) {
  5957. $liclass .= (empty($liclass)) ? 'here active' : ' here active';
  5958. }
  5959. }
  5960. $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
  5961. if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
  5962. // The a tag is used for styling
  5963. $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
  5964. } else {
  5965. $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
  5966. }
  5967. if (!empty($tab->subtree)) {
  5968. $str .= convert_tree_to_html($tab->subtree, $row+1);
  5969. } else if ($tab->selected) {
  5970. $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
  5971. }
  5972. $str .= ' </li>'."\n";
  5973. }
  5974. $str .= '</ul>'."\n";
  5975. return $str;
  5976. }
  5977. function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
  5978. /// Work backwards through the rows (bottom to top) collecting the tree as we go.
  5979. $tabrows = array_reverse($tabrows);
  5980. $subtree = array();
  5981. foreach ($tabrows as $row) {
  5982. $tree = array();
  5983. foreach ($row as $tab) {
  5984. $tab->inactive = in_array((string)$tab->id, $inactive);
  5985. $tab->active = in_array((string)$tab->id, $activated);
  5986. $tab->selected = (string)$tab->id == $selected;
  5987. if ($tab->active || $tab->selected) {
  5988. if ($subtree) {
  5989. $tab->subtree = $subtree;
  5990. }
  5991. }
  5992. $tree[] = $tab;
  5993. }
  5994. $subtree = $tree;
  5995. }
  5996. return $subtree;
  5997. }
  5998. /**
  5999. * Returns a string containing a link to the user documentation for the current
  6000. * page. Also contains an icon by default. Shown to teachers and admin only.
  6001. *
  6002. * @param string $text The text to be displayed for the link
  6003. * @param string $iconpath The path to the icon to be displayed
  6004. */
  6005. function page_doc_link($text='', $iconpath='') {
  6006. global $ME, $COURSE, $CFG;
  6007. if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
  6008. return '';
  6009. }
  6010. if (empty($COURSE->id)) {
  6011. $context = get_context_instance(CONTEXT_SYSTEM);
  6012. } else {
  6013. $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
  6014. }
  6015. if (!has_capability('moodle/site:doclinks', $context)) {
  6016. return '';
  6017. }
  6018. if (empty($CFG->pagepath)) {
  6019. $CFG->pagepath = $ME;
  6020. }
  6021. $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
  6022. $path = str_replace('.php', '', $path);
  6023. if (empty($path)) { // Not for home page
  6024. return '';
  6025. }
  6026. return doc_link($path, $text, $iconpath);
  6027. }
  6028. /**
  6029. * Returns a string containing a link to the user documentation.
  6030. * Also contains an icon by default. Shown to teachers and admin only.
  6031. *
  6032. * @param string $path The page link after doc root and language, no
  6033. * leading slash.
  6034. * @param string $text The text to be displayed for the link
  6035. * @param string $iconpath The path to the icon to be displayed
  6036. */
  6037. function doc_link($path='', $text='', $iconpath='') {
  6038. global $CFG;
  6039. $target = '';
  6040. if (!empty($CFG->doctonewwindow)) {
  6041. $target = ' target="_blank"';
  6042. }
  6043. if (is_null($docroot = get_doc_root())) {
  6044. return '';
  6045. }
  6046. $str = '<a href="' .$docroot. '/' .$path. '"' .$target. '>';
  6047. if (empty($iconpath)) {
  6048. $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
  6049. }
  6050. // alt left blank intentionally to prevent repetition in screenreaders
  6051. $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
  6052. return $str;
  6053. }
  6054. /**
  6055. * A function that checks if docroot is set, builds and returns the docs root url according to version release.
  6056. * @return string documentation url, null if doc root isn't set (ie:during installation perhaps).
  6057. */
  6058. function get_doc_root() {
  6059. global $CFG;
  6060. if (empty($CFG->docroot)) {
  6061. return null;
  6062. }
  6063. $lang = str_replace('_utf8', '', current_language());
  6064. if (!empty($CFG->release)) {
  6065. $release = $CFG->release;
  6066. } else {
  6067. //derive branch from the first three letters of version.php's $release with the period taken out.($CFG->release isn't populated yet during upgrade)
  6068. include($CFG->dirroot.'/version.php');
  6069. }
  6070. if (preg_match('/^(.)\.(.)/', $release, $matches)) {
  6071. $branch = $matches[1].$matches[2];
  6072. } else {
  6073. $branch = '.';
  6074. }
  6075. return $CFG->docroot. '/' .$branch. '/' .$lang;
  6076. }
  6077. /**
  6078. * Returns true if the current site debugging settings are equal or above specified level.
  6079. * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
  6080. * routing of notices is controlled by $CFG->debugdisplay
  6081. * eg use like this:
  6082. *
  6083. * 1) debugging('a normal debug notice');
  6084. * 2) debugging('something really picky', DEBUG_ALL);
  6085. * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
  6086. * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
  6087. *
  6088. * In code blocks controlled by debugging() (such as example 4)
  6089. * any output should be routed via debugging() itself, or the lower-level
  6090. * trigger_error() or error_log(). Using echo or print will break XHTML
  6091. * JS and HTTP headers.
  6092. *
  6093. *
  6094. * @param string $message a message to print
  6095. * @param int $level the level at which this debugging statement should show
  6096. * @return bool
  6097. */
  6098. function debugging($message='', $level=DEBUG_NORMAL) {
  6099. global $CFG;
  6100. if (empty($CFG->debug)) {
  6101. return false;
  6102. }
  6103. if ($CFG->debug >= $level) {
  6104. if ($message) {
  6105. $callers = debug_backtrace();
  6106. $from = '<ul style="text-align: left">';
  6107. foreach ($callers as $caller) {
  6108. if (!isset($caller['line'])) {
  6109. $caller['line'] = '?'; // probably call_user_func()
  6110. }
  6111. if (!isset($caller['file'])) {
  6112. $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
  6113. }
  6114. $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
  6115. if (isset($caller['function'])) {
  6116. $from .= ': call to ';
  6117. if (isset($caller['class'])) {
  6118. $from .= $caller['class'] . $caller['type'];
  6119. }
  6120. $from .= $caller['function'] . '()';
  6121. }
  6122. $from .= '</li>';
  6123. }
  6124. $from .= '</ul>';
  6125. if (!isset($CFG->debugdisplay)) {
  6126. $CFG->debugdisplay = ini_get_bool('display_errors');
  6127. }
  6128. if ($CFG->debugdisplay) {
  6129. if (!defined('DEBUGGING_PRINTED')) {
  6130. define('DEBUGGING_PRINTED', 1); // indicates we have printed something
  6131. }
  6132. notify($message . $from, 'notifytiny');
  6133. } else {
  6134. trigger_error($message . $from, E_USER_NOTICE);
  6135. }
  6136. }
  6137. return true;
  6138. }
  6139. return false;
  6140. }
  6141. /**
  6142. * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
  6143. */
  6144. function disable_debugging() {
  6145. global $CFG;
  6146. $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
  6147. }
  6148. /**
  6149. * Returns string to add a frame attribute, if required
  6150. */
  6151. function frametarget() {
  6152. global $CFG;
  6153. if (empty($CFG->framename) or ($CFG->framename == '_top')) {
  6154. return '';
  6155. } else {
  6156. return ' target="'.$CFG->framename.'" ';
  6157. }
  6158. }
  6159. /**
  6160. * Outputs a HTML comment to the browser. This is used for those hard-to-debug
  6161. * pages that use bits from many different files in very confusing ways (e.g. blocks).
  6162. * @usage print_location_comment(__FILE__, __LINE__);
  6163. * @param string $file
  6164. * @param integer $line
  6165. * @param boolean $return Whether to return or print the comment
  6166. * @return mixed Void unless true given as third parameter
  6167. */
  6168. function print_location_comment($file, $line, $return = false)
  6169. {
  6170. if ($return) {
  6171. return "<!-- $file at line $line -->\n";
  6172. } else {
  6173. echo "<!-- $file at line $line -->\n";
  6174. }
  6175. }
  6176. /**
  6177. * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
  6178. * provide this function with the language strings for sortasc and sortdesc.
  6179. * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
  6180. * @param string $direction 'up' or 'down'
  6181. * @param string $strsort The language string used for the alt attribute of this image
  6182. * @param bool $return Whether to print directly or return the html string
  6183. * @return string HTML for the image
  6184. *
  6185. * TODO See if this isn't already defined somewhere. If not, move this to weblib
  6186. */
  6187. function print_arrow($direction='up', $strsort=null, $return=false) {
  6188. global $CFG;
  6189. if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
  6190. return null;
  6191. }
  6192. $return = null;
  6193. switch ($direction) {
  6194. case 'up':
  6195. $sortdir = 'asc';
  6196. break;
  6197. case 'down':
  6198. $sortdir = 'desc';
  6199. break;
  6200. case 'move':
  6201. $sortdir = 'asc';
  6202. break;
  6203. default:
  6204. $sortdir = null;
  6205. break;
  6206. }
  6207. // Prepare language string
  6208. $strsort = '';
  6209. if (empty($strsort) && !empty($sortdir)) {
  6210. $strsort = get_string('sort' . $sortdir, 'grades');
  6211. }
  6212. $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
  6213. if ($return) {
  6214. return $return;
  6215. } else {
  6216. echo $return;
  6217. }
  6218. }
  6219. /**
  6220. * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
  6221. *
  6222. */
  6223. function right_to_left() {
  6224. static $result;
  6225. if (isset($result)) {
  6226. return $result;
  6227. }
  6228. return $result = (get_string('thisdirection') == 'rtl');
  6229. }
  6230. /**
  6231. * Returns swapped left<=>right if in RTL environment.
  6232. * part of RTL support
  6233. *
  6234. * @param string $align align to check
  6235. * @return string
  6236. */
  6237. function fix_align_rtl($align) {
  6238. if (!right_to_left()) {
  6239. return $align;
  6240. }
  6241. if ($align=='left') { return 'right'; }
  6242. if ($align=='right') { return 'left'; }
  6243. return $align;
  6244. }
  6245. /**
  6246. * Returns true if the page is displayed in a popup window.
  6247. * Gets the information from the URL parameter inpopup.
  6248. *
  6249. * @return boolean
  6250. *
  6251. * TODO Use a central function to create the popup calls allover Moodle and
  6252. * TODO In the moment only works with resources and probably questions.
  6253. */
  6254. function is_in_popup() {
  6255. $inpopup = optional_param('inpopup', '', PARAM_BOOL);
  6256. return ($inpopup);
  6257. }
  6258. /**
  6259. * Return the authentication plugin title
  6260. * @param string $authtype plugin type
  6261. * @return string
  6262. */
  6263. function auth_get_plugin_title ($authtype) {
  6264. $authtitle = get_string("auth_{$authtype}title", "auth");
  6265. if ($authtitle == "[[auth_{$authtype}title]]") {
  6266. $authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
  6267. }
  6268. return $authtitle;
  6269. }
  6270. /**
  6271. * Returns a localized sentence in the current language summarizing the current password policy
  6272. *
  6273. * @uses $CFG
  6274. * @return string
  6275. */
  6276. function print_password_policy() {
  6277. global $CFG;
  6278. $message = '';
  6279. if (!empty($CFG->passwordpolicy)) {
  6280. $messages = array();
  6281. $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
  6282. if (!empty($CFG->minpassworddigits)) {
  6283. $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
  6284. }
  6285. if (!empty($CFG->minpasswordlower)) {
  6286. $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
  6287. }
  6288. if (!empty($CFG->minpasswordupper)) {
  6289. $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
  6290. }
  6291. if (!empty($CFG->minpasswordnonalphanum)) {
  6292. $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
  6293. }
  6294. $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
  6295. $message = get_string('informpasswordpolicy', 'auth', $messages);
  6296. }
  6297. return $message;
  6298. }
  6299. // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
  6300. ?>