MDL-27541 course reports - allow teachers to view individual reports
[moodle.git] / lib / outputrenderers.php
blob786444f957990e6513f89e4c05bcae229e4f9ea9
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->legacythemeinuse) {
366 // The legacy theme is in use print the notification
367 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
369 if (!empty($CFG->debugpageinfo)) {
370 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
372 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
373 // Add link to profiling report if necessary
374 if (function_exists('profiling_is_running') && profiling_is_running()) {
375 $txt = get_string('profiledscript', 'admin');
376 $title = get_string('profiledscriptview', 'admin');
377 $url = $CFG->wwwroot . '/admin/report/profiling/index.php?script=' . urlencode($SCRIPT);
378 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
379 $output .= '<div class="profilingfooter">' . $link . '</div>';
381 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/admin/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
383 if (!empty($CFG->debugvalidators)) {
384 $output .= '<div class="validators"><ul>
385 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
386 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
387 <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>
388 </ul></div>';
390 if (!empty($CFG->additionalhtmlfooter)) {
391 $output .= "\n".$CFG->additionalhtmlfooter;
393 return $output;
397 * The standard tags (typically script tags that are not needed earlier) that
398 * should be output after everything else, . Designed to be called in theme layout.php files.
399 * @return string HTML fragment.
401 public function standard_end_of_body_html() {
402 // This function is normally called from a layout.php file in {@link header()}
403 // but some of the content won't be known until later, so we return a placeholder
404 // for now. This will be replaced with the real content in {@link footer()}.
405 return self::END_HTML_TOKEN;
409 * Return the standard string that says whether you are logged in (and switched
410 * roles/logged in as another user).
411 * @return string HTML fragment.
413 public function login_info() {
414 global $USER, $CFG, $DB, $SESSION;
416 if (during_initial_install()) {
417 return '';
420 $loginapge = ((string)$this->page->url === get_login_url());
421 $course = $this->page->course;
423 if (session_is_loggedinas()) {
424 $realuser = session_get_realuser();
425 $fullname = fullname($realuser, true);
426 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
427 } else {
428 $realuserinfo = '';
431 $loginurl = get_login_url();
433 if (empty($course->id)) {
434 // $course->id is not defined during installation
435 return '';
436 } else if (isloggedin()) {
437 $context = get_context_instance(CONTEXT_COURSE, $course->id);
439 $fullname = fullname($USER, true);
440 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
441 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
442 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
443 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
445 if (isguestuser()) {
446 $loggedinas = $realuserinfo.get_string('loggedinasguest');
447 if (!$loginapge) {
448 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
450 } else if (is_role_switched($course->id)) { // Has switched roles
451 $rolename = '';
452 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
453 $rolename = ': '.format_string($role->name);
455 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
456 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
457 } else {
458 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
459 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
461 } else {
462 $loggedinas = get_string('loggedinnot', 'moodle');
463 if (!$loginapge) {
464 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
468 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
470 if (isset($SESSION->justloggedin)) {
471 unset($SESSION->justloggedin);
472 if (!empty($CFG->displayloginfailures)) {
473 if (!isguestuser()) {
474 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
475 $loggedinas .= '&nbsp;<div class="loginfailures">';
476 if (empty($count->accounts)) {
477 $loggedinas .= get_string('failedloginattempts', '', $count);
478 } else {
479 $loggedinas .= get_string('failedloginattemptsall', '', $count);
481 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
482 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
483 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
485 $loggedinas .= '</div>';
491 return $loggedinas;
495 * Return the 'back' link that normally appears in the footer.
496 * @return string HTML fragment.
498 public function home_link() {
499 global $CFG, $SITE;
501 if ($this->page->pagetype == 'site-index') {
502 // Special case for site home page - please do not remove
503 return '<div class="sitelink">' .
504 '<a title="Moodle" href="http://moodle.org/">' .
505 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
507 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
508 // Special case for during install/upgrade.
509 return '<div class="sitelink">'.
510 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
511 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
513 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
514 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
515 get_string('home') . '</a></div>';
517 } else {
518 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
519 format_string($this->page->course->shortname) . '</a></div>';
524 * Redirects the user by any means possible given the current state
526 * This function should not be called directly, it should always be called using
527 * the redirect function in lib/weblib.php
529 * The redirect function should really only be called before page output has started
530 * however it will allow itself to be called during the state STATE_IN_BODY
532 * @param string $encodedurl The URL to send to encoded if required
533 * @param string $message The message to display to the user if any
534 * @param int $delay The delay before redirecting a user, if $message has been
535 * set this is a requirement and defaults to 3, set to 0 no delay
536 * @param boolean $debugdisableredirect this redirect has been disabled for
537 * debugging purposes. Display a message that explains, and don't
538 * trigger the redirect.
539 * @return string The HTML to display to the user before dying, may contain
540 * meta refresh, javascript refresh, and may have set header redirects
542 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
543 global $CFG;
544 $url = str_replace('&amp;', '&', $encodedurl);
546 switch ($this->page->state) {
547 case moodle_page::STATE_BEFORE_HEADER :
548 // No output yet it is safe to delivery the full arsenal of redirect methods
549 if (!$debugdisableredirect) {
550 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
551 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
552 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
554 $output = $this->header();
555 break;
556 case moodle_page::STATE_PRINTING_HEADER :
557 // We should hopefully never get here
558 throw new coding_exception('You cannot redirect while printing the page header');
559 break;
560 case moodle_page::STATE_IN_BODY :
561 // We really shouldn't be here but we can deal with this
562 debugging("You should really redirect before you start page output");
563 if (!$debugdisableredirect) {
564 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
566 $output = $this->opencontainers->pop_all_but_last();
567 break;
568 case moodle_page::STATE_DONE :
569 // Too late to be calling redirect now
570 throw new coding_exception('You cannot redirect after the entire page has been generated');
571 break;
573 $output .= $this->notification($message, 'redirectmessage');
574 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
575 if ($debugdisableredirect) {
576 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
578 $output .= $this->footer();
579 return $output;
583 * Start output by sending the HTTP headers, and printing the HTML <head>
584 * and the start of the <body>.
586 * To control what is printed, you should set properties on $PAGE. If you
587 * are familiar with the old {@link print_header()} function from Moodle 1.9
588 * you will find that there are properties on $PAGE that correspond to most
589 * of the old parameters to could be passed to print_header.
591 * Not that, in due course, the remaining $navigation, $menu parameters here
592 * will be replaced by more properties of $PAGE, but that is still to do.
594 * @return string HTML that you must output this, preferably immediately.
596 public function header() {
597 global $USER, $CFG;
599 if (session_is_loggedinas()) {
600 $this->page->add_body_class('userloggedinas');
603 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
605 // Find the appropriate page layout file, based on $this->page->pagelayout.
606 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
607 // Render the layout using the layout file.
608 $rendered = $this->render_page_layout($layoutfile);
610 // Slice the rendered output into header and footer.
611 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
612 if ($cutpos === false) {
613 throw new coding_exception('page layout file ' . $layoutfile .
614 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
616 $header = substr($rendered, 0, $cutpos);
617 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
619 if (empty($this->contenttype)) {
620 debugging('The page layout file did not call $OUTPUT->doctype()');
621 $header = $this->doctype() . $header;
624 send_headers($this->contenttype, $this->page->cacheable);
626 $this->opencontainers->push('header/footer', $footer);
627 $this->page->set_state(moodle_page::STATE_IN_BODY);
629 return $header . $this->skip_link_target('maincontent');
633 * Renders and outputs the page layout file.
634 * @param string $layoutfile The name of the layout file
635 * @return string HTML code
637 protected function render_page_layout($layoutfile) {
638 global $CFG, $SITE, $USER;
639 // The next lines are a bit tricky. The point is, here we are in a method
640 // of a renderer class, and this object may, or may not, be the same as
641 // the global $OUTPUT object. When rendering the page layout file, we want to use
642 // this object. However, people writing Moodle code expect the current
643 // renderer to be called $OUTPUT, not $this, so define a variable called
644 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
645 $OUTPUT = $this;
646 $PAGE = $this->page;
647 $COURSE = $this->page->course;
649 ob_start();
650 include($layoutfile);
651 $rendered = ob_get_contents();
652 ob_end_clean();
653 return $rendered;
657 * Outputs the page's footer
658 * @return string HTML fragment
660 public function footer() {
661 global $CFG, $DB;
663 $output = $this->container_end_all(true);
665 $footer = $this->opencontainers->pop('header/footer');
667 if (debugging() and $DB and $DB->is_transaction_started()) {
668 // TODO: MDL-20625 print warning - transaction will be rolled back
671 // Provide some performance info if required
672 $performanceinfo = '';
673 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
674 $perf = get_performance_info();
675 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
676 error_log("PERF: " . $perf['txt']);
678 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
679 $performanceinfo = $perf['html'];
682 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
684 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
686 $this->page->set_state(moodle_page::STATE_DONE);
688 return $output . $footer;
692 * Close all but the last open container. This is useful in places like error
693 * handling, where you want to close all the open containers (apart from <body>)
694 * before outputting the error message.
695 * @param bool $shouldbenone assert that the stack should be empty now - causes a
696 * developer debug warning if it isn't.
697 * @return string the HTML required to close any open containers inside <body>.
699 public function container_end_all($shouldbenone = false) {
700 return $this->opencontainers->pop_all_but_last($shouldbenone);
704 * Returns lang menu or '', this method also checks forcing of languages in courses.
705 * @return string
707 public function lang_menu() {
708 global $CFG;
710 if (empty($CFG->langmenu)) {
711 return '';
714 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
715 // do not show lang menu if language forced
716 return '';
719 $currlang = current_language();
720 $langs = get_string_manager()->get_list_of_translations();
722 if (count($langs) < 2) {
723 return '';
726 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
727 $s->label = get_accesshide(get_string('language'));
728 $s->class = 'langmenu';
729 return $this->render($s);
733 * Output the row of editing icons for a block, as defined by the controls array.
734 * @param array $controls an array like {@link block_contents::$controls}.
735 * @return HTML fragment.
737 public function block_controls($controls) {
738 if (empty($controls)) {
739 return '';
741 $controlshtml = array();
742 foreach ($controls as $control) {
743 $controlshtml[] = html_writer::tag('a',
744 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
745 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
747 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
751 * Prints a nice side block with an optional header.
753 * The content is described
754 * by a {@link block_contents} object.
756 * <div id="inst{$instanceid}" class="block_{$blockname} block">
757 * <div class="header"></div>
758 * <div class="content">
759 * ...CONTENT...
760 * <div class="footer">
761 * </div>
762 * </div>
763 * <div class="annotation">
764 * </div>
765 * </div>
767 * @param block_contents $bc HTML for the content
768 * @param string $region the region the block is appearing in.
769 * @return string the HTML to be output.
771 function block(block_contents $bc, $region) {
772 $bc = clone($bc); // Avoid messing up the object passed in.
773 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
774 $bc->collapsible = block_contents::NOT_HIDEABLE;
776 if ($bc->collapsible == block_contents::HIDDEN) {
777 $bc->add_class('hidden');
779 if (!empty($bc->controls)) {
780 $bc->add_class('block_with_controls');
783 $skiptitle = strip_tags($bc->title);
784 if (empty($skiptitle)) {
785 $output = '';
786 $skipdest = '';
787 } else {
788 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
789 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
792 $output .= html_writer::start_tag('div', $bc->attributes);
794 $output .= $this->block_header($bc);
795 $output .= $this->block_content($bc);
797 $output .= html_writer::end_tag('div');
799 $output .= $this->block_annotation($bc);
801 $output .= $skipdest;
803 $this->init_block_hider_js($bc);
804 return $output;
808 * Produces a header for a block
810 * @param block_contents $bc
811 * @return string
813 protected function block_header(block_contents $bc) {
815 $title = '';
816 if ($bc->title) {
817 $title = html_writer::tag('h2', $bc->title, null);
820 $controlshtml = $this->block_controls($bc->controls);
822 $output = '';
823 if ($title || $controlshtml) {
824 $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'));
826 return $output;
830 * Produces the content area for a block
832 * @param block_contents $bc
833 * @return string
835 protected function block_content(block_contents $bc) {
836 $output = html_writer::start_tag('div', array('class' => 'content'));
837 if (!$bc->title && !$this->block_controls($bc->controls)) {
838 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
840 $output .= $bc->content;
841 $output .= $this->block_footer($bc);
842 $output .= html_writer::end_tag('div');
844 return $output;
848 * Produces the footer for a block
850 * @param block_contents $bc
851 * @return string
853 protected function block_footer(block_contents $bc) {
854 $output = '';
855 if ($bc->footer) {
856 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
858 return $output;
862 * Produces the annotation for a block
864 * @param block_contents $bc
865 * @return string
867 protected function block_annotation(block_contents $bc) {
868 $output = '';
869 if ($bc->annotation) {
870 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
872 return $output;
876 * Calls the JS require function to hide a block.
877 * @param block_contents $bc A block_contents object
878 * @return void
880 protected function init_block_hider_js(block_contents $bc) {
881 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
882 $config = new stdClass;
883 $config->id = $bc->attributes['id'];
884 $config->title = strip_tags($bc->title);
885 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
886 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
887 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
889 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
890 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
895 * Render the contents of a block_list.
896 * @param array $icons the icon for each item.
897 * @param array $items the content of each item.
898 * @return string HTML
900 public function list_block_contents($icons, $items) {
901 $row = 0;
902 $lis = array();
903 foreach ($items as $key => $string) {
904 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
905 if (!empty($icons[$key])) { //test if the content has an assigned icon
906 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
908 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
909 $item .= html_writer::end_tag('li');
910 $lis[] = $item;
911 $row = 1 - $row; // Flip even/odd.
913 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
917 * Output all the blocks in a particular region.
918 * @param string $region the name of a region on this page.
919 * @return string the HTML to be output.
921 public function blocks_for_region($region) {
922 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
924 $output = '';
925 foreach ($blockcontents as $bc) {
926 if ($bc instanceof block_contents) {
927 $output .= $this->block($bc, $region);
928 } else if ($bc instanceof block_move_target) {
929 $output .= $this->block_move_target($bc);
930 } else {
931 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
934 return $output;
938 * Output a place where the block that is currently being moved can be dropped.
939 * @param block_move_target $target with the necessary details.
940 * @return string the HTML to be output.
942 public function block_move_target($target) {
943 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
947 * Renders a special html link with attached action
949 * @param string|moodle_url $url
950 * @param string $text HTML fragment
951 * @param component_action $action
952 * @param array $attributes associative array of html link attributes + disabled
953 * @return HTML fragment
955 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
956 if (!($url instanceof moodle_url)) {
957 $url = new moodle_url($url);
959 $link = new action_link($url, $text, $action, $attributes);
961 return $this->render($link);
965 * Implementation of action_link rendering
966 * @param action_link $link
967 * @return string HTML fragment
969 protected function render_action_link(action_link $link) {
970 global $CFG;
972 // A disabled link is rendered as formatted text
973 if (!empty($link->attributes['disabled'])) {
974 // do not use div here due to nesting restriction in xhtml strict
975 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
978 $attributes = $link->attributes;
979 unset($link->attributes['disabled']);
980 $attributes['href'] = $link->url;
982 if ($link->actions) {
983 if (empty($attributes['id'])) {
984 $id = html_writer::random_id('action_link');
985 $attributes['id'] = $id;
986 } else {
987 $id = $attributes['id'];
989 foreach ($link->actions as $action) {
990 $this->add_action_handler($action, $id);
994 return html_writer::tag('a', $link->text, $attributes);
999 * Similar to action_link, image is used instead of the text
1001 * @param string|moodle_url $url A string URL or moodel_url
1002 * @param pix_icon $pixicon
1003 * @param component_action $action
1004 * @param array $attributes associative array of html link attributes + disabled
1005 * @param bool $linktext show title next to image in link
1006 * @return string HTML fragment
1008 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1009 if (!($url instanceof moodle_url)) {
1010 $url = new moodle_url($url);
1012 $attributes = (array)$attributes;
1014 if (empty($attributes['class'])) {
1015 // let ppl override the class via $options
1016 $attributes['class'] = 'action-icon';
1019 $icon = $this->render($pixicon);
1021 if ($linktext) {
1022 $text = $pixicon->attributes['alt'];
1023 } else {
1024 $text = '';
1027 return $this->action_link($url, $text.$icon, $action, $attributes);
1031 * Print a message along with button choices for Continue/Cancel
1033 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1035 * @param string $message The question to ask the user
1036 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1037 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1038 * @return string HTML fragment
1040 public function confirm($message, $continue, $cancel) {
1041 if ($continue instanceof single_button) {
1042 // ok
1043 } else if (is_string($continue)) {
1044 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1045 } else if ($continue instanceof moodle_url) {
1046 $continue = new single_button($continue, get_string('continue'), 'post');
1047 } else {
1048 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1051 if ($cancel instanceof single_button) {
1052 // ok
1053 } else if (is_string($cancel)) {
1054 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1055 } else if ($cancel instanceof moodle_url) {
1056 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1057 } else {
1058 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1061 $output = $this->box_start('generalbox', 'notice');
1062 $output .= html_writer::tag('p', $message);
1063 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1064 $output .= $this->box_end();
1065 return $output;
1069 * Returns a form with a single button.
1071 * @param string|moodle_url $url
1072 * @param string $label button text
1073 * @param string $method get or post submit method
1074 * @param array $options associative array {disabled, title, etc.}
1075 * @return string HTML fragment
1077 public function single_button($url, $label, $method='post', array $options=null) {
1078 if (!($url instanceof moodle_url)) {
1079 $url = new moodle_url($url);
1081 $button = new single_button($url, $label, $method);
1083 foreach ((array)$options as $key=>$value) {
1084 if (array_key_exists($key, $button)) {
1085 $button->$key = $value;
1089 return $this->render($button);
1093 * Internal implementation of single_button rendering
1094 * @param single_button $button
1095 * @return string HTML fragment
1097 protected function render_single_button(single_button $button) {
1098 $attributes = array('type' => 'submit',
1099 'value' => $button->label,
1100 'disabled' => $button->disabled ? 'disabled' : null,
1101 'title' => $button->tooltip);
1103 if ($button->actions) {
1104 $id = html_writer::random_id('single_button');
1105 $attributes['id'] = $id;
1106 foreach ($button->actions as $action) {
1107 $this->add_action_handler($action, $id);
1111 // first the input element
1112 $output = html_writer::empty_tag('input', $attributes);
1114 // then hidden fields
1115 $params = $button->url->params();
1116 if ($button->method === 'post') {
1117 $params['sesskey'] = sesskey();
1119 foreach ($params as $var => $val) {
1120 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1123 // then div wrapper for xhtml strictness
1124 $output = html_writer::tag('div', $output);
1126 // now the form itself around it
1127 if ($button->method === 'get') {
1128 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1129 } else {
1130 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1132 if ($url === '') {
1133 $url = '#'; // there has to be always some action
1135 $attributes = array('method' => $button->method,
1136 'action' => $url,
1137 'id' => $button->formid);
1138 $output = html_writer::tag('form', $output, $attributes);
1140 // and finally one more wrapper with class
1141 return html_writer::tag('div', $output, array('class' => $button->class));
1145 * Returns a form with a single select widget.
1146 * @param moodle_url $url form action target, includes hidden fields
1147 * @param string $name name of selection field - the changing parameter in url
1148 * @param array $options list of options
1149 * @param string $selected selected element
1150 * @param array $nothing
1151 * @param string $formid
1152 * @return string HTML fragment
1154 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1155 if (!($url instanceof moodle_url)) {
1156 $url = new moodle_url($url);
1158 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1160 return $this->render($select);
1164 * Internal implementation of single_select rendering
1165 * @param single_select $select
1166 * @return string HTML fragment
1168 protected function render_single_select(single_select $select) {
1169 $select = clone($select);
1170 if (empty($select->formid)) {
1171 $select->formid = html_writer::random_id('single_select_f');
1174 $output = '';
1175 $params = $select->url->params();
1176 if ($select->method === 'post') {
1177 $params['sesskey'] = sesskey();
1179 foreach ($params as $name=>$value) {
1180 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1183 if (empty($select->attributes['id'])) {
1184 $select->attributes['id'] = html_writer::random_id('single_select');
1187 if ($select->disabled) {
1188 $select->attributes['disabled'] = 'disabled';
1191 if ($select->tooltip) {
1192 $select->attributes['title'] = $select->tooltip;
1195 if ($select->label) {
1196 $output .= html_writer::label($select->label, $select->attributes['id']);
1199 if ($select->helpicon instanceof help_icon) {
1200 $output .= $this->render($select->helpicon);
1201 } else if ($select->helpicon instanceof old_help_icon) {
1202 $output .= $this->render($select->helpicon);
1205 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1207 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1208 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1210 $nothing = empty($select->nothing) ? false : key($select->nothing);
1211 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1213 // then div wrapper for xhtml strictness
1214 $output = html_writer::tag('div', $output);
1216 // now the form itself around it
1217 if ($select->method === 'get') {
1218 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1219 } else {
1220 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1222 $formattributes = array('method' => $select->method,
1223 'action' => $url,
1224 'id' => $select->formid);
1225 $output = html_writer::tag('form', $output, $formattributes);
1227 // and finally one more wrapper with class
1228 return html_writer::tag('div', $output, array('class' => $select->class));
1232 * Returns a form with a url select widget.
1233 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1234 * @param string $selected selected element
1235 * @param array $nothing
1236 * @param string $formid
1237 * @return string HTML fragment
1239 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1240 $select = new url_select($urls, $selected, $nothing, $formid);
1241 return $this->render($select);
1245 * Internal implementation of url_select rendering
1246 * @param single_select $select
1247 * @return string HTML fragment
1249 protected function render_url_select(url_select $select) {
1250 global $CFG;
1252 $select = clone($select);
1253 if (empty($select->formid)) {
1254 $select->formid = html_writer::random_id('url_select_f');
1257 if (empty($select->attributes['id'])) {
1258 $select->attributes['id'] = html_writer::random_id('url_select');
1261 if ($select->disabled) {
1262 $select->attributes['disabled'] = 'disabled';
1265 if ($select->tooltip) {
1266 $select->attributes['title'] = $select->tooltip;
1269 $output = '';
1271 if ($select->label) {
1272 $output .= html_writer::label($select->label, $select->attributes['id']);
1275 if ($select->helpicon instanceof help_icon) {
1276 $output .= $this->render($select->helpicon);
1277 } else if ($select->helpicon instanceof old_help_icon) {
1278 $output .= $this->render($select->helpicon);
1281 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1282 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1283 $urls = array();
1284 foreach ($select->urls as $k=>$v) {
1285 if (is_array($v)) {
1286 // optgroup structure
1287 foreach ($v as $optgrouptitle => $optgroupoptions) {
1288 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1289 if (empty($optionurl)) {
1290 $safeoptionurl = '';
1291 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1292 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1293 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1294 } else if (strpos($optionurl, '/') !== 0) {
1295 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1296 continue;
1297 } else {
1298 $safeoptionurl = $optionurl;
1300 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1303 } else {
1304 // plain list structure
1305 if (empty($k)) {
1306 // nothing selected option
1307 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1308 $k = str_replace($CFG->wwwroot, '', $k);
1309 } else if (strpos($k, '/') !== 0) {
1310 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1311 continue;
1313 $urls[$k] = $v;
1316 $selected = $select->selected;
1317 if (!empty($selected)) {
1318 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1319 $selected = str_replace($CFG->wwwroot, '', $selected);
1320 } else if (strpos($selected, '/') !== 0) {
1321 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1325 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1326 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1328 if (!$select->showbutton) {
1329 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1330 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1331 $nothing = empty($select->nothing) ? false : key($select->nothing);
1332 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1333 } else {
1334 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1337 // then div wrapper for xhtml strictness
1338 $output = html_writer::tag('div', $output);
1340 // now the form itself around it
1341 $formattributes = array('method' => 'post',
1342 'action' => new moodle_url('/course/jumpto.php'),
1343 'id' => $select->formid);
1344 $output = html_writer::tag('form', $output, $formattributes);
1346 // and finally one more wrapper with class
1347 return html_writer::tag('div', $output, array('class' => $select->class));
1351 * Returns a string containing a link to the user documentation.
1352 * Also contains an icon by default. Shown to teachers and admin only.
1353 * @param string $path The page link after doc root and language, no leading slash.
1354 * @param string $text The text to be displayed for the link
1355 * @return string
1357 public function doc_link($path, $text = '') {
1358 global $CFG;
1360 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1362 $url = new moodle_url(get_docs_url($path));
1364 $attributes = array('href'=>$url);
1365 if (!empty($CFG->doctonewwindow)) {
1366 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1369 return html_writer::tag('a', $icon.$text, $attributes);
1373 * Render icon
1374 * @param string $pix short pix name
1375 * @param string $alt mandatory alt attribute
1376 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1377 * @param array $attributes htm lattributes
1378 * @return string HTML fragment
1380 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1381 $icon = new pix_icon($pix, $alt, $component, $attributes);
1382 return $this->render($icon);
1386 * Render icon
1387 * @param pix_icon $icon
1388 * @return string HTML fragment
1390 protected function render_pix_icon(pix_icon $icon) {
1391 $attributes = $icon->attributes;
1392 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1393 return html_writer::empty_tag('img', $attributes);
1397 * Render emoticon
1398 * @param pix_emoticon $emoticon
1399 * @return string HTML fragment
1401 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1402 $attributes = $emoticon->attributes;
1403 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1404 return html_writer::empty_tag('img', $attributes);
1408 * Produces the html that represents this rating in the UI
1409 * @param $page the page object on which this rating will appear
1411 function render_rating(rating $rating) {
1412 global $CFG, $USER;
1414 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1415 return null;//ratings are turned off
1418 $ratingmanager = new rating_manager();
1419 // Initialise the JavaScript so ratings can be done by AJAX.
1420 $ratingmanager->initialise_rating_javascript($this->page);
1422 $strrate = get_string("rate", "rating");
1423 $ratinghtml = ''; //the string we'll return
1425 // permissions check - can they view the aggregate?
1426 if ($rating->user_can_view_aggregate()) {
1428 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1429 $aggregatestr = $rating->get_aggregate_string();
1431 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid)).' ';
1432 $aggregatehtml .= html_writer::start_tag('span', array('id'=>"ratingcount{$rating->itemid}"));
1433 if ($rating->count > 0) {
1434 $aggregatehtml .= "({$rating->count})";
1435 } else {
1436 $aggregatehtml .= '-';
1438 $aggregatehtml .= html_writer::end_tag('span').' ';
1440 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1441 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1443 $nonpopuplink = $rating->get_view_ratings_url();
1444 $popuplink = $rating->get_view_ratings_url(true);
1446 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1447 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1448 } else {
1449 $ratinghtml .= $aggregatehtml;
1453 $formstart = null;
1454 // if the item doesn't belong to the current user, the user has permission to rate
1455 // and we're within the assessable period
1456 if ($rating->user_can_rate()) {
1458 $rateurl = $rating->get_rate_url();
1459 $inputs = $rateurl->params();
1461 //start the rating form
1462 $formattrs = array(
1463 'id' => "postrating{$rating->itemid}",
1464 'class' => 'postratingform',
1465 'method' => 'post',
1466 'action' => $rateurl->out_omit_querystring()
1468 $formstart = html_writer::start_tag('form', $formattrs);
1469 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1471 // add the hidden inputs
1472 foreach ($inputs as $name => $value) {
1473 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1474 $formstart .= html_writer::empty_tag('input', $attributes);
1477 if (empty($ratinghtml)) {
1478 $ratinghtml .= $strrate.': ';
1480 $ratinghtml = $formstart.$ratinghtml;
1482 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1483 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1484 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1486 //output submit button
1487 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1489 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1490 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1492 if (!$rating->settings->scale->isnumeric) {
1493 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1495 $ratinghtml .= html_writer::end_tag('span');
1496 $ratinghtml .= html_writer::end_tag('div');
1497 $ratinghtml .= html_writer::end_tag('form');
1500 return $ratinghtml;
1504 * Centered heading with attached help button (same title text)
1505 * and optional icon attached
1506 * @param string $text A heading text
1507 * @param string $helpidentifier The keyword that defines a help page
1508 * @param string $component component name
1509 * @param string|moodle_url $icon
1510 * @param string $iconalt icon alt text
1511 * @return string HTML fragment
1513 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1514 $image = '';
1515 if ($icon) {
1516 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1519 $help = '';
1520 if ($helpidentifier) {
1521 $help = $this->help_icon($helpidentifier, $component);
1524 return $this->heading($image.$text.$help, 2, 'main help');
1528 * Print a help icon.
1530 * @deprecated since Moodle 2.0
1531 * @param string $page The keyword that defines a help page
1532 * @param string $title A descriptive text for accessibility only
1533 * @param string $component component name
1534 * @param string|bool $linktext true means use $title as link text, string means link text value
1535 * @return string HTML fragment
1537 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1538 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1539 $icon = new old_help_icon($helpidentifier, $title, $component);
1540 if ($linktext === true) {
1541 $icon->linktext = $title;
1542 } else if (!empty($linktext)) {
1543 $icon->linktext = $linktext;
1545 return $this->render($icon);
1549 * Implementation of user image rendering.
1550 * @param help_icon $helpicon
1551 * @return string HTML fragment
1553 protected function render_old_help_icon(old_help_icon $helpicon) {
1554 global $CFG;
1556 // first get the help image icon
1557 $src = $this->pix_url('help');
1559 if (empty($helpicon->linktext)) {
1560 $alt = $helpicon->title;
1561 } else {
1562 $alt = get_string('helpwiththis');
1565 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1566 $output = html_writer::empty_tag('img', $attributes);
1568 // add the link text if given
1569 if (!empty($helpicon->linktext)) {
1570 // the spacing has to be done through CSS
1571 $output .= $helpicon->linktext;
1574 // now create the link around it - we need https on loginhttps pages
1575 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1577 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1578 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1580 $attributes = array('href'=>$url, 'title'=>$title);
1581 $id = html_writer::random_id('helpicon');
1582 $attributes['id'] = $id;
1583 $output = html_writer::tag('a', $output, $attributes);
1585 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1587 // and finally span
1588 return html_writer::tag('span', $output, array('class' => 'helplink'));
1592 * Print a help icon.
1594 * @param string $identifier The keyword that defines a help page
1595 * @param string $component component name
1596 * @param string|bool $linktext true means use $title as link text, string means link text value
1597 * @return string HTML fragment
1599 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1600 $icon = new help_icon($identifier, $component);
1601 $icon->diag_strings();
1602 if ($linktext === true) {
1603 $icon->linktext = get_string($icon->identifier, $icon->component);
1604 } else if (!empty($linktext)) {
1605 $icon->linktext = $linktext;
1607 return $this->render($icon);
1611 * Implementation of user image rendering.
1612 * @param help_icon $helpicon
1613 * @return string HTML fragment
1615 protected function render_help_icon(help_icon $helpicon) {
1616 global $CFG;
1618 // first get the help image icon
1619 $src = $this->pix_url('help');
1621 $title = get_string($helpicon->identifier, $helpicon->component);
1623 if (empty($helpicon->linktext)) {
1624 $alt = $title;
1625 } else {
1626 $alt = get_string('helpwiththis');
1629 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1630 $output = html_writer::empty_tag('img', $attributes);
1632 // add the link text if given
1633 if (!empty($helpicon->linktext)) {
1634 // the spacing has to be done through CSS
1635 $output .= $helpicon->linktext;
1638 // now create the link around it - we need https on loginhttps pages
1639 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1641 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1642 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1644 $attributes = array('href'=>$url, 'title'=>$title);
1645 $id = html_writer::random_id('helpicon');
1646 $attributes['id'] = $id;
1647 $output = html_writer::tag('a', $output, $attributes);
1649 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1651 // and finally span
1652 return html_writer::tag('span', $output, array('class' => 'helplink'));
1656 * Print scale help icon.
1658 * @param int $courseid
1659 * @param object $scale instance
1660 * @return string HTML fragment
1662 public function help_icon_scale($courseid, stdClass $scale) {
1663 global $CFG;
1665 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1667 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1669 $scaleid = abs($scale->id);
1671 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1672 $action = new popup_action('click', $link, 'ratingscale');
1674 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1678 * Creates and returns a spacer image with optional line break.
1680 * @param array $attributes
1681 * @param boo spacer
1682 * @return string HTML fragment
1684 public function spacer(array $attributes = null, $br = false) {
1685 $attributes = (array)$attributes;
1686 if (empty($attributes['width'])) {
1687 $attributes['width'] = 1;
1689 if (empty($attributes['height'])) {
1690 $attributes['height'] = 1;
1692 $attributes['class'] = 'spacer';
1694 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1696 if (!empty($br)) {
1697 $output .= '<br />';
1700 return $output;
1704 * Print the specified user's avatar.
1706 * User avatar may be obtained in two ways:
1707 * <pre>
1708 * // Option 1: (shortcut for simple cases, preferred way)
1709 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1710 * $OUTPUT->user_picture($user, array('popup'=>true));
1712 * // Option 2:
1713 * $userpic = new user_picture($user);
1714 * // Set properties of $userpic
1715 * $userpic->popup = true;
1716 * $OUTPUT->render($userpic);
1717 * </pre>
1719 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1720 * If any of these are missing, the database is queried. Avoid this
1721 * if at all possible, particularly for reports. It is very bad for performance.
1722 * @param array $options associative array with user picture options, used only if not a user_picture object,
1723 * options are:
1724 * - courseid=$this->page->course->id (course id of user profile in link)
1725 * - size=35 (size of image)
1726 * - link=true (make image clickable - the link leads to user profile)
1727 * - popup=false (open in popup)
1728 * - alttext=true (add image alt attribute)
1729 * - class = image class attribute (default 'userpicture')
1730 * @return string HTML fragment
1732 public function user_picture(stdClass $user, array $options = null) {
1733 $userpicture = new user_picture($user);
1734 foreach ((array)$options as $key=>$value) {
1735 if (array_key_exists($key, $userpicture)) {
1736 $userpicture->$key = $value;
1739 return $this->render($userpicture);
1743 * Internal implementation of user image rendering.
1744 * @param user_picture $userpicture
1745 * @return string
1747 protected function render_user_picture(user_picture $userpicture) {
1748 global $CFG, $DB;
1750 $user = $userpicture->user;
1752 if ($userpicture->alttext) {
1753 if (!empty($user->imagealt)) {
1754 $alt = $user->imagealt;
1755 } else {
1756 $alt = get_string('pictureof', '', fullname($user));
1758 } else {
1759 $alt = '';
1762 if (empty($userpicture->size)) {
1763 $file = 'f2';
1764 $size = 35;
1765 } else if ($userpicture->size === true or $userpicture->size == 1) {
1766 $file = 'f1';
1767 $size = 100;
1768 } else if ($userpicture->size >= 50) {
1769 $file = 'f1';
1770 $size = $userpicture->size;
1771 } else {
1772 $file = 'f2';
1773 $size = $userpicture->size;
1776 $class = $userpicture->class;
1778 if ($user->picture == 1) {
1779 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1780 $src = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', $file);
1782 } else if ($user->picture == 2) {
1783 //TODO: gravatar user icon support
1785 } else { // Print default user pictures (use theme version if available)
1786 $class .= ' defaultuserpic';
1787 $src = $this->pix_url('u/' . $file);
1790 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1792 // get the image html output fisrt
1793 $output = html_writer::empty_tag('img', $attributes);;
1795 // then wrap it in link if needed
1796 if (!$userpicture->link) {
1797 return $output;
1800 if (empty($userpicture->courseid)) {
1801 $courseid = $this->page->course->id;
1802 } else {
1803 $courseid = $userpicture->courseid;
1806 if ($courseid == SITEID) {
1807 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1808 } else {
1809 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1812 $attributes = array('href'=>$url);
1814 if ($userpicture->popup) {
1815 $id = html_writer::random_id('userpicture');
1816 $attributes['id'] = $id;
1817 $this->add_action_handler(new popup_action('click', $url), $id);
1820 return html_writer::tag('a', $output, $attributes);
1824 * Internal implementation of file tree viewer items rendering.
1825 * @param array $dir
1826 * @return string
1828 public function htmllize_file_tree($dir) {
1829 if (empty($dir['subdirs']) and empty($dir['files'])) {
1830 return '';
1832 $result = '<ul>';
1833 foreach ($dir['subdirs'] as $subdir) {
1834 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1836 foreach ($dir['files'] as $file) {
1837 $filename = $file->get_filename();
1838 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1840 $result .= '</ul>';
1842 return $result;
1845 * Print the file picker
1847 * <pre>
1848 * $OUTPUT->file_picker($options);
1849 * </pre>
1851 * @param array $options associative array with file manager options
1852 * options are:
1853 * maxbytes=>-1,
1854 * itemid=>0,
1855 * client_id=>uniqid(),
1856 * acepted_types=>'*',
1857 * return_types=>FILE_INTERNAL,
1858 * context=>$PAGE->context
1859 * @return string HTML fragment
1861 public function file_picker($options) {
1862 $fp = new file_picker($options);
1863 return $this->render($fp);
1866 * Internal implementation of file picker rendering.
1867 * @param file_picker $fp
1868 * @return string
1870 public function render_file_picker(file_picker $fp) {
1871 global $CFG, $OUTPUT, $USER;
1872 $options = $fp->options;
1873 $client_id = $options->client_id;
1874 $strsaved = get_string('filesaved', 'repository');
1875 $straddfile = get_string('openpicker', 'repository');
1876 $strloading = get_string('loading', 'repository');
1877 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1879 $currentfile = $options->currentfile;
1880 if (empty($currentfile)) {
1881 $currentfile = get_string('nofilesattached', 'repository');
1883 if ($options->maxbytes) {
1884 $size = $options->maxbytes;
1885 } else {
1886 $size = get_max_upload_file_size();
1888 if ($size == -1) {
1889 $maxsize = '';
1890 } else {
1891 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
1893 if ($options->buttonname) {
1894 $buttonname = ' name="' . $options->buttonname . '"';
1895 } else {
1896 $buttonname = '';
1898 $html = <<<EOD
1899 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1900 $icon_progress
1901 </div>
1902 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1903 <div>
1904 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
1905 <span> $maxsize </span>
1906 </div>
1907 EOD;
1908 if ($options->env != 'url') {
1909 $html .= <<<EOD
1910 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1911 EOD;
1913 $html .= '</div>';
1914 return $html;
1918 * Prints the 'Update this Modulename' button that appears on module pages.
1920 * @param string $cmid the course_module id.
1921 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1922 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1924 public function update_module_button($cmid, $modulename) {
1925 global $CFG;
1926 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1927 $modulename = get_string('modulename', $modulename);
1928 $string = get_string('updatethis', '', $modulename);
1929 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1930 return $this->single_button($url, $string);
1931 } else {
1932 return '';
1937 * Prints a "Turn editing on/off" button in a form.
1938 * @param moodle_url $url The URL + params to send through when clicking the button
1939 * @return string HTML the button
1941 public function edit_button(moodle_url $url) {
1943 $url->param('sesskey', sesskey());
1944 if ($this->page->user_is_editing()) {
1945 $url->param('edit', 'off');
1946 $editstring = get_string('turneditingoff');
1947 } else {
1948 $url->param('edit', 'on');
1949 $editstring = get_string('turneditingon');
1952 return $this->single_button($url, $editstring);
1956 * Prints a simple button to close a window
1958 * @param string $text The lang string for the button's label (already output from get_string())
1959 * @return string html fragment
1961 public function close_window_button($text='') {
1962 if (empty($text)) {
1963 $text = get_string('closewindow');
1965 $button = new single_button(new moodle_url('#'), $text, 'get');
1966 $button->add_action(new component_action('click', 'close_window'));
1968 return $this->container($this->render($button), 'closewindow');
1972 * Output an error message. By default wraps the error message in <span class="error">.
1973 * If the error message is blank, nothing is output.
1974 * @param string $message the error message.
1975 * @return string the HTML to output.
1977 public function error_text($message) {
1978 if (empty($message)) {
1979 return '';
1981 return html_writer::tag('span', $message, array('class' => 'error'));
1985 * Do not call this function directly.
1987 * To terminate the current script with a fatal error, call the {@link print_error}
1988 * function, or throw an exception. Doing either of those things will then call this
1989 * function to display the error, before terminating the execution.
1991 * @param string $message The message to output
1992 * @param string $moreinfourl URL where more info can be found about the error
1993 * @param string $link Link for the Continue button
1994 * @param array $backtrace The execution backtrace
1995 * @param string $debuginfo Debugging information
1996 * @return string the HTML to output.
1998 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1999 global $CFG;
2001 $output = '';
2002 $obbuffer = '';
2004 if ($this->has_started()) {
2005 // we can not always recover properly here, we have problems with output buffering,
2006 // html tables, etc.
2007 $output .= $this->opencontainers->pop_all_but_last();
2009 } else {
2010 // It is really bad if library code throws exception when output buffering is on,
2011 // because the buffered text would be printed before our start of page.
2012 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2013 error_reporting(0); // disable notices from gzip compression, etc.
2014 while (ob_get_level() > 0) {
2015 $buff = ob_get_clean();
2016 if ($buff === false) {
2017 break;
2019 $obbuffer .= $buff;
2021 error_reporting($CFG->debug);
2023 // Header not yet printed
2024 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2025 // server protocol should be always present, because this render
2026 // can not be used from command line or when outputting custom XML
2027 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2029 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2030 $this->page->set_url('/'); // no url
2031 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2032 $this->page->set_title(get_string('error'));
2033 $this->page->set_heading($this->page->course->fullname);
2034 $output .= $this->header();
2037 $message = '<p class="errormessage">' . $message . '</p>'.
2038 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2039 get_string('moreinformation') . '</a></p>';
2040 $output .= $this->box($message, 'errorbox');
2042 if (debugging('', DEBUG_DEVELOPER)) {
2043 if (!empty($debuginfo)) {
2044 $debuginfo = s($debuginfo); // removes all nasty JS
2045 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2046 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2048 if (!empty($backtrace)) {
2049 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2051 if ($obbuffer !== '' ) {
2052 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2056 if (!empty($link)) {
2057 $output .= $this->continue_button($link);
2060 $output .= $this->footer();
2062 // Padding to encourage IE to display our error page, rather than its own.
2063 $output .= str_repeat(' ', 512);
2065 return $output;
2069 * Output a notification (that is, a status message about something that has
2070 * just happened).
2072 * @param string $message the message to print out
2073 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2074 * @return string the HTML to output.
2076 public function notification($message, $classes = 'notifyproblem') {
2077 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2081 * Print a continue button that goes to a particular URL.
2083 * @param string|moodle_url $url The url the button goes to.
2084 * @return string the HTML to output.
2086 public function continue_button($url) {
2087 if (!($url instanceof moodle_url)) {
2088 $url = new moodle_url($url);
2090 $button = new single_button($url, get_string('continue'), 'get');
2091 $button->class = 'continuebutton';
2093 return $this->render($button);
2097 * Prints a single paging bar to provide access to other pages (usually in a search)
2099 * @param int $totalcount The total number of entries available to be paged through
2100 * @param int $page The page you are currently viewing
2101 * @param int $perpage The number of entries that should be shown per page
2102 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2103 * @param string $pagevar name of page parameter that holds the page number
2104 * @return string the HTML to output.
2106 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2107 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2108 return $this->render($pb);
2112 * Internal implementation of paging bar rendering.
2113 * @param paging_bar $pagingbar
2114 * @return string
2116 protected function render_paging_bar(paging_bar $pagingbar) {
2117 $output = '';
2118 $pagingbar = clone($pagingbar);
2119 $pagingbar->prepare($this, $this->page, $this->target);
2121 if ($pagingbar->totalcount > $pagingbar->perpage) {
2122 $output .= get_string('page') . ':';
2124 if (!empty($pagingbar->previouslink)) {
2125 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2128 if (!empty($pagingbar->firstlink)) {
2129 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2132 foreach ($pagingbar->pagelinks as $link) {
2133 $output .= "&#160;&#160;$link";
2136 if (!empty($pagingbar->lastlink)) {
2137 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2140 if (!empty($pagingbar->nextlink)) {
2141 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2145 return html_writer::tag('div', $output, array('class' => 'paging'));
2149 * Output the place a skip link goes to.
2150 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2151 * @return string the HTML to output.
2153 public function skip_link_target($id = null) {
2154 return html_writer::tag('span', '', array('id' => $id));
2158 * Outputs a heading
2159 * @param string $text The text of the heading
2160 * @param int $level The level of importance of the heading. Defaulting to 2
2161 * @param string $classes A space-separated list of CSS classes
2162 * @param string $id An optional ID
2163 * @return string the HTML to output.
2165 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2166 $level = (integer) $level;
2167 if ($level < 1 or $level > 6) {
2168 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2170 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2174 * Outputs a box.
2175 * @param string $contents The contents of the box
2176 * @param string $classes A space-separated list of CSS classes
2177 * @param string $id An optional ID
2178 * @return string the HTML to output.
2180 public function box($contents, $classes = 'generalbox', $id = null) {
2181 return $this->box_start($classes, $id) . $contents . $this->box_end();
2185 * Outputs the opening section of a box.
2186 * @param string $classes A space-separated list of CSS classes
2187 * @param string $id An optional ID
2188 * @return string the HTML to output.
2190 public function box_start($classes = 'generalbox', $id = null) {
2191 $this->opencontainers->push('box', html_writer::end_tag('div'));
2192 return html_writer::start_tag('div', array('id' => $id,
2193 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2197 * Outputs the closing section of a box.
2198 * @return string the HTML to output.
2200 public function box_end() {
2201 return $this->opencontainers->pop('box');
2205 * Outputs a container.
2206 * @param string $contents The contents of the box
2207 * @param string $classes A space-separated list of CSS classes
2208 * @param string $id An optional ID
2209 * @return string the HTML to output.
2211 public function container($contents, $classes = null, $id = null) {
2212 return $this->container_start($classes, $id) . $contents . $this->container_end();
2216 * Outputs the opening section of a container.
2217 * @param string $classes A space-separated list of CSS classes
2218 * @param string $id An optional ID
2219 * @return string the HTML to output.
2221 public function container_start($classes = null, $id = null) {
2222 $this->opencontainers->push('container', html_writer::end_tag('div'));
2223 return html_writer::start_tag('div', array('id' => $id,
2224 'class' => renderer_base::prepare_classes($classes)));
2228 * Outputs the closing section of a container.
2229 * @return string the HTML to output.
2231 public function container_end() {
2232 return $this->opencontainers->pop('container');
2236 * Make nested HTML lists out of the items
2238 * The resulting list will look something like this:
2240 * <pre>
2241 * <<ul>>
2242 * <<li>><div class='tree_item parent'>(item contents)</div>
2243 * <<ul>
2244 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2245 * <</ul>>
2246 * <</li>>
2247 * <</ul>>
2248 * </pre>
2250 * @param array[]tree_item $items
2251 * @param array[string]string $attrs html attributes passed to the top of
2252 * the list
2253 * @return string HTML
2255 function tree_block_contents($items, $attrs=array()) {
2256 // exit if empty, we don't want an empty ul element
2257 if (empty($items)) {
2258 return '';
2260 // array of nested li elements
2261 $lis = array();
2262 foreach ($items as $item) {
2263 // this applies to the li item which contains all child lists too
2264 $content = $item->content($this);
2265 $liclasses = array($item->get_css_type());
2266 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2267 $liclasses[] = 'collapsed';
2269 if ($item->isactive === true) {
2270 $liclasses[] = 'current_branch';
2272 $liattr = array('class'=>join(' ',$liclasses));
2273 // class attribute on the div item which only contains the item content
2274 $divclasses = array('tree_item');
2275 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2276 $divclasses[] = 'branch';
2277 } else {
2278 $divclasses[] = 'leaf';
2280 if (!empty($item->classes) && count($item->classes)>0) {
2281 $divclasses[] = join(' ', $item->classes);
2283 $divattr = array('class'=>join(' ', $divclasses));
2284 if (!empty($item->id)) {
2285 $divattr['id'] = $item->id;
2287 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2288 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2289 $content = html_writer::empty_tag('hr') . $content;
2291 $content = html_writer::tag('li', $content, $liattr);
2292 $lis[] = $content;
2294 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2298 * Return the navbar content so that it can be echoed out by the layout
2299 * @return string XHTML navbar
2301 public function navbar() {
2302 $items = $this->page->navbar->get_items();
2304 $htmlblocks = array();
2305 // Iterate the navarray and display each node
2306 $itemcount = count($items);
2307 $separator = get_separator();
2308 for ($i=0;$i < $itemcount;$i++) {
2309 $item = $items[$i];
2310 $item->hideicon = true;
2311 if ($i===0) {
2312 $content = html_writer::tag('li', $this->render($item));
2313 } else {
2314 $content = html_writer::tag('li', $separator.$this->render($item));
2316 $htmlblocks[] = $content;
2319 //accessibility: heading for navbar list (MDL-20446)
2320 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2321 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2322 // XHTML
2323 return $navbarcontent;
2326 protected function render_navigation_node(navigation_node $item) {
2327 $content = $item->get_content();
2328 $title = $item->get_title();
2329 if ($item->icon instanceof renderable && !$item->hideicon) {
2330 $icon = $this->render($item->icon);
2331 $content = $icon.$content; // use CSS for spacing of icons
2333 if ($item->helpbutton !== null) {
2334 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2336 if ($content === '') {
2337 return '';
2339 if ($item->action instanceof action_link) {
2340 $link = $item->action;
2341 if ($item->hidden) {
2342 $link->add_class('dimmed');
2344 $link->text = $content.$link->text; // add help icon
2345 $content = $this->render($link);
2346 } else if ($item->action instanceof moodle_url) {
2347 $attributes = array();
2348 if ($title !== '') {
2349 $attributes['title'] = $title;
2351 if ($item->hidden) {
2352 $attributes['class'] = 'dimmed_text';
2354 $content = html_writer::link($item->action, $content, $attributes);
2356 } else if (is_string($item->action) || empty($item->action)) {
2357 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2358 if ($title !== '') {
2359 $attributes['title'] = $title;
2361 if ($item->hidden) {
2362 $attributes['class'] = 'dimmed_text';
2364 $content = html_writer::tag('span', $content, $attributes);
2366 return $content;
2370 * Accessibility: Right arrow-like character is
2371 * used in the breadcrumb trail, course navigation menu
2372 * (previous/next activity), calendar, and search forum block.
2373 * If the theme does not set characters, appropriate defaults
2374 * are set automatically. Please DO NOT
2375 * use &lt; &gt; &raquo; - these are confusing for blind users.
2376 * @return string
2378 public function rarrow() {
2379 return $this->page->theme->rarrow;
2383 * Accessibility: Right arrow-like character is
2384 * used in the breadcrumb trail, course navigation menu
2385 * (previous/next activity), calendar, and search forum block.
2386 * If the theme does not set characters, appropriate defaults
2387 * are set automatically. Please DO NOT
2388 * use &lt; &gt; &raquo; - these are confusing for blind users.
2389 * @return string
2391 public function larrow() {
2392 return $this->page->theme->larrow;
2396 * Returns the custom menu if one has been set
2398 * A custom menu can be configured by browsing to
2399 * Settings: Administration > Appearance > Themes > Theme settings
2400 * and then configuring the custommenu config setting as described.
2402 * @return string
2404 public function custom_menu() {
2405 global $CFG;
2406 if (empty($CFG->custommenuitems)) {
2407 return '';
2409 $custommenu = new custom_menu();
2410 return $this->render_custom_menu($custommenu);
2414 * Renders a custom menu object (located in outputcomponents.php)
2416 * The custom menu this method produces makes use of the YUI3 menunav widget
2417 * and requires very specific html elements and classes.
2419 * @staticvar int $menucount
2420 * @param custom_menu $menu
2421 * @return string
2423 protected function render_custom_menu(custom_menu $menu) {
2424 static $menucount = 0;
2425 // If the menu has no children return an empty string
2426 if (!$menu->has_children()) {
2427 return '';
2429 // Increment the menu count. This is used for ID's that get worked with
2430 // in JavaScript as is essential
2431 $menucount++;
2432 // Initialise this custom menu
2433 $this->page->requires->js_init_call('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2434 // Build the root nodes as required by YUI
2435 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2436 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2437 $content .= html_writer::start_tag('ul');
2438 // Render each child
2439 foreach ($menu->get_children() as $item) {
2440 $content .= $this->render_custom_menu_item($item);
2442 // Close the open tags
2443 $content .= html_writer::end_tag('ul');
2444 $content .= html_writer::end_tag('div');
2445 $content .= html_writer::end_tag('div');
2446 // Return the custom menu
2447 return $content;
2451 * Renders a custom menu node as part of a submenu
2453 * The custom menu this method produces makes use of the YUI3 menunav widget
2454 * and requires very specific html elements and classes.
2456 * @see render_custom_menu()
2458 * @staticvar int $submenucount
2459 * @param custom_menu_item $menunode
2460 * @return string
2462 protected function render_custom_menu_item(custom_menu_item $menunode) {
2463 // Required to ensure we get unique trackable id's
2464 static $submenucount = 0;
2465 if ($menunode->has_children()) {
2466 // If the child has menus render it as a sub menu
2467 $submenucount++;
2468 $content = html_writer::start_tag('li');
2469 if ($menunode->get_url() !== null) {
2470 $url = $menunode->get_url();
2471 } else {
2472 $url = '#cm_submenu_'.$submenucount;
2474 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2475 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2476 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2477 $content .= html_writer::start_tag('ul');
2478 foreach ($menunode->get_children() as $menunode) {
2479 $content .= $this->render_custom_menu_item($menunode);
2481 $content .= html_writer::end_tag('ul');
2482 $content .= html_writer::end_tag('div');
2483 $content .= html_writer::end_tag('div');
2484 $content .= html_writer::end_tag('li');
2485 } else {
2486 // The node doesn't have children so produce a final menuitem
2487 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2488 if ($menunode->get_url() !== null) {
2489 $url = $menunode->get_url();
2490 } else {
2491 $url = '#';
2493 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2494 $content .= html_writer::end_tag('li');
2496 // Return the sub menu
2497 return $content;
2502 /// RENDERERS
2505 * A renderer that generates output for command-line scripts.
2507 * The implementation of this renderer is probably incomplete.
2509 * @copyright 2009 Tim Hunt
2510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2511 * @since Moodle 2.0
2513 class core_renderer_cli extends core_renderer {
2515 * Returns the page header.
2516 * @return string HTML fragment
2518 public function header() {
2519 return $this->page->heading . "\n";
2523 * Returns a template fragment representing a Heading.
2524 * @param string $text The text of the heading
2525 * @param int $level The level of importance of the heading
2526 * @param string $classes A space-separated list of CSS classes
2527 * @param string $id An optional ID
2528 * @return string A template fragment for a heading
2530 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2531 $text .= "\n";
2532 switch ($level) {
2533 case 1:
2534 return '=>' . $text;
2535 case 2:
2536 return '-->' . $text;
2537 default:
2538 return $text;
2543 * Returns a template fragment representing a fatal error.
2544 * @param string $message The message to output
2545 * @param string $moreinfourl URL where more info can be found about the error
2546 * @param string $link Link for the Continue button
2547 * @param array $backtrace The execution backtrace
2548 * @param string $debuginfo Debugging information
2549 * @return string A template fragment for a fatal error
2551 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2552 $output = "!!! $message !!!\n";
2554 if (debugging('', DEBUG_DEVELOPER)) {
2555 if (!empty($debuginfo)) {
2556 $output .= $this->notification($debuginfo, 'notifytiny');
2558 if (!empty($backtrace)) {
2559 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2563 return $output;
2567 * Returns a template fragment representing a notification.
2568 * @param string $message The message to include
2569 * @param string $classes A space-separated list of CSS classes
2570 * @return string A template fragment for a notification
2572 public function notification($message, $classes = 'notifyproblem') {
2573 $message = clean_text($message);
2574 if ($classes === 'notifysuccess') {
2575 return "++ $message ++\n";
2577 return "!! $message !!\n";
2583 * A renderer that generates output for ajax scripts.
2585 * This renderer prevents accidental sends back only json
2586 * encoded error messages, all other output is ignored.
2588 * @copyright 2010 Petr Skoda
2589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2590 * @since Moodle 2.0
2592 class core_renderer_ajax extends core_renderer {
2594 * Returns a template fragment representing a fatal error.
2595 * @param string $message The message to output
2596 * @param string $moreinfourl URL where more info can be found about the error
2597 * @param string $link Link for the Continue button
2598 * @param array $backtrace The execution backtrace
2599 * @param string $debuginfo Debugging information
2600 * @return string A template fragment for a fatal error
2602 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2603 global $CFG;
2605 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2607 $e = new stdClass();
2608 $e->error = $message;
2609 $e->stacktrace = NULL;
2610 $e->debuginfo = NULL;
2611 $e->reproductionlink = NULL;
2612 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2613 $e->reproductionlink = $link;
2614 if (!empty($debuginfo)) {
2615 $e->debuginfo = $debuginfo;
2617 if (!empty($backtrace)) {
2618 $e->stacktrace = format_backtrace($backtrace, true);
2621 $this->header();
2622 return json_encode($e);
2625 public function notification($message, $classes = 'notifyproblem') {
2628 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2631 public function header() {
2632 // unfortunately YUI iframe upload does not support application/json
2633 if (!empty($_FILES)) {
2634 @header('Content-type: text/plain; charset=utf-8');
2635 } else {
2636 @header('Content-type: application/json; charset=utf-8');
2639 /// Headers to make it not cacheable and json
2640 @header('Cache-Control: no-store, no-cache, must-revalidate');
2641 @header('Cache-Control: post-check=0, pre-check=0', false);
2642 @header('Pragma: no-cache');
2643 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2644 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2645 @header('Accept-Ranges: none');
2648 public function footer() {
2651 public function heading($text, $level = 2, $classes = 'main', $id = null) {