Merge branch 'MDL-29569' of git://github.com/rwijaya/moodle
[moodle.git] / lib / outputrenderers.php
blob8bd6252dc312310879e1e157e67a5c18c55b8f5f
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.'/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 (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
511 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/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)).' ';
1473 $aggregatehtml .= html_writer::start_tag('span', array('id'=>"ratingcount{$rating->itemid}"));
1474 if ($rating->count > 0) {
1475 $aggregatehtml .= "({$rating->count})";
1476 } else {
1477 $aggregatehtml .= '-';
1479 $aggregatehtml .= html_writer::end_tag('span').' ';
1481 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1482 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1484 $nonpopuplink = $rating->get_view_ratings_url();
1485 $popuplink = $rating->get_view_ratings_url(true);
1487 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1488 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1489 } else {
1490 $ratinghtml .= $aggregatehtml;
1494 $formstart = null;
1495 // if the item doesn't belong to the current user, the user has permission to rate
1496 // and we're within the assessable period
1497 if ($rating->user_can_rate()) {
1499 $rateurl = $rating->get_rate_url();
1500 $inputs = $rateurl->params();
1502 //start the rating form
1503 $formattrs = array(
1504 'id' => "postrating{$rating->itemid}",
1505 'class' => 'postratingform',
1506 'method' => 'post',
1507 'action' => $rateurl->out_omit_querystring()
1509 $formstart = html_writer::start_tag('form', $formattrs);
1510 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1512 // add the hidden inputs
1513 foreach ($inputs as $name => $value) {
1514 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1515 $formstart .= html_writer::empty_tag('input', $attributes);
1518 if (empty($ratinghtml)) {
1519 $ratinghtml .= $strrate.': ';
1521 $ratinghtml = $formstart.$ratinghtml;
1523 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1524 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1525 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1527 //output submit button
1528 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1530 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1531 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1533 if (!$rating->settings->scale->isnumeric) {
1534 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1536 $ratinghtml .= html_writer::end_tag('span');
1537 $ratinghtml .= html_writer::end_tag('div');
1538 $ratinghtml .= html_writer::end_tag('form');
1541 return $ratinghtml;
1545 * Centered heading with attached help button (same title text)
1546 * and optional icon attached
1547 * @param string $text A heading text
1548 * @param string $helpidentifier The keyword that defines a help page
1549 * @param string $component component name
1550 * @param string|moodle_url $icon
1551 * @param string $iconalt icon alt text
1552 * @return string HTML fragment
1554 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1555 $image = '';
1556 if ($icon) {
1557 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1560 $help = '';
1561 if ($helpidentifier) {
1562 $help = $this->help_icon($helpidentifier, $component);
1565 return $this->heading($image.$text.$help, 2, 'main help');
1569 * Print a help icon.
1571 * @deprecated since Moodle 2.0
1572 * @param string $page The keyword that defines a help page
1573 * @param string $title A descriptive text for accessibility only
1574 * @param string $component component name
1575 * @param string|bool $linktext true means use $title as link text, string means link text value
1576 * @return string HTML fragment
1578 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1579 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1580 $icon = new old_help_icon($helpidentifier, $title, $component);
1581 if ($linktext === true) {
1582 $icon->linktext = $title;
1583 } else if (!empty($linktext)) {
1584 $icon->linktext = $linktext;
1586 return $this->render($icon);
1590 * Implementation of user image rendering.
1591 * @param help_icon $helpicon
1592 * @return string HTML fragment
1594 protected function render_old_help_icon(old_help_icon $helpicon) {
1595 global $CFG;
1597 // first get the help image icon
1598 $src = $this->pix_url('help');
1600 if (empty($helpicon->linktext)) {
1601 $alt = $helpicon->title;
1602 } else {
1603 $alt = get_string('helpwiththis');
1606 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1607 $output = html_writer::empty_tag('img', $attributes);
1609 // add the link text if given
1610 if (!empty($helpicon->linktext)) {
1611 // the spacing has to be done through CSS
1612 $output .= $helpicon->linktext;
1615 // now create the link around it - we need https on loginhttps pages
1616 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1618 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1619 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1621 $attributes = array('href'=>$url, 'title'=>$title);
1622 $id = html_writer::random_id('helpicon');
1623 $attributes['id'] = $id;
1624 $output = html_writer::tag('a', $output, $attributes);
1626 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1628 // and finally span
1629 return html_writer::tag('span', $output, array('class' => 'helplink'));
1633 * Print a help icon.
1635 * @param string $identifier The keyword that defines a help page
1636 * @param string $component component name
1637 * @param string|bool $linktext true means use $title as link text, string means link text value
1638 * @return string HTML fragment
1640 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1641 $icon = new help_icon($identifier, $component);
1642 $icon->diag_strings();
1643 if ($linktext === true) {
1644 $icon->linktext = get_string($icon->identifier, $icon->component);
1645 } else if (!empty($linktext)) {
1646 $icon->linktext = $linktext;
1648 return $this->render($icon);
1652 * Implementation of user image rendering.
1653 * @param help_icon $helpicon
1654 * @return string HTML fragment
1656 protected function render_help_icon(help_icon $helpicon) {
1657 global $CFG;
1659 // first get the help image icon
1660 $src = $this->pix_url('help');
1662 $title = get_string($helpicon->identifier, $helpicon->component);
1664 if (empty($helpicon->linktext)) {
1665 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1666 } else {
1667 $alt = get_string('helpwiththis');
1670 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1671 $output = html_writer::empty_tag('img', $attributes);
1673 // add the link text if given
1674 if (!empty($helpicon->linktext)) {
1675 // the spacing has to be done through CSS
1676 $output .= $helpicon->linktext;
1679 // now create the link around it - we need https on loginhttps pages
1680 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1682 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1683 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1685 $attributes = array('href'=>$url, 'title'=>$title);
1686 $id = html_writer::random_id('helpicon');
1687 $attributes['id'] = $id;
1688 $output = html_writer::tag('a', $output, $attributes);
1690 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1692 // and finally span
1693 return html_writer::tag('span', $output, array('class' => 'helplink'));
1697 * Print scale help icon.
1699 * @param int $courseid
1700 * @param object $scale instance
1701 * @return string HTML fragment
1703 public function help_icon_scale($courseid, stdClass $scale) {
1704 global $CFG;
1706 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1708 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1710 $scaleid = abs($scale->id);
1712 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1713 $action = new popup_action('click', $link, 'ratingscale');
1715 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1719 * Creates and returns a spacer image with optional line break.
1721 * @param array $attributes
1722 * @param boo spacer
1723 * @return string HTML fragment
1725 public function spacer(array $attributes = null, $br = false) {
1726 $attributes = (array)$attributes;
1727 if (empty($attributes['width'])) {
1728 $attributes['width'] = 1;
1730 if (empty($attributes['height'])) {
1731 $attributes['height'] = 1;
1733 $attributes['class'] = 'spacer';
1735 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1737 if (!empty($br)) {
1738 $output .= '<br />';
1741 return $output;
1745 * Print the specified user's avatar.
1747 * User avatar may be obtained in two ways:
1748 * <pre>
1749 * // Option 1: (shortcut for simple cases, preferred way)
1750 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1751 * $OUTPUT->user_picture($user, array('popup'=>true));
1753 * // Option 2:
1754 * $userpic = new user_picture($user);
1755 * // Set properties of $userpic
1756 * $userpic->popup = true;
1757 * $OUTPUT->render($userpic);
1758 * </pre>
1760 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1761 * If any of these are missing, the database is queried. Avoid this
1762 * if at all possible, particularly for reports. It is very bad for performance.
1763 * @param array $options associative array with user picture options, used only if not a user_picture object,
1764 * options are:
1765 * - courseid=$this->page->course->id (course id of user profile in link)
1766 * - size=35 (size of image)
1767 * - link=true (make image clickable - the link leads to user profile)
1768 * - popup=false (open in popup)
1769 * - alttext=true (add image alt attribute)
1770 * - class = image class attribute (default 'userpicture')
1771 * @return string HTML fragment
1773 public function user_picture(stdClass $user, array $options = null) {
1774 $userpicture = new user_picture($user);
1775 foreach ((array)$options as $key=>$value) {
1776 if (array_key_exists($key, $userpicture)) {
1777 $userpicture->$key = $value;
1780 return $this->render($userpicture);
1784 * Internal implementation of user image rendering.
1785 * @param user_picture $userpicture
1786 * @return string
1788 protected function render_user_picture(user_picture $userpicture) {
1789 global $CFG, $DB;
1791 $user = $userpicture->user;
1793 if ($userpicture->alttext) {
1794 if (!empty($user->imagealt)) {
1795 $alt = $user->imagealt;
1796 } else {
1797 $alt = get_string('pictureof', '', fullname($user));
1799 } else {
1800 $alt = '';
1803 if (empty($userpicture->size)) {
1804 $size = 35;
1805 } else if ($userpicture->size === true or $userpicture->size == 1) {
1806 $size = 100;
1807 } else {
1808 $size = $userpicture->size;
1811 $class = $userpicture->class;
1813 if ($user->picture != 1 && $user->picture != 2) {
1814 $class .= ' defaultuserpic';
1817 $src = $userpicture->get_url($this->page, $this);
1819 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1821 // get the image html output fisrt
1822 $output = html_writer::empty_tag('img', $attributes);;
1824 // then wrap it in link if needed
1825 if (!$userpicture->link) {
1826 return $output;
1829 if (empty($userpicture->courseid)) {
1830 $courseid = $this->page->course->id;
1831 } else {
1832 $courseid = $userpicture->courseid;
1835 if ($courseid == SITEID) {
1836 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1837 } else {
1838 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1841 $attributes = array('href'=>$url);
1843 if ($userpicture->popup) {
1844 $id = html_writer::random_id('userpicture');
1845 $attributes['id'] = $id;
1846 $this->add_action_handler(new popup_action('click', $url), $id);
1849 return html_writer::tag('a', $output, $attributes);
1853 * Internal implementation of file tree viewer items rendering.
1854 * @param array $dir
1855 * @return string
1857 public function htmllize_file_tree($dir) {
1858 if (empty($dir['subdirs']) and empty($dir['files'])) {
1859 return '';
1861 $result = '<ul>';
1862 foreach ($dir['subdirs'] as $subdir) {
1863 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1865 foreach ($dir['files'] as $file) {
1866 $filename = $file->get_filename();
1867 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1869 $result .= '</ul>';
1871 return $result;
1874 * Print the file picker
1876 * <pre>
1877 * $OUTPUT->file_picker($options);
1878 * </pre>
1880 * @param array $options associative array with file manager options
1881 * options are:
1882 * maxbytes=>-1,
1883 * itemid=>0,
1884 * client_id=>uniqid(),
1885 * acepted_types=>'*',
1886 * return_types=>FILE_INTERNAL,
1887 * context=>$PAGE->context
1888 * @return string HTML fragment
1890 public function file_picker($options) {
1891 $fp = new file_picker($options);
1892 return $this->render($fp);
1895 * Internal implementation of file picker rendering.
1896 * @param file_picker $fp
1897 * @return string
1899 public function render_file_picker(file_picker $fp) {
1900 global $CFG, $OUTPUT, $USER;
1901 $options = $fp->options;
1902 $client_id = $options->client_id;
1903 $strsaved = get_string('filesaved', 'repository');
1904 $straddfile = get_string('openpicker', 'repository');
1905 $strloading = get_string('loading', 'repository');
1906 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1908 $currentfile = $options->currentfile;
1909 if (empty($currentfile)) {
1910 $currentfile = get_string('nofilesattached', 'repository');
1912 if ($options->maxbytes) {
1913 $size = $options->maxbytes;
1914 } else {
1915 $size = get_max_upload_file_size();
1917 if ($size == -1) {
1918 $maxsize = '';
1919 } else {
1920 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
1922 if ($options->buttonname) {
1923 $buttonname = ' name="' . $options->buttonname . '"';
1924 } else {
1925 $buttonname = '';
1927 $html = <<<EOD
1928 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1929 $icon_progress
1930 </div>
1931 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1932 <div>
1933 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
1934 <span> $maxsize </span>
1935 </div>
1936 EOD;
1937 if ($options->env != 'url') {
1938 $html .= <<<EOD
1939 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1940 EOD;
1942 $html .= '</div>';
1943 return $html;
1947 * Prints the 'Update this Modulename' button that appears on module pages.
1949 * @param string $cmid the course_module id.
1950 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1951 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1953 public function update_module_button($cmid, $modulename) {
1954 global $CFG;
1955 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1956 $modulename = get_string('modulename', $modulename);
1957 $string = get_string('updatethis', '', $modulename);
1958 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1959 return $this->single_button($url, $string);
1960 } else {
1961 return '';
1966 * Prints a "Turn editing on/off" button in a form.
1967 * @param moodle_url $url The URL + params to send through when clicking the button
1968 * @return string HTML the button
1970 public function edit_button(moodle_url $url) {
1972 $url->param('sesskey', sesskey());
1973 if ($this->page->user_is_editing()) {
1974 $url->param('edit', 'off');
1975 $editstring = get_string('turneditingoff');
1976 } else {
1977 $url->param('edit', 'on');
1978 $editstring = get_string('turneditingon');
1981 return $this->single_button($url, $editstring);
1985 * Prints a simple button to close a window
1987 * @param string $text The lang string for the button's label (already output from get_string())
1988 * @return string html fragment
1990 public function close_window_button($text='') {
1991 if (empty($text)) {
1992 $text = get_string('closewindow');
1994 $button = new single_button(new moodle_url('#'), $text, 'get');
1995 $button->add_action(new component_action('click', 'close_window'));
1997 return $this->container($this->render($button), 'closewindow');
2001 * Output an error message. By default wraps the error message in <span class="error">.
2002 * If the error message is blank, nothing is output.
2003 * @param string $message the error message.
2004 * @return string the HTML to output.
2006 public function error_text($message) {
2007 if (empty($message)) {
2008 return '';
2010 return html_writer::tag('span', $message, array('class' => 'error'));
2014 * Do not call this function directly.
2016 * To terminate the current script with a fatal error, call the {@link print_error}
2017 * function, or throw an exception. Doing either of those things will then call this
2018 * function to display the error, before terminating the execution.
2020 * @param string $message The message to output
2021 * @param string $moreinfourl URL where more info can be found about the error
2022 * @param string $link Link for the Continue button
2023 * @param array $backtrace The execution backtrace
2024 * @param string $debuginfo Debugging information
2025 * @return string the HTML to output.
2027 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2028 global $CFG;
2030 $output = '';
2031 $obbuffer = '';
2033 if ($this->has_started()) {
2034 // we can not always recover properly here, we have problems with output buffering,
2035 // html tables, etc.
2036 $output .= $this->opencontainers->pop_all_but_last();
2038 } else {
2039 // It is really bad if library code throws exception when output buffering is on,
2040 // because the buffered text would be printed before our start of page.
2041 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2042 error_reporting(0); // disable notices from gzip compression, etc.
2043 while (ob_get_level() > 0) {
2044 $buff = ob_get_clean();
2045 if ($buff === false) {
2046 break;
2048 $obbuffer .= $buff;
2050 error_reporting($CFG->debug);
2052 // Header not yet printed
2053 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2054 // server protocol should be always present, because this render
2055 // can not be used from command line or when outputting custom XML
2056 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2058 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2059 $this->page->set_url('/'); // no url
2060 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2061 $this->page->set_title(get_string('error'));
2062 $this->page->set_heading($this->page->course->fullname);
2063 $output .= $this->header();
2066 $message = '<p class="errormessage">' . $message . '</p>'.
2067 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2068 get_string('moreinformation') . '</a></p>';
2069 if (empty($CFG->rolesactive)) {
2070 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2071 //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.
2073 $output .= $this->box($message, 'errorbox');
2075 if (debugging('', DEBUG_DEVELOPER)) {
2076 if (!empty($debuginfo)) {
2077 $debuginfo = s($debuginfo); // removes all nasty JS
2078 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2079 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2081 if (!empty($backtrace)) {
2082 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2084 if ($obbuffer !== '' ) {
2085 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2089 if (empty($CFG->rolesactive)) {
2090 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2091 } else if (!empty($link)) {
2092 $output .= $this->continue_button($link);
2095 $output .= $this->footer();
2097 // Padding to encourage IE to display our error page, rather than its own.
2098 $output .= str_repeat(' ', 512);
2100 return $output;
2104 * Output a notification (that is, a status message about something that has
2105 * just happened).
2107 * @param string $message the message to print out
2108 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2109 * @return string the HTML to output.
2111 public function notification($message, $classes = 'notifyproblem') {
2112 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2116 * Print a continue button that goes to a particular URL.
2118 * @param string|moodle_url $url The url the button goes to.
2119 * @return string the HTML to output.
2121 public function continue_button($url) {
2122 if (!($url instanceof moodle_url)) {
2123 $url = new moodle_url($url);
2125 $button = new single_button($url, get_string('continue'), 'get');
2126 $button->class = 'continuebutton';
2128 return $this->render($button);
2132 * Prints a single paging bar to provide access to other pages (usually in a search)
2134 * @param int $totalcount The total number of entries available to be paged through
2135 * @param int $page The page you are currently viewing
2136 * @param int $perpage The number of entries that should be shown per page
2137 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2138 * @param string $pagevar name of page parameter that holds the page number
2139 * @return string the HTML to output.
2141 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2142 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2143 return $this->render($pb);
2147 * Internal implementation of paging bar rendering.
2148 * @param paging_bar $pagingbar
2149 * @return string
2151 protected function render_paging_bar(paging_bar $pagingbar) {
2152 $output = '';
2153 $pagingbar = clone($pagingbar);
2154 $pagingbar->prepare($this, $this->page, $this->target);
2156 if ($pagingbar->totalcount > $pagingbar->perpage) {
2157 $output .= get_string('page') . ':';
2159 if (!empty($pagingbar->previouslink)) {
2160 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2163 if (!empty($pagingbar->firstlink)) {
2164 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2167 foreach ($pagingbar->pagelinks as $link) {
2168 $output .= "&#160;&#160;$link";
2171 if (!empty($pagingbar->lastlink)) {
2172 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2175 if (!empty($pagingbar->nextlink)) {
2176 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2180 return html_writer::tag('div', $output, array('class' => 'paging'));
2184 * Output the place a skip link goes to.
2185 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2186 * @return string the HTML to output.
2188 public function skip_link_target($id = null) {
2189 return html_writer::tag('span', '', array('id' => $id));
2193 * Outputs a heading
2194 * @param string $text The text of the heading
2195 * @param int $level The level of importance of the heading. Defaulting to 2
2196 * @param string $classes A space-separated list of CSS classes
2197 * @param string $id An optional ID
2198 * @return string the HTML to output.
2200 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2201 $level = (integer) $level;
2202 if ($level < 1 or $level > 6) {
2203 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2205 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2209 * Outputs a box.
2210 * @param string $contents The contents of the box
2211 * @param string $classes A space-separated list of CSS classes
2212 * @param string $id An optional ID
2213 * @return string the HTML to output.
2215 public function box($contents, $classes = 'generalbox', $id = null) {
2216 return $this->box_start($classes, $id) . $contents . $this->box_end();
2220 * Outputs the opening section of a box.
2221 * @param string $classes A space-separated list of CSS classes
2222 * @param string $id An optional ID
2223 * @return string the HTML to output.
2225 public function box_start($classes = 'generalbox', $id = null) {
2226 $this->opencontainers->push('box', html_writer::end_tag('div'));
2227 return html_writer::start_tag('div', array('id' => $id,
2228 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2232 * Outputs the closing section of a box.
2233 * @return string the HTML to output.
2235 public function box_end() {
2236 return $this->opencontainers->pop('box');
2240 * Outputs a container.
2241 * @param string $contents The contents of the box
2242 * @param string $classes A space-separated list of CSS classes
2243 * @param string $id An optional ID
2244 * @return string the HTML to output.
2246 public function container($contents, $classes = null, $id = null) {
2247 return $this->container_start($classes, $id) . $contents . $this->container_end();
2251 * Outputs the opening section of a container.
2252 * @param string $classes A space-separated list of CSS classes
2253 * @param string $id An optional ID
2254 * @return string the HTML to output.
2256 public function container_start($classes = null, $id = null) {
2257 $this->opencontainers->push('container', html_writer::end_tag('div'));
2258 return html_writer::start_tag('div', array('id' => $id,
2259 'class' => renderer_base::prepare_classes($classes)));
2263 * Outputs the closing section of a container.
2264 * @return string the HTML to output.
2266 public function container_end() {
2267 return $this->opencontainers->pop('container');
2271 * Make nested HTML lists out of the items
2273 * The resulting list will look something like this:
2275 * <pre>
2276 * <<ul>>
2277 * <<li>><div class='tree_item parent'>(item contents)</div>
2278 * <<ul>
2279 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2280 * <</ul>>
2281 * <</li>>
2282 * <</ul>>
2283 * </pre>
2285 * @param array[]tree_item $items
2286 * @param array[string]string $attrs html attributes passed to the top of
2287 * the list
2288 * @return string HTML
2290 function tree_block_contents($items, $attrs=array()) {
2291 // exit if empty, we don't want an empty ul element
2292 if (empty($items)) {
2293 return '';
2295 // array of nested li elements
2296 $lis = array();
2297 foreach ($items as $item) {
2298 // this applies to the li item which contains all child lists too
2299 $content = $item->content($this);
2300 $liclasses = array($item->get_css_type());
2301 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2302 $liclasses[] = 'collapsed';
2304 if ($item->isactive === true) {
2305 $liclasses[] = 'current_branch';
2307 $liattr = array('class'=>join(' ',$liclasses));
2308 // class attribute on the div item which only contains the item content
2309 $divclasses = array('tree_item');
2310 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2311 $divclasses[] = 'branch';
2312 } else {
2313 $divclasses[] = 'leaf';
2315 if (!empty($item->classes) && count($item->classes)>0) {
2316 $divclasses[] = join(' ', $item->classes);
2318 $divattr = array('class'=>join(' ', $divclasses));
2319 if (!empty($item->id)) {
2320 $divattr['id'] = $item->id;
2322 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2323 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2324 $content = html_writer::empty_tag('hr') . $content;
2326 $content = html_writer::tag('li', $content, $liattr);
2327 $lis[] = $content;
2329 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2333 * Return the navbar content so that it can be echoed out by the layout
2334 * @return string XHTML navbar
2336 public function navbar() {
2337 $items = $this->page->navbar->get_items();
2339 $htmlblocks = array();
2340 // Iterate the navarray and display each node
2341 $itemcount = count($items);
2342 $separator = get_separator();
2343 for ($i=0;$i < $itemcount;$i++) {
2344 $item = $items[$i];
2345 $item->hideicon = true;
2346 if ($i===0) {
2347 $content = html_writer::tag('li', $this->render($item));
2348 } else {
2349 $content = html_writer::tag('li', $separator.$this->render($item));
2351 $htmlblocks[] = $content;
2354 //accessibility: heading for navbar list (MDL-20446)
2355 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2356 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2357 // XHTML
2358 return $navbarcontent;
2361 protected function render_navigation_node(navigation_node $item) {
2362 $content = $item->get_content();
2363 $title = $item->get_title();
2364 if ($item->icon instanceof renderable && !$item->hideicon) {
2365 $icon = $this->render($item->icon);
2366 $content = $icon.$content; // use CSS for spacing of icons
2368 if ($item->helpbutton !== null) {
2369 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2371 if ($content === '') {
2372 return '';
2374 if ($item->action instanceof action_link) {
2375 $link = $item->action;
2376 if ($item->hidden) {
2377 $link->add_class('dimmed');
2379 $link->text = $content.$link->text; // add help icon
2380 $content = $this->render($link);
2381 } else if ($item->action instanceof moodle_url) {
2382 $attributes = array();
2383 if ($title !== '') {
2384 $attributes['title'] = $title;
2386 if ($item->hidden) {
2387 $attributes['class'] = 'dimmed_text';
2389 $content = html_writer::link($item->action, $content, $attributes);
2391 } else if (is_string($item->action) || empty($item->action)) {
2392 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2393 if ($title !== '') {
2394 $attributes['title'] = $title;
2396 if ($item->hidden) {
2397 $attributes['class'] = 'dimmed_text';
2399 $content = html_writer::tag('span', $content, $attributes);
2401 return $content;
2405 * Accessibility: Right arrow-like character is
2406 * used in the breadcrumb trail, course navigation menu
2407 * (previous/next activity), calendar, and search forum block.
2408 * If the theme does not set characters, appropriate defaults
2409 * are set automatically. Please DO NOT
2410 * use &lt; &gt; &raquo; - these are confusing for blind users.
2411 * @return string
2413 public function rarrow() {
2414 return $this->page->theme->rarrow;
2418 * Accessibility: Right arrow-like character is
2419 * used in the breadcrumb trail, course navigation menu
2420 * (previous/next activity), calendar, and search forum block.
2421 * If the theme does not set characters, appropriate defaults
2422 * are set automatically. Please DO NOT
2423 * use &lt; &gt; &raquo; - these are confusing for blind users.
2424 * @return string
2426 public function larrow() {
2427 return $this->page->theme->larrow;
2431 * Returns the custom menu if one has been set
2433 * A custom menu can be configured by browsing to
2434 * Settings: Administration > Appearance > Themes > Theme settings
2435 * and then configuring the custommenu config setting as described.
2437 * @return string
2439 public function custom_menu() {
2440 global $CFG;
2441 if (empty($CFG->custommenuitems)) {
2442 return '';
2444 $custommenu = new custom_menu($CFG->custommenuitems, current_language());
2445 return $this->render_custom_menu($custommenu);
2449 * Renders a custom menu object (located in outputcomponents.php)
2451 * The custom menu this method produces makes use of the YUI3 menunav widget
2452 * and requires very specific html elements and classes.
2454 * @staticvar int $menucount
2455 * @param custom_menu $menu
2456 * @return string
2458 protected function render_custom_menu(custom_menu $menu) {
2459 static $menucount = 0;
2460 // If the menu has no children return an empty string
2461 if (!$menu->has_children()) {
2462 return '';
2464 // Increment the menu count. This is used for ID's that get worked with
2465 // in JavaScript as is essential
2466 $menucount++;
2467 // Initialise this custom menu (the custom menu object is contained in javascript-static
2468 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2469 $jscode = "(function(){{$jscode}})";
2470 $this->page->requires->yui_module('node-menunav', $jscode);
2471 // Build the root nodes as required by YUI
2472 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2473 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2474 $content .= html_writer::start_tag('ul');
2475 // Render each child
2476 foreach ($menu->get_children() as $item) {
2477 $content .= $this->render_custom_menu_item($item);
2479 // Close the open tags
2480 $content .= html_writer::end_tag('ul');
2481 $content .= html_writer::end_tag('div');
2482 $content .= html_writer::end_tag('div');
2483 // Return the custom menu
2484 return $content;
2488 * Renders a custom menu node as part of a submenu
2490 * The custom menu this method produces makes use of the YUI3 menunav widget
2491 * and requires very specific html elements and classes.
2493 * @see render_custom_menu()
2495 * @staticvar int $submenucount
2496 * @param custom_menu_item $menunode
2497 * @return string
2499 protected function render_custom_menu_item(custom_menu_item $menunode) {
2500 // Required to ensure we get unique trackable id's
2501 static $submenucount = 0;
2502 if ($menunode->has_children()) {
2503 // If the child has menus render it as a sub menu
2504 $submenucount++;
2505 $content = html_writer::start_tag('li');
2506 if ($menunode->get_url() !== null) {
2507 $url = $menunode->get_url();
2508 } else {
2509 $url = '#cm_submenu_'.$submenucount;
2511 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2512 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2513 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2514 $content .= html_writer::start_tag('ul');
2515 foreach ($menunode->get_children() as $menunode) {
2516 $content .= $this->render_custom_menu_item($menunode);
2518 $content .= html_writer::end_tag('ul');
2519 $content .= html_writer::end_tag('div');
2520 $content .= html_writer::end_tag('div');
2521 $content .= html_writer::end_tag('li');
2522 } else {
2523 // The node doesn't have children so produce a final menuitem
2524 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2525 if ($menunode->get_url() !== null) {
2526 $url = $menunode->get_url();
2527 } else {
2528 $url = '#';
2530 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2531 $content .= html_writer::end_tag('li');
2533 // Return the sub menu
2534 return $content;
2538 * Renders theme links for switching between default and other themes.
2540 * @return string
2542 protected function theme_switch_links() {
2544 $actualdevice = get_device_type();
2545 $currentdevice = $this->page->devicetypeinuse;
2546 $switched = ($actualdevice != $currentdevice);
2548 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2549 // The user is using the a default device and hasn't switched so don't shown the switch
2550 // device links.
2551 return '';
2554 if ($switched) {
2555 $linktext = get_string('switchdevicerecommended');
2556 $devicetype = $actualdevice;
2557 } else {
2558 $linktext = get_string('switchdevicedefault');
2559 $devicetype = 'default';
2561 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2563 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2564 $content .= html_writer::link($linkurl, $linktext);
2565 $content .= html_writer::end_tag('div');
2567 return $content;
2571 /// RENDERERS
2574 * A renderer that generates output for command-line scripts.
2576 * The implementation of this renderer is probably incomplete.
2578 * @copyright 2009 Tim Hunt
2579 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2580 * @since Moodle 2.0
2582 class core_renderer_cli extends core_renderer {
2584 * Returns the page header.
2585 * @return string HTML fragment
2587 public function header() {
2588 return $this->page->heading . "\n";
2592 * Returns a template fragment representing a Heading.
2593 * @param string $text The text of the heading
2594 * @param int $level The level of importance of the heading
2595 * @param string $classes A space-separated list of CSS classes
2596 * @param string $id An optional ID
2597 * @return string A template fragment for a heading
2599 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2600 $text .= "\n";
2601 switch ($level) {
2602 case 1:
2603 return '=>' . $text;
2604 case 2:
2605 return '-->' . $text;
2606 default:
2607 return $text;
2612 * Returns a template fragment representing a fatal error.
2613 * @param string $message The message to output
2614 * @param string $moreinfourl URL where more info can be found about the error
2615 * @param string $link Link for the Continue button
2616 * @param array $backtrace The execution backtrace
2617 * @param string $debuginfo Debugging information
2618 * @return string A template fragment for a fatal error
2620 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2621 $output = "!!! $message !!!\n";
2623 if (debugging('', DEBUG_DEVELOPER)) {
2624 if (!empty($debuginfo)) {
2625 $output .= $this->notification($debuginfo, 'notifytiny');
2627 if (!empty($backtrace)) {
2628 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2632 return $output;
2636 * Returns a template fragment representing a notification.
2637 * @param string $message The message to include
2638 * @param string $classes A space-separated list of CSS classes
2639 * @return string A template fragment for a notification
2641 public function notification($message, $classes = 'notifyproblem') {
2642 $message = clean_text($message);
2643 if ($classes === 'notifysuccess') {
2644 return "++ $message ++\n";
2646 return "!! $message !!\n";
2652 * A renderer that generates output for ajax scripts.
2654 * This renderer prevents accidental sends back only json
2655 * encoded error messages, all other output is ignored.
2657 * @copyright 2010 Petr Skoda
2658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2659 * @since Moodle 2.0
2661 class core_renderer_ajax extends core_renderer {
2663 * Returns a template fragment representing a fatal error.
2664 * @param string $message The message to output
2665 * @param string $moreinfourl URL where more info can be found about the error
2666 * @param string $link Link for the Continue button
2667 * @param array $backtrace The execution backtrace
2668 * @param string $debuginfo Debugging information
2669 * @return string A template fragment for a fatal error
2671 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2672 global $CFG;
2674 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2676 $e = new stdClass();
2677 $e->error = $message;
2678 $e->stacktrace = NULL;
2679 $e->debuginfo = NULL;
2680 $e->reproductionlink = NULL;
2681 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2682 $e->reproductionlink = $link;
2683 if (!empty($debuginfo)) {
2684 $e->debuginfo = $debuginfo;
2686 if (!empty($backtrace)) {
2687 $e->stacktrace = format_backtrace($backtrace, true);
2690 $this->header();
2691 return json_encode($e);
2694 public function notification($message, $classes = 'notifyproblem') {
2697 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2700 public function header() {
2701 // unfortunately YUI iframe upload does not support application/json
2702 if (!empty($_FILES)) {
2703 @header('Content-type: text/plain; charset=utf-8');
2704 } else {
2705 @header('Content-type: application/json; charset=utf-8');
2708 /// Headers to make it not cacheable and json
2709 @header('Cache-Control: no-store, no-cache, must-revalidate');
2710 @header('Cache-Control: post-check=0, pre-check=0', false);
2711 @header('Pragma: no-cache');
2712 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2713 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2714 @header('Accept-Ranges: none');
2717 public function footer() {
2720 public function heading($text, $level = 2, $classes = 'main', $id = null) {