PageRenderTime 137ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

/moodle/lib/weblib.php

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