MDL-24355 tag: minor clean up of tags changes
[moodle.git] / lib / outputrenderers.php
blob7f63cf31272988896b7fc0d635fc32cd270dc3b8
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Classes for rendering HTML output for Moodle.
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
24 * @package core
25 * @subpackage lib
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 /**
33 * Simple base class for Moodle renderers.
35 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
37 * Also has methods to facilitate generating HTML output.
39 * @copyright 2009 Tim Hunt
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 * @since Moodle 2.0
43 class renderer_base {
44 /** @var xhtml_container_stack the xhtml_container_stack to use. */
45 protected $opencontainers;
46 /** @var moodle_page the page we are rendering for. */
47 protected $page;
48 /** @var requested rendering target */
49 protected $target;
51 /**
52 * Constructor
53 * @param moodle_page $page the page we are doing output for.
54 * @param string $target one of rendering target constants
56 public function __construct(moodle_page $page, $target) {
57 $this->opencontainers = $page->opencontainers;
58 $this->page = $page;
59 $this->target = $target;
62 /**
63 * Returns rendered widget.
64 * @param renderable $widget instance with renderable interface
65 * @return string
67 public function render(renderable $widget) {
68 $rendermethod = 'render_'.get_class($widget);
69 if (method_exists($this, $rendermethod)) {
70 return $this->$rendermethod($widget);
72 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
75 /**
76 * Adds JS handlers needed for event execution for one html element id
77 * @param component_action $actions
78 * @param string $id
79 * @return string id of element, either original submitted or random new if not supplied
81 public function add_action_handler(component_action $action, $id=null) {
82 if (!$id) {
83 $id = html_writer::random_id($action->event);
85 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
86 return $id;
89 /**
90 * Have we started output yet?
91 * @return boolean true if the header has been printed.
93 public function has_started() {
94 return $this->page->state >= moodle_page::STATE_IN_BODY;
97 /**
98 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
99 * @param mixed $classes Space-separated string or array of classes
100 * @return string HTML class attribute value
102 public static function prepare_classes($classes) {
103 if (is_array($classes)) {
104 return implode(' ', array_unique($classes));
106 return $classes;
110 * Return the moodle_url for an image.
111 * The exact image location and extension is determined
112 * automatically by searching for gif|png|jpg|jpeg, please
113 * note there can not be diferent images with the different
114 * extension. The imagename is for historical reasons
115 * a relative path name, it may be changed later for core
116 * images. It is recommended to not use subdirectories
117 * in plugin and theme pix directories.
119 * There are three types of images:
120 * 1/ theme images - stored in theme/mytheme/pix/,
121 * use component 'theme'
122 * 2/ core images - stored in /pix/,
123 * overridden via theme/mytheme/pix_core/
124 * 3/ plugin images - stored in mod/mymodule/pix,
125 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
126 * example: pix_url('comment', 'mod_glossary')
128 * @param string $imagename the pathname of the image
129 * @param string $component full plugin name (aka component) or 'theme'
130 * @return moodle_url
132 public function pix_url($imagename, $component = 'moodle') {
133 return $this->page->theme->pix_url($imagename, $component);
139 * Basis for all plugin renderers.
141 * @author Petr Skoda (skodak)
142 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
143 * @since Moodle 2.0
145 class plugin_renderer_base extends renderer_base {
147 * A reference to the current general renderer probably {@see core_renderer}
148 * @var renderer_base
150 protected $output;
153 * Constructor method, calls the parent constructor
154 * @param moodle_page $page
155 * @param string $target one of rendering target constants
157 public function __construct(moodle_page $page, $target) {
158 $this->output = $page->get_renderer('core', null, $target);
159 parent::__construct($page, $target);
163 * Returns rendered widget.
164 * @param renderable $widget instance with renderable interface
165 * @return string
167 public function render(renderable $widget) {
168 $rendermethod = 'render_'.get_class($widget);
169 if (method_exists($this, $rendermethod)) {
170 return $this->$rendermethod($widget);
172 // pass to core renderer if method not found here
173 return $this->output->render($widget);
177 * Magic method used to pass calls otherwise meant for the standard renderer
178 * to it to ensure we don't go causing unnecessary grief.
180 * @param string $method
181 * @param array $arguments
182 * @return mixed
184 public function __call($method, $arguments) {
185 if (method_exists('renderer_base', $method)) {
186 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
188 if (method_exists($this->output, $method)) {
189 return call_user_func_array(array($this->output, $method), $arguments);
190 } else {
191 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
198 * The standard implementation of the core_renderer interface.
200 * @copyright 2009 Tim Hunt
201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
202 * @since Moodle 2.0
204 class core_renderer extends renderer_base {
205 /** @var string used in {@link header()}. */
206 const PERFORMANCE_INFO_TOKEN = '%%PERFORMANCEINFO%%';
207 /** @var string used in {@link header()}. */
208 const END_HTML_TOKEN = '%%ENDHTML%%';
209 /** @var string used in {@link header()}. */
210 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
211 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
212 protected $contenttype;
213 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
214 protected $metarefreshtag = '';
217 * Get the DOCTYPE declaration that should be used with this page. Designed to
218 * be called in theme layout.php files.
219 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
221 public function doctype() {
222 global $CFG;
224 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
225 $this->contenttype = 'text/html; charset=utf-8';
227 if (empty($CFG->xmlstrictheaders)) {
228 return $doctype;
231 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
232 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
233 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
234 // Firefox and other browsers that can cope natively with XHTML.
235 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
237 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
238 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
239 $this->contenttype = 'application/xml; charset=utf-8';
240 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
242 } else {
243 $prolog = '';
246 return $prolog . $doctype;
250 * The attributes that should be added to the <html> tag. Designed to
251 * be called in theme layout.php files.
252 * @return string HTML fragment.
254 public function htmlattributes() {
255 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
259 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
260 * that should be included in the <head> tag. Designed to be called in theme
261 * layout.php files.
262 * @return string HTML fragment.
264 public function standard_head_html() {
265 global $CFG, $SESSION;
266 $output = '';
267 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
268 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
269 if (!$this->page->cacheable) {
270 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
271 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
273 // This is only set by the {@link redirect()} method
274 $output .= $this->metarefreshtag;
276 // Check if a periodic refresh delay has been set and make sure we arn't
277 // already meta refreshing
278 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
279 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
282 // flow player embedding support
283 $this->page->requires->js_function_call('M.util.load_flowplayer');
285 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
287 $focus = $this->page->focuscontrol;
288 if (!empty($focus)) {
289 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
290 // This is a horrifically bad way to handle focus but it is passed in
291 // through messy formslib::moodleform
292 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
293 } else if (strpos($focus, '.')!==false) {
294 // Old style of focus, bad way to do it
295 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);
296 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
297 } else {
298 // Focus element with given id
299 $this->page->requires->js_function_call('focuscontrol', array($focus));
303 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
304 // any other custom CSS can not be overridden via themes and is highly discouraged
305 $urls = $this->page->theme->css_urls($this->page);
306 foreach ($urls as $url) {
307 $this->page->requires->css_theme($url);
310 // Get the theme javascript head and footer
311 $jsurl = $this->page->theme->javascript_url(true);
312 $this->page->requires->js($jsurl, true);
313 $jsurl = $this->page->theme->javascript_url(false);
314 $this->page->requires->js($jsurl);
316 // Perform a browser environment check for the flash version. Should only run once per login session.
317 if (!NO_MOODLE_COOKIES && isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
318 $this->page->requires->js('/lib/swfobject/swfobject.js');
319 $this->page->requires->js_init_call('M.core_flashdetect.init');
322 // Get any HTML from the page_requirements_manager.
323 $output .= $this->page->requires->get_head_code($this->page, $this);
325 // List alternate versions.
326 foreach ($this->page->alternateversions as $type => $alt) {
327 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
328 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
331 if (!empty($CFG->additionalhtmlhead)) {
332 $output .= "\n".$CFG->additionalhtmlhead;
335 return $output;
339 * The standard tags (typically skip links) that should be output just inside
340 * the start of the <body> tag. Designed to be called in theme layout.php files.
341 * @return string HTML fragment.
343 public function standard_top_of_body_html() {
344 global $CFG;
345 $output = $this->page->requires->get_top_of_body_code();
346 if (!empty($CFG->additionalhtmltopofbody)) {
347 $output .= "\n".$CFG->additionalhtmltopofbody;
349 return $output;
353 * The standard tags (typically performance information and validation links,
354 * if we are in developer debug mode) that should be output in the footer area
355 * of the page. Designed to be called in theme layout.php files.
356 * @return string HTML fragment.
358 public function standard_footer_html() {
359 global $CFG, $SCRIPT;
361 // This function is normally called from a layout.php file in {@link header()}
362 // but some of the content won't be known until later, so we return a placeholder
363 // for now. This will be replaced with the real content in {@link footer()}.
364 $output = self::PERFORMANCE_INFO_TOKEN;
365 if ($this->page->devicetypeinuse == 'legacy') {
366 // The legacy theme is in use print the notification
367 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
370 // Get links to switch device types (only shown for users not on a default device)
371 $output .= $this->theme_switch_links();
373 if (!empty($CFG->debugpageinfo)) {
374 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
376 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
377 // Add link to profiling report if necessary
378 if (function_exists('profiling_is_running') && profiling_is_running()) {
379 $txt = get_string('profiledscript', 'admin');
380 $title = get_string('profiledscriptview', 'admin');
381 $url = $CFG->wwwroot . '/admin/report/profiling/index.php?script=' . urlencode($SCRIPT);
382 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
383 $output .= '<div class="profilingfooter">' . $link . '</div>';
385 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/admin/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
387 if (!empty($CFG->debugvalidators)) {
388 $output .= '<div class="validators"><ul>
389 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
390 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
391 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
392 </ul></div>';
394 if (!empty($CFG->additionalhtmlfooter)) {
395 $output .= "\n".$CFG->additionalhtmlfooter;
397 return $output;
401 * The standard tags (typically script tags that are not needed earlier) that
402 * should be output after everything else, . Designed to be called in theme layout.php files.
403 * @return string HTML fragment.
405 public function standard_end_of_body_html() {
406 // This function is normally called from a layout.php file in {@link header()}
407 // but some of the content won't be known until later, so we return a placeholder
408 // for now. This will be replaced with the real content in {@link footer()}.
409 return self::END_HTML_TOKEN;
413 * Return the standard string that says whether you are logged in (and switched
414 * roles/logged in as another user).
415 * @return string HTML fragment.
417 public function login_info() {
418 global $USER, $CFG, $DB, $SESSION;
420 if (during_initial_install()) {
421 return '';
424 $loginapge = ((string)$this->page->url === get_login_url());
425 $course = $this->page->course;
427 if (session_is_loggedinas()) {
428 $realuser = session_get_realuser();
429 $fullname = fullname($realuser, true);
430 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
431 } else {
432 $realuserinfo = '';
435 $loginurl = get_login_url();
437 if (empty($course->id)) {
438 // $course->id is not defined during installation
439 return '';
440 } else if (isloggedin()) {
441 $context = get_context_instance(CONTEXT_COURSE, $course->id);
443 $fullname = fullname($USER, true);
444 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
445 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
446 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
447 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
449 if (isguestuser()) {
450 $loggedinas = $realuserinfo.get_string('loggedinasguest');
451 if (!$loginapge) {
452 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
454 } else if (is_role_switched($course->id)) { // Has switched roles
455 $rolename = '';
456 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
457 $rolename = ': '.format_string($role->name);
459 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
460 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
461 } else {
462 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
463 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
465 } else {
466 $loggedinas = get_string('loggedinnot', 'moodle');
467 if (!$loginapge) {
468 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
472 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
474 if (isset($SESSION->justloggedin)) {
475 unset($SESSION->justloggedin);
476 if (!empty($CFG->displayloginfailures)) {
477 if (!isguestuser()) {
478 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
479 $loggedinas .= '&nbsp;<div class="loginfailures">';
480 if (empty($count->accounts)) {
481 $loggedinas .= get_string('failedloginattempts', '', $count);
482 } else {
483 $loggedinas .= get_string('failedloginattemptsall', '', $count);
485 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
486 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
487 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
489 $loggedinas .= '</div>';
495 return $loggedinas;
499 * Return the 'back' link that normally appears in the footer.
500 * @return string HTML fragment.
502 public function home_link() {
503 global $CFG, $SITE;
505 if ($this->page->pagetype == 'site-index') {
506 // Special case for site home page - please do not remove
507 return '<div class="sitelink">' .
508 '<a title="Moodle" href="http://moodle.org/">' .
509 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
511 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
512 // Special case for during install/upgrade.
513 return '<div class="sitelink">'.
514 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
515 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
517 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
518 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
519 get_string('home') . '</a></div>';
521 } else {
522 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
523 format_string($this->page->course->shortname) . '</a></div>';
528 * Redirects the user by any means possible given the current state
530 * This function should not be called directly, it should always be called using
531 * the redirect function in lib/weblib.php
533 * The redirect function should really only be called before page output has started
534 * however it will allow itself to be called during the state STATE_IN_BODY
536 * @param string $encodedurl The URL to send to encoded if required
537 * @param string $message The message to display to the user if any
538 * @param int $delay The delay before redirecting a user, if $message has been
539 * set this is a requirement and defaults to 3, set to 0 no delay
540 * @param boolean $debugdisableredirect this redirect has been disabled for
541 * debugging purposes. Display a message that explains, and don't
542 * trigger the redirect.
543 * @return string The HTML to display to the user before dying, may contain
544 * meta refresh, javascript refresh, and may have set header redirects
546 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
547 global $CFG;
548 $url = str_replace('&amp;', '&', $encodedurl);
550 switch ($this->page->state) {
551 case moodle_page::STATE_BEFORE_HEADER :
552 // No output yet it is safe to delivery the full arsenal of redirect methods
553 if (!$debugdisableredirect) {
554 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
555 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
556 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
558 $output = $this->header();
559 break;
560 case moodle_page::STATE_PRINTING_HEADER :
561 // We should hopefully never get here
562 throw new coding_exception('You cannot redirect while printing the page header');
563 break;
564 case moodle_page::STATE_IN_BODY :
565 // We really shouldn't be here but we can deal with this
566 debugging("You should really redirect before you start page output");
567 if (!$debugdisableredirect) {
568 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
570 $output = $this->opencontainers->pop_all_but_last();
571 break;
572 case moodle_page::STATE_DONE :
573 // Too late to be calling redirect now
574 throw new coding_exception('You cannot redirect after the entire page has been generated');
575 break;
577 $output .= $this->notification($message, 'redirectmessage');
578 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
579 if ($debugdisableredirect) {
580 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
582 $output .= $this->footer();
583 return $output;
587 * Start output by sending the HTTP headers, and printing the HTML <head>
588 * and the start of the <body>.
590 * To control what is printed, you should set properties on $PAGE. If you
591 * are familiar with the old {@link print_header()} function from Moodle 1.9
592 * you will find that there are properties on $PAGE that correspond to most
593 * of the old parameters to could be passed to print_header.
595 * Not that, in due course, the remaining $navigation, $menu parameters here
596 * will be replaced by more properties of $PAGE, but that is still to do.
598 * @return string HTML that you must output this, preferably immediately.
600 public function header() {
601 global $USER, $CFG;
603 if (session_is_loggedinas()) {
604 $this->page->add_body_class('userloggedinas');
607 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
609 // Find the appropriate page layout file, based on $this->page->pagelayout.
610 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
611 // Render the layout using the layout file.
612 $rendered = $this->render_page_layout($layoutfile);
614 // Slice the rendered output into header and footer.
615 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
616 if ($cutpos === false) {
617 throw new coding_exception('page layout file ' . $layoutfile .
618 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
620 $header = substr($rendered, 0, $cutpos);
621 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
623 if (empty($this->contenttype)) {
624 debugging('The page layout file did not call $OUTPUT->doctype()');
625 $header = $this->doctype() . $header;
628 send_headers($this->contenttype, $this->page->cacheable);
630 $this->opencontainers->push('header/footer', $footer);
631 $this->page->set_state(moodle_page::STATE_IN_BODY);
633 return $header . $this->skip_link_target('maincontent');
637 * Renders and outputs the page layout file.
638 * @param string $layoutfile The name of the layout file
639 * @return string HTML code
641 protected function render_page_layout($layoutfile) {
642 global $CFG, $SITE, $USER;
643 // The next lines are a bit tricky. The point is, here we are in a method
644 // of a renderer class, and this object may, or may not, be the same as
645 // the global $OUTPUT object. When rendering the page layout file, we want to use
646 // this object. However, people writing Moodle code expect the current
647 // renderer to be called $OUTPUT, not $this, so define a variable called
648 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
649 $OUTPUT = $this;
650 $PAGE = $this->page;
651 $COURSE = $this->page->course;
653 ob_start();
654 include($layoutfile);
655 $rendered = ob_get_contents();
656 ob_end_clean();
657 return $rendered;
661 * Outputs the page's footer
662 * @return string HTML fragment
664 public function footer() {
665 global $CFG, $DB;
667 $output = $this->container_end_all(true);
669 $footer = $this->opencontainers->pop('header/footer');
671 if (debugging() and $DB and $DB->is_transaction_started()) {
672 // TODO: MDL-20625 print warning - transaction will be rolled back
675 // Provide some performance info if required
676 $performanceinfo = '';
677 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
678 $perf = get_performance_info();
679 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
680 error_log("PERF: " . $perf['txt']);
682 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
683 $performanceinfo = $perf['html'];
686 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
688 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
690 $this->page->set_state(moodle_page::STATE_DONE);
692 return $output . $footer;
696 * Close all but the last open container. This is useful in places like error
697 * handling, where you want to close all the open containers (apart from <body>)
698 * before outputting the error message.
699 * @param bool $shouldbenone assert that the stack should be empty now - causes a
700 * developer debug warning if it isn't.
701 * @return string the HTML required to close any open containers inside <body>.
703 public function container_end_all($shouldbenone = false) {
704 return $this->opencontainers->pop_all_but_last($shouldbenone);
708 * Returns lang menu or '', this method also checks forcing of languages in courses.
709 * @return string
711 public function lang_menu() {
712 global $CFG;
714 if (empty($CFG->langmenu)) {
715 return '';
718 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
719 // do not show lang menu if language forced
720 return '';
723 $currlang = current_language();
724 $langs = get_string_manager()->get_list_of_translations();
726 if (count($langs) < 2) {
727 return '';
730 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
731 $s->label = get_accesshide(get_string('language'));
732 $s->class = 'langmenu';
733 return $this->render($s);
737 * Output the row of editing icons for a block, as defined by the controls array.
738 * @param array $controls an array like {@link block_contents::$controls}.
739 * @return HTML fragment.
741 public function block_controls($controls) {
742 if (empty($controls)) {
743 return '';
745 $controlshtml = array();
746 foreach ($controls as $control) {
747 $controlshtml[] = html_writer::tag('a',
748 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
749 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
751 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
755 * Prints a nice side block with an optional header.
757 * The content is described
758 * by a {@link block_contents} object.
760 * <div id="inst{$instanceid}" class="block_{$blockname} block">
761 * <div class="header"></div>
762 * <div class="content">
763 * ...CONTENT...
764 * <div class="footer">
765 * </div>
766 * </div>
767 * <div class="annotation">
768 * </div>
769 * </div>
771 * @param block_contents $bc HTML for the content
772 * @param string $region the region the block is appearing in.
773 * @return string the HTML to be output.
775 function block(block_contents $bc, $region) {
776 $bc = clone($bc); // Avoid messing up the object passed in.
777 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
778 $bc->collapsible = block_contents::NOT_HIDEABLE;
780 if ($bc->collapsible == block_contents::HIDDEN) {
781 $bc->add_class('hidden');
783 if (!empty($bc->controls)) {
784 $bc->add_class('block_with_controls');
787 $skiptitle = strip_tags($bc->title);
788 if (empty($skiptitle)) {
789 $output = '';
790 $skipdest = '';
791 } else {
792 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
793 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
796 $output .= html_writer::start_tag('div', $bc->attributes);
798 $output .= $this->block_header($bc);
799 $output .= $this->block_content($bc);
801 $output .= html_writer::end_tag('div');
803 $output .= $this->block_annotation($bc);
805 $output .= $skipdest;
807 $this->init_block_hider_js($bc);
808 return $output;
812 * Produces a header for a block
814 * @param block_contents $bc
815 * @return string
817 protected function block_header(block_contents $bc) {
819 $title = '';
820 if ($bc->title) {
821 $title = html_writer::tag('h2', $bc->title, null);
824 $controlshtml = $this->block_controls($bc->controls);
826 $output = '';
827 if ($title || $controlshtml) {
828 $output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
830 return $output;
834 * Produces the content area for a block
836 * @param block_contents $bc
837 * @return string
839 protected function block_content(block_contents $bc) {
840 $output = html_writer::start_tag('div', array('class' => 'content'));
841 if (!$bc->title && !$this->block_controls($bc->controls)) {
842 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
844 $output .= $bc->content;
845 $output .= $this->block_footer($bc);
846 $output .= html_writer::end_tag('div');
848 return $output;
852 * Produces the footer for a block
854 * @param block_contents $bc
855 * @return string
857 protected function block_footer(block_contents $bc) {
858 $output = '';
859 if ($bc->footer) {
860 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
862 return $output;
866 * Produces the annotation for a block
868 * @param block_contents $bc
869 * @return string
871 protected function block_annotation(block_contents $bc) {
872 $output = '';
873 if ($bc->annotation) {
874 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
876 return $output;
880 * Calls the JS require function to hide a block.
881 * @param block_contents $bc A block_contents object
882 * @return void
884 protected function init_block_hider_js(block_contents $bc) {
885 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
886 $config = new stdClass;
887 $config->id = $bc->attributes['id'];
888 $config->title = strip_tags($bc->title);
889 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
890 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
891 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
893 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
894 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
899 * Render the contents of a block_list.
900 * @param array $icons the icon for each item.
901 * @param array $items the content of each item.
902 * @return string HTML
904 public function list_block_contents($icons, $items) {
905 $row = 0;
906 $lis = array();
907 foreach ($items as $key => $string) {
908 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
909 if (!empty($icons[$key])) { //test if the content has an assigned icon
910 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
912 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
913 $item .= html_writer::end_tag('li');
914 $lis[] = $item;
915 $row = 1 - $row; // Flip even/odd.
917 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
921 * Output all the blocks in a particular region.
922 * @param string $region the name of a region on this page.
923 * @return string the HTML to be output.
925 public function blocks_for_region($region) {
926 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
928 $output = '';
929 foreach ($blockcontents as $bc) {
930 if ($bc instanceof block_contents) {
931 $output .= $this->block($bc, $region);
932 } else if ($bc instanceof block_move_target) {
933 $output .= $this->block_move_target($bc);
934 } else {
935 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
938 return $output;
942 * Output a place where the block that is currently being moved can be dropped.
943 * @param block_move_target $target with the necessary details.
944 * @return string the HTML to be output.
946 public function block_move_target($target) {
947 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
951 * Renders a special html link with attached action
953 * @param string|moodle_url $url
954 * @param string $text HTML fragment
955 * @param component_action $action
956 * @param array $attributes associative array of html link attributes + disabled
957 * @return HTML fragment
959 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
960 if (!($url instanceof moodle_url)) {
961 $url = new moodle_url($url);
963 $link = new action_link($url, $text, $action, $attributes);
965 return $this->render($link);
969 * Implementation of action_link rendering
970 * @param action_link $link
971 * @return string HTML fragment
973 protected function render_action_link(action_link $link) {
974 global $CFG;
976 // A disabled link is rendered as formatted text
977 if (!empty($link->attributes['disabled'])) {
978 // do not use div here due to nesting restriction in xhtml strict
979 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
982 $attributes = $link->attributes;
983 unset($link->attributes['disabled']);
984 $attributes['href'] = $link->url;
986 if ($link->actions) {
987 if (empty($attributes['id'])) {
988 $id = html_writer::random_id('action_link');
989 $attributes['id'] = $id;
990 } else {
991 $id = $attributes['id'];
993 foreach ($link->actions as $action) {
994 $this->add_action_handler($action, $id);
998 return html_writer::tag('a', $link->text, $attributes);
1003 * Similar to action_link, image is used instead of the text
1005 * @param string|moodle_url $url A string URL or moodel_url
1006 * @param pix_icon $pixicon
1007 * @param component_action $action
1008 * @param array $attributes associative array of html link attributes + disabled
1009 * @param bool $linktext show title next to image in link
1010 * @return string HTML fragment
1012 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1013 if (!($url instanceof moodle_url)) {
1014 $url = new moodle_url($url);
1016 $attributes = (array)$attributes;
1018 if (empty($attributes['class'])) {
1019 // let ppl override the class via $options
1020 $attributes['class'] = 'action-icon';
1023 $icon = $this->render($pixicon);
1025 if ($linktext) {
1026 $text = $pixicon->attributes['alt'];
1027 } else {
1028 $text = '';
1031 return $this->action_link($url, $text.$icon, $action, $attributes);
1035 * Print a message along with button choices for Continue/Cancel
1037 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1039 * @param string $message The question to ask the user
1040 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1041 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1042 * @return string HTML fragment
1044 public function confirm($message, $continue, $cancel) {
1045 if ($continue instanceof single_button) {
1046 // ok
1047 } else if (is_string($continue)) {
1048 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1049 } else if ($continue instanceof moodle_url) {
1050 $continue = new single_button($continue, get_string('continue'), 'post');
1051 } else {
1052 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1055 if ($cancel instanceof single_button) {
1056 // ok
1057 } else if (is_string($cancel)) {
1058 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1059 } else if ($cancel instanceof moodle_url) {
1060 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1061 } else {
1062 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1065 $output = $this->box_start('generalbox', 'notice');
1066 $output .= html_writer::tag('p', $message);
1067 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1068 $output .= $this->box_end();
1069 return $output;
1073 * Returns a form with a single button.
1075 * @param string|moodle_url $url
1076 * @param string $label button text
1077 * @param string $method get or post submit method
1078 * @param array $options associative array {disabled, title, etc.}
1079 * @return string HTML fragment
1081 public function single_button($url, $label, $method='post', array $options=null) {
1082 if (!($url instanceof moodle_url)) {
1083 $url = new moodle_url($url);
1085 $button = new single_button($url, $label, $method);
1087 foreach ((array)$options as $key=>$value) {
1088 if (array_key_exists($key, $button)) {
1089 $button->$key = $value;
1093 return $this->render($button);
1097 * Internal implementation of single_button rendering
1098 * @param single_button $button
1099 * @return string HTML fragment
1101 protected function render_single_button(single_button $button) {
1102 $attributes = array('type' => 'submit',
1103 'value' => $button->label,
1104 'disabled' => $button->disabled ? 'disabled' : null,
1105 'title' => $button->tooltip);
1107 if ($button->actions) {
1108 $id = html_writer::random_id('single_button');
1109 $attributes['id'] = $id;
1110 foreach ($button->actions as $action) {
1111 $this->add_action_handler($action, $id);
1115 // first the input element
1116 $output = html_writer::empty_tag('input', $attributes);
1118 // then hidden fields
1119 $params = $button->url->params();
1120 if ($button->method === 'post') {
1121 $params['sesskey'] = sesskey();
1123 foreach ($params as $var => $val) {
1124 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1127 // then div wrapper for xhtml strictness
1128 $output = html_writer::tag('div', $output);
1130 // now the form itself around it
1131 if ($button->method === 'get') {
1132 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1133 } else {
1134 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1136 if ($url === '') {
1137 $url = '#'; // there has to be always some action
1139 $attributes = array('method' => $button->method,
1140 'action' => $url,
1141 'id' => $button->formid);
1142 $output = html_writer::tag('form', $output, $attributes);
1144 // and finally one more wrapper with class
1145 return html_writer::tag('div', $output, array('class' => $button->class));
1149 * Returns a form with a single select widget.
1150 * @param moodle_url $url form action target, includes hidden fields
1151 * @param string $name name of selection field - the changing parameter in url
1152 * @param array $options list of options
1153 * @param string $selected selected element
1154 * @param array $nothing
1155 * @param string $formid
1156 * @return string HTML fragment
1158 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1159 if (!($url instanceof moodle_url)) {
1160 $url = new moodle_url($url);
1162 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1164 return $this->render($select);
1168 * Internal implementation of single_select rendering
1169 * @param single_select $select
1170 * @return string HTML fragment
1172 protected function render_single_select(single_select $select) {
1173 $select = clone($select);
1174 if (empty($select->formid)) {
1175 $select->formid = html_writer::random_id('single_select_f');
1178 $output = '';
1179 $params = $select->url->params();
1180 if ($select->method === 'post') {
1181 $params['sesskey'] = sesskey();
1183 foreach ($params as $name=>$value) {
1184 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1187 if (empty($select->attributes['id'])) {
1188 $select->attributes['id'] = html_writer::random_id('single_select');
1191 if ($select->disabled) {
1192 $select->attributes['disabled'] = 'disabled';
1195 if ($select->tooltip) {
1196 $select->attributes['title'] = $select->tooltip;
1199 if ($select->label) {
1200 $output .= html_writer::label($select->label, $select->attributes['id']);
1203 if ($select->helpicon instanceof help_icon) {
1204 $output .= $this->render($select->helpicon);
1205 } else if ($select->helpicon instanceof old_help_icon) {
1206 $output .= $this->render($select->helpicon);
1209 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1211 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1212 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1214 $nothing = empty($select->nothing) ? false : key($select->nothing);
1215 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1217 // then div wrapper for xhtml strictness
1218 $output = html_writer::tag('div', $output);
1220 // now the form itself around it
1221 if ($select->method === 'get') {
1222 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1223 } else {
1224 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1226 $formattributes = array('method' => $select->method,
1227 'action' => $url,
1228 'id' => $select->formid);
1229 $output = html_writer::tag('form', $output, $formattributes);
1231 // and finally one more wrapper with class
1232 return html_writer::tag('div', $output, array('class' => $select->class));
1236 * Returns a form with a url select widget.
1237 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1238 * @param string $selected selected element
1239 * @param array $nothing
1240 * @param string $formid
1241 * @return string HTML fragment
1243 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1244 $select = new url_select($urls, $selected, $nothing, $formid);
1245 return $this->render($select);
1249 * Internal implementation of url_select rendering
1250 * @param single_select $select
1251 * @return string HTML fragment
1253 protected function render_url_select(url_select $select) {
1254 global $CFG;
1256 $select = clone($select);
1257 if (empty($select->formid)) {
1258 $select->formid = html_writer::random_id('url_select_f');
1261 if (empty($select->attributes['id'])) {
1262 $select->attributes['id'] = html_writer::random_id('url_select');
1265 if ($select->disabled) {
1266 $select->attributes['disabled'] = 'disabled';
1269 if ($select->tooltip) {
1270 $select->attributes['title'] = $select->tooltip;
1273 $output = '';
1275 if ($select->label) {
1276 $output .= html_writer::label($select->label, $select->attributes['id']);
1279 if ($select->helpicon instanceof help_icon) {
1280 $output .= $this->render($select->helpicon);
1281 } else if ($select->helpicon instanceof old_help_icon) {
1282 $output .= $this->render($select->helpicon);
1285 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1286 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1287 $urls = array();
1288 foreach ($select->urls as $k=>$v) {
1289 if (is_array($v)) {
1290 // optgroup structure
1291 foreach ($v as $optgrouptitle => $optgroupoptions) {
1292 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1293 if (empty($optionurl)) {
1294 $safeoptionurl = '';
1295 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1296 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1297 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1298 } else if (strpos($optionurl, '/') !== 0) {
1299 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1300 continue;
1301 } else {
1302 $safeoptionurl = $optionurl;
1304 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1307 } else {
1308 // plain list structure
1309 if (empty($k)) {
1310 // nothing selected option
1311 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1312 $k = str_replace($CFG->wwwroot, '', $k);
1313 } else if (strpos($k, '/') !== 0) {
1314 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1315 continue;
1317 $urls[$k] = $v;
1320 $selected = $select->selected;
1321 if (!empty($selected)) {
1322 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1323 $selected = str_replace($CFG->wwwroot, '', $selected);
1324 } else if (strpos($selected, '/') !== 0) {
1325 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1329 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1330 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1332 if (!$select->showbutton) {
1333 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1334 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1335 $nothing = empty($select->nothing) ? false : key($select->nothing);
1336 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1337 } else {
1338 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1341 // then div wrapper for xhtml strictness
1342 $output = html_writer::tag('div', $output);
1344 // now the form itself around it
1345 $formattributes = array('method' => 'post',
1346 'action' => new moodle_url('/course/jumpto.php'),
1347 'id' => $select->formid);
1348 $output = html_writer::tag('form', $output, $formattributes);
1350 // and finally one more wrapper with class
1351 return html_writer::tag('div', $output, array('class' => $select->class));
1355 * Returns a string containing a link to the user documentation.
1356 * Also contains an icon by default. Shown to teachers and admin only.
1357 * @param string $path The page link after doc root and language, no leading slash.
1358 * @param string $text The text to be displayed for the link
1359 * @return string
1361 public function doc_link($path, $text = '') {
1362 global $CFG;
1364 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1366 $url = new moodle_url(get_docs_url($path));
1368 $attributes = array('href'=>$url);
1369 if (!empty($CFG->doctonewwindow)) {
1370 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1373 return html_writer::tag('a', $icon.$text, $attributes);
1377 * Render icon
1378 * @param string $pix short pix name
1379 * @param string $alt mandatory alt attribute
1380 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1381 * @param array $attributes htm lattributes
1382 * @return string HTML fragment
1384 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1385 $icon = new pix_icon($pix, $alt, $component, $attributes);
1386 return $this->render($icon);
1390 * Render icon
1391 * @param pix_icon $icon
1392 * @return string HTML fragment
1394 protected function render_pix_icon(pix_icon $icon) {
1395 $attributes = $icon->attributes;
1396 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1397 return html_writer::empty_tag('img', $attributes);
1401 * Render emoticon
1402 * @param pix_emoticon $emoticon
1403 * @return string HTML fragment
1405 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1406 $attributes = $emoticon->attributes;
1407 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1408 return html_writer::empty_tag('img', $attributes);
1412 * Produces the html that represents this rating in the UI
1413 * @param $page the page object on which this rating will appear
1415 function render_rating(rating $rating) {
1416 global $CFG, $USER;
1418 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1419 return null;//ratings are turned off
1422 $ratingmanager = new rating_manager();
1423 // Initialise the JavaScript so ratings can be done by AJAX.
1424 $ratingmanager->initialise_rating_javascript($this->page);
1426 $strrate = get_string("rate", "rating");
1427 $ratinghtml = ''; //the string we'll return
1429 // permissions check - can they view the aggregate?
1430 if ($rating->user_can_view_aggregate()) {
1432 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1433 $aggregatestr = $rating->get_aggregate_string();
1435 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid)).' ';
1436 $aggregatehtml .= html_writer::start_tag('span', array('id'=>"ratingcount{$rating->itemid}"));
1437 if ($rating->count > 0) {
1438 $aggregatehtml .= "({$rating->count})";
1439 } else {
1440 $aggregatehtml .= '-';
1442 $aggregatehtml .= html_writer::end_tag('span').' ';
1444 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1445 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1447 $nonpopuplink = $rating->get_view_ratings_url();
1448 $popuplink = $rating->get_view_ratings_url(true);
1450 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1451 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1452 } else {
1453 $ratinghtml .= $aggregatehtml;
1457 $formstart = null;
1458 // if the item doesn't belong to the current user, the user has permission to rate
1459 // and we're within the assessable period
1460 if ($rating->user_can_rate()) {
1462 $rateurl = $rating->get_rate_url();
1463 $inputs = $rateurl->params();
1465 //start the rating form
1466 $formattrs = array(
1467 'id' => "postrating{$rating->itemid}",
1468 'class' => 'postratingform',
1469 'method' => 'post',
1470 'action' => $rateurl->out_omit_querystring()
1472 $formstart = html_writer::start_tag('form', $formattrs);
1473 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1475 // add the hidden inputs
1476 foreach ($inputs as $name => $value) {
1477 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1478 $formstart .= html_writer::empty_tag('input', $attributes);
1481 if (empty($ratinghtml)) {
1482 $ratinghtml .= $strrate.': ';
1484 $ratinghtml = $formstart.$ratinghtml;
1486 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1487 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1488 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1490 //output submit button
1491 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1493 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1494 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1496 if (!$rating->settings->scale->isnumeric) {
1497 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1499 $ratinghtml .= html_writer::end_tag('span');
1500 $ratinghtml .= html_writer::end_tag('div');
1501 $ratinghtml .= html_writer::end_tag('form');
1504 return $ratinghtml;
1508 * Centered heading with attached help button (same title text)
1509 * and optional icon attached
1510 * @param string $text A heading text
1511 * @param string $helpidentifier The keyword that defines a help page
1512 * @param string $component component name
1513 * @param string|moodle_url $icon
1514 * @param string $iconalt icon alt text
1515 * @return string HTML fragment
1517 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1518 $image = '';
1519 if ($icon) {
1520 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1523 $help = '';
1524 if ($helpidentifier) {
1525 $help = $this->help_icon($helpidentifier, $component);
1528 return $this->heading($image.$text.$help, 2, 'main help');
1532 * Print a help icon.
1534 * @deprecated since Moodle 2.0
1535 * @param string $page The keyword that defines a help page
1536 * @param string $title A descriptive text for accessibility only
1537 * @param string $component component name
1538 * @param string|bool $linktext true means use $title as link text, string means link text value
1539 * @return string HTML fragment
1541 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1542 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1543 $icon = new old_help_icon($helpidentifier, $title, $component);
1544 if ($linktext === true) {
1545 $icon->linktext = $title;
1546 } else if (!empty($linktext)) {
1547 $icon->linktext = $linktext;
1549 return $this->render($icon);
1553 * Implementation of user image rendering.
1554 * @param help_icon $helpicon
1555 * @return string HTML fragment
1557 protected function render_old_help_icon(old_help_icon $helpicon) {
1558 global $CFG;
1560 // first get the help image icon
1561 $src = $this->pix_url('help');
1563 if (empty($helpicon->linktext)) {
1564 $alt = $helpicon->title;
1565 } else {
1566 $alt = get_string('helpwiththis');
1569 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1570 $output = html_writer::empty_tag('img', $attributes);
1572 // add the link text if given
1573 if (!empty($helpicon->linktext)) {
1574 // the spacing has to be done through CSS
1575 $output .= $helpicon->linktext;
1578 // now create the link around it - we need https on loginhttps pages
1579 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1581 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1582 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1584 $attributes = array('href'=>$url, 'title'=>$title);
1585 $id = html_writer::random_id('helpicon');
1586 $attributes['id'] = $id;
1587 $output = html_writer::tag('a', $output, $attributes);
1589 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1591 // and finally span
1592 return html_writer::tag('span', $output, array('class' => 'helplink'));
1596 * Print a help icon.
1598 * @param string $identifier The keyword that defines a help page
1599 * @param string $component component name
1600 * @param string|bool $linktext true means use $title as link text, string means link text value
1601 * @return string HTML fragment
1603 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1604 $icon = new help_icon($identifier, $component);
1605 $icon->diag_strings();
1606 if ($linktext === true) {
1607 $icon->linktext = get_string($icon->identifier, $icon->component);
1608 } else if (!empty($linktext)) {
1609 $icon->linktext = $linktext;
1611 return $this->render($icon);
1615 * Implementation of user image rendering.
1616 * @param help_icon $helpicon
1617 * @return string HTML fragment
1619 protected function render_help_icon(help_icon $helpicon) {
1620 global $CFG;
1622 // first get the help image icon
1623 $src = $this->pix_url('help');
1625 $title = get_string($helpicon->identifier, $helpicon->component);
1627 if (empty($helpicon->linktext)) {
1628 $alt = $title;
1629 } else {
1630 $alt = get_string('helpwiththis');
1633 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1634 $output = html_writer::empty_tag('img', $attributes);
1636 // add the link text if given
1637 if (!empty($helpicon->linktext)) {
1638 // the spacing has to be done through CSS
1639 $output .= $helpicon->linktext;
1642 // now create the link around it - we need https on loginhttps pages
1643 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1645 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1646 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1648 $attributes = array('href'=>$url, 'title'=>$title);
1649 $id = html_writer::random_id('helpicon');
1650 $attributes['id'] = $id;
1651 $output = html_writer::tag('a', $output, $attributes);
1653 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1655 // and finally span
1656 return html_writer::tag('span', $output, array('class' => 'helplink'));
1660 * Print scale help icon.
1662 * @param int $courseid
1663 * @param object $scale instance
1664 * @return string HTML fragment
1666 public function help_icon_scale($courseid, stdClass $scale) {
1667 global $CFG;
1669 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1671 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1673 $scaleid = abs($scale->id);
1675 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1676 $action = new popup_action('click', $link, 'ratingscale');
1678 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1682 * Creates and returns a spacer image with optional line break.
1684 * @param array $attributes
1685 * @param boo spacer
1686 * @return string HTML fragment
1688 public function spacer(array $attributes = null, $br = false) {
1689 $attributes = (array)$attributes;
1690 if (empty($attributes['width'])) {
1691 $attributes['width'] = 1;
1693 if (empty($attributes['height'])) {
1694 $attributes['height'] = 1;
1696 $attributes['class'] = 'spacer';
1698 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1700 if (!empty($br)) {
1701 $output .= '<br />';
1704 return $output;
1708 * Print the specified user's avatar.
1710 * User avatar may be obtained in two ways:
1711 * <pre>
1712 * // Option 1: (shortcut for simple cases, preferred way)
1713 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1714 * $OUTPUT->user_picture($user, array('popup'=>true));
1716 * // Option 2:
1717 * $userpic = new user_picture($user);
1718 * // Set properties of $userpic
1719 * $userpic->popup = true;
1720 * $OUTPUT->render($userpic);
1721 * </pre>
1723 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1724 * If any of these are missing, the database is queried. Avoid this
1725 * if at all possible, particularly for reports. It is very bad for performance.
1726 * @param array $options associative array with user picture options, used only if not a user_picture object,
1727 * options are:
1728 * - courseid=$this->page->course->id (course id of user profile in link)
1729 * - size=35 (size of image)
1730 * - link=true (make image clickable - the link leads to user profile)
1731 * - popup=false (open in popup)
1732 * - alttext=true (add image alt attribute)
1733 * - class = image class attribute (default 'userpicture')
1734 * @return string HTML fragment
1736 public function user_picture(stdClass $user, array $options = null) {
1737 $userpicture = new user_picture($user);
1738 foreach ((array)$options as $key=>$value) {
1739 if (array_key_exists($key, $userpicture)) {
1740 $userpicture->$key = $value;
1743 return $this->render($userpicture);
1747 * Internal implementation of user image rendering.
1748 * @param user_picture $userpicture
1749 * @return string
1751 protected function render_user_picture(user_picture $userpicture) {
1752 global $CFG, $DB;
1754 $user = $userpicture->user;
1756 if ($userpicture->alttext) {
1757 if (!empty($user->imagealt)) {
1758 $alt = $user->imagealt;
1759 } else {
1760 $alt = get_string('pictureof', '', fullname($user));
1762 } else {
1763 $alt = '';
1766 if (empty($userpicture->size)) {
1767 $file = 'f2';
1768 $size = 35;
1769 } else if ($userpicture->size === true or $userpicture->size == 1) {
1770 $file = 'f1';
1771 $size = 100;
1772 } else if ($userpicture->size >= 50) {
1773 $file = 'f1';
1774 $size = $userpicture->size;
1775 } else {
1776 $file = 'f2';
1777 $size = $userpicture->size;
1780 $class = $userpicture->class;
1782 if ($user->picture == 1) {
1783 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1784 $src = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', $file);
1786 } else if ($user->picture == 2) {
1787 //TODO: gravatar user icon support
1789 } else { // Print default user pictures (use theme version if available)
1790 $class .= ' defaultuserpic';
1791 $src = $this->pix_url('u/' . $file);
1794 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1796 // get the image html output fisrt
1797 $output = html_writer::empty_tag('img', $attributes);;
1799 // then wrap it in link if needed
1800 if (!$userpicture->link) {
1801 return $output;
1804 if (empty($userpicture->courseid)) {
1805 $courseid = $this->page->course->id;
1806 } else {
1807 $courseid = $userpicture->courseid;
1810 if ($courseid == SITEID) {
1811 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1812 } else {
1813 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1816 $attributes = array('href'=>$url);
1818 if ($userpicture->popup) {
1819 $id = html_writer::random_id('userpicture');
1820 $attributes['id'] = $id;
1821 $this->add_action_handler(new popup_action('click', $url), $id);
1824 return html_writer::tag('a', $output, $attributes);
1828 * Internal implementation of file tree viewer items rendering.
1829 * @param array $dir
1830 * @return string
1832 public function htmllize_file_tree($dir) {
1833 if (empty($dir['subdirs']) and empty($dir['files'])) {
1834 return '';
1836 $result = '<ul>';
1837 foreach ($dir['subdirs'] as $subdir) {
1838 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1840 foreach ($dir['files'] as $file) {
1841 $filename = $file->get_filename();
1842 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1844 $result .= '</ul>';
1846 return $result;
1849 * Print the file picker
1851 * <pre>
1852 * $OUTPUT->file_picker($options);
1853 * </pre>
1855 * @param array $options associative array with file manager options
1856 * options are:
1857 * maxbytes=>-1,
1858 * itemid=>0,
1859 * client_id=>uniqid(),
1860 * acepted_types=>'*',
1861 * return_types=>FILE_INTERNAL,
1862 * context=>$PAGE->context
1863 * @return string HTML fragment
1865 public function file_picker($options) {
1866 $fp = new file_picker($options);
1867 return $this->render($fp);
1870 * Internal implementation of file picker rendering.
1871 * @param file_picker $fp
1872 * @return string
1874 public function render_file_picker(file_picker $fp) {
1875 global $CFG, $OUTPUT, $USER;
1876 $options = $fp->options;
1877 $client_id = $options->client_id;
1878 $strsaved = get_string('filesaved', 'repository');
1879 $straddfile = get_string('openpicker', 'repository');
1880 $strloading = get_string('loading', 'repository');
1881 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1883 $currentfile = $options->currentfile;
1884 if (empty($currentfile)) {
1885 $currentfile = get_string('nofilesattached', 'repository');
1887 if ($options->maxbytes) {
1888 $size = $options->maxbytes;
1889 } else {
1890 $size = get_max_upload_file_size();
1892 if ($size == -1) {
1893 $maxsize = '';
1894 } else {
1895 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
1897 if ($options->buttonname) {
1898 $buttonname = ' name="' . $options->buttonname . '"';
1899 } else {
1900 $buttonname = '';
1902 $html = <<<EOD
1903 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1904 $icon_progress
1905 </div>
1906 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1907 <div>
1908 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
1909 <span> $maxsize </span>
1910 </div>
1911 EOD;
1912 if ($options->env != 'url') {
1913 $html .= <<<EOD
1914 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1915 EOD;
1917 $html .= '</div>';
1918 return $html;
1922 * Prints the 'Update this Modulename' button that appears on module pages.
1924 * @param string $cmid the course_module id.
1925 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1926 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1928 public function update_module_button($cmid, $modulename) {
1929 global $CFG;
1930 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1931 $modulename = get_string('modulename', $modulename);
1932 $string = get_string('updatethis', '', $modulename);
1933 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1934 return $this->single_button($url, $string);
1935 } else {
1936 return '';
1941 * Prints a "Turn editing on/off" button in a form.
1942 * @param moodle_url $url The URL + params to send through when clicking the button
1943 * @return string HTML the button
1945 public function edit_button(moodle_url $url) {
1947 $url->param('sesskey', sesskey());
1948 if ($this->page->user_is_editing()) {
1949 $url->param('edit', 'off');
1950 $editstring = get_string('turneditingoff');
1951 } else {
1952 $url->param('edit', 'on');
1953 $editstring = get_string('turneditingon');
1956 return $this->single_button($url, $editstring);
1960 * Prints a simple button to close a window
1962 * @param string $text The lang string for the button's label (already output from get_string())
1963 * @return string html fragment
1965 public function close_window_button($text='') {
1966 if (empty($text)) {
1967 $text = get_string('closewindow');
1969 $button = new single_button(new moodle_url('#'), $text, 'get');
1970 $button->add_action(new component_action('click', 'close_window'));
1972 return $this->container($this->render($button), 'closewindow');
1976 * Output an error message. By default wraps the error message in <span class="error">.
1977 * If the error message is blank, nothing is output.
1978 * @param string $message the error message.
1979 * @return string the HTML to output.
1981 public function error_text($message) {
1982 if (empty($message)) {
1983 return '';
1985 return html_writer::tag('span', $message, array('class' => 'error'));
1989 * Do not call this function directly.
1991 * To terminate the current script with a fatal error, call the {@link print_error}
1992 * function, or throw an exception. Doing either of those things will then call this
1993 * function to display the error, before terminating the execution.
1995 * @param string $message The message to output
1996 * @param string $moreinfourl URL where more info can be found about the error
1997 * @param string $link Link for the Continue button
1998 * @param array $backtrace The execution backtrace
1999 * @param string $debuginfo Debugging information
2000 * @return string the HTML to output.
2002 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2003 global $CFG;
2005 $output = '';
2006 $obbuffer = '';
2008 if ($this->has_started()) {
2009 // we can not always recover properly here, we have problems with output buffering,
2010 // html tables, etc.
2011 $output .= $this->opencontainers->pop_all_but_last();
2013 } else {
2014 // It is really bad if library code throws exception when output buffering is on,
2015 // because the buffered text would be printed before our start of page.
2016 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2017 error_reporting(0); // disable notices from gzip compression, etc.
2018 while (ob_get_level() > 0) {
2019 $buff = ob_get_clean();
2020 if ($buff === false) {
2021 break;
2023 $obbuffer .= $buff;
2025 error_reporting($CFG->debug);
2027 // Header not yet printed
2028 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2029 // server protocol should be always present, because this render
2030 // can not be used from command line or when outputting custom XML
2031 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2033 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2034 $this->page->set_url('/'); // no url
2035 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2036 $this->page->set_title(get_string('error'));
2037 $this->page->set_heading($this->page->course->fullname);
2038 $output .= $this->header();
2041 $message = '<p class="errormessage">' . $message . '</p>'.
2042 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2043 get_string('moreinformation') . '</a></p>';
2044 $output .= $this->box($message, 'errorbox');
2046 if (debugging('', DEBUG_DEVELOPER)) {
2047 if (!empty($debuginfo)) {
2048 $debuginfo = s($debuginfo); // removes all nasty JS
2049 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2050 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2052 if (!empty($backtrace)) {
2053 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2055 if ($obbuffer !== '' ) {
2056 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2060 if (!empty($link)) {
2061 $output .= $this->continue_button($link);
2064 $output .= $this->footer();
2066 // Padding to encourage IE to display our error page, rather than its own.
2067 $output .= str_repeat(' ', 512);
2069 return $output;
2073 * Output a notification (that is, a status message about something that has
2074 * just happened).
2076 * @param string $message the message to print out
2077 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2078 * @return string the HTML to output.
2080 public function notification($message, $classes = 'notifyproblem') {
2081 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2085 * Print a continue button that goes to a particular URL.
2087 * @param string|moodle_url $url The url the button goes to.
2088 * @return string the HTML to output.
2090 public function continue_button($url) {
2091 if (!($url instanceof moodle_url)) {
2092 $url = new moodle_url($url);
2094 $button = new single_button($url, get_string('continue'), 'get');
2095 $button->class = 'continuebutton';
2097 return $this->render($button);
2101 * Prints a single paging bar to provide access to other pages (usually in a search)
2103 * @param int $totalcount The total number of entries available to be paged through
2104 * @param int $page The page you are currently viewing
2105 * @param int $perpage The number of entries that should be shown per page
2106 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2107 * @param string $pagevar name of page parameter that holds the page number
2108 * @return string the HTML to output.
2110 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2111 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2112 return $this->render($pb);
2116 * Internal implementation of paging bar rendering.
2117 * @param paging_bar $pagingbar
2118 * @return string
2120 protected function render_paging_bar(paging_bar $pagingbar) {
2121 $output = '';
2122 $pagingbar = clone($pagingbar);
2123 $pagingbar->prepare($this, $this->page, $this->target);
2125 if ($pagingbar->totalcount > $pagingbar->perpage) {
2126 $output .= get_string('page') . ':';
2128 if (!empty($pagingbar->previouslink)) {
2129 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2132 if (!empty($pagingbar->firstlink)) {
2133 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2136 foreach ($pagingbar->pagelinks as $link) {
2137 $output .= "&#160;&#160;$link";
2140 if (!empty($pagingbar->lastlink)) {
2141 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2144 if (!empty($pagingbar->nextlink)) {
2145 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2149 return html_writer::tag('div', $output, array('class' => 'paging'));
2153 * Output the place a skip link goes to.
2154 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2155 * @return string the HTML to output.
2157 public function skip_link_target($id = null) {
2158 return html_writer::tag('span', '', array('id' => $id));
2162 * Outputs a heading
2163 * @param string $text The text of the heading
2164 * @param int $level The level of importance of the heading. Defaulting to 2
2165 * @param string $classes A space-separated list of CSS classes
2166 * @param string $id An optional ID
2167 * @return string the HTML to output.
2169 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2170 $level = (integer) $level;
2171 if ($level < 1 or $level > 6) {
2172 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2174 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2178 * Outputs a box.
2179 * @param string $contents The contents of the box
2180 * @param string $classes A space-separated list of CSS classes
2181 * @param string $id An optional ID
2182 * @return string the HTML to output.
2184 public function box($contents, $classes = 'generalbox', $id = null) {
2185 return $this->box_start($classes, $id) . $contents . $this->box_end();
2189 * Outputs the opening section of a box.
2190 * @param string $classes A space-separated list of CSS classes
2191 * @param string $id An optional ID
2192 * @return string the HTML to output.
2194 public function box_start($classes = 'generalbox', $id = null) {
2195 $this->opencontainers->push('box', html_writer::end_tag('div'));
2196 return html_writer::start_tag('div', array('id' => $id,
2197 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2201 * Outputs the closing section of a box.
2202 * @return string the HTML to output.
2204 public function box_end() {
2205 return $this->opencontainers->pop('box');
2209 * Outputs a container.
2210 * @param string $contents The contents of the box
2211 * @param string $classes A space-separated list of CSS classes
2212 * @param string $id An optional ID
2213 * @return string the HTML to output.
2215 public function container($contents, $classes = null, $id = null) {
2216 return $this->container_start($classes, $id) . $contents . $this->container_end();
2220 * Outputs the opening section of a container.
2221 * @param string $classes A space-separated list of CSS classes
2222 * @param string $id An optional ID
2223 * @return string the HTML to output.
2225 public function container_start($classes = null, $id = null) {
2226 $this->opencontainers->push('container', html_writer::end_tag('div'));
2227 return html_writer::start_tag('div', array('id' => $id,
2228 'class' => renderer_base::prepare_classes($classes)));
2232 * Outputs the closing section of a container.
2233 * @return string the HTML to output.
2235 public function container_end() {
2236 return $this->opencontainers->pop('container');
2240 * Make nested HTML lists out of the items
2242 * The resulting list will look something like this:
2244 * <pre>
2245 * <<ul>>
2246 * <<li>><div class='tree_item parent'>(item contents)</div>
2247 * <<ul>
2248 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2249 * <</ul>>
2250 * <</li>>
2251 * <</ul>>
2252 * </pre>
2254 * @param array[]tree_item $items
2255 * @param array[string]string $attrs html attributes passed to the top of
2256 * the list
2257 * @return string HTML
2259 function tree_block_contents($items, $attrs=array()) {
2260 // exit if empty, we don't want an empty ul element
2261 if (empty($items)) {
2262 return '';
2264 // array of nested li elements
2265 $lis = array();
2266 foreach ($items as $item) {
2267 // this applies to the li item which contains all child lists too
2268 $content = $item->content($this);
2269 $liclasses = array($item->get_css_type());
2270 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2271 $liclasses[] = 'collapsed';
2273 if ($item->isactive === true) {
2274 $liclasses[] = 'current_branch';
2276 $liattr = array('class'=>join(' ',$liclasses));
2277 // class attribute on the div item which only contains the item content
2278 $divclasses = array('tree_item');
2279 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2280 $divclasses[] = 'branch';
2281 } else {
2282 $divclasses[] = 'leaf';
2284 if (!empty($item->classes) && count($item->classes)>0) {
2285 $divclasses[] = join(' ', $item->classes);
2287 $divattr = array('class'=>join(' ', $divclasses));
2288 if (!empty($item->id)) {
2289 $divattr['id'] = $item->id;
2291 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2292 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2293 $content = html_writer::empty_tag('hr') . $content;
2295 $content = html_writer::tag('li', $content, $liattr);
2296 $lis[] = $content;
2298 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2302 * Return the navbar content so that it can be echoed out by the layout
2303 * @return string XHTML navbar
2305 public function navbar() {
2306 $items = $this->page->navbar->get_items();
2308 $htmlblocks = array();
2309 // Iterate the navarray and display each node
2310 $itemcount = count($items);
2311 $separator = get_separator();
2312 for ($i=0;$i < $itemcount;$i++) {
2313 $item = $items[$i];
2314 $item->hideicon = true;
2315 if ($i===0) {
2316 $content = html_writer::tag('li', $this->render($item));
2317 } else {
2318 $content = html_writer::tag('li', $separator.$this->render($item));
2320 $htmlblocks[] = $content;
2323 //accessibility: heading for navbar list (MDL-20446)
2324 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2325 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2326 // XHTML
2327 return $navbarcontent;
2330 protected function render_navigation_node(navigation_node $item) {
2331 $content = $item->get_content();
2332 $title = $item->get_title();
2333 if ($item->icon instanceof renderable && !$item->hideicon) {
2334 $icon = $this->render($item->icon);
2335 $content = $icon.$content; // use CSS for spacing of icons
2337 if ($item->helpbutton !== null) {
2338 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2340 if ($content === '') {
2341 return '';
2343 if ($item->action instanceof action_link) {
2344 $link = $item->action;
2345 if ($item->hidden) {
2346 $link->add_class('dimmed');
2348 $link->text = $content.$link->text; // add help icon
2349 $content = $this->render($link);
2350 } else if ($item->action instanceof moodle_url) {
2351 $attributes = array();
2352 if ($title !== '') {
2353 $attributes['title'] = $title;
2355 if ($item->hidden) {
2356 $attributes['class'] = 'dimmed_text';
2358 $content = html_writer::link($item->action, $content, $attributes);
2360 } else if (is_string($item->action) || empty($item->action)) {
2361 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2362 if ($title !== '') {
2363 $attributes['title'] = $title;
2365 if ($item->hidden) {
2366 $attributes['class'] = 'dimmed_text';
2368 $content = html_writer::tag('span', $content, $attributes);
2370 return $content;
2374 * Accessibility: Right arrow-like character is
2375 * used in the breadcrumb trail, course navigation menu
2376 * (previous/next activity), calendar, and search forum block.
2377 * If the theme does not set characters, appropriate defaults
2378 * are set automatically. Please DO NOT
2379 * use &lt; &gt; &raquo; - these are confusing for blind users.
2380 * @return string
2382 public function rarrow() {
2383 return $this->page->theme->rarrow;
2387 * Accessibility: Right arrow-like character is
2388 * used in the breadcrumb trail, course navigation menu
2389 * (previous/next activity), calendar, and search forum block.
2390 * If the theme does not set characters, appropriate defaults
2391 * are set automatically. Please DO NOT
2392 * use &lt; &gt; &raquo; - these are confusing for blind users.
2393 * @return string
2395 public function larrow() {
2396 return $this->page->theme->larrow;
2400 * Returns the custom menu if one has been set
2402 * A custom menu can be configured by browsing to
2403 * Settings: Administration > Appearance > Themes > Theme settings
2404 * and then configuring the custommenu config setting as described.
2406 * @return string
2408 public function custom_menu() {
2409 global $CFG;
2410 if (empty($CFG->custommenuitems)) {
2411 return '';
2413 $custommenu = new custom_menu();
2414 return $this->render_custom_menu($custommenu);
2418 * Renders a custom menu object (located in outputcomponents.php)
2420 * The custom menu this method produces makes use of the YUI3 menunav widget
2421 * and requires very specific html elements and classes.
2423 * @staticvar int $menucount
2424 * @param custom_menu $menu
2425 * @return string
2427 protected function render_custom_menu(custom_menu $menu) {
2428 static $menucount = 0;
2429 // If the menu has no children return an empty string
2430 if (!$menu->has_children()) {
2431 return '';
2433 // Increment the menu count. This is used for ID's that get worked with
2434 // in JavaScript as is essential
2435 $menucount++;
2436 // Initialise this custom menu
2437 $this->page->requires->js_init_call('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2438 // Build the root nodes as required by YUI
2439 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2440 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2441 $content .= html_writer::start_tag('ul');
2442 // Render each child
2443 foreach ($menu->get_children() as $item) {
2444 $content .= $this->render_custom_menu_item($item);
2446 // Close the open tags
2447 $content .= html_writer::end_tag('ul');
2448 $content .= html_writer::end_tag('div');
2449 $content .= html_writer::end_tag('div');
2450 // Return the custom menu
2451 return $content;
2455 * Renders a custom menu node as part of a submenu
2457 * The custom menu this method produces makes use of the YUI3 menunav widget
2458 * and requires very specific html elements and classes.
2460 * @see render_custom_menu()
2462 * @staticvar int $submenucount
2463 * @param custom_menu_item $menunode
2464 * @return string
2466 protected function render_custom_menu_item(custom_menu_item $menunode) {
2467 // Required to ensure we get unique trackable id's
2468 static $submenucount = 0;
2469 if ($menunode->has_children()) {
2470 // If the child has menus render it as a sub menu
2471 $submenucount++;
2472 $content = html_writer::start_tag('li');
2473 if ($menunode->get_url() !== null) {
2474 $url = $menunode->get_url();
2475 } else {
2476 $url = '#cm_submenu_'.$submenucount;
2478 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2479 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2480 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2481 $content .= html_writer::start_tag('ul');
2482 foreach ($menunode->get_children() as $menunode) {
2483 $content .= $this->render_custom_menu_item($menunode);
2485 $content .= html_writer::end_tag('ul');
2486 $content .= html_writer::end_tag('div');
2487 $content .= html_writer::end_tag('div');
2488 $content .= html_writer::end_tag('li');
2489 } else {
2490 // The node doesn't have children so produce a final menuitem
2491 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2492 if ($menunode->get_url() !== null) {
2493 $url = $menunode->get_url();
2494 } else {
2495 $url = '#';
2497 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2498 $content .= html_writer::end_tag('li');
2500 // Return the sub menu
2501 return $content;
2505 * Renders theme links for switching between default and other themes.
2507 * @return string
2509 protected function theme_switch_links() {
2511 $actualdevice = get_device_type();
2512 $currentdevice = $this->page->devicetypeinuse;
2513 $switched = ($actualdevice != $currentdevice);
2515 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2516 // The user is using the a default device and hasn't switched so don't shown the switch
2517 // device links.
2518 return '';
2521 if ($switched) {
2522 $linktext = get_string('switchdevicerecommended');
2523 $devicetype = $actualdevice;
2524 } else {
2525 $linktext = get_string('switchdevicedefault');
2526 $devicetype = 'default';
2528 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2530 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2531 $content .= html_writer::link($linkurl, $linktext);
2532 $content .= html_writer::end_tag('div');
2534 return $content;
2538 /// RENDERERS
2541 * A renderer that generates output for command-line scripts.
2543 * The implementation of this renderer is probably incomplete.
2545 * @copyright 2009 Tim Hunt
2546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2547 * @since Moodle 2.0
2549 class core_renderer_cli extends core_renderer {
2551 * Returns the page header.
2552 * @return string HTML fragment
2554 public function header() {
2555 return $this->page->heading . "\n";
2559 * Returns a template fragment representing a Heading.
2560 * @param string $text The text of the heading
2561 * @param int $level The level of importance of the heading
2562 * @param string $classes A space-separated list of CSS classes
2563 * @param string $id An optional ID
2564 * @return string A template fragment for a heading
2566 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2567 $text .= "\n";
2568 switch ($level) {
2569 case 1:
2570 return '=>' . $text;
2571 case 2:
2572 return '-->' . $text;
2573 default:
2574 return $text;
2579 * Returns a template fragment representing a fatal error.
2580 * @param string $message The message to output
2581 * @param string $moreinfourl URL where more info can be found about the error
2582 * @param string $link Link for the Continue button
2583 * @param array $backtrace The execution backtrace
2584 * @param string $debuginfo Debugging information
2585 * @return string A template fragment for a fatal error
2587 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2588 $output = "!!! $message !!!\n";
2590 if (debugging('', DEBUG_DEVELOPER)) {
2591 if (!empty($debuginfo)) {
2592 $output .= $this->notification($debuginfo, 'notifytiny');
2594 if (!empty($backtrace)) {
2595 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2599 return $output;
2603 * Returns a template fragment representing a notification.
2604 * @param string $message The message to include
2605 * @param string $classes A space-separated list of CSS classes
2606 * @return string A template fragment for a notification
2608 public function notification($message, $classes = 'notifyproblem') {
2609 $message = clean_text($message);
2610 if ($classes === 'notifysuccess') {
2611 return "++ $message ++\n";
2613 return "!! $message !!\n";
2619 * A renderer that generates output for ajax scripts.
2621 * This renderer prevents accidental sends back only json
2622 * encoded error messages, all other output is ignored.
2624 * @copyright 2010 Petr Skoda
2625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2626 * @since Moodle 2.0
2628 class core_renderer_ajax extends core_renderer {
2630 * Returns a template fragment representing a fatal error.
2631 * @param string $message The message to output
2632 * @param string $moreinfourl URL where more info can be found about the error
2633 * @param string $link Link for the Continue button
2634 * @param array $backtrace The execution backtrace
2635 * @param string $debuginfo Debugging information
2636 * @return string A template fragment for a fatal error
2638 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2639 global $CFG;
2641 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2643 $e = new stdClass();
2644 $e->error = $message;
2645 $e->stacktrace = NULL;
2646 $e->debuginfo = NULL;
2647 $e->reproductionlink = NULL;
2648 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2649 $e->reproductionlink = $link;
2650 if (!empty($debuginfo)) {
2651 $e->debuginfo = $debuginfo;
2653 if (!empty($backtrace)) {
2654 $e->stacktrace = format_backtrace($backtrace, true);
2657 $this->header();
2658 return json_encode($e);
2661 public function notification($message, $classes = 'notifyproblem') {
2664 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2667 public function header() {
2668 // unfortunately YUI iframe upload does not support application/json
2669 if (!empty($_FILES)) {
2670 @header('Content-type: text/plain; charset=utf-8');
2671 } else {
2672 @header('Content-type: application/json; charset=utf-8');
2675 /// Headers to make it not cacheable and json
2676 @header('Cache-Control: no-store, no-cache, must-revalidate');
2677 @header('Cache-Control: post-check=0, pre-check=0', false);
2678 @header('Pragma: no-cache');
2679 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2680 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2681 @header('Accept-Ranges: none');
2684 public function footer() {
2687 public function heading($text, $level = 2, $classes = 'main', $id = null) {