2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
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
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
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
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 * @var string The requested rendering target.
70 * @var Mustache_Engine $mustache The mustache template compiler
75 * Return an instance of the mustache class.
78 * @return Mustache_Engine
80 protected function get_mustache() {
83 if ($this->mustache === null) {
84 require_once($CFG->dirroot . '/lib/mustache/src/Mustache/Autoloader.php');
85 Mustache_Autoloader::register();
87 $themename = $this->page->theme->name;
88 $themerev = theme_get_revision();
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 $loader = new \core\output\mustache_filesystem_loader();
93 $stringhelper = new \core\output\mustache_string_helper();
94 $quotehelper = new \core\output\mustache_quote_helper();
95 $jshelper = new \core\output\mustache_javascript_helper($this->page->requires);
96 $pixhelper = new \core\output\mustache_pix_helper($this);
98 // We only expose the variables that are exposed to JS templates.
99 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
101 $helpers = array('config' => $safeconfig,
102 'str' => array($stringhelper, 'str'),
103 'quote' => array($quotehelper, 'quote'),
104 'js' => array($jshelper, 'help'),
105 'pix' => array($pixhelper, 'pix'));
107 $this->mustache = new Mustache_Engine(array(
108 'cache' => $cachedir,
111 'helpers' => $helpers,
112 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
116 return $this->mustache;
123 * The constructor takes two arguments. The first is the page that the renderer
124 * has been created to assist with, and the second is the target.
125 * The target is an additional identifier that can be used to load different
126 * renderers for different options.
128 * @param moodle_page $page the page we are doing output for.
129 * @param string $target one of rendering target constants
131 public function __construct(moodle_page $page, $target) {
132 $this->opencontainers = $page->opencontainers;
134 $this->target = $target;
138 * Renders a template by name with the given context.
140 * The provided data needs to be array/stdClass made up of only simple types.
141 * Simple types are array,stdClass,bool,int,float,string
144 * @param array|stdClass $context Context containing data for the template.
145 * @return string|boolean
147 public function render_from_template($templatename, $context) {
148 static $templatecache = array();
149 $mustache = $this->get_mustache();
151 // Provide 1 random value that will not change within a template
152 // but will be different from template to template. This is useful for
153 // e.g. aria attributes that only work with id attributes and must be
155 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
156 if (isset($templatecache[$templatename])) {
157 $template = $templatecache[$templatename];
160 $template = $mustache->loadTemplate($templatename);
161 $templatecache[$templatename] = $template;
162 } catch (Mustache_Exception_UnknownTemplateException $e) {
163 throw new moodle_exception('Unknown template: ' . $templatename);
166 return trim($template->render($context));
171 * Returns rendered widget.
173 * The provided widget needs to be an object that extends the renderable
175 * If will then be rendered by a method based upon the classname for the widget.
176 * For instance a widget of class `crazywidget` will be rendered by a protected
177 * render_crazywidget method of this renderer.
179 * @param renderable $widget instance with renderable interface
182 public function render(renderable $widget) {
183 $classname = get_class($widget);
185 $classname = preg_replace('/^.*\\\/', '', $classname);
186 // Remove _renderable suffixes
187 $classname = preg_replace('/_renderable$/', '', $classname);
189 $rendermethod = 'render_'.$classname;
190 if (method_exists($this, $rendermethod)) {
191 return $this->$rendermethod($widget);
193 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
197 * Adds a JS action for the element with the provided id.
199 * This method adds a JS event for the provided component action to the page
200 * and then returns the id that the event has been attached to.
201 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
203 * @param component_action $action
205 * @return string id of element, either original submitted or random new if not supplied
207 public function add_action_handler(component_action $action, $id = null) {
209 $id = html_writer::random_id($action->event);
211 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
216 * Returns true is output has already started, and false if not.
218 * @return boolean true if the header has been printed.
220 public function has_started() {
221 return $this->page->state >= moodle_page::STATE_IN_BODY;
225 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
227 * @param mixed $classes Space-separated string or array of classes
228 * @return string HTML class attribute value
230 public static function prepare_classes($classes) {
231 if (is_array($classes)) {
232 return implode(' ', array_unique($classes));
238 * Return the moodle_url for an image.
240 * The exact image location and extension is determined
241 * automatically by searching for gif|png|jpg|jpeg, please
242 * note there can not be diferent images with the different
243 * extension. The imagename is for historical reasons
244 * a relative path name, it may be changed later for core
245 * images. It is recommended to not use subdirectories
246 * in plugin and theme pix directories.
248 * There are three types of images:
249 * 1/ theme images - stored in theme/mytheme/pix/,
250 * use component 'theme'
251 * 2/ core images - stored in /pix/,
252 * overridden via theme/mytheme/pix_core/
253 * 3/ plugin images - stored in mod/mymodule/pix,
254 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
255 * example: pix_url('comment', 'mod_glossary')
257 * @param string $imagename the pathname of the image
258 * @param string $component full plugin name (aka component) or 'theme'
261 public function pix_url($imagename, $component = 'moodle') {
262 return $this->page->theme->pix_url($imagename, $component);
268 * Basis for all plugin renderers.
270 * @copyright Petr Skoda (skodak)
271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
276 class plugin_renderer_base extends renderer_base {
279 * @var renderer_base|core_renderer A reference to the current renderer.
280 * The renderer provided here will be determined by the page but will in 90%
281 * of cases by the {@link core_renderer}
286 * Constructor method, calls the parent constructor
288 * @param moodle_page $page
289 * @param string $target one of rendering target constants
291 public function __construct(moodle_page $page, $target) {
292 if (empty($target) && $page->pagelayout === 'maintenance') {
293 // If the page is using the maintenance layout then we're going to force the target to maintenance.
294 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
295 // unavailable for this page layout.
296 $target = RENDERER_TARGET_MAINTENANCE;
298 $this->output = $page->get_renderer('core', null, $target);
299 parent::__construct($page, $target);
303 * Renders the provided widget and returns the HTML to display it.
305 * @param renderable $widget instance with renderable interface
308 public function render(renderable $widget) {
309 $classname = get_class($widget);
311 $classname = preg_replace('/^.*\\\/', '', $classname);
312 // Keep a copy at this point, we may need to look for a deprecated method.
313 $deprecatedmethod = 'render_'.$classname;
314 // Remove _renderable suffixes
315 $classname = preg_replace('/_renderable$/', '', $classname);
317 $rendermethod = 'render_'.$classname;
318 if (method_exists($this, $rendermethod)) {
319 return $this->$rendermethod($widget);
321 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
322 // This is exactly where we don't want to be.
323 // If you have arrived here you have a renderable component within your plugin that has the name
324 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
325 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
326 // and the _renderable suffix now gets removed when looking for a render method.
327 // You need to change your renderers render_blah_renderable to render_blah.
328 // Until you do this it will not be possible for a theme to override the renderer to override your method.
329 // Please do it ASAP.
330 static $debugged = array();
331 if (!isset($debugged[$deprecatedmethod])) {
332 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
333 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
334 $debugged[$deprecatedmethod] = true;
336 return $this->$deprecatedmethod($widget);
338 // pass to core renderer if method not found here
339 return $this->output->render($widget);
343 * Magic method used to pass calls otherwise meant for the standard renderer
344 * to it to ensure we don't go causing unnecessary grief.
346 * @param string $method
347 * @param array $arguments
350 public function __call($method, $arguments) {
351 if (method_exists('renderer_base', $method)) {
352 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
354 if (method_exists($this->output, $method)) {
355 return call_user_func_array(array($this->output, $method), $arguments);
357 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
364 * The standard implementation of the core_renderer interface.
366 * @copyright 2009 Tim Hunt
367 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
372 class core_renderer extends renderer_base {
374 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
375 * in layout files instead.
377 * @var string used in {@link core_renderer::header()}.
379 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
382 * @var string Used to pass information from {@link core_renderer::doctype()} to
383 * {@link core_renderer::standard_head_html()}.
385 protected $contenttype;
388 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
389 * with {@link core_renderer::header()}.
391 protected $metarefreshtag = '';
394 * @var string Unique token for the closing HTML
396 protected $unique_end_html_token;
399 * @var string Unique token for performance information
401 protected $unique_performance_info_token;
404 * @var string Unique token for the main content.
406 protected $unique_main_content_token;
411 * @param moodle_page $page the page we are doing output for.
412 * @param string $target one of rendering target constants
414 public function __construct(moodle_page $page, $target) {
415 $this->opencontainers = $page->opencontainers;
417 $this->target = $target;
419 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
420 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
421 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
425 * Get the DOCTYPE declaration that should be used with this page. Designed to
426 * be called in theme layout.php files.
428 * @return string the DOCTYPE declaration that should be used.
430 public function doctype() {
431 if ($this->page->theme->doctype === 'html5') {
432 $this->contenttype = 'text/html; charset=utf-8';
433 return "<!DOCTYPE html>\n";
435 } else if ($this->page->theme->doctype === 'xhtml5') {
436 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
437 return "<!DOCTYPE html>\n";
441 $this->contenttype = 'text/html; charset=utf-8';
442 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
447 * The attributes that should be added to the <html> tag. Designed to
448 * be called in theme layout.php files.
450 * @return string HTML fragment.
452 public function htmlattributes() {
453 $return = get_html_lang(true);
454 if ($this->page->theme->doctype !== 'html5') {
455 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
461 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
462 * that should be included in the <head> tag. Designed to be called in theme
465 * @return string HTML fragment.
467 public function standard_head_html() {
468 global $CFG, $SESSION;
470 // Before we output any content, we need to ensure that certain
471 // page components are set up.
473 // Blocks must be set up early as they may require javascript which
474 // has to be included in the page header before output is created.
475 foreach ($this->page->blocks->get_regions() as $region) {
476 $this->page->blocks->ensure_content_created($region, $this);
481 // Allow a url_rewrite plugin to setup any dynamic head content.
482 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
483 $class = $CFG->urlrewriteclass;
484 $output .= $class::html_head_setup();
487 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
488 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
489 // This is only set by the {@link redirect()} method
490 $output .= $this->metarefreshtag;
492 // Check if a periodic refresh delay has been set and make sure we arn't
493 // already meta refreshing
494 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
495 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
498 // flow player embedding support
499 $this->page->requires->js_function_call('M.util.load_flowplayer');
501 // Set up help link popups for all links with the helptooltip class
502 $this->page->requires->js_init_call('M.util.help_popups.setup');
504 // Setup help icon overlays.
505 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
506 $this->page->requires->strings_for_js(array(
511 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
513 $focus = $this->page->focuscontrol;
514 if (!empty($focus)) {
515 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
516 // This is a horrifically bad way to handle focus but it is passed in
517 // through messy formslib::moodleform
518 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
519 } else if (strpos($focus, '.')!==false) {
520 // Old style of focus, bad way to do it
521 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);
522 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
524 // Focus element with given id
525 $this->page->requires->js_function_call('focuscontrol', array($focus));
529 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
530 // any other custom CSS can not be overridden via themes and is highly discouraged
531 $urls = $this->page->theme->css_urls($this->page);
532 foreach ($urls as $url) {
533 $this->page->requires->css_theme($url);
536 // Get the theme javascript head and footer
537 if ($jsurl = $this->page->theme->javascript_url(true)) {
538 $this->page->requires->js($jsurl, true);
540 if ($jsurl = $this->page->theme->javascript_url(false)) {
541 $this->page->requires->js($jsurl);
544 // Get any HTML from the page_requirements_manager.
545 $output .= $this->page->requires->get_head_code($this->page, $this);
547 // List alternate versions.
548 foreach ($this->page->alternateversions as $type => $alt) {
549 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
550 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
553 if (!empty($CFG->additionalhtmlhead)) {
554 $output .= "\n".$CFG->additionalhtmlhead;
561 * The standard tags (typically skip links) that should be output just inside
562 * the start of the <body> tag. Designed to be called in theme layout.php files.
564 * @return string HTML fragment.
566 public function standard_top_of_body_html() {
568 $output = $this->page->requires->get_top_of_body_code();
569 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
570 $output .= "\n".$CFG->additionalhtmltopofbody;
572 $output .= $this->maintenance_warning();
577 * Scheduled maintenance warning message.
579 * Note: This is a nasty hack to display maintenance notice, this should be moved
580 * to some general notification area once we have it.
584 public function maintenance_warning() {
588 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
589 $timeleft = $CFG->maintenance_later - time();
590 // If timeleft less than 30 sec, set the class on block to error to highlight.
591 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
592 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
594 $a->min = (int)($timeleft/60);
595 $a->sec = (int)($timeleft % 60);
596 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
597 $output .= $this->box_end();
598 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
599 array(array('timeleftinsec' => $timeleft)));
600 $this->page->requires->strings_for_js(
601 array('maintenancemodeisscheduled', 'sitemaintenance'),
608 * The standard tags (typically performance information and validation links,
609 * if we are in developer debug mode) that should be output in the footer area
610 * of the page. Designed to be called in theme layout.php files.
612 * @return string HTML fragment.
614 public function standard_footer_html() {
615 global $CFG, $SCRIPT;
617 if (during_initial_install()) {
618 // Debugging info can not work before install is finished,
619 // in any case we do not want any links during installation!
623 // This function is normally called from a layout.php file in {@link core_renderer::header()}
624 // but some of the content won't be known until later, so we return a placeholder
625 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
626 $output = $this->unique_performance_info_token;
627 if ($this->page->devicetypeinuse == 'legacy') {
628 // The legacy theme is in use print the notification
629 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
632 // Get links to switch device types (only shown for users not on a default device)
633 $output .= $this->theme_switch_links();
635 if (!empty($CFG->debugpageinfo)) {
636 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
638 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
639 // Add link to profiling report if necessary
640 if (function_exists('profiling_is_running') && profiling_is_running()) {
641 $txt = get_string('profiledscript', 'admin');
642 $title = get_string('profiledscriptview', 'admin');
643 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
644 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
645 $output .= '<div class="profilingfooter">' . $link . '</div>';
647 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
648 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
649 $output .= '<div class="purgecaches">' .
650 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
652 if (!empty($CFG->debugvalidators)) {
653 // 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
654 $output .= '<div class="validators"><ul>
655 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
656 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
657 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
664 * Returns standard main content placeholder.
665 * Designed to be called in theme layout.php files.
667 * @return string HTML fragment.
669 public function main_content() {
670 // This is here because it is the only place we can inject the "main" role over the entire main content area
671 // without requiring all theme's to manually do it, and without creating yet another thing people need to
672 // remember in the theme.
673 // This is an unfortunate hack. DO NO EVER add anything more here.
674 // DO NOT add classes.
676 return '<div role="main">'.$this->unique_main_content_token.'</div>';
680 * The standard tags (typically script tags that are not needed earlier) that
681 * should be output after everything else. Designed to be called in theme layout.php files.
683 * @return string HTML fragment.
685 public function standard_end_of_body_html() {
688 // This function is normally called from a layout.php file in {@link core_renderer::header()}
689 // but some of the content won't be known until later, so we return a placeholder
690 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
692 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
693 $output .= "\n".$CFG->additionalhtmlfooter;
695 $output .= $this->unique_end_html_token;
700 * Return the standard string that says whether you are logged in (and switched
701 * roles/logged in as another user).
702 * @param bool $withlinks if false, then don't include any links in the HTML produced.
703 * If not set, the default is the nologinlinks option from the theme config.php file,
704 * and if that is not set, then links are included.
705 * @return string HTML fragment.
707 public function login_info($withlinks = null) {
708 global $USER, $CFG, $DB, $SESSION;
710 if (during_initial_install()) {
714 if (is_null($withlinks)) {
715 $withlinks = empty($this->page->layout_options['nologinlinks']);
718 $course = $this->page->course;
719 if (\core\session\manager::is_loggedinas()) {
720 $realuser = \core\session\manager::get_realuser();
721 $fullname = fullname($realuser, true);
723 $loginastitle = get_string('loginas');
724 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
725 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
727 $realuserinfo = " [$fullname] ";
733 $loginpage = $this->is_login_page();
734 $loginurl = get_login_url();
736 if (empty($course->id)) {
737 // $course->id is not defined during installation
739 } else if (isloggedin()) {
740 $context = context_course::instance($course->id);
742 $fullname = fullname($USER, true);
743 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
745 $linktitle = get_string('viewprofile');
746 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
748 $username = $fullname;
750 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
752 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
754 $username .= " from {$idprovider->name}";
758 $loggedinas = $realuserinfo.get_string('loggedinasguest');
759 if (!$loginpage && $withlinks) {
760 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
762 } else if (is_role_switched($course->id)) { // Has switched roles
764 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
765 $rolename = ': '.role_get_name($role, $context);
767 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
769 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
770 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
773 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
775 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
779 $loggedinas = get_string('loggedinnot', 'moodle');
780 if (!$loginpage && $withlinks) {
781 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
785 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
787 if (isset($SESSION->justloggedin)) {
788 unset($SESSION->justloggedin);
789 if (!empty($CFG->displayloginfailures)) {
790 if (!isguestuser()) {
791 // Include this file only when required.
792 require_once($CFG->dirroot . '/user/lib.php');
793 if ($count = user_count_login_failures($USER)) {
794 $loggedinas .= '<div class="loginfailures">';
796 $a->attempts = $count;
797 $loggedinas .= get_string('failedloginattempts', '', $a);
798 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
799 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
800 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
802 $loggedinas .= '</div>';
812 * Check whether the current page is a login page.
817 protected function is_login_page() {
818 // This is a real bit of a hack, but its a rarety that we need to do something like this.
819 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
820 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
822 $this->page->url->out_as_local_url(false, array()),
825 '/login/forgot_password.php',
831 * Return the 'back' link that normally appears in the footer.
833 * @return string HTML fragment.
835 public function home_link() {
838 if ($this->page->pagetype == 'site-index') {
839 // Special case for site home page - please do not remove
840 return '<div class="sitelink">' .
841 '<a title="Moodle" href="http://moodle.org/">' .
842 '<img src="' . $this->pix_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
844 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
845 // Special case for during install/upgrade.
846 return '<div class="sitelink">'.
847 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
848 '<img src="' . $this->pix_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
850 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
851 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
852 get_string('home') . '</a></div>';
855 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
856 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
861 * Redirects the user by any means possible given the current state
863 * This function should not be called directly, it should always be called using
864 * the redirect function in lib/weblib.php
866 * The redirect function should really only be called before page output has started
867 * however it will allow itself to be called during the state STATE_IN_BODY
869 * @param string $encodedurl The URL to send to encoded if required
870 * @param string $message The message to display to the user if any
871 * @param int $delay The delay before redirecting a user, if $message has been
872 * set this is a requirement and defaults to 3, set to 0 no delay
873 * @param boolean $debugdisableredirect this redirect has been disabled for
874 * debugging purposes. Display a message that explains, and don't
875 * trigger the redirect.
876 * @param string $messagetype The type of notification to show the message in.
877 * See constants on \core\output\notification.
878 * @return string The HTML to display to the user before dying, may contain
879 * meta refresh, javascript refresh, and may have set header redirects
881 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
882 $messagetype = \core\output\notification::NOTIFY_INFO) {
884 $url = str_replace('&', '&', $encodedurl);
886 switch ($this->page->state) {
887 case moodle_page::STATE_BEFORE_HEADER :
888 // No output yet it is safe to delivery the full arsenal of redirect methods
889 if (!$debugdisableredirect) {
890 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
891 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
892 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
894 $output = $this->header();
896 case moodle_page::STATE_PRINTING_HEADER :
897 // We should hopefully never get here
898 throw new coding_exception('You cannot redirect while printing the page header');
900 case moodle_page::STATE_IN_BODY :
901 // We really shouldn't be here but we can deal with this
902 debugging("You should really redirect before you start page output");
903 if (!$debugdisableredirect) {
904 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
906 $output = $this->opencontainers->pop_all_but_last();
908 case moodle_page::STATE_DONE :
909 // Too late to be calling redirect now
910 throw new coding_exception('You cannot redirect after the entire page has been generated');
913 $output .= $this->notification($message, $messagetype);
914 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
915 if ($debugdisableredirect) {
916 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
918 $output .= $this->footer();
923 * Start output by sending the HTTP headers, and printing the HTML <head>
924 * and the start of the <body>.
926 * To control what is printed, you should set properties on $PAGE. If you
927 * are familiar with the old {@link print_header()} function from Moodle 1.9
928 * you will find that there are properties on $PAGE that correspond to most
929 * of the old parameters to could be passed to print_header.
931 * Not that, in due course, the remaining $navigation, $menu parameters here
932 * will be replaced by more properties of $PAGE, but that is still to do.
934 * @return string HTML that you must output this, preferably immediately.
936 public function header() {
939 if (\core\session\manager::is_loggedinas()) {
940 $this->page->add_body_class('userloggedinas');
943 // If the user is logged in, and we're not in initial install,
944 // check to see if the user is role-switched and add the appropriate
945 // CSS class to the body element.
946 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
947 $this->page->add_body_class('userswitchedrole');
950 // Give themes a chance to init/alter the page object.
951 $this->page->theme->init_page($this->page);
953 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
955 // Find the appropriate page layout file, based on $this->page->pagelayout.
956 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
957 // Render the layout using the layout file.
958 $rendered = $this->render_page_layout($layoutfile);
960 // Slice the rendered output into header and footer.
961 $cutpos = strpos($rendered, $this->unique_main_content_token);
962 if ($cutpos === false) {
963 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
964 $token = self::MAIN_CONTENT_TOKEN;
966 $token = $this->unique_main_content_token;
969 if ($cutpos === false) {
970 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.');
972 $header = substr($rendered, 0, $cutpos);
973 $footer = substr($rendered, $cutpos + strlen($token));
975 if (empty($this->contenttype)) {
976 debugging('The page layout file did not call $OUTPUT->doctype()');
977 $header = $this->doctype() . $header;
980 // If this theme version is below 2.4 release and this is a course view page
981 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
982 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
983 // check if course content header/footer have not been output during render of theme layout
984 $coursecontentheader = $this->course_content_header(true);
985 $coursecontentfooter = $this->course_content_footer(true);
986 if (!empty($coursecontentheader)) {
987 // display debug message and add header and footer right above and below main content
988 // Please note that course header and footer (to be displayed above and below the whole page)
989 // are not displayed in this case at all.
990 // Besides the content header and footer are not displayed on any other course page
991 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);
992 $header .= $coursecontentheader;
993 $footer = $coursecontentfooter. $footer;
997 send_headers($this->contenttype, $this->page->cacheable);
999 $this->opencontainers->push('header/footer', $footer);
1000 $this->page->set_state(moodle_page::STATE_IN_BODY);
1002 return $header . $this->skip_link_target('maincontent');
1006 * Renders and outputs the page layout file.
1008 * This is done by preparing the normal globals available to a script, and
1009 * then including the layout file provided by the current theme for the
1012 * @param string $layoutfile The name of the layout file
1013 * @return string HTML code
1015 protected function render_page_layout($layoutfile) {
1016 global $CFG, $SITE, $USER;
1017 // The next lines are a bit tricky. The point is, here we are in a method
1018 // of a renderer class, and this object may, or may not, be the same as
1019 // the global $OUTPUT object. When rendering the page layout file, we want to use
1020 // this object. However, people writing Moodle code expect the current
1021 // renderer to be called $OUTPUT, not $this, so define a variable called
1022 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1024 $PAGE = $this->page;
1025 $COURSE = $this->page->course;
1028 include($layoutfile);
1029 $rendered = ob_get_contents();
1035 * Outputs the page's footer
1037 * @return string HTML fragment
1039 public function footer() {
1040 global $CFG, $DB, $PAGE;
1042 $output = $this->container_end_all(true);
1044 $footer = $this->opencontainers->pop('header/footer');
1046 if (debugging() and $DB and $DB->is_transaction_started()) {
1047 // TODO: MDL-20625 print warning - transaction will be rolled back
1050 // Provide some performance info if required
1051 $performanceinfo = '';
1052 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1053 $perf = get_performance_info();
1054 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1055 $performanceinfo = $perf['html'];
1059 // We always want performance data when running a performance test, even if the user is redirected to another page.
1060 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1061 $footer = $this->unique_performance_info_token . $footer;
1063 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1065 // Only show notifications when we have a $PAGE context id.
1066 if (!empty($PAGE->context->id)) {
1067 $this->page->requires->js_call_amd('core/notification', 'init', array(
1069 \core\notification::fetch_as_array($this)
1072 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1074 $this->page->set_state(moodle_page::STATE_DONE);
1076 return $output . $footer;
1080 * Close all but the last open container. This is useful in places like error
1081 * handling, where you want to close all the open containers (apart from <body>)
1082 * before outputting the error message.
1084 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1085 * developer debug warning if it isn't.
1086 * @return string the HTML required to close any open containers inside <body>.
1088 public function container_end_all($shouldbenone = false) {
1089 return $this->opencontainers->pop_all_but_last($shouldbenone);
1093 * Returns course-specific information to be output immediately above content on any course page
1094 * (for the current course)
1096 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1099 public function course_content_header($onlyifnotcalledbefore = false) {
1101 static $functioncalled = false;
1102 if ($functioncalled && $onlyifnotcalledbefore) {
1103 // we have already output the content header
1107 // Output any session notification.
1108 $notifications = \core\notification::fetch();
1110 $bodynotifications = '';
1111 foreach ($notifications as $notification) {
1112 $bodynotifications .= $this->render_from_template(
1113 $notification->get_template_name(),
1114 $notification->export_for_template($this)
1118 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1120 if ($this->page->course->id == SITEID) {
1121 // return immediately and do not include /course/lib.php if not necessary
1125 require_once($CFG->dirroot.'/course/lib.php');
1126 $functioncalled = true;
1127 $courseformat = course_get_format($this->page->course);
1128 if (($obj = $courseformat->course_content_header()) !== null) {
1129 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1135 * Returns course-specific information to be output immediately below content on any course page
1136 * (for the current course)
1138 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1141 public function course_content_footer($onlyifnotcalledbefore = false) {
1143 if ($this->page->course->id == SITEID) {
1144 // return immediately and do not include /course/lib.php if not necessary
1147 static $functioncalled = false;
1148 if ($functioncalled && $onlyifnotcalledbefore) {
1149 // we have already output the content footer
1152 $functioncalled = true;
1153 require_once($CFG->dirroot.'/course/lib.php');
1154 $courseformat = course_get_format($this->page->course);
1155 if (($obj = $courseformat->course_content_footer()) !== null) {
1156 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1162 * Returns course-specific information to be output on any course page in the header area
1163 * (for the current course)
1167 public function course_header() {
1169 if ($this->page->course->id == SITEID) {
1170 // return immediately and do not include /course/lib.php if not necessary
1173 require_once($CFG->dirroot.'/course/lib.php');
1174 $courseformat = course_get_format($this->page->course);
1175 if (($obj = $courseformat->course_header()) !== null) {
1176 return $courseformat->get_renderer($this->page)->render($obj);
1182 * Returns course-specific information to be output on any course page in the footer area
1183 * (for the current course)
1187 public function course_footer() {
1189 if ($this->page->course->id == SITEID) {
1190 // return immediately and do not include /course/lib.php if not necessary
1193 require_once($CFG->dirroot.'/course/lib.php');
1194 $courseformat = course_get_format($this->page->course);
1195 if (($obj = $courseformat->course_footer()) !== null) {
1196 return $courseformat->get_renderer($this->page)->render($obj);
1202 * Returns lang menu or '', this method also checks forcing of languages in courses.
1204 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1206 * @return string The lang menu HTML or empty string
1208 public function lang_menu() {
1211 if (empty($CFG->langmenu)) {
1215 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1216 // do not show lang menu if language forced
1220 $currlang = current_language();
1221 $langs = get_string_manager()->get_list_of_translations();
1223 if (count($langs) < 2) {
1227 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1228 $s->label = get_accesshide(get_string('language'));
1229 $s->class = 'langmenu';
1230 return $this->render($s);
1234 * Output the row of editing icons for a block, as defined by the controls array.
1236 * @param array $controls an array like {@link block_contents::$controls}.
1237 * @param string $blockid The ID given to the block.
1238 * @return string HTML fragment.
1240 public function block_controls($actions, $blockid = null) {
1242 if (empty($actions)) {
1245 $menu = new action_menu($actions);
1246 if ($blockid !== null) {
1247 $menu->set_owner_selector('#'.$blockid);
1249 $menu->set_constraint('.block-region');
1250 $menu->attributes['class'] .= ' block-control-actions commands';
1251 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1252 $menu->do_not_enhance();
1254 return $this->render($menu);
1258 * Renders an action menu component.
1261 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1262 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1264 * @param action_menu $menu
1265 * @return string HTML
1267 public function render_action_menu(action_menu $menu) {
1268 $menu->initialise_js($this->page);
1270 $output = html_writer::start_tag('div', $menu->attributes);
1271 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1272 foreach ($menu->get_primary_actions($this) as $action) {
1273 if ($action instanceof renderable) {
1274 $content = $this->render($action);
1278 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1280 $output .= html_writer::end_tag('ul');
1281 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1282 foreach ($menu->get_secondary_actions() as $action) {
1283 if ($action instanceof renderable) {
1284 $content = $this->render($action);
1288 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1290 $output .= html_writer::end_tag('ul');
1291 $output .= html_writer::end_tag('div');
1296 * Renders an action_menu_link item.
1298 * @param action_menu_link $action
1299 * @return string HTML fragment
1301 protected function render_action_menu_link(action_menu_link $action) {
1302 static $actioncount = 0;
1307 if (!$action->icon || $action->primary === false) {
1308 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1309 if ($action->text instanceof renderable) {
1310 $text .= $this->render($action->text);
1312 $text .= $action->text;
1313 $comparetoalt = (string)$action->text;
1315 $text .= html_writer::end_tag('span');
1319 if ($action->icon) {
1320 $icon = $action->icon;
1321 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1322 $action->attributes['title'] = $action->text;
1324 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1325 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1326 $icon->attributes['alt'] = '';
1328 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1329 unset($icon->attributes['title']);
1332 $icon = $this->render($icon);
1335 // A disabled link is rendered as formatted text.
1336 if (!empty($action->attributes['disabled'])) {
1337 // Do not use div here due to nesting restriction in xhtml strict.
1338 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1341 $attributes = $action->attributes;
1342 unset($action->attributes['disabled']);
1343 $attributes['href'] = $action->url;
1345 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1348 return html_writer::tag('a', $icon.$text, $attributes);
1352 * Renders a primary action_menu_filler item.
1354 * @param action_menu_link_filler $action
1355 * @return string HTML fragment
1357 protected function render_action_menu_filler(action_menu_filler $action) {
1358 return html_writer::span(' ', 'filler');
1362 * Renders a primary action_menu_link item.
1364 * @param action_menu_link_primary $action
1365 * @return string HTML fragment
1367 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1368 return $this->render_action_menu_link($action);
1372 * Renders a secondary action_menu_link item.
1374 * @param action_menu_link_secondary $action
1375 * @return string HTML fragment
1377 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1378 return $this->render_action_menu_link($action);
1382 * Prints a nice side block with an optional header.
1384 * The content is described
1385 * by a {@link core_renderer::block_contents} object.
1387 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1388 * <div class="header"></div>
1389 * <div class="content">
1391 * <div class="footer">
1394 * <div class="annotation">
1398 * @param block_contents $bc HTML for the content
1399 * @param string $region the region the block is appearing in.
1400 * @return string the HTML to be output.
1402 public function block(block_contents $bc, $region) {
1403 $bc = clone($bc); // Avoid messing up the object passed in.
1404 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1405 $bc->collapsible = block_contents::NOT_HIDEABLE;
1407 if (!empty($bc->blockinstanceid)) {
1408 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1410 $skiptitle = strip_tags($bc->title);
1411 if ($bc->blockinstanceid && !empty($skiptitle)) {
1412 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1413 } else if (!empty($bc->arialabel)) {
1414 $bc->attributes['aria-label'] = $bc->arialabel;
1416 if ($bc->dockable) {
1417 $bc->attributes['data-dockable'] = 1;
1419 if ($bc->collapsible == block_contents::HIDDEN) {
1420 $bc->add_class('hidden');
1422 if (!empty($bc->controls)) {
1423 $bc->add_class('block_with_controls');
1427 if (empty($skiptitle)) {
1431 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1432 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1433 $skipdest = html_writer::span('', 'skip-block-to',
1434 array('id' => 'sb-' . $bc->skipid));
1437 $output .= html_writer::start_tag('div', $bc->attributes);
1439 $output .= $this->block_header($bc);
1440 $output .= $this->block_content($bc);
1442 $output .= html_writer::end_tag('div');
1444 $output .= $this->block_annotation($bc);
1446 $output .= $skipdest;
1448 $this->init_block_hider_js($bc);
1453 * Produces a header for a block
1455 * @param block_contents $bc
1458 protected function block_header(block_contents $bc) {
1462 $attributes = array();
1463 if ($bc->blockinstanceid) {
1464 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1466 $title = html_writer::tag('h2', $bc->title, $attributes);
1470 if (isset($bc->attributes['id'])) {
1471 $blockid = $bc->attributes['id'];
1473 $controlshtml = $this->block_controls($bc->controls, $blockid);
1476 if ($title || $controlshtml) {
1477 $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'));
1483 * Produces the content area for a block
1485 * @param block_contents $bc
1488 protected function block_content(block_contents $bc) {
1489 $output = html_writer::start_tag('div', array('class' => 'content'));
1490 if (!$bc->title && !$this->block_controls($bc->controls)) {
1491 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1493 $output .= $bc->content;
1494 $output .= $this->block_footer($bc);
1495 $output .= html_writer::end_tag('div');
1501 * Produces the footer for a block
1503 * @param block_contents $bc
1506 protected function block_footer(block_contents $bc) {
1509 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1515 * Produces the annotation for a block
1517 * @param block_contents $bc
1520 protected function block_annotation(block_contents $bc) {
1522 if ($bc->annotation) {
1523 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1529 * Calls the JS require function to hide a block.
1531 * @param block_contents $bc A block_contents object
1533 protected function init_block_hider_js(block_contents $bc) {
1534 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1535 $config = new stdClass;
1536 $config->id = $bc->attributes['id'];
1537 $config->title = strip_tags($bc->title);
1538 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1539 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1540 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1542 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1543 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1548 * Render the contents of a block_list.
1550 * @param array $icons the icon for each item.
1551 * @param array $items the content of each item.
1552 * @return string HTML
1554 public function list_block_contents($icons, $items) {
1557 foreach ($items as $key => $string) {
1558 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1559 if (!empty($icons[$key])) { //test if the content has an assigned icon
1560 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1562 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1563 $item .= html_writer::end_tag('li');
1565 $row = 1 - $row; // Flip even/odd.
1567 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1571 * Output all the blocks in a particular region.
1573 * @param string $region the name of a region on this page.
1574 * @return string the HTML to be output.
1576 public function blocks_for_region($region) {
1577 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1578 $blocks = $this->page->blocks->get_blocks_for_region($region);
1581 foreach ($blocks as $block) {
1582 $zones[] = $block->title;
1586 foreach ($blockcontents as $bc) {
1587 if ($bc instanceof block_contents) {
1588 $output .= $this->block($bc, $region);
1589 $lastblock = $bc->title;
1590 } else if ($bc instanceof block_move_target) {
1591 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1593 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1600 * Output a place where the block that is currently being moved can be dropped.
1602 * @param block_move_target $target with the necessary details.
1603 * @param array $zones array of areas where the block can be moved to
1604 * @param string $previous the block located before the area currently being rendered.
1605 * @param string $region the name of the region
1606 * @return string the HTML to be output.
1608 public function block_move_target($target, $zones, $previous, $region) {
1609 if ($previous == null) {
1610 if (empty($zones)) {
1611 // There are no zones, probably because there are no blocks.
1612 $regions = $this->page->theme->get_all_block_regions();
1613 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1615 $position = get_string('moveblockbefore', 'block', $zones[0]);
1618 $position = get_string('moveblockafter', 'block', $previous);
1620 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1624 * Renders a special html link with attached action
1626 * Theme developers: DO NOT OVERRIDE! Please override function
1627 * {@link core_renderer::render_action_link()} instead.
1629 * @param string|moodle_url $url
1630 * @param string $text HTML fragment
1631 * @param component_action $action
1632 * @param array $attributes associative array of html link attributes + disabled
1633 * @param pix_icon optional pix icon to render with the link
1634 * @return string HTML fragment
1636 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1637 if (!($url instanceof moodle_url)) {
1638 $url = new moodle_url($url);
1640 $link = new action_link($url, $text, $action, $attributes, $icon);
1642 return $this->render($link);
1646 * Renders an action_link object.
1648 * The provided link is renderer and the HTML returned. At the same time the
1649 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1651 * @param action_link $link
1652 * @return string HTML fragment
1654 protected function render_action_link(action_link $link) {
1659 $text .= $this->render($link->icon);
1662 if ($link->text instanceof renderable) {
1663 $text .= $this->render($link->text);
1665 $text .= $link->text;
1668 // A disabled link is rendered as formatted text
1669 if (!empty($link->attributes['disabled'])) {
1670 // do not use div here due to nesting restriction in xhtml strict
1671 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1674 $attributes = $link->attributes;
1675 unset($link->attributes['disabled']);
1676 $attributes['href'] = $link->url;
1678 if ($link->actions) {
1679 if (empty($attributes['id'])) {
1680 $id = html_writer::random_id('action_link');
1681 $attributes['id'] = $id;
1683 $id = $attributes['id'];
1685 foreach ($link->actions as $action) {
1686 $this->add_action_handler($action, $id);
1690 return html_writer::tag('a', $text, $attributes);
1695 * Renders an action_icon.
1697 * This function uses the {@link core_renderer::action_link()} method for the
1698 * most part. What it does different is prepare the icon as HTML and use it
1701 * Theme developers: If you want to change how action links and/or icons are rendered,
1702 * consider overriding function {@link core_renderer::render_action_link()} and
1703 * {@link core_renderer::render_pix_icon()}.
1705 * @param string|moodle_url $url A string URL or moodel_url
1706 * @param pix_icon $pixicon
1707 * @param component_action $action
1708 * @param array $attributes associative array of html link attributes + disabled
1709 * @param bool $linktext show title next to image in link
1710 * @return string HTML fragment
1712 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1713 if (!($url instanceof moodle_url)) {
1714 $url = new moodle_url($url);
1716 $attributes = (array)$attributes;
1718 if (empty($attributes['class'])) {
1719 // let ppl override the class via $options
1720 $attributes['class'] = 'action-icon';
1723 $icon = $this->render($pixicon);
1726 $text = $pixicon->attributes['alt'];
1731 return $this->action_link($url, $text.$icon, $action, $attributes);
1735 * Print a message along with button choices for Continue/Cancel
1737 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1739 * @param string $message The question to ask the user
1740 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1741 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1742 * @return string HTML fragment
1744 public function confirm($message, $continue, $cancel) {
1745 if ($continue instanceof single_button) {
1747 } else if (is_string($continue)) {
1748 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1749 } else if ($continue instanceof moodle_url) {
1750 $continue = new single_button($continue, get_string('continue'), 'post');
1752 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1755 if ($cancel instanceof single_button) {
1757 } else if (is_string($cancel)) {
1758 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1759 } else if ($cancel instanceof moodle_url) {
1760 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1762 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1765 $output = $this->box_start('generalbox', 'notice');
1766 $output .= html_writer::tag('p', $message);
1767 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1768 $output .= $this->box_end();
1773 * Returns a form with a single button.
1775 * Theme developers: DO NOT OVERRIDE! Please override function
1776 * {@link core_renderer::render_single_button()} instead.
1778 * @param string|moodle_url $url
1779 * @param string $label button text
1780 * @param string $method get or post submit method
1781 * @param array $options associative array {disabled, title, etc.}
1782 * @return string HTML fragment
1784 public function single_button($url, $label, $method='post', array $options=null) {
1785 if (!($url instanceof moodle_url)) {
1786 $url = new moodle_url($url);
1788 $button = new single_button($url, $label, $method);
1790 foreach ((array)$options as $key=>$value) {
1791 if (array_key_exists($key, $button)) {
1792 $button->$key = $value;
1796 return $this->render($button);
1800 * Renders a single button widget.
1802 * This will return HTML to display a form containing a single button.
1804 * @param single_button $button
1805 * @return string HTML fragment
1807 protected function render_single_button(single_button $button) {
1808 $attributes = array('type' => 'submit',
1809 'value' => $button->label,
1810 'disabled' => $button->disabled ? 'disabled' : null,
1811 'title' => $button->tooltip);
1813 if ($button->actions) {
1814 $id = html_writer::random_id('single_button');
1815 $attributes['id'] = $id;
1816 foreach ($button->actions as $action) {
1817 $this->add_action_handler($action, $id);
1821 // first the input element
1822 $output = html_writer::empty_tag('input', $attributes);
1824 // then hidden fields
1825 $params = $button->url->params();
1826 if ($button->method === 'post') {
1827 $params['sesskey'] = sesskey();
1829 foreach ($params as $var => $val) {
1830 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1833 // then div wrapper for xhtml strictness
1834 $output = html_writer::tag('div', $output);
1836 // now the form itself around it
1837 if ($button->method === 'get') {
1838 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1840 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1843 $url = '#'; // there has to be always some action
1845 $attributes = array('method' => $button->method,
1847 'id' => $button->formid);
1848 $output = html_writer::tag('form', $output, $attributes);
1850 // and finally one more wrapper with class
1851 return html_writer::tag('div', $output, array('class' => $button->class));
1855 * Returns a form with a single select widget.
1857 * Theme developers: DO NOT OVERRIDE! Please override function
1858 * {@link core_renderer::render_single_select()} instead.
1860 * @param moodle_url $url form action target, includes hidden fields
1861 * @param string $name name of selection field - the changing parameter in url
1862 * @param array $options list of options
1863 * @param string $selected selected element
1864 * @param array $nothing
1865 * @param string $formid
1866 * @param array $attributes other attributes for the single select
1867 * @return string HTML fragment
1869 public function single_select($url, $name, array $options, $selected = '',
1870 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1871 if (!($url instanceof moodle_url)) {
1872 $url = new moodle_url($url);
1874 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1876 if (array_key_exists('label', $attributes)) {
1877 $select->set_label($attributes['label']);
1878 unset($attributes['label']);
1880 $select->attributes = $attributes;
1882 return $this->render($select);
1886 * Returns a dataformat selection and download form
1888 * @param string $label A text label
1889 * @param moodle_url|string $base The download page url
1890 * @param string $name The query param which will hold the type of the download
1891 * @param array $params Extra params sent to the download page
1892 * @return string HTML fragment
1894 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
1896 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
1898 foreach ($formats as $format) {
1899 if ($format->is_enabled()) {
1901 'value' => $format->name,
1902 'label' => get_string('dataformat', $format->component),
1906 $hiddenparams = array();
1907 foreach ($params as $key => $value) {
1908 $hiddenparams[] = array(
1917 'params' => $hiddenparams,
1918 'options' => $options,
1919 'sesskey' => sesskey(),
1920 'submit' => get_string('download'),
1923 return $this->render_from_template('core/dataformat_selector', $data);
1928 * Internal implementation of single_select rendering
1930 * @param single_select $select
1931 * @return string HTML fragment
1933 protected function render_single_select(single_select $select) {
1934 $select = clone($select);
1935 if (empty($select->formid)) {
1936 $select->formid = html_writer::random_id('single_select_f');
1940 $params = $select->url->params();
1941 if ($select->method === 'post') {
1942 $params['sesskey'] = sesskey();
1944 foreach ($params as $name=>$value) {
1945 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1948 if (empty($select->attributes['id'])) {
1949 $select->attributes['id'] = html_writer::random_id('single_select');
1952 if ($select->disabled) {
1953 $select->attributes['disabled'] = 'disabled';
1956 if ($select->tooltip) {
1957 $select->attributes['title'] = $select->tooltip;
1960 $select->attributes['class'] = 'autosubmit';
1961 if ($select->class) {
1962 $select->attributes['class'] .= ' ' . $select->class;
1965 if ($select->label) {
1966 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1969 if ($select->helpicon instanceof help_icon) {
1970 $output .= $this->render($select->helpicon);
1972 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1974 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1975 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1977 $nothing = empty($select->nothing) ? false : key($select->nothing);
1978 $this->page->requires->yui_module('moodle-core-formautosubmit',
1979 'M.core.init_formautosubmit',
1980 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1983 // then div wrapper for xhtml strictness
1984 $output = html_writer::tag('div', $output);
1986 // now the form itself around it
1987 if ($select->method === 'get') {
1988 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1990 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1992 $formattributes = array('method' => $select->method,
1994 'id' => $select->formid);
1995 $output = html_writer::tag('form', $output, $formattributes);
1997 // and finally one more wrapper with class
1998 return html_writer::tag('div', $output, array('class' => $select->class));
2002 * Returns a form with a url select widget.
2004 * Theme developers: DO NOT OVERRIDE! Please override function
2005 * {@link core_renderer::render_url_select()} instead.
2007 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2008 * @param string $selected selected element
2009 * @param array $nothing
2010 * @param string $formid
2011 * @return string HTML fragment
2013 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2014 $select = new url_select($urls, $selected, $nothing, $formid);
2015 return $this->render($select);
2019 * Internal implementation of url_select rendering
2021 * @param url_select $select
2022 * @return string HTML fragment
2024 protected function render_url_select(url_select $select) {
2027 $select = clone($select);
2028 if (empty($select->formid)) {
2029 $select->formid = html_writer::random_id('url_select_f');
2032 if (empty($select->attributes['id'])) {
2033 $select->attributes['id'] = html_writer::random_id('url_select');
2036 if ($select->disabled) {
2037 $select->attributes['disabled'] = 'disabled';
2040 if ($select->tooltip) {
2041 $select->attributes['title'] = $select->tooltip;
2046 if ($select->label) {
2047 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
2051 if (!$select->showbutton) {
2052 $classes[] = 'autosubmit';
2054 if ($select->class) {
2055 $classes[] = $select->class;
2057 if (count($classes)) {
2058 $select->attributes['class'] = implode(' ', $classes);
2061 if ($select->helpicon instanceof help_icon) {
2062 $output .= $this->render($select->helpicon);
2065 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
2066 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
2068 foreach ($select->urls as $k=>$v) {
2070 // optgroup structure
2071 foreach ($v as $optgrouptitle => $optgroupoptions) {
2072 foreach ($optgroupoptions as $optionurl => $optiontitle) {
2073 if (empty($optionurl)) {
2074 $safeoptionurl = '';
2075 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
2076 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
2077 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
2078 } else if (strpos($optionurl, '/') !== 0) {
2079 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2082 $safeoptionurl = $optionurl;
2084 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2088 // plain list structure
2090 // nothing selected option
2091 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2092 $k = str_replace($CFG->wwwroot, '', $k);
2093 } else if (strpos($k, '/') !== 0) {
2094 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2100 $selected = $select->selected;
2101 if (!empty($selected)) {
2102 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2103 $selected = str_replace($CFG->wwwroot, '', $selected);
2104 } else if (strpos($selected, '/') !== 0) {
2105 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
2109 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
2110 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
2112 if (!$select->showbutton) {
2113 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
2114 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
2115 $nothing = empty($select->nothing) ? false : key($select->nothing);
2116 $this->page->requires->yui_module('moodle-core-formautosubmit',
2117 'M.core.init_formautosubmit',
2118 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2121 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2124 // then div wrapper for xhtml strictness
2125 $output = html_writer::tag('div', $output);
2127 // now the form itself around it
2128 $formattributes = array('method' => 'post',
2129 'action' => new moodle_url('/course/jumpto.php'),
2130 'id' => $select->formid);
2131 $output = html_writer::tag('form', $output, $formattributes);
2133 // and finally one more wrapper with class
2134 return html_writer::tag('div', $output, array('class' => $select->class));
2138 * Returns a string containing a link to the user documentation.
2139 * Also contains an icon by default. Shown to teachers and admin only.
2141 * @param string $path The page link after doc root and language, no leading slash.
2142 * @param string $text The text to be displayed for the link
2143 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2146 public function doc_link($path, $text = '', $forcepopup = false) {
2149 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2151 $url = new moodle_url(get_docs_url($path));
2153 $attributes = array('href'=>$url);
2154 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2155 $attributes['class'] = 'helplinkpopup';
2158 return html_writer::tag('a', $icon.$text, $attributes);
2162 * Return HTML for a pix_icon.
2164 * Theme developers: DO NOT OVERRIDE! Please override function
2165 * {@link core_renderer::render_pix_icon()} instead.
2167 * @param string $pix short pix name
2168 * @param string $alt mandatory alt attribute
2169 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2170 * @param array $attributes htm lattributes
2171 * @return string HTML fragment
2173 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2174 $icon = new pix_icon($pix, $alt, $component, $attributes);
2175 return $this->render($icon);
2179 * Renders a pix_icon widget and returns the HTML to display it.
2181 * @param pix_icon $icon
2182 * @return string HTML fragment
2184 protected function render_pix_icon(pix_icon $icon) {
2185 $data = $icon->export_for_template($this);
2186 return $this->render_from_template('core/pix_icon', $data);
2190 * Return HTML to display an emoticon icon.
2192 * @param pix_emoticon $emoticon
2193 * @return string HTML fragment
2195 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2196 $attributes = $emoticon->attributes;
2197 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2198 return html_writer::empty_tag('img', $attributes);
2202 * Produces the html that represents this rating in the UI
2204 * @param rating $rating the page object on which this rating will appear
2207 function render_rating(rating $rating) {
2210 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2211 return null;//ratings are turned off
2214 $ratingmanager = new rating_manager();
2215 // Initialise the JavaScript so ratings can be done by AJAX.
2216 $ratingmanager->initialise_rating_javascript($this->page);
2218 $strrate = get_string("rate", "rating");
2219 $ratinghtml = ''; //the string we'll return
2221 // permissions check - can they view the aggregate?
2222 if ($rating->user_can_view_aggregate()) {
2224 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2225 $aggregatestr = $rating->get_aggregate_string();
2227 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2228 if ($rating->count > 0) {
2229 $countstr = "({$rating->count})";
2233 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2235 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2236 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2238 $nonpopuplink = $rating->get_view_ratings_url();
2239 $popuplink = $rating->get_view_ratings_url(true);
2241 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2242 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2244 $ratinghtml .= $aggregatehtml;
2249 // if the item doesn't belong to the current user, the user has permission to rate
2250 // and we're within the assessable period
2251 if ($rating->user_can_rate()) {
2253 $rateurl = $rating->get_rate_url();
2254 $inputs = $rateurl->params();
2256 //start the rating form
2258 'id' => "postrating{$rating->itemid}",
2259 'class' => 'postratingform',
2261 'action' => $rateurl->out_omit_querystring()
2263 $formstart = html_writer::start_tag('form', $formattrs);
2264 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2266 // add the hidden inputs
2267 foreach ($inputs as $name => $value) {
2268 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2269 $formstart .= html_writer::empty_tag('input', $attributes);
2272 if (empty($ratinghtml)) {
2273 $ratinghtml .= $strrate.': ';
2275 $ratinghtml = $formstart.$ratinghtml;
2277 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2278 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2279 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2280 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2282 //output submit button
2283 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2285 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2286 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2288 if (!$rating->settings->scale->isnumeric) {
2289 // If a global scale, try to find current course ID from the context
2290 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2291 $courseid = $coursecontext->instanceid;
2293 $courseid = $rating->settings->scale->courseid;
2295 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2297 $ratinghtml .= html_writer::end_tag('span');
2298 $ratinghtml .= html_writer::end_tag('div');
2299 $ratinghtml .= html_writer::end_tag('form');
2306 * Centered heading with attached help button (same title text)
2307 * and optional icon attached.
2309 * @param string $text A heading text
2310 * @param string $helpidentifier The keyword that defines a help page
2311 * @param string $component component name
2312 * @param string|moodle_url $icon
2313 * @param string $iconalt icon alt text
2314 * @param int $level The level of importance of the heading. Defaulting to 2
2315 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2316 * @return string HTML fragment
2318 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2321 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2325 if ($helpidentifier) {
2326 $help = $this->help_icon($helpidentifier, $component);
2329 return $this->heading($image.$text.$help, $level, $classnames);
2333 * Returns HTML to display a help icon.
2335 * @deprecated since Moodle 2.0
2337 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2338 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2342 * Returns HTML to display a help icon.
2344 * Theme developers: DO NOT OVERRIDE! Please override function
2345 * {@link core_renderer::render_help_icon()} instead.
2347 * @param string $identifier The keyword that defines a help page
2348 * @param string $component component name
2349 * @param string|bool $linktext true means use $title as link text, string means link text value
2350 * @return string HTML fragment
2352 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2353 $icon = new help_icon($identifier, $component);
2354 $icon->diag_strings();
2355 if ($linktext === true) {
2356 $icon->linktext = get_string($icon->identifier, $icon->component);
2357 } else if (!empty($linktext)) {
2358 $icon->linktext = $linktext;
2360 return $this->render($icon);
2364 * Implementation of user image rendering.
2366 * @param help_icon $helpicon A help icon instance
2367 * @return string HTML fragment
2369 protected function render_help_icon(help_icon $helpicon) {
2372 // first get the help image icon
2373 $src = $this->pix_url('help');
2375 $title = get_string($helpicon->identifier, $helpicon->component);
2377 if (empty($helpicon->linktext)) {
2378 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2380 $alt = get_string('helpwiththis');
2383 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2384 $output = html_writer::empty_tag('img', $attributes);
2386 // add the link text if given
2387 if (!empty($helpicon->linktext)) {
2388 // the spacing has to be done through CSS
2389 $output .= $helpicon->linktext;
2392 // now create the link around it - we need https on loginhttps pages
2393 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2395 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2396 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2398 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2399 $output = html_writer::tag('a', $output, $attributes);
2402 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2406 * Returns HTML to display a scale help icon.
2408 * @param int $courseid
2409 * @param stdClass $scale instance
2410 * @return string HTML fragment
2412 public function help_icon_scale($courseid, stdClass $scale) {
2415 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2417 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2419 $scaleid = abs($scale->id);
2421 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2422 $action = new popup_action('click', $link, 'ratingscale');
2424 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2428 * Creates and returns a spacer image with optional line break.
2430 * @param array $attributes Any HTML attributes to add to the spaced.
2431 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2432 * laxy do it with CSS which is a much better solution.
2433 * @return string HTML fragment
2435 public function spacer(array $attributes = null, $br = false) {
2436 $attributes = (array)$attributes;
2437 if (empty($attributes['width'])) {
2438 $attributes['width'] = 1;
2440 if (empty($attributes['height'])) {
2441 $attributes['height'] = 1;
2443 $attributes['class'] = 'spacer';
2445 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2448 $output .= '<br />';
2455 * Returns HTML to display the specified user's avatar.
2457 * User avatar may be obtained in two ways:
2459 * // Option 1: (shortcut for simple cases, preferred way)
2460 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2461 * $OUTPUT->user_picture($user, array('popup'=>true));
2464 * $userpic = new user_picture($user);
2465 * // Set properties of $userpic
2466 * $userpic->popup = true;
2467 * $OUTPUT->render($userpic);
2470 * Theme developers: DO NOT OVERRIDE! Please override function
2471 * {@link core_renderer::render_user_picture()} instead.
2473 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2474 * If any of these are missing, the database is queried. Avoid this
2475 * if at all possible, particularly for reports. It is very bad for performance.
2476 * @param array $options associative array with user picture options, used only if not a user_picture object,
2478 * - courseid=$this->page->course->id (course id of user profile in link)
2479 * - size=35 (size of image)
2480 * - link=true (make image clickable - the link leads to user profile)
2481 * - popup=false (open in popup)
2482 * - alttext=true (add image alt attribute)
2483 * - class = image class attribute (default 'userpicture')
2484 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2485 * @return string HTML fragment
2487 public function user_picture(stdClass $user, array $options = null) {
2488 $userpicture = new user_picture($user);
2489 foreach ((array)$options as $key=>$value) {
2490 if (array_key_exists($key, $userpicture)) {
2491 $userpicture->$key = $value;
2494 return $this->render($userpicture);
2498 * Internal implementation of user image rendering.
2500 * @param user_picture $userpicture
2503 protected function render_user_picture(user_picture $userpicture) {
2506 $user = $userpicture->user;
2508 if ($userpicture->alttext) {
2509 if (!empty($user->imagealt)) {
2510 $alt = $user->imagealt;
2512 $alt = get_string('pictureof', '', fullname($user));
2518 if (empty($userpicture->size)) {
2520 } else if ($userpicture->size === true or $userpicture->size == 1) {
2523 $size = $userpicture->size;
2526 $class = $userpicture->class;
2528 if ($user->picture == 0) {
2529 $class .= ' defaultuserpic';
2532 $src = $userpicture->get_url($this->page, $this);
2534 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2535 if (!$userpicture->visibletoscreenreaders) {
2536 $attributes['role'] = 'presentation';
2539 // get the image html output fisrt
2540 $output = html_writer::empty_tag('img', $attributes);
2542 // then wrap it in link if needed
2543 if (!$userpicture->link) {
2547 if (empty($userpicture->courseid)) {
2548 $courseid = $this->page->course->id;
2550 $courseid = $userpicture->courseid;
2553 if ($courseid == SITEID) {
2554 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2556 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2559 $attributes = array('href'=>$url);
2560 if (!$userpicture->visibletoscreenreaders) {
2561 $attributes['tabindex'] = '-1';
2562 $attributes['aria-hidden'] = 'true';
2565 if ($userpicture->popup) {
2566 $id = html_writer::random_id('userpicture');
2567 $attributes['id'] = $id;
2568 $this->add_action_handler(new popup_action('click', $url), $id);
2571 return html_writer::tag('a', $output, $attributes);
2575 * Internal implementation of file tree viewer items rendering.
2580 public function htmllize_file_tree($dir) {
2581 if (empty($dir['subdirs']) and empty($dir['files'])) {
2585 foreach ($dir['subdirs'] as $subdir) {
2586 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2588 foreach ($dir['files'] as $file) {
2589 $filename = $file->get_filename();
2590 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2598 * Returns HTML to display the file picker
2601 * $OUTPUT->file_picker($options);
2604 * Theme developers: DO NOT OVERRIDE! Please override function
2605 * {@link core_renderer::render_file_picker()} instead.
2607 * @param array $options associative array with file manager options
2611 * client_id=>uniqid(),
2612 * acepted_types=>'*',
2613 * return_types=>FILE_INTERNAL,
2614 * context=>$PAGE->context
2615 * @return string HTML fragment
2617 public function file_picker($options) {
2618 $fp = new file_picker($options);
2619 return $this->render($fp);
2623 * Internal implementation of file picker rendering.
2625 * @param file_picker $fp
2628 public function render_file_picker(file_picker $fp) {
2629 global $CFG, $OUTPUT, $USER;
2630 $options = $fp->options;
2631 $client_id = $options->client_id;
2632 $strsaved = get_string('filesaved', 'repository');
2633 $straddfile = get_string('openpicker', 'repository');
2634 $strloading = get_string('loading', 'repository');
2635 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2636 $strdroptoupload = get_string('droptoupload', 'moodle');
2637 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2639 $currentfile = $options->currentfile;
2640 if (empty($currentfile)) {
2643 $currentfile .= ' - ';
2645 if ($options->maxbytes) {
2646 $size = $options->maxbytes;
2648 $size = get_max_upload_file_size();
2653 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2655 if ($options->buttonname) {
2656 $buttonname = ' name="' . $options->buttonname . '"';
2661 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2664 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2666 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2667 <span> $maxsize </span>
2670 if ($options->env != 'url') {
2672 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2673 <div class="filepicker-filename">
2674 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2675 <div class="dndupload-progressbars"></div>
2677 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2686 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2688 * @deprecated since Moodle 3.2
2690 * @param string $cmid the course_module id.
2691 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2692 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2694 public function update_module_button($cmid, $modulename) {
2697 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2698 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2699 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2701 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2702 $modulename = get_string('modulename', $modulename);
2703 $string = get_string('updatethis', '', $modulename);
2704 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2705 return $this->single_button($url, $string);
2712 * Returns HTML to display a "Turn editing on/off" button in a form.
2714 * @param moodle_url $url The URL + params to send through when clicking the button
2715 * @return string HTML the button
2717 public function edit_button(moodle_url $url) {
2719 $url->param('sesskey', sesskey());
2720 if ($this->page->user_is_editing()) {
2721 $url->param('edit', 'off');
2722 $editstring = get_string('turneditingoff');
2724 $url->param('edit', 'on');
2725 $editstring = get_string('turneditingon');
2728 return $this->single_button($url, $editstring);
2732 * Returns HTML to display a simple button to close a window
2734 * @param string $text The lang string for the button's label (already output from get_string())
2735 * @return string html fragment
2737 public function close_window_button($text='') {
2739 $text = get_string('closewindow');
2741 $button = new single_button(new moodle_url('#'), $text, 'get');
2742 $button->add_action(new component_action('click', 'close_window'));
2744 return $this->container($this->render($button), 'closewindow');
2748 * Output an error message. By default wraps the error message in <span class="error">.
2749 * If the error message is blank, nothing is output.
2751 * @param string $message the error message.
2752 * @return string the HTML to output.
2754 public function error_text($message) {
2755 if (empty($message)) {
2758 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2759 return html_writer::tag('span', $message, array('class' => 'error'));
2763 * Do not call this function directly.
2765 * To terminate the current script with a fatal error, call the {@link print_error}
2766 * function, or throw an exception. Doing either of those things will then call this
2767 * function to display the error, before terminating the execution.
2769 * @param string $message The message to output
2770 * @param string $moreinfourl URL where more info can be found about the error
2771 * @param string $link Link for the Continue button
2772 * @param array $backtrace The execution backtrace
2773 * @param string $debuginfo Debugging information
2774 * @return string the HTML to output.
2776 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2782 if ($this->has_started()) {
2783 // we can not always recover properly here, we have problems with output buffering,
2784 // html tables, etc.
2785 $output .= $this->opencontainers->pop_all_but_last();
2788 // It is really bad if library code throws exception when output buffering is on,
2789 // because the buffered text would be printed before our start of page.
2790 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2791 error_reporting(0); // disable notices from gzip compression, etc.
2792 while (ob_get_level() > 0) {
2793 $buff = ob_get_clean();
2794 if ($buff === false) {
2799 error_reporting($CFG->debug);
2801 // Output not yet started.
2802 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2803 if (empty($_SERVER['HTTP_RANGE'])) {
2804 @header($protocol . ' 404 Not Found');
2806 // Must stop byteserving attempts somehow,
2807 // this is weird but Chrome PDF viewer can be stopped only with 407!
2808 @header($protocol . ' 407 Proxy Authentication Required');
2811 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2812 $this->page->set_url('/'); // no url
2813 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2814 $this->page->set_title(get_string('error'));
2815 $this->page->set_heading($this->page->course->fullname);
2816 $output .= $this->header();
2819 $message = '<p class="errormessage">' . $message . '</p>'.
2820 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2821 get_string('moreinformation') . '</a></p>';
2822 if (empty($CFG->rolesactive)) {
2823 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2824 //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.
2826 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2828 if ($CFG->debugdeveloper) {
2829 if (!empty($debuginfo)) {
2830 $debuginfo = s($debuginfo); // removes all nasty JS
2831 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2832 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2834 if (!empty($backtrace)) {
2835 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2837 if ($obbuffer !== '' ) {
2838 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2842 if (empty($CFG->rolesactive)) {
2843 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2844 } else if (!empty($link)) {
2845 $output .= $this->continue_button($link);
2848 $output .= $this->footer();
2850 // Padding to encourage IE to display our error page, rather than its own.
2851 $output .= str_repeat(' ', 512);
2857 * Output a notification (that is, a status message about something that has just happened).
2859 * Note: \core\notification::add() may be more suitable for your usage.
2861 * @param string $message The message to print out.
2862 * @param string $type The type of notification. See constants on \core\output\notification.
2863 * @return string the HTML to output.
2865 public function notification($message, $type = null) {
2868 'success' => \core\output\notification::NOTIFY_SUCCESS,
2869 'info' => \core\output\notification::NOTIFY_INFO,
2870 'warning' => \core\output\notification::NOTIFY_WARNING,
2871 'error' => \core\output\notification::NOTIFY_ERROR,
2873 // Legacy types mapped to current types.
2874 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2875 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2876 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2877 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2878 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2879 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2880 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2886 if (strpos($type, ' ') === false) {
2887 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2888 if (isset($typemappings[$type])) {
2889 $type = $typemappings[$type];
2891 // The value provided did not match a known type. It must be an extra class.
2892 $extraclasses = [$type];
2895 // Identify what type of notification this is.
2896 $classarray = explode(' ', self::prepare_classes($type));
2898 // Separate out the type of notification from the extra classes.
2899 foreach ($classarray as $class) {
2900 if (isset($typemappings[$class])) {
2901 $type = $typemappings[$class];
2903 $extraclasses[] = $class;
2909 $notification = new \core\output\notification($message, $type);
2910 if (count($extraclasses)) {
2911 $notification->set_extra_classes($extraclasses);
2914 // Return the rendered template.
2915 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2919 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2921 * @param string $message the message to print out
2922 * @return string HTML fragment.
2923 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2924 * @todo MDL-53113 This will be removed in Moodle 3.5.
2925 * @see \core\output\notification
2927 public function notify_problem($message) {
2928 debugging(__FUNCTION__ . ' is deprecated.' .
2929 'Please use \core\notification::add, or \core\output\notification as required',
2931 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
2932 return $this->render($n);
2936 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2938 * @param string $message the message to print out
2939 * @return string HTML fragment.
2940 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2941 * @todo MDL-53113 This will be removed in Moodle 3.5.
2942 * @see \core\output\notification
2944 public function notify_success($message) {
2945 debugging(__FUNCTION__ . ' is deprecated.' .
2946 'Please use \core\notification::add, or \core\output\notification as required',
2948 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2949 return $this->render($n);
2953 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2955 * @param string $message the message to print out
2956 * @return string HTML fragment.
2957 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2958 * @todo MDL-53113 This will be removed in Moodle 3.5.
2959 * @see \core\output\notification
2961 public function notify_message($message) {
2962 debugging(__FUNCTION__ . ' is deprecated.' .
2963 'Please use \core\notification::add, or \core\output\notification as required',
2965 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2966 return $this->render($n);
2970 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2972 * @param string $message the message to print out
2973 * @return string HTML fragment.
2974 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2975 * @todo MDL-53113 This will be removed in Moodle 3.5.
2976 * @see \core\output\notification
2978 public function notify_redirect($message) {
2979 debugging(__FUNCTION__ . ' is deprecated.' .
2980 'Please use \core\notification::add, or \core\output\notification as required',
2982 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2983 return $this->render($n);
2987 * Render a notification (that is, a status message about something that has
2990 * @param \core\output\notification $notification the notification to print out
2991 * @return string the HTML to output.
2993 protected function render_notification(\core\output\notification $notification) {
2994 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2998 * Returns HTML to display a continue button that goes to a particular URL.
3000 * @param string|moodle_url $url The url the button goes to.
3001 * @return string the HTML to output.
3003 public function continue_button($url) {
3004 if (!($url instanceof moodle_url)) {
3005 $url = new moodle_url($url);
3007 $button = new single_button($url, get_string('continue'), 'get');
3008 $button->class = 'continuebutton';
3010 return $this->render($button);
3014 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3016 * Theme developers: DO NOT OVERRIDE! Please override function
3017 * {@link core_renderer::render_paging_bar()} instead.
3019 * @param int $totalcount The total number of entries available to be paged through
3020 * @param int $page The page you are currently viewing
3021 * @param int $perpage The number of entries that should be shown per page
3022 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3023 * @param string $pagevar name of page parameter that holds the page number
3024 * @return string the HTML to output.
3026 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3027 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3028 return $this->render($pb);
3032 * Internal implementation of paging bar rendering.
3034 * @param paging_bar $pagingbar
3037 protected function render_paging_bar(paging_bar $pagingbar) {
3039 $pagingbar = clone($pagingbar);
3040 $pagingbar->prepare($this, $this->page, $this->target);
3042 if ($pagingbar->totalcount > $pagingbar->perpage) {
3043 $output .= get_string('page') . ':';
3045 if (!empty($pagingbar->previouslink)) {
3046 $output .= ' (' . $pagingbar->previouslink . ') ';
3049 if (!empty($pagingbar->firstlink)) {
3050 $output .= ' ' . $pagingbar->firstlink . ' ...';
3053 foreach ($pagingbar->pagelinks as $link) {
3054 $output .= " $link";
3057 if (!empty($pagingbar->lastlink)) {
3058 $output .= ' ... ' . $pagingbar->lastlink . ' ';
3061 if (!empty($pagingbar->nextlink)) {
3062 $output .= ' (' . $pagingbar->nextlink . ')';
3066 return html_writer::tag('div', $output, array('class' => 'paging'));
3070 * Output the place a skip link goes to.
3072 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3073 * @return string the HTML to output.
3075 public function skip_link_target($id = null) {
3076 return html_writer::span('', '', array('id' => $id));
3082 * @param string $text The text of the heading
3083 * @param int $level The level of importance of the heading. Defaulting to 2
3084 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3085 * @param string $id An optional ID
3086 * @return string the HTML to output.
3088 public function heading($text, $level = 2, $classes = null, $id = null) {
3089 $level = (integer) $level;
3090 if ($level < 1 or $level > 6) {
3091 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3093 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3099 * @param string $contents The contents of the box
3100 * @param string $classes A space-separated list of CSS classes
3101 * @param string $id An optional ID
3102 * @param array $attributes An array of other attributes to give the box.
3103 * @return string the HTML to output.
3105 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3106 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3110 * Outputs the opening section of a box.
3112 * @param string $classes A space-separated list of CSS classes
3113 * @param string $id An optional ID
3114 * @param array $attributes An array of other attributes to give the box.
3115 * @return string the HTML to output.
3117 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3118 $this->opencontainers->push('box', html_writer::end_tag('div'));
3119 $attributes['id'] = $id;
3120 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3121 return html_writer::start_tag('div', $attributes);
3125 * Outputs the closing section of a box.
3127 * @return string the HTML to output.
3129 public function box_end() {
3130 return $this->opencontainers->pop('box');
3134 * Outputs a container.
3136 * @param string $contents The contents of the box
3137 * @param string $classes A space-separated list of CSS classes
3138 * @param string $id An optional ID
3139 * @return string the HTML to output.
3141 public function container($contents, $classes = null, $id = null) {
3142 return $this->container_start($classes, $id) . $contents . $this->container_end();
3146 * Outputs the opening section of a container.
3148 * @param string $classes A space-separated list of CSS classes
3149 * @param string $id An optional ID
3150 * @return string the HTML to output.
3152 public function container_start($classes = null, $id = null) {
3153 $this->opencontainers->push('container', html_writer::end_tag('div'));
3154 return html_writer::start_tag('div', array('id' => $id,
3155 'class' => renderer_base::prepare_classes($classes)));
3159 * Outputs the closing section of a container.
3161 * @return string the HTML to output.
3163 public function container_end() {
3164 return $this->opencontainers->pop('container');
3168 * Make nested HTML lists out of the items
3170 * The resulting list will look something like this:
3174 * <<li>><div class='tree_item parent'>(item contents)</div>
3176 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3182 * @param array $items
3183 * @param array $attrs html attributes passed to the top ofs the list
3184 * @return string HTML
3186 public function tree_block_contents($items, $attrs = array()) {
3187 // exit if empty, we don't want an empty ul element
3188 if (empty($items)) {
3191 // array of nested li elements
3193 foreach ($items as $item) {
3194 // this applies to the li item which contains all child lists too
3195 $content = $item->content($this);
3196 $liclasses = array($item->get_css_type());
3197 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3198 $liclasses[] = 'collapsed';
3200 if ($item->isactive === true) {
3201 $liclasses[] = 'current_branch';
3203 $liattr = array('class'=>join(' ',$liclasses));
3204 // class attribute on the div item which only contains the item content
3205 $divclasses = array('tree_item');
3206 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3207 $divclasses[] = 'branch';
3209 $divclasses[] = 'leaf';
3211 if (!empty($item->classes) && count($item->classes)>0) {
3212 $divclasses[] = join(' ', $item->classes);
3214 $divattr = array('class'=>join(' ', $divclasses));
3215 if (!empty($item->id)) {
3216 $divattr['id'] = $item->id;
3218 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3219 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3220 $content = html_writer::empty_tag('hr') . $content;
3222 $content = html_writer::tag('li', $content, $liattr);
3225 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3229 * Returns a search box.
3231 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3232 * @return string HTML with the search form hidden by default.
3234 public function search_box($id = false) {
3237 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3238 // result in an extra included file for each site, even the ones where global search
3240 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3247 // Needs to be cleaned, we use it for the input id.
3248 $id = clean_param($id, PARAM_ALPHANUMEXT);
3251 // JS to animate the form.
3252 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3254 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3255 array('role' => 'button', 'tabindex' => 0));
3256 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3257 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3258 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id);
3260 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3261 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3262 $searchinput = html_writer::tag('form', $contents, $formattrs);
3264 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper', 'id' => $id));
3268 * Construct a user menu, returning HTML that can be echoed out by a
3271 * @param stdClass $user A user object, usually $USER.
3272 * @param bool $withlinks true if a dropdown should be built.
3273 * @return string HTML fragment.
3275 public function user_menu($user = null, $withlinks = null) {
3277 require_once($CFG->dirroot . '/user/lib.php');
3279 if (is_null($user)) {
3283 // Note: this behaviour is intended to match that of core_renderer::login_info,
3284 // but should not be considered to be good practice; layout options are
3285 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3286 if (is_null($withlinks)) {
3287 $withlinks = empty($this->page->layout_options['nologinlinks']);
3290 // Add a class for when $withlinks is false.
3291 $usermenuclasses = 'usermenu';
3293 $usermenuclasses .= ' withoutlinks';
3298 // If during initial install, return the empty return string.
3299 if (during_initial_install()) {
3303 $loginpage = $this->is_login_page();
3304 $loginurl = get_login_url();
3305 // If not logged in, show the typical not-logged-in string.
3306 if (!isloggedin()) {
3307 $returnstr = get_string('loggedinnot', 'moodle');
3309 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3311 return html_writer::div(
3321 // If logged in as a guest user, show a string to that effect.
3322 if (isguestuser()) {
3323 $returnstr = get_string('loggedinasguest');
3324 if (!$loginpage && $withlinks) {
3325 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3328 return html_writer::div(
3337 // Get some navigation opts.
3338 $opts = user_get_user_navigation_info($user, $this->page);
3340 $avatarclasses = "avatars";
3341 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3342 $usertextcontents = $opts->metadata['userfullname'];
3345 if (!empty($opts->metadata['asotheruser'])) {
3346 $avatarcontents .= html_writer::span(
3347 $opts->metadata['realuseravatar'],
3350 $usertextcontents = $opts->metadata['realuserfullname'];
3351 $usertextcontents .= html_writer::tag(
3357 $opts->metadata['userfullname'],
3361 array('class' => 'meta viewingas')
3366 if (!empty($opts->metadata['asotherrole'])) {
3367 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3368 $usertextcontents .= html_writer::span(
3369 $opts->metadata['rolename'],
3370 'meta role role-' . $role
3374 // User login failures.
3375 if (!empty($opts->metadata['userloginfail'])) {
3376 $usertextcontents .= html_writer::span(
3377 $opts->metadata['userloginfail'],