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