Merge branch 'MDL-34171_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / outputrenderers.php
blob3afdf57f217d3c376727ccf74eceea609698339f
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 {
206 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
207 * in layout files instead.
208 * @var string used in {@link header()}.
209 * @deprecated
211 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
212 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
213 protected $contenttype;
214 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
215 protected $metarefreshtag = '';
216 /** @var string unique token */
217 protected $unique_end_html_token;
218 /** @var string unique token */
219 protected $unique_performance_info_token;
220 /** @var string unique token */
221 protected $unique_main_content_token;
224 * Constructor
225 * @param moodle_page $page the page we are doing output for.
226 * @param string $target one of rendering target constants
228 public function __construct(moodle_page $page, $target) {
229 $this->opencontainers = $page->opencontainers;
230 $this->page = $page;
231 $this->target = $target;
233 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
234 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
235 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
239 * Get the DOCTYPE declaration that should be used with this page. Designed to
240 * be called in theme layout.php files.
241 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
243 public function doctype() {
244 global $CFG;
246 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
247 $this->contenttype = 'text/html; charset=utf-8';
249 if (empty($CFG->xmlstrictheaders)) {
250 return $doctype;
253 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
254 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
255 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
256 // Firefox and other browsers that can cope natively with XHTML.
257 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
259 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
260 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
261 $this->contenttype = 'application/xml; charset=utf-8';
262 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
264 } else {
265 $prolog = '';
268 return $prolog . $doctype;
272 * The attributes that should be added to the <html> tag. Designed to
273 * be called in theme layout.php files.
274 * @return string HTML fragment.
276 public function htmlattributes() {
277 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
281 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
282 * that should be included in the <head> tag. Designed to be called in theme
283 * layout.php files.
284 * @return string HTML fragment.
286 public function standard_head_html() {
287 global $CFG, $SESSION;
288 $output = '';
289 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
290 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
291 if (!$this->page->cacheable) {
292 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
293 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
295 // This is only set by the {@link redirect()} method
296 $output .= $this->metarefreshtag;
298 // Check if a periodic refresh delay has been set and make sure we arn't
299 // already meta refreshing
300 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
301 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
304 // flow player embedding support
305 $this->page->requires->js_function_call('M.util.load_flowplayer');
307 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
309 $focus = $this->page->focuscontrol;
310 if (!empty($focus)) {
311 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
312 // This is a horrifically bad way to handle focus but it is passed in
313 // through messy formslib::moodleform
314 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
315 } else if (strpos($focus, '.')!==false) {
316 // Old style of focus, bad way to do it
317 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);
318 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
319 } else {
320 // Focus element with given id
321 $this->page->requires->js_function_call('focuscontrol', array($focus));
325 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
326 // any other custom CSS can not be overridden via themes and is highly discouraged
327 $urls = $this->page->theme->css_urls($this->page);
328 foreach ($urls as $url) {
329 $this->page->requires->css_theme($url);
332 // Get the theme javascript head and footer
333 $jsurl = $this->page->theme->javascript_url(true);
334 $this->page->requires->js($jsurl, true);
335 $jsurl = $this->page->theme->javascript_url(false);
336 $this->page->requires->js($jsurl);
338 // Get any HTML from the page_requirements_manager.
339 $output .= $this->page->requires->get_head_code($this->page, $this);
341 // List alternate versions.
342 foreach ($this->page->alternateversions as $type => $alt) {
343 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
344 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
347 if (!empty($CFG->additionalhtmlhead)) {
348 $output .= "\n".$CFG->additionalhtmlhead;
351 return $output;
355 * The standard tags (typically skip links) that should be output just inside
356 * the start of the <body> tag. Designed to be called in theme layout.php files.
357 * @return string HTML fragment.
359 public function standard_top_of_body_html() {
360 global $CFG;
361 $output = $this->page->requires->get_top_of_body_code();
362 if (!empty($CFG->additionalhtmltopofbody)) {
363 $output .= "\n".$CFG->additionalhtmltopofbody;
365 return $output;
369 * The standard tags (typically performance information and validation links,
370 * if we are in developer debug mode) that should be output in the footer area
371 * of the page. Designed to be called in theme layout.php files.
372 * @return string HTML fragment.
374 public function standard_footer_html() {
375 global $CFG, $SCRIPT;
377 // This function is normally called from a layout.php file in {@link header()}
378 // but some of the content won't be known until later, so we return a placeholder
379 // for now. This will be replaced with the real content in {@link footer()}.
380 $output = $this->unique_performance_info_token;
381 if ($this->page->devicetypeinuse == 'legacy') {
382 // The legacy theme is in use print the notification
383 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
386 // Get links to switch device types (only shown for users not on a default device)
387 $output .= $this->theme_switch_links();
389 if (!empty($CFG->debugpageinfo)) {
390 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
392 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
393 // Add link to profiling report if necessary
394 if (function_exists('profiling_is_running') && profiling_is_running()) {
395 $txt = get_string('profiledscript', 'admin');
396 $title = get_string('profiledscriptview', 'admin');
397 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
398 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
399 $output .= '<div class="profilingfooter">' . $link . '</div>';
401 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
403 if (!empty($CFG->debugvalidators)) {
404 $output .= '<div class="validators"><ul>
405 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
406 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
407 <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>
408 </ul></div>';
410 if (!empty($CFG->additionalhtmlfooter)) {
411 $output .= "\n".$CFG->additionalhtmlfooter;
413 return $output;
417 * Returns standard main content placeholder.
418 * Designed to be called in theme layout.php files.
419 * @return string HTML fragment.
421 public function main_content() {
422 return $this->unique_main_content_token;
426 * The standard tags (typically script tags that are not needed earlier) that
427 * should be output after everything else, . Designed to be called in theme layout.php files.
428 * @return string HTML fragment.
430 public function standard_end_of_body_html() {
431 // This function is normally called from a layout.php file in {@link header()}
432 // but some of the content won't be known until later, so we return a placeholder
433 // for now. This will be replaced with the real content in {@link footer()}.
434 return $this->unique_end_html_token;
438 * Return the standard string that says whether you are logged in (and switched
439 * roles/logged in as another user).
440 * @return string HTML fragment.
442 public function login_info() {
443 global $USER, $CFG, $DB, $SESSION;
445 if (during_initial_install()) {
446 return '';
449 $loginapge = ((string)$this->page->url === get_login_url());
450 $course = $this->page->course;
452 if (session_is_loggedinas()) {
453 $realuser = session_get_realuser();
454 $fullname = fullname($realuser, true);
455 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
456 } else {
457 $realuserinfo = '';
460 $loginurl = get_login_url();
462 if (empty($course->id)) {
463 // $course->id is not defined during installation
464 return '';
465 } else if (isloggedin()) {
466 $context = get_context_instance(CONTEXT_COURSE, $course->id);
468 $fullname = fullname($USER, true);
469 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
470 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
471 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
472 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
474 if (isguestuser()) {
475 $loggedinas = $realuserinfo.get_string('loggedinasguest');
476 if (!$loginapge) {
477 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
479 } else if (is_role_switched($course->id)) { // Has switched roles
480 $rolename = '';
481 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
482 $rolename = ': '.format_string($role->name);
484 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
485 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
486 } else {
487 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
488 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
490 } else {
491 $loggedinas = get_string('loggedinnot', 'moodle');
492 if (!$loginapge) {
493 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
497 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
499 if (isset($SESSION->justloggedin)) {
500 unset($SESSION->justloggedin);
501 if (!empty($CFG->displayloginfailures)) {
502 if (!isguestuser()) {
503 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
504 $loggedinas .= '&nbsp;<div class="loginfailures">';
505 if (empty($count->accounts)) {
506 $loggedinas .= get_string('failedloginattempts', '', $count);
507 } else {
508 $loggedinas .= get_string('failedloginattemptsall', '', $count);
510 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) {
511 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
512 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
514 $loggedinas .= '</div>';
520 return $loggedinas;
524 * Return the 'back' link that normally appears in the footer.
525 * @return string HTML fragment.
527 public function home_link() {
528 global $CFG, $SITE;
530 if ($this->page->pagetype == 'site-index') {
531 // Special case for site home page - please do not remove
532 return '<div class="sitelink">' .
533 '<a title="Moodle" href="http://moodle.org/">' .
534 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
536 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
537 // Special case for during install/upgrade.
538 return '<div class="sitelink">'.
539 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
540 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
542 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
543 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
544 get_string('home') . '</a></div>';
546 } else {
547 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
548 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
553 * Redirects the user by any means possible given the current state
555 * This function should not be called directly, it should always be called using
556 * the redirect function in lib/weblib.php
558 * The redirect function should really only be called before page output has started
559 * however it will allow itself to be called during the state STATE_IN_BODY
561 * @param string $encodedurl The URL to send to encoded if required
562 * @param string $message The message to display to the user if any
563 * @param int $delay The delay before redirecting a user, if $message has been
564 * set this is a requirement and defaults to 3, set to 0 no delay
565 * @param boolean $debugdisableredirect this redirect has been disabled for
566 * debugging purposes. Display a message that explains, and don't
567 * trigger the redirect.
568 * @return string The HTML to display to the user before dying, may contain
569 * meta refresh, javascript refresh, and may have set header redirects
571 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
572 global $CFG;
573 $url = str_replace('&amp;', '&', $encodedurl);
575 switch ($this->page->state) {
576 case moodle_page::STATE_BEFORE_HEADER :
577 // No output yet it is safe to delivery the full arsenal of redirect methods
578 if (!$debugdisableredirect) {
579 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
580 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
581 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
583 $output = $this->header();
584 break;
585 case moodle_page::STATE_PRINTING_HEADER :
586 // We should hopefully never get here
587 throw new coding_exception('You cannot redirect while printing the page header');
588 break;
589 case moodle_page::STATE_IN_BODY :
590 // We really shouldn't be here but we can deal with this
591 debugging("You should really redirect before you start page output");
592 if (!$debugdisableredirect) {
593 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
595 $output = $this->opencontainers->pop_all_but_last();
596 break;
597 case moodle_page::STATE_DONE :
598 // Too late to be calling redirect now
599 throw new coding_exception('You cannot redirect after the entire page has been generated');
600 break;
602 $output .= $this->notification($message, 'redirectmessage');
603 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
604 if ($debugdisableredirect) {
605 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
607 $output .= $this->footer();
608 return $output;
612 * Start output by sending the HTTP headers, and printing the HTML <head>
613 * and the start of the <body>.
615 * To control what is printed, you should set properties on $PAGE. If you
616 * are familiar with the old {@link print_header()} function from Moodle 1.9
617 * you will find that there are properties on $PAGE that correspond to most
618 * of the old parameters to could be passed to print_header.
620 * Not that, in due course, the remaining $navigation, $menu parameters here
621 * will be replaced by more properties of $PAGE, but that is still to do.
623 * @return string HTML that you must output this, preferably immediately.
625 public function header() {
626 global $USER, $CFG;
628 if (session_is_loggedinas()) {
629 $this->page->add_body_class('userloggedinas');
632 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
634 // Find the appropriate page layout file, based on $this->page->pagelayout.
635 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
636 // Render the layout using the layout file.
637 $rendered = $this->render_page_layout($layoutfile);
639 // Slice the rendered output into header and footer.
640 $cutpos = strpos($rendered, $this->unique_main_content_token);
641 if ($cutpos === false) {
642 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
643 $token = self::MAIN_CONTENT_TOKEN;
644 } else {
645 $token = $this->unique_main_content_token;
648 if ($cutpos === false) {
649 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
651 $header = substr($rendered, 0, $cutpos);
652 $footer = substr($rendered, $cutpos + strlen($token));
654 if (empty($this->contenttype)) {
655 debugging('The page layout file did not call $OUTPUT->doctype()');
656 $header = $this->doctype() . $header;
659 send_headers($this->contenttype, $this->page->cacheable);
661 $this->opencontainers->push('header/footer', $footer);
662 $this->page->set_state(moodle_page::STATE_IN_BODY);
664 return $header . $this->skip_link_target('maincontent');
668 * Renders and outputs the page layout file.
669 * @param string $layoutfile The name of the layout file
670 * @return string HTML code
672 protected function render_page_layout($layoutfile) {
673 global $CFG, $SITE, $USER;
674 // The next lines are a bit tricky. The point is, here we are in a method
675 // of a renderer class, and this object may, or may not, be the same as
676 // the global $OUTPUT object. When rendering the page layout file, we want to use
677 // this object. However, people writing Moodle code expect the current
678 // renderer to be called $OUTPUT, not $this, so define a variable called
679 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
680 $OUTPUT = $this;
681 $PAGE = $this->page;
682 $COURSE = $this->page->course;
684 ob_start();
685 include($layoutfile);
686 $rendered = ob_get_contents();
687 ob_end_clean();
688 return $rendered;
692 * Outputs the page's footer
693 * @return string HTML fragment
695 public function footer() {
696 global $CFG, $DB;
698 $output = $this->container_end_all(true);
700 $footer = $this->opencontainers->pop('header/footer');
702 if (debugging() and $DB and $DB->is_transaction_started()) {
703 // TODO: MDL-20625 print warning - transaction will be rolled back
706 // Provide some performance info if required
707 $performanceinfo = '';
708 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
709 $perf = get_performance_info();
710 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
711 error_log("PERF: " . $perf['txt']);
713 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
714 $performanceinfo = $perf['html'];
717 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
719 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
721 $this->page->set_state(moodle_page::STATE_DONE);
723 return $output . $footer;
727 * Close all but the last open container. This is useful in places like error
728 * handling, where you want to close all the open containers (apart from <body>)
729 * before outputting the error message.
730 * @param bool $shouldbenone assert that the stack should be empty now - causes a
731 * developer debug warning if it isn't.
732 * @return string the HTML required to close any open containers inside <body>.
734 public function container_end_all($shouldbenone = false) {
735 return $this->opencontainers->pop_all_but_last($shouldbenone);
739 * Returns lang menu or '', this method also checks forcing of languages in courses.
740 * @return string
742 public function lang_menu() {
743 global $CFG;
745 if (empty($CFG->langmenu)) {
746 return '';
749 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
750 // do not show lang menu if language forced
751 return '';
754 $currlang = current_language();
755 $langs = get_string_manager()->get_list_of_translations();
757 if (count($langs) < 2) {
758 return '';
761 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
762 $s->label = get_accesshide(get_string('language'));
763 $s->class = 'langmenu';
764 return $this->render($s);
768 * Output the row of editing icons for a block, as defined by the controls array.
769 * @param array $controls an array like {@link block_contents::$controls}.
770 * @return HTML fragment.
772 public function block_controls($controls) {
773 if (empty($controls)) {
774 return '';
776 $controlshtml = array();
777 foreach ($controls as $control) {
778 $controlshtml[] = html_writer::tag('a',
779 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
780 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
782 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
786 * Prints a nice side block with an optional header.
788 * The content is described
789 * by a {@link block_contents} object.
791 * <div id="inst{$instanceid}" class="block_{$blockname} block">
792 * <div class="header"></div>
793 * <div class="content">
794 * ...CONTENT...
795 * <div class="footer">
796 * </div>
797 * </div>
798 * <div class="annotation">
799 * </div>
800 * </div>
802 * @param block_contents $bc HTML for the content
803 * @param string $region the region the block is appearing in.
804 * @return string the HTML to be output.
806 function block(block_contents $bc, $region) {
807 $bc = clone($bc); // Avoid messing up the object passed in.
808 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
809 $bc->collapsible = block_contents::NOT_HIDEABLE;
811 if ($bc->collapsible == block_contents::HIDDEN) {
812 $bc->add_class('hidden');
814 if (!empty($bc->controls)) {
815 $bc->add_class('block_with_controls');
818 $skiptitle = strip_tags($bc->title);
819 if (empty($skiptitle)) {
820 $output = '';
821 $skipdest = '';
822 } else {
823 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
824 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
827 $output .= html_writer::start_tag('div', $bc->attributes);
829 $output .= $this->block_header($bc);
830 $output .= $this->block_content($bc);
832 $output .= html_writer::end_tag('div');
834 $output .= $this->block_annotation($bc);
836 $output .= $skipdest;
838 $this->init_block_hider_js($bc);
839 return $output;
843 * Produces a header for a block
845 * @param block_contents $bc
846 * @return string
848 protected function block_header(block_contents $bc) {
850 $title = '';
851 if ($bc->title) {
852 $title = html_writer::tag('h2', $bc->title, null);
855 $controlshtml = $this->block_controls($bc->controls);
857 $output = '';
858 if ($title || $controlshtml) {
859 $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'));
861 return $output;
865 * Produces the content area for a block
867 * @param block_contents $bc
868 * @return string
870 protected function block_content(block_contents $bc) {
871 $output = html_writer::start_tag('div', array('class' => 'content'));
872 if (!$bc->title && !$this->block_controls($bc->controls)) {
873 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
875 $output .= $bc->content;
876 $output .= $this->block_footer($bc);
877 $output .= html_writer::end_tag('div');
879 return $output;
883 * Produces the footer for a block
885 * @param block_contents $bc
886 * @return string
888 protected function block_footer(block_contents $bc) {
889 $output = '';
890 if ($bc->footer) {
891 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
893 return $output;
897 * Produces the annotation for a block
899 * @param block_contents $bc
900 * @return string
902 protected function block_annotation(block_contents $bc) {
903 $output = '';
904 if ($bc->annotation) {
905 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
907 return $output;
911 * Calls the JS require function to hide a block.
912 * @param block_contents $bc A block_contents object
913 * @return void
915 protected function init_block_hider_js(block_contents $bc) {
916 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
917 $config = new stdClass;
918 $config->id = $bc->attributes['id'];
919 $config->title = strip_tags($bc->title);
920 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
921 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
922 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
924 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
925 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
930 * Render the contents of a block_list.
931 * @param array $icons the icon for each item.
932 * @param array $items the content of each item.
933 * @return string HTML
935 public function list_block_contents($icons, $items) {
936 $row = 0;
937 $lis = array();
938 foreach ($items as $key => $string) {
939 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
940 if (!empty($icons[$key])) { //test if the content has an assigned icon
941 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
943 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
944 $item .= html_writer::end_tag('li');
945 $lis[] = $item;
946 $row = 1 - $row; // Flip even/odd.
948 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
952 * Output all the blocks in a particular region.
953 * @param string $region the name of a region on this page.
954 * @return string the HTML to be output.
956 public function blocks_for_region($region) {
957 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
959 $output = '';
960 foreach ($blockcontents as $bc) {
961 if ($bc instanceof block_contents) {
962 $output .= $this->block($bc, $region);
963 } else if ($bc instanceof block_move_target) {
964 $output .= $this->block_move_target($bc);
965 } else {
966 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
969 return $output;
973 * Output a place where the block that is currently being moved can be dropped.
974 * @param block_move_target $target with the necessary details.
975 * @return string the HTML to be output.
977 public function block_move_target($target) {
978 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
982 * Renders a special html link with attached action
984 * @param string|moodle_url $url
985 * @param string $text HTML fragment
986 * @param component_action $action
987 * @param array $attributes associative array of html link attributes + disabled
988 * @return HTML fragment
990 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
991 if (!($url instanceof moodle_url)) {
992 $url = new moodle_url($url);
994 $link = new action_link($url, $text, $action, $attributes);
996 return $this->render($link);
1000 * Implementation of action_link rendering
1001 * @param action_link $link
1002 * @return string HTML fragment
1004 protected function render_action_link(action_link $link) {
1005 global $CFG;
1007 if ($link->text instanceof renderable) {
1008 $text = $this->render($link->text);
1009 } else {
1010 $text = $link->text;
1013 // A disabled link is rendered as formatted text
1014 if (!empty($link->attributes['disabled'])) {
1015 // do not use div here due to nesting restriction in xhtml strict
1016 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1019 $attributes = $link->attributes;
1020 unset($link->attributes['disabled']);
1021 $attributes['href'] = $link->url;
1023 if ($link->actions) {
1024 if (empty($attributes['id'])) {
1025 $id = html_writer::random_id('action_link');
1026 $attributes['id'] = $id;
1027 } else {
1028 $id = $attributes['id'];
1030 foreach ($link->actions as $action) {
1031 $this->add_action_handler($action, $id);
1035 return html_writer::tag('a', $text, $attributes);
1040 * Similar to action_link, image is used instead of the text
1042 * @param string|moodle_url $url A string URL or moodel_url
1043 * @param pix_icon $pixicon
1044 * @param component_action $action
1045 * @param array $attributes associative array of html link attributes + disabled
1046 * @param bool $linktext show title next to image in link
1047 * @return string HTML fragment
1049 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1050 if (!($url instanceof moodle_url)) {
1051 $url = new moodle_url($url);
1053 $attributes = (array)$attributes;
1055 if (empty($attributes['class'])) {
1056 // let ppl override the class via $options
1057 $attributes['class'] = 'action-icon';
1060 $icon = $this->render($pixicon);
1062 if ($linktext) {
1063 $text = $pixicon->attributes['alt'];
1064 } else {
1065 $text = '';
1068 return $this->action_link($url, $text.$icon, $action, $attributes);
1072 * Print a message along with button choices for Continue/Cancel
1074 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1076 * @param string $message The question to ask the user
1077 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1078 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1079 * @return string HTML fragment
1081 public function confirm($message, $continue, $cancel) {
1082 if ($continue instanceof single_button) {
1083 // ok
1084 } else if (is_string($continue)) {
1085 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1086 } else if ($continue instanceof moodle_url) {
1087 $continue = new single_button($continue, get_string('continue'), 'post');
1088 } else {
1089 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1092 if ($cancel instanceof single_button) {
1093 // ok
1094 } else if (is_string($cancel)) {
1095 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1096 } else if ($cancel instanceof moodle_url) {
1097 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1098 } else {
1099 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1102 $output = $this->box_start('generalbox', 'notice');
1103 $output .= html_writer::tag('p', $message);
1104 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1105 $output .= $this->box_end();
1106 return $output;
1110 * Returns a form with a single button.
1112 * @param string|moodle_url $url
1113 * @param string $label button text
1114 * @param string $method get or post submit method
1115 * @param array $options associative array {disabled, title, etc.}
1116 * @return string HTML fragment
1118 public function single_button($url, $label, $method='post', array $options=null) {
1119 if (!($url instanceof moodle_url)) {
1120 $url = new moodle_url($url);
1122 $button = new single_button($url, $label, $method);
1124 foreach ((array)$options as $key=>$value) {
1125 if (array_key_exists($key, $button)) {
1126 $button->$key = $value;
1130 return $this->render($button);
1134 * Internal implementation of single_button rendering
1135 * @param single_button $button
1136 * @return string HTML fragment
1138 protected function render_single_button(single_button $button) {
1139 $attributes = array('type' => 'submit',
1140 'value' => $button->label,
1141 'disabled' => $button->disabled ? 'disabled' : null,
1142 'title' => $button->tooltip);
1144 if ($button->actions) {
1145 $id = html_writer::random_id('single_button');
1146 $attributes['id'] = $id;
1147 foreach ($button->actions as $action) {
1148 $this->add_action_handler($action, $id);
1152 // first the input element
1153 $output = html_writer::empty_tag('input', $attributes);
1155 // then hidden fields
1156 $params = $button->url->params();
1157 if ($button->method === 'post') {
1158 $params['sesskey'] = sesskey();
1160 foreach ($params as $var => $val) {
1161 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1164 // then div wrapper for xhtml strictness
1165 $output = html_writer::tag('div', $output);
1167 // now the form itself around it
1168 if ($button->method === 'get') {
1169 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1170 } else {
1171 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1173 if ($url === '') {
1174 $url = '#'; // there has to be always some action
1176 $attributes = array('method' => $button->method,
1177 'action' => $url,
1178 'id' => $button->formid);
1179 $output = html_writer::tag('form', $output, $attributes);
1181 // and finally one more wrapper with class
1182 return html_writer::tag('div', $output, array('class' => $button->class));
1186 * Returns a form with a single select widget.
1187 * @param moodle_url $url form action target, includes hidden fields
1188 * @param string $name name of selection field - the changing parameter in url
1189 * @param array $options list of options
1190 * @param string $selected selected element
1191 * @param array $nothing
1192 * @param string $formid
1193 * @return string HTML fragment
1195 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1196 if (!($url instanceof moodle_url)) {
1197 $url = new moodle_url($url);
1199 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1201 return $this->render($select);
1205 * Internal implementation of single_select rendering
1206 * @param single_select $select
1207 * @return string HTML fragment
1209 protected function render_single_select(single_select $select) {
1210 $select = clone($select);
1211 if (empty($select->formid)) {
1212 $select->formid = html_writer::random_id('single_select_f');
1215 $output = '';
1216 $params = $select->url->params();
1217 if ($select->method === 'post') {
1218 $params['sesskey'] = sesskey();
1220 foreach ($params as $name=>$value) {
1221 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1224 if (empty($select->attributes['id'])) {
1225 $select->attributes['id'] = html_writer::random_id('single_select');
1228 if ($select->disabled) {
1229 $select->attributes['disabled'] = 'disabled';
1232 if ($select->tooltip) {
1233 $select->attributes['title'] = $select->tooltip;
1236 if ($select->label) {
1237 $output .= html_writer::label($select->label, $select->attributes['id']);
1240 if ($select->helpicon instanceof help_icon) {
1241 $output .= $this->render($select->helpicon);
1242 } else if ($select->helpicon instanceof old_help_icon) {
1243 $output .= $this->render($select->helpicon);
1246 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1248 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1249 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1251 $nothing = empty($select->nothing) ? false : key($select->nothing);
1252 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1254 // then div wrapper for xhtml strictness
1255 $output = html_writer::tag('div', $output);
1257 // now the form itself around it
1258 if ($select->method === 'get') {
1259 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1260 } else {
1261 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1263 $formattributes = array('method' => $select->method,
1264 'action' => $url,
1265 'id' => $select->formid);
1266 $output = html_writer::tag('form', $output, $formattributes);
1268 // and finally one more wrapper with class
1269 return html_writer::tag('div', $output, array('class' => $select->class));
1273 * Returns a form with a url select widget.
1274 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1275 * @param string $selected selected element
1276 * @param array $nothing
1277 * @param string $formid
1278 * @return string HTML fragment
1280 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1281 $select = new url_select($urls, $selected, $nothing, $formid);
1282 return $this->render($select);
1286 * Internal implementation of url_select rendering
1287 * @param single_select $select
1288 * @return string HTML fragment
1290 protected function render_url_select(url_select $select) {
1291 global $CFG;
1293 $select = clone($select);
1294 if (empty($select->formid)) {
1295 $select->formid = html_writer::random_id('url_select_f');
1298 if (empty($select->attributes['id'])) {
1299 $select->attributes['id'] = html_writer::random_id('url_select');
1302 if ($select->disabled) {
1303 $select->attributes['disabled'] = 'disabled';
1306 if ($select->tooltip) {
1307 $select->attributes['title'] = $select->tooltip;
1310 $output = '';
1312 if ($select->label) {
1313 $output .= html_writer::label($select->label, $select->attributes['id']);
1316 if ($select->helpicon instanceof help_icon) {
1317 $output .= $this->render($select->helpicon);
1318 } else if ($select->helpicon instanceof old_help_icon) {
1319 $output .= $this->render($select->helpicon);
1322 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1323 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1324 $urls = array();
1325 foreach ($select->urls as $k=>$v) {
1326 if (is_array($v)) {
1327 // optgroup structure
1328 foreach ($v as $optgrouptitle => $optgroupoptions) {
1329 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1330 if (empty($optionurl)) {
1331 $safeoptionurl = '';
1332 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1333 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1334 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1335 } else if (strpos($optionurl, '/') !== 0) {
1336 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1337 continue;
1338 } else {
1339 $safeoptionurl = $optionurl;
1341 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1344 } else {
1345 // plain list structure
1346 if (empty($k)) {
1347 // nothing selected option
1348 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1349 $k = str_replace($CFG->wwwroot, '', $k);
1350 } else if (strpos($k, '/') !== 0) {
1351 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1352 continue;
1354 $urls[$k] = $v;
1357 $selected = $select->selected;
1358 if (!empty($selected)) {
1359 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1360 $selected = str_replace($CFG->wwwroot, '', $selected);
1361 } else if (strpos($selected, '/') !== 0) {
1362 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1366 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1367 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1369 if (!$select->showbutton) {
1370 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1371 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1372 $nothing = empty($select->nothing) ? false : key($select->nothing);
1373 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1374 } else {
1375 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1378 // then div wrapper for xhtml strictness
1379 $output = html_writer::tag('div', $output);
1381 // now the form itself around it
1382 $formattributes = array('method' => 'post',
1383 'action' => new moodle_url('/course/jumpto.php'),
1384 'id' => $select->formid);
1385 $output = html_writer::tag('form', $output, $formattributes);
1387 // and finally one more wrapper with class
1388 return html_writer::tag('div', $output, array('class' => $select->class));
1392 * Returns a string containing a link to the user documentation.
1393 * Also contains an icon by default. Shown to teachers and admin only.
1394 * @param string $path The page link after doc root and language, no leading slash.
1395 * @param string $text The text to be displayed for the link
1396 * @return string
1398 public function doc_link($path, $text = '') {
1399 global $CFG;
1401 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1403 $url = new moodle_url(get_docs_url($path));
1405 $attributes = array('href'=>$url);
1406 if (!empty($CFG->doctonewwindow)) {
1407 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1410 return html_writer::tag('a', $icon.$text, $attributes);
1414 * Render icon
1415 * @param string $pix short pix name
1416 * @param string $alt mandatory alt attribute
1417 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1418 * @param array $attributes htm lattributes
1419 * @return string HTML fragment
1421 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1422 $icon = new pix_icon($pix, $alt, $component, $attributes);
1423 return $this->render($icon);
1427 * Render icon
1428 * @param pix_icon $icon
1429 * @return string HTML fragment
1431 protected function render_pix_icon(pix_icon $icon) {
1432 $attributes = $icon->attributes;
1433 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1434 return html_writer::empty_tag('img', $attributes);
1438 * Render emoticon
1439 * @param pix_emoticon $emoticon
1440 * @return string HTML fragment
1442 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1443 $attributes = $emoticon->attributes;
1444 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1445 return html_writer::empty_tag('img', $attributes);
1449 * Produces the html that represents this rating in the UI
1450 * @param $page the page object on which this rating will appear
1452 function render_rating(rating $rating) {
1453 global $CFG, $USER;
1455 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1456 return null;//ratings are turned off
1459 $ratingmanager = new rating_manager();
1460 // Initialise the JavaScript so ratings can be done by AJAX.
1461 $ratingmanager->initialise_rating_javascript($this->page);
1463 $strrate = get_string("rate", "rating");
1464 $ratinghtml = ''; //the string we'll return
1466 // permissions check - can they view the aggregate?
1467 if ($rating->user_can_view_aggregate()) {
1469 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1470 $aggregatestr = $rating->get_aggregate_string();
1472 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1473 if ($rating->count > 0) {
1474 $countstr = "({$rating->count})";
1475 } else {
1476 $countstr = '-';
1478 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1480 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1481 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1483 $nonpopuplink = $rating->get_view_ratings_url();
1484 $popuplink = $rating->get_view_ratings_url(true);
1486 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1487 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1488 } else {
1489 $ratinghtml .= $aggregatehtml;
1493 $formstart = null;
1494 // if the item doesn't belong to the current user, the user has permission to rate
1495 // and we're within the assessable period
1496 if ($rating->user_can_rate()) {
1498 $rateurl = $rating->get_rate_url();
1499 $inputs = $rateurl->params();
1501 //start the rating form
1502 $formattrs = array(
1503 'id' => "postrating{$rating->itemid}",
1504 'class' => 'postratingform',
1505 'method' => 'post',
1506 'action' => $rateurl->out_omit_querystring()
1508 $formstart = html_writer::start_tag('form', $formattrs);
1509 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1511 // add the hidden inputs
1512 foreach ($inputs as $name => $value) {
1513 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1514 $formstart .= html_writer::empty_tag('input', $attributes);
1517 if (empty($ratinghtml)) {
1518 $ratinghtml .= $strrate.': ';
1520 $ratinghtml = $formstart.$ratinghtml;
1522 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1523 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1524 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1526 //output submit button
1527 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1529 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1530 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1532 if (!$rating->settings->scale->isnumeric) {
1533 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1535 $ratinghtml .= html_writer::end_tag('span');
1536 $ratinghtml .= html_writer::end_tag('div');
1537 $ratinghtml .= html_writer::end_tag('form');
1540 return $ratinghtml;
1544 * Centered heading with attached help button (same title text)
1545 * and optional icon attached
1546 * @param string $text A heading text
1547 * @param string $helpidentifier The keyword that defines a help page
1548 * @param string $component component name
1549 * @param string|moodle_url $icon
1550 * @param string $iconalt icon alt text
1551 * @return string HTML fragment
1553 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1554 $image = '';
1555 if ($icon) {
1556 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1559 $help = '';
1560 if ($helpidentifier) {
1561 $help = $this->help_icon($helpidentifier, $component);
1564 return $this->heading($image.$text.$help, 2, 'main help');
1568 * Print a help icon.
1570 * @deprecated since Moodle 2.0
1571 * @param string $page The keyword that defines a help page
1572 * @param string $title A descriptive text for accessibility only
1573 * @param string $component component name
1574 * @param string|bool $linktext true means use $title as link text, string means link text value
1575 * @return string HTML fragment
1577 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1578 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1579 $icon = new old_help_icon($helpidentifier, $title, $component);
1580 if ($linktext === true) {
1581 $icon->linktext = $title;
1582 } else if (!empty($linktext)) {
1583 $icon->linktext = $linktext;
1585 return $this->render($icon);
1589 * Implementation of user image rendering.
1590 * @param help_icon $helpicon
1591 * @return string HTML fragment
1593 protected function render_old_help_icon(old_help_icon $helpicon) {
1594 global $CFG;
1596 // first get the help image icon
1597 $src = $this->pix_url('help');
1599 if (empty($helpicon->linktext)) {
1600 $alt = $helpicon->title;
1601 } else {
1602 $alt = get_string('helpwiththis');
1605 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1606 $output = html_writer::empty_tag('img', $attributes);
1608 // add the link text if given
1609 if (!empty($helpicon->linktext)) {
1610 // the spacing has to be done through CSS
1611 $output .= $helpicon->linktext;
1614 // now create the link around it - we need https on loginhttps pages
1615 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1617 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1618 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1620 $attributes = array('href'=>$url, 'title'=>$title);
1621 $id = html_writer::random_id('helpicon');
1622 $attributes['id'] = $id;
1623 $output = html_writer::tag('a', $output, $attributes);
1625 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1627 // and finally span
1628 return html_writer::tag('span', $output, array('class' => 'helplink'));
1632 * Print a help icon.
1634 * @param string $identifier The keyword that defines a help page
1635 * @param string $component component name
1636 * @param string|bool $linktext true means use $title as link text, string means link text value
1637 * @return string HTML fragment
1639 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1640 $icon = new help_icon($identifier, $component);
1641 $icon->diag_strings();
1642 if ($linktext === true) {
1643 $icon->linktext = get_string($icon->identifier, $icon->component);
1644 } else if (!empty($linktext)) {
1645 $icon->linktext = $linktext;
1647 return $this->render($icon);
1651 * Implementation of user image rendering.
1652 * @param help_icon $helpicon
1653 * @return string HTML fragment
1655 protected function render_help_icon(help_icon $helpicon) {
1656 global $CFG;
1658 // first get the help image icon
1659 $src = $this->pix_url('help');
1661 $title = get_string($helpicon->identifier, $helpicon->component);
1663 if (empty($helpicon->linktext)) {
1664 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1665 } else {
1666 $alt = get_string('helpwiththis');
1669 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1670 $output = html_writer::empty_tag('img', $attributes);
1672 // add the link text if given
1673 if (!empty($helpicon->linktext)) {
1674 // the spacing has to be done through CSS
1675 $output .= $helpicon->linktext;
1678 // now create the link around it - we need https on loginhttps pages
1679 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1681 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1682 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1684 $attributes = array('href'=>$url, 'title'=>$title);
1685 $id = html_writer::random_id('helpicon');
1686 $attributes['id'] = $id;
1687 $output = html_writer::tag('a', $output, $attributes);
1689 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1691 // and finally span
1692 return html_writer::tag('span', $output, array('class' => 'helplink'));
1696 * Print scale help icon.
1698 * @param int $courseid
1699 * @param object $scale instance
1700 * @return string HTML fragment
1702 public function help_icon_scale($courseid, stdClass $scale) {
1703 global $CFG;
1705 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1707 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1709 $scaleid = abs($scale->id);
1711 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1712 $action = new popup_action('click', $link, 'ratingscale');
1714 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1718 * Creates and returns a spacer image with optional line break.
1720 * @param array $attributes
1721 * @param boo spacer
1722 * @return string HTML fragment
1724 public function spacer(array $attributes = null, $br = false) {
1725 $attributes = (array)$attributes;
1726 if (empty($attributes['width'])) {
1727 $attributes['width'] = 1;
1729 if (empty($attributes['height'])) {
1730 $attributes['height'] = 1;
1732 $attributes['class'] = 'spacer';
1734 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1736 if (!empty($br)) {
1737 $output .= '<br />';
1740 return $output;
1744 * Print the specified user's avatar.
1746 * User avatar may be obtained in two ways:
1747 * <pre>
1748 * // Option 1: (shortcut for simple cases, preferred way)
1749 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1750 * $OUTPUT->user_picture($user, array('popup'=>true));
1752 * // Option 2:
1753 * $userpic = new user_picture($user);
1754 * // Set properties of $userpic
1755 * $userpic->popup = true;
1756 * $OUTPUT->render($userpic);
1757 * </pre>
1759 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1760 * If any of these are missing, the database is queried. Avoid this
1761 * if at all possible, particularly for reports. It is very bad for performance.
1762 * @param array $options associative array with user picture options, used only if not a user_picture object,
1763 * options are:
1764 * - courseid=$this->page->course->id (course id of user profile in link)
1765 * - size=35 (size of image)
1766 * - link=true (make image clickable - the link leads to user profile)
1767 * - popup=false (open in popup)
1768 * - alttext=true (add image alt attribute)
1769 * - class = image class attribute (default 'userpicture')
1770 * @return string HTML fragment
1772 public function user_picture(stdClass $user, array $options = null) {
1773 $userpicture = new user_picture($user);
1774 foreach ((array)$options as $key=>$value) {
1775 if (array_key_exists($key, $userpicture)) {
1776 $userpicture->$key = $value;
1779 return $this->render($userpicture);
1783 * Internal implementation of user image rendering.
1784 * @param user_picture $userpicture
1785 * @return string
1787 protected function render_user_picture(user_picture $userpicture) {
1788 global $CFG, $DB;
1790 $user = $userpicture->user;
1792 if ($userpicture->alttext) {
1793 if (!empty($user->imagealt)) {
1794 $alt = $user->imagealt;
1795 } else {
1796 $alt = get_string('pictureof', '', fullname($user));
1798 } else {
1799 $alt = '';
1802 if (empty($userpicture->size)) {
1803 $size = 35;
1804 } else if ($userpicture->size === true or $userpicture->size == 1) {
1805 $size = 100;
1806 } else {
1807 $size = $userpicture->size;
1810 $class = $userpicture->class;
1812 if ($user->picture != 1 && $user->picture != 2) {
1813 $class .= ' defaultuserpic';
1816 $src = $userpicture->get_url($this->page, $this);
1818 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1820 // get the image html output fisrt
1821 $output = html_writer::empty_tag('img', $attributes);;
1823 // then wrap it in link if needed
1824 if (!$userpicture->link) {
1825 return $output;
1828 if (empty($userpicture->courseid)) {
1829 $courseid = $this->page->course->id;
1830 } else {
1831 $courseid = $userpicture->courseid;
1834 if ($courseid == SITEID) {
1835 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1836 } else {
1837 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1840 $attributes = array('href'=>$url);
1842 if ($userpicture->popup) {
1843 $id = html_writer::random_id('userpicture');
1844 $attributes['id'] = $id;
1845 $this->add_action_handler(new popup_action('click', $url), $id);
1848 return html_writer::tag('a', $output, $attributes);
1852 * Internal implementation of file tree viewer items rendering.
1853 * @param array $dir
1854 * @return string
1856 public function htmllize_file_tree($dir) {
1857 if (empty($dir['subdirs']) and empty($dir['files'])) {
1858 return '';
1860 $result = '<ul>';
1861 foreach ($dir['subdirs'] as $subdir) {
1862 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1864 foreach ($dir['files'] as $file) {
1865 $filename = $file->get_filename();
1866 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1868 $result .= '</ul>';
1870 return $result;
1873 * Print the file picker
1875 * <pre>
1876 * $OUTPUT->file_picker($options);
1877 * </pre>
1879 * @param array $options associative array with file manager options
1880 * options are:
1881 * maxbytes=>-1,
1882 * itemid=>0,
1883 * client_id=>uniqid(),
1884 * acepted_types=>'*',
1885 * return_types=>FILE_INTERNAL,
1886 * context=>$PAGE->context
1887 * @return string HTML fragment
1889 public function file_picker($options) {
1890 $fp = new file_picker($options);
1891 return $this->render($fp);
1894 * Internal implementation of file picker rendering.
1895 * @param file_picker $fp
1896 * @return string
1898 public function render_file_picker(file_picker $fp) {
1899 global $CFG, $OUTPUT, $USER;
1900 $options = $fp->options;
1901 $client_id = $options->client_id;
1902 $strsaved = get_string('filesaved', 'repository');
1903 $straddfile = get_string('openpicker', 'repository');
1904 $strloading = get_string('loading', 'repository');
1905 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1907 $currentfile = $options->currentfile;
1908 if (empty($currentfile)) {
1909 $currentfile = get_string('nofilesattached', 'repository');
1911 if ($options->maxbytes) {
1912 $size = $options->maxbytes;
1913 } else {
1914 $size = get_max_upload_file_size();
1916 if ($size == -1) {
1917 $maxsize = '';
1918 } else {
1919 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
1921 if ($options->buttonname) {
1922 $buttonname = ' name="' . $options->buttonname . '"';
1923 } else {
1924 $buttonname = '';
1926 $html = <<<EOD
1927 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1928 $icon_progress
1929 </div>
1930 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1931 <div>
1932 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
1933 <span> $maxsize </span>
1934 </div>
1935 EOD;
1936 if ($options->env != 'url') {
1937 $html .= <<<EOD
1938 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1939 EOD;
1941 $html .= '</div>';
1942 return $html;
1946 * Prints the 'Update this Modulename' button that appears on module pages.
1948 * @param string $cmid the course_module id.
1949 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1950 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1952 public function update_module_button($cmid, $modulename) {
1953 global $CFG;
1954 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1955 $modulename = get_string('modulename', $modulename);
1956 $string = get_string('updatethis', '', $modulename);
1957 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1958 return $this->single_button($url, $string);
1959 } else {
1960 return '';
1965 * Prints a "Turn editing on/off" button in a form.
1966 * @param moodle_url $url The URL + params to send through when clicking the button
1967 * @return string HTML the button
1969 public function edit_button(moodle_url $url) {
1971 $url->param('sesskey', sesskey());
1972 if ($this->page->user_is_editing()) {
1973 $url->param('edit', 'off');
1974 $editstring = get_string('turneditingoff');
1975 } else {
1976 $url->param('edit', 'on');
1977 $editstring = get_string('turneditingon');
1980 return $this->single_button($url, $editstring);
1984 * Prints a simple button to close a window
1986 * @param string $text The lang string for the button's label (already output from get_string())
1987 * @return string html fragment
1989 public function close_window_button($text='') {
1990 if (empty($text)) {
1991 $text = get_string('closewindow');
1993 $button = new single_button(new moodle_url('#'), $text, 'get');
1994 $button->add_action(new component_action('click', 'close_window'));
1996 return $this->container($this->render($button), 'closewindow');
2000 * Output an error message. By default wraps the error message in <span class="error">.
2001 * If the error message is blank, nothing is output.
2002 * @param string $message the error message.
2003 * @return string the HTML to output.
2005 public function error_text($message) {
2006 if (empty($message)) {
2007 return '';
2009 return html_writer::tag('span', $message, array('class' => 'error'));
2013 * Do not call this function directly.
2015 * To terminate the current script with a fatal error, call the {@link print_error}
2016 * function, or throw an exception. Doing either of those things will then call this
2017 * function to display the error, before terminating the execution.
2019 * @param string $message The message to output
2020 * @param string $moreinfourl URL where more info can be found about the error
2021 * @param string $link Link for the Continue button
2022 * @param array $backtrace The execution backtrace
2023 * @param string $debuginfo Debugging information
2024 * @return string the HTML to output.
2026 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2027 global $CFG;
2029 $output = '';
2030 $obbuffer = '';
2032 if ($this->has_started()) {
2033 // we can not always recover properly here, we have problems with output buffering,
2034 // html tables, etc.
2035 $output .= $this->opencontainers->pop_all_but_last();
2037 } else {
2038 // It is really bad if library code throws exception when output buffering is on,
2039 // because the buffered text would be printed before our start of page.
2040 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2041 error_reporting(0); // disable notices from gzip compression, etc.
2042 while (ob_get_level() > 0) {
2043 $buff = ob_get_clean();
2044 if ($buff === false) {
2045 break;
2047 $obbuffer .= $buff;
2049 error_reporting($CFG->debug);
2051 // Header not yet printed
2052 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2053 // server protocol should be always present, because this render
2054 // can not be used from command line or when outputting custom XML
2055 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2057 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2058 $this->page->set_url('/'); // no url
2059 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2060 $this->page->set_title(get_string('error'));
2061 $this->page->set_heading($this->page->course->fullname);
2062 $output .= $this->header();
2065 $message = '<p class="errormessage">' . $message . '</p>'.
2066 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2067 get_string('moreinformation') . '</a></p>';
2068 if (empty($CFG->rolesactive)) {
2069 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2070 //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation.
2072 $output .= $this->box($message, 'errorbox');
2074 if (debugging('', DEBUG_DEVELOPER)) {
2075 if (!empty($debuginfo)) {
2076 $debuginfo = s($debuginfo); // removes all nasty JS
2077 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2078 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2080 if (!empty($backtrace)) {
2081 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2083 if ($obbuffer !== '' ) {
2084 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2088 if (empty($CFG->rolesactive)) {
2089 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2090 } else if (!empty($link)) {
2091 $output .= $this->continue_button($link);
2094 $output .= $this->footer();
2096 // Padding to encourage IE to display our error page, rather than its own.
2097 $output .= str_repeat(' ', 512);
2099 return $output;
2103 * Output a notification (that is, a status message about something that has
2104 * just happened).
2106 * @param string $message the message to print out
2107 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2108 * @return string the HTML to output.
2110 public function notification($message, $classes = 'notifyproblem') {
2111 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2115 * Print a continue button that goes to a particular URL.
2117 * @param string|moodle_url $url The url the button goes to.
2118 * @return string the HTML to output.
2120 public function continue_button($url) {
2121 if (!($url instanceof moodle_url)) {
2122 $url = new moodle_url($url);
2124 $button = new single_button($url, get_string('continue'), 'get');
2125 $button->class = 'continuebutton';
2127 return $this->render($button);
2131 * Prints a single paging bar to provide access to other pages (usually in a search)
2133 * @param int $totalcount The total number of entries available to be paged through
2134 * @param int $page The page you are currently viewing
2135 * @param int $perpage The number of entries that should be shown per page
2136 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2137 * @param string $pagevar name of page parameter that holds the page number
2138 * @return string the HTML to output.
2140 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2141 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2142 return $this->render($pb);
2146 * Internal implementation of paging bar rendering.
2147 * @param paging_bar $pagingbar
2148 * @return string
2150 protected function render_paging_bar(paging_bar $pagingbar) {
2151 $output = '';
2152 $pagingbar = clone($pagingbar);
2153 $pagingbar->prepare($this, $this->page, $this->target);
2155 if ($pagingbar->totalcount > $pagingbar->perpage) {
2156 $output .= get_string('page') . ':';
2158 if (!empty($pagingbar->previouslink)) {
2159 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2162 if (!empty($pagingbar->firstlink)) {
2163 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2166 foreach ($pagingbar->pagelinks as $link) {
2167 $output .= "&#160;&#160;$link";
2170 if (!empty($pagingbar->lastlink)) {
2171 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2174 if (!empty($pagingbar->nextlink)) {
2175 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2179 return html_writer::tag('div', $output, array('class' => 'paging'));
2183 * Output the place a skip link goes to.
2184 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2185 * @return string the HTML to output.
2187 public function skip_link_target($id = null) {
2188 return html_writer::tag('span', '', array('id' => $id));
2192 * Outputs a heading
2193 * @param string $text The text of the heading
2194 * @param int $level The level of importance of the heading. Defaulting to 2
2195 * @param string $classes A space-separated list of CSS classes
2196 * @param string $id An optional ID
2197 * @return string the HTML to output.
2199 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2200 $level = (integer) $level;
2201 if ($level < 1 or $level > 6) {
2202 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2204 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2208 * Outputs a box.
2209 * @param string $contents The contents of the box
2210 * @param string $classes A space-separated list of CSS classes
2211 * @param string $id An optional ID
2212 * @return string the HTML to output.
2214 public function box($contents, $classes = 'generalbox', $id = null) {
2215 return $this->box_start($classes, $id) . $contents . $this->box_end();
2219 * Outputs the opening section of a box.
2220 * @param string $classes A space-separated list of CSS classes
2221 * @param string $id An optional ID
2222 * @return string the HTML to output.
2224 public function box_start($classes = 'generalbox', $id = null) {
2225 $this->opencontainers->push('box', html_writer::end_tag('div'));
2226 return html_writer::start_tag('div', array('id' => $id,
2227 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2231 * Outputs the closing section of a box.
2232 * @return string the HTML to output.
2234 public function box_end() {
2235 return $this->opencontainers->pop('box');
2239 * Outputs a container.
2240 * @param string $contents The contents of the box
2241 * @param string $classes A space-separated list of CSS classes
2242 * @param string $id An optional ID
2243 * @return string the HTML to output.
2245 public function container($contents, $classes = null, $id = null) {
2246 return $this->container_start($classes, $id) . $contents . $this->container_end();
2250 * Outputs the opening section of a container.
2251 * @param string $classes A space-separated list of CSS classes
2252 * @param string $id An optional ID
2253 * @return string the HTML to output.
2255 public function container_start($classes = null, $id = null) {
2256 $this->opencontainers->push('container', html_writer::end_tag('div'));
2257 return html_writer::start_tag('div', array('id' => $id,
2258 'class' => renderer_base::prepare_classes($classes)));
2262 * Outputs the closing section of a container.
2263 * @return string the HTML to output.
2265 public function container_end() {
2266 return $this->opencontainers->pop('container');
2270 * Make nested HTML lists out of the items
2272 * The resulting list will look something like this:
2274 * <pre>
2275 * <<ul>>
2276 * <<li>><div class='tree_item parent'>(item contents)</div>
2277 * <<ul>
2278 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2279 * <</ul>>
2280 * <</li>>
2281 * <</ul>>
2282 * </pre>
2284 * @param array[]tree_item $items
2285 * @param array[string]string $attrs html attributes passed to the top of
2286 * the list
2287 * @return string HTML
2289 function tree_block_contents($items, $attrs=array()) {
2290 // exit if empty, we don't want an empty ul element
2291 if (empty($items)) {
2292 return '';
2294 // array of nested li elements
2295 $lis = array();
2296 foreach ($items as $item) {
2297 // this applies to the li item which contains all child lists too
2298 $content = $item->content($this);
2299 $liclasses = array($item->get_css_type());
2300 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2301 $liclasses[] = 'collapsed';
2303 if ($item->isactive === true) {
2304 $liclasses[] = 'current_branch';
2306 $liattr = array('class'=>join(' ',$liclasses));
2307 // class attribute on the div item which only contains the item content
2308 $divclasses = array('tree_item');
2309 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2310 $divclasses[] = 'branch';
2311 } else {
2312 $divclasses[] = 'leaf';
2314 if (!empty($item->classes) && count($item->classes)>0) {
2315 $divclasses[] = join(' ', $item->classes);
2317 $divattr = array('class'=>join(' ', $divclasses));
2318 if (!empty($item->id)) {
2319 $divattr['id'] = $item->id;
2321 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2322 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2323 $content = html_writer::empty_tag('hr') . $content;
2325 $content = html_writer::tag('li', $content, $liattr);
2326 $lis[] = $content;
2328 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2332 * Return the navbar content so that it can be echoed out by the layout
2333 * @return string XHTML navbar
2335 public function navbar() {
2336 $items = $this->page->navbar->get_items();
2338 $htmlblocks = array();
2339 // Iterate the navarray and display each node
2340 $itemcount = count($items);
2341 $separator = get_separator();
2342 for ($i=0;$i < $itemcount;$i++) {
2343 $item = $items[$i];
2344 $item->hideicon = true;
2345 if ($i===0) {
2346 $content = html_writer::tag('li', $this->render($item));
2347 } else {
2348 $content = html_writer::tag('li', $separator.$this->render($item));
2350 $htmlblocks[] = $content;
2353 //accessibility: heading for navbar list (MDL-20446)
2354 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2355 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2356 // XHTML
2357 return $navbarcontent;
2360 protected function render_navigation_node(navigation_node $item) {
2361 $content = $item->get_content();
2362 $title = $item->get_title();
2363 if ($item->icon instanceof renderable && !$item->hideicon) {
2364 $icon = $this->render($item->icon);
2365 $content = $icon.$content; // use CSS for spacing of icons
2367 if ($item->helpbutton !== null) {
2368 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2370 if ($content === '') {
2371 return '';
2373 if ($item->action instanceof action_link) {
2374 $link = $item->action;
2375 if ($item->hidden) {
2376 $link->add_class('dimmed');
2378 if (!empty($content)) {
2379 // Providing there is content we will use that for the link content.
2380 $link->text = $content;
2382 $content = $this->render($link);
2383 } else if ($item->action instanceof moodle_url) {
2384 $attributes = array();
2385 if ($title !== '') {
2386 $attributes['title'] = $title;
2388 if ($item->hidden) {
2389 $attributes['class'] = 'dimmed_text';
2391 $content = html_writer::link($item->action, $content, $attributes);
2393 } else if (is_string($item->action) || empty($item->action)) {
2394 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2395 if ($title !== '') {
2396 $attributes['title'] = $title;
2398 if ($item->hidden) {
2399 $attributes['class'] = 'dimmed_text';
2401 $content = html_writer::tag('span', $content, $attributes);
2403 return $content;
2407 * Accessibility: Right arrow-like character is
2408 * used in the breadcrumb trail, course navigation menu
2409 * (previous/next activity), calendar, and search forum block.
2410 * If the theme does not set characters, appropriate defaults
2411 * are set automatically. Please DO NOT
2412 * use &lt; &gt; &raquo; - these are confusing for blind users.
2413 * @return string
2415 public function rarrow() {
2416 return $this->page->theme->rarrow;
2420 * Accessibility: Right arrow-like character is
2421 * used in the breadcrumb trail, course navigation menu
2422 * (previous/next activity), calendar, and search forum block.
2423 * If the theme does not set characters, appropriate defaults
2424 * are set automatically. Please DO NOT
2425 * use &lt; &gt; &raquo; - these are confusing for blind users.
2426 * @return string
2428 public function larrow() {
2429 return $this->page->theme->larrow;
2433 * Returns the custom menu if one has been set
2435 * A custom menu can be configured by browsing to
2436 * Settings: Administration > Appearance > Themes > Theme settings
2437 * and then configuring the custommenu config setting as described.
2439 * @return string
2441 public function custom_menu() {
2442 global $CFG;
2443 if (empty($CFG->custommenuitems)) {
2444 return '';
2446 $custommenu = new custom_menu($CFG->custommenuitems, current_language());
2447 return $this->render_custom_menu($custommenu);
2451 * Renders a custom menu object (located in outputcomponents.php)
2453 * The custom menu this method produces makes use of the YUI3 menunav widget
2454 * and requires very specific html elements and classes.
2456 * @staticvar int $menucount
2457 * @param custom_menu $menu
2458 * @return string
2460 protected function render_custom_menu(custom_menu $menu) {
2461 static $menucount = 0;
2462 // If the menu has no children return an empty string
2463 if (!$menu->has_children()) {
2464 return '';
2466 // Increment the menu count. This is used for ID's that get worked with
2467 // in JavaScript as is essential
2468 $menucount++;
2469 // Initialise this custom menu (the custom menu object is contained in javascript-static
2470 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2471 $jscode = "(function(){{$jscode}})";
2472 $this->page->requires->yui_module('node-menunav', $jscode);
2473 // Build the root nodes as required by YUI
2474 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2475 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2476 $content .= html_writer::start_tag('ul');
2477 // Render each child
2478 foreach ($menu->get_children() as $item) {
2479 $content .= $this->render_custom_menu_item($item);
2481 // Close the open tags
2482 $content .= html_writer::end_tag('ul');
2483 $content .= html_writer::end_tag('div');
2484 $content .= html_writer::end_tag('div');
2485 // Return the custom menu
2486 return $content;
2490 * Renders a custom menu node as part of a submenu
2492 * The custom menu this method produces makes use of the YUI3 menunav widget
2493 * and requires very specific html elements and classes.
2495 * @see render_custom_menu()
2497 * @staticvar int $submenucount
2498 * @param custom_menu_item $menunode
2499 * @return string
2501 protected function render_custom_menu_item(custom_menu_item $menunode) {
2502 // Required to ensure we get unique trackable id's
2503 static $submenucount = 0;
2504 if ($menunode->has_children()) {
2505 // If the child has menus render it as a sub menu
2506 $submenucount++;
2507 $content = html_writer::start_tag('li');
2508 if ($menunode->get_url() !== null) {
2509 $url = $menunode->get_url();
2510 } else {
2511 $url = '#cm_submenu_'.$submenucount;
2513 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2514 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2515 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2516 $content .= html_writer::start_tag('ul');
2517 foreach ($menunode->get_children() as $menunode) {
2518 $content .= $this->render_custom_menu_item($menunode);
2520 $content .= html_writer::end_tag('ul');
2521 $content .= html_writer::end_tag('div');
2522 $content .= html_writer::end_tag('div');
2523 $content .= html_writer::end_tag('li');
2524 } else {
2525 // The node doesn't have children so produce a final menuitem
2526 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2527 if ($menunode->get_url() !== null) {
2528 $url = $menunode->get_url();
2529 } else {
2530 $url = '#';
2532 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2533 $content .= html_writer::end_tag('li');
2535 // Return the sub menu
2536 return $content;
2540 * Renders theme links for switching between default and other themes.
2542 * @return string
2544 protected function theme_switch_links() {
2546 $actualdevice = get_device_type();
2547 $currentdevice = $this->page->devicetypeinuse;
2548 $switched = ($actualdevice != $currentdevice);
2550 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2551 // The user is using the a default device and hasn't switched so don't shown the switch
2552 // device links.
2553 return '';
2556 if ($switched) {
2557 $linktext = get_string('switchdevicerecommended');
2558 $devicetype = $actualdevice;
2559 } else {
2560 $linktext = get_string('switchdevicedefault');
2561 $devicetype = 'default';
2563 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2565 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2566 $content .= html_writer::link($linkurl, $linktext);
2567 $content .= html_writer::end_tag('div');
2569 return $content;
2573 /// RENDERERS
2576 * A renderer that generates output for command-line scripts.
2578 * The implementation of this renderer is probably incomplete.
2580 * @copyright 2009 Tim Hunt
2581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2582 * @since Moodle 2.0
2584 class core_renderer_cli extends core_renderer {
2586 * Returns the page header.
2587 * @return string HTML fragment
2589 public function header() {
2590 return $this->page->heading . "\n";
2594 * Returns a template fragment representing a Heading.
2595 * @param string $text The text of the heading
2596 * @param int $level The level of importance of the heading
2597 * @param string $classes A space-separated list of CSS classes
2598 * @param string $id An optional ID
2599 * @return string A template fragment for a heading
2601 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2602 $text .= "\n";
2603 switch ($level) {
2604 case 1:
2605 return '=>' . $text;
2606 case 2:
2607 return '-->' . $text;
2608 default:
2609 return $text;
2614 * Returns a template fragment representing a fatal error.
2615 * @param string $message The message to output
2616 * @param string $moreinfourl URL where more info can be found about the error
2617 * @param string $link Link for the Continue button
2618 * @param array $backtrace The execution backtrace
2619 * @param string $debuginfo Debugging information
2620 * @return string A template fragment for a fatal error
2622 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2623 $output = "!!! $message !!!\n";
2625 if (debugging('', DEBUG_DEVELOPER)) {
2626 if (!empty($debuginfo)) {
2627 $output .= $this->notification($debuginfo, 'notifytiny');
2629 if (!empty($backtrace)) {
2630 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2634 return $output;
2638 * Returns a template fragment representing a notification.
2639 * @param string $message The message to include
2640 * @param string $classes A space-separated list of CSS classes
2641 * @return string A template fragment for a notification
2643 public function notification($message, $classes = 'notifyproblem') {
2644 $message = clean_text($message);
2645 if ($classes === 'notifysuccess') {
2646 return "++ $message ++\n";
2648 return "!! $message !!\n";
2654 * A renderer that generates output for ajax scripts.
2656 * This renderer prevents accidental sends back only json
2657 * encoded error messages, all other output is ignored.
2659 * @copyright 2010 Petr Skoda
2660 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2661 * @since Moodle 2.0
2663 class core_renderer_ajax extends core_renderer {
2665 * Returns a template fragment representing a fatal error.
2666 * @param string $message The message to output
2667 * @param string $moreinfourl URL where more info can be found about the error
2668 * @param string $link Link for the Continue button
2669 * @param array $backtrace The execution backtrace
2670 * @param string $debuginfo Debugging information
2671 * @return string A template fragment for a fatal error
2673 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2674 global $CFG;
2676 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2678 $e = new stdClass();
2679 $e->error = $message;
2680 $e->stacktrace = NULL;
2681 $e->debuginfo = NULL;
2682 $e->reproductionlink = NULL;
2683 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2684 $e->reproductionlink = $link;
2685 if (!empty($debuginfo)) {
2686 $e->debuginfo = $debuginfo;
2688 if (!empty($backtrace)) {
2689 $e->stacktrace = format_backtrace($backtrace, true);
2692 $this->header();
2693 return json_encode($e);
2696 public function notification($message, $classes = 'notifyproblem') {
2699 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2702 public function header() {
2703 // unfortunately YUI iframe upload does not support application/json
2704 if (!empty($_FILES)) {
2705 @header('Content-type: text/plain; charset=utf-8');
2706 } else {
2707 @header('Content-type: application/json; charset=utf-8');
2710 /// Headers to make it not cacheable and json
2711 @header('Cache-Control: no-store, no-cache, must-revalidate');
2712 @header('Cache-Control: post-check=0, pre-check=0', false);
2713 @header('Pragma: no-cache');
2714 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2715 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2716 @header('Accept-Ranges: none');
2719 public function footer() {
2722 public function heading($text, $level = 2, $classes = 'main', $id = null) {