Merge branch 'MDL-59511-master-oauthsysmail' of git://github.com/Dagefoerde/moodle
[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      * The standard tags (typically script tags that are not needed earlier) that
818      * should be output after everything else. Designed to be called in theme layout.php files.
819      *
820      * @return string HTML fragment.
821      */
822     public function standard_end_of_body_html() {
823         global $CFG;
825         // This function is normally called from a layout.php file in {@link core_renderer::header()}
826         // but some of the content won't be known until later, so we return a placeholder
827         // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
828         $output = '';
829         if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
830             $output .= "\n".$CFG->additionalhtmlfooter;
831         }
832         $output .= $this->unique_end_html_token;
833         return $output;
834     }
836     /**
837      * Return the standard string that says whether you are logged in (and switched
838      * roles/logged in as another user).
839      * @param bool $withlinks if false, then don't include any links in the HTML produced.
840      * If not set, the default is the nologinlinks option from the theme config.php file,
841      * and if that is not set, then links are included.
842      * @return string HTML fragment.
843      */
844     public function login_info($withlinks = null) {
845         global $USER, $CFG, $DB, $SESSION;
847         if (during_initial_install()) {
848             return '';
849         }
851         if (is_null($withlinks)) {
852             $withlinks = empty($this->page->layout_options['nologinlinks']);
853         }
855         $course = $this->page->course;
856         if (\core\session\manager::is_loggedinas()) {
857             $realuser = \core\session\manager::get_realuser();
858             $fullname = fullname($realuser, true);
859             if ($withlinks) {
860                 $loginastitle = get_string('loginas');
861                 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
862                 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
863             } else {
864                 $realuserinfo = " [$fullname] ";
865             }
866         } else {
867             $realuserinfo = '';
868         }
870         $loginpage = $this->is_login_page();
871         $loginurl = get_login_url();
873         if (empty($course->id)) {
874             // $course->id is not defined during installation
875             return '';
876         } else if (isloggedin()) {
877             $context = context_course::instance($course->id);
879             $fullname = fullname($USER, true);
880             // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
881             if ($withlinks) {
882                 $linktitle = get_string('viewprofile');
883                 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
884             } else {
885                 $username = $fullname;
886             }
887             if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
888                 if ($withlinks) {
889                     $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
890                 } else {
891                     $username .= " from {$idprovider->name}";
892                 }
893             }
894             if (isguestuser()) {
895                 $loggedinas = $realuserinfo.get_string('loggedinasguest');
896                 if (!$loginpage && $withlinks) {
897                     $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
898                 }
899             } else if (is_role_switched($course->id)) { // Has switched roles
900                 $rolename = '';
901                 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
902                     $rolename = ': '.role_get_name($role, $context);
903                 }
904                 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
905                 if ($withlinks) {
906                     $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
907                     $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
908                 }
909             } else {
910                 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
911                 if ($withlinks) {
912                     $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
913                 }
914             }
915         } else {
916             $loggedinas = get_string('loggedinnot', 'moodle');
917             if (!$loginpage && $withlinks) {
918                 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
919             }
920         }
922         $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
924         if (isset($SESSION->justloggedin)) {
925             unset($SESSION->justloggedin);
926             if (!empty($CFG->displayloginfailures)) {
927                 if (!isguestuser()) {
928                     // Include this file only when required.
929                     require_once($CFG->dirroot . '/user/lib.php');
930                     if ($count = user_count_login_failures($USER)) {
931                         $loggedinas .= '<div class="loginfailures">';
932                         $a = new stdClass();
933                         $a->attempts = $count;
934                         $loggedinas .= get_string('failedloginattempts', '', $a);
935                         if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
936                             $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
937                                     'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
938                         }
939                         $loggedinas .= '</div>';
940                     }
941                 }
942             }
943         }
945         return $loggedinas;
946     }
948     /**
949      * Check whether the current page is a login page.
950      *
951      * @since Moodle 2.9
952      * @return bool
953      */
954     protected function is_login_page() {
955         // This is a real bit of a hack, but its a rarety that we need to do something like this.
956         // In fact the login pages should be only these two pages and as exposing this as an option for all pages
957         // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
958         return in_array(
959             $this->page->url->out_as_local_url(false, array()),
960             array(
961                 '/login/index.php',
962                 '/login/forgot_password.php',
963             )
964         );
965     }
967     /**
968      * Return the 'back' link that normally appears in the footer.
969      *
970      * @return string HTML fragment.
971      */
972     public function home_link() {
973         global $CFG, $SITE;
975         if ($this->page->pagetype == 'site-index') {
976             // Special case for site home page - please do not remove
977             return '<div class="sitelink">' .
978                    '<a title="Moodle" href="http://moodle.org/">' .
979                    '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
981         } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
982             // Special case for during install/upgrade.
983             return '<div class="sitelink">'.
984                    '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
985                    '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
987         } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
988             return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
989                     get_string('home') . '</a></div>';
991         } else {
992             return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
993                     format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
994         }
995     }
997     /**
998      * Redirects the user by any means possible given the current state
999      *
1000      * This function should not be called directly, it should always be called using
1001      * the redirect function in lib/weblib.php
1002      *
1003      * The redirect function should really only be called before page output has started
1004      * however it will allow itself to be called during the state STATE_IN_BODY
1005      *
1006      * @param string $encodedurl The URL to send to encoded if required
1007      * @param string $message The message to display to the user if any
1008      * @param int $delay The delay before redirecting a user, if $message has been
1009      *         set this is a requirement and defaults to 3, set to 0 no delay
1010      * @param boolean $debugdisableredirect this redirect has been disabled for
1011      *         debugging purposes. Display a message that explains, and don't
1012      *         trigger the redirect.
1013      * @param string $messagetype The type of notification to show the message in.
1014      *         See constants on \core\output\notification.
1015      * @return string The HTML to display to the user before dying, may contain
1016      *         meta refresh, javascript refresh, and may have set header redirects
1017      */
1018     public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1019                                      $messagetype = \core\output\notification::NOTIFY_INFO) {
1020         global $CFG;
1021         $url = str_replace('&amp;', '&', $encodedurl);
1023         switch ($this->page->state) {
1024             case moodle_page::STATE_BEFORE_HEADER :
1025                 // No output yet it is safe to delivery the full arsenal of redirect methods
1026                 if (!$debugdisableredirect) {
1027                     // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1028                     $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1029                     $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1030                 }
1031                 $output = $this->header();
1032                 break;
1033             case moodle_page::STATE_PRINTING_HEADER :
1034                 // We should hopefully never get here
1035                 throw new coding_exception('You cannot redirect while printing the page header');
1036                 break;
1037             case moodle_page::STATE_IN_BODY :
1038                 // We really shouldn't be here but we can deal with this
1039                 debugging("You should really redirect before you start page output");
1040                 if (!$debugdisableredirect) {
1041                     $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1042                 }
1043                 $output = $this->opencontainers->pop_all_but_last();
1044                 break;
1045             case moodle_page::STATE_DONE :
1046                 // Too late to be calling redirect now
1047                 throw new coding_exception('You cannot redirect after the entire page has been generated');
1048                 break;
1049         }
1050         $output .= $this->notification($message, $messagetype);
1051         $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1052         if ($debugdisableredirect) {
1053             $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1054         }
1055         $output .= $this->footer();
1056         return $output;
1057     }
1059     /**
1060      * Start output by sending the HTTP headers, and printing the HTML <head>
1061      * and the start of the <body>.
1062      *
1063      * To control what is printed, you should set properties on $PAGE. If you
1064      * are familiar with the old {@link print_header()} function from Moodle 1.9
1065      * you will find that there are properties on $PAGE that correspond to most
1066      * of the old parameters to could be passed to print_header.
1067      *
1068      * Not that, in due course, the remaining $navigation, $menu parameters here
1069      * will be replaced by more properties of $PAGE, but that is still to do.
1070      *
1071      * @return string HTML that you must output this, preferably immediately.
1072      */
1073     public function header() {
1074         global $USER, $CFG, $SESSION;
1076         // Give plugins an opportunity touch things before the http headers are sent
1077         // such as adding additional headers. The return value is ignored.
1078         $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1079         foreach ($pluginswithfunction as $plugins) {
1080             foreach ($plugins as $function) {
1081                 $function();
1082             }
1083         }
1085         if (\core\session\manager::is_loggedinas()) {
1086             $this->page->add_body_class('userloggedinas');
1087         }
1089         if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1090             require_once($CFG->dirroot . '/user/lib.php');
1091             // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1092             if ($count = user_count_login_failures($USER, false)) {
1093                 $this->page->add_body_class('loginfailures');
1094             }
1095         }
1097         // If the user is logged in, and we're not in initial install,
1098         // check to see if the user is role-switched and add the appropriate
1099         // CSS class to the body element.
1100         if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1101             $this->page->add_body_class('userswitchedrole');
1102         }
1104         // Give themes a chance to init/alter the page object.
1105         $this->page->theme->init_page($this->page);
1107         $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1109         // Find the appropriate page layout file, based on $this->page->pagelayout.
1110         $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1111         // Render the layout using the layout file.
1112         $rendered = $this->render_page_layout($layoutfile);
1114         // Slice the rendered output into header and footer.
1115         $cutpos = strpos($rendered, $this->unique_main_content_token);
1116         if ($cutpos === false) {
1117             $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1118             $token = self::MAIN_CONTENT_TOKEN;
1119         } else {
1120             $token = $this->unique_main_content_token;
1121         }
1123         if ($cutpos === false) {
1124             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.');
1125         }
1126         $header = substr($rendered, 0, $cutpos);
1127         $footer = substr($rendered, $cutpos + strlen($token));
1129         if (empty($this->contenttype)) {
1130             debugging('The page layout file did not call $OUTPUT->doctype()');
1131             $header = $this->doctype() . $header;
1132         }
1134         // If this theme version is below 2.4 release and this is a course view page
1135         if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1136                 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1137             // check if course content header/footer have not been output during render of theme layout
1138             $coursecontentheader = $this->course_content_header(true);
1139             $coursecontentfooter = $this->course_content_footer(true);
1140             if (!empty($coursecontentheader)) {
1141                 // display debug message and add header and footer right above and below main content
1142                 // Please note that course header and footer (to be displayed above and below the whole page)
1143                 // are not displayed in this case at all.
1144                 // Besides the content header and footer are not displayed on any other course page
1145                 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);
1146                 $header .= $coursecontentheader;
1147                 $footer = $coursecontentfooter. $footer;
1148             }
1149         }
1151         send_headers($this->contenttype, $this->page->cacheable);
1153         $this->opencontainers->push('header/footer', $footer);
1154         $this->page->set_state(moodle_page::STATE_IN_BODY);
1156         return $header . $this->skip_link_target('maincontent');
1157     }
1159     /**
1160      * Renders and outputs the page layout file.
1161      *
1162      * This is done by preparing the normal globals available to a script, and
1163      * then including the layout file provided by the current theme for the
1164      * requested layout.
1165      *
1166      * @param string $layoutfile The name of the layout file
1167      * @return string HTML code
1168      */
1169     protected function render_page_layout($layoutfile) {
1170         global $CFG, $SITE, $USER;
1171         // The next lines are a bit tricky. The point is, here we are in a method
1172         // of a renderer class, and this object may, or may not, be the same as
1173         // the global $OUTPUT object. When rendering the page layout file, we want to use
1174         // this object. However, people writing Moodle code expect the current
1175         // renderer to be called $OUTPUT, not $this, so define a variable called
1176         // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1177         $OUTPUT = $this;
1178         $PAGE = $this->page;
1179         $COURSE = $this->page->course;
1181         ob_start();
1182         include($layoutfile);
1183         $rendered = ob_get_contents();
1184         ob_end_clean();
1185         return $rendered;
1186     }
1188     /**
1189      * Outputs the page's footer
1190      *
1191      * @return string HTML fragment
1192      */
1193     public function footer() {
1194         global $CFG, $DB, $PAGE;
1196         // Give plugins an opportunity to touch the page before JS is finalized.
1197         $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1198         foreach ($pluginswithfunction as $plugins) {
1199             foreach ($plugins as $function) {
1200                 $function();
1201             }
1202         }
1204         $output = $this->container_end_all(true);
1206         $footer = $this->opencontainers->pop('header/footer');
1208         if (debugging() and $DB and $DB->is_transaction_started()) {
1209             // TODO: MDL-20625 print warning - transaction will be rolled back
1210         }
1212         // Provide some performance info if required
1213         $performanceinfo = '';
1214         if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1215             $perf = get_performance_info();
1216             if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1217                 $performanceinfo = $perf['html'];
1218             }
1219         }
1221         // We always want performance data when running a performance test, even if the user is redirected to another page.
1222         if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1223             $footer = $this->unique_performance_info_token . $footer;
1224         }
1225         $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1227         // Only show notifications when we have a $PAGE context id.
1228         if (!empty($PAGE->context->id)) {
1229             $this->page->requires->js_call_amd('core/notification', 'init', array(
1230                 $PAGE->context->id,
1231                 \core\notification::fetch_as_array($this)
1232             ));
1233         }
1234         $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1236         $this->page->set_state(moodle_page::STATE_DONE);
1238         return $output . $footer;
1239     }
1241     /**
1242      * Close all but the last open container. This is useful in places like error
1243      * handling, where you want to close all the open containers (apart from <body>)
1244      * before outputting the error message.
1245      *
1246      * @param bool $shouldbenone assert that the stack should be empty now - causes a
1247      *      developer debug warning if it isn't.
1248      * @return string the HTML required to close any open containers inside <body>.
1249      */
1250     public function container_end_all($shouldbenone = false) {
1251         return $this->opencontainers->pop_all_but_last($shouldbenone);
1252     }
1254     /**
1255      * Returns course-specific information to be output immediately above content on any course page
1256      * (for the current course)
1257      *
1258      * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1259      * @return string
1260      */
1261     public function course_content_header($onlyifnotcalledbefore = false) {
1262         global $CFG;
1263         static $functioncalled = false;
1264         if ($functioncalled && $onlyifnotcalledbefore) {
1265             // we have already output the content header
1266             return '';
1267         }
1269         // Output any session notification.
1270         $notifications = \core\notification::fetch();
1272         $bodynotifications = '';
1273         foreach ($notifications as $notification) {
1274             $bodynotifications .= $this->render_from_template(
1275                     $notification->get_template_name(),
1276                     $notification->export_for_template($this)
1277                 );
1278         }
1280         $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1282         if ($this->page->course->id == SITEID) {
1283             // return immediately and do not include /course/lib.php if not necessary
1284             return $output;
1285         }
1287         require_once($CFG->dirroot.'/course/lib.php');
1288         $functioncalled = true;
1289         $courseformat = course_get_format($this->page->course);
1290         if (($obj = $courseformat->course_content_header()) !== null) {
1291             $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1292         }
1293         return $output;
1294     }
1296     /**
1297      * Returns course-specific information to be output immediately below content on any course page
1298      * (for the current course)
1299      *
1300      * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1301      * @return string
1302      */
1303     public function course_content_footer($onlyifnotcalledbefore = false) {
1304         global $CFG;
1305         if ($this->page->course->id == SITEID) {
1306             // return immediately and do not include /course/lib.php if not necessary
1307             return '';
1308         }
1309         static $functioncalled = false;
1310         if ($functioncalled && $onlyifnotcalledbefore) {
1311             // we have already output the content footer
1312             return '';
1313         }
1314         $functioncalled = true;
1315         require_once($CFG->dirroot.'/course/lib.php');
1316         $courseformat = course_get_format($this->page->course);
1317         if (($obj = $courseformat->course_content_footer()) !== null) {
1318             return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1319         }
1320         return '';
1321     }
1323     /**
1324      * Returns course-specific information to be output on any course page in the header area
1325      * (for the current course)
1326      *
1327      * @return string
1328      */
1329     public function course_header() {
1330         global $CFG;
1331         if ($this->page->course->id == SITEID) {
1332             // return immediately and do not include /course/lib.php if not necessary
1333             return '';
1334         }
1335         require_once($CFG->dirroot.'/course/lib.php');
1336         $courseformat = course_get_format($this->page->course);
1337         if (($obj = $courseformat->course_header()) !== null) {
1338             return $courseformat->get_renderer($this->page)->render($obj);
1339         }
1340         return '';
1341     }
1343     /**
1344      * Returns course-specific information to be output on any course page in the footer area
1345      * (for the current course)
1346      *
1347      * @return string
1348      */
1349     public function course_footer() {
1350         global $CFG;
1351         if ($this->page->course->id == SITEID) {
1352             // return immediately and do not include /course/lib.php if not necessary
1353             return '';
1354         }
1355         require_once($CFG->dirroot.'/course/lib.php');
1356         $courseformat = course_get_format($this->page->course);
1357         if (($obj = $courseformat->course_footer()) !== null) {
1358             return $courseformat->get_renderer($this->page)->render($obj);
1359         }
1360         return '';
1361     }
1363     /**
1364      * Returns lang menu or '', this method also checks forcing of languages in courses.
1365      *
1366      * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1367      *
1368      * @return string The lang menu HTML or empty string
1369      */
1370     public function lang_menu() {
1371         global $CFG;
1373         if (empty($CFG->langmenu)) {
1374             return '';
1375         }
1377         if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1378             // do not show lang menu if language forced
1379             return '';
1380         }
1382         $currlang = current_language();
1383         $langs = get_string_manager()->get_list_of_translations();
1385         if (count($langs) < 2) {
1386             return '';
1387         }
1389         $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1390         $s->label = get_accesshide(get_string('language'));
1391         $s->class = 'langmenu';
1392         return $this->render($s);
1393     }
1395     /**
1396      * Output the row of editing icons for a block, as defined by the controls array.
1397      *
1398      * @param array $controls an array like {@link block_contents::$controls}.
1399      * @param string $blockid The ID given to the block.
1400      * @return string HTML fragment.
1401      */
1402     public function block_controls($actions, $blockid = null) {
1403         global $CFG;
1404         if (empty($actions)) {
1405             return '';
1406         }
1407         $menu = new action_menu($actions);
1408         if ($blockid !== null) {
1409             $menu->set_owner_selector('#'.$blockid);
1410         }
1411         $menu->set_constraint('.block-region');
1412         $menu->attributes['class'] .= ' block-control-actions commands';
1413         return $this->render($menu);
1414     }
1416     /**
1417      * Renders an action menu component.
1418      *
1419      * ARIA references:
1420      *   - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1421      *   - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1422      *
1423      * @param action_menu $menu
1424      * @return string HTML
1425      */
1426     public function render_action_menu(action_menu $menu) {
1427         $context = $menu->export_for_template($this);
1428         return $this->render_from_template('core/action_menu', $context);
1429     }
1431     /**
1432      * Renders an action_menu_link item.
1433      *
1434      * @param action_menu_link $action
1435      * @return string HTML fragment
1436      */
1437     protected function render_action_menu_link(action_menu_link $action) {
1438         return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1439     }
1441     /**
1442      * Renders a primary action_menu_filler item.
1443      *
1444      * @param action_menu_link_filler $action
1445      * @return string HTML fragment
1446      */
1447     protected function render_action_menu_filler(action_menu_filler $action) {
1448         return html_writer::span('&nbsp;', 'filler');
1449     }
1451     /**
1452      * Renders a primary action_menu_link item.
1453      *
1454      * @param action_menu_link_primary $action
1455      * @return string HTML fragment
1456      */
1457     protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1458         return $this->render_action_menu_link($action);
1459     }
1461     /**
1462      * Renders a secondary action_menu_link item.
1463      *
1464      * @param action_menu_link_secondary $action
1465      * @return string HTML fragment
1466      */
1467     protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1468         return $this->render_action_menu_link($action);
1469     }
1471     /**
1472      * Prints a nice side block with an optional header.
1473      *
1474      * The content is described
1475      * by a {@link core_renderer::block_contents} object.
1476      *
1477      * <div id="inst{$instanceid}" class="block_{$blockname} block">
1478      *      <div class="header"></div>
1479      *      <div class="content">
1480      *          ...CONTENT...
1481      *          <div class="footer">
1482      *          </div>
1483      *      </div>
1484      *      <div class="annotation">
1485      *      </div>
1486      * </div>
1487      *
1488      * @param block_contents $bc HTML for the content
1489      * @param string $region the region the block is appearing in.
1490      * @return string the HTML to be output.
1491      */
1492     public function block(block_contents $bc, $region) {
1493         $bc = clone($bc); // Avoid messing up the object passed in.
1494         if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1495             $bc->collapsible = block_contents::NOT_HIDEABLE;
1496         }
1497         if (!empty($bc->blockinstanceid)) {
1498             $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1499         }
1500         $skiptitle = strip_tags($bc->title);
1501         if ($bc->blockinstanceid && !empty($skiptitle)) {
1502             $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1503         } else if (!empty($bc->arialabel)) {
1504             $bc->attributes['aria-label'] = $bc->arialabel;
1505         }
1506         if ($bc->dockable) {
1507             $bc->attributes['data-dockable'] = 1;
1508         }
1509         if ($bc->collapsible == block_contents::HIDDEN) {
1510             $bc->add_class('hidden');
1511         }
1512         if (!empty($bc->controls)) {
1513             $bc->add_class('block_with_controls');
1514         }
1517         if (empty($skiptitle)) {
1518             $output = '';
1519             $skipdest = '';
1520         } else {
1521             $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1522                       array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1523             $skipdest = html_writer::span('', 'skip-block-to',
1524                       array('id' => 'sb-' . $bc->skipid));
1525         }
1527         $output .= html_writer::start_tag('div', $bc->attributes);
1529         $output .= $this->block_header($bc);
1530         $output .= $this->block_content($bc);
1532         $output .= html_writer::end_tag('div');
1534         $output .= $this->block_annotation($bc);
1536         $output .= $skipdest;
1538         $this->init_block_hider_js($bc);
1539         return $output;
1540     }
1542     /**
1543      * Produces a header for a block
1544      *
1545      * @param block_contents $bc
1546      * @return string
1547      */
1548     protected function block_header(block_contents $bc) {
1550         $title = '';
1551         if ($bc->title) {
1552             $attributes = array();
1553             if ($bc->blockinstanceid) {
1554                 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1555             }
1556             $title = html_writer::tag('h2', $bc->title, $attributes);
1557         }
1559         $blockid = null;
1560         if (isset($bc->attributes['id'])) {
1561             $blockid = $bc->attributes['id'];
1562         }
1563         $controlshtml = $this->block_controls($bc->controls, $blockid);
1565         $output = '';
1566         if ($title || $controlshtml) {
1567             $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'));
1568         }
1569         return $output;
1570     }
1572     /**
1573      * Produces the content area for a block
1574      *
1575      * @param block_contents $bc
1576      * @return string
1577      */
1578     protected function block_content(block_contents $bc) {
1579         $output = html_writer::start_tag('div', array('class' => 'content'));
1580         if (!$bc->title && !$this->block_controls($bc->controls)) {
1581             $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1582         }
1583         $output .= $bc->content;
1584         $output .= $this->block_footer($bc);
1585         $output .= html_writer::end_tag('div');
1587         return $output;
1588     }
1590     /**
1591      * Produces the footer for a block
1592      *
1593      * @param block_contents $bc
1594      * @return string
1595      */
1596     protected function block_footer(block_contents $bc) {
1597         $output = '';
1598         if ($bc->footer) {
1599             $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1600         }
1601         return $output;
1602     }
1604     /**
1605      * Produces the annotation for a block
1606      *
1607      * @param block_contents $bc
1608      * @return string
1609      */
1610     protected function block_annotation(block_contents $bc) {
1611         $output = '';
1612         if ($bc->annotation) {
1613             $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1614         }
1615         return $output;
1616     }
1618     /**
1619      * Calls the JS require function to hide a block.
1620      *
1621      * @param block_contents $bc A block_contents object
1622      */
1623     protected function init_block_hider_js(block_contents $bc) {
1624         if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1625             $config = new stdClass;
1626             $config->id = $bc->attributes['id'];
1627             $config->title = strip_tags($bc->title);
1628             $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1629             $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1630             $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1632             $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1633             user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1634         }
1635     }
1637     /**
1638      * Render the contents of a block_list.
1639      *
1640      * @param array $icons the icon for each item.
1641      * @param array $items the content of each item.
1642      * @return string HTML
1643      */
1644     public function list_block_contents($icons, $items) {
1645         $row = 0;
1646         $lis = array();
1647         foreach ($items as $key => $string) {
1648             $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1649             if (!empty($icons[$key])) { //test if the content has an assigned icon
1650                 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1651             }
1652             $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1653             $item .= html_writer::end_tag('li');
1654             $lis[] = $item;
1655             $row = 1 - $row; // Flip even/odd.
1656         }
1657         return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1658     }
1660     /**
1661      * Output all the blocks in a particular region.
1662      *
1663      * @param string $region the name of a region on this page.
1664      * @return string the HTML to be output.
1665      */
1666     public function blocks_for_region($region) {
1667         $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1668         $blocks = $this->page->blocks->get_blocks_for_region($region);
1669         $lastblock = null;
1670         $zones = array();
1671         foreach ($blocks as $block) {
1672             $zones[] = $block->title;
1673         }
1674         $output = '';
1676         foreach ($blockcontents as $bc) {
1677             if ($bc instanceof block_contents) {
1678                 $output .= $this->block($bc, $region);
1679                 $lastblock = $bc->title;
1680             } else if ($bc instanceof block_move_target) {
1681                 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1682             } else {
1683                 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1684             }
1685         }
1686         return $output;
1687     }
1689     /**
1690      * Output a place where the block that is currently being moved can be dropped.
1691      *
1692      * @param block_move_target $target with the necessary details.
1693      * @param array $zones array of areas where the block can be moved to
1694      * @param string $previous the block located before the area currently being rendered.
1695      * @param string $region the name of the region
1696      * @return string the HTML to be output.
1697      */
1698     public function block_move_target($target, $zones, $previous, $region) {
1699         if ($previous == null) {
1700             if (empty($zones)) {
1701                 // There are no zones, probably because there are no blocks.
1702                 $regions = $this->page->theme->get_all_block_regions();
1703                 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1704             } else {
1705                 $position = get_string('moveblockbefore', 'block', $zones[0]);
1706             }
1707         } else {
1708             $position = get_string('moveblockafter', 'block', $previous);
1709         }
1710         return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1711     }
1713     /**
1714      * Renders a special html link with attached action
1715      *
1716      * Theme developers: DO NOT OVERRIDE! Please override function
1717      * {@link core_renderer::render_action_link()} instead.
1718      *
1719      * @param string|moodle_url $url
1720      * @param string $text HTML fragment
1721      * @param component_action $action
1722      * @param array $attributes associative array of html link attributes + disabled
1723      * @param pix_icon optional pix icon to render with the link
1724      * @return string HTML fragment
1725      */
1726     public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1727         if (!($url instanceof moodle_url)) {
1728             $url = new moodle_url($url);
1729         }
1730         $link = new action_link($url, $text, $action, $attributes, $icon);
1732         return $this->render($link);
1733     }
1735     /**
1736      * Renders an action_link object.
1737      *
1738      * The provided link is renderer and the HTML returned. At the same time the
1739      * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1740      *
1741      * @param action_link $link
1742      * @return string HTML fragment
1743      */
1744     protected function render_action_link(action_link $link) {
1745         return $this->render_from_template('core/action_link', $link->export_for_template($this));
1746     }
1748     /**
1749      * Renders an action_icon.
1750      *
1751      * This function uses the {@link core_renderer::action_link()} method for the
1752      * most part. What it does different is prepare the icon as HTML and use it
1753      * as the link text.
1754      *
1755      * Theme developers: If you want to change how action links and/or icons are rendered,
1756      * consider overriding function {@link core_renderer::render_action_link()} and
1757      * {@link core_renderer::render_pix_icon()}.
1758      *
1759      * @param string|moodle_url $url A string URL or moodel_url
1760      * @param pix_icon $pixicon
1761      * @param component_action $action
1762      * @param array $attributes associative array of html link attributes + disabled
1763      * @param bool $linktext show title next to image in link
1764      * @return string HTML fragment
1765      */
1766     public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1767         if (!($url instanceof moodle_url)) {
1768             $url = new moodle_url($url);
1769         }
1770         $attributes = (array)$attributes;
1772         if (empty($attributes['class'])) {
1773             // let ppl override the class via $options
1774             $attributes['class'] = 'action-icon';
1775         }
1777         $icon = $this->render($pixicon);
1779         if ($linktext) {
1780             $text = $pixicon->attributes['alt'];
1781         } else {
1782             $text = '';
1783         }
1785         return $this->action_link($url, $text.$icon, $action, $attributes);
1786     }
1788    /**
1789     * Print a message along with button choices for Continue/Cancel
1790     *
1791     * If a string or moodle_url is given instead of a single_button, method defaults to post.
1792     *
1793     * @param string $message The question to ask the user
1794     * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1795     * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1796     * @return string HTML fragment
1797     */
1798     public function confirm($message, $continue, $cancel) {
1799         if ($continue instanceof single_button) {
1800             // ok
1801             $continue->primary = true;
1802         } else if (is_string($continue)) {
1803             $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1804         } else if ($continue instanceof moodle_url) {
1805             $continue = new single_button($continue, get_string('continue'), 'post', true);
1806         } else {
1807             throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1808         }
1810         if ($cancel instanceof single_button) {
1811             // ok
1812         } else if (is_string($cancel)) {
1813             $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1814         } else if ($cancel instanceof moodle_url) {
1815             $cancel = new single_button($cancel, get_string('cancel'), 'get');
1816         } else {
1817             throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1818         }
1820         $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1821         $output .= $this->box_start('modal-content', 'modal-content');
1822         $output .= $this->box_start('modal-header', 'modal-header');
1823         $output .= html_writer::tag('h4', get_string('confirm'));
1824         $output .= $this->box_end();
1825         $output .= $this->box_start('modal-body', 'modal-body');
1826         $output .= html_writer::tag('p', $message);
1827         $output .= $this->box_end();
1828         $output .= $this->box_start('modal-footer', 'modal-footer');
1829         $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1830         $output .= $this->box_end();
1831         $output .= $this->box_end();
1832         $output .= $this->box_end();
1833         return $output;
1834     }
1836     /**
1837      * Returns a form with a single button.
1838      *
1839      * Theme developers: DO NOT OVERRIDE! Please override function
1840      * {@link core_renderer::render_single_button()} instead.
1841      *
1842      * @param string|moodle_url $url
1843      * @param string $label button text
1844      * @param string $method get or post submit method
1845      * @param array $options associative array {disabled, title, etc.}
1846      * @return string HTML fragment
1847      */
1848     public function single_button($url, $label, $method='post', array $options=null) {
1849         if (!($url instanceof moodle_url)) {
1850             $url = new moodle_url($url);
1851         }
1852         $button = new single_button($url, $label, $method);
1854         foreach ((array)$options as $key=>$value) {
1855             if (array_key_exists($key, $button)) {
1856                 $button->$key = $value;
1857             }
1858         }
1860         return $this->render($button);
1861     }
1863     /**
1864      * Renders a single button widget.
1865      *
1866      * This will return HTML to display a form containing a single button.
1867      *
1868      * @param single_button $button
1869      * @return string HTML fragment
1870      */
1871     protected function render_single_button(single_button $button) {
1872         $attributes = array('type'     => 'submit',
1873                             'value'    => $button->label,
1874                             'disabled' => $button->disabled ? 'disabled' : null,
1875                             'title'    => $button->tooltip);
1877         if ($button->actions) {
1878             $id = html_writer::random_id('single_button');
1879             $attributes['id'] = $id;
1880             foreach ($button->actions as $action) {
1881                 $this->add_action_handler($action, $id);
1882             }
1883         }
1885         // first the input element
1886         $output = html_writer::empty_tag('input', $attributes);
1888         // then hidden fields
1889         $params = $button->url->params();
1890         if ($button->method === 'post') {
1891             $params['sesskey'] = sesskey();
1892         }
1893         foreach ($params as $var => $val) {
1894             $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1895         }
1897         // then div wrapper for xhtml strictness
1898         $output = html_writer::tag('div', $output);
1900         // now the form itself around it
1901         if ($button->method === 'get') {
1902             $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1903         } else {
1904             $url = $button->url->out_omit_querystring();     // url without params, the anchor part not allowed
1905         }
1906         if ($url === '') {
1907             $url = '#'; // there has to be always some action
1908         }
1909         $attributes = array('method' => $button->method,
1910                             'action' => $url,
1911                             'id'     => $button->formid);
1912         $output = html_writer::tag('form', $output, $attributes);
1914         // and finally one more wrapper with class
1915         return html_writer::tag('div', $output, array('class' => $button->class));
1916     }
1918     /**
1919      * Returns a form with a single select widget.
1920      *
1921      * Theme developers: DO NOT OVERRIDE! Please override function
1922      * {@link core_renderer::render_single_select()} instead.
1923      *
1924      * @param moodle_url $url form action target, includes hidden fields
1925      * @param string $name name of selection field - the changing parameter in url
1926      * @param array $options list of options
1927      * @param string $selected selected element
1928      * @param array $nothing
1929      * @param string $formid
1930      * @param array $attributes other attributes for the single select
1931      * @return string HTML fragment
1932      */
1933     public function single_select($url, $name, array $options, $selected = '',
1934                                 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1935         if (!($url instanceof moodle_url)) {
1936             $url = new moodle_url($url);
1937         }
1938         $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1940         if (array_key_exists('label', $attributes)) {
1941             $select->set_label($attributes['label']);
1942             unset($attributes['label']);
1943         }
1944         $select->attributes = $attributes;
1946         return $this->render($select);
1947     }
1949     /**
1950      * Returns a dataformat selection and download form
1951      *
1952      * @param string $label A text label
1953      * @param moodle_url|string $base The download page url
1954      * @param string $name The query param which will hold the type of the download
1955      * @param array $params Extra params sent to the download page
1956      * @return string HTML fragment
1957      */
1958     public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
1960         $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
1961         $options = array();
1962         foreach ($formats as $format) {
1963             if ($format->is_enabled()) {
1964                 $options[] = array(
1965                     'value' => $format->name,
1966                     'label' => get_string('dataformat', $format->component),
1967                 );
1968             }
1969         }
1970         $hiddenparams = array();
1971         foreach ($params as $key => $value) {
1972             $hiddenparams[] = array(
1973                 'name' => $key,
1974                 'value' => $value,
1975             );
1976         }
1977         $data = array(
1978             'label' => $label,
1979             'base' => $base,
1980             'name' => $name,
1981             'params' => $hiddenparams,
1982             'options' => $options,
1983             'sesskey' => sesskey(),
1984             'submit' => get_string('download'),
1985         );
1987         return $this->render_from_template('core/dataformat_selector', $data);
1988     }
1991     /**
1992      * Internal implementation of single_select rendering
1993      *
1994      * @param single_select $select
1995      * @return string HTML fragment
1996      */
1997     protected function render_single_select(single_select $select) {
1998         return $this->render_from_template('core/single_select', $select->export_for_template($this));
1999     }
2001     /**
2002      * Returns a form with a url select widget.
2003      *
2004      * Theme developers: DO NOT OVERRIDE! Please override function
2005      * {@link core_renderer::render_url_select()} instead.
2006      *
2007      * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2008      * @param string $selected selected element
2009      * @param array $nothing
2010      * @param string $formid
2011      * @return string HTML fragment
2012      */
2013     public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2014         $select = new url_select($urls, $selected, $nothing, $formid);
2015         return $this->render($select);
2016     }
2018     /**
2019      * Internal implementation of url_select rendering
2020      *
2021      * @param url_select $select
2022      * @return string HTML fragment
2023      */
2024     protected function render_url_select(url_select $select) {
2025         return $this->render_from_template('core/url_select', $select->export_for_template($this));
2026     }
2028     /**
2029      * Returns a string containing a link to the user documentation.
2030      * Also contains an icon by default. Shown to teachers and admin only.
2031      *
2032      * @param string $path The page link after doc root and language, no leading slash.
2033      * @param string $text The text to be displayed for the link
2034      * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2035      * @return string
2036      */
2037     public function doc_link($path, $text = '', $forcepopup = false) {
2038         global $CFG;
2040         $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2042         $url = new moodle_url(get_docs_url($path));
2044         $attributes = array('href'=>$url);
2045         if (!empty($CFG->doctonewwindow) || $forcepopup) {
2046             $attributes['class'] = 'helplinkpopup';
2047         }
2049         return html_writer::tag('a', $icon.$text, $attributes);
2050     }
2052     /**
2053      * Return HTML for an image_icon.
2054      *
2055      * Theme developers: DO NOT OVERRIDE! Please override function
2056      * {@link core_renderer::render_image_icon()} instead.
2057      *
2058      * @param string $pix short pix name
2059      * @param string $alt mandatory alt attribute
2060      * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2061      * @param array $attributes htm lattributes
2062      * @return string HTML fragment
2063      */
2064     public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2065         $icon = new image_icon($pix, $alt, $component, $attributes);
2066         return $this->render($icon);
2067     }
2069     /**
2070      * Renders a pix_icon widget and returns the HTML to display it.
2071      *
2072      * @param image_icon $icon
2073      * @return string HTML fragment
2074      */
2075     protected function render_image_icon(image_icon $icon) {
2076         $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2077         return $system->render_pix_icon($this, $icon);
2078     }
2080     /**
2081      * Return HTML for a pix_icon.
2082      *
2083      * Theme developers: DO NOT OVERRIDE! Please override function
2084      * {@link core_renderer::render_pix_icon()} instead.
2085      *
2086      * @param string $pix short pix name
2087      * @param string $alt mandatory alt attribute
2088      * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2089      * @param array $attributes htm lattributes
2090      * @return string HTML fragment
2091      */
2092     public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2093         $icon = new pix_icon($pix, $alt, $component, $attributes);
2094         return $this->render($icon);
2095     }
2097     /**
2098      * Renders a pix_icon widget and returns the HTML to display it.
2099      *
2100      * @param pix_icon $icon
2101      * @return string HTML fragment
2102      */
2103     protected function render_pix_icon(pix_icon $icon) {
2104         $system = \core\output\icon_system::instance();
2105         return $system->render_pix_icon($this, $icon);
2106     }
2108     /**
2109      * Return HTML to display an emoticon icon.
2110      *
2111      * @param pix_emoticon $emoticon
2112      * @return string HTML fragment
2113      */
2114     protected function render_pix_emoticon(pix_emoticon $emoticon) {
2115         $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2116         return $system->render_pix_icon($this, $emoticon);
2117     }
2119     /**
2120      * Produces the html that represents this rating in the UI
2121      *
2122      * @param rating $rating the page object on which this rating will appear
2123      * @return string
2124      */
2125     function render_rating(rating $rating) {
2126         global $CFG, $USER;
2128         if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2129             return null;//ratings are turned off
2130         }
2132         $ratingmanager = new rating_manager();
2133         // Initialise the JavaScript so ratings can be done by AJAX.
2134         $ratingmanager->initialise_rating_javascript($this->page);
2136         $strrate = get_string("rate", "rating");
2137         $ratinghtml = ''; //the string we'll return
2139         // permissions check - can they view the aggregate?
2140         if ($rating->user_can_view_aggregate()) {
2142             $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2143             $aggregatestr   = $rating->get_aggregate_string();
2145             $aggregatehtml  = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2146             if ($rating->count > 0) {
2147                 $countstr = "({$rating->count})";
2148             } else {
2149                 $countstr = '-';
2150             }
2151             $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2153             $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2154             if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2156                 $nonpopuplink = $rating->get_view_ratings_url();
2157                 $popuplink = $rating->get_view_ratings_url(true);
2159                 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2160                 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2161             } else {
2162                 $ratinghtml .= $aggregatehtml;
2163             }
2164         }
2166         $formstart = null;
2167         // if the item doesn't belong to the current user, the user has permission to rate
2168         // and we're within the assessable period
2169         if ($rating->user_can_rate()) {
2171             $rateurl = $rating->get_rate_url();
2172             $inputs = $rateurl->params();
2174             //start the rating form
2175             $formattrs = array(
2176                 'id'     => "postrating{$rating->itemid}",
2177                 'class'  => 'postratingform',
2178                 'method' => 'post',
2179                 'action' => $rateurl->out_omit_querystring()
2180             );
2181             $formstart  = html_writer::start_tag('form', $formattrs);
2182             $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2184             // add the hidden inputs
2185             foreach ($inputs as $name => $value) {
2186                 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2187                 $formstart .= html_writer::empty_tag('input', $attributes);
2188             }
2190             if (empty($ratinghtml)) {
2191                 $ratinghtml .= $strrate.': ';
2192             }
2193             $ratinghtml = $formstart.$ratinghtml;
2195             $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2196             $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2197             $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2198             $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2200             //output submit button
2201             $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2203             $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2204             $ratinghtml .= html_writer::empty_tag('input', $attributes);
2206             if (!$rating->settings->scale->isnumeric) {
2207                 // If a global scale, try to find current course ID from the context
2208                 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2209                     $courseid = $coursecontext->instanceid;
2210                 } else {
2211                     $courseid = $rating->settings->scale->courseid;
2212                 }
2213                 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2214             }
2215             $ratinghtml .= html_writer::end_tag('span');
2216             $ratinghtml .= html_writer::end_tag('div');
2217             $ratinghtml .= html_writer::end_tag('form');
2218         }
2220         return $ratinghtml;
2221     }
2223     /**
2224      * Centered heading with attached help button (same title text)
2225      * and optional icon attached.
2226      *
2227      * @param string $text A heading text
2228      * @param string $helpidentifier The keyword that defines a help page
2229      * @param string $component component name
2230      * @param string|moodle_url $icon
2231      * @param string $iconalt icon alt text
2232      * @param int $level The level of importance of the heading. Defaulting to 2
2233      * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2234      * @return string HTML fragment
2235      */
2236     public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2237         $image = '';
2238         if ($icon) {
2239             $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2240         }
2242         $help = '';
2243         if ($helpidentifier) {
2244             $help = $this->help_icon($helpidentifier, $component);
2245         }
2247         return $this->heading($image.$text.$help, $level, $classnames);
2248     }
2250     /**
2251      * Returns HTML to display a help icon.
2252      *
2253      * @deprecated since Moodle 2.0
2254      */
2255     public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2256         throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2257     }
2259     /**
2260      * Returns HTML to display a help icon.
2261      *
2262      * Theme developers: DO NOT OVERRIDE! Please override function
2263      * {@link core_renderer::render_help_icon()} instead.
2264      *
2265      * @param string $identifier The keyword that defines a help page
2266      * @param string $component component name
2267      * @param string|bool $linktext true means use $title as link text, string means link text value
2268      * @return string HTML fragment
2269      */
2270     public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2271         $icon = new help_icon($identifier, $component);
2272         $icon->diag_strings();
2273         if ($linktext === true) {
2274             $icon->linktext = get_string($icon->identifier, $icon->component);
2275         } else if (!empty($linktext)) {
2276             $icon->linktext = $linktext;
2277         }
2278         return $this->render($icon);
2279     }
2281     /**
2282      * Implementation of user image rendering.
2283      *
2284      * @param help_icon $helpicon A help icon instance
2285      * @return string HTML fragment
2286      */
2287     protected function render_help_icon(help_icon $helpicon) {
2288         return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2289     }
2291     /**
2292      * Returns HTML to display a scale help icon.
2293      *
2294      * @param int $courseid
2295      * @param stdClass $scale instance
2296      * @return string HTML fragment
2297      */
2298     public function help_icon_scale($courseid, stdClass $scale) {
2299         global $CFG;
2301         $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2303         $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2305         $scaleid = abs($scale->id);
2307         $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2308         $action = new popup_action('click', $link, 'ratingscale');
2310         return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2311     }
2313     /**
2314      * Creates and returns a spacer image with optional line break.
2315      *
2316      * @param array $attributes Any HTML attributes to add to the spaced.
2317      * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2318      *     laxy do it with CSS which is a much better solution.
2319      * @return string HTML fragment
2320      */
2321     public function spacer(array $attributes = null, $br = false) {
2322         $attributes = (array)$attributes;
2323         if (empty($attributes['width'])) {
2324             $attributes['width'] = 1;
2325         }
2326         if (empty($attributes['height'])) {
2327             $attributes['height'] = 1;
2328         }
2329         $attributes['class'] = 'spacer';
2331         $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2333         if (!empty($br)) {
2334             $output .= '<br />';
2335         }
2337         return $output;
2338     }
2340     /**
2341      * Returns HTML to display the specified user's avatar.
2342      *
2343      * User avatar may be obtained in two ways:
2344      * <pre>
2345      * // Option 1: (shortcut for simple cases, preferred way)
2346      * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2347      * $OUTPUT->user_picture($user, array('popup'=>true));
2348      *
2349      * // Option 2:
2350      * $userpic = new user_picture($user);
2351      * // Set properties of $userpic
2352      * $userpic->popup = true;
2353      * $OUTPUT->render($userpic);
2354      * </pre>
2355      *
2356      * Theme developers: DO NOT OVERRIDE! Please override function
2357      * {@link core_renderer::render_user_picture()} instead.
2358      *
2359      * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2360      *     If any of these are missing, the database is queried. Avoid this
2361      *     if at all possible, particularly for reports. It is very bad for performance.
2362      * @param array $options associative array with user picture options, used only if not a user_picture object,
2363      *     options are:
2364      *     - courseid=$this->page->course->id (course id of user profile in link)
2365      *     - size=35 (size of image)
2366      *     - link=true (make image clickable - the link leads to user profile)
2367      *     - popup=false (open in popup)
2368      *     - alttext=true (add image alt attribute)
2369      *     - class = image class attribute (default 'userpicture')
2370      *     - visibletoscreenreaders=true (whether to be visible to screen readers)
2371      *     - includefullname=false (whether to include the user's full name together with the user picture)
2372      * @return string HTML fragment
2373      */
2374     public function user_picture(stdClass $user, array $options = null) {
2375         $userpicture = new user_picture($user);
2376         foreach ((array)$options as $key=>$value) {
2377             if (array_key_exists($key, $userpicture)) {
2378                 $userpicture->$key = $value;
2379             }
2380         }
2381         return $this->render($userpicture);
2382     }
2384     /**
2385      * Internal implementation of user image rendering.
2386      *
2387      * @param user_picture $userpicture
2388      * @return string
2389      */
2390     protected function render_user_picture(user_picture $userpicture) {
2391         global $CFG, $DB;
2393         $user = $userpicture->user;
2395         if ($userpicture->alttext) {
2396             if (!empty($user->imagealt)) {
2397                 $alt = $user->imagealt;
2398             } else {
2399                 $alt = get_string('pictureof', '', fullname($user));
2400             }
2401         } else {
2402             $alt = '';
2403         }
2405         if (empty($userpicture->size)) {
2406             $size = 35;
2407         } else if ($userpicture->size === true or $userpicture->size == 1) {
2408             $size = 100;
2409         } else {
2410             $size = $userpicture->size;
2411         }
2413         $class = $userpicture->class;
2415         if ($user->picture == 0) {
2416             $class .= ' defaultuserpic';
2417         }
2419         $src = $userpicture->get_url($this->page, $this);
2421         $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2422         if (!$userpicture->visibletoscreenreaders) {
2423             $attributes['role'] = 'presentation';
2424         }
2426         // get the image html output fisrt
2427         $output = html_writer::empty_tag('img', $attributes);
2429         // Show fullname together with the picture when desired.
2430         if ($userpicture->includefullname) {
2431             $output .= fullname($userpicture->user);
2432         }
2434         // then wrap it in link if needed
2435         if (!$userpicture->link) {
2436             return $output;
2437         }
2439         if (empty($userpicture->courseid)) {
2440             $courseid = $this->page->course->id;
2441         } else {
2442             $courseid = $userpicture->courseid;
2443         }
2445         if ($courseid == SITEID) {
2446             $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2447         } else {
2448             $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2449         }
2451         $attributes = array('href'=>$url);
2452         if (!$userpicture->visibletoscreenreaders) {
2453             $attributes['tabindex'] = '-1';
2454             $attributes['aria-hidden'] = 'true';
2455         }
2457         if ($userpicture->popup) {
2458             $id = html_writer::random_id('userpicture');
2459             $attributes['id'] = $id;
2460             $this->add_action_handler(new popup_action('click', $url), $id);
2461         }
2463         return html_writer::tag('a', $output, $attributes);
2464     }
2466     /**
2467      * Internal implementation of file tree viewer items rendering.
2468      *
2469      * @param array $dir
2470      * @return string
2471      */
2472     public function htmllize_file_tree($dir) {
2473         if (empty($dir['subdirs']) and empty($dir['files'])) {
2474             return '';
2475         }
2476         $result = '<ul>';
2477         foreach ($dir['subdirs'] as $subdir) {
2478             $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2479         }
2480         foreach ($dir['files'] as $file) {
2481             $filename = $file->get_filename();
2482             $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2483         }
2484         $result .= '</ul>';
2486         return $result;
2487     }
2489     /**
2490      * Returns HTML to display the file picker
2491      *
2492      * <pre>
2493      * $OUTPUT->file_picker($options);
2494      * </pre>
2495      *
2496      * Theme developers: DO NOT OVERRIDE! Please override function
2497      * {@link core_renderer::render_file_picker()} instead.
2498      *
2499      * @param array $options associative array with file manager options
2500      *   options are:
2501      *       maxbytes=>-1,
2502      *       itemid=>0,
2503      *       client_id=>uniqid(),
2504      *       acepted_types=>'*',
2505      *       return_types=>FILE_INTERNAL,
2506      *       context=>$PAGE->context
2507      * @return string HTML fragment
2508      */
2509     public function file_picker($options) {
2510         $fp = new file_picker($options);
2511         return $this->render($fp);
2512     }
2514     /**
2515      * Internal implementation of file picker rendering.
2516      *
2517      * @param file_picker $fp
2518      * @return string
2519      */
2520     public function render_file_picker(file_picker $fp) {
2521         global $CFG, $OUTPUT, $USER;
2522         $options = $fp->options;
2523         $client_id = $options->client_id;
2524         $strsaved = get_string('filesaved', 'repository');
2525         $straddfile = get_string('openpicker', 'repository');
2526         $strloading  = get_string('loading', 'repository');
2527         $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2528         $strdroptoupload = get_string('droptoupload', 'moodle');
2529         $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2531         $currentfile = $options->currentfile;
2532         if (empty($currentfile)) {
2533             $currentfile = '';
2534         } else {
2535             $currentfile .= ' - ';
2536         }
2537         if ($options->maxbytes) {
2538             $size = $options->maxbytes;
2539         } else {
2540             $size = get_max_upload_file_size();
2541         }
2542         if ($size == -1) {
2543             $maxsize = '';
2544         } else {
2545             $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2546         }
2547         if ($options->buttonname) {
2548             $buttonname = ' name="' . $options->buttonname . '"';
2549         } else {
2550             $buttonname = '';
2551         }
2552         $html = <<<EOD
2553 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2554 $icon_progress
2555 </div>
2556 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2557     <div>
2558         <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2559         <span> $maxsize </span>
2560     </div>
2561 EOD;
2562         if ($options->env != 'url') {
2563             $html .= <<<EOD
2564     <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2565     <div class="filepicker-filename">
2566         <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2567         <div class="dndupload-progressbars"></div>
2568     </div>
2569     <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2570     </div>
2571 EOD;
2572         }
2573         $html .= '</div>';
2574         return $html;
2575     }
2577     /**
2578      * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2579      *
2580      * @deprecated since Moodle 3.2
2581      *
2582      * @param string $cmid the course_module id.
2583      * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2584      * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2585      */
2586     public function update_module_button($cmid, $modulename) {
2587         global $CFG;
2589         debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2590             'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2591             'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2593         if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2594             $modulename = get_string('modulename', $modulename);
2595             $string = get_string('updatethis', '', $modulename);
2596             $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2597             return $this->single_button($url, $string);
2598         } else {
2599             return '';
2600         }
2601     }
2603     /**
2604      * Returns HTML to display a "Turn editing on/off" button in a form.
2605      *
2606      * @param moodle_url $url The URL + params to send through when clicking the button
2607      * @return string HTML the button
2608      */
2609     public function edit_button(moodle_url $url) {
2611         $url->param('sesskey', sesskey());
2612         if ($this->page->user_is_editing()) {
2613             $url->param('edit', 'off');
2614             $editstring = get_string('turneditingoff');
2615         } else {
2616             $url->param('edit', 'on');
2617             $editstring = get_string('turneditingon');
2618         }
2620         return $this->single_button($url, $editstring);
2621     }
2623     /**
2624      * Returns HTML to display a simple button to close a window
2625      *
2626      * @param string $text The lang string for the button's label (already output from get_string())
2627      * @return string html fragment
2628      */
2629     public function close_window_button($text='') {
2630         if (empty($text)) {
2631             $text = get_string('closewindow');
2632         }
2633         $button = new single_button(new moodle_url('#'), $text, 'get');
2634         $button->add_action(new component_action('click', 'close_window'));
2636         return $this->container($this->render($button), 'closewindow');
2637     }
2639     /**
2640      * Output an error message. By default wraps the error message in <span class="error">.
2641      * If the error message is blank, nothing is output.
2642      *
2643      * @param string $message the error message.
2644      * @return string the HTML to output.
2645      */
2646     public function error_text($message) {
2647         if (empty($message)) {
2648             return '';
2649         }
2650         $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2651         return html_writer::tag('span', $message, array('class' => 'error'));
2652     }
2654     /**
2655      * Do not call this function directly.
2656      *
2657      * To terminate the current script with a fatal error, call the {@link print_error}
2658      * function, or throw an exception. Doing either of those things will then call this
2659      * function to display the error, before terminating the execution.
2660      *
2661      * @param string $message The message to output
2662      * @param string $moreinfourl URL where more info can be found about the error
2663      * @param string $link Link for the Continue button
2664      * @param array $backtrace The execution backtrace
2665      * @param string $debuginfo Debugging information
2666      * @return string the HTML to output.
2667      */
2668     public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2669         global $CFG;
2671         $output = '';
2672         $obbuffer = '';
2674         if ($this->has_started()) {
2675             // we can not always recover properly here, we have problems with output buffering,
2676             // html tables, etc.
2677             $output .= $this->opencontainers->pop_all_but_last();
2679         } else {
2680             // It is really bad if library code throws exception when output buffering is on,
2681             // because the buffered text would be printed before our start of page.
2682             // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2683             error_reporting(0); // disable notices from gzip compression, etc.
2684             while (ob_get_level() > 0) {
2685                 $buff = ob_get_clean();
2686                 if ($buff === false) {
2687                     break;
2688                 }
2689                 $obbuffer .= $buff;
2690             }
2691             error_reporting($CFG->debug);
2693             // Output not yet started.
2694             $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2695             if (empty($_SERVER['HTTP_RANGE'])) {
2696                 @header($protocol . ' 404 Not Found');
2697             } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2698                 // Coax iOS 10 into sending the session cookie.
2699                 @header($protocol . ' 403 Forbidden');
2700             } else {
2701                 // Must stop byteserving attempts somehow,
2702                 // this is weird but Chrome PDF viewer can be stopped only with 407!
2703                 @header($protocol . ' 407 Proxy Authentication Required');
2704             }
2706             $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2707             $this->page->set_url('/'); // no url
2708             //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2709             $this->page->set_title(get_string('error'));
2710             $this->page->set_heading($this->page->course->fullname);
2711             $output .= $this->header();
2712         }
2714         $message = '<p class="errormessage">' . $message . '</p>'.
2715                 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2716                 get_string('moreinformation') . '</a></p>';
2717         if (empty($CFG->rolesactive)) {
2718             $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2719             //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.
2720         }
2721         $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2723         if ($CFG->debugdeveloper) {
2724             if (!empty($debuginfo)) {
2725                 $debuginfo = s($debuginfo); // removes all nasty JS
2726                 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2727                 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2728             }
2729             if (!empty($backtrace)) {
2730                 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2731             }
2732             if ($obbuffer !== '' ) {
2733                 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2734             }
2735         }
2737         if (empty($CFG->rolesactive)) {
2738             // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2739         } else if (!empty($link)) {
2740             $output .= $this->continue_button($link);
2741         }
2743         $output .= $this->footer();
2745         // Padding to encourage IE to display our error page, rather than its own.
2746         $output .= str_repeat(' ', 512);
2748         return $output;
2749     }
2751     /**
2752      * Output a notification (that is, a status message about something that has just happened).
2753      *
2754      * Note: \core\notification::add() may be more suitable for your usage.
2755      *
2756      * @param string $message The message to print out.
2757      * @param string $type    The type of notification. See constants on \core\output\notification.
2758      * @return string the HTML to output.
2759      */
2760     public function notification($message, $type = null) {
2761         $typemappings = [
2762             // Valid types.
2763             'success'           => \core\output\notification::NOTIFY_SUCCESS,
2764             'info'              => \core\output\notification::NOTIFY_INFO,
2765             'warning'           => \core\output\notification::NOTIFY_WARNING,
2766             'error'             => \core\output\notification::NOTIFY_ERROR,
2768             // Legacy types mapped to current types.
2769             'notifyproblem'     => \core\output\notification::NOTIFY_ERROR,
2770             'notifytiny'        => \core\output\notification::NOTIFY_ERROR,
2771             'notifyerror'       => \core\output\notification::NOTIFY_ERROR,
2772             'notifysuccess'     => \core\output\notification::NOTIFY_SUCCESS,
2773             'notifymessage'     => \core\output\notification::NOTIFY_INFO,
2774             'notifyredirect'    => \core\output\notification::NOTIFY_INFO,
2775             'redirectmessage'   => \core\output\notification::NOTIFY_INFO,
2776         ];
2778         $extraclasses = [];
2780         if ($type) {
2781             if (strpos($type, ' ') === false) {
2782                 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2783                 if (isset($typemappings[$type])) {
2784                     $type = $typemappings[$type];
2785                 } else {
2786                     // The value provided did not match a known type. It must be an extra class.
2787                     $extraclasses = [$type];
2788                 }
2789             } else {
2790                 // Identify what type of notification this is.
2791                 $classarray = explode(' ', self::prepare_classes($type));
2793                 // Separate out the type of notification from the extra classes.
2794                 foreach ($classarray as $class) {
2795                     if (isset($typemappings[$class])) {
2796                         $type = $typemappings[$class];
2797                     } else {
2798                         $extraclasses[] = $class;
2799                     }
2800                 }
2801             }
2802         }
2804         $notification = new \core\output\notification($message, $type);
2805         if (count($extraclasses)) {
2806             $notification->set_extra_classes($extraclasses);
2807         }
2809         // Return the rendered template.
2810         return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2811     }
2813     /**
2814      * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2815      *
2816      * @param string $message the message to print out
2817      * @return string HTML fragment.
2818      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2819      * @todo MDL-53113 This will be removed in Moodle 3.5.
2820      * @see \core\output\notification
2821      */
2822     public function notify_problem($message) {
2823         debugging(__FUNCTION__ . ' is deprecated.' .
2824             'Please use \core\notification::add, or \core\output\notification as required',
2825             DEBUG_DEVELOPER);
2826         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
2827         return $this->render($n);
2828     }
2830     /**
2831      * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2832      *
2833      * @param string $message the message to print out
2834      * @return string HTML fragment.
2835      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2836      * @todo MDL-53113 This will be removed in Moodle 3.5.
2837      * @see \core\output\notification
2838      */
2839     public function notify_success($message) {
2840         debugging(__FUNCTION__ . ' is deprecated.' .
2841             'Please use \core\notification::add, or \core\output\notification as required',
2842             DEBUG_DEVELOPER);
2843         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2844         return $this->render($n);
2845     }
2847     /**
2848      * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2849      *
2850      * @param string $message the message to print out
2851      * @return string HTML fragment.
2852      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2853      * @todo MDL-53113 This will be removed in Moodle 3.5.
2854      * @see \core\output\notification
2855      */
2856     public function notify_message($message) {
2857         debugging(__FUNCTION__ . ' is deprecated.' .
2858             'Please use \core\notification::add, or \core\output\notification as required',
2859             DEBUG_DEVELOPER);
2860         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2861         return $this->render($n);
2862     }
2864     /**
2865      * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2866      *
2867      * @param string $message the message to print out
2868      * @return string HTML fragment.
2869      * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2870      * @todo MDL-53113 This will be removed in Moodle 3.5.
2871      * @see \core\output\notification
2872      */
2873     public function notify_redirect($message) {
2874         debugging(__FUNCTION__ . ' is deprecated.' .
2875             'Please use \core\notification::add, or \core\output\notification as required',
2876             DEBUG_DEVELOPER);
2877         $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2878         return $this->render($n);
2879     }
2881     /**
2882      * Render a notification (that is, a status message about something that has
2883      * just happened).
2884      *
2885      * @param \core\output\notification $notification the notification to print out
2886      * @return string the HTML to output.
2887      */
2888     protected function render_notification(\core\output\notification $notification) {
2889         return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2890     }
2892     /**
2893      * Returns HTML to display a continue button that goes to a particular URL.
2894      *
2895      * @param string|moodle_url $url The url the button goes to.
2896      * @return string the HTML to output.
2897      */
2898     public function continue_button($url) {
2899         if (!($url instanceof moodle_url)) {
2900             $url = new moodle_url($url);
2901         }
2902         $button = new single_button($url, get_string('continue'), 'get', true);
2903         $button->class = 'continuebutton';
2905         return $this->render($button);
2906     }
2908     /**
2909      * Returns HTML to display a single paging bar to provide access to other pages  (usually in a search)
2910      *
2911      * Theme developers: DO NOT OVERRIDE! Please override function
2912      * {@link core_renderer::render_paging_bar()} instead.
2913      *
2914      * @param int $totalcount The total number of entries available to be paged through
2915      * @param int $page The page you are currently viewing
2916      * @param int $perpage The number of entries that should be shown per page
2917      * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2918      * @param string $pagevar name of page parameter that holds the page number
2919      * @return string the HTML to output.
2920      */
2921     public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2922         $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2923         return $this->render($pb);
2924     }
2926     /**
2927      * Internal implementation of paging bar rendering.
2928      *
2929      * @param paging_bar $pagingbar
2930      * @return string
2931      */
2932     protected function render_paging_bar(paging_bar $pagingbar) {
2933         $output = '';
2934         $pagingbar = clone($pagingbar);
2935         $pagingbar->prepare($this, $this->page, $this->target);
2937         if ($pagingbar->totalcount > $pagingbar->perpage) {
2938             $output .= get_string('page') . ':';
2940             if (!empty($pagingbar->previouslink)) {
2941                 $output .= ' (' . $pagingbar->previouslink . ') ';
2942             }
2944             if (!empty($pagingbar->firstlink)) {
2945                 $output .= ' ' . $pagingbar->firstlink . ' ...';
2946             }
2948             foreach ($pagingbar->pagelinks as $link) {
2949                 $output .= "  $link";
2950             }
2952             if (!empty($pagingbar->lastlink)) {
2953                 $output .= ' ... ' . $pagingbar->lastlink . ' ';
2954             }
2956             if (!empty($pagingbar->nextlink)) {
2957                 $output .= '  (' . $pagingbar->nextlink . ')';
2958             }
2959         }
2961         return html_writer::tag('div', $output, array('class' => 'paging'));
2962     }
2964     /**
2965      * Returns HTML to display initials bar to provide access to other pages  (usually in a search)
2966      *
2967      * @param string $current the currently selected letter.
2968      * @param string $class class name to add to this initial bar.
2969      * @param string $title the name to put in front of this initial bar.
2970      * @param string $urlvar URL parameter name for this initial.
2971      * @param string $url URL object.
2972      * @param array $alpha of letters in the alphabet.
2973      * @return string the HTML to output.
2974      */
2975     public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
2976         $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
2977         return $this->render($ib);
2978     }
2980     /**
2981      * Internal implementation of initials bar rendering.
2982      *
2983      * @param initials_bar $initialsbar
2984      * @return string
2985      */
2986     protected function render_initials_bar(initials_bar $initialsbar) {
2987         return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
2988     }
2990     /**
2991      * Output the place a skip link goes to.
2992      *
2993      * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2994      * @return string the HTML to output.
2995      */
2996     public function skip_link_target($id = null) {
2997         return html_writer::span('', '', array('id' => $id));
2998     }
3000     /**
3001      * Outputs a heading
3002      *
3003      * @param string $text The text of the heading
3004      * @param int $level The level of importance of the heading. Defaulting to 2
3005      * @param string $classes A space-separated list of CSS classes. Defaulting to null
3006      * @param string $id An optional ID
3007      * @return string the HTML to output.
3008      */
3009     public function heading($text, $level = 2, $classes = null, $id = null) {
3010         $level = (integer) $level;
3011         if ($level < 1 or $level > 6) {
3012             throw new coding_exception('Heading level must be an integer between 1 and 6.');
3013         }
3014         return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3015     }
3017     /**
3018      * Outputs a box.
3019      *
3020      * @param string $contents The contents of the box
3021      * @param string $classes A space-separated list of CSS classes
3022      * @param string $id An optional ID
3023      * @param array $attributes An array of other attributes to give the box.
3024      * @return string the HTML to output.
3025      */
3026     public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3027         return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3028     }
3030     /**
3031      * Outputs the opening section of a box.
3032      *
3033      * @param string $classes A space-separated list of CSS classes
3034      * @param string $id An optional ID
3035      * @param array $attributes An array of other attributes to give the box.
3036      * @return string the HTML to output.
3037      */
3038     public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3039         $this->opencontainers->push('box', html_writer::end_tag('div'));
3040         $attributes['id'] = $id;
3041         $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3042         return html_writer::start_tag('div', $attributes);
3043     }
3045     /**
3046      * Outputs the closing section of a box.
3047      *
3048      * @return string the HTML to output.
3049      */
3050     public function box_end() {
3051         return $this->opencontainers->pop('box');
3052     }
3054     /**
3055      * Outputs a container.
3056      *
3057      * @param string $contents The contents of the box
3058      * @param string $classes A space-separated list of CSS classes
3059      * @param string $id An optional ID
3060      * @return string the HTML to output.
3061      */
3062     public function container($contents, $classes = null, $id = null) {
3063         return $this->container_start($classes, $id) . $contents . $this->container_end();
3064     }
3066     /**
3067      * Outputs the opening section of a container.
3068      *
3069      * @param string $classes A space-separated list of CSS classes
3070      * @param string $id An optional ID
3071      * @return string the HTML to output.
3072      */
3073     public function container_start($classes = null, $id = null) {
3074         $this->opencontainers->push('container', html_writer::end_tag('div'));
3075         return html_writer::start_tag('div', array('id' => $id,
3076                 'class' => renderer_base::prepare_classes($classes)));
3077     }
3079     /**
3080      * Outputs the closing section of a container.
3081      *
3082      * @return string the HTML to output.
3083      */
3084     public function container_end() {
3085         return $this->opencontainers->pop('container');
3086     }
3088     /**
3089      * Make nested HTML lists out of the items
3090      *
3091      * The resulting list will look something like this:
3092      *
3093      * <pre>
3094      * <<ul>>
3095      * <<li>><div class='tree_item parent'>(item contents)</div>
3096      *      <<ul>
3097      *      <<li>><div class='tree_item'>(item contents)</div><</li>>
3098      *      <</ul>>
3099      * <</li>>
3100      * <</ul>>
3101      * </pre>
3102      *
3103      * @param array $items
3104      * @param array $attrs html attributes passed to the top ofs the list
3105      * @return string HTML
3106      */
3107     public function tree_block_contents($items, $attrs = array()) {
3108         // exit if empty, we don't want an empty ul element
3109         if (empty($items)) {
3110             return '';
3111         }
3112         // array of nested li elements
3113         $lis = array();
3114         foreach ($items as $item) {
3115             // this applies to the li item which contains all child lists too
3116             $content = $item->content($this);
3117             $liclasses = array($item->get_css_type());
3118             if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0  && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3119                 $liclasses[] = 'collapsed';
3120             }
3121             if ($item->isactive === true) {
3122                 $liclasses[] = 'current_branch';
3123             }
3124             $liattr = array('class'=>join(' ',$liclasses));
3125             // class attribute on the div item which only contains the item content
3126             $divclasses = array('tree_item');
3127             if ($item->children->count()>0  || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3128                 $divclasses[] = 'branch';
3129             } else {
3130                 $divclasses[] = 'leaf';
3131             }
3132             if (!empty($item->classes) && count($item->classes)>0) {
3133                 $divclasses[] = join(' ', $item->classes);
3134             }
3135             $divattr = array('class'=>join(' ', $divclasses));
3136             if (!empty($item->id)) {
3137                 $divattr['id'] = $item->id;
3138             }
3139             $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3140             if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3141                 $content = html_writer::empty_tag('hr') . $content;
3142             }
3143             $content = html_writer::tag('li', $content, $liattr);
3144             $lis[] = $content;
3145         }
3146         return html_writer::tag('ul', implode("\n", $lis), $attrs);
3147     }
3149     /**
3150      * Returns a search box.
3151      *
3152      * @param  string $id     The search box wrapper div id, defaults to an autogenerated one.
3153      * @return string         HTML with the search form hidden by default.
3154      */
3155     public function search_box($id = false) {
3156         global $CFG;
3158         // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3159         // result in an extra included file for each site, even the ones where global search
3160         // is disabled.
3161         if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3162             return '';
3163         }
3165         if ($id == false) {
3166             $id = uniqid();
3167         } else {
3168             // Needs to be cleaned, we use it for the input id.
3169             $id = clean_param($id, PARAM_ALPHANUMEXT);
3170         }
3172         // JS to animate the form.
3173         $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3175         $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3176             array('role' => 'button', 'tabindex' => 0));
3177         $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3178         $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3179             'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id);
3181         $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3182             array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3183         $searchinput = html_writer::tag('form', $contents, $formattrs);
3185         return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3186     }
3188     /**
3189      * Allow plugins to provide some content to be rendered in the navbar.
3190      * The plugin must define a PLUGIN_render_navbar_output function that returns
3191      * the HTML they wish to add to the navbar.
3192      *
3193      * @return string HTML for the navbar
3194      */
3195     public function navbar_plugin_output() {
3196         $output = '';
3198         if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3199             foreach ($pluginsfunction as $plugintype => $plugins) {
3200                 foreach ($plugins as $pluginfunction) {
3201                     $output .= $pluginfunction($this);
3202                 }
3203             }
3204         }
3206         return $output;
3207     }
3209     /**
3210      * Construct a user menu, returning HTML that can be echoed out by a
3211      * layout file.
3212      *
3213      * @param stdClass $user A user object, usually $USER.
3214      * @param bool $withlinks true if a dropdown should be built.
3215      * @return string HTML fragment.
3216      */
3217     public function user_menu($user = null, $withlinks = null) {
3218         global $USER, $CFG;
3219         require_once($CFG->dirroot . '/user/lib.php');
3221         if (is_null($user)) {
3222             $user = $USER;
3223         }
3225         // Note: this behaviour is intended to match that of core_renderer::login_info,
3226         // but should not be considered to be good practice; layout options are
3227         // intended to be theme-specific. Please don't copy this snippet anywhere else.
3228         if (is_null($withlinks)) {
3229             $withlinks = empty($this->page->layout_options['nologinlinks']);
3230         }
3232         // Add a class for when $withlinks is false.
3233         $usermenuclasses = 'usermenu';
3234         if (!$withlinks) {
3235             $usermenuclasses .= ' withoutlinks';
3236         }
3238         $returnstr = "";
3240         // If during initial install, return the empty return string.
3241         if (during_initial_install()) {
3242             return $returnstr;
3243         }
3245         $loginpage = $this->is_login_page();
3246         $loginurl = get_login_url();
3247         // If not logged in, show the typical not-logged-in string.
3248         if (!isloggedin()) {
3249             $returnstr = get_string('loggedinnot', 'moodle');
3250             if (!$loginpage) {
3251                 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3252             }
3253             return html_writer::div(
3254                 html_writer::span(
3255                     $returnstr,
3256                     'login'
3257                 ),
3258                 $usermenuclasses
3259             );
3261         }
3263         // If logged in as a guest user, show a string to that effect.
3264         if (isguestuser()) {
3265             $returnstr = get_string('loggedinasguest');
3266             if (!$loginpage && $withlinks) {
3267                 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3268             }
3270             return html_writer::div(
3271                 html_writer::span(
3272                     $returnstr,
3273                     'login'
3274                 ),
3275                 $usermenuclasses
3276             );
3277         }
3279         // Get some navigation opts.
3280         $opts = user_get_user_navigation_info($user, $this->page);
3282         $avatarclasses = "avatars";
3283         $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3284         $usertextcontents = $opts->metadata['userfullname'];
3286         // Other user.
3287         if (!empty($opts->metadata['asotheruser'])) {
3288             $avatarcontents .= html_writer::span(
3289                 $opts->metadata['realuseravatar'],
3290                 'avatar realuser'
3291             );
3292             $usertextcontents = $opts->metadata['realuserfullname'];
3293             $usertextcontents .= html_writer::tag(
3294                 'span',
3295                 get_string(
3296                     'loggedinas',
3297                     'moodle',
3298                     html_writer::span(
3299                         $opts->metadata['userfullname'],
3300                         'value'
3301                     )
3302                 ),
3303                 array('class' => 'meta viewingas')
3304             );
3305         }
3307         // Role.
3308         if (!empty($opts->metadata['asotherrole'])) {
3309             $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3310             $usertextcontents .= html_writer::span(
3311                 $opts->metadata['rolename'],
3312                 'meta role role-' . $role
3313             );
3314         }
3316         // User login failures.
3317         if (!empty($opts->metadata['userloginfail'])) {
3318             $usertextcontents .= html_writer::span(
3319                 $opts->metadata['userloginfail'],
3320                 'meta loginfailures'
3321             );
3322         }
3324         // MNet.
3325         if (!empty($opts->metadata['asmnetuser'])) {
3326             $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3327             $usertextcontents .= html_writer::span(
3328                 $opts->metadata['mnetidprovidername'],
3329                 'meta mnet mnet-' . $mnet
3330             );
3331         }
3333         $returnstr .= html_writer::span(
3334             html_writer::span($usertextcontents, 'usertext') .
3335             html_writer::span($avatarcontents, $avatarclasses),
3336             'userbutton'
3337         );
3339         // Create a divider (well, a filler).
3340         $divider = new action_menu_filler();
3341         $divider->primary = false;
3343         $am = new action_menu();
3344         $am->set_menu_trigger(
3345             $returnstr
3346         );
3347         $am->set_alignment(action_menu::TR, action_menu::BR);
3348         $am->set_nowrap_on_items();
3349         if ($withlinks) {
3350             $navitemcount = count($opts->navitems);
3351             $idx = 0;
3352             foreach ($opts->navitems as $key => $value) {
3354                 switch ($value->itemtype) {
3355                     case 'divider':
3356                         // If the nav item is a divider, add one and skip link processing.
3357                         $am->add($divider);
3358                         break;
3360                     case 'invalid':
3361                         // Silently skip invalid entries (should we post a notification?).
3362                         break;
3364                     case 'link':
3365                         // Process this as a link item.
3366                         $pix = null;
3367                         if (isset($value->pix) && !empty($value->pix)) {
3368                             $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3369                         } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3370                             $value->title = html_writer::img(
3371                                 $value->imgsrc,
3372                                 $value->title,
3373                                 array('class' => 'iconsmall')
3374                             ) . $value->title;
3375                         }
3377                         $al = new action_menu_link_secondary(
3378                             $value->url,
3379                             $pix,