MDL-45893 user_menu: revised based on action_menu
[moodle.git] / lib / outputrenderers.php
blobf289bf7a997c9aeaa15bdb31fcd9e2f0fd51de8a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $classname = get_class($widget);
100 // Strip namespaces.
101 $classname = preg_replace('/^.*\\\/', '', $classname);
102 // Remove _renderable suffixes
103 $classname = preg_replace('/_renderable$/', '', $classname);
105 $rendermethod = 'render_'.$classname;
106 if (method_exists($this, $rendermethod)) {
107 return $this->$rendermethod($widget);
109 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
113 * Adds a JS action for the element with the provided id.
115 * This method adds a JS event for the provided component action to the page
116 * and then returns the id that the event has been attached to.
117 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
119 * @param component_action $action
120 * @param string $id
121 * @return string id of element, either original submitted or random new if not supplied
123 public function add_action_handler(component_action $action, $id = null) {
124 if (!$id) {
125 $id = html_writer::random_id($action->event);
127 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
128 return $id;
132 * Returns true is output has already started, and false if not.
134 * @return boolean true if the header has been printed.
136 public function has_started() {
137 return $this->page->state >= moodle_page::STATE_IN_BODY;
141 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
143 * @param mixed $classes Space-separated string or array of classes
144 * @return string HTML class attribute value
146 public static function prepare_classes($classes) {
147 if (is_array($classes)) {
148 return implode(' ', array_unique($classes));
150 return $classes;
154 * Return the moodle_url for an image.
156 * The exact image location and extension is determined
157 * automatically by searching for gif|png|jpg|jpeg, please
158 * note there can not be diferent images with the different
159 * extension. The imagename is for historical reasons
160 * a relative path name, it may be changed later for core
161 * images. It is recommended to not use subdirectories
162 * in plugin and theme pix directories.
164 * There are three types of images:
165 * 1/ theme images - stored in theme/mytheme/pix/,
166 * use component 'theme'
167 * 2/ core images - stored in /pix/,
168 * overridden via theme/mytheme/pix_core/
169 * 3/ plugin images - stored in mod/mymodule/pix,
170 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
171 * example: pix_url('comment', 'mod_glossary')
173 * @param string $imagename the pathname of the image
174 * @param string $component full plugin name (aka component) or 'theme'
175 * @return moodle_url
177 public function pix_url($imagename, $component = 'moodle') {
178 return $this->page->theme->pix_url($imagename, $component);
184 * Basis for all plugin renderers.
186 * @copyright Petr Skoda (skodak)
187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
188 * @since Moodle 2.0
189 * @package core
190 * @category output
192 class plugin_renderer_base extends renderer_base {
195 * @var renderer_base|core_renderer A reference to the current renderer.
196 * The renderer provided here will be determined by the page but will in 90%
197 * of cases by the {@link core_renderer}
199 protected $output;
202 * Constructor method, calls the parent constructor
204 * @param moodle_page $page
205 * @param string $target one of rendering target constants
207 public function __construct(moodle_page $page, $target) {
208 if (empty($target) && $page->pagelayout === 'maintenance') {
209 // If the page is using the maintenance layout then we're going to force the target to maintenance.
210 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
211 // unavailable for this page layout.
212 $target = RENDERER_TARGET_MAINTENANCE;
214 $this->output = $page->get_renderer('core', null, $target);
215 parent::__construct($page, $target);
219 * Renders the provided widget and returns the HTML to display it.
221 * @param renderable $widget instance with renderable interface
222 * @return string
224 public function render(renderable $widget) {
225 $classname = get_class($widget);
226 // Strip namespaces.
227 $classname = preg_replace('/^.*\\\/', '', $classname);
228 // Keep a copy at this point, we may need to look for a deprecated method.
229 $deprecatedmethod = 'render_'.$classname;
230 // Remove _renderable suffixes
231 $classname = preg_replace('/_renderable$/', '', $classname);
233 $rendermethod = 'render_'.$classname;
234 if (method_exists($this, $rendermethod)) {
235 return $this->$rendermethod($widget);
237 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
238 // This is exactly where we don't want to be.
239 // If you have arrived here you have a renderable component within your plugin that has the name
240 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
241 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
242 // and the _renderable suffix now gets removed when looking for a render method.
243 // You need to change your renderers render_blah_renderable to render_blah.
244 // Until you do this it will not be possible for a theme to override the renderer to override your method.
245 // Please do it ASAP.
246 static $debugged = array();
247 if (!isset($debugged[$deprecatedmethod])) {
248 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
249 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
250 $debugged[$deprecatedmethod] = true;
252 return $this->$deprecatedmethod($widget);
254 // pass to core renderer if method not found here
255 return $this->output->render($widget);
259 * Magic method used to pass calls otherwise meant for the standard renderer
260 * to it to ensure we don't go causing unnecessary grief.
262 * @param string $method
263 * @param array $arguments
264 * @return mixed
266 public function __call($method, $arguments) {
267 if (method_exists('renderer_base', $method)) {
268 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
270 if (method_exists($this->output, $method)) {
271 return call_user_func_array(array($this->output, $method), $arguments);
272 } else {
273 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
280 * The standard implementation of the core_renderer interface.
282 * @copyright 2009 Tim Hunt
283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
284 * @since Moodle 2.0
285 * @package core
286 * @category output
288 class core_renderer extends renderer_base {
290 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
291 * in layout files instead.
292 * @deprecated
293 * @var string used in {@link core_renderer::header()}.
295 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
298 * @var string Used to pass information from {@link core_renderer::doctype()} to
299 * {@link core_renderer::standard_head_html()}.
301 protected $contenttype;
304 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
305 * with {@link core_renderer::header()}.
307 protected $metarefreshtag = '';
310 * @var string Unique token for the closing HTML
312 protected $unique_end_html_token;
315 * @var string Unique token for performance information
317 protected $unique_performance_info_token;
320 * @var string Unique token for the main content.
322 protected $unique_main_content_token;
325 * Constructor
327 * @param moodle_page $page the page we are doing output for.
328 * @param string $target one of rendering target constants
330 public function __construct(moodle_page $page, $target) {
331 $this->opencontainers = $page->opencontainers;
332 $this->page = $page;
333 $this->target = $target;
335 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
336 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
337 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
341 * Get the DOCTYPE declaration that should be used with this page. Designed to
342 * be called in theme layout.php files.
344 * @return string the DOCTYPE declaration that should be used.
346 public function doctype() {
347 if ($this->page->theme->doctype === 'html5') {
348 $this->contenttype = 'text/html; charset=utf-8';
349 return "<!DOCTYPE html>\n";
351 } else if ($this->page->theme->doctype === 'xhtml5') {
352 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
353 return "<!DOCTYPE html>\n";
355 } else {
356 // legacy xhtml 1.0
357 $this->contenttype = 'text/html; charset=utf-8';
358 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
363 * The attributes that should be added to the <html> tag. Designed to
364 * be called in theme layout.php files.
366 * @return string HTML fragment.
368 public function htmlattributes() {
369 $return = get_html_lang(true);
370 if ($this->page->theme->doctype !== 'html5') {
371 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
373 return $return;
377 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
378 * that should be included in the <head> tag. Designed to be called in theme
379 * layout.php files.
381 * @return string HTML fragment.
383 public function standard_head_html() {
384 global $CFG, $SESSION;
386 // Before we output any content, we need to ensure that certain
387 // page components are set up.
389 // Blocks must be set up early as they may require javascript which
390 // has to be included in the page header before output is created.
391 foreach ($this->page->blocks->get_regions() as $region) {
392 $this->page->blocks->ensure_content_created($region, $this);
395 $output = '';
396 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
397 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
398 // This is only set by the {@link redirect()} method
399 $output .= $this->metarefreshtag;
401 // Check if a periodic refresh delay has been set and make sure we arn't
402 // already meta refreshing
403 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
404 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
407 // flow player embedding support
408 $this->page->requires->js_function_call('M.util.load_flowplayer');
410 // Set up help link popups for all links with the helptooltip class
411 $this->page->requires->js_init_call('M.util.help_popups.setup');
413 // Setup help icon overlays.
414 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
415 $this->page->requires->strings_for_js(array(
416 'morehelp',
417 'loadinghelp',
418 ), 'moodle');
420 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
422 $focus = $this->page->focuscontrol;
423 if (!empty($focus)) {
424 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
425 // This is a horrifically bad way to handle focus but it is passed in
426 // through messy formslib::moodleform
427 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
428 } else if (strpos($focus, '.')!==false) {
429 // Old style of focus, bad way to do it
430 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);
431 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
432 } else {
433 // Focus element with given id
434 $this->page->requires->js_function_call('focuscontrol', array($focus));
438 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
439 // any other custom CSS can not be overridden via themes and is highly discouraged
440 $urls = $this->page->theme->css_urls($this->page);
441 foreach ($urls as $url) {
442 $this->page->requires->css_theme($url);
445 // Get the theme javascript head and footer
446 if ($jsurl = $this->page->theme->javascript_url(true)) {
447 $this->page->requires->js($jsurl, true);
449 if ($jsurl = $this->page->theme->javascript_url(false)) {
450 $this->page->requires->js($jsurl);
453 // Get any HTML from the page_requirements_manager.
454 $output .= $this->page->requires->get_head_code($this->page, $this);
456 // List alternate versions.
457 foreach ($this->page->alternateversions as $type => $alt) {
458 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
459 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
462 if (!empty($CFG->additionalhtmlhead)) {
463 $output .= "\n".$CFG->additionalhtmlhead;
466 return $output;
470 * The standard tags (typically skip links) that should be output just inside
471 * the start of the <body> tag. Designed to be called in theme layout.php files.
473 * @return string HTML fragment.
475 public function standard_top_of_body_html() {
476 global $CFG;
477 $output = $this->page->requires->get_top_of_body_code();
478 if (!empty($CFG->additionalhtmltopofbody)) {
479 $output .= "\n".$CFG->additionalhtmltopofbody;
481 $output .= $this->maintenance_warning();
482 return $output;
486 * Scheduled maintenance warning message.
488 * Note: This is a nasty hack to display maintenance notice, this should be moved
489 * to some general notification area once we have it.
491 * @return string
493 public function maintenance_warning() {
494 global $CFG;
496 $output = '';
497 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
498 $timeleft = $CFG->maintenance_later - time();
499 // If timeleft less than 30 sec, set the class on block to error to highlight.
500 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
501 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
502 $a = new stdClass();
503 $a->min = (int)($timeleft/60);
504 $a->sec = (int)($timeleft % 60);
505 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
506 $output .= $this->box_end();
507 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
508 array(array('timeleftinsec' => $timeleft)));
509 $this->page->requires->strings_for_js(
510 array('maintenancemodeisscheduled', 'sitemaintenance'),
511 'admin');
513 return $output;
517 * The standard tags (typically performance information and validation links,
518 * if we are in developer debug mode) that should be output in the footer area
519 * of the page. Designed to be called in theme layout.php files.
521 * @return string HTML fragment.
523 public function standard_footer_html() {
524 global $CFG, $SCRIPT;
526 if (during_initial_install()) {
527 // Debugging info can not work before install is finished,
528 // in any case we do not want any links during installation!
529 return '';
532 // This function is normally called from a layout.php file in {@link core_renderer::header()}
533 // but some of the content won't be known until later, so we return a placeholder
534 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
535 $output = $this->unique_performance_info_token;
536 if ($this->page->devicetypeinuse == 'legacy') {
537 // The legacy theme is in use print the notification
538 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
541 // Get links to switch device types (only shown for users not on a default device)
542 $output .= $this->theme_switch_links();
544 if (!empty($CFG->debugpageinfo)) {
545 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
547 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
548 // Add link to profiling report if necessary
549 if (function_exists('profiling_is_running') && profiling_is_running()) {
550 $txt = get_string('profiledscript', 'admin');
551 $title = get_string('profiledscriptview', 'admin');
552 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
553 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
554 $output .= '<div class="profilingfooter">' . $link . '</div>';
556 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
557 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
558 $output .= '<div class="purgecaches">' .
559 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
561 if (!empty($CFG->debugvalidators)) {
562 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
563 $output .= '<div class="validators"><ul>
564 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
565 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
566 <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>
567 </ul></div>';
569 return $output;
573 * Returns standard main content placeholder.
574 * Designed to be called in theme layout.php files.
576 * @return string HTML fragment.
578 public function main_content() {
579 // This is here because it is the only place we can inject the "main" role over the entire main content area
580 // without requiring all theme's to manually do it, and without creating yet another thing people need to
581 // remember in the theme.
582 // This is an unfortunate hack. DO NO EVER add anything more here.
583 // DO NOT add classes.
584 // DO NOT add an id.
585 return '<div role="main">'.$this->unique_main_content_token.'</div>';
589 * The standard tags (typically script tags that are not needed earlier) that
590 * should be output after everything else. Designed to be called in theme layout.php files.
592 * @return string HTML fragment.
594 public function standard_end_of_body_html() {
595 global $CFG;
597 // This function is normally called from a layout.php file in {@link core_renderer::header()}
598 // but some of the content won't be known until later, so we return a placeholder
599 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
600 $output = '';
601 if (!empty($CFG->additionalhtmlfooter)) {
602 $output .= "\n".$CFG->additionalhtmlfooter;
604 $output .= $this->unique_end_html_token;
605 return $output;
609 * Return the standard string that says whether you are logged in (and switched
610 * roles/logged in as another user).
611 * @param bool $withlinks if false, then don't include any links in the HTML produced.
612 * If not set, the default is the nologinlinks option from the theme config.php file,
613 * and if that is not set, then links are included.
614 * @return string HTML fragment.
616 public function login_info($withlinks = null) {
617 global $USER, $CFG, $DB, $SESSION;
619 if (during_initial_install()) {
620 return '';
623 if (is_null($withlinks)) {
624 $withlinks = empty($this->page->layout_options['nologinlinks']);
627 $loginpage = ((string)$this->page->url === get_login_url());
628 $course = $this->page->course;
629 if (\core\session\manager::is_loggedinas()) {
630 $realuser = \core\session\manager::get_realuser();
631 $fullname = fullname($realuser, true);
632 if ($withlinks) {
633 $loginastitle = get_string('loginas');
634 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
635 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
636 } else {
637 $realuserinfo = " [$fullname] ";
639 } else {
640 $realuserinfo = '';
643 $loginurl = get_login_url();
645 if (empty($course->id)) {
646 // $course->id is not defined during installation
647 return '';
648 } else if (isloggedin()) {
649 $context = context_course::instance($course->id);
651 $fullname = fullname($USER, true);
652 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
653 if ($withlinks) {
654 $linktitle = get_string('viewprofile');
655 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
656 } else {
657 $username = $fullname;
659 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
660 if ($withlinks) {
661 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
662 } else {
663 $username .= " from {$idprovider->name}";
666 if (isguestuser()) {
667 $loggedinas = $realuserinfo.get_string('loggedinasguest');
668 if (!$loginpage && $withlinks) {
669 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
671 } else if (is_role_switched($course->id)) { // Has switched roles
672 $rolename = '';
673 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
674 $rolename = ': '.role_get_name($role, $context);
676 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
677 if ($withlinks) {
678 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
679 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
681 } else {
682 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
683 if ($withlinks) {
684 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
687 } else {
688 $loggedinas = get_string('loggedinnot', 'moodle');
689 if (!$loginpage && $withlinks) {
690 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
694 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
696 if (isset($SESSION->justloggedin)) {
697 unset($SESSION->justloggedin);
698 if (!empty($CFG->displayloginfailures)) {
699 if (!isguestuser()) {
700 // Include this file only when required.
701 require_once($CFG->dirroot . '/user/lib.php');
702 if ($count = user_count_login_failures($USER)) {
703 $loggedinas .= '<div class="loginfailures">';
704 $a = new stdClass();
705 $a->attempts = $count;
706 $loggedinas .= get_string('failedloginattempts', '', $a);
707 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
708 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
709 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
711 $loggedinas .= '</div>';
717 return $loggedinas;
721 * Return the 'back' link that normally appears in the footer.
723 * @return string HTML fragment.
725 public function home_link() {
726 global $CFG, $SITE;
728 if ($this->page->pagetype == 'site-index') {
729 // Special case for site home page - please do not remove
730 return '<div class="sitelink">' .
731 '<a title="Moodle" href="http://moodle.org/">' .
732 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
734 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
735 // Special case for during install/upgrade.
736 return '<div class="sitelink">'.
737 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
738 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
740 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
741 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
742 get_string('home') . '</a></div>';
744 } else {
745 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
746 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
751 * Redirects the user by any means possible given the current state
753 * This function should not be called directly, it should always be called using
754 * the redirect function in lib/weblib.php
756 * The redirect function should really only be called before page output has started
757 * however it will allow itself to be called during the state STATE_IN_BODY
759 * @param string $encodedurl The URL to send to encoded if required
760 * @param string $message The message to display to the user if any
761 * @param int $delay The delay before redirecting a user, if $message has been
762 * set this is a requirement and defaults to 3, set to 0 no delay
763 * @param boolean $debugdisableredirect this redirect has been disabled for
764 * debugging purposes. Display a message that explains, and don't
765 * trigger the redirect.
766 * @return string The HTML to display to the user before dying, may contain
767 * meta refresh, javascript refresh, and may have set header redirects
769 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
770 global $CFG;
771 $url = str_replace('&amp;', '&', $encodedurl);
773 switch ($this->page->state) {
774 case moodle_page::STATE_BEFORE_HEADER :
775 // No output yet it is safe to delivery the full arsenal of redirect methods
776 if (!$debugdisableredirect) {
777 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
778 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
779 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
781 $output = $this->header();
782 break;
783 case moodle_page::STATE_PRINTING_HEADER :
784 // We should hopefully never get here
785 throw new coding_exception('You cannot redirect while printing the page header');
786 break;
787 case moodle_page::STATE_IN_BODY :
788 // We really shouldn't be here but we can deal with this
789 debugging("You should really redirect before you start page output");
790 if (!$debugdisableredirect) {
791 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
793 $output = $this->opencontainers->pop_all_but_last();
794 break;
795 case moodle_page::STATE_DONE :
796 // Too late to be calling redirect now
797 throw new coding_exception('You cannot redirect after the entire page has been generated');
798 break;
800 $output .= $this->notification($message, 'redirectmessage');
801 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
802 if ($debugdisableredirect) {
803 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
805 $output .= $this->footer();
806 return $output;
810 * Start output by sending the HTTP headers, and printing the HTML <head>
811 * and the start of the <body>.
813 * To control what is printed, you should set properties on $PAGE. If you
814 * are familiar with the old {@link print_header()} function from Moodle 1.9
815 * you will find that there are properties on $PAGE that correspond to most
816 * of the old parameters to could be passed to print_header.
818 * Not that, in due course, the remaining $navigation, $menu parameters here
819 * will be replaced by more properties of $PAGE, but that is still to do.
821 * @return string HTML that you must output this, preferably immediately.
823 public function header() {
824 global $USER, $CFG;
826 if (\core\session\manager::is_loggedinas()) {
827 $this->page->add_body_class('userloggedinas');
830 // Give themes a chance to init/alter the page object.
831 $this->page->theme->init_page($this->page);
833 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
835 // Find the appropriate page layout file, based on $this->page->pagelayout.
836 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
837 // Render the layout using the layout file.
838 $rendered = $this->render_page_layout($layoutfile);
840 // Slice the rendered output into header and footer.
841 $cutpos = strpos($rendered, $this->unique_main_content_token);
842 if ($cutpos === false) {
843 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
844 $token = self::MAIN_CONTENT_TOKEN;
845 } else {
846 $token = $this->unique_main_content_token;
849 if ($cutpos === false) {
850 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
852 $header = substr($rendered, 0, $cutpos);
853 $footer = substr($rendered, $cutpos + strlen($token));
855 if (empty($this->contenttype)) {
856 debugging('The page layout file did not call $OUTPUT->doctype()');
857 $header = $this->doctype() . $header;
860 // If this theme version is below 2.4 release and this is a course view page
861 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
862 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
863 // check if course content header/footer have not been output during render of theme layout
864 $coursecontentheader = $this->course_content_header(true);
865 $coursecontentfooter = $this->course_content_footer(true);
866 if (!empty($coursecontentheader)) {
867 // display debug message and add header and footer right above and below main content
868 // Please note that course header and footer (to be displayed above and below the whole page)
869 // are not displayed in this case at all.
870 // Besides the content header and footer are not displayed on any other course page
871 debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
872 $header .= $coursecontentheader;
873 $footer = $coursecontentfooter. $footer;
877 send_headers($this->contenttype, $this->page->cacheable);
879 $this->opencontainers->push('header/footer', $footer);
880 $this->page->set_state(moodle_page::STATE_IN_BODY);
882 return $header . $this->skip_link_target('maincontent');
886 * Renders and outputs the page layout file.
888 * This is done by preparing the normal globals available to a script, and
889 * then including the layout file provided by the current theme for the
890 * requested layout.
892 * @param string $layoutfile The name of the layout file
893 * @return string HTML code
895 protected function render_page_layout($layoutfile) {
896 global $CFG, $SITE, $USER;
897 // The next lines are a bit tricky. The point is, here we are in a method
898 // of a renderer class, and this object may, or may not, be the same as
899 // the global $OUTPUT object. When rendering the page layout file, we want to use
900 // this object. However, people writing Moodle code expect the current
901 // renderer to be called $OUTPUT, not $this, so define a variable called
902 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
903 $OUTPUT = $this;
904 $PAGE = $this->page;
905 $COURSE = $this->page->course;
907 ob_start();
908 include($layoutfile);
909 $rendered = ob_get_contents();
910 ob_end_clean();
911 return $rendered;
915 * Outputs the page's footer
917 * @return string HTML fragment
919 public function footer() {
920 global $CFG, $DB;
922 $output = $this->container_end_all(true);
924 $footer = $this->opencontainers->pop('header/footer');
926 if (debugging() and $DB and $DB->is_transaction_started()) {
927 // TODO: MDL-20625 print warning - transaction will be rolled back
930 // Provide some performance info if required
931 $performanceinfo = '';
932 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
933 $perf = get_performance_info();
934 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
935 $performanceinfo = $perf['html'];
939 // We always want performance data when running a performance test, even if the user is redirected to another page.
940 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
941 $footer = $this->unique_performance_info_token . $footer;
943 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
945 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
947 $this->page->set_state(moodle_page::STATE_DONE);
949 return $output . $footer;
953 * Close all but the last open container. This is useful in places like error
954 * handling, where you want to close all the open containers (apart from <body>)
955 * before outputting the error message.
957 * @param bool $shouldbenone assert that the stack should be empty now - causes a
958 * developer debug warning if it isn't.
959 * @return string the HTML required to close any open containers inside <body>.
961 public function container_end_all($shouldbenone = false) {
962 return $this->opencontainers->pop_all_but_last($shouldbenone);
966 * Returns course-specific information to be output immediately above content on any course page
967 * (for the current course)
969 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
970 * @return string
972 public function course_content_header($onlyifnotcalledbefore = false) {
973 global $CFG;
974 if ($this->page->course->id == SITEID) {
975 // return immediately and do not include /course/lib.php if not necessary
976 return '';
978 static $functioncalled = false;
979 if ($functioncalled && $onlyifnotcalledbefore) {
980 // we have already output the content header
981 return '';
983 require_once($CFG->dirroot.'/course/lib.php');
984 $functioncalled = true;
985 $courseformat = course_get_format($this->page->course);
986 if (($obj = $courseformat->course_content_header()) !== null) {
987 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
989 return '';
993 * Returns course-specific information to be output immediately below content on any course page
994 * (for the current course)
996 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
997 * @return string
999 public function course_content_footer($onlyifnotcalledbefore = false) {
1000 global $CFG;
1001 if ($this->page->course->id == SITEID) {
1002 // return immediately and do not include /course/lib.php if not necessary
1003 return '';
1005 static $functioncalled = false;
1006 if ($functioncalled && $onlyifnotcalledbefore) {
1007 // we have already output the content footer
1008 return '';
1010 $functioncalled = true;
1011 require_once($CFG->dirroot.'/course/lib.php');
1012 $courseformat = course_get_format($this->page->course);
1013 if (($obj = $courseformat->course_content_footer()) !== null) {
1014 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1016 return '';
1020 * Returns course-specific information to be output on any course page in the header area
1021 * (for the current course)
1023 * @return string
1025 public function course_header() {
1026 global $CFG;
1027 if ($this->page->course->id == SITEID) {
1028 // return immediately and do not include /course/lib.php if not necessary
1029 return '';
1031 require_once($CFG->dirroot.'/course/lib.php');
1032 $courseformat = course_get_format($this->page->course);
1033 if (($obj = $courseformat->course_header()) !== null) {
1034 return $courseformat->get_renderer($this->page)->render($obj);
1036 return '';
1040 * Returns course-specific information to be output on any course page in the footer area
1041 * (for the current course)
1043 * @return string
1045 public function course_footer() {
1046 global $CFG;
1047 if ($this->page->course->id == SITEID) {
1048 // return immediately and do not include /course/lib.php if not necessary
1049 return '';
1051 require_once($CFG->dirroot.'/course/lib.php');
1052 $courseformat = course_get_format($this->page->course);
1053 if (($obj = $courseformat->course_footer()) !== null) {
1054 return $courseformat->get_renderer($this->page)->render($obj);
1056 return '';
1060 * Returns lang menu or '', this method also checks forcing of languages in courses.
1062 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1064 * @return string The lang menu HTML or empty string
1066 public function lang_menu() {
1067 global $CFG;
1069 if (empty($CFG->langmenu)) {
1070 return '';
1073 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1074 // do not show lang menu if language forced
1075 return '';
1078 $currlang = current_language();
1079 $langs = get_string_manager()->get_list_of_translations();
1081 if (count($langs) < 2) {
1082 return '';
1085 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1086 $s->label = get_accesshide(get_string('language'));
1087 $s->class = 'langmenu';
1088 return $this->render($s);
1092 * Output the row of editing icons for a block, as defined by the controls array.
1094 * @param array $controls an array like {@link block_contents::$controls}.
1095 * @param string $blockid The ID given to the block.
1096 * @return string HTML fragment.
1098 public function block_controls($actions, $blockid = null) {
1099 global $CFG;
1100 if (empty($actions)) {
1101 return '';
1103 $menu = new action_menu($actions);
1104 if ($blockid !== null) {
1105 $menu->set_owner_selector('#'.$blockid);
1107 $menu->set_constraint('.block-region');
1108 $menu->attributes['class'] .= ' block-control-actions commands';
1109 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1110 $menu->do_not_enhance();
1112 return $this->render($menu);
1116 * Renders an action menu component.
1118 * ARIA references:
1119 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1120 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1122 * @param action_menu $menu
1123 * @return string HTML
1125 public function render_action_menu(action_menu $menu) {
1126 $menu->initialise_js($this->page);
1128 $output = html_writer::start_tag('div', $menu->attributes);
1129 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1130 foreach ($menu->get_primary_actions($this) as $action) {
1131 if ($action instanceof renderable) {
1132 $content = $this->render($action);
1133 } else {
1134 $content = $action;
1136 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1138 $output .= html_writer::end_tag('ul');
1139 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1140 foreach ($menu->get_secondary_actions() as $action) {
1141 if ($action instanceof renderable) {
1142 $content = $this->render($action);
1143 } else {
1144 $content = $action;
1146 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1148 $output .= html_writer::end_tag('ul');
1149 $output .= html_writer::end_tag('div');
1150 return $output;
1154 * Renders an action_menu_link item.
1156 * @param action_menu_link $action
1157 * @return string HTML fragment
1159 protected function render_action_menu_link(action_menu_link $action) {
1160 static $actioncount = 0;
1161 $actioncount++;
1163 $comparetoalt = '';
1164 $text = '';
1165 if (!$action->icon || $action->primary === false) {
1166 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1167 if ($action->text instanceof renderable) {
1168 $text .= $this->render($action->text);
1169 } else {
1170 $text .= $action->text;
1171 $comparetoalt = (string)$action->text;
1173 $text .= html_writer::end_tag('span');
1176 $icon = '';
1177 if ($action->icon) {
1178 $icon = $action->icon;
1179 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1180 $action->attributes['title'] = $action->text;
1182 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1183 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1184 $icon->attributes['alt'] = '';
1186 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1187 unset($icon->attributes['title']);
1190 $icon = $this->render($icon);
1193 // A disabled link is rendered as formatted text.
1194 if (!empty($action->attributes['disabled'])) {
1195 // Do not use div here due to nesting restriction in xhtml strict.
1196 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1199 $attributes = $action->attributes;
1200 unset($action->attributes['disabled']);
1201 $attributes['href'] = $action->url;
1202 if ($text !== '') {
1203 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1206 return html_writer::tag('a', $icon.$text, $attributes);
1210 * Renders a primary action_menu_filler item.
1212 * @param action_menu_link_filler $action
1213 * @return string HTML fragment
1215 protected function render_action_menu_filler(action_menu_filler $action) {
1216 return html_writer::span('&nbsp;', 'filler');
1220 * Renders a primary action_menu_link item.
1222 * @param action_menu_link_primary $action
1223 * @return string HTML fragment
1225 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1226 return $this->render_action_menu_link($action);
1230 * Renders a secondary action_menu_link item.
1232 * @param action_menu_link_secondary $action
1233 * @return string HTML fragment
1235 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1236 return $this->render_action_menu_link($action);
1240 * Prints a nice side block with an optional header.
1242 * The content is described
1243 * by a {@link core_renderer::block_contents} object.
1245 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1246 * <div class="header"></div>
1247 * <div class="content">
1248 * ...CONTENT...
1249 * <div class="footer">
1250 * </div>
1251 * </div>
1252 * <div class="annotation">
1253 * </div>
1254 * </div>
1256 * @param block_contents $bc HTML for the content
1257 * @param string $region the region the block is appearing in.
1258 * @return string the HTML to be output.
1260 public function block(block_contents $bc, $region) {
1261 $bc = clone($bc); // Avoid messing up the object passed in.
1262 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1263 $bc->collapsible = block_contents::NOT_HIDEABLE;
1265 if (!empty($bc->blockinstanceid)) {
1266 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1268 $skiptitle = strip_tags($bc->title);
1269 if ($bc->blockinstanceid && !empty($skiptitle)) {
1270 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1271 } else if (!empty($bc->arialabel)) {
1272 $bc->attributes['aria-label'] = $bc->arialabel;
1274 if ($bc->dockable) {
1275 $bc->attributes['data-dockable'] = 1;
1277 if ($bc->collapsible == block_contents::HIDDEN) {
1278 $bc->add_class('hidden');
1280 if (!empty($bc->controls)) {
1281 $bc->add_class('block_with_controls');
1285 if (empty($skiptitle)) {
1286 $output = '';
1287 $skipdest = '';
1288 } else {
1289 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1290 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1293 $output .= html_writer::start_tag('div', $bc->attributes);
1295 $output .= $this->block_header($bc);
1296 $output .= $this->block_content($bc);
1298 $output .= html_writer::end_tag('div');
1300 $output .= $this->block_annotation($bc);
1302 $output .= $skipdest;
1304 $this->init_block_hider_js($bc);
1305 return $output;
1309 * Produces a header for a block
1311 * @param block_contents $bc
1312 * @return string
1314 protected function block_header(block_contents $bc) {
1316 $title = '';
1317 if ($bc->title) {
1318 $attributes = array();
1319 if ($bc->blockinstanceid) {
1320 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1322 $title = html_writer::tag('h2', $bc->title, $attributes);
1325 $blockid = null;
1326 if (isset($bc->attributes['id'])) {
1327 $blockid = $bc->attributes['id'];
1329 $controlshtml = $this->block_controls($bc->controls, $blockid);
1331 $output = '';
1332 if ($title || $controlshtml) {
1333 $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'));
1335 return $output;
1339 * Produces the content area for a block
1341 * @param block_contents $bc
1342 * @return string
1344 protected function block_content(block_contents $bc) {
1345 $output = html_writer::start_tag('div', array('class' => 'content'));
1346 if (!$bc->title && !$this->block_controls($bc->controls)) {
1347 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1349 $output .= $bc->content;
1350 $output .= $this->block_footer($bc);
1351 $output .= html_writer::end_tag('div');
1353 return $output;
1357 * Produces the footer for a block
1359 * @param block_contents $bc
1360 * @return string
1362 protected function block_footer(block_contents $bc) {
1363 $output = '';
1364 if ($bc->footer) {
1365 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1367 return $output;
1371 * Produces the annotation for a block
1373 * @param block_contents $bc
1374 * @return string
1376 protected function block_annotation(block_contents $bc) {
1377 $output = '';
1378 if ($bc->annotation) {
1379 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1381 return $output;
1385 * Calls the JS require function to hide a block.
1387 * @param block_contents $bc A block_contents object
1389 protected function init_block_hider_js(block_contents $bc) {
1390 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1391 $config = new stdClass;
1392 $config->id = $bc->attributes['id'];
1393 $config->title = strip_tags($bc->title);
1394 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1395 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1396 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1398 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1399 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1404 * Render the contents of a block_list.
1406 * @param array $icons the icon for each item.
1407 * @param array $items the content of each item.
1408 * @return string HTML
1410 public function list_block_contents($icons, $items) {
1411 $row = 0;
1412 $lis = array();
1413 foreach ($items as $key => $string) {
1414 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1415 if (!empty($icons[$key])) { //test if the content has an assigned icon
1416 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1418 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1419 $item .= html_writer::end_tag('li');
1420 $lis[] = $item;
1421 $row = 1 - $row; // Flip even/odd.
1423 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1427 * Output all the blocks in a particular region.
1429 * @param string $region the name of a region on this page.
1430 * @return string the HTML to be output.
1432 public function blocks_for_region($region) {
1433 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1434 $blocks = $this->page->blocks->get_blocks_for_region($region);
1435 $lastblock = null;
1436 $zones = array();
1437 foreach ($blocks as $block) {
1438 $zones[] = $block->title;
1440 $output = '';
1442 foreach ($blockcontents as $bc) {
1443 if ($bc instanceof block_contents) {
1444 $output .= $this->block($bc, $region);
1445 $lastblock = $bc->title;
1446 } else if ($bc instanceof block_move_target) {
1447 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1448 } else {
1449 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1452 return $output;
1456 * Output a place where the block that is currently being moved can be dropped.
1458 * @param block_move_target $target with the necessary details.
1459 * @param array $zones array of areas where the block can be moved to
1460 * @param string $previous the block located before the area currently being rendered.
1461 * @param string $region the name of the region
1462 * @return string the HTML to be output.
1464 public function block_move_target($target, $zones, $previous, $region) {
1465 if ($previous == null) {
1466 if (empty($zones)) {
1467 // There are no zones, probably because there are no blocks.
1468 $regions = $this->page->theme->get_all_block_regions();
1469 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1470 } else {
1471 $position = get_string('moveblockbefore', 'block', $zones[0]);
1473 } else {
1474 $position = get_string('moveblockafter', 'block', $previous);
1476 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1480 * Renders a special html link with attached action
1482 * Theme developers: DO NOT OVERRIDE! Please override function
1483 * {@link core_renderer::render_action_link()} instead.
1485 * @param string|moodle_url $url
1486 * @param string $text HTML fragment
1487 * @param component_action $action
1488 * @param array $attributes associative array of html link attributes + disabled
1489 * @param pix_icon optional pix icon to render with the link
1490 * @return string HTML fragment
1492 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1493 if (!($url instanceof moodle_url)) {
1494 $url = new moodle_url($url);
1496 $link = new action_link($url, $text, $action, $attributes, $icon);
1498 return $this->render($link);
1502 * Renders an action_link object.
1504 * The provided link is renderer and the HTML returned. At the same time the
1505 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1507 * @param action_link $link
1508 * @return string HTML fragment
1510 protected function render_action_link(action_link $link) {
1511 global $CFG;
1513 $text = '';
1514 if ($link->icon) {
1515 $text .= $this->render($link->icon);
1518 if ($link->text instanceof renderable) {
1519 $text .= $this->render($link->text);
1520 } else {
1521 $text .= $link->text;
1524 // A disabled link is rendered as formatted text
1525 if (!empty($link->attributes['disabled'])) {
1526 // do not use div here due to nesting restriction in xhtml strict
1527 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1530 $attributes = $link->attributes;
1531 unset($link->attributes['disabled']);
1532 $attributes['href'] = $link->url;
1534 if ($link->actions) {
1535 if (empty($attributes['id'])) {
1536 $id = html_writer::random_id('action_link');
1537 $attributes['id'] = $id;
1538 } else {
1539 $id = $attributes['id'];
1541 foreach ($link->actions as $action) {
1542 $this->add_action_handler($action, $id);
1546 return html_writer::tag('a', $text, $attributes);
1551 * Renders an action_icon.
1553 * This function uses the {@link core_renderer::action_link()} method for the
1554 * most part. What it does different is prepare the icon as HTML and use it
1555 * as the link text.
1557 * Theme developers: If you want to change how action links and/or icons are rendered,
1558 * consider overriding function {@link core_renderer::render_action_link()} and
1559 * {@link core_renderer::render_pix_icon()}.
1561 * @param string|moodle_url $url A string URL or moodel_url
1562 * @param pix_icon $pixicon
1563 * @param component_action $action
1564 * @param array $attributes associative array of html link attributes + disabled
1565 * @param bool $linktext show title next to image in link
1566 * @return string HTML fragment
1568 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1569 if (!($url instanceof moodle_url)) {
1570 $url = new moodle_url($url);
1572 $attributes = (array)$attributes;
1574 if (empty($attributes['class'])) {
1575 // let ppl override the class via $options
1576 $attributes['class'] = 'action-icon';
1579 $icon = $this->render($pixicon);
1581 if ($linktext) {
1582 $text = $pixicon->attributes['alt'];
1583 } else {
1584 $text = '';
1587 return $this->action_link($url, $text.$icon, $action, $attributes);
1591 * Print a message along with button choices for Continue/Cancel
1593 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1595 * @param string $message The question to ask the user
1596 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1597 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1598 * @return string HTML fragment
1600 public function confirm($message, $continue, $cancel) {
1601 if ($continue instanceof single_button) {
1602 // ok
1603 } else if (is_string($continue)) {
1604 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1605 } else if ($continue instanceof moodle_url) {
1606 $continue = new single_button($continue, get_string('continue'), 'post');
1607 } else {
1608 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1611 if ($cancel instanceof single_button) {
1612 // ok
1613 } else if (is_string($cancel)) {
1614 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1615 } else if ($cancel instanceof moodle_url) {
1616 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1617 } else {
1618 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1621 $output = $this->box_start('generalbox', 'notice');
1622 $output .= html_writer::tag('p', $message);
1623 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1624 $output .= $this->box_end();
1625 return $output;
1629 * Returns a form with a single button.
1631 * Theme developers: DO NOT OVERRIDE! Please override function
1632 * {@link core_renderer::render_single_button()} instead.
1634 * @param string|moodle_url $url
1635 * @param string $label button text
1636 * @param string $method get or post submit method
1637 * @param array $options associative array {disabled, title, etc.}
1638 * @return string HTML fragment
1640 public function single_button($url, $label, $method='post', array $options=null) {
1641 if (!($url instanceof moodle_url)) {
1642 $url = new moodle_url($url);
1644 $button = new single_button($url, $label, $method);
1646 foreach ((array)$options as $key=>$value) {
1647 if (array_key_exists($key, $button)) {
1648 $button->$key = $value;
1652 return $this->render($button);
1656 * Renders a single button widget.
1658 * This will return HTML to display a form containing a single button.
1660 * @param single_button $button
1661 * @return string HTML fragment
1663 protected function render_single_button(single_button $button) {
1664 $attributes = array('type' => 'submit',
1665 'value' => $button->label,
1666 'disabled' => $button->disabled ? 'disabled' : null,
1667 'title' => $button->tooltip);
1669 if ($button->actions) {
1670 $id = html_writer::random_id('single_button');
1671 $attributes['id'] = $id;
1672 foreach ($button->actions as $action) {
1673 $this->add_action_handler($action, $id);
1677 // first the input element
1678 $output = html_writer::empty_tag('input', $attributes);
1680 // then hidden fields
1681 $params = $button->url->params();
1682 if ($button->method === 'post') {
1683 $params['sesskey'] = sesskey();
1685 foreach ($params as $var => $val) {
1686 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1689 // then div wrapper for xhtml strictness
1690 $output = html_writer::tag('div', $output);
1692 // now the form itself around it
1693 if ($button->method === 'get') {
1694 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1695 } else {
1696 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1698 if ($url === '') {
1699 $url = '#'; // there has to be always some action
1701 $attributes = array('method' => $button->method,
1702 'action' => $url,
1703 'id' => $button->formid);
1704 $output = html_writer::tag('form', $output, $attributes);
1706 // and finally one more wrapper with class
1707 return html_writer::tag('div', $output, array('class' => $button->class));
1711 * Returns a form with a single select widget.
1713 * Theme developers: DO NOT OVERRIDE! Please override function
1714 * {@link core_renderer::render_single_select()} instead.
1716 * @param moodle_url $url form action target, includes hidden fields
1717 * @param string $name name of selection field - the changing parameter in url
1718 * @param array $options list of options
1719 * @param string $selected selected element
1720 * @param array $nothing
1721 * @param string $formid
1722 * @return string HTML fragment
1724 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1725 if (!($url instanceof moodle_url)) {
1726 $url = new moodle_url($url);
1728 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1730 return $this->render($select);
1734 * Internal implementation of single_select rendering
1736 * @param single_select $select
1737 * @return string HTML fragment
1739 protected function render_single_select(single_select $select) {
1740 $select = clone($select);
1741 if (empty($select->formid)) {
1742 $select->formid = html_writer::random_id('single_select_f');
1745 $output = '';
1746 $params = $select->url->params();
1747 if ($select->method === 'post') {
1748 $params['sesskey'] = sesskey();
1750 foreach ($params as $name=>$value) {
1751 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1754 if (empty($select->attributes['id'])) {
1755 $select->attributes['id'] = html_writer::random_id('single_select');
1758 if ($select->disabled) {
1759 $select->attributes['disabled'] = 'disabled';
1762 if ($select->tooltip) {
1763 $select->attributes['title'] = $select->tooltip;
1766 $select->attributes['class'] = 'autosubmit';
1767 if ($select->class) {
1768 $select->attributes['class'] .= ' ' . $select->class;
1771 if ($select->label) {
1772 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1775 if ($select->helpicon instanceof help_icon) {
1776 $output .= $this->render($select->helpicon);
1778 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1780 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1781 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1783 $nothing = empty($select->nothing) ? false : key($select->nothing);
1784 $this->page->requires->yui_module('moodle-core-formautosubmit',
1785 'M.core.init_formautosubmit',
1786 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1789 // then div wrapper for xhtml strictness
1790 $output = html_writer::tag('div', $output);
1792 // now the form itself around it
1793 if ($select->method === 'get') {
1794 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1795 } else {
1796 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1798 $formattributes = array('method' => $select->method,
1799 'action' => $url,
1800 'id' => $select->formid);
1801 $output = html_writer::tag('form', $output, $formattributes);
1803 // and finally one more wrapper with class
1804 return html_writer::tag('div', $output, array('class' => $select->class));
1808 * Returns a form with a url select widget.
1810 * Theme developers: DO NOT OVERRIDE! Please override function
1811 * {@link core_renderer::render_url_select()} instead.
1813 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1814 * @param string $selected selected element
1815 * @param array $nothing
1816 * @param string $formid
1817 * @return string HTML fragment
1819 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1820 $select = new url_select($urls, $selected, $nothing, $formid);
1821 return $this->render($select);
1825 * Internal implementation of url_select rendering
1827 * @param url_select $select
1828 * @return string HTML fragment
1830 protected function render_url_select(url_select $select) {
1831 global $CFG;
1833 $select = clone($select);
1834 if (empty($select->formid)) {
1835 $select->formid = html_writer::random_id('url_select_f');
1838 if (empty($select->attributes['id'])) {
1839 $select->attributes['id'] = html_writer::random_id('url_select');
1842 if ($select->disabled) {
1843 $select->attributes['disabled'] = 'disabled';
1846 if ($select->tooltip) {
1847 $select->attributes['title'] = $select->tooltip;
1850 $output = '';
1852 if ($select->label) {
1853 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1856 $classes = array();
1857 if (!$select->showbutton) {
1858 $classes[] = 'autosubmit';
1860 if ($select->class) {
1861 $classes[] = $select->class;
1863 if (count($classes)) {
1864 $select->attributes['class'] = implode(' ', $classes);
1867 if ($select->helpicon instanceof help_icon) {
1868 $output .= $this->render($select->helpicon);
1871 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1872 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1873 $urls = array();
1874 foreach ($select->urls as $k=>$v) {
1875 if (is_array($v)) {
1876 // optgroup structure
1877 foreach ($v as $optgrouptitle => $optgroupoptions) {
1878 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1879 if (empty($optionurl)) {
1880 $safeoptionurl = '';
1881 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1882 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1883 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1884 } else if (strpos($optionurl, '/') !== 0) {
1885 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1886 continue;
1887 } else {
1888 $safeoptionurl = $optionurl;
1890 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1893 } else {
1894 // plain list structure
1895 if (empty($k)) {
1896 // nothing selected option
1897 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1898 $k = str_replace($CFG->wwwroot, '', $k);
1899 } else if (strpos($k, '/') !== 0) {
1900 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1901 continue;
1903 $urls[$k] = $v;
1906 $selected = $select->selected;
1907 if (!empty($selected)) {
1908 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1909 $selected = str_replace($CFG->wwwroot, '', $selected);
1910 } else if (strpos($selected, '/') !== 0) {
1911 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1915 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1916 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1918 if (!$select->showbutton) {
1919 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1920 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1921 $nothing = empty($select->nothing) ? false : key($select->nothing);
1922 $this->page->requires->yui_module('moodle-core-formautosubmit',
1923 'M.core.init_formautosubmit',
1924 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1926 } else {
1927 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1930 // then div wrapper for xhtml strictness
1931 $output = html_writer::tag('div', $output);
1933 // now the form itself around it
1934 $formattributes = array('method' => 'post',
1935 'action' => new moodle_url('/course/jumpto.php'),
1936 'id' => $select->formid);
1937 $output = html_writer::tag('form', $output, $formattributes);
1939 // and finally one more wrapper with class
1940 return html_writer::tag('div', $output, array('class' => $select->class));
1944 * Returns a string containing a link to the user documentation.
1945 * Also contains an icon by default. Shown to teachers and admin only.
1947 * @param string $path The page link after doc root and language, no leading slash.
1948 * @param string $text The text to be displayed for the link
1949 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1950 * @return string
1952 public function doc_link($path, $text = '', $forcepopup = false) {
1953 global $CFG;
1955 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
1957 $url = new moodle_url(get_docs_url($path));
1959 $attributes = array('href'=>$url);
1960 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1961 $attributes['class'] = 'helplinkpopup';
1964 return html_writer::tag('a', $icon.$text, $attributes);
1968 * Return HTML for a pix_icon.
1970 * Theme developers: DO NOT OVERRIDE! Please override function
1971 * {@link core_renderer::render_pix_icon()} instead.
1973 * @param string $pix short pix name
1974 * @param string $alt mandatory alt attribute
1975 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1976 * @param array $attributes htm lattributes
1977 * @return string HTML fragment
1979 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1980 $icon = new pix_icon($pix, $alt, $component, $attributes);
1981 return $this->render($icon);
1985 * Renders a pix_icon widget and returns the HTML to display it.
1987 * @param pix_icon $icon
1988 * @return string HTML fragment
1990 protected function render_pix_icon(pix_icon $icon) {
1991 $attributes = $icon->attributes;
1992 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1993 return html_writer::empty_tag('img', $attributes);
1997 * Return HTML to display an emoticon icon.
1999 * @param pix_emoticon $emoticon
2000 * @return string HTML fragment
2002 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2003 $attributes = $emoticon->attributes;
2004 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2005 return html_writer::empty_tag('img', $attributes);
2009 * Produces the html that represents this rating in the UI
2011 * @param rating $rating the page object on which this rating will appear
2012 * @return string
2014 function render_rating(rating $rating) {
2015 global $CFG, $USER;
2017 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2018 return null;//ratings are turned off
2021 $ratingmanager = new rating_manager();
2022 // Initialise the JavaScript so ratings can be done by AJAX.
2023 $ratingmanager->initialise_rating_javascript($this->page);
2025 $strrate = get_string("rate", "rating");
2026 $ratinghtml = ''; //the string we'll return
2028 // permissions check - can they view the aggregate?
2029 if ($rating->user_can_view_aggregate()) {
2031 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2032 $aggregatestr = $rating->get_aggregate_string();
2034 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2035 if ($rating->count > 0) {
2036 $countstr = "({$rating->count})";
2037 } else {
2038 $countstr = '-';
2040 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2042 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2043 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2045 $nonpopuplink = $rating->get_view_ratings_url();
2046 $popuplink = $rating->get_view_ratings_url(true);
2048 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2049 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2050 } else {
2051 $ratinghtml .= $aggregatehtml;
2055 $formstart = null;
2056 // if the item doesn't belong to the current user, the user has permission to rate
2057 // and we're within the assessable period
2058 if ($rating->user_can_rate()) {
2060 $rateurl = $rating->get_rate_url();
2061 $inputs = $rateurl->params();
2063 //start the rating form
2064 $formattrs = array(
2065 'id' => "postrating{$rating->itemid}",
2066 'class' => 'postratingform',
2067 'method' => 'post',
2068 'action' => $rateurl->out_omit_querystring()
2070 $formstart = html_writer::start_tag('form', $formattrs);
2071 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2073 // add the hidden inputs
2074 foreach ($inputs as $name => $value) {
2075 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2076 $formstart .= html_writer::empty_tag('input', $attributes);
2079 if (empty($ratinghtml)) {
2080 $ratinghtml .= $strrate.': ';
2082 $ratinghtml = $formstart.$ratinghtml;
2084 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2085 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2086 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2087 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2089 //output submit button
2090 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2092 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2093 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2095 if (!$rating->settings->scale->isnumeric) {
2096 // If a global scale, try to find current course ID from the context
2097 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2098 $courseid = $coursecontext->instanceid;
2099 } else {
2100 $courseid = $rating->settings->scale->courseid;
2102 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2104 $ratinghtml .= html_writer::end_tag('span');
2105 $ratinghtml .= html_writer::end_tag('div');
2106 $ratinghtml .= html_writer::end_tag('form');
2109 return $ratinghtml;
2113 * Centered heading with attached help button (same title text)
2114 * and optional icon attached.
2116 * @param string $text A heading text
2117 * @param string $helpidentifier The keyword that defines a help page
2118 * @param string $component component name
2119 * @param string|moodle_url $icon
2120 * @param string $iconalt icon alt text
2121 * @param int $level The level of importance of the heading. Defaulting to 2
2122 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2123 * @return string HTML fragment
2125 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2126 $image = '';
2127 if ($icon) {
2128 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2131 $help = '';
2132 if ($helpidentifier) {
2133 $help = $this->help_icon($helpidentifier, $component);
2136 return $this->heading($image.$text.$help, $level, $classnames);
2140 * Returns HTML to display a help icon.
2142 * @deprecated since Moodle 2.0
2144 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2145 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2149 * Returns HTML to display a help icon.
2151 * Theme developers: DO NOT OVERRIDE! Please override function
2152 * {@link core_renderer::render_help_icon()} instead.
2154 * @param string $identifier The keyword that defines a help page
2155 * @param string $component component name
2156 * @param string|bool $linktext true means use $title as link text, string means link text value
2157 * @return string HTML fragment
2159 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2160 $icon = new help_icon($identifier, $component);
2161 $icon->diag_strings();
2162 if ($linktext === true) {
2163 $icon->linktext = get_string($icon->identifier, $icon->component);
2164 } else if (!empty($linktext)) {
2165 $icon->linktext = $linktext;
2167 return $this->render($icon);
2171 * Implementation of user image rendering.
2173 * @param help_icon $helpicon A help icon instance
2174 * @return string HTML fragment
2176 protected function render_help_icon(help_icon $helpicon) {
2177 global $CFG;
2179 // first get the help image icon
2180 $src = $this->pix_url('help');
2182 $title = get_string($helpicon->identifier, $helpicon->component);
2184 if (empty($helpicon->linktext)) {
2185 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2186 } else {
2187 $alt = get_string('helpwiththis');
2190 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2191 $output = html_writer::empty_tag('img', $attributes);
2193 // add the link text if given
2194 if (!empty($helpicon->linktext)) {
2195 // the spacing has to be done through CSS
2196 $output .= $helpicon->linktext;
2199 // now create the link around it - we need https on loginhttps pages
2200 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2202 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2203 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2205 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2206 $output = html_writer::tag('a', $output, $attributes);
2208 // and finally span
2209 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2213 * Returns HTML to display a scale help icon.
2215 * @param int $courseid
2216 * @param stdClass $scale instance
2217 * @return string HTML fragment
2219 public function help_icon_scale($courseid, stdClass $scale) {
2220 global $CFG;
2222 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2224 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2226 $scaleid = abs($scale->id);
2228 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2229 $action = new popup_action('click', $link, 'ratingscale');
2231 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2235 * Creates and returns a spacer image with optional line break.
2237 * @param array $attributes Any HTML attributes to add to the spaced.
2238 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2239 * laxy do it with CSS which is a much better solution.
2240 * @return string HTML fragment
2242 public function spacer(array $attributes = null, $br = false) {
2243 $attributes = (array)$attributes;
2244 if (empty($attributes['width'])) {
2245 $attributes['width'] = 1;
2247 if (empty($attributes['height'])) {
2248 $attributes['height'] = 1;
2250 $attributes['class'] = 'spacer';
2252 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2254 if (!empty($br)) {
2255 $output .= '<br />';
2258 return $output;
2262 * Returns HTML to display the specified user's avatar.
2264 * User avatar may be obtained in two ways:
2265 * <pre>
2266 * // Option 1: (shortcut for simple cases, preferred way)
2267 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2268 * $OUTPUT->user_picture($user, array('popup'=>true));
2270 * // Option 2:
2271 * $userpic = new user_picture($user);
2272 * // Set properties of $userpic
2273 * $userpic->popup = true;
2274 * $OUTPUT->render($userpic);
2275 * </pre>
2277 * Theme developers: DO NOT OVERRIDE! Please override function
2278 * {@link core_renderer::render_user_picture()} instead.
2280 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2281 * If any of these are missing, the database is queried. Avoid this
2282 * if at all possible, particularly for reports. It is very bad for performance.
2283 * @param array $options associative array with user picture options, used only if not a user_picture object,
2284 * options are:
2285 * - courseid=$this->page->course->id (course id of user profile in link)
2286 * - size=35 (size of image)
2287 * - link=true (make image clickable - the link leads to user profile)
2288 * - popup=false (open in popup)
2289 * - alttext=true (add image alt attribute)
2290 * - class = image class attribute (default 'userpicture')
2291 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2292 * @return string HTML fragment
2294 public function user_picture(stdClass $user, array $options = null) {
2295 $userpicture = new user_picture($user);
2296 foreach ((array)$options as $key=>$value) {
2297 if (array_key_exists($key, $userpicture)) {
2298 $userpicture->$key = $value;
2301 return $this->render($userpicture);
2305 * Internal implementation of user image rendering.
2307 * @param user_picture $userpicture
2308 * @return string
2310 protected function render_user_picture(user_picture $userpicture) {
2311 global $CFG, $DB;
2313 $user = $userpicture->user;
2315 if ($userpicture->alttext) {
2316 if (!empty($user->imagealt)) {
2317 $alt = $user->imagealt;
2318 } else {
2319 $alt = get_string('pictureof', '', fullname($user));
2321 } else {
2322 $alt = '';
2325 if (empty($userpicture->size)) {
2326 $size = 35;
2327 } else if ($userpicture->size === true or $userpicture->size == 1) {
2328 $size = 100;
2329 } else {
2330 $size = $userpicture->size;
2333 $class = $userpicture->class;
2335 if ($user->picture == 0) {
2336 $class .= ' defaultuserpic';
2339 $src = $userpicture->get_url($this->page, $this);
2341 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2342 if (!$userpicture->visibletoscreenreaders) {
2343 $attributes['role'] = 'presentation';
2346 // get the image html output fisrt
2347 $output = html_writer::empty_tag('img', $attributes);
2349 // then wrap it in link if needed
2350 if (!$userpicture->link) {
2351 return $output;
2354 if (empty($userpicture->courseid)) {
2355 $courseid = $this->page->course->id;
2356 } else {
2357 $courseid = $userpicture->courseid;
2360 if ($courseid == SITEID) {
2361 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2362 } else {
2363 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2366 $attributes = array('href'=>$url);
2367 if (!$userpicture->visibletoscreenreaders) {
2368 $attributes['role'] = 'presentation';
2369 $attributes['tabindex'] = '-1';
2370 $attributes['aria-hidden'] = 'true';
2373 if ($userpicture->popup) {
2374 $id = html_writer::random_id('userpicture');
2375 $attributes['id'] = $id;
2376 $this->add_action_handler(new popup_action('click', $url), $id);
2379 return html_writer::tag('a', $output, $attributes);
2383 * Internal implementation of file tree viewer items rendering.
2385 * @param array $dir
2386 * @return string
2388 public function htmllize_file_tree($dir) {
2389 if (empty($dir['subdirs']) and empty($dir['files'])) {
2390 return '';
2392 $result = '<ul>';
2393 foreach ($dir['subdirs'] as $subdir) {
2394 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2396 foreach ($dir['files'] as $file) {
2397 $filename = $file->get_filename();
2398 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2400 $result .= '</ul>';
2402 return $result;
2406 * Returns HTML to display the file picker
2408 * <pre>
2409 * $OUTPUT->file_picker($options);
2410 * </pre>
2412 * Theme developers: DO NOT OVERRIDE! Please override function
2413 * {@link core_renderer::render_file_picker()} instead.
2415 * @param array $options associative array with file manager options
2416 * options are:
2417 * maxbytes=>-1,
2418 * itemid=>0,
2419 * client_id=>uniqid(),
2420 * acepted_types=>'*',
2421 * return_types=>FILE_INTERNAL,
2422 * context=>$PAGE->context
2423 * @return string HTML fragment
2425 public function file_picker($options) {
2426 $fp = new file_picker($options);
2427 return $this->render($fp);
2431 * Internal implementation of file picker rendering.
2433 * @param file_picker $fp
2434 * @return string
2436 public function render_file_picker(file_picker $fp) {
2437 global $CFG, $OUTPUT, $USER;
2438 $options = $fp->options;
2439 $client_id = $options->client_id;
2440 $strsaved = get_string('filesaved', 'repository');
2441 $straddfile = get_string('openpicker', 'repository');
2442 $strloading = get_string('loading', 'repository');
2443 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2444 $strdroptoupload = get_string('droptoupload', 'moodle');
2445 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2447 $currentfile = $options->currentfile;
2448 if (empty($currentfile)) {
2449 $currentfile = '';
2450 } else {
2451 $currentfile .= ' - ';
2453 if ($options->maxbytes) {
2454 $size = $options->maxbytes;
2455 } else {
2456 $size = get_max_upload_file_size();
2458 if ($size == -1) {
2459 $maxsize = '';
2460 } else {
2461 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2463 if ($options->buttonname) {
2464 $buttonname = ' name="' . $options->buttonname . '"';
2465 } else {
2466 $buttonname = '';
2468 $html = <<<EOD
2469 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2470 $icon_progress
2471 </div>
2472 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2473 <div>
2474 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2475 <span> $maxsize </span>
2476 </div>
2477 EOD;
2478 if ($options->env != 'url') {
2479 $html .= <<<EOD
2480 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2481 <div class="filepicker-filename">
2482 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2483 <div class="dndupload-progressbars"></div>
2484 </div>
2485 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2486 </div>
2487 EOD;
2489 $html .= '</div>';
2490 return $html;
2494 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2496 * @param string $cmid the course_module id.
2497 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2498 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2500 public function update_module_button($cmid, $modulename) {
2501 global $CFG;
2502 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2503 $modulename = get_string('modulename', $modulename);
2504 $string = get_string('updatethis', '', $modulename);
2505 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2506 return $this->single_button($url, $string);
2507 } else {
2508 return '';
2513 * Returns HTML to display a "Turn editing on/off" button in a form.
2515 * @param moodle_url $url The URL + params to send through when clicking the button
2516 * @return string HTML the button
2518 public function edit_button(moodle_url $url) {
2520 $url->param('sesskey', sesskey());
2521 if ($this->page->user_is_editing()) {
2522 $url->param('edit', 'off');
2523 $editstring = get_string('turneditingoff');
2524 } else {
2525 $url->param('edit', 'on');
2526 $editstring = get_string('turneditingon');
2529 return $this->single_button($url, $editstring);
2533 * Returns HTML to display a simple button to close a window
2535 * @param string $text The lang string for the button's label (already output from get_string())
2536 * @return string html fragment
2538 public function close_window_button($text='') {
2539 if (empty($text)) {
2540 $text = get_string('closewindow');
2542 $button = new single_button(new moodle_url('#'), $text, 'get');
2543 $button->add_action(new component_action('click', 'close_window'));
2545 return $this->container($this->render($button), 'closewindow');
2549 * Output an error message. By default wraps the error message in <span class="error">.
2550 * If the error message is blank, nothing is output.
2552 * @param string $message the error message.
2553 * @return string the HTML to output.
2555 public function error_text($message) {
2556 if (empty($message)) {
2557 return '';
2559 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2560 return html_writer::tag('span', $message, array('class' => 'error'));
2564 * Do not call this function directly.
2566 * To terminate the current script with a fatal error, call the {@link print_error}
2567 * function, or throw an exception. Doing either of those things will then call this
2568 * function to display the error, before terminating the execution.
2570 * @param string $message The message to output
2571 * @param string $moreinfourl URL where more info can be found about the error
2572 * @param string $link Link for the Continue button
2573 * @param array $backtrace The execution backtrace
2574 * @param string $debuginfo Debugging information
2575 * @return string the HTML to output.
2577 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2578 global $CFG;
2580 $output = '';
2581 $obbuffer = '';
2583 if ($this->has_started()) {
2584 // we can not always recover properly here, we have problems with output buffering,
2585 // html tables, etc.
2586 $output .= $this->opencontainers->pop_all_but_last();
2588 } else {
2589 // It is really bad if library code throws exception when output buffering is on,
2590 // because the buffered text would be printed before our start of page.
2591 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2592 error_reporting(0); // disable notices from gzip compression, etc.
2593 while (ob_get_level() > 0) {
2594 $buff = ob_get_clean();
2595 if ($buff === false) {
2596 break;
2598 $obbuffer .= $buff;
2600 error_reporting($CFG->debug);
2602 // Output not yet started.
2603 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2604 if (empty($_SERVER['HTTP_RANGE'])) {
2605 @header($protocol . ' 404 Not Found');
2606 } else {
2607 // Must stop byteserving attempts somehow,
2608 // this is weird but Chrome PDF viewer can be stopped only with 407!
2609 @header($protocol . ' 407 Proxy Authentication Required');
2612 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2613 $this->page->set_url('/'); // no url
2614 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2615 $this->page->set_title(get_string('error'));
2616 $this->page->set_heading($this->page->course->fullname);
2617 $output .= $this->header();
2620 $message = '<p class="errormessage">' . $message . '</p>'.
2621 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2622 get_string('moreinformation') . '</a></p>';
2623 if (empty($CFG->rolesactive)) {
2624 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2625 //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation.
2627 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2629 if ($CFG->debugdeveloper) {
2630 if (!empty($debuginfo)) {
2631 $debuginfo = s($debuginfo); // removes all nasty JS
2632 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2633 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2635 if (!empty($backtrace)) {
2636 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2638 if ($obbuffer !== '' ) {
2639 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2643 if (empty($CFG->rolesactive)) {
2644 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2645 } else if (!empty($link)) {
2646 $output .= $this->continue_button($link);
2649 $output .= $this->footer();
2651 // Padding to encourage IE to display our error page, rather than its own.
2652 $output .= str_repeat(' ', 512);
2654 return $output;
2658 * Output a notification (that is, a status message about something that has
2659 * just happened).
2661 * @param string $message the message to print out
2662 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2663 * @return string the HTML to output.
2665 public function notification($message, $classes = 'notifyproblem') {
2666 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2670 * Returns HTML to display a continue button that goes to a particular URL.
2672 * @param string|moodle_url $url The url the button goes to.
2673 * @return string the HTML to output.
2675 public function continue_button($url) {
2676 if (!($url instanceof moodle_url)) {
2677 $url = new moodle_url($url);
2679 $button = new single_button($url, get_string('continue'), 'get');
2680 $button->class = 'continuebutton';
2682 return $this->render($button);
2686 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2688 * Theme developers: DO NOT OVERRIDE! Please override function
2689 * {@link core_renderer::render_paging_bar()} instead.
2691 * @param int $totalcount The total number of entries available to be paged through
2692 * @param int $page The page you are currently viewing
2693 * @param int $perpage The number of entries that should be shown per page
2694 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2695 * @param string $pagevar name of page parameter that holds the page number
2696 * @return string the HTML to output.
2698 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2699 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2700 return $this->render($pb);
2704 * Internal implementation of paging bar rendering.
2706 * @param paging_bar $pagingbar
2707 * @return string
2709 protected function render_paging_bar(paging_bar $pagingbar) {
2710 $output = '';
2711 $pagingbar = clone($pagingbar);
2712 $pagingbar->prepare($this, $this->page, $this->target);
2714 if ($pagingbar->totalcount > $pagingbar->perpage) {
2715 $output .= get_string('page') . ':';
2717 if (!empty($pagingbar->previouslink)) {
2718 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2721 if (!empty($pagingbar->firstlink)) {
2722 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2725 foreach ($pagingbar->pagelinks as $link) {
2726 $output .= "&#160;&#160;$link";
2729 if (!empty($pagingbar->lastlink)) {
2730 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2733 if (!empty($pagingbar->nextlink)) {
2734 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2738 return html_writer::tag('div', $output, array('class' => 'paging'));
2742 * Output the place a skip link goes to.
2744 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2745 * @return string the HTML to output.
2747 public function skip_link_target($id = null) {
2748 return html_writer::tag('span', '', array('id' => $id));
2752 * Outputs a heading
2754 * @param string $text The text of the heading
2755 * @param int $level The level of importance of the heading. Defaulting to 2
2756 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2757 * @param string $id An optional ID
2758 * @return string the HTML to output.
2760 public function heading($text, $level = 2, $classes = null, $id = null) {
2761 $level = (integer) $level;
2762 if ($level < 1 or $level > 6) {
2763 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2765 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2769 * Outputs a box.
2771 * @param string $contents The contents of the box
2772 * @param string $classes A space-separated list of CSS classes
2773 * @param string $id An optional ID
2774 * @param array $attributes An array of other attributes to give the box.
2775 * @return string the HTML to output.
2777 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2778 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2782 * Outputs the opening section of a box.
2784 * @param string $classes A space-separated list of CSS classes
2785 * @param string $id An optional ID
2786 * @param array $attributes An array of other attributes to give the box.
2787 * @return string the HTML to output.
2789 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2790 $this->opencontainers->push('box', html_writer::end_tag('div'));
2791 $attributes['id'] = $id;
2792 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2793 return html_writer::start_tag('div', $attributes);
2797 * Outputs the closing section of a box.
2799 * @return string the HTML to output.
2801 public function box_end() {
2802 return $this->opencontainers->pop('box');
2806 * Outputs a container.
2808 * @param string $contents The contents of the box
2809 * @param string $classes A space-separated list of CSS classes
2810 * @param string $id An optional ID
2811 * @return string the HTML to output.
2813 public function container($contents, $classes = null, $id = null) {
2814 return $this->container_start($classes, $id) . $contents . $this->container_end();
2818 * Outputs the opening section of a container.
2820 * @param string $classes A space-separated list of CSS classes
2821 * @param string $id An optional ID
2822 * @return string the HTML to output.
2824 public function container_start($classes = null, $id = null) {
2825 $this->opencontainers->push('container', html_writer::end_tag('div'));
2826 return html_writer::start_tag('div', array('id' => $id,
2827 'class' => renderer_base::prepare_classes($classes)));
2831 * Outputs the closing section of a container.
2833 * @return string the HTML to output.
2835 public function container_end() {
2836 return $this->opencontainers->pop('container');
2840 * Make nested HTML lists out of the items
2842 * The resulting list will look something like this:
2844 * <pre>
2845 * <<ul>>
2846 * <<li>><div class='tree_item parent'>(item contents)</div>
2847 * <<ul>
2848 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2849 * <</ul>>
2850 * <</li>>
2851 * <</ul>>
2852 * </pre>
2854 * @param array $items
2855 * @param array $attrs html attributes passed to the top ofs the list
2856 * @return string HTML
2858 public function tree_block_contents($items, $attrs = array()) {
2859 // exit if empty, we don't want an empty ul element
2860 if (empty($items)) {
2861 return '';
2863 // array of nested li elements
2864 $lis = array();
2865 foreach ($items as $item) {
2866 // this applies to the li item which contains all child lists too
2867 $content = $item->content($this);
2868 $liclasses = array($item->get_css_type());
2869 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2870 $liclasses[] = 'collapsed';
2872 if ($item->isactive === true) {
2873 $liclasses[] = 'current_branch';
2875 $liattr = array('class'=>join(' ',$liclasses));
2876 // class attribute on the div item which only contains the item content
2877 $divclasses = array('tree_item');
2878 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2879 $divclasses[] = 'branch';
2880 } else {
2881 $divclasses[] = 'leaf';
2883 if (!empty($item->classes) && count($item->classes)>0) {
2884 $divclasses[] = join(' ', $item->classes);
2886 $divattr = array('class'=>join(' ', $divclasses));
2887 if (!empty($item->id)) {
2888 $divattr['id'] = $item->id;
2890 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2891 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2892 $content = html_writer::empty_tag('hr') . $content;
2894 $content = html_writer::tag('li', $content, $liattr);
2895 $lis[] = $content;
2897 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2901 * Construct a user menu, returning HTML that can be echoed out by a
2902 * layout file.
2904 * @param stdClass $user A user object, usually $USER.
2905 * @param bool $withlinks true if a dropdown should be built.
2906 * @return string HTML fragment.
2908 public function user_menu($user = null, $withlinks = null) {
2909 global $USER, $CFG;
2911 if (is_null($user)) {
2912 $user = $USER;
2915 // Note: this behaviour is intended to match that of core_renderer::login_info,
2916 // but should not be considered to be good practice; layout options are
2917 // intended to be theme-specific. Please don't copy this snippet anywhere else.
2918 if (is_null($withlinks)) {
2919 $withlinks = empty($this->page->layout_options['nologinlinks']);
2922 $returnstr = "";
2924 // If during initial install, return the empty return string.
2925 if (during_initial_install()) {
2926 return $returnstr;
2929 // If not logged in, show the typical not-logged-in string.
2930 if (!isloggedin()) {
2931 $returnstr = get_string('loggedinnot', 'moodle');
2932 $loginpage = ((string)$this->page->url === get_login_url());
2933 if (!$loginpage) {
2934 $loginurl = get_login_url();
2935 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
2937 return html_writer::tag(
2938 'span',
2939 $returnstr
2943 // Get some navigation opts.
2944 require_once($CFG->dirroot . '/user/lib.php');
2945 $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
2947 $avatarclasses = "avatars";
2948 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
2949 $usertextcontents = $opts->metadata['userfullname'];
2951 // Other user.
2952 if ($opts->metadata['asotheruser']) {
2953 $avatarcontents .= html_writer::span(
2954 $opts->metadata['realuseravatar'],
2955 'avatar realuser'
2957 $usertextcontents = $opts->metadata['realuserfullname'];
2958 $usertextcontents .= html_writer::tag(
2959 'span',
2960 get_string(
2961 'loggedinas',
2962 'moodle',
2963 html_writer::span(
2964 $opts->metadata['userfullname'],
2965 'value'
2968 array('class' => 'meta viewingas')
2972 // Role.
2973 if ($opts->metadata['asotherrole']) {
2974 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
2975 $usertextcontents .= html_writer::span(
2976 get_string(
2977 'roleviewas',
2978 'moodle',
2979 html_writer::span(
2980 $opts->metadata['rolename'],
2981 'value'
2984 'meta role role-' . $role
2988 // MNet.
2989 if ($opts->metadata['asmnetuser']) {
2990 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
2991 $usertextcontents .= html_writer::span(
2992 get_string(
2993 'loggedinfrom',
2994 'moodle',
2995 html_writer::span(
2996 $opts->metadata['mnetidprovidername'],
2997 'value'
3000 'meta mnet mnet-' . $mnet
3004 $returnstr .= html_writer::span(
3005 html_writer::span($avatarcontents, $avatarclasses) . html_writer::span($usertextcontents, 'usertext'),
3006 'userbutton'
3009 $am = new action_menu();
3010 $am->initialise_js($this->page);
3011 $am->set_menu_trigger($returnstr);
3012 $am->set_alignment(action_menu::TR, action_menu::BR);
3013 if ($withlinks) {
3014 foreach ($opts->navitems as $key => $value) {
3015 $al = new action_menu_link_secondary(
3016 $value->url,
3017 new pix_icon($value->pix, $value->title, null),
3018 $value->title,
3019 array('class' => 'icon')
3021 $am->add($al);
3025 return html_writer::div(
3026 $this->render($am),
3027 'usermenu'
3032 * Return the navbar content so that it can be echoed out by the layout
3034 * @return string XHTML navbar
3036 public function navbar() {
3037 $items = $this->page->navbar->get_items();
3038 $itemcount = count($items);
3039 if ($itemcount === 0) {
3040 return '';
3043 $htmlblocks = array();
3044 // Iterate the navarray and display each node
3045 $separator = get_separator();
3046 for ($i=0;$i < $itemcount;$i++) {
3047 $item = $items[$i];
3048 $item->hideicon = true;
3049 if ($i===0) {
3050 $content = html_writer::tag('li', $this->render($item));
3051 } else {
3052 $content = html_writer::tag('li', $separator.$this->render($item));
3054 $htmlblocks[] = $content;
3057 //accessibility: heading for navbar list (MDL-20446)
3058 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
3059 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
3060 // XHTML
3061 return $navbarcontent;
3065 * Renders a navigation node object.
3067 * @param navigation_node $item The navigation node to render.
3068 * @return string HTML fragment
3070 protected function render_navigation_node(navigation_node $item) {
3071 $content = $item->get_content();
3072 $title = $item->get_title();
3073 if ($item->icon instanceof renderable && !$item->hideicon) {
3074 $icon = $this->render($item->icon);
3075 $content = $icon.$content; // use CSS for spacing of icons
3077 if ($item->helpbutton !== null) {
3078 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3080 if ($content === '') {
3081 return '';
3083 if ($item->action instanceof action_link) {
3084 $link = $item->action;
3085 if ($item->hidden) {
3086 $link->add_class('dimmed');
3088 if (!empty($content)) {
3089 // Providing there is content we will use that for the link content.
3090 $link->text = $content;
3092 $content = $this->render($link);
3093 } else if ($item->action instanceof moodle_url) {
3094 $attributes = array();
3095 if ($title !== '') {
3096 $attributes['title'] = $title;
3098 if ($item->hidden) {
3099 $attributes['class'] = 'dimmed_text';
3101 $content = html_writer::link($item->action, $content, $attributes);
3103 } else if (is_string($item->action) || empty($item->action)) {
3104 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3105 if ($title !== '') {
3106 $attributes['title'] = $title;
3108 if ($item->hidden) {
3109 $attributes['class'] = 'dimmed_text';
3111 $content = html_writer::tag('span', $content, $attributes);
3113 return $content;
3117 * Accessibility: Right arrow-like character is
3118 * used in the breadcrumb trail, course navigation menu
3119 * (previous/next activity), calendar, and search forum block.
3120 * If the theme does not set characters, appropriate defaults
3121 * are set automatically. Please DO NOT
3122 * use &lt; &gt; &raquo; - these are confusing for blind users.
3124 * @return string
3126 public function rarrow() {
3127 return $this->page->theme->rarrow;
3131 * Accessibility: Right arrow-like character is
3132 * used in the breadcrumb trail, course navigation menu
3133 * (previous/next activity), calendar, and search forum block.
3134 * If the theme does not set characters, appropriate defaults
3135 * are set automatically. Please DO NOT
3136 * use &lt; &gt; &raquo; - these are confusing for blind users.
3138 * @return string
3140 public function larrow() {
3141 return $this->page->theme->larrow;
3145 * Returns the custom menu if one has been set
3147 * A custom menu can be configured by browsing to
3148 * Settings: Administration > Appearance > Themes > Theme settings
3149 * and then configuring the custommenu config setting as described.
3151 * Theme developers: DO NOT OVERRIDE! Please override function
3152 * {@link core_renderer::render_custom_menu()} instead.
3154 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3155 * @return string
3157 public function custom_menu($custommenuitems = '') {
3158 global $CFG;
3159 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3160 $custommenuitems = $CFG->custommenuitems;
3162 if (empty($custommenuitems)) {
3163 return '';
3165 $custommenu = new custom_menu($custommenuitems, current_language());
3166 return $this->render($custommenu);
3170 * Renders a custom menu object (located in outputcomponents.php)
3172 * The custom menu this method produces makes use of the YUI3 menunav widget
3173 * and requires very specific html elements and classes.
3175 * @staticvar int $menucount
3176 * @param custom_menu $menu
3177 * @return string
3179 protected function render_custom_menu(custom_menu $menu) {
3180 static $menucount = 0;
3181 // If the menu has no children return an empty string
3182 if (!$menu->has_children()) {
3183 return '';
3185 // Increment the menu count. This is used for ID's that get worked with
3186 // in JavaScript as is essential
3187 $menucount++;
3188 // Initialise this custom menu (the custom menu object is contained in javascript-static
3189 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3190 $jscode = "(function(){{$jscode}})";
3191 $this->page->requires->yui_module('node-menunav', $jscode);
3192 // Build the root nodes as required by YUI
3193 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3194 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3195 $content .= html_writer::start_tag('ul');
3196 // Render each child
3197 foreach ($menu->get_children() as $item) {
3198 $content .= $this->render_custom_menu_item($item);
3200 // Close the open tags
3201 $content .= html_writer::end_tag('ul');
3202 $content .= html_writer::end_tag('div');
3203 $content .= html_writer::end_tag('div');
3204 // Return the custom menu
3205 return $content;
3209 * Renders a custom menu node as part of a submenu
3211 * The custom menu this method produces makes use of the YUI3 menunav widget
3212 * and requires very specific html elements and classes.
3214 * @see core:renderer::render_custom_menu()
3216 * @staticvar int $submenucount
3217 * @param custom_menu_item $menunode
3218 * @return string
3220 protected function render_custom_menu_item(custom_menu_item $menunode) {
3221 // Required to ensure we get unique trackable id's
3222 static $submenucount = 0;
3223 if ($menunode->has_children()) {
3224 // If the child has menus render it as a sub menu
3225 $submenucount++;
3226 $content = html_writer::start_tag('li');
3227 if ($menunode->get_url() !== null) {
3228 $url = $menunode->get_url();
3229 } else {
3230 $url = '#cm_submenu_'.$submenucount;
3232 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3233 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3234 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3235 $content .= html_writer::start_tag('ul');
3236 foreach ($menunode->get_children() as $menunode) {
3237 $content .= $this->render_custom_menu_item($menunode);
3239 $content .= html_writer::end_tag('ul');
3240 $content .= html_writer::end_tag('div');
3241 $content .= html_writer::end_tag('div');
3242 $content .= html_writer::end_tag('li');
3243 } else {
3244 // The node doesn't have children so produce a final menuitem.
3245 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3246 $content = '';
3247 if (preg_match("/^#+$/", $menunode->get_text())) {
3249 // This is a divider.
3250 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3251 } else {
3252 $content = html_writer::start_tag(
3253 'li',
3254 array(
3255 'class' => 'yui3-menuitem'
3258 if ($menunode->get_url() !== null) {
3259 $url = $menunode->get_url();
3260 } else {
3261 $url = '#';
3263 $content .= html_writer::link(
3264 $url,
3265 $menunode->get_text(),
3266 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3269 $content .= html_writer::end_tag('li');
3271 // Return the sub menu
3272 return $content;
3276 * Renders theme links for switching between default and other themes.
3278 * @return string
3280 protected function theme_switch_links() {
3282 $actualdevice = core_useragent::get_device_type();
3283 $currentdevice = $this->page->devicetypeinuse;
3284 $switched = ($actualdevice != $currentdevice);
3286 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3287 // The user is using the a default device and hasn't switched so don't shown the switch
3288 // device links.
3289 return '';
3292 if ($switched) {
3293 $linktext = get_string('switchdevicerecommended');
3294 $devicetype = $actualdevice;
3295 } else {
3296 $linktext = get_string('switchdevicedefault');
3297 $devicetype = 'default';
3299 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3301 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3302 $content .= html_writer::link($linkurl, $linktext);
3303 $content .= html_writer::end_tag('div');
3305 return $content;
3309 * Renders tabs
3311 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3313 * Theme developers: In order to change how tabs are displayed please override functions
3314 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3316 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3317 * @param string|null $selected which tab to mark as selected, all parent tabs will
3318 * automatically be marked as activated
3319 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3320 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3321 * @return string
3323 public final function tabtree($tabs, $selected = null, $inactive = null) {
3324 return $this->render(new tabtree($tabs, $selected, $inactive));
3328 * Renders tabtree
3330 * @param tabtree $tabtree
3331 * @return string
3333 protected function render_tabtree(tabtree $tabtree) {
3334 if (empty($tabtree->subtree)) {
3335 return '';
3337 $str = '';
3338 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3339 $str .= $this->render_tabobject($tabtree);
3340 $str .= html_writer::end_tag('div').
3341 html_writer::tag('div', ' ', array('class' => 'clearer'));
3342 return $str;
3346 * Renders tabobject (part of tabtree)
3348 * This function is called from {@link core_renderer::render_tabtree()}
3349 * and also it calls itself when printing the $tabobject subtree recursively.
3351 * Property $tabobject->level indicates the number of row of tabs.
3353 * @param tabobject $tabobject
3354 * @return string HTML fragment
3356 protected function render_tabobject(tabobject $tabobject) {
3357 $str = '';
3359 // Print name of the current tab.
3360 if ($tabobject instanceof tabtree) {
3361 // No name for tabtree root.
3362 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3363 // Tab name without a link. The <a> tag is used for styling.
3364 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3365 } else {
3366 // Tab name with a link.
3367 if (!($tabobject->link instanceof moodle_url)) {
3368 // backward compartibility when link was passed as quoted string
3369 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3370 } else {
3371 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3375 if (empty($tabobject->subtree)) {
3376 if ($tabobject->selected) {
3377 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3379 return $str;
3382 // Print subtree
3383 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3384 $cnt = 0;
3385 foreach ($tabobject->subtree as $tab) {
3386 $liclass = '';
3387 if (!$cnt) {
3388 $liclass .= ' first';
3390 if ($cnt == count($tabobject->subtree) - 1) {
3391 $liclass .= ' last';
3393 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3394 $liclass .= ' onerow';
3397 if ($tab->selected) {
3398 $liclass .= ' here selected';
3399 } else if ($tab->activated) {
3400 $liclass .= ' here active';
3403 // This will recursively call function render_tabobject() for each item in subtree
3404 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3405 $cnt++;
3407 $str .= html_writer::end_tag('ul');
3409 return $str;
3413 * Get the HTML for blocks in the given region.
3415 * @since Moodle 2.5.1 2.6
3416 * @param string $region The region to get HTML for.
3417 * @return string HTML.
3419 public function blocks($region, $classes = array(), $tag = 'aside') {
3420 $displayregion = $this->page->apply_theme_region_manipulations($region);
3421 $classes = (array)$classes;
3422 $classes[] = 'block-region';
3423 $attributes = array(
3424 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3425 'class' => join(' ', $classes),
3426 'data-blockregion' => $displayregion,
3427 'data-droptarget' => '1'
3429 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3430 $content = $this->blocks_for_region($displayregion);
3431 } else {
3432 $content = '';
3434 return html_writer::tag($tag, $content, $attributes);
3438 * Renders a custom block region.
3440 * Use this method if you want to add an additional block region to the content of the page.
3441 * Please note this should only be used in special situations.
3442 * We want to leave the theme is control where ever possible!
3444 * This method must use the same method that the theme uses within its layout file.
3445 * As such it asks the theme what method it is using.
3446 * It can be one of two values, blocks or blocks_for_region (deprecated).
3448 * @param string $regionname The name of the custom region to add.
3449 * @return string HTML for the block region.
3451 public function custom_block_region($regionname) {
3452 if ($this->page->theme->get_block_render_method() === 'blocks') {
3453 return $this->blocks($regionname);
3454 } else {
3455 return $this->blocks_for_region($regionname);
3460 * Returns the CSS classes to apply to the body tag.
3462 * @since Moodle 2.5.1 2.6
3463 * @param array $additionalclasses Any additional classes to apply.
3464 * @return string
3466 public function body_css_classes(array $additionalclasses = array()) {
3467 // Add a class for each block region on the page.
3468 // We use the block manager here because the theme object makes get_string calls.
3469 foreach ($this->page->blocks->get_regions() as $region) {
3470 $additionalclasses[] = 'has-region-'.$region;
3471 if ($this->page->blocks->region_has_content($region, $this)) {
3472 $additionalclasses[] = 'used-region-'.$region;
3473 } else {
3474 $additionalclasses[] = 'empty-region-'.$region;
3476 if ($this->page->blocks->region_completely_docked($region, $this)) {
3477 $additionalclasses[] = 'docked-region-'.$region;
3480 foreach ($this->page->layout_options as $option => $value) {
3481 if ($value) {
3482 $additionalclasses[] = 'layout-option-'.$option;
3485 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3486 return $css;
3490 * The ID attribute to apply to the body tag.
3492 * @since Moodle 2.5.1 2.6
3493 * @return string
3495 public function body_id() {
3496 return $this->page->bodyid;
3500 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3502 * @since Moodle 2.5.1 2.6
3503 * @param string|array $additionalclasses Any additional classes to give the body tag,
3504 * @return string
3506 public function body_attributes($additionalclasses = array()) {
3507 if (!is_array($additionalclasses)) {
3508 $additionalclasses = explode(' ', $additionalclasses);
3510 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3514 * Gets HTML for the page heading.
3516 * @since Moodle 2.5.1 2.6
3517 * @param string $tag The tag to encase the heading in. h1 by default.
3518 * @return string HTML.
3520 public function page_heading($tag = 'h1') {
3521 return html_writer::tag($tag, $this->page->heading);
3525 * Gets the HTML for the page heading button.
3527 * @since Moodle 2.5.1 2.6
3528 * @return string HTML.
3530 public function page_heading_button() {
3531 return $this->page->button;
3535 * Returns the Moodle docs link to use for this page.
3537 * @since Moodle 2.5.1 2.6
3538 * @param string $text
3539 * @return string
3541 public function page_doc_link($text = null) {
3542 if ($text === null) {
3543 $text = get_string('moodledocslink');
3545 $path = page_get_doc_link_path($this->page);
3546 if (!$path) {
3547 return '';
3549 return $this->doc_link($path, $text);
3553 * Returns the page heading menu.
3555 * @since Moodle 2.5.1 2.6
3556 * @return string HTML.
3558 public function page_heading_menu() {
3559 return $this->page->headingmenu;
3563 * Returns the title to use on the page.
3565 * @since Moodle 2.5.1 2.6
3566 * @return string
3568 public function page_title() {
3569 return $this->page->title;
3573 * Returns the URL for the favicon.
3575 * @since Moodle 2.5.1 2.6
3576 * @return string The favicon URL
3578 public function favicon() {
3579 return $this->pix_url('favicon', 'theme');
3584 * A renderer that generates output for command-line scripts.
3586 * The implementation of this renderer is probably incomplete.
3588 * @copyright 2009 Tim Hunt
3589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3590 * @since Moodle 2.0
3591 * @package core
3592 * @category output
3594 class core_renderer_cli extends core_renderer {
3597 * Returns the page header.
3599 * @return string HTML fragment
3601 public function header() {
3602 return $this->page->heading . "\n";
3606 * Returns a template fragment representing a Heading.
3608 * @param string $text The text of the heading
3609 * @param int $level The level of importance of the heading
3610 * @param string $classes A space-separated list of CSS classes
3611 * @param string $id An optional ID
3612 * @return string A template fragment for a heading
3614 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3615 $text .= "\n";
3616 switch ($level) {
3617 case 1:
3618 return '=>' . $text;
3619 case 2:
3620 return '-->' . $text;
3621 default:
3622 return $text;
3627 * Returns a template fragment representing a fatal error.
3629 * @param string $message The message to output
3630 * @param string $moreinfourl URL where more info can be found about the error
3631 * @param string $link Link for the Continue button
3632 * @param array $backtrace The execution backtrace
3633 * @param string $debuginfo Debugging information
3634 * @return string A template fragment for a fatal error
3636 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3637 global $CFG;
3639 $output = "!!! $message !!!\n";
3641 if ($CFG->debugdeveloper) {
3642 if (!empty($debuginfo)) {
3643 $output .= $this->notification($debuginfo, 'notifytiny');
3645 if (!empty($backtrace)) {
3646 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3650 return $output;
3654 * Returns a template fragment representing a notification.
3656 * @param string $message The message to include
3657 * @param string $classes A space-separated list of CSS classes
3658 * @return string A template fragment for a notification
3660 public function notification($message, $classes = 'notifyproblem') {
3661 $message = clean_text($message);
3662 if ($classes === 'notifysuccess') {
3663 return "++ $message ++\n";
3665 return "!! $message !!\n";
3671 * A renderer that generates output for ajax scripts.
3673 * This renderer prevents accidental sends back only json
3674 * encoded error messages, all other output is ignored.
3676 * @copyright 2010 Petr Skoda
3677 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3678 * @since Moodle 2.0
3679 * @package core
3680 * @category output
3682 class core_renderer_ajax extends core_renderer {
3685 * Returns a template fragment representing a fatal error.
3687 * @param string $message The message to output
3688 * @param string $moreinfourl URL where more info can be found about the error
3689 * @param string $link Link for the Continue button
3690 * @param array $backtrace The execution backtrace
3691 * @param string $debuginfo Debugging information
3692 * @return string A template fragment for a fatal error
3694 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3695 global $CFG;
3697 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3699 $e = new stdClass();
3700 $e->error = $message;
3701 $e->stacktrace = NULL;
3702 $e->debuginfo = NULL;
3703 $e->reproductionlink = NULL;
3704 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3705 $link = (string) $link;
3706 if ($link) {
3707 $e->reproductionlink = $link;
3709 if (!empty($debuginfo)) {
3710 $e->debuginfo = $debuginfo;
3712 if (!empty($backtrace)) {
3713 $e->stacktrace = format_backtrace($backtrace, true);
3716 $this->header();
3717 return json_encode($e);
3721 * Used to display a notification.
3722 * For the AJAX notifications are discarded.
3724 * @param string $message
3725 * @param string $classes
3727 public function notification($message, $classes = 'notifyproblem') {}
3730 * Used to display a redirection message.
3731 * AJAX redirections should not occur and as such redirection messages
3732 * are discarded.
3734 * @param moodle_url|string $encodedurl
3735 * @param string $message
3736 * @param int $delay
3737 * @param bool $debugdisableredirect
3739 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3742 * Prepares the start of an AJAX output.
3744 public function header() {
3745 // unfortunately YUI iframe upload does not support application/json
3746 if (!empty($_FILES)) {
3747 @header('Content-type: text/plain; charset=utf-8');
3748 if (!core_useragent::supports_json_contenttype()) {
3749 @header('X-Content-Type-Options: nosniff');
3751 } else if (!core_useragent::supports_json_contenttype()) {
3752 @header('Content-type: text/plain; charset=utf-8');
3753 @header('X-Content-Type-Options: nosniff');
3754 } else {
3755 @header('Content-type: application/json; charset=utf-8');
3758 // Headers to make it not cacheable and json
3759 @header('Cache-Control: no-store, no-cache, must-revalidate');
3760 @header('Cache-Control: post-check=0, pre-check=0', false);
3761 @header('Pragma: no-cache');
3762 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3763 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3764 @header('Accept-Ranges: none');
3768 * There is no footer for an AJAX request, however we must override the
3769 * footer method to prevent the default footer.
3771 public function footer() {}
3774 * No need for headers in an AJAX request... this should never happen.
3775 * @param string $text
3776 * @param int $level
3777 * @param string $classes
3778 * @param string $id
3780 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3785 * Renderer for media files.
3787 * Used in file resources, media filter, and any other places that need to
3788 * output embedded media.
3790 * @copyright 2011 The Open University
3791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3793 class core_media_renderer extends plugin_renderer_base {
3794 /** @var array Array of available 'player' objects */
3795 private $players;
3796 /** @var string Regex pattern for links which may contain embeddable content */
3797 private $embeddablemarkers;
3800 * Constructor requires medialib.php.
3802 * This is needed in the constructor (not later) so that you can use the
3803 * constants and static functions that are defined in core_media class
3804 * before you call renderer functions.
3806 public function __construct() {
3807 global $CFG;
3808 require_once($CFG->libdir . '/medialib.php');
3812 * Obtains the list of core_media_player objects currently in use to render
3813 * items.
3815 * The list is in rank order (highest first) and does not include players
3816 * which are disabled.
3818 * @return array Array of core_media_player objects in rank order
3820 protected function get_players() {
3821 global $CFG;
3823 // Save time by only building the list once.
3824 if (!$this->players) {
3825 // Get raw list of players.
3826 $players = $this->get_players_raw();
3828 // Chuck all the ones that are disabled.
3829 foreach ($players as $key => $player) {
3830 if (!$player->is_enabled()) {
3831 unset($players[$key]);
3835 // Sort in rank order (highest first).
3836 usort($players, array('core_media_player', 'compare_by_rank'));
3837 $this->players = $players;
3839 return $this->players;
3843 * Obtains a raw list of player objects that includes objects regardless
3844 * of whether they are disabled or not, and without sorting.
3846 * You can override this in a subclass if you need to add additional
3847 * players.
3849 * The return array is be indexed by player name to make it easier to
3850 * remove players in a subclass.
3852 * @return array $players Array of core_media_player objects in any order
3854 protected function get_players_raw() {
3855 return array(
3856 'vimeo' => new core_media_player_vimeo(),
3857 'youtube' => new core_media_player_youtube(),
3858 'youtube_playlist' => new core_media_player_youtube_playlist(),
3859 'html5video' => new core_media_player_html5video(),
3860 'html5audio' => new core_media_player_html5audio(),
3861 'mp3' => new core_media_player_mp3(),
3862 'flv' => new core_media_player_flv(),
3863 'wmp' => new core_media_player_wmp(),
3864 'qt' => new core_media_player_qt(),
3865 'rm' => new core_media_player_rm(),
3866 'swf' => new core_media_player_swf(),
3867 'link' => new core_media_player_link(),
3872 * Renders a media file (audio or video) using suitable embedded player.
3874 * See embed_alternatives function for full description of parameters.
3875 * This function calls through to that one.
3877 * When using this function you can also specify width and height in the
3878 * URL by including ?d=100x100 at the end. If specified in the URL, this
3879 * will override the $width and $height parameters.
3881 * @param moodle_url $url Full URL of media file
3882 * @param string $name Optional user-readable name to display in download link
3883 * @param int $width Width in pixels (optional)
3884 * @param int $height Height in pixels (optional)
3885 * @param array $options Array of key/value pairs
3886 * @return string HTML content of embed
3888 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3889 $options = array()) {
3891 // Get width and height from URL if specified (overrides parameters in
3892 // function call).
3893 $rawurl = $url->out(false);
3894 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3895 $width = $matches[1];
3896 $height = $matches[2];
3897 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3900 // Defer to array version of function.
3901 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3905 * Renders media files (audio or video) using suitable embedded player.
3906 * The list of URLs should be alternative versions of the same content in
3907 * multiple formats. If there is only one format it should have a single
3908 * entry.
3910 * If the media files are not in a supported format, this will give students
3911 * a download link to each format. The download link uses the filename
3912 * unless you supply the optional name parameter.
3914 * Width and height are optional. If specified, these are suggested sizes
3915 * and should be the exact values supplied by the user, if they come from
3916 * user input. These will be treated as relating to the size of the video
3917 * content, not including any player control bar.
3919 * For audio files, height will be ignored. For video files, a few formats
3920 * work if you specify only width, but in general if you specify width
3921 * you must specify height as well.
3923 * The $options array is passed through to the core_media_player classes
3924 * that render the object tag. The keys can contain values from
3925 * core_media::OPTION_xx.
3927 * @param array $alternatives Array of moodle_url to media files
3928 * @param string $name Optional user-readable name to display in download link
3929 * @param int $width Width in pixels (optional)
3930 * @param int $height Height in pixels (optional)
3931 * @param array $options Array of key/value pairs
3932 * @return string HTML content of embed
3934 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3935 $options = array()) {
3937 // Get list of player plugins (will also require the library).
3938 $players = $this->get_players();
3940 // Set up initial text which will be replaced by first player that
3941 // supports any of the formats.
3942 $out = core_media_player::PLACEHOLDER;
3944 // Loop through all players that support any of these URLs.
3945 foreach ($players as $player) {
3946 // Option: When no other player matched, don't do the default link player.
3947 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3948 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3949 continue;
3952 $supported = $player->list_supported_urls($alternatives, $options);
3953 if ($supported) {
3954 // Embed.
3955 $text = $player->embed($supported, $name, $width, $height, $options);
3957 // Put this in place of the 'fallback' slot in the previous text.
3958 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3962 // Remove 'fallback' slot from final version and return it.
3963 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3964 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3965 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3967 return $out;
3971 * Checks whether a file can be embedded. If this returns true you will get
3972 * an embedded player; if this returns false, you will just get a download
3973 * link.
3975 * This is a wrapper for can_embed_urls.
3977 * @param moodle_url $url URL of media file
3978 * @param array $options Options (same as when embedding)
3979 * @return bool True if file can be embedded
3981 public function can_embed_url(moodle_url $url, $options = array()) {
3982 return $this->can_embed_urls(array($url), $options);
3986 * Checks whether a file can be embedded. If this returns true you will get
3987 * an embedded player; if this returns false, you will just get a download
3988 * link.
3990 * @param array $urls URL of media file and any alternatives (moodle_url)
3991 * @param array $options Options (same as when embedding)
3992 * @return bool True if file can be embedded
3994 public function can_embed_urls(array $urls, $options = array()) {
3995 // Check all players to see if any of them support it.
3996 foreach ($this->get_players() as $player) {
3997 // Link player (always last on list) doesn't count!
3998 if ($player->get_rank() <= 0) {
3999 break;
4001 // First player that supports it, return true.
4002 if ($player->list_supported_urls($urls, $options)) {
4003 return true;
4006 return false;
4010 * Obtains a list of markers that can be used in a regular expression when
4011 * searching for URLs that can be embedded by any player type.
4013 * This string is used to improve peformance of regex matching by ensuring
4014 * that the (presumably C) regex code can do a quick keyword check on the
4015 * URL part of a link to see if it matches one of these, rather than having
4016 * to go into PHP code for every single link to see if it can be embedded.
4018 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4020 public function get_embeddable_markers() {
4021 if (empty($this->embeddablemarkers)) {
4022 $markers = '';
4023 foreach ($this->get_players() as $player) {
4024 foreach ($player->get_embeddable_markers() as $marker) {
4025 if ($markers !== '') {
4026 $markers .= '|';
4028 $markers .= preg_quote($marker);
4031 $this->embeddablemarkers = $markers;
4033 return $this->embeddablemarkers;
4038 * The maintenance renderer.
4040 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4041 * is running a maintenance related task.
4042 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4044 * @since Moodle 2.6
4045 * @package core
4046 * @category output
4047 * @copyright 2013 Sam Hemelryk
4048 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4050 class core_renderer_maintenance extends core_renderer {
4053 * Initialises the renderer instance.
4054 * @param moodle_page $page
4055 * @param string $target
4056 * @throws coding_exception
4058 public function __construct(moodle_page $page, $target) {
4059 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4060 throw new coding_exception('Invalid request for the maintenance renderer.');
4062 parent::__construct($page, $target);
4066 * Does nothing. The maintenance renderer cannot produce blocks.
4068 * @param block_contents $bc
4069 * @param string $region
4070 * @return string
4072 public function block(block_contents $bc, $region) {
4073 // Computer says no blocks.
4074 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4075 return '';
4079 * Does nothing. The maintenance renderer cannot produce blocks.
4081 * @param string $region
4082 * @param array $classes
4083 * @param string $tag
4084 * @return string
4086 public function blocks($region, $classes = array(), $tag = 'aside') {
4087 // Computer says no blocks.
4088 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4089 return '';
4093 * Does nothing. The maintenance renderer cannot produce blocks.
4095 * @param string $region
4096 * @return string
4098 public function blocks_for_region($region) {
4099 // Computer says no blocks for region.
4100 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4101 return '';
4105 * Does nothing. The maintenance renderer cannot produce a course content header.
4107 * @param bool $onlyifnotcalledbefore
4108 * @return string
4110 public function course_content_header($onlyifnotcalledbefore = false) {
4111 // Computer says no course content header.
4112 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4113 return '';
4117 * Does nothing. The maintenance renderer cannot produce a course content footer.
4119 * @param bool $onlyifnotcalledbefore
4120 * @return string
4122 public function course_content_footer($onlyifnotcalledbefore = false) {
4123 // Computer says no course content footer.
4124 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4125 return '';
4129 * Does nothing. The maintenance renderer cannot produce a course header.
4131 * @return string
4133 public function course_header() {
4134 // Computer says no course header.
4135 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4136 return '';
4140 * Does nothing. The maintenance renderer cannot produce a course footer.
4142 * @return string
4144 public function course_footer() {
4145 // Computer says no course footer.
4146 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4147 return '';
4151 * Does nothing. The maintenance renderer cannot produce a custom menu.
4153 * @param string $custommenuitems
4154 * @return string
4156 public function custom_menu($custommenuitems = '') {
4157 // Computer says no custom menu.
4158 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4159 return '';
4163 * Does nothing. The maintenance renderer cannot produce a file picker.
4165 * @param array $options
4166 * @return string
4168 public function file_picker($options) {
4169 // Computer says no file picker.
4170 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4171 return '';
4175 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4177 * @param array $dir
4178 * @return string
4180 public function htmllize_file_tree($dir) {
4181 // Hell no we don't want no htmllized file tree.
4182 // Also why on earth is this function on the core renderer???
4183 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4184 return '';
4189 * Does nothing. The maintenance renderer does not support JS.
4191 * @param block_contents $bc
4193 public function init_block_hider_js(block_contents $bc) {
4194 // Computer says no JavaScript.
4195 // Do nothing, ridiculous method.
4199 * Does nothing. The maintenance renderer cannot produce language menus.
4201 * @return string
4203 public function lang_menu() {
4204 // Computer says no lang menu.
4205 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4206 return '';
4210 * Does nothing. The maintenance renderer has no need for login information.
4212 * @param null $withlinks
4213 * @return string
4215 public function login_info($withlinks = null) {
4216 // Computer says no login info.
4217 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4218 return '';
4222 * Does nothing. The maintenance renderer cannot produce user pictures.
4224 * @param stdClass $user
4225 * @param array $options
4226 * @return string
4228 public function user_picture(stdClass $user, array $options = null) {
4229 // Computer says no user pictures.
4230 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4231 return '';