3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Classes for rendering HTML output for Moodle.
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 * Simple base class for Moodle renderers.
32 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
34 * Also has methods to facilitate generating HTML output.
36 * @copyright 2009 Tim Hunt
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 /** @var xhtml_container_stack the xhtml_container_stack to use. */
42 protected $opencontainers;
43 /** @var moodle_page the page we are rendering for. */
45 /** @var requested rendering target conatnt */
50 * @param moodle_page $page the page we are doing output for.
51 * @param string $target one of rendering target constants
53 public function __construct(moodle_page $page, $target) {
54 $this->opencontainers = $page->opencontainers;
56 $this->target = $target;
60 * Returns rendered widget.
61 * @param renderable $widget intence with renderable interface
64 public function render(renderable $widget) {
65 $rendermethod = 'render_'.get_class($widget);
66 if (method_exists($this, $rendermethod)) {
67 return $this->$rendermethod($widget);
69 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
73 * Adds JS handlers needed for event execution for one html element id
74 * @param component_action $actions
76 * @return string id of element, either original submitted or random new if not supplied
78 public function add_action_handler(component_action $action, $id=null) {
80 $id = html_writer::random_id($action->event);
82 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
87 * Have we started output yet?
88 * @return boolean true if the header has been printed.
90 public function has_started() {
91 return $this->page->state >= moodle_page::STATE_IN_BODY;
95 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
96 * @param mixed $classes Space-separated string or array of classes
97 * @return string HTML class attribute value
99 public static function prepare_classes($classes) {
100 if (is_array($classes)) {
101 return implode(' ', array_unique($classes));
107 * Return the moodle_url for an image.
108 * The exact image location and extension is determined
109 * automatically by searching for gif|png|jpg|jpeg, please
110 * note there can not be diferent images with the different
111 * extension. The imagename is for historical reasons
112 * a relative path name, it may be changed later for core
113 * images. It is recommended to not use subdirectories
114 * in plugin and theme pix directories.
116 * There are three types of images:
117 * 1/ theme images - stored in theme/mytheme/pix/,
118 * use component 'theme'
119 * 2/ core images - stored in /pix/,
120 * overridden via theme/mytheme/pix_core/
121 * 3/ plugin images - stored in mod/mymodule/pix,
122 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
123 * example: pix_url('comment', 'mod_glossary')
125 * @param string $imagename the pathname of the image
126 * @param string $component full plugin name (aka component) or 'theme'
129 public function pix_url($imagename, $component = 'moodle') {
130 return $this->page->theme->pix_url($imagename, $component);
136 * Basis for all plugin renderers.
138 * @author Petr Skoda (skodak)
139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
142 class plugin_renderer_base extends renderer_base {
144 * A reference to the current general renderer probably {@see core_renderer}
150 * Contructor method, calls the parent constructor
151 * @param moodle_page $page
152 * @param string $target one of rendering target constants
154 public function __construct(moodle_page $page, $target) {
155 $this->output = $page->get_renderer('core', null, $target);
156 parent::__construct($page, $target);
160 * Returns rendered widget.
161 * @param renderable $widget intence with renderable interface
164 public function render(renderable $widget) {
165 $rendermethod = 'render_'.get_class($widget);
166 if (method_exists($this, $rendermethod)) {
167 return $this->$rendermethod($widget);
169 // pass to core renderer if method not found here
170 $this->output->render($widget);
174 * Magic method used to pass calls otherwise meant for the standard renderer
175 * to it to ensure we don't go causing unnessecary greif.
177 * @param string $method
178 * @param array $arguments
181 public function __call($method, $arguments) {
182 if (method_exists('renderer_base', $method)) {
183 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
185 if (method_exists($this->output, $method)) {
186 return call_user_func_array(array($this->output, $method), $arguments);
188 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
195 * The standard implementation of the core_renderer interface.
197 * @copyright 2009 Tim Hunt
198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
201 class core_renderer extends renderer_base {
202 /** @var string used in {@link header()}. */
203 const PERFORMANCE_INFO_TOKEN = '%%PERFORMANCEINFO%%';
204 /** @var string used in {@link header()}. */
205 const END_HTML_TOKEN = '%%ENDHTML%%';
206 /** @var string used in {@link header()}. */
207 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
208 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
209 protected $contenttype;
210 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
211 protected $metarefreshtag = '';
214 * Get the DOCTYPE declaration that should be used with this page. Designed to
215 * be called in theme layout.php files.
216 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
218 public function doctype() {
221 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
222 $this->contenttype = 'text/html; charset=utf-8';
224 if (empty($CFG->xmlstrictheaders)) {
228 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
229 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
230 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
231 // Firefox and other browsers that can cope natively with XHTML.
232 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
234 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
235 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
236 $this->contenttype = 'application/xml; charset=utf-8';
237 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
243 return $prolog . $doctype;
247 * The attributes that should be added to the <html> tag. Designed to
248 * be called in theme layout.php files.
249 * @return string HTML fragment.
251 public function htmlattributes() {
252 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
256 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
257 * that should be included in the <head> tag. Designed to be called in theme
259 * @return string HTML fragment.
261 public function standard_head_html() {
262 global $CFG, $SESSION;
264 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
265 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
266 if (!$this->page->cacheable) {
267 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
268 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
270 // This is only set by the {@link redirect()} method
271 $output .= $this->metarefreshtag;
273 // Check if a periodic refresh delay has been set and make sure we arn't
274 // already meta refreshing
275 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
276 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
279 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
281 $focus = $this->page->focuscontrol;
282 if (!empty($focus)) {
283 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
284 // This is a horrifically bad way to handle focus but it is passed in
285 // through messy formslib::moodleform
286 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
287 } else if (strpos($focus, '.')!==false) {
288 // Old style of focus, bad way to do it
289 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
290 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
292 // Focus element with given id
293 $this->page->requires->js_function_call('focuscontrol', array($focus));
297 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
298 // any other custom CSS can not be overridden via themes and is highly discouraged
299 $urls = $this->page->theme->css_urls($this->page);
300 foreach ($urls as $url) {
301 $this->page->requires->css_theme($url);
304 // Get the theme javascript head and footer
305 $jsurl = $this->page->theme->javascript_url(true);
306 $this->page->requires->js($jsurl, true);
307 $jsurl = $this->page->theme->javascript_url(false);
308 $this->page->requires->js($jsurl);
310 // Perform a browser environment check for the flash version. Should only run once per login session.
311 if (!NO_MOODLE_COOKIES && isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
312 $this->page->requires->js('/lib/swfobject/swfobject.js');
313 $this->page->requires->js_init_call('M.core_flashdetect.init');
316 // Get any HTML from the page_requirements_manager.
317 $output .= $this->page->requires->get_head_code($this->page, $this);
319 // List alternate versions.
320 foreach ($this->page->alternateversions as $type => $alt) {
321 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
322 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
329 * The standard tags (typically skip links) that should be output just inside
330 * the start of the <body> tag. Designed to be called in theme layout.php files.
331 * @return string HTML fragment.
333 public function standard_top_of_body_html() {
334 return $this->page->requires->get_top_of_body_code();
338 * The standard tags (typically performance information and validation links,
339 * if we are in developer debug mode) that should be output in the footer area
340 * of the page. Designed to be called in theme layout.php files.
341 * @return string HTML fragment.
343 public function standard_footer_html() {
346 // This function is normally called from a layout.php file in {@link header()}
347 // but some of the content won't be known until later, so we return a placeholder
348 // for now. This will be replaced with the real content in {@link footer()}.
349 $output = self::PERFORMANCE_INFO_TOKEN;
350 if (!empty($CFG->debugpageinfo)) {
351 $output .= '<div class="performanceinfo">This page is: ' . $this->page->debug_summary() . '</div>';
353 if (!empty($CFG->debugvalidators)) {
354 $output .= '<div class="validators"><ul>
355 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
356 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
357 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
364 * The standard tags (typically script tags that are not needed earlier) that
365 * should be output after everything else, . Designed to be called in theme layout.php files.
366 * @return string HTML fragment.
368 public function standard_end_of_body_html() {
369 // This function is normally called from a layout.php file in {@link header()}
370 // but some of the content won't be known until later, so we return a placeholder
371 // for now. This will be replaced with the real content in {@link footer()}.
372 echo self::END_HTML_TOKEN;
376 * Return the standard string that says whether you are logged in (and switched
377 * roles/logged in as another user).
378 * @return string HTML fragment.
380 public function login_info() {
381 global $USER, $CFG, $DB;
383 if (during_initial_install()) {
387 $course = $this->page->course;
389 if (session_is_loggedinas()) {
390 $realuser = session_get_realuser();
391 $fullname = fullname($realuser, true);
392 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
397 $loginurl = get_login_url();
399 if (empty($course->id)) {
400 // $course->id is not defined during installation
402 } else if (!empty($USER->id)) {
403 $context = get_context_instance(CONTEXT_COURSE, $course->id);
405 $fullname = fullname($USER, true);
406 $username = "<a href=\"$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id\">$fullname</a>";
407 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
408 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
410 if (isset($USER->username) && $USER->username == 'guest') {
411 $loggedinas = $realuserinfo.get_string('loggedinasguest').
412 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
413 } else if (!empty($USER->access['rsw'][$context->path])) {
415 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
416 $rolename = ': '.format_string($role->name);
418 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
419 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
421 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
422 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
425 $loggedinas = get_string('loggedinnot', 'moodle').
426 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
429 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
431 if (isset($SESSION->justloggedin)) {
432 unset($SESSION->justloggedin);
433 if (!empty($CFG->displayloginfailures)) {
434 if (!empty($USER->username) and $USER->username != 'guest') {
435 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
436 $loggedinas .= ' <div class="loginfailures">';
437 if (empty($count->accounts)) {
438 $loggedinas .= get_string('failedloginattempts', '', $count);
440 $loggedinas .= get_string('failedloginattemptsall', '', $count);
442 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
443 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
444 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
446 $loggedinas .= '</div>';
456 * Return the 'back' link that normally appears in the footer.
457 * @return string HTML fragment.
459 public function home_link() {
462 if ($this->page->pagetype == 'site-index') {
463 // Special case for site home page - please do not remove
464 return '<div class="sitelink">' .
465 '<a title="Moodle" href="http://moodle.org/">' .
466 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
468 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
469 // Special case for during install/upgrade.
470 return '<div class="sitelink">'.
471 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
472 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
474 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
475 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
476 get_string('home') . '</a></div>';
479 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
480 format_string($this->page->course->shortname) . '</a></div>';
485 * Redirects the user by any means possible given the current state
487 * This function should not be called directly, it should always be called using
488 * the redirect function in lib/weblib.php
490 * The redirect function should really only be called before page output has started
491 * however it will allow itself to be called during the state STATE_IN_BODY
493 * @param string $encodedurl The URL to send to encoded if required
494 * @param string $message The message to display to the user if any
495 * @param int $delay The delay before redirecting a user, if $message has been
496 * set this is a requirement and defaults to 3, set to 0 no delay
497 * @param boolean $debugdisableredirect this redirect has been disabled for
498 * debugging purposes. Display a message that explains, and don't
499 * trigger the redirect.
500 * @return string The HTML to display to the user before dying, may contain
501 * meta refresh, javascript refresh, and may have set header redirects
503 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
505 $url = str_replace('&', '&', $encodedurl);
507 switch ($this->page->state) {
508 case moodle_page::STATE_BEFORE_HEADER :
509 // No output yet it is safe to delivery the full arsenal of redirect methods
510 if (!$debugdisableredirect) {
511 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
512 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
513 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
515 $output = $this->header();
517 case moodle_page::STATE_PRINTING_HEADER :
518 // We should hopefully never get here
519 throw new coding_exception('You cannot redirect while printing the page header');
521 case moodle_page::STATE_IN_BODY :
522 // We really shouldn't be here but we can deal with this
523 debugging("You should really redirect before you start page output");
524 if (!$debugdisableredirect) {
525 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
527 $output = $this->opencontainers->pop_all_but_last();
529 case moodle_page::STATE_DONE :
530 // Too late to be calling redirect now
531 throw new coding_exception('You cannot redirect after the entire page has been generated');
534 $output .= $this->notification($message, 'redirectmessage');
535 $output .= '<a href="'. $encodedurl .'">'. get_string('continue') .'</a>';
536 if ($debugdisableredirect) {
537 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
539 $output .= $this->footer();
544 * Start output by sending the HTTP headers, and printing the HTML <head>
545 * and the start of the <body>.
547 * To control what is printed, you should set properties on $PAGE. If you
548 * are familiar with the old {@link print_header()} function from Moodle 1.9
549 * you will find that there are properties on $PAGE that correspond to most
550 * of the old parameters to could be passed to print_header.
552 * Not that, in due course, the remaining $navigation, $menu parameters here
553 * will be replaced by more properties of $PAGE, but that is still to do.
555 * @return string HTML that you must output this, preferably immediately.
557 public function header() {
560 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
562 // Find the appropriate page layout file, based on $this->page->pagelayout.
563 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
564 // Render the layout using the layout file.
565 $rendered = $this->render_page_layout($layoutfile);
567 // Slice the rendered output into header and footer.
568 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
569 if ($cutpos === false) {
570 throw new coding_exception('page layout file ' . $layoutfile .
571 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
573 $header = substr($rendered, 0, $cutpos);
574 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
576 if (empty($this->contenttype)) {
577 debugging('The page layout file did not call $OUTPUT->doctype()');
578 $header = $this->doctype() . $header;
581 send_headers($this->contenttype, $this->page->cacheable);
583 $this->opencontainers->push('header/footer', $footer);
584 $this->page->set_state(moodle_page::STATE_IN_BODY);
586 return $header . $this->skip_link_target();
590 * Renders and outputs the page layout file.
591 * @param string $layoutfile The name of the layout file
592 * @return string HTML code
594 protected function render_page_layout($layoutfile) {
595 global $CFG, $SITE, $USER;
596 // The next lines are a bit tricky. The point is, here we are in a method
597 // of a renderer class, and this object may, or may not, be the same as
598 // the global $OUTPUT object. When rendering the page layout file, we want to use
599 // this object. However, people writing Moodle code expect the current
600 // renderer to be called $OUTPUT, not $this, so define a variable called
601 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
604 $COURSE = $this->page->course;
607 include($layoutfile);
608 $rendered = ob_get_contents();
614 * Outputs the page's footer
615 * @return string HTML fragment
617 public function footer() {
620 $output = $this->container_end_all(true);
622 $footer = $this->opencontainers->pop('header/footer');
624 if (debugging() and $DB and $DB->is_transaction_started()) {
625 // TODO: MDL-20625 print warning - transaction will be rolled back
628 // Provide some performance info if required
629 $performanceinfo = '';
630 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
631 $perf = get_performance_info();
632 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
633 error_log("PERF: " . $perf['txt']);
635 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
636 $performanceinfo = $perf['html'];
639 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
641 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
643 $this->page->set_state(moodle_page::STATE_DONE);
646 return $output . $footer;
650 * Close all but the last open container. This is useful in places like error
651 * handling, where you want to close all the open containers (apart from <body>)
652 * before outputting the error message.
653 * @param bool $shouldbenone assert that the stack should be empty now - causes a
654 * developer debug warning if it isn't.
655 * @return string the HTML required to close any open containers inside <body>.
657 public function container_end_all($shouldbenone = false) {
658 return $this->opencontainers->pop_all_but_last($shouldbenone);
662 * Returns lang menu or '', this method also checks forcing of languages in courses.
665 public function lang_menu() {
668 if (empty($CFG->langmenu)) {
672 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
673 // do not show lang menu if language forced
677 $currlang = current_language();
678 $langs = get_list_of_languages();
680 if (count($langs) < 2) {
684 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
685 $s->label = get_accesshide(get_string('language'));
686 $s->class = 'langmenu';
687 return $this->render($s);
691 * Output the row of editing icons for a block, as defined by the controls array.
692 * @param array $controls an array like {@link block_contents::$controls}.
693 * @return HTML fragment.
695 public function block_controls($controls) {
696 if (empty($controls)) {
699 $controlshtml = array();
700 foreach ($controls as $control) {
701 $controlshtml[] = html_writer::tag('a', array('class' => 'icon',
702 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
703 'title' => $control['caption'], 'href' => $control['url']));
705 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
709 * Prints a nice side block with an optional header.
711 * The content is described
712 * by a {@link block_contents} object.
714 * @param block_contents $bc HTML for the content
715 * @param string $region the region the block is appearing in.
716 * @return string the HTML to be output.
718 function block(block_contents $bc, $region) {
719 $bc = clone($bc); // Avoid messing up the object passed in.
720 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
721 $bc->collapsible = block_contents::NOT_HIDEABLE;
723 if ($bc->collapsible == block_contents::HIDDEN) {
724 $bc->add_class('hidden');
726 if (!empty($bc->controls)) {
727 $bc->add_class('block_with_controls');
730 $skiptitle = strip_tags($bc->title);
731 if (empty($skiptitle)) {
735 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
736 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
739 $output .= html_writer::start_tag('div', $bc->attributes);
741 $controlshtml = $this->block_controls($bc->controls);
745 $title = html_writer::tag('h2', $bc->title, null);
748 if ($title || $controlshtml) {
749 $output .= html_writer::tag('div', html_writer::tag('div', $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
752 $output .= html_writer::start_tag('div', array('class' => 'content'));
753 $output .= $bc->content;
756 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
759 $output .= html_writer::end_tag('div');
760 $output .= html_writer::end_tag('div');
762 if ($bc->annotation) {
763 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
765 $output .= $skipdest;
767 $this->init_block_hider_js($bc);
772 * Calls the JS require function to hide a block.
773 * @param block_contents $bc A block_contents object
776 protected function init_block_hider_js(block_contents $bc) {
777 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
778 $userpref = 'block' . $bc->blockinstanceid . 'hidden';
779 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
780 $this->page->requires->yui2_lib('dom');
781 $this->page->requires->yui2_lib('event');
782 $plaintitle = strip_tags($bc->title);
783 $this->page->requires->js_function_call('new block_hider', array($bc->attributes['id'], $userpref,
784 get_string('hideblocka', 'access', $plaintitle), get_string('showblocka', 'access', $plaintitle),
785 $this->pix_url('t/switch_minus')->out(false), $this->pix_url('t/switch_plus')->out(false)));
790 * Render the contents of a block_list.
791 * @param array $icons the icon for each item.
792 * @param array $items the content of each item.
793 * @return string HTML
795 public function list_block_contents($icons, $items) {
798 foreach ($items as $key => $string) {
799 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
800 if (!empty($icons[$key])) { //test if the content has an assigned icon
801 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
803 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
804 $item .= html_writer::end_tag('li');
806 $row = 1 - $row; // Flip even/odd.
808 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'list'));
812 * Output all the blocks in a particular region.
813 * @param string $region the name of a region on this page.
814 * @return string the HTML to be output.
816 public function blocks_for_region($region) {
817 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
820 foreach ($blockcontents as $bc) {
821 if ($bc instanceof block_contents) {
822 $output .= $this->block($bc, $region);
823 } else if ($bc instanceof block_move_target) {
824 $output .= $this->block_move_target($bc);
826 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
833 * Output a place where the block that is currently being moved can be dropped.
834 * @param block_move_target $target with the necessary details.
835 * @return string the HTML to be output.
837 public function block_move_target($target) {
838 return html_writer::tag('a', html_writer::tag('span', array('class' => 'accesshide'), $target->text), array('href' => $target->url, 'class' => 'blockmovetarget'));
842 * Renders a sepcial html link with attached action
844 * @param string|moodle_url $url
845 * @param string $text HTML fragment
846 * @param component_action $action
847 * @param array $attributes associative array of html link attributes + disabled
848 * @return HTML fragment
850 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
851 if (!($url instanceof moodle_url)) {
852 $url = new moodle_url($url);
854 $link = new action_link($url, $text, $action, $attributes);
856 return $this->render($link);
860 * Implementation of action_link rendering
861 * @param action_link $link
862 * @return string HTML fragment
864 protected function render_action_link(action_link $link) {
867 // A disabled link is rendered as formatted text
868 if (!empty($link->attributes['disabled'])) {
869 // do not use div here due to nesting restriction in xhtml strict
870 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
873 $attributes = $link->attributes;
874 unset($link->attributes['disabled']);
875 $attributes['href'] = $link->url;
877 if ($link->actions) {
878 if (empty($attributes['id'])) {
879 $id = html_writer::random_id('action_link');
880 $attributes['id'] = $id;
882 $id = $attributes['id'];
884 foreach ($link->actions as $action) {
885 $this->add_action_handler($action, $id);
889 return html_writer::tag('a', $link->text, $attributes);
894 * Similar to action_link, image is used instead of the text
896 * @param string|moodle_url $url A string URL or moodel_url
897 * @param pix_icon $pixicon
898 * @param component_action $action
899 * @param array $attributes associative array of html link attributes + disabled
900 * @param bool $linktext show title next to image in link
901 * @return string HTML fragment
903 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
904 if (!($url instanceof moodle_url)) {
905 $url = new moodle_url($url);
907 $attributes = (array)$attributes;
909 if (empty($options['class'])) {
910 // let ppl override the class via $options
911 $attributes['class'] = 'action-icon';
914 $icon = $this->render($pixicon);
917 $text = $pixicon->attributes['alt'];
922 return $this->action_link($url, $text.$icon, $action, $attributes);
926 * Print a message along with button choices for Continue/Cancel
928 * If a string or moodle_url is given instead of a single_button, method defaults to post.
930 * @param string $message The question to ask the user
931 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
932 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
933 * @return string HTML fragment
935 public function confirm($message, $continue, $cancel) {
936 if ($continue instanceof single_button) {
938 } else if (is_string($continue)) {
939 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
940 } else if ($continue instanceof moodle_url) {
941 $continue = new single_button($continue, get_string('continue'), 'post');
943 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
946 if ($cancel instanceof single_button) {
948 } else if (is_string($cancel)) {
949 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
950 } else if ($cancel instanceof moodle_url) {
951 $cancel = new single_button($cancel, get_string('cancel'), 'get');
953 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
956 $output = $this->box_start('generalbox', 'notice');
957 $output .= html_writer::tag('p', $message);
958 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
959 $output .= $this->box_end();
964 * Returns a form with a single button.
966 * @param string|moodle_url $url
967 * @param string $label button text
968 * @param string $method get or post submit method
969 * @param array $options associative array {disabled, title, etc.}
970 * @return string HTML fragment
972 public function single_button($url, $label, $method='post', array $options=null) {
973 if (!($url instanceof moodle_url)) {
974 $url = new moodle_url($url);
976 $button = new single_button($url, $label, $method);
978 foreach ((array)$options as $key=>$value) {
979 if (array_key_exists($key, $button)) {
980 $button->$key = $value;
984 return $this->render($button);
988 * Internal implementation of single_button rendering
989 * @param single_button $button
990 * @return string HTML fragment
992 protected function render_single_button(single_button $button) {
993 $attributes = array('type' => 'submit',
994 'value' => $button->label,
995 'disabled' => $button->disabled ? 'disabled' : null,
996 'title' => $button->tooltip);
998 if ($button->actions) {
999 $id = html_writer::random_id('single_button');
1000 $attributes['id'] = $id;
1001 foreach ($button->actions as $action) {
1002 $this->add_action_handler($action, $id);
1006 // first the input element
1007 $output = html_writer::empty_tag('input', $attributes);
1009 // then hidden fields
1010 $params = $button->url->params();
1011 if ($button->method === 'post') {
1012 $params['sesskey'] = sesskey();
1014 foreach ($params as $var => $val) {
1015 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1018 // then div wrapper for xhtml strictness
1019 $output = html_writer::tag('div', $output);
1021 // now the form itself around it
1022 $url = $button->url->out_omit_querystring(); // url without params
1024 $url = '#'; // there has to be always some action
1026 $attributes = array('method' => $button->method,
1028 'id' => $button->formid);
1029 $output = html_writer::tag('form', $output, $attributes);
1031 // and finally one more wrapper with class
1032 return html_writer::tag('div', $output, array('class' => $button->class));
1036 * Returns a form with a single select widget.
1037 * @param moodle_url $url form action target, includes hidden fields
1038 * @param string $name name of selection field - the changing parameter in url
1039 * @param array $options list of options
1040 * @param string $selected selected element
1041 * @param array $nothing
1042 * @param string $formid
1043 * @return string HTML fragment
1045 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1046 if (!($url instanceof moodle_url)) {
1047 $url = new moodle_url($url);
1049 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1051 return $this->render($select);
1055 * Internal implementation of single_select rendering
1056 * @param single_select $select
1057 * @return string HTML fragment
1059 protected function render_single_select(single_select $select) {
1060 $select = clone($select);
1061 if (empty($select->formid)) {
1062 $select->formid = html_writer::random_id('single_select_f');
1066 $params = $select->url->params();
1067 if ($select->method === 'post') {
1068 $params['sesskey'] = sesskey();
1070 foreach ($params as $name=>$value) {
1071 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1074 if (empty($select->attributes['id'])) {
1075 $select->attributes['id'] = html_writer::random_id('single_select');
1078 if ($select->disabled) {
1079 $select->attributes['disabled'] = 'disabled';
1082 if ($select->tooltip) {
1083 $select->attributes['title'] = $select->tooltip;
1086 if ($select->label) {
1087 $output .= html_writer::tag('label', $select->label, array('for'=>$select->attributes['id']));
1090 if ($select->helpicon instanceof help_icon) {
1091 $output .= $this->render($select->helpicon);
1094 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1096 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1097 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
1099 $nothing = empty($select->nothing) ? false : key($select->nothing);
1100 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1102 // then div wrapper for xhtml strictness
1103 $output = html_writer::tag('div', $output);
1105 // now the form itself around it
1106 $formattributes = array('method' => $select->method,
1107 'action' => $select->url->out_omit_querystring(),
1108 'id' => $select->formid);
1109 $output = html_writer::tag('form', $output, $formattributes);
1111 // and finally one more wrapper with class
1112 return html_writer::tag('div', $output, array('class' => $select->class));
1116 * Returns a form with a url select widget.
1117 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1118 * @param string $selected selected element
1119 * @param array $nothing
1120 * @param string $formid
1121 * @return string HTML fragment
1123 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1124 $select = new url_select($urls, $selected, $nothing, $formid);
1125 return $this->render($select);
1129 * Internal implementation of url_select rendering
1130 * @param single_select $select
1131 * @return string HTML fragment
1133 protected function render_url_select(url_select $select) {
1134 $select = clone($select);
1135 if (empty($select->formid)) {
1136 $select->formid = html_writer::random_id('url_select_f');
1139 if (empty($select->attributes['id'])) {
1140 $select->attributes['id'] = html_writer::random_id('url_select');
1143 if ($select->disabled) {
1144 $select->attributes['disabled'] = 'disabled';
1147 if ($select->tooltip) {
1148 $select->attributes['title'] = $select->tooltip;
1153 if ($select->label) {
1154 $output .= html_writer::tag('label', $select->label, array('for'=>$select->attributes['id']));
1157 if ($select->helpicon instanceof help_icon) {
1158 $output .= $this->render($select->helpicon);
1161 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1162 $output .= html_writer::select($select->urls, 'jump', $select->selected, $select->nothing, $select->attributes);
1164 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1165 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
1167 $nothing = empty($select->nothing) ? false : key($select->nothing);
1168 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1170 // then div wrapper for xhtml strictness
1171 $output = html_writer::tag('div', $output);
1173 // now the form itself around it
1174 $formattributes = array('method' => 'post',
1175 'action' => new moodle_url('/course/jumpto.php'),
1176 'id' => $select->formid);
1177 $output = html_writer::tag('form', $output, $formattributes);
1179 // and finally one more wrapper with class
1180 return html_writer::tag('div', $output, array('class' => $select->class));
1184 * Returns a string containing a link to the user documentation.
1185 * Also contains an icon by default. Shown to teachers and admin only.
1186 * @param string $path The page link after doc root and language, no leading slash.
1187 * @param string $text The text to be displayed for the link
1190 public function doc_link($path, $text) {
1193 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1195 $url = new moodle_url(get_docs_url($path));
1197 $attributes = array('href'=>$url);
1198 if (!empty($CFG->doctonewwindow)) {
1199 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1202 return html_writer::tag('a', $icon.$text, $attributes);
1207 * @param string $pix short pix name
1208 * @param string $alt mandatory alt attribute
1209 * @param strin $component standard compoennt name like 'moodle', 'mod_form', etc.
1210 * @param array $attributes htm lattributes
1211 * @return string HTML fragment
1213 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1214 $icon = new pix_icon($pix, $alt, $component, $attributes);
1215 return $this->render($icon);
1220 * @param pix_icon $icon
1221 * @return string HTML fragment
1223 protected function render_pix_icon(pix_icon $icon) {
1224 $attributes = $icon->attributes;
1225 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1226 return html_writer::empty_tag('img', $attributes);
1230 * Centered heading with attached help button (same title text)
1231 * and optional icon attached
1232 * @param string $text A heading text
1233 * @param string $page The keyword that defines a help page
1234 * @param string $component component name
1235 * @param string|moodle_url $icon
1236 * @param string $iconalt icon alt text
1237 * @return string HTML fragment
1239 public function heading_with_help($text, $helppage, $component='moodle', $icon='', $iconalt='') {
1242 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1245 $help = $this->help_icon($helppage, $text, $component);
1247 return $this->heading($image.$text.$help, 2, 'main help');
1251 * Print a help icon.
1253 * @param string $page The keyword that defines a help page
1254 * @param string $title A descriptive text for accessibility only
1255 * @param string $component component name
1256 * @param string|bool $linktext true means use $title as link text, string means link text value
1257 * @return string HTML fragment
1259 public function help_icon($helppage, $title, $component = 'moodle', $linktext='') {
1260 $icon = new help_icon($helppage, $title, $component);
1261 if ($linktext === true) {
1262 $icon->linktext = $title;
1263 } else if (!empty($linktext)) {
1264 $icon->linktext = $linktext;
1266 return $this->render($icon);
1270 * Implementation of user image rendering.
1271 * @param help_icon $helpicon
1272 * @return string HTML fragment
1274 protected function render_help_icon(help_icon $helpicon) {
1277 // first get the help image icon
1278 $src = $this->pix_url('help');
1280 if (empty($helpicon->linktext)) {
1281 $alt = $helpicon->title;
1283 $alt = get_string('helpwiththis');
1286 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1287 $output = html_writer::empty_tag('img', $attributes);
1289 // add the link text if given
1290 if (!empty($helpicon->linktext)) {
1291 // the spacing has to be done through CSS
1292 $output .= $helpicon->linktext;
1295 // now create the link around it - TODO: this will be changed during the big lang cleanup in 2.0
1296 $url = new moodle_url('/help.php', array('module' => $helpicon->component, 'file' => $helpicon->helppage .'.html'));
1298 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1299 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1301 $attributes = array('href'=>$url, 'title'=>$title);
1302 $id = html_writer::random_id('helpicon');
1303 $attributes['id'] = $id;
1304 $this->add_action_handler(new popup_action('click', $url), $id);
1305 $output = html_writer::tag('a', $output, $attributes);
1308 return html_writer::tag('span', $output, array('class' => 'helplink'));
1312 * Print scale help icon.
1314 * @param int $courseid
1315 * @param object $scale instance
1316 * @return string HTML fragment
1318 public function help_icon_scale($courseid, stdClass $scale) {
1321 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1323 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1325 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scale->id));
1326 $action = new popup_action('click', $link->url, 'ratingscale');
1328 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1332 * Creates and returns a spacer image with optional line break.
1334 * @param array $attributes
1336 * @return string HTML fragment
1338 public function spacer(array $attributes = null, $br = false) {
1339 $attributes = (array)$attributes;
1340 if (empty($attributes['width'])) {
1341 $attributes['width'] = 1;
1343 if (empty($options['height'])) {
1344 $attributes['height'] = 1;
1346 $attributes['class'] = 'spacer';
1348 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1351 $output .= '<br />';
1358 * Print the specified user's avatar.
1360 * User avatar may be obtained in two ways:
1362 * // Option 1: (shortcut for simple cases, preferred way)
1363 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1364 * $OUTPUT->user_picture($user, array('popup'=>true));
1367 * $userpic = new user_picture($user);
1368 * // Set properties of $userpic
1369 * $userpic->popup = true;
1370 * $OUTPUT->render($userpic);
1373 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1374 * If any of these are missing, the database is queried. Avoid this
1375 * if at all possible, particularly for reports. It is very bad for performance.
1376 * @param array $options associative array with user picture options, used only if not a user_picture object,
1378 * - courseid=$this->page->course->id (course id of user profile in link)
1379 * - size=35 (size of image)
1380 * - link=true (make image clickable - the link leads to user profile)
1381 * - popup=false (open in popup)
1382 * - alttext=true (add image alt attribute)
1383 * - class = image class attribute (default 'userpicture')
1384 * @return string HTML fragment
1386 public function user_picture(stdClass $user, array $options = null) {
1387 $userpicture = new user_picture($user);
1388 foreach ((array)$options as $key=>$value) {
1389 if (array_key_exists($key, $userpicture)) {
1390 $userpicture->$key = $value;
1393 return $this->render($userpicture);
1397 * Internal implementation of user image rendering.
1398 * @param user_picture $userpicture
1401 protected function render_user_picture(user_picture $userpicture) {
1404 $user = $userpicture->user;
1406 if ($userpicture->alttext) {
1407 if (!empty($user->imagealt)) {
1408 $alt = $user->imagealt;
1410 $alt = get_string('pictureof', '', fullname($user));
1416 if (empty($userpicture->size)) {
1419 } else if ($userpicture->size === true or $userpicture->size == 1) {
1422 } else if ($userpicture->size >= 50) {
1424 $size = $userpicture->size;
1427 $size = $userpicture->size;
1430 $class = $userpicture->class;
1432 if (!empty($user->picture)) {
1433 require_once($CFG->libdir.'/filelib.php');
1434 $src = new moodle_url(get_file_url($user->id.'/'.$file.'.jpg', null, 'user'));
1435 } else { // Print default user pictures (use theme version if available)
1436 $class .= ' defaultuserpic';
1437 $src = $this->pix_url('u/' . $file);
1440 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1442 // get the image html output fisrt
1443 $output = html_writer::empty_tag('img', $attributes);;
1445 // then wrap it in link if needed
1446 if (!$userpicture->link) {
1450 if (empty($userpicture->courseid)) {
1451 $courseid = $this->page->course->id;
1453 $courseid = $userpicture->courseid;
1456 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1458 $attributes = array('href'=>$url);
1460 if ($userpicture->popup) {
1461 $id = html_writer::random_id('userpicture');
1462 $attributes['id'] = $id;
1463 $this->add_action_handler(new popup_action('click', $url), $id);
1466 return html_writer::tag('a', $output, $attributes);
1470 * Prints the 'Update this Modulename' button that appears on module pages.
1472 * @param string $cmid the course_module id.
1473 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1474 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1476 public function update_module_button($cmid, $modulename) {
1478 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1479 $modulename = get_string('modulename', $modulename);
1480 $string = get_string('updatethis', '', $modulename);
1481 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1482 return $this->single_button($url, $string);
1489 * Prints a "Turn editing on/off" button in a form.
1490 * @param moodle_url $url The URL + params to send through when clicking the button
1491 * @return string HTML the button
1493 public function edit_button(moodle_url $url) {
1495 if (!empty($USER->editing)) {
1496 $string = get_string('turneditingoff');
1499 $string = get_string('turneditingon');
1503 $url = new moodle_url($url, array('edit'=>$edit));
1505 return $this->single_button($url, $string);
1509 * Prints a simple button to close a window
1511 * @param string $text The lang string for the button's label (already output from get_string())
1512 * @return string html fragment
1514 public function close_window_button($text='') {
1516 $text = get_string('closewindow');
1518 $button = new single_button(new moodle_url('#'), $text, 'get');
1519 $button->add_action(new component_action('click', 'close_window'));
1521 return $this->container($this->render($button), 'closewindow');
1525 * Output an error message. By default wraps the error message in <span class="error">.
1526 * If the error message is blank, nothing is output.
1527 * @param string $message the error message.
1528 * @return string the HTML to output.
1530 public function error_text($message) {
1531 if (empty($message)) {
1534 return html_writer::tag('span', $message, array('class' => 'error'));
1538 * Do not call this function directly.
1540 * To terminate the current script with a fatal error, call the {@link print_error}
1541 * function, or throw an exception. Doing either of those things will then call this
1542 * function to display the error, before terminating the execution.
1544 * @param string $message The message to output
1545 * @param string $moreinfourl URL where more info can be found about the error
1546 * @param string $link Link for the Continue button
1547 * @param array $backtrace The execution backtrace
1548 * @param string $debuginfo Debugging information
1549 * @return string the HTML to output.
1551 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1556 if ($this->has_started()) {
1557 // we can not always recover properly here, we have problems with output buffering,
1558 // html tables, etc.
1559 $output .= $this->opencontainers->pop_all_but_last();
1562 // It is really bad if library code throws exception when output buffering is on,
1563 // because the buffered text would be printed before our start of page.
1564 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
1565 while (ob_get_level() > 0) {
1566 $obbuffer .= ob_get_clean();
1569 // Header not yet printed
1570 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1571 // server protocol should be always present, because this render
1572 // can not be used from command line or when outputting custom XML
1573 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
1575 $this->page->set_url('/'); // no url
1576 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
1577 $this->page->set_title(get_string('error'));
1578 $output .= $this->header();
1581 $message = '<p class="errormessage">' . $message . '</p>'.
1582 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
1583 get_string('moreinformation') . '</a></p>';
1584 $output .= $this->box($message, 'errorbox');
1586 if (debugging('', DEBUG_DEVELOPER)) {
1587 if (!empty($debuginfo)) {
1588 $output .= $this->notification('<strong>Debug info:</strong> '.s($debuginfo), 'notifytiny');
1590 if (!empty($backtrace)) {
1591 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
1593 if ($obbuffer !== '' ) {
1594 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
1598 if (!empty($link)) {
1599 $output .= $this->continue_button($link);
1602 $output .= $this->footer();
1604 // Padding to encourage IE to display our error page, rather than its own.
1605 $output .= str_repeat(' ', 512);
1611 * Output a notification (that is, a status message about something that has
1614 * @param string $message the message to print out
1615 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
1616 * @return string the HTML to output.
1618 public function notification($message, $classes = 'notifyproblem') {
1619 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
1623 * Print a continue button that goes to a particular URL.
1625 * @param string|moodle_url $url The url the button goes to.
1626 * @return string the HTML to output.
1628 public function continue_button($url) {
1629 if (!($url instanceof moodle_url)) {
1630 $url = new moodle_url($url);
1632 $button = new single_button($url, get_string('continue'), 'get');
1633 $button->class = 'continuebutton';
1635 return $this->render($button);
1639 * Prints a single paging bar to provide access to other pages (usually in a search)
1641 * @param int $totalcount Thetotal number of entries available to be paged through
1642 * @param int $page The page you are currently viewing
1643 * @param int $perpage The number of entries that should be shown per page
1644 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1645 * @param string $pagevar name of page parameter that holds the page number
1646 * @return string the HTML to output.
1648 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1649 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
1650 return $this->render($pb);
1654 * Internal implementation of paging bar rendering.
1655 * @param paging_bar $pagingbar
1658 protected function render_paging_bar(paging_bar $pagingbar) {
1660 $pagingbar = clone($pagingbar);
1661 $pagingbar->prepare($this, $this->page, $this->target);
1663 if ($pagingbar->totalcount > $pagingbar->perpage) {
1664 $output .= get_string('page') . ':';
1666 if (!empty($pagingbar->previouslink)) {
1667 $output .= ' (' . $pagingbar->previouslink . ') ';
1670 if (!empty($pagingbar->firstlink)) {
1671 $output .= ' ' . $pagingbar->firstlink . ' ...';
1674 foreach ($pagingbar->pagelinks as $link) {
1675 $output .= "  $link";
1678 if (!empty($pagingbar->lastlink)) {
1679 $output .= ' ...' . $pagingbar->lastlink . ' ';
1682 if (!empty($pagingbar->nextlink)) {
1683 $output .= '  (' . $pagingbar->nextlink . ')';
1687 return html_writer::tag('div', $output, array('class' => 'paging'));
1691 * Render a HTML table
1693 * @param object $table {@link html_table} instance containing all the information needed
1694 * @return string the HTML to output.
1696 public function table(html_table $table) {
1697 $table = clone($table);
1698 $table->prepare($this, $this->page, $this->target);
1699 $attributes = array(
1701 'width' => $table->width,
1702 'summary' => $table->summary,
1703 'cellpadding' => $table->cellpadding,
1704 'cellspacing' => $table->cellspacing,
1705 'class' => $table->get_classes_string());
1706 $output = html_writer::start_tag('table', $attributes) . "\n";
1710 if (!empty($table->head)) {
1711 $countcols = count($table->head);
1712 $output .= html_writer::start_tag('thead', $table->headclasses) . "\n";
1713 $output .= html_writer::start_tag('tr', array()) . "\n";
1714 $keys = array_keys($table->head);
1715 $lastkey = end($keys);
1717 foreach ($table->head as $key => $heading) {
1718 // Convert plain string headings into html_table_cell objects
1719 if (!($heading instanceof html_table_cell)) {
1720 $headingtext = $heading;
1721 $heading = new html_table_cell();
1722 $heading->text = $headingtext;
1723 $heading->header = true;
1726 if ($heading->header !== false) {
1727 $heading->header = true;
1730 $heading->add_classes(array('header', 'c' . $key));
1731 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1732 $heading->colspan = $table->headspan[$key];
1733 $countcols += $table->headspan[$key] - 1;
1736 if ($key == $lastkey) {
1737 $heading->add_class('lastcol');
1739 if (isset($table->colclasses[$key])) {
1740 $heading->add_class($table->colclasses[$key]);
1742 if ($table->rotateheaders) {
1743 // we need to wrap the heading content
1744 $heading->text = html_writer::tag('span', $heading->text);
1747 $attributes = array(
1748 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1749 'class' => $heading->get_classes_string(),
1750 'scope' => $heading->scope,
1751 'colspan' => $heading->colspan);
1754 if ($heading->header === true) {
1757 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1759 $output .= html_writer::end_tag('tr') . "\n";
1760 $output .= html_writer::end_tag('thead') . "\n";
1762 if (empty($table->data)) {
1763 // For valid XHTML strict every table must contain either a valid tr
1764 // or a valid tbody... both of which must contain a valid td
1765 $output .= html_writer::start_tag('tbody', array('class' => renderer_base::prepare_classes($table->bodyclasses).' empty'));
1766 $output .= html_writer::tag('tr', html_writer::tag('td', array('colspan'=>count($table->head)), ''));
1767 $output .= html_writer::end_tag('tbody');
1771 if (!empty($table->data)) {
1773 $keys = array_keys($table->data);
1774 $lastrowkey = end($keys);
1775 $output .= html_writer::start_tag('tbody', array('class' => renderer_base::prepare_classes($table->bodyclasses))) . "\n";
1777 foreach ($table->data as $key => $row) {
1778 if (($row === 'hr') && ($countcols)) {
1779 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols)) . "\n";
1781 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1782 if (!($row instanceof html_table_row)) {
1783 $newrow = new html_table_row();
1785 foreach ($row as $unused => $item) {
1786 $cell = new html_table_cell();
1787 $cell->text = $item;
1788 $newrow->cells[] = $cell;
1793 $oddeven = $oddeven ? 0 : 1;
1794 if (isset($table->rowclasses[$key])) {
1795 $row->add_classes(array_unique(html_component::clean_classes($table->rowclasses[$key])));
1798 $row->add_class('r' . $oddeven);
1799 if ($key == $lastrowkey) {
1800 $row->add_class('lastrow');
1803 $output .= html_writer::start_tag('tr', array('class' => $row->get_classes_string(), 'style' => $row->style, 'id' => $row->id)) . "\n";
1804 $keys2 = array_keys($row->cells);
1805 $lastkey = end($keys2);
1807 foreach ($row->cells as $key => $cell) {
1808 if (!($cell instanceof html_table_cell)) {
1809 $mycell = new html_table_cell();
1810 $mycell->text = $cell;
1814 if (isset($table->colclasses[$key])) {
1815 $cell->add_classes(array_unique(html_component::clean_classes($table->colclasses[$key])));
1818 $cell->add_classes('cell');
1819 $cell->add_classes('c' . $key);
1820 if ($key == $lastkey) {
1821 $cell->add_classes('lastcol');
1824 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1825 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1826 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1827 $tdattributes = array(
1828 'style' => $tdstyle . $cell->style,
1829 'colspan' => $cell->colspan,
1830 'rowspan' => $cell->rowspan,
1832 'class' => $cell->get_classes_string(),
1833 'abbr' => $cell->abbr,
1834 'scope' => $cell->scope,
1835 'title' => $cell->title);
1837 if ($cell->header === true) {
1840 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1843 $output .= html_writer::end_tag('tr') . "\n";
1845 $output .= html_writer::end_tag('tbody') . "\n";
1847 $output .= html_writer::end_tag('table') . "\n";
1849 if ($table->rotateheaders && can_use_rotated_text()) {
1850 $this->page->requires->yui2_lib('event');
1851 $this->page->requires->js('/course/report/progress/textrotate.js');
1858 * Output the place a skip link goes to.
1859 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
1860 * @return string the HTML to output.
1862 public function skip_link_target($id = null) {
1863 return html_writer::tag('span', '', array('id' => $id));
1868 * @param string $text The text of the heading
1869 * @param int $level The level of importance of the heading. Defaulting to 2
1870 * @param string $classes A space-separated list of CSS classes
1871 * @param string $id An optional ID
1872 * @return string the HTML to output.
1874 public function heading($text, $level = 2, $classes = 'main', $id = null) {
1875 $level = (integer) $level;
1876 if ($level < 1 or $level > 6) {
1877 throw new coding_exception('Heading level must be an integer between 1 and 6.');
1879 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
1884 * @param string $contents The contents of the box
1885 * @param string $classes A space-separated list of CSS classes
1886 * @param string $id An optional ID
1887 * @return string the HTML to output.
1889 public function box($contents, $classes = 'generalbox', $id = null) {
1890 return $this->box_start($classes, $id) . $contents . $this->box_end();
1894 * Outputs the opening section of a box.
1895 * @param string $classes A space-separated list of CSS classes
1896 * @param string $id An optional ID
1897 * @return string the HTML to output.
1899 public function box_start($classes = 'generalbox', $id = null) {
1900 $this->opencontainers->push('box', html_writer::end_tag('div'));
1901 return html_writer::start_tag('div', array('id' => $id,
1902 'class' => 'box ' . renderer_base::prepare_classes($classes)));
1906 * Outputs the closing section of a box.
1907 * @return string the HTML to output.
1909 public function box_end() {
1910 return $this->opencontainers->pop('box');
1914 * Outputs a container.
1915 * @param string $contents The contents of the box
1916 * @param string $classes A space-separated list of CSS classes
1917 * @param string $id An optional ID
1918 * @return string the HTML to output.
1920 public function container($contents, $classes = null, $id = null) {
1921 return $this->container_start($classes, $id) . $contents . $this->container_end();
1925 * Outputs the opening section of a container.
1926 * @param string $classes A space-separated list of CSS classes
1927 * @param string $id An optional ID
1928 * @return string the HTML to output.
1930 public function container_start($classes = null, $id = null) {
1931 $this->opencontainers->push('container', html_writer::end_tag('div'));
1932 return html_writer::start_tag('div', array('id' => $id,
1933 'class' => renderer_base::prepare_classes($classes)));
1937 * Outputs the closing section of a container.
1938 * @return string the HTML to output.
1940 public function container_end() {
1941 return $this->opencontainers->pop('container');
1945 * Make nested HTML lists out of the items
1947 * The resulting list will look something like this:
1951 * <<li>><div class='tree_item parent'>(item contents)</div>
1953 * <<li>><div class='tree_item'>(item contents)</div><</li>>
1959 * @param array[]tree_item $items
1960 * @param array[string]string $attrs html attributes passed to the top of
1962 * @return string HTML
1964 function tree_block_contents($items, $attrs=array()) {
1965 // exit if empty, we don't want an empty ul element
1966 if (empty($items)) {
1969 // array of nested li elements
1971 foreach ($items as $item) {
1972 // this applies to the li item which contains all child lists too
1973 $content = $item->content($this);
1974 $liclasses = array($item->get_css_type());
1975 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || (count($item->children)==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
1976 $liclasses[] = 'collapsed';
1978 if ($item->isactive === true) {
1979 $liclasses[] = 'current_branch';
1981 $liattr = array('class'=>join(' ',$liclasses));
1982 // class attribute on the div item which only contains the item content
1983 $divclasses = array('tree_item');
1984 if (!empty($item->children) || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
1985 $divclasses[] = 'branch';
1987 $divclasses[] = 'leaf';
1989 if (!empty($item->classes) && count($item->classes)>0) {
1990 $divclasses[] = join(' ', $item->classes);
1992 $divattr = array('class'=>join(' ', $divclasses));
1993 if (!empty($item->id)) {
1994 $divattr['id'] = $item->id;
1996 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
1997 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
1998 $content = html_writer::empty_tag('hr') . $content;
2000 $content = html_writer::tag('li', $content, $liattr);
2003 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2007 * Return the navbar content so that it can be echoed out by the layout
2008 * @return string XHTML navbar
2010 public function navbar() {
2011 return $this->page->navbar->content();
2015 * Accessibility: Right arrow-like character is
2016 * used in the breadcrumb trail, course navigation menu
2017 * (previous/next activity), calendar, and search forum block.
2018 * If the theme does not set characters, appropriate defaults
2019 * are set automatically. Please DO NOT
2020 * use < > » - these are confusing for blind users.
2023 public function rarrow() {
2024 return $this->page->theme->rarrow;
2028 * Accessibility: Right arrow-like character is
2029 * used in the breadcrumb trail, course navigation menu
2030 * (previous/next activity), calendar, and search forum block.
2031 * If the theme does not set characters, appropriate defaults
2032 * are set automatically. Please DO NOT
2033 * use < > » - these are confusing for blind users.
2036 public function larrow() {
2037 return $this->page->theme->larrow;
2041 * Returns the colours of the small MP3 player
2044 public function filter_mediaplugin_colors() {
2045 return $this->page->theme->filter_mediaplugin_colors;
2049 * Returns the colours of the big MP3 player
2052 public function resource_mp3player_colors() {
2053 return $this->page->theme->resource_mp3player_colors;
2061 * A renderer that generates output for command-line scripts.
2063 * The implementation of this renderer is probably incomplete.
2065 * @copyright 2009 Tim Hunt
2066 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2069 class core_renderer_cli extends core_renderer {
2071 * Returns the page header.
2072 * @return string HTML fragment
2074 public function header() {
2075 output_starting_hook();
2076 return $this->page->heading . "\n";
2080 * Returns a template fragment representing a Heading.
2081 * @param string $text The text of the heading
2082 * @param int $level The level of importance of the heading
2083 * @param string $classes A space-separated list of CSS classes
2084 * @param string $id An optional ID
2085 * @return string A template fragment for a heading
2087 public function heading($text, $level, $classes = 'main', $id = null) {
2091 return '=>' . $text;
2093 return '-->' . $text;
2100 * Returns a template fragment representing a fatal error.
2101 * @param string $message The message to output
2102 * @param string $moreinfourl URL where more info can be found about the error
2103 * @param string $link Link for the Continue button
2104 * @param array $backtrace The execution backtrace
2105 * @param string $debuginfo Debugging information
2106 * @return string A template fragment for a fatal error
2108 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2109 $output = "!!! $message !!!\n";
2111 if (debugging('', DEBUG_DEVELOPER)) {
2112 if (!empty($debuginfo)) {
2113 $this->notification($debuginfo, 'notifytiny');
2115 if (!empty($backtrace)) {
2116 $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2122 * Returns a template fragment representing a notification.
2123 * @param string $message The message to include
2124 * @param string $classes A space-separated list of CSS classes
2125 * @return string A template fragment for a notification
2127 public function notification($message, $classes = 'notifyproblem') {
2128 $message = clean_text($message);
2129 if ($classes === 'notifysuccess') {
2130 return "++ $message ++\n";
2132 return "!! $message !!\n";