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 $jshelper = new \core\output\mustache_javascript_helper($this->page->requires);
95 $pixhelper = new \core\output\mustache_pix_helper($this);
97 // We only expose the variables that are exposed to JS templates.
98 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
100 $helpers = array('config' => $safeconfig,
101 'str' => array($stringhelper, 'str'),
102 'js' => array($jshelper, 'help'),
103 'pix' => array($pixhelper, 'pix'));
105 $this->mustache = new Mustache_Engine(array(
106 'cache' => $cachedir,
109 'helpers' => $helpers));
113 return $this->mustache;
120 * The constructor takes two arguments. The first is the page that the renderer
121 * has been created to assist with, and the second is the target.
122 * The target is an additional identifier that can be used to load different
123 * renderers for different options.
125 * @param moodle_page $page the page we are doing output for.
126 * @param string $target one of rendering target constants
128 public function __construct(moodle_page $page, $target) {
129 $this->opencontainers = $page->opencontainers;
131 $this->target = $target;
135 * Renders a template by name with the given context.
137 * The provided data needs to be array/stdClass made up of only simple types.
138 * Simple types are array,stdClass,bool,int,float,string
141 * @param array|stdClass $context Context containing data for the template.
142 * @return string|boolean
144 public function render_from_template($templatename, $context) {
145 static $templatecache = array();
146 $mustache = $this->get_mustache();
148 // Provide 1 random value that will not change within a template
149 // but will be different from template to template. This is useful for
150 // e.g. aria attributes that only work with id attributes and must be
152 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
153 if (isset($templatecache[$templatename])) {
154 $template = $templatecache[$templatename];
157 $template = $mustache->loadTemplate($templatename);
158 $templatecache[$templatename] = $template;
159 } catch (Mustache_Exception_UnknownTemplateException $e) {
160 throw new moodle_exception('Unknown template: ' . $templatename);
163 return trim($template->render($context));
168 * Returns rendered widget.
170 * The provided widget needs to be an object that extends the renderable
172 * If will then be rendered by a method based upon the classname for the widget.
173 * For instance a widget of class `crazywidget` will be rendered by a protected
174 * render_crazywidget method of this renderer.
176 * @param renderable $widget instance with renderable interface
179 public function render(renderable $widget) {
180 $classname = get_class($widget);
182 $classname = preg_replace('/^.*\\\/', '', $classname);
183 // Remove _renderable suffixes
184 $classname = preg_replace('/_renderable$/', '', $classname);
186 $rendermethod = 'render_'.$classname;
187 if (method_exists($this, $rendermethod)) {
188 return $this->$rendermethod($widget);
190 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
194 * Adds a JS action for the element with the provided id.
196 * This method adds a JS event for the provided component action to the page
197 * and then returns the id that the event has been attached to.
198 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
200 * @param component_action $action
202 * @return string id of element, either original submitted or random new if not supplied
204 public function add_action_handler(component_action $action, $id = null) {
206 $id = html_writer::random_id($action->event);
208 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
213 * Returns true is output has already started, and false if not.
215 * @return boolean true if the header has been printed.
217 public function has_started() {
218 return $this->page->state >= moodle_page::STATE_IN_BODY;
222 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
224 * @param mixed $classes Space-separated string or array of classes
225 * @return string HTML class attribute value
227 public static function prepare_classes($classes) {
228 if (is_array($classes)) {
229 return implode(' ', array_unique($classes));
235 * Return the moodle_url for an image.
237 * The exact image location and extension is determined
238 * automatically by searching for gif|png|jpg|jpeg, please
239 * note there can not be diferent images with the different
240 * extension. The imagename is for historical reasons
241 * a relative path name, it may be changed later for core
242 * images. It is recommended to not use subdirectories
243 * in plugin and theme pix directories.
245 * There are three types of images:
246 * 1/ theme images - stored in theme/mytheme/pix/,
247 * use component 'theme'
248 * 2/ core images - stored in /pix/,
249 * overridden via theme/mytheme/pix_core/
250 * 3/ plugin images - stored in mod/mymodule/pix,
251 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
252 * example: pix_url('comment', 'mod_glossary')
254 * @param string $imagename the pathname of the image
255 * @param string $component full plugin name (aka component) or 'theme'
258 public function pix_url($imagename, $component = 'moodle') {
259 return $this->page->theme->pix_url($imagename, $component);
265 * Basis for all plugin renderers.
267 * @copyright Petr Skoda (skodak)
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
273 class plugin_renderer_base extends renderer_base {
276 * @var renderer_base|core_renderer A reference to the current renderer.
277 * The renderer provided here will be determined by the page but will in 90%
278 * of cases by the {@link core_renderer}
283 * Constructor method, calls the parent constructor
285 * @param moodle_page $page
286 * @param string $target one of rendering target constants
288 public function __construct(moodle_page $page, $target) {
289 if (empty($target) && $page->pagelayout === 'maintenance') {
290 // If the page is using the maintenance layout then we're going to force the target to maintenance.
291 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
292 // unavailable for this page layout.
293 $target = RENDERER_TARGET_MAINTENANCE;
295 $this->output = $page->get_renderer('core', null, $target);
296 parent::__construct($page, $target);
300 * Renders the provided widget and returns the HTML to display it.
302 * @param renderable $widget instance with renderable interface
305 public function render(renderable $widget) {
306 $classname = get_class($widget);
308 $classname = preg_replace('/^.*\\\/', '', $classname);
309 // Keep a copy at this point, we may need to look for a deprecated method.
310 $deprecatedmethod = 'render_'.$classname;
311 // Remove _renderable suffixes
312 $classname = preg_replace('/_renderable$/', '', $classname);
314 $rendermethod = 'render_'.$classname;
315 if (method_exists($this, $rendermethod)) {
316 return $this->$rendermethod($widget);
318 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
319 // This is exactly where we don't want to be.
320 // If you have arrived here you have a renderable component within your plugin that has the name
321 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
322 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
323 // and the _renderable suffix now gets removed when looking for a render method.
324 // You need to change your renderers render_blah_renderable to render_blah.
325 // Until you do this it will not be possible for a theme to override the renderer to override your method.
326 // Please do it ASAP.
327 static $debugged = array();
328 if (!isset($debugged[$deprecatedmethod])) {
329 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
330 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
331 $debugged[$deprecatedmethod] = true;
333 return $this->$deprecatedmethod($widget);
335 // pass to core renderer if method not found here
336 return $this->output->render($widget);
340 * Magic method used to pass calls otherwise meant for the standard renderer
341 * to it to ensure we don't go causing unnecessary grief.
343 * @param string $method
344 * @param array $arguments
347 public function __call($method, $arguments) {
348 if (method_exists('renderer_base', $method)) {
349 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
351 if (method_exists($this->output, $method)) {
352 return call_user_func_array(array($this->output, $method), $arguments);
354 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
361 * The standard implementation of the core_renderer interface.
363 * @copyright 2009 Tim Hunt
364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
369 class core_renderer extends renderer_base {
371 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
372 * in layout files instead.
374 * @var string used in {@link core_renderer::header()}.
376 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
379 * @var string Used to pass information from {@link core_renderer::doctype()} to
380 * {@link core_renderer::standard_head_html()}.
382 protected $contenttype;
385 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
386 * with {@link core_renderer::header()}.
388 protected $metarefreshtag = '';
391 * @var string Unique token for the closing HTML
393 protected $unique_end_html_token;
396 * @var string Unique token for performance information
398 protected $unique_performance_info_token;
401 * @var string Unique token for the main content.
403 protected $unique_main_content_token;
408 * @param moodle_page $page the page we are doing output for.
409 * @param string $target one of rendering target constants
411 public function __construct(moodle_page $page, $target) {
412 $this->opencontainers = $page->opencontainers;
414 $this->target = $target;
416 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
417 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
418 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
422 * Get the DOCTYPE declaration that should be used with this page. Designed to
423 * be called in theme layout.php files.
425 * @return string the DOCTYPE declaration that should be used.
427 public function doctype() {
428 if ($this->page->theme->doctype === 'html5') {
429 $this->contenttype = 'text/html; charset=utf-8';
430 return "<!DOCTYPE html>\n";
432 } else if ($this->page->theme->doctype === 'xhtml5') {
433 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
434 return "<!DOCTYPE html>\n";
438 $this->contenttype = 'text/html; charset=utf-8';
439 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
444 * The attributes that should be added to the <html> tag. Designed to
445 * be called in theme layout.php files.
447 * @return string HTML fragment.
449 public function htmlattributes() {
450 $return = get_html_lang(true);
451 if ($this->page->theme->doctype !== 'html5') {
452 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
458 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
459 * that should be included in the <head> tag. Designed to be called in theme
462 * @return string HTML fragment.
464 public function standard_head_html() {
465 global $CFG, $SESSION;
467 // Before we output any content, we need to ensure that certain
468 // page components are set up.
470 // Blocks must be set up early as they may require javascript which
471 // has to be included in the page header before output is created.
472 foreach ($this->page->blocks->get_regions() as $region) {
473 $this->page->blocks->ensure_content_created($region, $this);
477 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
478 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
479 // This is only set by the {@link redirect()} method
480 $output .= $this->metarefreshtag;
482 // Check if a periodic refresh delay has been set and make sure we arn't
483 // already meta refreshing
484 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
485 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
488 // flow player embedding support
489 $this->page->requires->js_function_call('M.util.load_flowplayer');
491 // Set up help link popups for all links with the helptooltip class
492 $this->page->requires->js_init_call('M.util.help_popups.setup');
494 // Setup help icon overlays.
495 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
496 $this->page->requires->strings_for_js(array(
501 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
503 $focus = $this->page->focuscontrol;
504 if (!empty($focus)) {
505 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
506 // This is a horrifically bad way to handle focus but it is passed in
507 // through messy formslib::moodleform
508 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
509 } else if (strpos($focus, '.')!==false) {
510 // Old style of focus, bad way to do it
511 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);
512 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
514 // Focus element with given id
515 $this->page->requires->js_function_call('focuscontrol', array($focus));
519 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
520 // any other custom CSS can not be overridden via themes and is highly discouraged
521 $urls = $this->page->theme->css_urls($this->page);
522 foreach ($urls as $url) {
523 $this->page->requires->css_theme($url);
526 // Get the theme javascript head and footer
527 if ($jsurl = $this->page->theme->javascript_url(true)) {
528 $this->page->requires->js($jsurl, true);
530 if ($jsurl = $this->page->theme->javascript_url(false)) {
531 $this->page->requires->js($jsurl);
534 // Get any HTML from the page_requirements_manager.
535 $output .= $this->page->requires->get_head_code($this->page, $this);
537 // List alternate versions.
538 foreach ($this->page->alternateversions as $type => $alt) {
539 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
540 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
543 if (!empty($CFG->additionalhtmlhead)) {
544 $output .= "\n".$CFG->additionalhtmlhead;
551 * The standard tags (typically skip links) that should be output just inside
552 * the start of the <body> tag. Designed to be called in theme layout.php files.
554 * @return string HTML fragment.
556 public function standard_top_of_body_html() {
558 $output = $this->page->requires->get_top_of_body_code();
559 if (!empty($CFG->additionalhtmltopofbody)) {
560 $output .= "\n".$CFG->additionalhtmltopofbody;
562 $output .= $this->maintenance_warning();
567 * Scheduled maintenance warning message.
569 * Note: This is a nasty hack to display maintenance notice, this should be moved
570 * to some general notification area once we have it.
574 public function maintenance_warning() {
578 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
579 $timeleft = $CFG->maintenance_later - time();
580 // If timeleft less than 30 sec, set the class on block to error to highlight.
581 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
582 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
584 $a->min = (int)($timeleft/60);
585 $a->sec = (int)($timeleft % 60);
586 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
587 $output .= $this->box_end();
588 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
589 array(array('timeleftinsec' => $timeleft)));
590 $this->page->requires->strings_for_js(
591 array('maintenancemodeisscheduled', 'sitemaintenance'),
598 * The standard tags (typically performance information and validation links,
599 * if we are in developer debug mode) that should be output in the footer area
600 * of the page. Designed to be called in theme layout.php files.
602 * @return string HTML fragment.
604 public function standard_footer_html() {
605 global $CFG, $SCRIPT;
607 if (during_initial_install()) {
608 // Debugging info can not work before install is finished,
609 // in any case we do not want any links during installation!
613 // This function is normally called from a layout.php file in {@link core_renderer::header()}
614 // but some of the content won't be known until later, so we return a placeholder
615 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
616 $output = $this->unique_performance_info_token;
617 if ($this->page->devicetypeinuse == 'legacy') {
618 // The legacy theme is in use print the notification
619 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
622 // Get links to switch device types (only shown for users not on a default device)
623 $output .= $this->theme_switch_links();
625 if (!empty($CFG->debugpageinfo)) {
626 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
628 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
629 // Add link to profiling report if necessary
630 if (function_exists('profiling_is_running') && profiling_is_running()) {
631 $txt = get_string('profiledscript', 'admin');
632 $title = get_string('profiledscriptview', 'admin');
633 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
634 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
635 $output .= '<div class="profilingfooter">' . $link . '</div>';
637 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
638 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
639 $output .= '<div class="purgecaches">' .
640 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
642 if (!empty($CFG->debugvalidators)) {
643 // 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
644 $output .= '<div class="validators"><ul>
645 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
646 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
647 <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>
654 * Returns standard main content placeholder.
655 * Designed to be called in theme layout.php files.
657 * @return string HTML fragment.
659 public function main_content() {
660 // This is here because it is the only place we can inject the "main" role over the entire main content area
661 // without requiring all theme's to manually do it, and without creating yet another thing people need to
662 // remember in the theme.
663 // This is an unfortunate hack. DO NO EVER add anything more here.
664 // DO NOT add classes.
666 return '<div role="main">'.$this->unique_main_content_token.'</div>';
670 * The standard tags (typically script tags that are not needed earlier) that
671 * should be output after everything else. Designed to be called in theme layout.php files.
673 * @return string HTML fragment.
675 public function standard_end_of_body_html() {
678 // This function is normally called from a layout.php file in {@link core_renderer::header()}
679 // but some of the content won't be known until later, so we return a placeholder
680 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
682 if (!empty($CFG->additionalhtmlfooter)) {
683 $output .= "\n".$CFG->additionalhtmlfooter;
685 $output .= $this->unique_end_html_token;
690 * Return the standard string that says whether you are logged in (and switched
691 * roles/logged in as another user).
692 * @param bool $withlinks if false, then don't include any links in the HTML produced.
693 * If not set, the default is the nologinlinks option from the theme config.php file,
694 * and if that is not set, then links are included.
695 * @return string HTML fragment.
697 public function login_info($withlinks = null) {
698 global $USER, $CFG, $DB, $SESSION;
700 if (during_initial_install()) {
704 if (is_null($withlinks)) {
705 $withlinks = empty($this->page->layout_options['nologinlinks']);
708 $course = $this->page->course;
709 if (\core\session\manager::is_loggedinas()) {
710 $realuser = \core\session\manager::get_realuser();
711 $fullname = fullname($realuser, true);
713 $loginastitle = get_string('loginas');
714 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
715 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
717 $realuserinfo = " [$fullname] ";
723 $loginpage = $this->is_login_page();
724 $loginurl = get_login_url();
726 if (empty($course->id)) {
727 // $course->id is not defined during installation
729 } else if (isloggedin()) {
730 $context = context_course::instance($course->id);
732 $fullname = fullname($USER, true);
733 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
735 $linktitle = get_string('viewprofile');
736 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
738 $username = $fullname;
740 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
742 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
744 $username .= " from {$idprovider->name}";
748 $loggedinas = $realuserinfo.get_string('loggedinasguest');
749 if (!$loginpage && $withlinks) {
750 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
752 } else if (is_role_switched($course->id)) { // Has switched roles
754 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
755 $rolename = ': '.role_get_name($role, $context);
757 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
759 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
760 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
763 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
765 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
769 $loggedinas = get_string('loggedinnot', 'moodle');
770 if (!$loginpage && $withlinks) {
771 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
775 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
777 if (isset($SESSION->justloggedin)) {
778 unset($SESSION->justloggedin);
779 if (!empty($CFG->displayloginfailures)) {
780 if (!isguestuser()) {
781 // Include this file only when required.
782 require_once($CFG->dirroot . '/user/lib.php');
783 if ($count = user_count_login_failures($USER)) {
784 $loggedinas .= '<div class="loginfailures">';
786 $a->attempts = $count;
787 $loggedinas .= get_string('failedloginattempts', '', $a);
788 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
789 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
790 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
792 $loggedinas .= '</div>';
802 * Check whether the current page is a login page.
807 protected function is_login_page() {
808 // This is a real bit of a hack, but its a rarety that we need to do something like this.
809 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
810 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
812 $this->page->url->out_as_local_url(false, array()),
815 '/login/forgot_password.php',
821 * Return the 'back' link that normally appears in the footer.
823 * @return string HTML fragment.
825 public function home_link() {
828 if ($this->page->pagetype == 'site-index') {
829 // Special case for site home page - please do not remove
830 return '<div class="sitelink">' .
831 '<a title="Moodle" href="http://moodle.org/">' .
832 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
834 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
835 // Special case for during install/upgrade.
836 return '<div class="sitelink">'.
837 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
838 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
840 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
841 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
842 get_string('home') . '</a></div>';
845 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
846 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
851 * Redirects the user by any means possible given the current state
853 * This function should not be called directly, it should always be called using
854 * the redirect function in lib/weblib.php
856 * The redirect function should really only be called before page output has started
857 * however it will allow itself to be called during the state STATE_IN_BODY
859 * @param string $encodedurl The URL to send to encoded if required
860 * @param string $message The message to display to the user if any
861 * @param int $delay The delay before redirecting a user, if $message has been
862 * set this is a requirement and defaults to 3, set to 0 no delay
863 * @param boolean $debugdisableredirect this redirect has been disabled for
864 * debugging purposes. Display a message that explains, and don't
865 * trigger the redirect.
866 * @return string The HTML to display to the user before dying, may contain
867 * meta refresh, javascript refresh, and may have set header redirects
869 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
871 $url = str_replace('&', '&', $encodedurl);
873 switch ($this->page->state) {
874 case moodle_page::STATE_BEFORE_HEADER :
875 // No output yet it is safe to delivery the full arsenal of redirect methods
876 if (!$debugdisableredirect) {
877 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
878 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
879 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
881 $output = $this->header();
883 case moodle_page::STATE_PRINTING_HEADER :
884 // We should hopefully never get here
885 throw new coding_exception('You cannot redirect while printing the page header');
887 case moodle_page::STATE_IN_BODY :
888 // We really shouldn't be here but we can deal with this
889 debugging("You should really redirect before you start page output");
890 if (!$debugdisableredirect) {
891 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
893 $output = $this->opencontainers->pop_all_but_last();
895 case moodle_page::STATE_DONE :
896 // Too late to be calling redirect now
897 throw new coding_exception('You cannot redirect after the entire page has been generated');
900 $output .= $this->notification($message, 'redirectmessage');
901 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
902 if ($debugdisableredirect) {
903 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
905 $output .= $this->footer();
910 * Start output by sending the HTTP headers, and printing the HTML <head>
911 * and the start of the <body>.
913 * To control what is printed, you should set properties on $PAGE. If you
914 * are familiar with the old {@link print_header()} function from Moodle 1.9
915 * you will find that there are properties on $PAGE that correspond to most
916 * of the old parameters to could be passed to print_header.
918 * Not that, in due course, the remaining $navigation, $menu parameters here
919 * will be replaced by more properties of $PAGE, but that is still to do.
921 * @return string HTML that you must output this, preferably immediately.
923 public function header() {
926 if (\core\session\manager::is_loggedinas()) {
927 $this->page->add_body_class('userloggedinas');
930 // If the user is logged in, and we're not in initial install,
931 // check to see if the user is role-switched and add the appropriate
932 // CSS class to the body element.
933 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
934 $this->page->add_body_class('userswitchedrole');
937 // Give themes a chance to init/alter the page object.
938 $this->page->theme->init_page($this->page);
940 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
942 // Find the appropriate page layout file, based on $this->page->pagelayout.
943 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
944 // Render the layout using the layout file.
945 $rendered = $this->render_page_layout($layoutfile);
947 // Slice the rendered output into header and footer.
948 $cutpos = strpos($rendered, $this->unique_main_content_token);
949 if ($cutpos === false) {
950 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
951 $token = self::MAIN_CONTENT_TOKEN;
953 $token = $this->unique_main_content_token;
956 if ($cutpos === false) {
957 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.');
959 $header = substr($rendered, 0, $cutpos);
960 $footer = substr($rendered, $cutpos + strlen($token));
962 if (empty($this->contenttype)) {
963 debugging('The page layout file did not call $OUTPUT->doctype()');
964 $header = $this->doctype() . $header;
967 // If this theme version is below 2.4 release and this is a course view page
968 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
969 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
970 // check if course content header/footer have not been output during render of theme layout
971 $coursecontentheader = $this->course_content_header(true);
972 $coursecontentfooter = $this->course_content_footer(true);
973 if (!empty($coursecontentheader)) {
974 // display debug message and add header and footer right above and below main content
975 // Please note that course header and footer (to be displayed above and below the whole page)
976 // are not displayed in this case at all.
977 // Besides the content header and footer are not displayed on any other course page
978 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);
979 $header .= $coursecontentheader;
980 $footer = $coursecontentfooter. $footer;
984 send_headers($this->contenttype, $this->page->cacheable);
986 $this->opencontainers->push('header/footer', $footer);
987 $this->page->set_state(moodle_page::STATE_IN_BODY);
989 return $header . $this->skip_link_target('maincontent');
993 * Renders and outputs the page layout file.
995 * This is done by preparing the normal globals available to a script, and
996 * then including the layout file provided by the current theme for the
999 * @param string $layoutfile The name of the layout file
1000 * @return string HTML code
1002 protected function render_page_layout($layoutfile) {
1003 global $CFG, $SITE, $USER;
1004 // The next lines are a bit tricky. The point is, here we are in a method
1005 // of a renderer class, and this object may, or may not, be the same as
1006 // the global $OUTPUT object. When rendering the page layout file, we want to use
1007 // this object. However, people writing Moodle code expect the current
1008 // renderer to be called $OUTPUT, not $this, so define a variable called
1009 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1011 $PAGE = $this->page;
1012 $COURSE = $this->page->course;
1015 include($layoutfile);
1016 $rendered = ob_get_contents();
1022 * Outputs the page's footer
1024 * @return string HTML fragment
1026 public function footer() {
1029 $output = $this->container_end_all(true);
1031 $footer = $this->opencontainers->pop('header/footer');
1033 if (debugging() and $DB and $DB->is_transaction_started()) {
1034 // TODO: MDL-20625 print warning - transaction will be rolled back
1037 // Provide some performance info if required
1038 $performanceinfo = '';
1039 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1040 $perf = get_performance_info();
1041 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1042 $performanceinfo = $perf['html'];
1046 // We always want performance data when running a performance test, even if the user is redirected to another page.
1047 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1048 $footer = $this->unique_performance_info_token . $footer;
1050 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1052 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1054 $this->page->set_state(moodle_page::STATE_DONE);
1056 return $output . $footer;
1060 * Close all but the last open container. This is useful in places like error
1061 * handling, where you want to close all the open containers (apart from <body>)
1062 * before outputting the error message.
1064 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1065 * developer debug warning if it isn't.
1066 * @return string the HTML required to close any open containers inside <body>.
1068 public function container_end_all($shouldbenone = false) {
1069 return $this->opencontainers->pop_all_but_last($shouldbenone);
1073 * Returns course-specific information to be output immediately above content on any course page
1074 * (for the current course)
1076 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1079 public function course_content_header($onlyifnotcalledbefore = false) {
1081 if ($this->page->course->id == SITEID) {
1082 // return immediately and do not include /course/lib.php if not necessary
1085 static $functioncalled = false;
1086 if ($functioncalled && $onlyifnotcalledbefore) {
1087 // we have already output the content header
1090 require_once($CFG->dirroot.'/course/lib.php');
1091 $functioncalled = true;
1092 $courseformat = course_get_format($this->page->course);
1093 if (($obj = $courseformat->course_content_header()) !== null) {
1094 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1100 * Returns course-specific information to be output immediately below content on any course page
1101 * (for the current course)
1103 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1106 public function course_content_footer($onlyifnotcalledbefore = false) {
1108 if ($this->page->course->id == SITEID) {
1109 // return immediately and do not include /course/lib.php if not necessary
1112 static $functioncalled = false;
1113 if ($functioncalled && $onlyifnotcalledbefore) {
1114 // we have already output the content footer
1117 $functioncalled = true;
1118 require_once($CFG->dirroot.'/course/lib.php');
1119 $courseformat = course_get_format($this->page->course);
1120 if (($obj = $courseformat->course_content_footer()) !== null) {
1121 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1127 * Returns course-specific information to be output on any course page in the header area
1128 * (for the current course)
1132 public function course_header() {
1134 if ($this->page->course->id == SITEID) {
1135 // return immediately and do not include /course/lib.php if not necessary
1138 require_once($CFG->dirroot.'/course/lib.php');
1139 $courseformat = course_get_format($this->page->course);
1140 if (($obj = $courseformat->course_header()) !== null) {
1141 return $courseformat->get_renderer($this->page)->render($obj);
1147 * Returns course-specific information to be output on any course page in the footer area
1148 * (for the current course)
1152 public function course_footer() {
1154 if ($this->page->course->id == SITEID) {
1155 // return immediately and do not include /course/lib.php if not necessary
1158 require_once($CFG->dirroot.'/course/lib.php');
1159 $courseformat = course_get_format($this->page->course);
1160 if (($obj = $courseformat->course_footer()) !== null) {
1161 return $courseformat->get_renderer($this->page)->render($obj);
1167 * Returns lang menu or '', this method also checks forcing of languages in courses.
1169 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1171 * @return string The lang menu HTML or empty string
1173 public function lang_menu() {
1176 if (empty($CFG->langmenu)) {
1180 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1181 // do not show lang menu if language forced
1185 $currlang = current_language();
1186 $langs = get_string_manager()->get_list_of_translations();
1188 if (count($langs) < 2) {
1192 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1193 $s->label = get_accesshide(get_string('language'));
1194 $s->class = 'langmenu';
1195 return $this->render($s);
1199 * Output the row of editing icons for a block, as defined by the controls array.
1201 * @param array $controls an array like {@link block_contents::$controls}.
1202 * @param string $blockid The ID given to the block.
1203 * @return string HTML fragment.
1205 public function block_controls($actions, $blockid = null) {
1207 if (empty($actions)) {
1210 $menu = new action_menu($actions);
1211 if ($blockid !== null) {
1212 $menu->set_owner_selector('#'.$blockid);
1214 $menu->set_constraint('.block-region');
1215 $menu->attributes['class'] .= ' block-control-actions commands';
1216 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1217 $menu->do_not_enhance();
1219 return $this->render($menu);
1223 * Renders an action menu component.
1226 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1227 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1229 * @param action_menu $menu
1230 * @return string HTML
1232 public function render_action_menu(action_menu $menu) {
1233 $menu->initialise_js($this->page);
1235 $output = html_writer::start_tag('div', $menu->attributes);
1236 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1237 foreach ($menu->get_primary_actions($this) as $action) {
1238 if ($action instanceof renderable) {
1239 $content = $this->render($action);
1243 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1245 $output .= html_writer::end_tag('ul');
1246 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1247 foreach ($menu->get_secondary_actions() as $action) {
1248 if ($action instanceof renderable) {
1249 $content = $this->render($action);
1253 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1255 $output .= html_writer::end_tag('ul');
1256 $output .= html_writer::end_tag('div');
1261 * Renders an action_menu_link item.
1263 * @param action_menu_link $action
1264 * @return string HTML fragment
1266 protected function render_action_menu_link(action_menu_link $action) {
1267 static $actioncount = 0;
1272 if (!$action->icon || $action->primary === false) {
1273 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1274 if ($action->text instanceof renderable) {
1275 $text .= $this->render($action->text);
1277 $text .= $action->text;
1278 $comparetoalt = (string)$action->text;
1280 $text .= html_writer::end_tag('span');
1284 if ($action->icon) {
1285 $icon = $action->icon;
1286 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1287 $action->attributes['title'] = $action->text;
1289 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1290 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1291 $icon->attributes['alt'] = '';
1293 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1294 unset($icon->attributes['title']);
1297 $icon = $this->render($icon);
1300 // A disabled link is rendered as formatted text.
1301 if (!empty($action->attributes['disabled'])) {
1302 // Do not use div here due to nesting restriction in xhtml strict.
1303 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1306 $attributes = $action->attributes;
1307 unset($action->attributes['disabled']);
1308 $attributes['href'] = $action->url;
1310 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1313 return html_writer::tag('a', $icon.$text, $attributes);
1317 * Renders a primary action_menu_filler item.
1319 * @param action_menu_link_filler $action
1320 * @return string HTML fragment
1322 protected function render_action_menu_filler(action_menu_filler $action) {
1323 return html_writer::span(' ', 'filler');
1327 * Renders a primary action_menu_link item.
1329 * @param action_menu_link_primary $action
1330 * @return string HTML fragment
1332 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1333 return $this->render_action_menu_link($action);
1337 * Renders a secondary action_menu_link item.
1339 * @param action_menu_link_secondary $action
1340 * @return string HTML fragment
1342 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1343 return $this->render_action_menu_link($action);
1347 * Prints a nice side block with an optional header.
1349 * The content is described
1350 * by a {@link core_renderer::block_contents} object.
1352 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1353 * <div class="header"></div>
1354 * <div class="content">
1356 * <div class="footer">
1359 * <div class="annotation">
1363 * @param block_contents $bc HTML for the content
1364 * @param string $region the region the block is appearing in.
1365 * @return string the HTML to be output.
1367 public function block(block_contents $bc, $region) {
1368 $bc = clone($bc); // Avoid messing up the object passed in.
1369 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1370 $bc->collapsible = block_contents::NOT_HIDEABLE;
1372 if (!empty($bc->blockinstanceid)) {
1373 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1375 $skiptitle = strip_tags($bc->title);
1376 if ($bc->blockinstanceid && !empty($skiptitle)) {
1377 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1378 } else if (!empty($bc->arialabel)) {
1379 $bc->attributes['aria-label'] = $bc->arialabel;
1381 if ($bc->dockable) {
1382 $bc->attributes['data-dockable'] = 1;
1384 if ($bc->collapsible == block_contents::HIDDEN) {
1385 $bc->add_class('hidden');
1387 if (!empty($bc->controls)) {
1388 $bc->add_class('block_with_controls');
1392 if (empty($skiptitle)) {
1396 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1397 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1400 $output .= html_writer::start_tag('div', $bc->attributes);
1402 $output .= $this->block_header($bc);
1403 $output .= $this->block_content($bc);
1405 $output .= html_writer::end_tag('div');
1407 $output .= $this->block_annotation($bc);
1409 $output .= $skipdest;
1411 $this->init_block_hider_js($bc);
1416 * Produces a header for a block
1418 * @param block_contents $bc
1421 protected function block_header(block_contents $bc) {
1425 $attributes = array();
1426 if ($bc->blockinstanceid) {
1427 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1429 $title = html_writer::tag('h2', $bc->title, $attributes);
1433 if (isset($bc->attributes['id'])) {
1434 $blockid = $bc->attributes['id'];
1436 $controlshtml = $this->block_controls($bc->controls, $blockid);
1439 if ($title || $controlshtml) {
1440 $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'));
1446 * Produces the content area for a block
1448 * @param block_contents $bc
1451 protected function block_content(block_contents $bc) {
1452 $output = html_writer::start_tag('div', array('class' => 'content'));
1453 if (!$bc->title && !$this->block_controls($bc->controls)) {
1454 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1456 $output .= $bc->content;
1457 $output .= $this->block_footer($bc);
1458 $output .= html_writer::end_tag('div');
1464 * Produces the footer for a block
1466 * @param block_contents $bc
1469 protected function block_footer(block_contents $bc) {
1472 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1478 * Produces the annotation for a block
1480 * @param block_contents $bc
1483 protected function block_annotation(block_contents $bc) {
1485 if ($bc->annotation) {
1486 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1492 * Calls the JS require function to hide a block.
1494 * @param block_contents $bc A block_contents object
1496 protected function init_block_hider_js(block_contents $bc) {
1497 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1498 $config = new stdClass;
1499 $config->id = $bc->attributes['id'];
1500 $config->title = strip_tags($bc->title);
1501 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1502 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1503 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1505 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1506 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1511 * Render the contents of a block_list.
1513 * @param array $icons the icon for each item.
1514 * @param array $items the content of each item.
1515 * @return string HTML
1517 public function list_block_contents($icons, $items) {
1520 foreach ($items as $key => $string) {
1521 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1522 if (!empty($icons[$key])) { //test if the content has an assigned icon
1523 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1525 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1526 $item .= html_writer::end_tag('li');
1528 $row = 1 - $row; // Flip even/odd.
1530 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1534 * Output all the blocks in a particular region.
1536 * @param string $region the name of a region on this page.
1537 * @return string the HTML to be output.
1539 public function blocks_for_region($region) {
1540 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1541 $blocks = $this->page->blocks->get_blocks_for_region($region);
1544 foreach ($blocks as $block) {
1545 $zones[] = $block->title;
1549 foreach ($blockcontents as $bc) {
1550 if ($bc instanceof block_contents) {
1551 $output .= $this->block($bc, $region);
1552 $lastblock = $bc->title;
1553 } else if ($bc instanceof block_move_target) {
1554 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1556 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1563 * Output a place where the block that is currently being moved can be dropped.
1565 * @param block_move_target $target with the necessary details.
1566 * @param array $zones array of areas where the block can be moved to
1567 * @param string $previous the block located before the area currently being rendered.
1568 * @param string $region the name of the region
1569 * @return string the HTML to be output.
1571 public function block_move_target($target, $zones, $previous, $region) {
1572 if ($previous == null) {
1573 if (empty($zones)) {
1574 // There are no zones, probably because there are no blocks.
1575 $regions = $this->page->theme->get_all_block_regions();
1576 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1578 $position = get_string('moveblockbefore', 'block', $zones[0]);
1581 $position = get_string('moveblockafter', 'block', $previous);
1583 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1587 * Renders a special html link with attached action
1589 * Theme developers: DO NOT OVERRIDE! Please override function
1590 * {@link core_renderer::render_action_link()} instead.
1592 * @param string|moodle_url $url
1593 * @param string $text HTML fragment
1594 * @param component_action $action
1595 * @param array $attributes associative array of html link attributes + disabled
1596 * @param pix_icon optional pix icon to render with the link
1597 * @return string HTML fragment
1599 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1600 if (!($url instanceof moodle_url)) {
1601 $url = new moodle_url($url);
1603 $link = new action_link($url, $text, $action, $attributes, $icon);
1605 return $this->render($link);
1609 * Renders an action_link object.
1611 * The provided link is renderer and the HTML returned. At the same time the
1612 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1614 * @param action_link $link
1615 * @return string HTML fragment
1617 protected function render_action_link(action_link $link) {
1622 $text .= $this->render($link->icon);
1625 if ($link->text instanceof renderable) {
1626 $text .= $this->render($link->text);
1628 $text .= $link->text;
1631 // A disabled link is rendered as formatted text
1632 if (!empty($link->attributes['disabled'])) {
1633 // do not use div here due to nesting restriction in xhtml strict
1634 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1637 $attributes = $link->attributes;
1638 unset($link->attributes['disabled']);
1639 $attributes['href'] = $link->url;
1641 if ($link->actions) {
1642 if (empty($attributes['id'])) {
1643 $id = html_writer::random_id('action_link');
1644 $attributes['id'] = $id;
1646 $id = $attributes['id'];
1648 foreach ($link->actions as $action) {
1649 $this->add_action_handler($action, $id);
1653 return html_writer::tag('a', $text, $attributes);
1658 * Renders an action_icon.
1660 * This function uses the {@link core_renderer::action_link()} method for the
1661 * most part. What it does different is prepare the icon as HTML and use it
1664 * Theme developers: If you want to change how action links and/or icons are rendered,
1665 * consider overriding function {@link core_renderer::render_action_link()} and
1666 * {@link core_renderer::render_pix_icon()}.
1668 * @param string|moodle_url $url A string URL or moodel_url
1669 * @param pix_icon $pixicon
1670 * @param component_action $action
1671 * @param array $attributes associative array of html link attributes + disabled
1672 * @param bool $linktext show title next to image in link
1673 * @return string HTML fragment
1675 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1676 if (!($url instanceof moodle_url)) {
1677 $url = new moodle_url($url);
1679 $attributes = (array)$attributes;
1681 if (empty($attributes['class'])) {
1682 // let ppl override the class via $options
1683 $attributes['class'] = 'action-icon';
1686 $icon = $this->render($pixicon);
1689 $text = $pixicon->attributes['alt'];
1694 return $this->action_link($url, $text.$icon, $action, $attributes);
1698 * Print a message along with button choices for Continue/Cancel
1700 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1702 * @param string $message The question to ask the user
1703 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1704 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1705 * @return string HTML fragment
1707 public function confirm($message, $continue, $cancel) {
1708 if ($continue instanceof single_button) {
1710 } else if (is_string($continue)) {
1711 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1712 } else if ($continue instanceof moodle_url) {
1713 $continue = new single_button($continue, get_string('continue'), 'post');
1715 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1718 if ($cancel instanceof single_button) {
1720 } else if (is_string($cancel)) {
1721 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1722 } else if ($cancel instanceof moodle_url) {
1723 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1725 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1728 $output = $this->box_start('generalbox', 'notice');
1729 $output .= html_writer::tag('p', $message);
1730 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1731 $output .= $this->box_end();
1736 * Returns a form with a single button.
1738 * Theme developers: DO NOT OVERRIDE! Please override function
1739 * {@link core_renderer::render_single_button()} instead.
1741 * @param string|moodle_url $url
1742 * @param string $label button text
1743 * @param string $method get or post submit method
1744 * @param array $options associative array {disabled, title, etc.}
1745 * @return string HTML fragment
1747 public function single_button($url, $label, $method='post', array $options=null) {
1748 if (!($url instanceof moodle_url)) {
1749 $url = new moodle_url($url);
1751 $button = new single_button($url, $label, $method);
1753 foreach ((array)$options as $key=>$value) {
1754 if (array_key_exists($key, $button)) {
1755 $button->$key = $value;
1759 return $this->render($button);
1763 * Renders a single button widget.
1765 * This will return HTML to display a form containing a single button.
1767 * @param single_button $button
1768 * @return string HTML fragment
1770 protected function render_single_button(single_button $button) {
1771 $attributes = array('type' => 'submit',
1772 'value' => $button->label,
1773 'disabled' => $button->disabled ? 'disabled' : null,
1774 'title' => $button->tooltip);
1776 if ($button->actions) {
1777 $id = html_writer::random_id('single_button');
1778 $attributes['id'] = $id;
1779 foreach ($button->actions as $action) {
1780 $this->add_action_handler($action, $id);
1784 // first the input element
1785 $output = html_writer::empty_tag('input', $attributes);
1787 // then hidden fields
1788 $params = $button->url->params();
1789 if ($button->method === 'post') {
1790 $params['sesskey'] = sesskey();
1792 foreach ($params as $var => $val) {
1793 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1796 // then div wrapper for xhtml strictness
1797 $output = html_writer::tag('div', $output);
1799 // now the form itself around it
1800 if ($button->method === 'get') {
1801 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1803 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1806 $url = '#'; // there has to be always some action
1808 $attributes = array('method' => $button->method,
1810 'id' => $button->formid);
1811 $output = html_writer::tag('form', $output, $attributes);
1813 // and finally one more wrapper with class
1814 return html_writer::tag('div', $output, array('class' => $button->class));
1818 * Returns a form with a single select widget.
1820 * Theme developers: DO NOT OVERRIDE! Please override function
1821 * {@link core_renderer::render_single_select()} instead.
1823 * @param moodle_url $url form action target, includes hidden fields
1824 * @param string $name name of selection field - the changing parameter in url
1825 * @param array $options list of options
1826 * @param string $selected selected element
1827 * @param array $nothing
1828 * @param string $formid
1829 * @param array $attributes other attributes for the single select
1830 * @return string HTML fragment
1832 public function single_select($url, $name, array $options, $selected = '',
1833 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1834 if (!($url instanceof moodle_url)) {
1835 $url = new moodle_url($url);
1837 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1839 if (array_key_exists('label', $attributes)) {
1840 $select->set_label($attributes['label']);
1841 unset($attributes['label']);
1843 $select->attributes = $attributes;
1845 return $this->render($select);
1849 * Internal implementation of single_select rendering
1851 * @param single_select $select
1852 * @return string HTML fragment
1854 protected function render_single_select(single_select $select) {
1855 $select = clone($select);
1856 if (empty($select->formid)) {
1857 $select->formid = html_writer::random_id('single_select_f');
1861 $params = $select->url->params();
1862 if ($select->method === 'post') {
1863 $params['sesskey'] = sesskey();
1865 foreach ($params as $name=>$value) {
1866 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1869 if (empty($select->attributes['id'])) {
1870 $select->attributes['id'] = html_writer::random_id('single_select');
1873 if ($select->disabled) {
1874 $select->attributes['disabled'] = 'disabled';
1877 if ($select->tooltip) {
1878 $select->attributes['title'] = $select->tooltip;
1881 $select->attributes['class'] = 'autosubmit';
1882 if ($select->class) {
1883 $select->attributes['class'] .= ' ' . $select->class;
1886 if ($select->label) {
1887 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1890 if ($select->helpicon instanceof help_icon) {
1891 $output .= $this->render($select->helpicon);
1893 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1895 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1896 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1898 $nothing = empty($select->nothing) ? false : key($select->nothing);
1899 $this->page->requires->yui_module('moodle-core-formautosubmit',
1900 'M.core.init_formautosubmit',
1901 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1904 // then div wrapper for xhtml strictness
1905 $output = html_writer::tag('div', $output);
1907 // now the form itself around it
1908 if ($select->method === 'get') {
1909 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1911 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1913 $formattributes = array('method' => $select->method,
1915 'id' => $select->formid);
1916 $output = html_writer::tag('form', $output, $formattributes);
1918 // and finally one more wrapper with class
1919 return html_writer::tag('div', $output, array('class' => $select->class));
1923 * Returns a form with a url select widget.
1925 * Theme developers: DO NOT OVERRIDE! Please override function
1926 * {@link core_renderer::render_url_select()} instead.
1928 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1929 * @param string $selected selected element
1930 * @param array $nothing
1931 * @param string $formid
1932 * @return string HTML fragment
1934 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1935 $select = new url_select($urls, $selected, $nothing, $formid);
1936 return $this->render($select);
1940 * Internal implementation of url_select rendering
1942 * @param url_select $select
1943 * @return string HTML fragment
1945 protected function render_url_select(url_select $select) {
1948 $select = clone($select);
1949 if (empty($select->formid)) {
1950 $select->formid = html_writer::random_id('url_select_f');
1953 if (empty($select->attributes['id'])) {
1954 $select->attributes['id'] = html_writer::random_id('url_select');
1957 if ($select->disabled) {
1958 $select->attributes['disabled'] = 'disabled';
1961 if ($select->tooltip) {
1962 $select->attributes['title'] = $select->tooltip;
1967 if ($select->label) {
1968 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1972 if (!$select->showbutton) {
1973 $classes[] = 'autosubmit';
1975 if ($select->class) {
1976 $classes[] = $select->class;
1978 if (count($classes)) {
1979 $select->attributes['class'] = implode(' ', $classes);
1982 if ($select->helpicon instanceof help_icon) {
1983 $output .= $this->render($select->helpicon);
1986 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1987 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1989 foreach ($select->urls as $k=>$v) {
1991 // optgroup structure
1992 foreach ($v as $optgrouptitle => $optgroupoptions) {
1993 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1994 if (empty($optionurl)) {
1995 $safeoptionurl = '';
1996 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1997 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1998 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1999 } else if (strpos($optionurl, '/') !== 0) {
2000 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2003 $safeoptionurl = $optionurl;
2005 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2009 // plain list structure
2011 // nothing selected option
2012 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2013 $k = str_replace($CFG->wwwroot, '', $k);
2014 } else if (strpos($k, '/') !== 0) {
2015 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2021 $selected = $select->selected;
2022 if (!empty($selected)) {
2023 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2024 $selected = str_replace($CFG->wwwroot, '', $selected);
2025 } else if (strpos($selected, '/') !== 0) {
2026 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
2030 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
2031 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
2033 if (!$select->showbutton) {
2034 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
2035 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
2036 $nothing = empty($select->nothing) ? false : key($select->nothing);
2037 $this->page->requires->yui_module('moodle-core-formautosubmit',
2038 'M.core.init_formautosubmit',
2039 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2042 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2045 // then div wrapper for xhtml strictness
2046 $output = html_writer::tag('div', $output);
2048 // now the form itself around it
2049 $formattributes = array('method' => 'post',
2050 'action' => new moodle_url('/course/jumpto.php'),
2051 'id' => $select->formid);
2052 $output = html_writer::tag('form', $output, $formattributes);
2054 // and finally one more wrapper with class
2055 return html_writer::tag('div', $output, array('class' => $select->class));
2059 * Returns a string containing a link to the user documentation.
2060 * Also contains an icon by default. Shown to teachers and admin only.
2062 * @param string $path The page link after doc root and language, no leading slash.
2063 * @param string $text The text to be displayed for the link
2064 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2067 public function doc_link($path, $text = '', $forcepopup = false) {
2070 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2072 $url = new moodle_url(get_docs_url($path));
2074 $attributes = array('href'=>$url);
2075 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2076 $attributes['class'] = 'helplinkpopup';
2079 return html_writer::tag('a', $icon.$text, $attributes);
2083 * Return HTML for a pix_icon.
2085 * Theme developers: DO NOT OVERRIDE! Please override function
2086 * {@link core_renderer::render_pix_icon()} instead.
2088 * @param string $pix short pix name
2089 * @param string $alt mandatory alt attribute
2090 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2091 * @param array $attributes htm lattributes
2092 * @return string HTML fragment
2094 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2095 $icon = new pix_icon($pix, $alt, $component, $attributes);
2096 return $this->render($icon);
2100 * Renders a pix_icon widget and returns the HTML to display it.
2102 * @param pix_icon $icon
2103 * @return string HTML fragment
2105 protected function render_pix_icon(pix_icon $icon) {
2106 $data = $icon->export_for_template($this);
2107 return $this->render_from_template('core/pix_icon', $data);
2111 * Return HTML to display an emoticon icon.
2113 * @param pix_emoticon $emoticon
2114 * @return string HTML fragment
2116 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2117 $attributes = $emoticon->attributes;
2118 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2119 return html_writer::empty_tag('img', $attributes);
2123 * Produces the html that represents this rating in the UI
2125 * @param rating $rating the page object on which this rating will appear
2128 function render_rating(rating $rating) {
2131 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2132 return null;//ratings are turned off
2135 $ratingmanager = new rating_manager();
2136 // Initialise the JavaScript so ratings can be done by AJAX.
2137 $ratingmanager->initialise_rating_javascript($this->page);
2139 $strrate = get_string("rate", "rating");
2140 $ratinghtml = ''; //the string we'll return
2142 // permissions check - can they view the aggregate?
2143 if ($rating->user_can_view_aggregate()) {
2145 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2146 $aggregatestr = $rating->get_aggregate_string();
2148 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2149 if ($rating->count > 0) {
2150 $countstr = "({$rating->count})";
2154 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2156 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2157 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2159 $nonpopuplink = $rating->get_view_ratings_url();
2160 $popuplink = $rating->get_view_ratings_url(true);
2162 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2163 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2165 $ratinghtml .= $aggregatehtml;
2170 // if the item doesn't belong to the current user, the user has permission to rate
2171 // and we're within the assessable period
2172 if ($rating->user_can_rate()) {
2174 $rateurl = $rating->get_rate_url();
2175 $inputs = $rateurl->params();
2177 //start the rating form
2179 'id' => "postrating{$rating->itemid}",
2180 'class' => 'postratingform',
2182 'action' => $rateurl->out_omit_querystring()
2184 $formstart = html_writer::start_tag('form', $formattrs);
2185 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2187 // add the hidden inputs
2188 foreach ($inputs as $name => $value) {
2189 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2190 $formstart .= html_writer::empty_tag('input', $attributes);
2193 if (empty($ratinghtml)) {
2194 $ratinghtml .= $strrate.': ';
2196 $ratinghtml = $formstart.$ratinghtml;
2198 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2199 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2200 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2201 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2203 //output submit button
2204 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2206 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2207 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2209 if (!$rating->settings->scale->isnumeric) {
2210 // If a global scale, try to find current course ID from the context
2211 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2212 $courseid = $coursecontext->instanceid;
2214 $courseid = $rating->settings->scale->courseid;
2216 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2218 $ratinghtml .= html_writer::end_tag('span');
2219 $ratinghtml .= html_writer::end_tag('div');
2220 $ratinghtml .= html_writer::end_tag('form');
2227 * Centered heading with attached help button (same title text)
2228 * and optional icon attached.
2230 * @param string $text A heading text
2231 * @param string $helpidentifier The keyword that defines a help page
2232 * @param string $component component name
2233 * @param string|moodle_url $icon
2234 * @param string $iconalt icon alt text
2235 * @param int $level The level of importance of the heading. Defaulting to 2
2236 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2237 * @return string HTML fragment
2239 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2242 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2246 if ($helpidentifier) {
2247 $help = $this->help_icon($helpidentifier, $component);
2250 return $this->heading($image.$text.$help, $level, $classnames);
2254 * Returns HTML to display a help icon.
2256 * @deprecated since Moodle 2.0
2258 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2259 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2263 * Returns HTML to display a help icon.
2265 * Theme developers: DO NOT OVERRIDE! Please override function
2266 * {@link core_renderer::render_help_icon()} instead.
2268 * @param string $identifier The keyword that defines a help page
2269 * @param string $component component name
2270 * @param string|bool $linktext true means use $title as link text, string means link text value
2271 * @return string HTML fragment
2273 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2274 $icon = new help_icon($identifier, $component);
2275 $icon->diag_strings();
2276 if ($linktext === true) {
2277 $icon->linktext = get_string($icon->identifier, $icon->component);
2278 } else if (!empty($linktext)) {
2279 $icon->linktext = $linktext;
2281 return $this->render($icon);
2285 * Implementation of user image rendering.
2287 * @param help_icon $helpicon A help icon instance
2288 * @return string HTML fragment
2290 protected function render_help_icon(help_icon $helpicon) {
2293 // first get the help image icon
2294 $src = $this->pix_url('help');
2296 $title = get_string($helpicon->identifier, $helpicon->component);
2298 if (empty($helpicon->linktext)) {
2299 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2301 $alt = get_string('helpwiththis');
2304 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2305 $output = html_writer::empty_tag('img', $attributes);
2307 // add the link text if given
2308 if (!empty($helpicon->linktext)) {
2309 // the spacing has to be done through CSS
2310 $output .= $helpicon->linktext;
2313 // now create the link around it - we need https on loginhttps pages
2314 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2316 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2317 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2319 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2320 $output = html_writer::tag('a', $output, $attributes);
2323 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2327 * Returns HTML to display a scale help icon.
2329 * @param int $courseid
2330 * @param stdClass $scale instance
2331 * @return string HTML fragment
2333 public function help_icon_scale($courseid, stdClass $scale) {
2336 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2338 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2340 $scaleid = abs($scale->id);
2342 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2343 $action = new popup_action('click', $link, 'ratingscale');
2345 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2349 * Creates and returns a spacer image with optional line break.
2351 * @param array $attributes Any HTML attributes to add to the spaced.
2352 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2353 * laxy do it with CSS which is a much better solution.
2354 * @return string HTML fragment
2356 public function spacer(array $attributes = null, $br = false) {
2357 $attributes = (array)$attributes;
2358 if (empty($attributes['width'])) {
2359 $attributes['width'] = 1;
2361 if (empty($attributes['height'])) {
2362 $attributes['height'] = 1;
2364 $attributes['class'] = 'spacer';
2366 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2369 $output .= '<br />';
2376 * Returns HTML to display the specified user's avatar.
2378 * User avatar may be obtained in two ways:
2380 * // Option 1: (shortcut for simple cases, preferred way)
2381 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2382 * $OUTPUT->user_picture($user, array('popup'=>true));
2385 * $userpic = new user_picture($user);
2386 * // Set properties of $userpic
2387 * $userpic->popup = true;
2388 * $OUTPUT->render($userpic);
2391 * Theme developers: DO NOT OVERRIDE! Please override function
2392 * {@link core_renderer::render_user_picture()} instead.
2394 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2395 * If any of these are missing, the database is queried. Avoid this
2396 * if at all possible, particularly for reports. It is very bad for performance.
2397 * @param array $options associative array with user picture options, used only if not a user_picture object,
2399 * - courseid=$this->page->course->id (course id of user profile in link)
2400 * - size=35 (size of image)
2401 * - link=true (make image clickable - the link leads to user profile)
2402 * - popup=false (open in popup)
2403 * - alttext=true (add image alt attribute)
2404 * - class = image class attribute (default 'userpicture')
2405 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2406 * @return string HTML fragment
2408 public function user_picture(stdClass $user, array $options = null) {
2409 $userpicture = new user_picture($user);
2410 foreach ((array)$options as $key=>$value) {
2411 if (array_key_exists($key, $userpicture)) {
2412 $userpicture->$key = $value;
2415 return $this->render($userpicture);
2419 * Internal implementation of user image rendering.
2421 * @param user_picture $userpicture
2424 protected function render_user_picture(user_picture $userpicture) {
2427 $user = $userpicture->user;
2429 if ($userpicture->alttext) {
2430 if (!empty($user->imagealt)) {
2431 $alt = $user->imagealt;
2433 $alt = get_string('pictureof', '', fullname($user));
2439 if (empty($userpicture->size)) {
2441 } else if ($userpicture->size === true or $userpicture->size == 1) {
2444 $size = $userpicture->size;
2447 $class = $userpicture->class;
2449 if ($user->picture == 0) {
2450 $class .= ' defaultuserpic';
2453 $src = $userpicture->get_url($this->page, $this);
2455 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2456 if (!$userpicture->visibletoscreenreaders) {
2457 $attributes['role'] = 'presentation';
2460 // get the image html output fisrt
2461 $output = html_writer::empty_tag('img', $attributes);
2463 // then wrap it in link if needed
2464 if (!$userpicture->link) {
2468 if (empty($userpicture->courseid)) {
2469 $courseid = $this->page->course->id;
2471 $courseid = $userpicture->courseid;
2474 if ($courseid == SITEID) {
2475 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2477 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2480 $attributes = array('href'=>$url);
2481 if (!$userpicture->visibletoscreenreaders) {
2482 $attributes['tabindex'] = '-1';
2483 $attributes['aria-hidden'] = 'true';
2486 if ($userpicture->popup) {
2487 $id = html_writer::random_id('userpicture');
2488 $attributes['id'] = $id;
2489 $this->add_action_handler(new popup_action('click', $url), $id);
2492 return html_writer::tag('a', $output, $attributes);
2496 * Internal implementation of file tree viewer items rendering.
2501 public function htmllize_file_tree($dir) {
2502 if (empty($dir['subdirs']) and empty($dir['files'])) {
2506 foreach ($dir['subdirs'] as $subdir) {
2507 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2509 foreach ($dir['files'] as $file) {
2510 $filename = $file->get_filename();
2511 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2519 * Returns HTML to display the file picker
2522 * $OUTPUT->file_picker($options);
2525 * Theme developers: DO NOT OVERRIDE! Please override function
2526 * {@link core_renderer::render_file_picker()} instead.
2528 * @param array $options associative array with file manager options
2532 * client_id=>uniqid(),
2533 * acepted_types=>'*',
2534 * return_types=>FILE_INTERNAL,
2535 * context=>$PAGE->context
2536 * @return string HTML fragment
2538 public function file_picker($options) {
2539 $fp = new file_picker($options);
2540 return $this->render($fp);
2544 * Internal implementation of file picker rendering.
2546 * @param file_picker $fp
2549 public function render_file_picker(file_picker $fp) {
2550 global $CFG, $OUTPUT, $USER;
2551 $options = $fp->options;
2552 $client_id = $options->client_id;
2553 $strsaved = get_string('filesaved', 'repository');
2554 $straddfile = get_string('openpicker', 'repository');
2555 $strloading = get_string('loading', 'repository');
2556 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2557 $strdroptoupload = get_string('droptoupload', 'moodle');
2558 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2560 $currentfile = $options->currentfile;
2561 if (empty($currentfile)) {
2564 $currentfile .= ' - ';
2566 if ($options->maxbytes) {
2567 $size = $options->maxbytes;
2569 $size = get_max_upload_file_size();
2574 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2576 if ($options->buttonname) {
2577 $buttonname = ' name="' . $options->buttonname . '"';
2582 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2585 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2587 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2588 <span> $maxsize </span>
2591 if ($options->env != 'url') {
2593 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2594 <div class="filepicker-filename">
2595 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2596 <div class="dndupload-progressbars"></div>
2598 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2607 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2609 * @param string $cmid the course_module id.
2610 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2611 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2613 public function update_module_button($cmid, $modulename) {
2615 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2616 $modulename = get_string('modulename', $modulename);
2617 $string = get_string('updatethis', '', $modulename);
2618 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2619 return $this->single_button($url, $string);
2626 * Returns HTML to display a "Turn editing on/off" button in a form.
2628 * @param moodle_url $url The URL + params to send through when clicking the button
2629 * @return string HTML the button
2631 public function edit_button(moodle_url $url) {
2633 $url->param('sesskey', sesskey());
2634 if ($this->page->user_is_editing()) {
2635 $url->param('edit', 'off');
2636 $editstring = get_string('turneditingoff');
2638 $url->param('edit', 'on');
2639 $editstring = get_string('turneditingon');
2642 return $this->single_button($url, $editstring);
2646 * Returns HTML to display a simple button to close a window
2648 * @param string $text The lang string for the button's label (already output from get_string())
2649 * @return string html fragment
2651 public function close_window_button($text='') {
2653 $text = get_string('closewindow');
2655 $button = new single_button(new moodle_url('#'), $text, 'get');
2656 $button->add_action(new component_action('click', 'close_window'));
2658 return $this->container($this->render($button), 'closewindow');
2662 * Output an error message. By default wraps the error message in <span class="error">.
2663 * If the error message is blank, nothing is output.
2665 * @param string $message the error message.
2666 * @return string the HTML to output.
2668 public function error_text($message) {
2669 if (empty($message)) {
2672 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2673 return html_writer::tag('span', $message, array('class' => 'error'));
2677 * Do not call this function directly.
2679 * To terminate the current script with a fatal error, call the {@link print_error}
2680 * function, or throw an exception. Doing either of those things will then call this
2681 * function to display the error, before terminating the execution.
2683 * @param string $message The message to output
2684 * @param string $moreinfourl URL where more info can be found about the error
2685 * @param string $link Link for the Continue button
2686 * @param array $backtrace The execution backtrace
2687 * @param string $debuginfo Debugging information
2688 * @return string the HTML to output.
2690 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2696 if ($this->has_started()) {
2697 // we can not always recover properly here, we have problems with output buffering,
2698 // html tables, etc.
2699 $output .= $this->opencontainers->pop_all_but_last();
2702 // It is really bad if library code throws exception when output buffering is on,
2703 // because the buffered text would be printed before our start of page.
2704 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2705 error_reporting(0); // disable notices from gzip compression, etc.
2706 while (ob_get_level() > 0) {
2707 $buff = ob_get_clean();
2708 if ($buff === false) {
2713 error_reporting($CFG->debug);
2715 // Output not yet started.
2716 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2717 if (empty($_SERVER['HTTP_RANGE'])) {
2718 @header($protocol . ' 404 Not Found');
2720 // Must stop byteserving attempts somehow,
2721 // this is weird but Chrome PDF viewer can be stopped only with 407!
2722 @header($protocol . ' 407 Proxy Authentication Required');
2725 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2726 $this->page->set_url('/'); // no url
2727 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2728 $this->page->set_title(get_string('error'));
2729 $this->page->set_heading($this->page->course->fullname);
2730 $output .= $this->header();
2733 $message = '<p class="errormessage">' . $message . '</p>'.
2734 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2735 get_string('moreinformation') . '</a></p>';
2736 if (empty($CFG->rolesactive)) {
2737 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2738 //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.
2740 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2742 if ($CFG->debugdeveloper) {
2743 if (!empty($debuginfo)) {
2744 $debuginfo = s($debuginfo); // removes all nasty JS
2745 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2746 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2748 if (!empty($backtrace)) {
2749 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2751 if ($obbuffer !== '' ) {
2752 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2756 if (empty($CFG->rolesactive)) {
2757 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2758 } else if (!empty($link)) {
2759 $output .= $this->continue_button($link);
2762 $output .= $this->footer();
2764 // Padding to encourage IE to display our error page, rather than its own.
2765 $output .= str_repeat(' ', 512);
2771 * Output a notification (that is, a status message about something that has
2774 * @param string $message the message to print out
2775 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2776 * @return string the HTML to output.
2778 public function notification($message, $classes = 'notifyproblem') {
2780 $classmappings = array(
2781 'notifyproblem' => \core\output\notification::NOTIFY_PROBLEM,
2782 'notifytiny' => \core\output\notification::NOTIFY_PROBLEM,
2783 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2784 'notifymessage' => \core\output\notification::NOTIFY_MESSAGE,
2785 'redirectmessage' => \core\output\notification::NOTIFY_REDIRECT
2788 // Identify what type of notification this is.
2789 $type = \core\output\notification::NOTIFY_PROBLEM;
2790 $classarray = explode(' ', self::prepare_classes($classes));
2791 if (count($classarray) > 0) {
2792 foreach ($classarray as $class) {
2793 if (isset($classmappings[$class])) {
2794 $type = $classmappings[$class];
2800 $n = new \core\output\notification($message, $type);
2801 return $this->render($n);
2806 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2808 * @param string $message the message to print out
2809 * @return string HTML fragment.
2811 public function notify_problem($message) {
2812 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_PROBLEM);
2813 return $this->render($n);
2817 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2819 * @param string $message the message to print out
2820 * @return string HTML fragment.
2822 public function notify_success($message) {
2823 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2824 return $this->render($n);
2828 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2830 * @param string $message the message to print out
2831 * @return string HTML fragment.
2833 public function notify_message($message) {
2834 $n = new notification($message, notification::NOTIFY_MESSAGE);
2835 return $this->render($n);
2839 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2841 * @param string $message the message to print out
2842 * @return string HTML fragment.
2844 public function notify_redirect($message) {
2845 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_REDIRECT);
2846 return $this->render($n);
2850 * Render a notification (that is, a status message about something that has
2853 * @param \core\output\notification $notification the notification to print out
2854 * @return string the HTML to output.
2856 protected function render_notification(\core\output\notification $notification) {
2858 $data = $notification->export_for_template($this);
2861 switch($data->type) {
2862 case \core\output\notification::NOTIFY_MESSAGE:
2863 $templatename = 'core/notification_message';
2865 case \core\output\notification::NOTIFY_SUCCESS:
2866 $templatename = 'core/notification_success';
2868 case \core\output\notification::NOTIFY_PROBLEM:
2869 $templatename = 'core/notification_problem';
2871 case \core\output\notification::NOTIFY_REDIRECT:
2872 $templatename = 'core/notification_redirect';
2875 $templatename = 'core/notification_message';
2879 return self::render_from_template($templatename, $data);
2884 * Returns HTML to display a continue button that goes to a particular URL.
2886 * @param string|moodle_url $url The url the button goes to.
2887 * @return string the HTML to output.
2889 public function continue_button($url) {
2890 if (!($url instanceof moodle_url)) {
2891 $url = new moodle_url($url);
2893 $button = new single_button($url, get_string('continue'), 'get');
2894 $button->class = 'continuebutton';
2896 return $this->render($button);
2900 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2902 * Theme developers: DO NOT OVERRIDE! Please override function
2903 * {@link core_renderer::render_paging_bar()} instead.
2905 * @param int $totalcount The total number of entries available to be paged through
2906 * @param int $page The page you are currently viewing
2907 * @param int $perpage The number of entries that should be shown per page
2908 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2909 * @param string $pagevar name of page parameter that holds the page number
2910 * @return string the HTML to output.
2912 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2913 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2914 return $this->render($pb);
2918 * Internal implementation of paging bar rendering.
2920 * @param paging_bar $pagingbar
2923 protected function render_paging_bar(paging_bar $pagingbar) {
2925 $pagingbar = clone($pagingbar);
2926 $pagingbar->prepare($this, $this->page, $this->target);
2928 if ($pagingbar->totalcount > $pagingbar->perpage) {
2929 $output .= get_string('page') . ':';
2931 if (!empty($pagingbar->previouslink)) {
2932 $output .= ' (' . $pagingbar->previouslink . ') ';
2935 if (!empty($pagingbar->firstlink)) {
2936 $output .= ' ' . $pagingbar->firstlink . ' ...';
2939 foreach ($pagingbar->pagelinks as $link) {
2940 $output .= " $link";
2943 if (!empty($pagingbar->lastlink)) {
2944 $output .= ' ...' . $pagingbar->lastlink . ' ';
2947 if (!empty($pagingbar->nextlink)) {
2948 $output .= ' (' . $pagingbar->nextlink . ')';
2952 return html_writer::tag('div', $output, array('class' => 'paging'));
2956 * Output the place a skip link goes to.
2958 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2959 * @return string the HTML to output.
2961 public function skip_link_target($id = null) {
2962 return html_writer::tag('span', '', array('id' => $id));
2968 * @param string $text The text of the heading
2969 * @param int $level The level of importance of the heading. Defaulting to 2
2970 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2971 * @param string $id An optional ID
2972 * @return string the HTML to output.
2974 public function heading($text, $level = 2, $classes = null, $id = null) {
2975 $level = (integer) $level;
2976 if ($level < 1 or $level > 6) {
2977 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2979 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2985 * @param string $contents The contents of the box
2986 * @param string $classes A space-separated list of CSS classes
2987 * @param string $id An optional ID
2988 * @param array $attributes An array of other attributes to give the box.
2989 * @return string the HTML to output.
2991 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2992 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2996 * Outputs the opening section of a box.
2998 * @param string $classes A space-separated list of CSS classes
2999 * @param string $id An optional ID
3000 * @param array $attributes An array of other attributes to give the box.
3001 * @return string the HTML to output.
3003 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3004 $this->opencontainers->push('box', html_writer::end_tag('div'));
3005 $attributes['id'] = $id;
3006 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3007 return html_writer::start_tag('div', $attributes);
3011 * Outputs the closing section of a box.
3013 * @return string the HTML to output.
3015 public function box_end() {
3016 return $this->opencontainers->pop('box');
3020 * Outputs a container.
3022 * @param string $contents The contents of the box
3023 * @param string $classes A space-separated list of CSS classes
3024 * @param string $id An optional ID
3025 * @return string the HTML to output.
3027 public function container($contents, $classes = null, $id = null) {
3028 return $this->container_start($classes, $id) . $contents . $this->container_end();
3032 * Outputs the opening section of a container.
3034 * @param string $classes A space-separated list of CSS classes
3035 * @param string $id An optional ID
3036 * @return string the HTML to output.
3038 public function container_start($classes = null, $id = null) {
3039 $this->opencontainers->push('container', html_writer::end_tag('div'));
3040 return html_writer::start_tag('div', array('id' => $id,
3041 'class' => renderer_base::prepare_classes($classes)));
3045 * Outputs the closing section of a container.
3047 * @return string the HTML to output.
3049 public function container_end() {
3050 return $this->opencontainers->pop('container');
3054 * Make nested HTML lists out of the items
3056 * The resulting list will look something like this:
3060 * <<li>><div class='tree_item parent'>(item contents)</div>
3062 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3068 * @param array $items
3069 * @param array $attrs html attributes passed to the top ofs the list
3070 * @return string HTML
3072 public function tree_block_contents($items, $attrs = array()) {
3073 // exit if empty, we don't want an empty ul element
3074 if (empty($items)) {
3077 // array of nested li elements
3079 foreach ($items as $item) {
3080 // this applies to the li item which contains all child lists too
3081 $content = $item->content($this);
3082 $liclasses = array($item->get_css_type());
3083 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3084 $liclasses[] = 'collapsed';
3086 if ($item->isactive === true) {
3087 $liclasses[] = 'current_branch';
3089 $liattr = array('class'=>join(' ',$liclasses));
3090 // class attribute on the div item which only contains the item content
3091 $divclasses = array('tree_item');
3092 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3093 $divclasses[] = 'branch';
3095 $divclasses[] = 'leaf';
3097 if (!empty($item->classes) && count($item->classes)>0) {
3098 $divclasses[] = join(' ', $item->classes);
3100 $divattr = array('class'=>join(' ', $divclasses));
3101 if (!empty($item->id)) {
3102 $divattr['id'] = $item->id;
3104 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3105 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3106 $content = html_writer::empty_tag('hr') . $content;
3108 $content = html_writer::tag('li', $content, $liattr);
3111 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3115 * Construct a user menu, returning HTML that can be echoed out by a
3118 * @param stdClass $user A user object, usually $USER.
3119 * @param bool $withlinks true if a dropdown should be built.
3120 * @return string HTML fragment.
3122 public function user_menu($user = null, $withlinks = null) {
3124 require_once($CFG->dirroot . '/user/lib.php');
3126 if (is_null($user)) {
3130 // Note: this behaviour is intended to match that of core_renderer::login_info,
3131 // but should not be considered to be good practice; layout options are
3132 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3133 if (is_null($withlinks)) {
3134 $withlinks = empty($this->page->layout_options['nologinlinks']);
3137 // Add a class for when $withlinks is false.
3138 $usermenuclasses = 'usermenu';
3140 $usermenuclasses .= ' withoutlinks';
3145 // If during initial install, return the empty return string.
3146 if (during_initial_install()) {
3150 $loginpage = $this->is_login_page();
3151 $loginurl = get_login_url();
3152 // If not logged in, show the typical not-logged-in string.
3153 if (!isloggedin()) {
3154 $returnstr = get_string('loggedinnot', 'moodle');
3156 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3158 return html_writer::div(
3168 // If logged in as a guest user, show a string to that effect.
3169 if (isguestuser()) {
3170 $returnstr = get_string('loggedinasguest');
3171 if (!$loginpage && $withlinks) {
3172 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3175 return html_writer::div(
3184 // Get some navigation opts.
3185 $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
3187 $avatarclasses = "avatars";
3188 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3189 $usertextcontents = $opts->metadata['userfullname'];
3192 if (!empty($opts->metadata['asotheruser'])) {
3193 $avatarcontents .= html_writer::span(
3194 $opts->metadata['realuseravatar'],
3197 $usertextcontents = $opts->metadata['realuserfullname'];
3198 $usertextcontents .= html_writer::tag(
3204 $opts->metadata['userfullname'],
3208 array('class' => 'meta viewingas')
3213 if (!empty($opts->metadata['asotherrole'])) {
3214 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3215 $usertextcontents .= html_writer::span(
3216 $opts->metadata['rolename'],
3217 'meta role role-' . $role
3221 // User login failures.
3222 if (!empty($opts->metadata['userloginfail'])) {
3223 $usertextcontents .= html_writer::span(
3224 $opts->metadata['userloginfail'],
3225 'meta loginfailures'
3230 if (!empty($opts->metadata['asmnetuser'])) {
3231 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3232 $usertextcontents .= html_writer::span(
3233 $opts->metadata['mnetidprovidername'],
3234 'meta mnet mnet-' . $mnet
3238 $returnstr .= html_writer::span(
3239 html_writer::span($usertextcontents, 'usertext') .
3240 html_writer::span($avatarcontents, $avatarclasses),
3244 // Create a divider (well, a filler).
3245 $divider = new action_menu_filler();
3246 $divider->primary = false;
3248 $am = new action_menu();
3249 $am->initialise_js($this->page);
3250 $am->set_menu_trigger(
3253 $am->set_alignment(action_menu::TR, action_menu::BR);
3254 $am->set_nowrap_on_items();
3256 $navitemcount = count($opts->navitems);
3258 foreach ($opts->navitems as $key => $value) {
3260 switch ($value->itemtype) {
3262 // If the nav item is a divider, add one and skip link processing.
3267 // Silently skip invalid entries (should we post a notification?).
3271 // Process this as a link item.
3273 if (isset($value->pix) && !empty($value->pix)) {
3274 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3275 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3276 $value->title = html_writer::img(
3279 array('class' => 'iconsmall')
3282 $al = new action_menu_link_secondary(
3286 array('class' => 'icon')
3294 // Add dividers after the first item and before the last item.
3295 if ($idx == 1 || $idx == $navitemcount - 1) {
3301 return html_writer::div(
3308 * Return the navbar content so that it can be echoed out by the layout
3310 * @return string XHTML navbar
3312 public function navbar() {
3313 $items = $this->page->navbar->get_items();
3314 $itemcount = count($items);
3315 if ($itemcount === 0) {
3319 $htmlblocks = array();
3320 // Iterate the navarray and display each node
3321 $separator = get_separator();
3322 for ($i=0;$i < $itemcount;$i++) {
3324 $item->hideicon = true;
3326 $content = html_writer::tag('li', $this->render($item));
3328 $content = html_writer::tag('li', $separator.$this->render($item));
3330 $htmlblocks[] = $content;
3333 //accessibility: heading for navbar list (MDL-20446)
3334 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
3335 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
3337 return $navbarcontent;
3341 * Renders a navigation node object.
3343 * @param navigation_node $item The navigation node to render.
3344 * @return string HTML fragment
3346 protected function render_navigation_node(navigation_node $item) {
3347 $content = $item->get_content();
3348 $title = $item->get_title();
3349 if ($item->icon instanceof renderable && !$item->hideicon) {
3350 $icon = $this->render($item->icon);
3351 $content = $icon.$content; // use CSS for spacing of icons
3353 if ($item->helpbutton !== null) {
3354 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3356 if ($content === '') {
3359 if ($item->action instanceof action_link) {
3360 $link = $item->action;
3361 if ($item->hidden) {
3362 $link->add_class('dimmed');
3364 if (!empty($content)) {
3365 // Providing there is content we will use that for the link content.
3366 $link->text = $content;
3368 $content = $this->render($link);
3369 } else if ($item->action instanceof moodle_url) {
3370 $attributes = array();
3371 if ($title !== '') {
3372 $attributes['title'] = $title;
3374 if ($item->hidden) {
3375 $attributes['class'] = 'dimmed_text';
3377 $content = html_writer::link($item->action, $content, $attributes);
3379 } else if (is_string($item->action) || empty($item->action)) {
3380 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3381 if ($title !== '') {
3382 $attributes['title'] = $title;