MDL-59612 course: Use action_link template for activity navigation
[moodle.git] / lib / outputrenderers.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Classes for rendering HTML output for Moodle.
19  *
20  * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21  * for an overview.
22  *
23  * Included in this file are the primary renderer classes:
24  *     - renderer_base:         The renderer outline class that all renderers
25  *                              should inherit from.
26  *     - core_renderer:         The standard HTML renderer.
27  *     - core_renderer_cli:     An adaption of the standard renderer for CLI scripts.
28  *     - core_renderer_ajax:    An adaption of the standard renderer for AJAX scripts.
29  *     - plugin_renderer_base:  A renderer class that should be extended by all
30  *                              plugin renderers.
31  *
32  * @package core
33  * @category output
34  * @copyright  2009 Tim Hunt
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
38 defined('MOODLE_INTERNAL') || die();
40 /**
41  * Simple base class for Moodle renderers.
42  *
43  * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
44  *
45  * Also has methods to facilitate generating HTML output.
46  *
47  * @copyright 2009 Tim Hunt
48  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49  * @since Moodle 2.0
50  * @package core
51  * @category output
52  */
53 class renderer_base {
54     /**
55      * @var xhtml_container_stack The xhtml_container_stack to use.
56      */
57     protected $opencontainers;
59     /**
60      * @var moodle_page The Moodle page the renderer has been created to assist with.
61      */
62     protected $page;
64     /**
65      * @var string The requested rendering target.
66      */
67     protected $target;
69     /**
70      * @var Mustache_Engine $mustache The mustache template compiler
71      */
72     private $mustache;
74     /**
75      * Return an instance of the mustache class.
76      *
77      * @since 2.9
78      * @return Mustache_Engine
79      */
80     protected function get_mustache() {
81         global $CFG;
83         if ($this->mustache === null) {
84             $themename = $this->page->theme->name;
85             $themerev = theme_get_revision();
87             $cachedir = make_localcache_directory("mustache/$themerev/$themename");
89             $loader = new \core\output\mustache_filesystem_loader();
90             $stringhelper = new \core\output\mustache_string_helper();
91             $quotehelper = new \core\output\mustache_quote_helper();
92             $jshelper = new \core\output\mustache_javascript_helper($this->page);
93             $pixhelper = new \core\output\mustache_pix_helper($this);
94             $shortentexthelper = new \core\output\mustache_shorten_text_helper();
95             $userdatehelper = new \core\output\mustache_user_date_helper();
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                              'quote' => array($quotehelper, 'quote'),
103                              'js' => array($jshelper, 'help'),
104                              'pix' => array($pixhelper, 'pix'),
105                              'shortentext' => array($shortentexthelper, 'shorten'),
106                              'userdate' => array($userdatehelper, 'transform'),
107                          );
109             $this->mustache = new Mustache_Engine(array(
110                 'cache' => $cachedir,
111                 'escape' => 's',
112                 'loader' => $loader,
113                 'helpers' => $helpers,
114                 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
116         }
118         return $this->mustache;
119     }
122     /**
123      * Constructor
124      *
125      * The constructor takes two arguments. The first is the page that the renderer
126      * has been created to assist with, and the second is the target.
127      * The target is an additional identifier that can be used to load different
128      * renderers for different options.
129      *
130      * @param moodle_page $page the page we are doing output for.
131      * @param string $target one of rendering target constants
132      */
133     public function __construct(moodle_page $page, $target) {
134         $this->opencontainers = $page->opencontainers;
135         $this->page = $page;
136         $this->target = $target;
137     }
139     /**
140      * Renders a template by name with the given context.
141      *
142      * The provided data needs to be array/stdClass made up of only simple types.
143      * Simple types are array,stdClass,bool,int,float,string
144      *
145      * @since 2.9
146      * @param array|stdClass $context Context containing data for the template.
147      * @return string|boolean
148      */
149     public function render_from_template($templatename, $context) {
150         static $templatecache = array();
151         $mustache = $this->get_mustache();
153         try {
154             // Grab a copy of the existing helper to be restored later.
155             $uniqidhelper = $mustache->getHelper('uniqid');
156         } catch (Mustache_Exception_UnknownHelperException $e) {
157             // Helper doesn't exist.
158             $uniqidhelper = null;
159         }
161         // Provide 1 random value that will not change within a template
162         // but will be different from template to template. This is useful for
163         // e.g. aria attributes that only work with id attributes and must be
164         // unique in a page.
165         $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
166         if (isset($templatecache[$templatename])) {
167             $template = $templatecache[$templatename];
168         } else {
169             try {
170                 $template = $mustache->loadTemplate($templatename);
171                 $templatecache[$templatename] = $template;
172             } catch (Mustache_Exception_UnknownTemplateException $e) {
173                 throw new moodle_exception('Unknown template: ' . $templatename);
174             }
175         }
177         $renderedtemplate = trim($template->render($context));
179         // If we had an existing uniqid helper then we need to restore it to allow
180         // handle nested calls of render_from_template.
181         if ($uniqidhelper) {
182             $mustache->addHelper('uniqid', $uniqidhelper);
183         }
185         return $renderedtemplate;
186     }
189     /**
190      * Returns rendered widget.
191      *
192      * The provided widget needs to be an object that extends the renderable
193      * interface.
194      * If will then be rendered by a method based upon the classname for the widget.
195      * For instance a widget of class `crazywidget` will be rendered by a protected
196      * render_crazywidget method of this renderer.
197      *
198      * @param renderable $widget instance with renderable interface
199      * @return string
200      */
201     public function render(renderable $widget) {
202         $classname = get_class($widget);
203         // Strip namespaces.
204         $classname = preg_replace('/^.*\\\/', '', $classname);
205         // Remove _renderable suffixes
206         $classname = preg_replace('/_renderable$/', '', $classname);
208         $rendermethod = 'render_'.$classname;
209         if (method_exists($this, $rendermethod)) {
210             return $this->$rendermethod($widget);
211         }
212         throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
213     }
215     /**
216      * Adds a JS action for the element with the provided id.
217      *
218      * This method adds a JS event for the provided component action to the page
219      * and then returns the id that the event has been attached to.
220      * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
221      *
222      * @param component_action $action
223      * @param string $id
224      * @return string id of element, either original submitted or random new if not supplied
225      */
226     public function add_action_handler(component_action $action, $id = null) {
227         if (!$id) {
228             $id = html_writer::random_id($action->event);
229         }
230         $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
231         return $id;
232     }
234     /**
235      * Returns true is output has already started, and false if not.
236      *
237      * @return boolean true if the header has been printed.
238      */
239     public function has_started() {
240         return $this->page->state >= moodle_page::STATE_IN_BODY;
241     }
243     /**
244      * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
245      *
246      * @param mixed $classes Space-separated string or array of classes
247      * @return string HTML class attribute value
248      */
249     public static function prepare_classes($classes) {
250         if (is_array($classes)) {
251             return implode(' ', array_unique($classes));
252         }
253         return $classes;
254     }
256     /**
257      * Return the direct URL for an image from the pix folder.
258      *
259      * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
260      *
261      * @deprecated since Moodle 3.3
262      * @param string $imagename the name of the icon.
263      * @param string $component specification of one plugin like in get_string()
264      * @return moodle_url
265      */
266     public function pix_url($imagename, $component = 'moodle') {
267         debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
268         return $this->page->theme->image_url($imagename, $component);
269     }
271     /**
272      * Return the moodle_url for an image.
273      *
274      * The exact image location and extension is determined
275      * automatically by searching for gif|png|jpg|jpeg, please
276      * note there can not be diferent images with the different
277      * extension. The imagename is for historical reasons
278      * a relative path name, it may be changed later for core
279      * images. It is recommended to not use subdirectories
280      * in plugin and theme pix directories.
281      *
282      * There are three types of images:
283      * 1/ theme images  - stored in theme/mytheme/pix/,
284      *                    use component 'theme'
285      * 2/ core images   - stored in /pix/,
286      *                    overridden via theme/mytheme/pix_core/
287      * 3/ plugin images - stored in mod/mymodule/pix,
288      *                    overridden via theme/mytheme/pix_plugins/mod/mymodule/,
289      *                    example: image_url('comment', 'mod_glossary')
290      *
291      * @param string $imagename the pathname of the image
292      * @param string $component full plugin name (aka component) or 'theme'
293      * @return moodle_url
294      */
295     public function image_url($imagename, $component = 'moodle') {
296         return $this->page->theme->image_url($imagename, $component);
297     }
299     /**
300      * Return the site's logo URL, if any.
301      *
302      * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
303      * @param int $maxheight The maximum height, or null when the maximum height does not matter.
304      * @return moodle_url|false
305      */
306     public function get_logo_url($maxwidth = null, $maxheight = 200) {
307         global $CFG;
308         $logo = get_config('core_admin', 'logo');
309         if (empty($logo)) {
310             return false;
311         }
313         // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
314         // It's not worth the overhead of detecting and serving 2 different images based on the device.
316         // Hide the requested size in the file path.
317         $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
319         // Use $CFG->themerev to prevent browser caching when the file changes.
320         return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
321             theme_get_revision(), $logo);
322     }
324     /**
325      * Return the site's compact logo URL, if any.
326      *
327      * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
328      * @param int $maxheight The maximum height, or null when the maximum height does not matter.
329      * @return moodle_url|false
330      */
331     public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
332         global $CFG;
333         $logo = get_config('core_admin', 'logocompact');
334         if (empty($logo)) {
335             return false;
336         }
338         // Hide the requested size in the file path.
339         $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
341         // Use $CFG->themerev to prevent browser caching when the file changes.
342         return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
343             theme_get_revision(), $logo);
344     }
349 /**
350  * Basis for all plugin renderers.
351  *
352  * @copyright Petr Skoda (skodak)
353  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
354  * @since Moodle 2.0
355  * @package core
356  * @category output
357  */
358 class plugin_renderer_base extends renderer_base {
360     /**
361      * @var renderer_base|core_renderer A reference to the current renderer.
362      * The renderer provided here will be determined by the page but will in 90%
363      * of cases by the {@link core_renderer}
364      */
365     protected $output;
367     /**
368      * Constructor method, calls the parent constructor
369      *
370      * @param moodle_page $page
371      * @param string $target one of rendering target constants
372      */
373     public function __construct(moodle_page $page, $target) {
374         if (empty($target) && $page->pagelayout === 'maintenance') {
375             // If the page is using the maintenance layout then we're going to force the target to maintenance.
376             // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
377             // unavailable for this page layout.
378             $target = RENDERER_TARGET_MAINTENANCE;
379         }
380         $this->output = $page->get_renderer('core', null, $target);
381         parent::__construct($page, $target);
382     }
384     /**
385      * Renders the provided widget and returns the HTML to display it.
386      *
387      * @param renderable $widget instance with renderable interface
388      * @return string
389      */
390     public function render(renderable $widget) {
391         $classname = get_class($widget);
392         // Strip namespaces.
393         $classname = preg_replace('/^.*\\\/', '', $classname);
394         // Keep a copy at this point, we may need to look for a deprecated method.
395         $deprecatedmethod = 'render_'.$classname;
396         // Remove _renderable suffixes
397         $classname = preg_replace('/_renderable$/', '', $classname);
399         $rendermethod = 'render_'.$classname;
400         if (method_exists($this, $rendermethod)) {
401             return $this->$rendermethod($widget);
402         }
403         if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
404             // This is exactly where we don't want to be.
405             // If you have arrived here you have a renderable component within your plugin that has the name
406             // blah_renderable, and you have a render method render_blah_renderable on your plugin.
407             // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
408             // and the _renderable suffix now gets removed when looking for a render method.
409             // You need to change your renderers render_blah_renderable to render_blah.
410             // Until you do this it will not be possible for a theme to override the renderer to override your method.
411             // Please do it ASAP.
412             static $debugged = array();
413             if (!isset($debugged[$deprecatedmethod])) {
414                 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
415                     $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
416                 $debugged[$deprecatedmethod] = true;
417             }
418             return $this->$deprecatedmethod($widget);
419         }
420         // pass to core renderer if method not found here
421         return $this->output->render($widget);
422     }
424     /**
425      * Magic method used to pass calls otherwise meant for the standard renderer
426      * to it to ensure we don't go causing unnecessary grief.
427      *
428      * @param string $method
429      * @param array $arguments
430      * @return mixed
431      */
432     public function __call($method, $arguments) {
433         if (method_exists('renderer_base', $method)) {
434             throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
435         }
436         if (method_exists($this->output, $method)) {
437             return call_user_func_array(array($this->output, $method), $arguments);
438         } else {
439             throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
440         }
441     }
445 /**
446  * The standard implementation of the core_renderer interface.
447  *
448  * @copyright 2009 Tim Hunt
449  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450  * @since Moodle 2.0
451  * @package core
452  * @category output
453  */
454 class core_renderer extends renderer_base {
455     /**
456      * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
457      * in layout files instead.
458      * @deprecated
459      * @var string used in {@link core_renderer::header()}.
460      */
461     const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
463     /**
464      * @var string Used to pass information from {@link core_renderer::doctype()} to
465      * {@link core_renderer::standard_head_html()}.
466      */
467     protected $contenttype;
469     /**
470      * @var string Used by {@link core_renderer::redirect_message()} method to communicate
471      * with {@link core_renderer::header()}.
472      */
473     protected $metarefreshtag = '';
475     /**
476      * @var string Unique token for the closing HTML
477      */
478     protected $unique_end_html_token;
480     /**
481      * @var string Unique token for performance information
482      */
483     protected $unique_performance_info_token;
485     /**
486      * @var string Unique token for the main content.
487      */
488     protected $unique_main_content_token;
490     /**
491      * Constructor
492      *
493      * @param moodle_page $page the page we are doing output for.
494      * @param string $target one of rendering target constants
495      */
496     public function __construct(moodle_page $page, $target) {
497         $this->opencontainers = $page->opencontainers;
498         $this->page = $page;
499         $this->target = $target;
501         $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
502         $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
503         $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
504     }
506     /**
507      * Get the DOCTYPE declaration that should be used with this page. Designed to
508      * be called in theme layout.php files.
509      *
510      * @return string the DOCTYPE declaration that should be used.
511      */
512     public function doctype() {
513         if ($this->page->theme->doctype === 'html5') {
514             $this->contenttype = 'text/html; charset=utf-8';
515             return "<!DOCTYPE html>\n";
517         } else if ($this->page->theme->doctype === 'xhtml5') {
518             $this->contenttype = 'application/xhtml+xml; charset=utf-8';
519             return "<!DOCTYPE html>\n";
521         } else {
522             // legacy xhtml 1.0
523             $this->contenttype = 'text/html; charset=utf-8';
524             return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
525         }
526     }
528     /**
529      * The attributes that should be added to the <html> tag. Designed to
530      * be called in theme layout.php files.
531      *
532      * @return string HTML fragment.
533      */
534     public function htmlattributes() {
535         $return = get_html_lang(true);
536         $attributes = array();
537         if ($this->page->theme->doctype !== 'html5') {
538             $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
539         }
541         // Give plugins an opportunity to add things like xml namespaces to the html element.
542         // This function should return an array of html attribute names => values.
543         $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
544         foreach ($pluginswithfunction as $plugins) {
545             foreach ($plugins as $function) {
546                 $newattrs = $function();
547                 unset($newattrs['dir']);
548                 unset($newattrs['lang']);
549                 unset($newattrs['xmlns']);
550                 unset($newattrs['xml:lang']);
551                 $attributes += $newattrs;
552             }
553         }
555         foreach ($attributes as $key => $val) {
556             $val = s($val);
557             $return .= " $key=\"$val\"";
558         }
560         return $return;
561     }
563     /**
564      * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
565      * that should be included in the <head> tag. Designed to be called in theme
566      * layout.php files.
567      *
568      * @return string HTML fragment.
569      */
570     public function standard_head_html() {
571         global $CFG, $SESSION;
573         // Before we output any content, we need to ensure that certain
574         // page components are set up.
576         // Blocks must be set up early as they may require javascript which
577         // has to be included in the page header before output is created.
578         foreach ($this->page->blocks->get_regions() as $region) {
579             $this->page->blocks->ensure_content_created($region, $this);
580         }
582         $output = '';
584         // Give plugins an opportunity to add any head elements. The callback
585         // must always return a string containing valid html head content.
586         $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
587         foreach ($pluginswithfunction as $plugins) {
588             foreach ($plugins as $function) {
589                 $output .= $function();
590             }
591         }
593         // Allow a url_rewrite plugin to setup any dynamic head content.
594         if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
595             $class = $CFG->urlrewriteclass;
596             $output .= $class::html_head_setup();
597         }
599         $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
600         $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
601         // This is only set by the {@link redirect()} method
602         $output .= $this->metarefreshtag;
604         // Check if a periodic refresh delay has been set and make sure we arn't
605         // already meta refreshing
606         if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
607             $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
608         }
610         // Set up help link popups for all links with the helptooltip class
611         $this->page->requires->js_init_call('M.util.help_popups.setup');
613         $focus = $this->page->focuscontrol;
614         if (!empty($focus)) {
615             if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
616                 // This is a horrifically bad way to handle focus but it is passed in
617                 // through messy formslib::moodleform
618                 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
619             } else if (strpos($focus, '.')!==false) {
620                 // Old style of focus, bad way to do it
621                 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);
622                 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
623             } else {
624                 // Focus element with given id
625                 $this->page->requires->js_function_call('focuscontrol', array($focus));
626             }
627         }
629         // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
630         // any other custom CSS can not be overridden via themes and is highly discouraged
631         $urls = $this->page->theme->css_urls($this->page);
632         foreach ($urls as $url) {
633             $this->page->requires->css_theme($url);
634         }
636         // Get the theme javascript head and footer
637         if ($jsurl = $this->page->theme->javascript_url(true)) {
638             $this->page->requires->js($jsurl, true);
639         }
640         if ($jsurl = $this->page->theme->javascript_url(false)) {
641             $this->page->requires->js($jsurl);
642         }
644         // Get any HTML from the page_requirements_manager.
645         $output .= $this->page->requires->get_head_code($this->page, $this);
647         // List alternate versions.
648         foreach ($this->page->alternateversions as $type => $alt) {
649             $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
650                     'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
651         }
653         // Add noindex tag if relevant page and setting applied.
654         $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
655         $loginpages = array('login-index', 'login-signup');
656         if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
657             if (!isset($CFG->additionalhtmlhead)) {
658                 $CFG->additionalhtmlhead = '';
659             }
660             $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
661         }
663         if (!empty($CFG->additionalhtmlhead)) {
664             $output .= "\n".$CFG->additionalhtmlhead;
665         }
667         return $output;
668     }
670     /**
671      * The standard tags (typically skip links) that should be output just inside
672      * the start of the <body> tag. Designed to be called in theme layout.php files.
673      *
674      * @return string HTML fragment.
675      */
676     public function standard_top_of_body_html() {
677         global $CFG;
678         $output = $this->page->requires->get_top_of_body_code($this);
679         if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
680             $output .= "\n".$CFG->additionalhtmltopofbody;
681         }
683         // Give plugins an opportunity to inject extra html content. The callback
684         // must always return a string containing valid html.
685         $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
686         foreach ($pluginswithfunction as $plugins) {
687             foreach ($plugins as $function) {
688                 $output .= $function();
689             }
690         }
692         $output .= $this->maintenance_warning();
694         return $output;
695     }
697     /**
698      * Scheduled maintenance warning message.
699      *
700      * Note: This is a nasty hack to display maintenance notice, this should be moved
701      *       to some general notification area once we have it.
702      *
703      * @return string
704      */
705     public function maintenance_warning() {
706         global $CFG;
708         $output = '';
709         if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
710             $timeleft = $CFG->maintenance_later - time();
711             // If timeleft less than 30 sec, set the class on block to error to highlight.
712             $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
713             $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
714             $a = new stdClass();
715             $a->hour = (int)($timeleft / 3600);
716             $a->min = (int)(($timeleft / 60) % 60);
717             $a->sec = (int)($timeleft % 60);
718             if ($a->hour > 0) {
719                 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
720             } else {
721                 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
722             }
724             $output .= $this->box_end();
725             $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
726                     array(array('timeleftinsec' => $timeleft)));
727             $this->page->requires->strings_for_js(
728                     array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
729                     'admin');
730         }
731         return $output;
732     }
734     /**
735      * The standard tags (typically performance information and validation links,
736      * if we are in developer debug mode) that should be output in the footer area
737      * of the page. Designed to be called in theme layout.php files.
738      *
739      * @return string HTML fragment.
740      */
741     public function standard_footer_html() {
742         global $CFG, $SCRIPT;
744         $output = '';
745         if (during_initial_install()) {
746             // Debugging info can not work before install is finished,
747             // in any case we do not want any links during installation!
748             return $output;
749         }
751         // Give plugins an opportunity to add any footer elements.
752         // The callback must always return a string containing valid html footer content.
753         $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
754         foreach ($pluginswithfunction as $plugins) {
755             foreach ($plugins as $function) {
756                 $output .= $function();
757             }
758         }
760         // This function is normally called from a layout.php file in {@link core_renderer::header()}
761         // but some of the content won't be known until later, so we return a placeholder
762         // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
763         $output .= $this->unique_performance_info_token;
764         if ($this->page->devicetypeinuse == 'legacy') {
765             // The legacy theme is in use print the notification
766             $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
767         }
769         // Get links to switch device types (only shown for users not on a default device)
770         $output .= $this->theme_switch_links();
772         if (!empty($CFG->debugpageinfo)) {
773             $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
774         }
775         if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) {  // Only in developer mode
776             // Add link to profiling report if necessary
777             if (function_exists('profiling_is_running') && profiling_is_running()) {
778                 $txt = get_string('profiledscript', 'admin');
779                 $title = get_string('profiledscriptview', 'admin');
780                 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
781                 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
782                 $output .= '<div class="profilingfooter">' . $link . '</div>';
783             }
784             $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
785                 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
786             $output .= '<div class="purgecaches">' .
787                     html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
788         }
789         if (!empty($CFG->debugvalidators)) {
790             // 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
791             $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
792               <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
793               <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
794               <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
795             </ul></div>';
796         }
797         return $output;
798     }
800     /**
801      * Returns standard main content placeholder.
802      * Designed to be called in theme layout.php files.
803      *
804      * @return string HTML fragment.
805      */
806     public function main_content() {
807         // This is here because it is the only place we can inject the "main" role over the entire main content area
808         // without requiring all theme's to manually do it, and without creating yet another thing people need to
809         // remember in the theme.
810         // This is an unfortunate hack. DO NO EVER add anything more here.
811         // DO NOT add classes.
812         // DO NOT add an id.
813         return '<div role="main">'.$this->unique_main_content_token.'</div>';
814     }
816     /**
817      * Returns standard navigation between activities in a course.
818      *
819      * @return string the navigation HTML.
820      */
821     public function activity_navigation() {
822         // First we should check if we want to add navigation.
823         $context = $this->page->context;
824         if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
825             || $context->contextlevel != CONTEXT_MODULE) {
826             return '';
827         }
829         // If the activity is in stealth mode, show no links.
830         if ($this->page->cm->is_stealth()) {
831             return '';
832         }
834         // Get a list of all the activities in the course.
835         $course = $this->page->cm->get_course();
836         $modules = get_fast_modinfo($course->id)->get_cms();
838         // Put the modules into an array in order by the position they are shown in the course.
839         $mods = [];
840         foreach ($modules as $module) {
841             // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
842             if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
843                 continue;
844             }
845             $mods[$module->id] = $module;
846         }
848         $nummods = count($mods);
850         // If there is only one mod then do nothing.
851         if ($nummods == 1) {
852             return '';
853         }
855         // Get an array of just the course module ids used to get the cmid value based on their position in the course.
856         $modids = array_keys($mods);
858         // Get the position in the array of the course module we are viewing.
859         $position = array_search($this->page->cm->id, $modids);
861         $prevmod = null;
862         $nextmod = null;
864         // Check if we have a previous mod to show.
865         if ($position > 0) {
866             $prevmod = $mods[$modids[$position - 1]];
867         }
869         // Check if we have a next mod to show.
870         if ($position < ($nummods - 1)) {
871             $nextmod = $mods[$modids[$position + 1]];
872         }
874         $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod);
875         $renderer = $this->page->get_renderer('core', 'course');
876         return $renderer->render($activitynav);
877     }
879     /**
880      * The standard tags (typically script tags that are not needed earlier) that
881      * should be output after everything else. Designed to be called in theme layout.php files.
882      *
883      * @return string HTML fragment.
884      */
885     public function standard_end_of_body_html() {
886         global $CFG;
888         // This function is normally called from a layout.php file in {@link core_renderer::header()}
889         // but some of the content won't be known until later, so we return a placeholder
890         // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
891         $output = '';
892         if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
893             $output .= "\n".$CFG->additionalhtmlfooter;
894         }
895         $output .= $this->unique_end_html_token;
896         return $output;
897     }
899     /**
900      * Return the standard string that says whether you are logged in (and switched
901      * roles/logged in as another user).
902      * @param bool $withlinks if false, then don't include any links in the HTML produced.
903      * If not set, the default is the nologinlinks option from the theme config.php file,
904      * and if that is not set, then links are included.
905      * @return string HTML fragment.
906      */
907     public function login_info($withlinks = null) {
908         global $USER, $CFG, $DB, $SESSION;
910         if (during_initial_install()) {
911             return '';
912         }
914         if (is_null($withlinks)) {
915             $withlinks = empty($this->page->layout_options['nologinlinks']);
916         }
918         $course = $this->page->course;
919         if (\core\session\manager::is_loggedinas()) {
920             $realuser = \core\session\manager::get_realuser();
921             $fullname = fullname($realuser, true);
922             if ($withlinks) {
923                 $loginastitle = get_string('loginas');
924                 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
925                 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
926             } else {
927                 $realuserinfo = " [$fullname] ";
928             }
929         } else {
930             $realuserinfo = '';
931         }
933         $loginpage = $this->is_login_page();
934         $loginurl = get_login_url();
936         if (empty($course->id)) {
937             // $course->id is not defined during installation
938             return '';
939         } else if (isloggedin()) {
940             $context = context_course::instance($course->id);
942             $fullname = fullname($USER, true);
943             // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
944             if ($withlinks) {
945                 $linktitle = get_string('viewprofile');
946                 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
947             } else {
948                 $username = $fullname;
949             }
950             if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
951                 if ($withlinks) {
952                     $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
953                 } else {
954                     $username .= " from {$idprovider->name}";
955                 }
956             }
957             if (isguestuser()) {
958                 $loggedinas = $realuserinfo.get_string('loggedinasguest');
959                 if (!$loginpage && $withlinks) {
960                     $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
961                 }
962             } else if (is_role_switched($course->id)) { // Has switched roles
963                 $rolename = '';
964                 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
965                     $rolename = ': '.role_get_name($role, $context);
966                 }
967                 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
968                 if ($withlinks) {
969                     $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
970                     $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
971                 }
972             } else {
973                 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
974                 if ($withlinks) {
975                     $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
976                 }
977             }
978         } else {
979             $loggedinas = get_string('loggedinnot', 'moodle');
980             if (!$loginpage && $withlinks) {
981                 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
982             }
983         }
985         $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
987         if (isset($SESSION->justloggedin)) {
988             unset($SESSION->justloggedin);
989             if (!empty($CFG->displayloginfailures)) {
990                 if (!isguestuser()) {
991                     // Include this file only when required.
992                     require_once($CFG->dirroot . '/user/lib.php');
993                     if ($count = user_count_login_failures($USER)) {
994                         $loggedinas .= '<div class="loginfailures">';
995                         $a = new stdClass();
996                         $a->attempts = $count;
997                         $loggedinas .= get_string('failedloginattempts', '', $a);
998                         if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
999                             $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1000                                     'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1001                         }
1002                         $loggedinas .= '</div>';
1003                     }
1004                 }
1005             }
1006         }
1008         return $loggedinas;
1009     }
1011     /**
1012      * Check whether the current page is a login page.
1013      *
1014      * @since Moodle 2.9
1015      * @return bool
1016      */
1017     protected function is_login_page() {
1018         // This is a real bit of a hack, but its a rarety that we need to do something like this.
1019         // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1020         // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1021         return in_array(
1022             $this->page->url->out_as_local_url(false, array()),
1023             array(
1024                 '/login/index.php',
1025                 '/login/forgot_password.php',
1026             )
1027         );
1028     }
1030     /**
1031      * Return the 'back' link that normally appears in the footer.
1032      *
1033      * @return string HTML fragment.
1034      */
1035     public function home_link() {
1036         global $CFG, $SITE;
1038         if ($this->page->pagetype == 'site-index') {
1039             // Special case for site home page - please do not remove
1040             return '<div class="sitelink">' .
1041                    '<a title="Moodle" href="http://moodle.org/">' .
1042                    '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1044         } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1045             // Special case for during install/upgrade.
1046             return '<div class="sitelink">'.
1047                    '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1048                    '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1050         } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1051             return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1052                     get_string('home') . '</a></div>';
1054         } else {
1055             return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1056                     format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1057         }
1058     }
1060     /**
1061      * Redirects the user by any means possible given the current state
1062      *
1063      * This function should not be called directly, it should always be called using
1064      * the redirect function in lib/weblib.php
1065      *
1066      * The redirect function should really only be called before page output has started
1067      * however it will allow itself to be called during the state STATE_IN_BODY
1068      *
1069      * @param string $encodedurl The URL to send to encoded if required
1070      * @param string $message The message to display to the user if any
1071      * @param int $delay The delay before redirecting a user, if $message has been
1072      *         set this is a requirement and defaults to 3, set to 0 no delay
1073      * @param boolean $debugdisableredirect this redirect has been disabled for
1074      *         debugging purposes. Display a message that explains, and don't
1075      *         trigger the redirect.
1076      * @param string $messagetype The type of notification to show the message in.
1077      *         See constants on \core\output\notification.
1078      * @return string The HTML to display to the user before dying, may contain
1079      *         meta refresh, javascript refresh, and may have set header redirects
1080      */
1081     public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1082                                      $messagetype = \core\output\notification::NOTIFY_INFO) {
1083         global $CFG;
1084         $url = str_replace('&amp;', '&', $encodedurl);
1086         switch ($this->page->state) {
1087             case moodle_page::STATE_BEFORE_HEADER :
1088                 // No output yet it is safe to delivery the full arsenal of redirect methods
1089                 if (!$debugdisableredirect) {
1090                     // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1091                     $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1092                     $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1093                 }
1094                 $output = $this->header();
1095                 break;
1096             case moodle_page::STATE_PRINTING_HEADER :
1097                 // We should hopefully never get here
1098                 throw new coding_exception('You cannot redirect while printing the page header');
1099                 break;
1100             case moodle_page::STATE_IN_BODY :
1101                 // We really shouldn't be here but we can deal with this
1102                 debugging("You should really redirect before you start page output");
1103                 if (!$debugdisableredirect) {
1104                     $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1105                 }
1106                 $output = $this->opencontainers->pop_all_but_last();
1107                 break;
1108             case moodle_page::STATE_DONE :
1109                 // Too late to be calling redirect now
1110                 throw new coding_exception('You cannot redirect after the entire page has been generated');
1111                 break;
1112         }
1113         $output .= $this->notification($message, $messagetype);
1114         $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1115         if ($debugdisableredirect) {
1116             $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1117         }
1118         $output .= $this->footer();
1119         return $output;
1120     }
1122     /**
1123      * Start output by sending the HTTP headers, and printing the HTML <head>
1124      * and the start of the <body>.
1125      *
1126      * To control what is printed, you should set properties on $PAGE. If you
1127      * are familiar with the old {@link print_header()} function from Moodle 1.9
1128      * you will find that there are properties on $PAGE that correspond to most
1129      * of the old parameters to could be passed to print_header.
1130      *
1131      * Not that, in due course, the remaining $navigation, $menu parameters here
1132      * will be replaced by more properties of $PAGE, but that is still to do.
1133      *
1134      * @return string HTML that you must output this, preferably immediately.
1135      */
1136     public function header() {
1137         global $USER, $CFG, $SESSION;
1139         // Give plugins an opportunity touch things before the http headers are sent
1140         // such as adding additional headers. The return value is ignored.
1141         $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1142         foreach ($pluginswithfunction as $plugins) {
1143             foreach ($plugins as $function) {
1144                 $function();
1145             }
1146         }
1148         if (\core\session\manager::is_loggedinas()) {
1149             $this->page->add_body_class('userloggedinas');
1150         }
1152         if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1153             require_once($CFG->dirroot . '/user/lib.php');
1154             // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1155             if ($count = user_count_login_failures($USER, false)) {
1156                 $this->page->add_body_class('loginfailures');
1157             }
1158         }
1160         // If the user is logged in, and we're not in initial install,
1161         // check to see if the user is role-switched and add the appropriate
1162         // CSS class to the body element.
1163         if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1164             $this->page->add_body_class('userswitchedrole');
1165         }
1167         // Give themes a chance to init/alter the page object.
1168         $this->page->theme->init_page($this->page);
1170         $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1172         // Find the appropriate page layout file, based on $this->page->pagelayout.
1173         $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1174         // Render the layout using the layout file.
1175         $rendered = $this->render_page_layout($layoutfile);
1177         // Slice the rendered output into header and footer.
1178         $cutpos = strpos($rendered, $this->unique_main_content_token);
1179         if ($cutpos === false) {
1180             $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1181             $token = self::MAIN_CONTENT_TOKEN;
1182         } else {
1183             $token = $this->unique_main_content_token;
1184         }
1186         if ($cutpos === false) {
1187             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.');
1188         }
1189         $header = substr($rendered, 0, $cutpos);
1190         $footer = substr($rendered, $cutpos + strlen($token));
1192         if (empty($this->contenttype)) {
1193             debugging('The page layout file did not call $OUTPUT->doctype()');
1194             $header = $this->doctype() . $header;
1195         }
1197         // If this theme version is below 2.4 release and this is a course view page
1198         if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1199                 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1200             // check if course content header/footer have not been output during render of theme layout
1201             $coursecontentheader = $this->course_content_header(true);
1202             $coursecontentfooter = $this->course_content_footer(true);
1203             if (!empty($coursecontentheader)) {
1204                 // display debug message and add header and footer right above and below main content
1205                 // Please note that course header and footer (to be displayed above and below the whole page)
1206                 // are not displayed in this case at all.
1207                 // Besides the content header and footer are not displayed on any other course page
1208                 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);
1209                 $header .= $coursecontentheader;
1210                 $footer = $coursecontentfooter. $footer;
1211             }
1212         }
1214         send_headers($this->contenttype, $this->page->cacheable);
1216         $this->opencontainers->push('header/footer', $footer);
1217         $this->page->set_state(moodle_page::STATE_IN_BODY);
1219         return $header . $this->skip_link_target('maincontent');
1220     }
1222     /**
1223      * Renders and outputs the page layout file.
1224      *
1225      * This is done by preparing the normal globals available to a script, and
1226      * then including the layout file provided by the current theme for the
1227      * requested layout.
1228      *
1229      * @param string $layoutfile The name of the layout file
1230      * @return string HTML code
1231      */
1232     protected function render_page_layout($layoutfile) {
1233         global $CFG, $SITE, $USER;
1234         // The next lines are a bit tricky. The point is, here we are in a method
1235         // of a renderer class, and this object may, or may not, be the same as
1236         // the global $OUTPUT object. When rendering the page layout file, we want to use
1237         // this object. However, people writing Moodle code expect the current
1238         // renderer to be called $OUTPUT, not $this, so define a variable called
1239         // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1240         $OUTPUT = $this;
1241         $PAGE = $this->page;
1242         $COURSE = $this->page->course;
1244         ob_start();
1245         include($layoutfile);
1246         $rendered = ob_get_contents();
1247         ob_end_clean();
1248         return $rendered;
1249     }
1251     /**
1252      * Outputs the page's footer
1253      *
1254      * @return string HTML fragment
1255      */
1256     public function footer() {
1257         global $CFG, $DB, $PAGE;
1259         // Give plugins an opportunity to touch the page before JS is finalized.
1260         $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1261         foreach ($pluginswithfunction as $plugins) {
1262             foreach ($plugins as $function) {
1263                 $function();
1264             }
1265         }
1267         $output = $this->container_end_all(true);
1269         $footer = $this->opencontainers->pop('header/footer');
1271         if (debugging() and $DB and $DB->is_transaction_started()) {
1272             // TODO: MDL-20625 print warning - transaction will be rolled back
1273         }
1275         // Provide some performance info if required
1276         $performanceinfo = '';
1277         if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1278             $perf = get_performance_info();
1279             if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1280                 $performanceinfo = $perf['html'];
1281             }
1282         }
1284         // We always want performance data when running a performance test, even if the user is redirected to another page.
1285         if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1286             $footer = $this->unique_performance_info_token . $footer;
1287         }
1288         $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1290         // Only show notifications when we have a $PAGE context id.
1291         if (!empty($PAGE->context->id)) {
1292             $this->page->requires->js_call_amd('core/notification', 'init', array(
1293                 $PAGE->context->id,
1294                 \core\notification::fetch_as_array($this)
1295             ));
1296         }
1297         $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1299         $this->page->set_state(moodle_page::STATE_DONE);
1301         return $output . $footer;
1302     }
1304     /**
1305      * Close all but the last open container. This is useful in places like error
1306      * handling, where you want to close all the open containers (apart from <body>)
1307      * before outputting the error message.
1308      *
1309      * @param bool $shouldbenone assert that the stack should be empty now - causes a
1310      *      developer debug warning if it isn't.
1311      * @return string the HTML required to close any open containers inside <body>.
1312      */
1313     public function container_end_all($shouldbenone = false) {
1314         return $this->opencontainers->pop_all_but_last($shouldbenone);
1315     }
1317     /**
1318      * Returns course-specific information to be output immediately above content on any course page
1319      * (for the current course)
1320      *
1321      * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1322      * @return string
1323      */
1324     public function course_content_header($onlyifnotcalledbefore = false) {
1325         global $CFG;
1326         static $functioncalled = false;
1327         if ($functioncalled && $onlyifnotcalledbefore) {
1328             // we have already output the content header
1329             return '';
1330         }
1332         // Output any session notification.
1333         $notifications = \core\notification::fetch();
1335         $bodynotifications = '';
1336         foreach ($notifications as $notification) {
1337             $bodynotifications .= $this->render_from_template(
1338                     $notification->get_template_name(),
1339                     $notification->export_for_template($this)
1340                 );
1341         }
1343         $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1345         if ($this->page->course->id == SITEID) {
1346             // return immediately and do not include /course/lib.php if not necessary
1347             return $output;
1348         }
1350         require_once($CFG->dirroot.'/course/lib.php');
1351         $functioncalled = true;
1352         $courseformat = course_get_format($this->page->course);
1353         if (($obj = $courseformat->course_content_header()) !== null) {
1354             $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1355         }
1356         return $output;
1357     }
1359     /**
1360      * Returns course-specific information to be output immediately below content on any course page
1361      * (for the current course)
1362      *
1363      * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1364      * @return string
1365      */
1366     public function course_content_footer($onlyifnotcalledbefore = false) {
1367         global $CFG;
1368         if ($this->page->course->id == SITEID) {
1369             // return immediately and do not include /course/lib.php if not necessary
1370             return '';
1371         }
1372         static $functioncalled = false;
1373         if ($functioncalled && $onlyifnotcalledbefore) {
1374             // we have already output the content footer
1375             return '';
1376         }
1377         $functioncalled = true;
1378         require_once($CFG->dirroot.'/course/lib.php');
1379         $courseformat = course_get_format($this->page->course);
1380         if (($obj = $courseformat->course_content_footer()) !== null) {
1381             return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1382         }
1383         return '';
1384     }
1386     /**
1387      * Returns course-specific information to be output on any course page in the header area
1388      * (for the current course)
1389      *
1390      * @return string
1391      */
1392     public function course_header() {
1393         global $CFG;
1394         if ($this->page->course->id == SITEID) {
1395             // return immediately and do not include /course/lib.php if not necessary
1396             return '';
1397         }
1398         require_once($CFG->dirroot.'/course/lib.php');
1399         $courseformat = course_get_format($this->page->course);
1400         if (($obj = $courseformat->course_header()) !== null) {
1401             return $courseformat->get_renderer($this->page)->render($obj);
1402         }
1403         return '';
1404     }
1406     /**
1407      * Returns course-specific information to be output on any course page in the footer area
1408      * (for the current course)
1409      *
1410      * @return string
1411      */
1412     public function course_footer() {
1413         global $CFG;
1414         if ($this->page->course->id == SITEID) {
1415             // return immediately and do not include /course/lib.php if not necessary
1416             return '';
1417         }
1418         require_once($CFG->dirroot.'/course/lib.php');
1419         $courseformat = course_get_format($this->page->course);
1420         if (($obj = $courseformat->course_footer()) !== null) {
1421             return $courseformat->get_renderer($this->page)->render($obj);
1422         }
1423         return '';
1424     }
1426     /**
1427      * Returns lang menu or '', this method also checks forcing of languages in courses.
1428      *
1429      * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1430      *
1431      * @return string The lang menu HTML or empty string
1432      */
1433     public function lang_menu() {
1434         global $CFG;
1436         if (empty($CFG->langmenu)) {
1437             return '';
1438         }
1440         if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1441             // do not show lang menu if language forced
1442             return '';
1443         }
1445         $currlang = current_language();
1446         $langs = get_string_manager()->get_list_of_translations();
1448         if (count($langs) < 2) {
1449             return '';
1450         }
1452         $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1453         $s->label = get_accesshide(get_string('language'));
1454         $s->class = 'langmenu';
1455         return $this->render($s);
1456     }
1458     /**
1459      * Output the row of editing icons for a block, as defined by the controls array.
1460      *
1461      * @param array $controls an array like {@link block_contents::$controls}.
1462      * @param string $blockid The ID given to the block.
1463      * @return string HTML fragment.
1464      */
1465     public function block_controls($actions, $blockid = null) {
1466         global $CFG;
1467         if (empty($actions)) {
1468             return '';
1469         }
1470         $menu = new action_menu($actions);
1471         if ($blockid !== null) {
1472             $menu->set_owner_selector('#'.$blockid);
1473         }
1474         $menu->set_constraint('.block-region');
1475         $menu->attributes['class'] .= ' block-control-actions commands';
1476         return $this->render($menu);
1477     }
1479     /**
1480      * Renders an action menu component.
1481      *
1482      * ARIA references:
1483      *   - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1484      *   - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1485      *
1486      * @param action_menu $menu
1487      * @return string HTML
1488      */
1489     public function render_action_menu(action_menu $menu) {
1490         $context = $menu->export_for_template($this);
1491         return $this->render_from_template('core/action_menu', $context);
1492     }
1494     /**
1495      * Renders an action_menu_link item.
1496      *
1497      * @param action_menu_link $action
1498      * @return string HTML fragment
1499      */
1500     protected function render_action_menu_link(action_menu_link $action) {
1501         return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1502     }
1504     /**
1505      * Renders a primary action_menu_filler item.
1506      *
1507      * @param action_menu_link_filler $action
1508      * @return string HTML fragment
1509      */
1510     protected function render_action_menu_filler(action_menu_filler $action) {
1511         return html_writer::span('&nbsp;', 'filler');
1512     }
1514     /**
1515      * Renders a primary action_menu_link item.
1516      *
1517      * @param action_menu_link_primary $action
1518      * @return string HTML fragment
1519      */
1520     protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1521         return $this->render_action_menu_link($action);
1522     }
1524     /**
1525      * Renders a secondary action_menu_link item.
1526      *
1527      * @param action_menu_link_secondary $action
1528      * @return string HTML fragment
1529      */
1530     protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1531         return $this->render_action_menu_link($action);
1532     }
1534     /**
1535      * Prints a nice side block with an optional header.
1536      *
1537      * The content is described
1538      * by a {@link core_renderer::block_contents} object.
1539      *
1540      * <div id="inst{$instanceid}" class="block_{$blockname} block">
1541      *      <div class="header"></div>
1542      *      <div class="content">
1543      *          ...CONTENT...
1544      *          <div class="footer">
1545      *          </div>
1546      *      </div>
1547      *      <div class="annotation">
1548      *      </div>
1549      * </div>
1550      *
1551      * @param block_contents $bc HTML for the content
1552      * @param string $region the region the block is appearing in.
1553      * @return string the HTML to be output.
1554      */
1555     public function block(block_contents $bc, $region) {
1556         $bc = clone($bc); // Avoid messing up the object passed in.
1557         if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1558             $bc->collapsible = block_contents::NOT_HIDEABLE;
1559         }
1560         if (!empty($bc->blockinstanceid)) {
1561             $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1562         }
1563         $skiptitle = strip_tags($bc->title);
1564         if ($bc->blockinstanceid && !empty($skiptitle)) {
1565             $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1566         } else if (!empty($bc->arialabel)) {
1567             $bc->attributes['aria-label'] = $bc->arialabel;
1568         }
1569         if ($bc->dockable) {
1570             $bc->attributes['data-dockable'] = 1;
1571         }
1572         if ($bc->collapsible == block_contents::HIDDEN) {
1573             $bc->add_class('hidden');
1574         }
1575         if (!empty($bc->controls)) {
1576             $bc->add_class('block_with_controls');
1577         }
1580         if (empty($skiptitle)) {
1581             $output = '';
1582             $skipdest = '';
1583         } else {
1584             $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1585                       array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1586             $skipdest = html_writer::span('', 'skip-block-to',
1587                       array('id' => 'sb-' . $bc->skipid));
1588         }
1590         $output .= html_writer::start_tag('div', $bc->attributes);
1592         $output .= $this->block_header($bc);
1593         $output .= $this->block_content($bc);
1595         $output .= html_writer::end_tag('div');
1597         $output .= $this->block_annotation($bc);
1599         $output .= $skipdest;
1601         $this->init_block_hider_js($bc);
1602         return $output;
1603     }
1605     /**
1606      * Produces a header for a block
1607      *
1608      * @param block_contents $bc
1609      * @return string
1610      */
1611     protected function block_header(block_contents $bc) {
1613         $title = '';
1614         if ($bc->title) {
1615             $attributes = array();
1616             if ($bc->blockinstanceid) {
1617                 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1618             }
1619             $title = html_writer::tag('h2', $bc->title, $attributes);
1620         }
1622         $blockid = null;
1623         if (isset($bc->attributes['id'])) {
1624             $blockid = $bc->attributes['id'];
1625         }
1626         $controlshtml = $this->block_controls($bc->controls, $blockid);
1628         $output = '';
1629         if ($title || $controlshtml) {
1630             $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'));
1631         }
1632         return $output;
1633     }
1635     /**
1636      * Produces the content area for a block
1637      *
1638      * @param block_contents $bc
1639      * @return string
1640      */
1641     protected function block_content(block_contents $bc) {
1642         $output = html_writer::start_tag('div', array('class' => 'content'));
1643         if (!$bc->title && !$this->block_controls($bc->controls)) {
1644             $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1645         }
1646         $output .= $bc->content;
1647         $output .= $this->block_footer($bc);
1648         $output .= html_writer::end_tag('div');
1650         return $output;
1651     }
1653     /**
1654      * Produces the footer for a block
1655      *
1656      * @param block_contents $bc
1657      * @return string
1658      */
1659     protected function block_footer(block_contents $bc) {
1660         $output = '';
1661         if ($bc->footer) {
1662             $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1663         }
1664         return $output;
1665     }
1667     /**
1668      * Produces the annotation for a block
1669      *
1670      * @param block_contents $bc
1671      * @return string
1672      */
1673     protected function block_annotation(block_contents $bc) {
1674         $output = '';
1675         if ($bc->annotation) {
1676             $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1677         }
1678         return $output;
1679     }
1681     /**
1682      * Calls the JS require function to hide a block.
1683      *
1684      * @param block_contents $bc A block_contents object
1685      */
1686     protected function init_block_hider_js(block_contents $bc) {
1687         if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1688             $config = new stdClass;
1689             $config->id = $bc->attributes['id'];
1690             $config->title = strip_tags($bc->title);
1691             $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1692             $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1693             $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1695             $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1696             user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1697         }
1698     }
1700     /**
1701      * Render the contents of a block_list.
1702      *
1703      * @param array $icons the icon for each item.
1704      * @param array $items the content of each item.
1705      * @return string HTML
1706      */
1707     public function list_block_contents($icons, $items) {
1708         $row = 0;
1709         $lis = array();
1710         foreach ($items as $key => $string) {
1711             $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1712             if (!empty($icons[$key])) { //test if the content has an assigned icon
1713                 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1714             }
1715             $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1716             $item .= html_writer::end_tag('li');
1717             $lis[] = $item;
1718             $row = 1 - $row; // Flip even/odd.
1719         }
1720         return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1721     }
1723     /**
1724      * Output all the blocks in a particular region.
1725      *
1726      * @param string $region the name of a region on this page.
1727      * @return string the HTML to be output.
1728      */
1729     public function blocks_for_region($region) {
1730         $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1731         $blocks = $this->page->blocks->get_blocks_for_region($region);
1732         $lastblock = null;
1733         $zones = array();
1734         foreach ($blocks as $block) {
1735             $zones[] = $block->title;
1736         }
1737         $output = '';
1739         foreach ($blockcontents as $bc) {
1740             if ($bc instanceof block_contents) {
1741                 $output .= $this->block($bc, $region);
1742                 $lastblock = $bc->title;
1743             } else if ($bc instanceof block_move_target) {
1744                 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1745             } else {
1746                 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1747             }
1748         }
1749         return $output;
1750     }
1752     /**
1753      * Output a place where the block that is currently being moved can be dropped.
1754      *
1755      * @param block_move_target $target with the necessary details.
1756      * @param array $zones array of areas where the block can be moved to
1757      * @param string $previous the block located before the area currently being rendered.
1758      * @param string $region the name of the region
1759      * @return string the HTML to be output.
1760      */
1761     public function block_move_target($target, $zones, $previous, $region) {
1762         if ($previous == null) {
1763             if (empty($zones)) {
1764                 // There are no zones, probably because there are no blocks.
1765                 $regions = $this->page->theme->get_all_block_regions();
1766                 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1767             } else {
1768                 $position = get_string('moveblockbefore', 'block', $zones[0]);
1769             }
1770         } else {
1771             $position = get_string('moveblockafter', 'block', $previous);
1772         }
1773         return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1774     }
1776     /**
1777      * Renders a special html link with attached action
1778      *
1779      * Theme developers: DO NOT OVERRIDE! Please override function
1780      * {@link core_renderer::render_action_link()} instead.
1781      *
1782      * @param string|moodle_url $url
1783      * @param string $text HTML fragment
1784      * @param component_action $action
1785      * @param array $attributes associative array of html link attributes + disabled
1786      * @param pix_icon optional pix icon to render with the link
1787      * @return string HTML fragment
1788      */
1789     public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1790         if (!($url instanceof moodle_url)) {
1791             $url = new moodle_url($url);
1792         }
1793         $link = new action_link($url, $text, $action, $attributes, $icon);
1795         return $this->render($link);
1796     }
1798     /**
1799      * Renders an action_link object.
1800      *
1801      * The provided link is renderer and the HTML returned. At the same time the
1802      * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1803      *
1804      * @param action_link $link
1805      * @return string HTML fragment
1806      */
1807     protected function render_action_link(action_link $link) {
1808         return $this->render_from_template('core/action_link', $link->export_for_template($this));
1809     }
1811     /**
1812      * Renders an action_icon.
1813      *
1814      * This function uses the {@link core_renderer::action_link()} method for the
1815      * most part. What it does different is prepare the icon as HTML and use it
1816      * as the link text.
1817      *
1818      * Theme developers: If you want to change how action links and/or icons are rendered,
1819      * consider overriding function {@link core_renderer::render_action_link()} and
1820      * {@link core_renderer::render_pix_icon()}.
1821      *
1822      * @param string|moodle_url $url A string URL or moodel_url
1823      * @param pix_icon $pixicon
1824      * @param component_action $action
1825      * @param array $attributes associative array of html link attributes + disabled
1826      * @param bool $linktext show title next to image in link
1827      * @return string HTML fragment
1828      */
1829     public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1830         if (!($url instanceof moodle_url)) {
1831             $url = new moodle_url($url);
1832         }
1833         $attributes = (array)$attributes;
1835         if (empty($attributes['class'])) {
1836             // let ppl override the class via $options
1837             $attributes['class'] = 'action-icon';
1838         }
1840         $icon = $this->render($pixicon);
1842         if ($linktext) {
1843             $text = $pixicon->attributes['alt'];
1844         } else {
1845             $text = '';
1846         }
1848         return $this->action_link($url, $text.$icon, $action, $attributes);
1849     }
1851    /**
1852     * Print a message along with button choices for Continue/Cancel
1853     *
1854     * If a string or moodle_url is given instead of a single_button, method defaults to post.
1855     *
1856     * @param string $message The question to ask the user
1857     * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1858     * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1859     * @return string HTML fragment
1860     */
1861     public function confirm($message, $continue, $cancel) {
1862         if ($continue instanceof single_button) {
1863             // ok
1864             $continue->primary = true;
1865         } else if (is_string($continue)) {
1866             $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1867         } else if ($continue instanceof moodle_url) {
1868             $continue = new single_button($continue, get_string('continue'), 'post', true);
1869         } else {
1870             throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1871         }
1873         if ($cancel instanceof single_button) {
1874             // ok
1875         } else if (is_string($cancel)) {
1876             $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1877         } else if ($cancel instanceof moodle_url) {
1878             $cancel = new single_button($cancel, get_string('cancel'), 'get');
1879         } else {
1880             throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1881         }
1883         $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1884         $output .= $this->box_start('modal-content', 'modal-content');
1885         $output .= $this->box_start('modal-header', 'modal-header');
1886         $output .= html_writer::tag('h4', get_string('confirm'));
1887         $output .= $this->box_end();
1888         $output .= $this->box_start('modal-body', 'modal-body');
1889         $output .= html_writer::tag('p', $message);
1890         $output .= $this->box_end();
1891         $output .= $this->box_start('modal-footer', 'modal-footer');
1892         $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1893         $output .= $this->box_end();
1894         $output .= $this->box_end();
1895         $output .= $this->box_end();
1896         return $output;
1897     }
1899     /**
1900      * Returns a form with a single button.
1901      *
1902      * Theme developers: DO NOT OVERRIDE! Please override function
1903      * {@link core_renderer::render_single_button()} instead.
1904      *
1905      * @param string|moodle_url $url
1906      * @param string $label button text
1907      * @param string $method get or post submit method
1908      * @param array $options associative array {disabled, title, etc.}
1909      * @return string HTML fragment
1910      */
1911     public function single_button($url, $label, $method='post', array $options=null) {
1912         if (!($url instanceof moodle_url)) {
1913             $url = new moodle_url($url);
1914         }
1915         $button = new single_button($url, $label, $method);
1917         foreach ((array)$options as $key=>$value) {
1918             if (array_key_exists($key, $button)) {
1919                 $button->$key = $value;
1920             }
1921         }
1923         return $this->render($button);
1924     }
1926     /**
1927      * Renders a single button widget.
1928      *
1929      * This will return HTML to display a form containing a single button.
1930      *
1931      * @param single_button $button
1932      * @return string HTML fragment
1933      */
1934     protected function render_single_button(single_button $button) {
1935         $attributes = array('type'     => 'submit',
1936                             'value'    => $button->label,
1937                             'disabled' => $button->disabled ? 'disabled' : null,
1938                             'title'    => $button->tooltip);
1940         if ($button->actions) {
1941             $id = html_writer::random_id('single_button');
1942             $attributes['id'] = $id;
1943             foreach ($button->actions as $action) {
1944                 $this->add_action_handler($action, $id);
1945             }
1946         }
1948         // first the input element
1949         $output = html_writer::empty_tag('input', $attributes);
1951         // then hidden fields
1952         $params = $button->url->params();
1953         if ($button->method === 'post') {
1954             $params['sesskey'] = sesskey();
1955         }
1956         foreach ($params as $var => $val) {
1957             $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1958         }
1960         // then div wrapper for xhtml strictness
1961         $output = html_writer::tag('div', $output);
1963         // now the form itself around it
1964         if ($button->method === 'get') {
1965             $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1966         } else {
1967             $url = $button->url->out_omit_querystring();     // url without params, the anchor part not allowed
1968         }
1969         if ($url === '') {
1970             $url = '#'; // there has to be always some action
1971         }
1972         $attributes = array('method' => $button->method,
1973                             'action' => $url,
1974                             'id'     => $button->formid);
1975         $output = html_writer::tag('form', $output, $attributes);
1977         // and finally one more wrapper with class
1978         return html_writer::tag('div', $output, array('class' => $button->class));
1979     }
1981     /**
1982      * Returns a form with a single select widget.
1983      *
1984      * Theme developers: DO NOT OVERRIDE! Please override function
1985      * {@link core_renderer::render_single_select()} instead.
1986      *
1987      * @param moodle_url $url form action target, includes hidden fields
1988      * @param string $name name of selection field - the changing parameter in url
1989      * @param array $options list of options
1990      * @param string $selected selected element
1991      * @param array $nothing
1992      * @param string $formid
1993      * @param array $attributes other attributes for the single select
1994      * @return string HTML fragment
1995      */
1996     public function single_select($url, $name, array $options, $selected = '',
1997                                 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1998         if (!($url instanceof moodle_url)) {
1999             $url = new moodle_url($url);
2000         }
2001         $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2003         if (array_key_exists('label', $attributes)) {
2004             $select->set_label($attributes['label']);
2005             unset($attributes['label']);
2006         }
2007         $select->attributes = $attributes;
2009         return $this->render($select);
2010     }
2012     /**
2013      * Returns a dataformat selection and download form
2014      *
2015      * @param string $label A text label
2016      * @param moodle_url|string $base The download page url
2017      * @param string $name The query param which will hold the type of the download
2018      * @param array $params Extra params sent to the download page
2019      * @return string HTML fragment
2020      */
2021     public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2023         $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2024         $options = array();
2025         foreach ($formats as $format) {
2026             if ($format->is_enabled()) {
2027                 $options[] = array(
2028                     'value' => $format->name,
2029                     'label' => get_string('dataformat', $format->component),
2030                 );
2031             }
2032         }
2033         $hiddenparams = array();
2034         foreach ($params as $key => $value) {
2035             $hiddenparams[] = array(
2036                 'name' => $key,
2037                 'value' => $value,
2038             );
2039         }
2040         $data = array(
2041             'label' => $label,
2042             'base' => $base,
2043             'name' => $name,
2044             'params' => $hiddenparams,
2045             'options' => $options,
2046             'sesskey' => sesskey(),
2047             'submit' => get_string('download'),
2048         );
2050         return $this->render_from_template('core/dataformat_selector', $data);
2051     }
2054     /**
2055      * Internal implementation of single_select rendering
2056      *
2057      * @param single_select $select
2058      * @return string HTML fragment
2059      */
2060     protected function render_single_select(single_select $select) {
2061         return $this->render_from_template('core/single_select', $select->export_for_template($this));
2062     }
2064     /**
2065      * Returns a form with a url select widget.
2066      *
2067      * Theme developers: DO NOT OVERRIDE! Please override function
2068      * {@link core_renderer::render_url_select()} instead.
2069      *
2070      * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2071      * @param string $selected selected element
2072      * @param array $nothing
2073      * @param string $formid
2074      * @return string HTML fragment
2075      */
2076     public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2077         $select = new url_select($urls, $selected, $nothing, $formid);
2078         return $this->render($select);
2079     }
2081     /**
2082      * Internal implementation of url_select rendering
2083      *
2084      * @param url_select $select
2085      * @return string HTML fragment
2086      */
2087     protected function render_url_select(url_select $select) {
2088         return $this->render_from_template('core/url_select', $select->export_for_template($this));
2089     }
2091     /**
2092      * Returns a string containing a link to the user documentation.
2093      * Also contains an icon by default. Shown to teachers and admin only.
2094      *
2095      * @param string $path The page link after doc root and language, no leading slash.
2096      * @param string $text The text to be displayed for the link
2097      * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2098      * @return string
2099      */
2100     public function doc_link($path, $text = '', $forcepopup = false) {
2101         global $CFG;
2103         $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2105         $url = new moodle_url(get_docs_url($path));
2107         $attributes = array('href'=>$url);
2108         if (!empty($CFG->doctonewwindow) || $forcepopup) {
2109             $attributes['class'] = 'helplinkpopup';
2110         }
2112         return html_writer::tag('a', $icon.$text, $attributes);
2113     }
2115     /**
2116      * Return HTML for an image_icon.
2117      *
2118      * Theme developers: DO NOT OVERRIDE! Please override function
2119      * {@link core_renderer::render_image_icon()} instead.
2120      *
2121      * @param string $pix short pix name
2122      * @param string $alt mandatory alt attribute
2123      * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2124      * @param array $attributes htm lattributes
2125      * @return string HTML fragment
2126      */
2127     public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2128         $icon = new image_icon($pix, $alt, $component, $attributes);
2129         return $this->render($icon);
2130     }
2132     /**
2133      * Renders a pix_icon widget and returns the HTML to display it.
2134      *
2135      * @param image_icon $icon
2136      * @return string HTML fragment
2137      */
2138     protected function render_image_icon(image_icon $icon) {
2139         $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2140         return $system->render_pix_icon($this, $icon);
2141     }
2143     /**
2144      * Return HTML for a pix_icon.
2145      *
2146      * Theme developers: DO NOT OVERRIDE! Please override function
2147      * {@link core_renderer::render_pix_icon()} instead.
2148      *
2149      * @param string $pix short pix name
2150      * @param string $alt mandatory alt attribute
2151      * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2152      * @param array $attributes htm lattributes
2153      * @return string HTML fragment
2154      */
2155     public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2156         $icon = new pix_icon($pix, $alt, $component, $attributes);
2157         return $this->render($icon);
2158     }
2160     /**
2161      * Renders a pix_icon widget and returns the HTML to display it.
2162      *
2163      * @param pix_icon $icon
2164      * @return string HTML fragment
2165      */
2166     protected function render_pix_icon(pix_icon $icon) {
2167         $system = \core\output\icon_system::instance();
2168         return $system->render_pix_icon($this, $icon);
2169     }
2171     /**
2172      * Return HTML to display an emoticon icon.
2173      *
2174      * @param pix_emoticon $emoticon
2175      * @return string HTML fragment
2176      */
2177     protected function render_pix_emoticon(pix_emoticon $emoticon) {
2178         $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2179         return $system->render_pix_icon($this, $emoticon);
2180     }
2182     /**
2183      * Produces the html that represents this rating in the UI
2184      *
2185      * @param rating $rating the page object on which this rating will appear
2186      * @return string
2187      */
2188     function render_rating(rating $rating) {
2189         global $CFG, $USER;
2191         if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2192             return null;//ratings are turned off
2193         }
2195         $ratingmanager = new rating_manager();
2196         // Initialise the JavaScript so ratings can be done by AJAX.
2197         $ratingmanager->initialise_rating_javascript($this->page);
2199         $strrate = get_string("rate", "rating");
2200         $ratinghtml = ''; //the string we'll return
2202         // permissions check - can they view the aggregate?
2203         if ($rating->user_can_view_aggregate()) {
2205             $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2206             $aggregatestr   = $rating->get_aggregate_string();
2208             $aggregatehtml  = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2209             if ($rating->count > 0) {
2210                 $countstr = "({$rating->count})";
2211             } else {
2212                 $countstr = '-';
2213             }
2214             $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2216             $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2217             if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2219                 $nonpopuplink = $rating->get_view_ratings_url();
2220                 $popuplink = $rating->get_view_ratings_url(true);
2222                 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2223                 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2224             } else {
2225                 $ratinghtml .= $aggregatehtml;
2226             }
2227         }
2229         $formstart = null;
2230         // if the item doesn't belong to the current user, the user has permission to rate
2231         // and we're within the assessable period
2232         if ($rating->user_can_rate()) {
2234             $rateurl = $rating->get_rate_url();
2235             $inputs = $rateurl->params();
2237             //start the rating form
2238             $formattrs = array(
2239                 'id'     => "postrating{$rating->itemid}",
2240                 'class'  => 'postratingform',
2241                 'method' => 'post',
2242                 'action' => $rateurl->out_omit_querystring()
2243             );
2244             $formstart  = html_writer::start_tag('form', $formattrs);
2245             $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2247             // add the hidden inputs
2248             foreach ($inputs as $name => $value) {
2249                 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2250                 $formstart .= html_writer::empty_tag('input', $attributes);
2251             }
2253             if (empty($ratinghtml)) {
2254                 $ratinghtml .= $strrate.': ';
2255             }
2256             $ratinghtml = $formstart.$ratinghtml;
2258             $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2259             $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2260             $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2261             $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2263             //output submit button
2264             $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2266             $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2267             $ratinghtml .= html_writer::empty_tag('input', $attributes);
2269             if (!$rating->settings->scale->isnumeric) {
2270                 // If a global scale, try to find current course ID from the context
2271                 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2272                     $courseid = $coursecontext->instanceid;
2273                 } else {
2274                     $courseid = $rating->settings->scale->courseid;
2275                 }
2276                 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2277             }
2278             $ratinghtml .= html_writer::end_tag('span');
2279             $ratinghtml .= html_writer::end_tag('div');
2280             $ratinghtml .= html_writer::end_tag('form');
2281         }
2283         return $ratinghtml;
2284     }
2286     /**
2287      * Centered heading with attached help button (same title text)
2288      * and optional icon attached.
2289      *
2290      * @param string $text A heading text
2291      * @param string $helpidentifier The keyword that defines a help page
2292      * @param string $component component name
2293      * @param string|moodle_url $icon
2294      * @param string $iconalt icon alt text
2295      * @param int $level The level of importance of the heading. Defaulting to 2
2296      * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2297      * @return string HTML fragment
2298      */
2299     public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2300         $image = '';
2301         if ($icon) {
2302             $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2303         }
2305         $help = '';
2306         if ($helpidentifier) {
2307             $help = $this->help_icon($helpidentifier, $component);
2308         }
2310         return $this->heading($image.$text.$help, $level, $classnames);
2311     }
2313     /**
2314      * Returns HTML to display a help icon.
2315      *
2316      * @deprecated since Moodle 2.0
2317      */
2318     public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2319         throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2320     }
2322     /**
2323      * Returns HTML to display a help icon.
2324      *
2325      * Theme developers: DO NOT OVERRIDE! Please override function
2326      * {@link core_renderer::render_help_icon()} instead.
2327      *
2328      * @param string $identifier The keyword that defines a help page
2329      * @param string $component component name
2330      * @param string|bool $linktext true means use $title as link text, string means link text value
2331      * @return string HTML fragment
2332      */
2333     public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2334         $icon = new help_icon($identifier, $component);
2335         $icon->diag_strings();
2336         if ($linktext === true) {
2337             $icon->linktext = get_string($icon->identifier, $icon->component);
2338         } else if (!empty($linktext)) {
2339             $icon->linktext = $linktext;
2340         }
2341         return $this->render($icon);
2342     }
2344     /**
2345      * Implementation of user image rendering.
2346      *
2347      * @param help_icon $helpicon A help icon instance
2348      * @return string HTML fragment
2349      */
2350     protected function render_help_icon(help_icon $helpicon) {
2351         return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2352     }
2354     /**
2355      * Returns HTML to display a scale help icon.
2356      *
2357      * @param int $courseid
2358      * @param stdClass $scale instance
2359      * @return string HTML fragment
2360      */
2361     public function help_icon_scale($courseid, stdClass $scale) {
2362         global $CFG;
2364         $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2366         $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2368         $scaleid = abs($scale->id);
2370         $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2371         $action = new popup_action('click', $link, 'ratingscale');
2373         return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2374     }
2376     /**
2377      * Creates and returns a spacer image with optional line break.
2378      *
2379      * @param array $attributes Any HTML attributes to add to the spaced.
2380      * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2381      *     laxy do it with CSS which is a much better solution.
2382      * @return string HTML fragment
2383      */
2384     public function spacer(array $attributes = null, $br = false) {
2385         $attributes = (array)$attributes;
2386         if (empty($attributes['width'])) {
2387             $attributes['width'] = 1;
2388         }
2389         if (empty($attributes['height'])) {
2390             $attributes['height'] = 1;
2391         }
2392         $attributes['class'] = 'spacer';
2394         $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2396         if (!empty($br)) {
2397             $output .= '<br />';
2398         }
2400         return $output;
2401     }
2403     /**
2404      * Returns HTML to display the specified user's avatar.
2405      *
2406      * User avatar may be obtained in two ways:
2407      * <pre>
2408      * // Option 1: (shortcut for simple cases, preferred way)
2409      * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2410      * $OUTPUT->user_picture($user, array('popup'=>true));
2411      *
2412      * // Option 2:
2413      * $userpic = new user_picture($user);
2414      * // Set properties of $userpic
2415      * $userpic->popup = true;
2416      * $OUTPUT->render($userpic);
2417      * </pre>
2418      *
2419      * Theme developers: DO NOT OVERRIDE! Please override function
2420      * {@link core_renderer::render_user_picture()} instead.
2421      *
2422      * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2423      *     If any of these are missing, the database is queried. Avoid this
2424      *     if at all possible, particularly for reports. It is very bad for performance.
2425      * @param array $options associative array with user picture options, used only if not a user_picture object,
2426      *     options are:
2427      *     - courseid=$this->page->course->id (course id of user profile in link)
2428      *     - size=35 (size of image)
2429      *     - link=true (make image clickable - the link leads to user profile)
2430      *     - popup=false (open in popup)
2431      *     - alttext=true (add image alt attribute)
2432      *     - class = image class attribute (default 'userpicture')
2433      *     - visibletoscreenreaders=true (whether to be visible to screen readers)
2434      *     - includefullname=false (whether to include the user's full name together with the user picture)
2435      * @return string HTML fragment
2436      */
2437     public function user_picture(stdClass $user, array $options = null) {
2438         $userpicture = new user_picture($user);
2439         foreach ((array)$options as $key=>$value) {
2440             if (array_key_exists($key, $userpicture)) {
2441                 $userpicture->$key = $value;
2442             }
2443         }
2444         return $this->render($userpicture);
2445     }
2447     /**
2448      * Internal implementation of user image rendering.
2449      *
2450      * @param user_picture $userpicture
2451      * @return string
2452      */
2453     protected function render_user_picture(user_picture $userpicture) {
2454         global $CFG, $DB;
2456         $user = $userpicture->user;
2458         if ($userpicture->alttext) {
2459             if (!empty($user->imagealt)) {
2460                 $alt = $user->imagealt;
2461             } else {
2462                 $alt = get_string('pictureof', '', fullname($user));
2463             }
2464         } else {
2465             $alt = '';
2466         }
2468         if (empty($userpicture->size)) {
2469             $size = 35;
2470         } else if ($userpicture->size === true or $userpicture->size == 1) {
2471             $size = 100;
2472         } else {
2473             $size = $userpicture->size;
2474         }
2476         $class = $userpicture->class;
2478         if ($user->picture == 0) {
2479             $class .= ' defaultuserpic';
2480         }
2482         $src = $userpicture->get_url($this->page, $this);
2484         $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2485         if (!$userpicture->visibletoscreenreaders) {
2486             $attributes['role'] = 'presentation';
2487         }
2489         // get the image html output fisrt
2490         $output = html_writer::empty_tag('img', $attributes);
2492         // Show fullname together with the picture when desired.
2493         if ($userpicture->includefullname) {
2494             $output .= fullname($userpicture->user);
2495         }
2497         // then wrap it in link if needed
2498         if (!$userpicture->link) {
2499             return $output;
2500         }
2502         if (empty($userpicture->courseid)) {
2503             $courseid = $this->page->course->id;
2504         } else {
2505             $courseid = $userpicture->courseid;
2506         }
2508         if ($courseid == SITEID) {
2509             $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2510         } else {
2511             $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2512         }
2514         $attributes = array('href'=>$url);
2515         if (!$userpicture->visibletoscreenreaders) {
2516             $attributes['tabindex'] = '-1';
2517             $attributes['aria-hidden'] = 'true';
2518         }
2520         if ($userpicture->popup) {
2521             $id = html_writer::random_id('userpicture');
2522             $attributes['id'] = $id;
2523             $this->add_action_handler(new popup_action('click', $url), $id);
2524         }
2526         return html_writer::tag('a', $output, $attributes);
2527     }
2529     /**
2530      * Internal implementation of file tree viewer items rendering.
2531      *
2532      * @param array $dir
2533      * @return string
2534      */
2535     public function htmllize_file_tree($dir) {
2536         if (empty($dir['subdirs']) and empty($dir['files'])) {
2537             return '';
2538         }
2539         $result = '<ul>';
2540         foreach ($dir['subdirs'] as $subdir) {
2541             $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2542         }
2543         foreach ($dir['files'] as $file) {
2544             $filename = $file->get_filename();
2545             $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2546         }
2547         $result .= '</ul>';
2549         return $result;
2550     }
2552     /**
2553      * Returns HTML to display the file picker
2554      *
2555      * <pre>
2556      * $OUTPUT->file_picker($options);
2557      * </pre>
2558      *
2559      * Theme developers: DO NOT OVERRIDE! Please override function
2560      * {@link core_renderer::render_file_picker()} instead.
2561      *
2562      * @param array $options associative array with file manager options
2563      *   options are:
2564      *       maxbytes=>-1,
2565      *       itemid=>0,
2566      *       client_id=>uniqid(),
2567      *       acepted_types=>'*',
2568      *       return_types=>FILE_INTERNAL,
2569      *       context=>$PAGE->context
2570      * @return string HTML fragment
2571      */
2572     public function file_picker($options) {
2573         $fp = new file_picker($options);
2574         return $this->render($fp);
2575     }
2577     /**
2578      * Internal implementation of file picker rendering.
2579      *
2580      * @param file_picker $fp
2581      * @return string
2582      */
2583     public function render_file_picker(file_picker $fp) {
2584         global $CFG, $OUTPUT, $USER;
2585         $options = $fp->options;
2586         $client_id = $options->client_id;
2587         $strsaved = get_string('filesaved', 'repository');
2588         $straddfile = get_string('openpicker', 'repository');
2589         $strloading  = get_string('loading', 'repository');
2590         $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2591         $strdroptoupload = get_string('droptoupload', 'moodle');
2592         $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2594         $currentfile = $options->currentfile;
2595         if (empty($currentfile)) {
2596             $currentfile = '';
2597         } else {
2598             $currentfile .= ' - ';
2599         }
2600         if ($options->maxbytes) {
2601             $size = $options->maxbytes;
2602         } else {
2603             $size = get_max_upload_file_size();
2604         }
2605         if ($size == -1) {
2606             $maxsize = '';
2607         } else {
2608             $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2609         }
2610         if ($options->buttonname) {
2611             $buttonname = ' name="' . $options->buttonname . '"';
2612         } else {
2613             $buttonname = '';
2614         }
2615         $html = <<<EOD
2616 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2617 $icon_progress
2618 </div>
2619 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2620     <div>
2621         <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2622         <span> $maxsize </span>
2623     </div>
2624 EOD;
2625         if ($options->env != 'url') {
2626             $html .= <<<EOD
2627     <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2628     <div class="filepicker-filename">
2629         <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2630         <div class="dndupload-progressbars"></div>
2631     </div>
2632     <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2633     </div>
2634 EOD;
2635         }
2636         $html .= '</div>';
2637         return $html;
2638     }
2640     /**
2641      * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2642      *
2643      * @deprecated since Moodle 3.2
2644      *
2645      * @param string $cmid the course_module id.
2646      * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2647      * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2648      */
2649     public function update_module_button($cmid, $modulename) {
2650         global $CFG;
2652         debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2653             'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2654             'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2656         if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2657             $modulename = get_string('modulename', $modulename);
2658             $string = get_string('updatethis', '', $modulename);
2659             $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2660             return $this->single_button($url, $string);
2661         } else {
2662             return '';
2663         }
2664     }
2666     /**
2667      * Returns HTML to display a "Turn editing on/off" button in a form.
2668      *
2669      * @param moodle_url $url The URL + params to send through when clicking the button
2670      * @return string HTML the button
2671      */
2672     public function edit_button(moodle_url $url) {
2674         $url->param('sesskey', sesskey());
2675         if ($this->page->user_is_editing()) {
2676             $url->param('edit', 'off');
2677             $editstring = get_string('turneditingoff');
2678         } else {
2679             $url->param('edit', 'on');
2680             $editstring = get_string('turneditingon');
2681         }
2683         return $this->single_button($url, $editstring);
2684     }
2686     /**
2687      * Returns HTML to display a simple button to close a window
2688      *
2689      * @param string $text The lang string for the button's label (already output from get_string())
2690      * @return string html fragment
2691      */
2692     public function close_window_button($text='') {
2693         if (empty($text)) {
2694             $text = get_string('closewindow');
2695         }
2696         $button = new single_button(new moodle_url('#'), $text, 'get');
2697         $button->add_action(new component_action('click', 'close_window'));
2699         return $this->container($this->render($button), 'closewindow');
2700     }
2702     /**
2703      * Output an error message. By default wraps the error message in <span class="error">.
2704      * If the error message is blank, nothing is output.
2705      *
2706      * @param string $message the error message.
2707      * @return string the HTML to output.
2708      */
2709     public function error_text($message) {
2710         if (empty($message)) {
2711             return '';
2712         }
2713         $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2714         return html_writer::tag('span', $message, array('class' => 'error'));
2715     }
2717     /**
2718      * Do not call this function directly.
2719      *
2720      * To terminate the current script with a fatal error, call the {@link print_error}
2721      * function, or throw an exception. Doing either of those things will then call this
2722      * function to display the error, before terminating the execution.
2723      *
2724      * @param string $message The message to output
2725      * @param string $moreinfourl URL where more info can be found about the error
2726      * @param string $link Link for the Continue button
2727      * @param array $backtrace The execution backtrace
2728      * @param string $debuginfo Debugging information
2729      * @return string the HTML to output.
2730      */
2731     public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2732         global $CFG;
2734         $output = '';
2735         $obbuffer = '';
2737         if ($this->has_started()) {
2738             // we can not always recover properly here, we have problems with output buffering,
2739             // html tables, etc.
2740             $output .= $this->opencontainers->pop_all_but_last();
2742         } else {
2743             // It is really bad if library code throws exception when output buffering is on,
2744             // because the buffered text would be printed before our start of page.
2745             // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2746             error_reporting(0); // disable notices from gzip compression, etc.
2747             while (ob_get_level() > 0) {
2748                 $buff = ob_get_clean();
2749                 if ($buff === false) {
2750                     break;
2751                 }
2752                 $obbuffer .= $buff;
2753             }
2754             error_reporting($CFG->debug);
2756             // Output not yet started.
2757             $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2758             if (empty($_SERVER['HTTP_RANGE'])) {
2759                 @header($protocol . ' 404 Not Found');
2760             } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2761                 // Coax iOS 10 into sending the session cookie.
2762                 @header($protocol . ' 403 Forbidden');
2763             } else {
2764                 // Must stop byteserving attempts somehow,
2765                 // this is weird but Chrome PDF viewer can be stopped only with 407!
2766                 @header($protocol . ' 407 Proxy Authentication Required');
2767             }
2769             $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2770             $this->page->set_url('/'); // no url
2771             //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2772             $this->page->set_title(get_string('error'));
2773             $this->page->set_heading($this->page->course->fullname);
2774             $output .= $this->header();
2775         }
2777         $message = '<p class="errormessage">' . $message . '</p>'.
2778                 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2779                 get_string('moreinformation') . '</a></p>';
2780         if (empty($CFG->rolesactive)) {
2781             $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2782             //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.
2783         }
2784         $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2786         if ($CFG->debugdeveloper) {
2787             if (!empty($debuginfo)) {
2788                 $debuginfo = s($debuginfo); // removes all nasty JS
2789                 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2790                 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2791             }
2792             if (!empty($backtrace)) {
2793                 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2794             }
2795             if ($obbuffer !== '' ) {
2796                 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2797             }
2798         }
2800         if (empty($CFG->rolesactive)) {
2801             // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2802         } else if (!empty($link)) {
2803             $output .= $this->continue_button($link);
2804         }
2806         $output .= $this->footer();
2808         // Padding to encourage IE to display our error page, rather than its own.
2809         $output .= str_repeat(' ', 512);
2811         return $output;
2812     }
2814     /**
2815      * Output a notification (that is, a status message about something that has just happened).
2816      *
2817      * Note: \core\notification::add() may be more suitable for your usage.
2818      *
2819      * @param string $message The message to print out.
2820      * @param string $type    The type of notification. See constants on \core\output\notification.
2821      * @return string the HTML to output.
2822      */
2823     public function notification($message, $type = null) {
2824         $typemappings = [
2825             // Valid types.
2826             'success'           => \core\output\notification::NOTIFY_SUCCESS,
2827             'info'              => \core\output\notification::NOTIFY_INFO,
2828             'warning'           => \core\output\notification::NOTIFY_WARNING,
2829             'error'             => \core\output\notification::NOTIFY_ERROR,
2831             // Legacy types mapped to current types.
2832             'notifyproblem'     => \core\output\notification::NOTIFY_ERROR,
2833             'notifytiny'        => \core\output\notification::NOTIFY_ERROR,
2834             'notifyerror'       => \core\output\notification::NOTIFY_ERROR,
2835             'notifysuccess'     => \core\output\notification::NOTIFY_SUCCESS,
2836             'notifymessage'     => \core\output\notification::NOTIFY_INFO,
2837             'notifyredirect'    => \core\output\notification::NOTIFY_INFO,
2838             'redirectmessage'   => \core\output\notification::NOTIFY_INFO,
2839         ];
2841         $extraclasses = [];
2843         if ($type) {
2844             if (strpos($type, ' ') === false) {
2845                 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2846                 if (isset($typemappings[$type])) {
2847                     $type = $typemappings[$type];
2848                 } else {
2849                     // The value provided did not match a known type. It must be an extra class.
2850                     $extraclasses = [$type];
2851                 }
2852             } else {
2853                 // Identify what type of notification this is.
2854                 $classarray = explode(' ', self::prepare_classes($type));
2856                 // Separate out the type of notification from the extra classes.
2857                 foreach ($classarray as $class) {
2858                     if (isset($typemappings[$class])) {
2859                         $type = $typemappings[$class];
2860                     } else {
2861                         $extraclasses[] = $class;
2862                     }
2863                 }
2864             }
2865         }
2867         $notification = new \core\output\notification($message, $type);
2868         if (count($extraclasses)) {
2869             $notification->set_extra_classes($extraclasses);
2870         }
2872         // Return the rendered template.
2873         return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2874     }
2876     /**
2877      * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2878      *
2879      * @param string $message the message to print out
2880      * @return string HTML fragment.
2881      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2882      * @todo MDL-53113 This will be removed in Moodle 3.5.
2883      * @see \core\output\notification
2884      */
2885     public function notify_problem($message) {
2886         debugging(__FUNCTION__ . ' is deprecated.' .
2887             'Please use \core\notification::add, or \core\output\notification as required',
2888             DEBUG_DEVELOPER);
2889         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
2890         return $this->render($n);
2891     }
2893     /**
2894      * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2895      *
2896      * @param string $message the message to print out
2897      * @return string HTML fragment.
2898      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2899      * @todo MDL-53113 This will be removed in Moodle 3.5.
2900      * @see \core\output\notification
2901      */
2902     public function notify_success($message) {
2903         debugging(__FUNCTION__ . ' is deprecated.' .
2904             'Please use \core\notification::add, or \core\output\notification as required',
2905             DEBUG_DEVELOPER);
2906         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2907         return $this->render($n);
2908     }
2910     /**
2911      * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2912      *
2913      * @param string $message the message to print out
2914      * @return string HTML fragment.
2915      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2916      * @todo MDL-53113 This will be removed in Moodle 3.5.
2917      * @see \core\output\notification
2918      */
2919     public function notify_message($message) {
2920         debugging(__FUNCTION__ . ' is deprecated.' .
2921             'Please use \core\notification::add, or \core\output\notification as required',
2922             DEBUG_DEVELOPER);
2923         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2924         return $this->render($n);
2925     }
2927     /**
2928      * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2929      *
2930      * @param string $message the message to print out
2931      * @return string HTML fragment.
2932      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2933      * @todo MDL-53113 This will be removed in Moodle 3.5.
2934      * @see \core\output\notification
2935      */
2936     public function notify_redirect($message) {
2937         debugging(__FUNCTION__ . ' is deprecated.' .
2938             'Please use \core\notification::add, or \core\output\notification as required',
2939             DEBUG_DEVELOPER);
2940         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2941         return $this->render($n);
2942     }
2944     /**
2945      * Render a notification (that is, a status message about something that has
2946      * just happened).
2947      *
2948      * @param \core\output\notification $notification the notification to print out
2949      * @return string the HTML to output.
2950      */
2951     protected function render_notification(\core\output\notification $notification) {
2952         return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2953     }
2955     /**
2956      * Returns HTML to display a continue button that goes to a particular URL.
2957      *
2958      * @param string|moodle_url $url The url the button goes to.
2959      * @return string the HTML to output.
2960      */
2961     public function continue_button($url) {
2962         if (!($url instanceof moodle_url)) {
2963             $url = new moodle_url($url);
2964         }
2965         $button = new single_button($url, get_string('continue'), 'get', true);
2966         $button->class = 'continuebutton';
2968         return $this->render($button);
2969     }
2971     /**
2972      * Returns HTML to display a single paging bar to provide access to other pages  (usually in a search)
2973      *
2974      * Theme developers: DO NOT OVERRIDE! Please override function
2975      * {@link core_renderer::render_paging_bar()} instead.
2976      *
2977      * @param int $totalcount The total number of entries available to be paged through
2978      * @param int $page The page you are currently viewing
2979      * @param int $perpage The number of entries that should be shown per page
2980      * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2981      * @param string $pagevar name of page parameter that holds the page number
2982      * @return string the HTML to output.
2983      */
2984     public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2985         $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2986         return $this->render($pb);
2987     }
2989     /**
2990      * Internal implementation of paging bar rendering.
2991      *
2992      * @param paging_bar $pagingbar
2993      * @return string
2994      */
2995     protected function render_paging_bar(paging_bar $pagingbar) {
2996         $output = '';
2997         $pagingbar = clone($pagingbar);
2998         $pagingbar->prepare($this, $this->page, $this->target);
3000         if ($pagingbar->totalcount > $pagingbar->perpage) {
3001             $output .= get_string('page') . ':';
3003             if (!empty($pagingbar->previouslink)) {
3004                 $output .= ' (' . $pagingbar->previouslink . ') ';
3005             }
3007             if (!empty($pagingbar->firstlink)) {
3008                 $output .= ' ' . $pagingbar->firstlink . ' ...';
3009             }
3011             foreach ($pagingbar->pagelinks as $link) {
3012                 $output .= "  $link";
3013             }
3015             if (!empty($pagingbar->lastlink)) {
3016                 $output .= ' ... ' . $pagingbar->lastlink . ' ';
3017             }
3019             if (!empty($pagingbar->nextlink)) {
3020                 $output .= '  (' . $pagingbar->nextlink . ')';
3021             }
3022         }
3024         return html_writer::tag('div', $output, array('class' => 'paging'));
3025     }
3027     /**
3028      * Returns HTML to display initials bar to provide access to other pages  (usually in a search)
3029      *
3030      * @param string $current the currently selected letter.
3031      * @param string $class class name to add to this initial bar.
3032      * @param string $title the name to put in front of this initial bar.
3033      * @param string $urlvar URL parameter name for this initial.
3034      * @param string $url URL object.
3035      * @param array $alpha of letters in the alphabet.
3036      * @return string the HTML to output.
3037      */
3038     public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3039         $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3040         return $this->render($ib);
3041     }
3043     /**
3044      * Internal implementation of initials bar rendering.
3045      *
3046      * @param initials_bar $initialsbar
3047      * @return string
3048      */
3049     protected function render_initials_bar(initials_bar $initialsbar) {
3050         return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3051     }
3053     /**
3054      * Output the place a skip link goes to.
3055      *
3056      * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3057      * @return string the HTML to output.
3058      */
3059     public function skip_link_target($id = null) {
3060         return html_writer::span('', '', array('id' => $id));
3061     }
3063     /**
3064      * Outputs a heading
3065      *
3066      * @param string $text The text of the heading
3067      * @param int $level The level of importance of the heading. Defaulting to 2
3068      * @param string $classes A space-separated list of CSS classes. Defaulting to null
3069      * @param string $id An optional ID
3070      * @return string the HTML to output.
3071      */
3072     public function heading($text, $level = 2, $classes = null, $id = null) {
3073         $level = (integer) $level;
3074         if ($level < 1 or $level > 6) {
3075             throw new coding_exception('Heading level must be an integer between 1 and 6.');
3076         }
3077         return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3078     }
3080     /**
3081      * Outputs a box.
3082      *
3083      * @param string $contents The contents of the box
3084      * @param string $classes A space-separated list of CSS classes
3085      * @param string $id An optional ID
3086      * @param array $attributes An array of other attributes to give the box.
3087      * @return string the HTML to output.
3088      */
3089     public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3090         return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3091     }
3093     /**
3094      * Outputs the opening section of a box.
3095      *
3096      * @param string $classes A space-separated list of CSS classes
3097      * @param string $id An optional ID
3098      * @param array $attributes An array of other attributes to give the box.
3099      * @return string the HTML to output.
3100      */
3101     public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3102         $this->opencontainers->push('box', html_writer::end_tag('div'));
3103         $attributes['id'] = $id;
3104         $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3105         return html_writer::start_tag('div', $attributes);
3106     }
3108     /**
3109      * Outputs the closing section of a box.
3110      *
3111      * @return string the HTML to output.
3112      */
3113     public function box_end() {
3114         return $this->opencontainers->pop('box');
3115     }
3117     /**
3118      * Outputs a container.
3119      *
3120      * @param string $contents The contents of the box
3121      * @param string $classes A space-separated list of CSS classes
3122      * @param string $id An optional ID
3123      * @return string the HTML to output.
3124      */
3125     public function container($contents, $classes = null, $id = null) {
3126         return $this->container_start($classes, $id) . $contents . $this->container_end();
3127     }
3129     /**
3130      * Outputs the opening section of a container.
3131      *
3132      * @param string $classes A space-separated list of CSS classes
3133      * @param string $id An optional ID
3134      * @return string the HTML to output.
3135      */
3136     public function container_start($classes = null, $id = null) {
3137         $this->opencontainers->push('container', html_writer::end_tag('div'));
3138         return html_writer::start_tag('div', array('id' => $id,
3139                 'class' => renderer_base::prepare_classes($classes)));
3140     }
3142     /**
3143      * Outputs the closing section of a container.
3144      *
3145      * @return string the HTML to output.
3146      */
3147     public function container_end() {
3148         return $this->opencontainers->pop('container');
3149     }
3151     /**
3152      * Make nested HTML lists out of the items
3153      *
3154      * The resulting list will look something like this:
3155      *
3156      * <pre>
3157      * <<ul>>
3158      * <<li>><div class='tree_item parent'>(item contents)</div>
3159      *      <<ul>
3160      *      <<li>><div class='tree_item'>(item contents)</div><</li>>
3161      *      <</ul>>
3162      * <</li>>
3163      * <</ul>>
3164      * </pre>
3165      *
3166      * @param array $items
3167      * @param array $attrs html attributes passed to the top ofs the list
3168      * @return string HTML
3169      */
3170     public function tree_block_contents($items, $attrs = array()) {
3171         // exit if empty, we don't want an empty ul element
3172         if (empty($items)) {
3173             return '';
3174         }
3175         // array of nested li elements
3176         $lis = array();
3177         foreach ($items as $item) {
3178             // this applies to the li item which contains all child lists too
3179             $content = $item->content($this);
3180             $liclasses = array($item->get_css_type());
3181             if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0  && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3182                 $liclasses[] = 'collapsed';
3183             }
3184             if ($item->isactive === true) {
3185                 $liclasses[] = 'current_branch';
3186             }
3187             $liattr = array('class'=>join(' ',$liclasses));
3188             // class attribute on the div item which only contains the item content
3189             $divclasses = array('tree_item');
3190             if ($item->children->count()>0  || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3191                 $divclasses[] = 'branch';
3192             } else {
3193                 $divclasses[] = 'leaf';
3194             }
3195             if (!empty($item->classes) && count($item->classes)>0) {
3196                 $divclasses[] = join(' ', $item->classes);
3197             }
3198             $divattr = array('class'=>join(' ', $divclasses));
3199             if (!empty($item->id)) {
3200                 $divattr['id'] = $item->id;
3201             }
3202             $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3203             if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3204                 $content = html_writer::empty_tag('hr') . $content;
3205             }
3206             $content = html_writer::tag('li', $content, $liattr);
3207             $lis[] = $content;
3208         }
3209         return html_writer::tag('ul', implode("\n", $lis), $attrs);
3210     }
3212     /**
3213      * Returns a search box.
3214      *
3215      * @param  string $id     The search box wrapper div id, defaults to an autogenerated one.
3216      * @return string         HTML with the search form hidden by default.
3217      */
3218     public function search_box($id = false) {
3219         global $CFG;
3221         // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3222         // result in an extra included file for each site, even the ones where global search
3223         // is disabled.
3224         if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3225             return '';
3226         }
3228         if ($id == false) {
3229             $id = uniqid();
3230         } else {
3231             // Needs to be cleaned, we use it for the input id.
3232             $id = clean_param($id, PARAM_ALPHANUMEXT);
3233         }
3235         // JS to animate the form.
3236         $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3238         $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3239             array('role' => 'button', 'tabindex' => 0));
3240         $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3241         $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3242             'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id);
3244         $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3245             array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3246         $searchinput = html_writer::tag('form', $contents, $formattrs);
3248         return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3249     }
3251     /**
3252      * Allow plugins to provide some content to be rendered in the navbar.
3253      * The plugin must define a PLUGIN_render_navbar_output function that returns
3254      * the HTML they wish to add to the navbar.
3255      *
3256      * @return string HTML for the navbar
3257      */
3258     public function navbar_plugin_output() {
3259         $output = '';
3261         if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3262             foreach ($pluginsfunction as $plugintype => $plugins) {
3263                 foreach ($plugins as $pluginfunction) {
3264                     $output .= $pluginfunction($this);
3265                 }
3266             }
3267         }
3269         return $output;
3270     }
3272     /**
3273      * Construct a user menu, returning HTML that can be echoed out by a
3274      * layout file.
3275      *
3276      * @param stdClass $user A user object, usually $USER.
3277      * @param bool $withlinks true if a dropdown should be built.
3278      * @return string HTML fragment.
3279      */
3280     public function user_menu($user = null, $withlinks = null) {
3281         global $USER, $CFG;
3282         require_once($CFG->dirroot . '/user/lib.php');
3284         if (is_null($user)) {
3285             $user = $USER;
3286         }
3288         // Note: this behaviour is intended to match that of core_renderer::login_info,
3289         // but should not be considered to be good practice; layout options are
3290         // intended to be theme-specific. Please don't copy this snippet anywhere else.
3291         if (is_null($withlinks)) {
3292             $withlinks = empty($this->page->layout_options['nologinlinks']);
3293         }
3295         // Add a class for when $withlinks is false.
3296         $usermenuclasses = 'usermenu';
3297         if (!$withlinks) {
3298             $usermenuclasses .= ' withoutlinks';
3299         }
3301         $returnstr = "";
3303         // If during initial install, return the empty return string.
3304         if (during_initial_install()) {
3305             return $returnstr;
3306         }
3308         $loginpage = $this->is_login_page();
3309         $loginurl = get_login_url();
3310         // If not logged in, show the typical not-logged-in string.
3311         if (!isloggedin()) {
3312             $returnstr = get_string('loggedinnot', 'moodle');
3313             if (!$loginpage) {
3314                 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3315             }
3316             return html_writer::div(
3317                 html_writer::span(
3318                     $returnstr,
3319                     'login'
3320                 ),
3321                 $usermenuclasses
3322             );
3324         }
3326         // If logged in as a guest user, show a string to that effect.
3327         if (isguestuser()) {
3328             $returnstr = get_string('loggedinasguest');
3329             if (!$loginpage && $withlinks) {
3330                 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3331             }
3333             return html_writer::div(
3334                 html_writer::span(
3335                     $returnstr,
3336                     'login'
3337                 ),
3338                 $usermenuclasses
3339             );
3340         }
3342         // Get some navigation opts.
3343         $opts = user_get_user_navigation_info($user, $this->page);
3345         $avatarclasses = "avatars";
3346         $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3347         $usertextcontents = $opts->metadata['userfullname'];
3349         // Other user.
3350         if (!empty($opts->metadata['asotheruser'])) {
3351             $avatarcontents .= html_writer::span(
3352                 $opts->metadata['realuseravatar'],
3353                 'avatar realuser'
3354             );
3355             $usertextcontents = $opts->metadata['realuserfullname'];
3356             $usertextcontents .= html_writer::tag(
3357                 'span',
3358                 get_string(
3359                     'loggedinas',
3360                     'moodle',
3361                     html_writer::span(
3362                         $opts->metadata['userfullname'],
3363                         'value'
3364                     )
3365                 ),
3366                 array('class' => 'meta viewingas')
3367             );
3368         }
3370         // Role.
3371         if (!empty($opts->metadata['asotherrole'])) {
3372             $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3373             $usertextcontents .= html_writer::span(
3374                 $opts->metadata['rolename'],
3375                 'meta role role-' . $role
3376             );
3377         }
3379         // User login failures.
3380         if (!empty($opts->metadata['userloginfail'])) {
3381             $usertextcontents .= html_writer::span(
3382                 $opts->metadata['userloginfail'],
3383                 'meta loginfailures'
3384             );
3385         }
3387         // MNet.