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