Merge branch 'MDL-39488_m24' of git://github.com/rwijaya/moodle into MOODLE_24_STABLE
[moodle.git] / lib / outputrenderers.php
blob006bf9ab1d671cc861090242de93d468cc014451
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
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
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
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;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
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
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 $this->output = $page->get_renderer('core', null, $target);
203 parent::__construct($page, $target);
207 * Renders the provided widget and returns the HTML to display it.
209 * @param renderable $widget instance with renderable interface
210 * @return string
212 public function render(renderable $widget) {
213 $rendermethod = 'render_'.get_class($widget);
214 if (method_exists($this, $rendermethod)) {
215 return $this->$rendermethod($widget);
217 // pass to core renderer if method not found here
218 return $this->output->render($widget);
222 * Magic method used to pass calls otherwise meant for the standard renderer
223 * to it to ensure we don't go causing unnecessary grief.
225 * @param string $method
226 * @param array $arguments
227 * @return mixed
229 public function __call($method, $arguments) {
230 if (method_exists('renderer_base', $method)) {
231 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
233 if (method_exists($this->output, $method)) {
234 return call_user_func_array(array($this->output, $method), $arguments);
235 } else {
236 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
243 * The standard implementation of the core_renderer interface.
245 * @copyright 2009 Tim Hunt
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247 * @since Moodle 2.0
248 * @package core
249 * @category output
251 class core_renderer extends renderer_base {
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
255 * @deprecated
256 * @var string used in {@link core_renderer::header()}.
258 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
261 * @var string Used to pass information from {@link core_renderer::doctype()} to
262 * {@link core_renderer::standard_head_html()}.
264 protected $contenttype;
267 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
268 * with {@link core_renderer::header()}.
270 protected $metarefreshtag = '';
273 * @var string Unique token for the closing HTML
275 protected $unique_end_html_token;
278 * @var string Unique token for performance information
280 protected $unique_performance_info_token;
283 * @var string Unique token for the main content.
285 protected $unique_main_content_token;
288 * Constructor
290 * @param moodle_page $page the page we are doing output for.
291 * @param string $target one of rendering target constants
293 public function __construct(moodle_page $page, $target) {
294 $this->opencontainers = $page->opencontainers;
295 $this->page = $page;
296 $this->target = $target;
298 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
299 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
300 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
304 * Get the DOCTYPE declaration that should be used with this page. Designed to
305 * be called in theme layout.php files.
307 * @return string the DOCTYPE declaration that should be used.
309 public function doctype() {
310 if ($this->page->theme->doctype === 'html5') {
311 $this->contenttype = 'text/html; charset=utf-8';
312 return "<!DOCTYPE html>\n";
314 } else if ($this->page->theme->doctype === 'xhtml5') {
315 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
316 return "<!DOCTYPE html>\n";
318 } else {
319 // legacy xhtml 1.0
320 $this->contenttype = 'text/html; charset=utf-8';
321 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
326 * The attributes that should be added to the <html> tag. Designed to
327 * be called in theme layout.php files.
329 * @return string HTML fragment.
331 public function htmlattributes() {
332 $return = get_html_lang(true);
333 if ($this->page->theme->doctype !== 'html5') {
334 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
336 return $return;
340 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
341 * that should be included in the <head> tag. Designed to be called in theme
342 * layout.php files.
344 * @return string HTML fragment.
346 public function standard_head_html() {
347 global $CFG, $SESSION;
348 $output = '';
349 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
350 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
351 if (!$this->page->cacheable) {
352 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
353 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
355 // This is only set by the {@link redirect()} method
356 $output .= $this->metarefreshtag;
358 // Check if a periodic refresh delay has been set and make sure we arn't
359 // already meta refreshing
360 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
361 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
364 // flow player embedding support
365 $this->page->requires->js_function_call('M.util.load_flowplayer');
367 // Set up help link popups for all links with the helplinkpopup class
368 $this->page->requires->js_init_call('M.util.help_popups.setup');
370 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
372 $focus = $this->page->focuscontrol;
373 if (!empty($focus)) {
374 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
375 // This is a horrifically bad way to handle focus but it is passed in
376 // through messy formslib::moodleform
377 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
378 } else if (strpos($focus, '.')!==false) {
379 // Old style of focus, bad way to do it
380 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);
381 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
382 } else {
383 // Focus element with given id
384 $this->page->requires->js_function_call('focuscontrol', array($focus));
388 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
389 // any other custom CSS can not be overridden via themes and is highly discouraged
390 $urls = $this->page->theme->css_urls($this->page);
391 foreach ($urls as $url) {
392 $this->page->requires->css_theme($url);
395 // Get the theme javascript head and footer
396 $jsurl = $this->page->theme->javascript_url(true);
397 $this->page->requires->js($jsurl, true);
398 $jsurl = $this->page->theme->javascript_url(false);
399 $this->page->requires->js($jsurl);
401 // Get any HTML from the page_requirements_manager.
402 $output .= $this->page->requires->get_head_code($this->page, $this);
404 // List alternate versions.
405 foreach ($this->page->alternateversions as $type => $alt) {
406 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
407 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
410 if (!empty($CFG->additionalhtmlhead)) {
411 $output .= "\n".$CFG->additionalhtmlhead;
414 return $output;
418 * The standard tags (typically skip links) that should be output just inside
419 * the start of the <body> tag. Designed to be called in theme layout.php files.
421 * @return string HTML fragment.
423 public function standard_top_of_body_html() {
424 global $CFG;
425 $output = $this->page->requires->get_top_of_body_code();
426 if (!empty($CFG->additionalhtmltopofbody)) {
427 $output .= "\n".$CFG->additionalhtmltopofbody;
429 return $output;
433 * The standard tags (typically performance information and validation links,
434 * if we are in developer debug mode) that should be output in the footer area
435 * of the page. Designed to be called in theme layout.php files.
437 * @return string HTML fragment.
439 public function standard_footer_html() {
440 global $CFG, $SCRIPT;
442 // This function is normally called from a layout.php file in {@link core_renderer::header()}
443 // but some of the content won't be known until later, so we return a placeholder
444 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
445 $output = $this->unique_performance_info_token;
446 if ($this->page->devicetypeinuse == 'legacy') {
447 // The legacy theme is in use print the notification
448 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
451 // Get links to switch device types (only shown for users not on a default device)
452 $output .= $this->theme_switch_links();
454 if (!empty($CFG->debugpageinfo)) {
455 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
457 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
458 // Add link to profiling report if necessary
459 if (function_exists('profiling_is_running') && profiling_is_running()) {
460 $txt = get_string('profiledscript', 'admin');
461 $title = get_string('profiledscriptview', 'admin');
462 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
463 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
464 $output .= '<div class="profilingfooter">' . $link . '</div>';
466 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
468 if (!empty($CFG->debugvalidators)) {
469 // 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
470 $output .= '<div class="validators"><ul>
471 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
472 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
473 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
474 </ul></div>';
476 if (!empty($CFG->additionalhtmlfooter)) {
477 $output .= "\n".$CFG->additionalhtmlfooter;
479 return $output;
483 * Returns standard main content placeholder.
484 * Designed to be called in theme layout.php files.
486 * @return string HTML fragment.
488 public function main_content() {
489 // This is here because it is the only place we can inject the "main" role over the entire main content area
490 // without requiring all theme's to manually do it, and without creating yet another thing people need to
491 // remember in the theme.
492 // This is an unfortunate hack. DO NO EVER add anything more here.
493 // DO NOT add classes.
494 // DO NOT add an id.
495 return '<div role="main">'.$this->unique_main_content_token.'</div>';
499 * The standard tags (typically script tags that are not needed earlier) that
500 * should be output after everything else, . Designed to be called in theme layout.php files.
502 * @return string HTML fragment.
504 public function standard_end_of_body_html() {
505 // This function is normally called from a layout.php file in {@link core_renderer::header()}
506 // but some of the content won't be known until later, so we return a placeholder
507 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
508 return $this->unique_end_html_token;
512 * Return the standard string that says whether you are logged in (and switched
513 * roles/logged in as another user).
514 * @param bool $withlinks if false, then don't include any links in the HTML produced.
515 * If not set, the default is the nologinlinks option from the theme config.php file,
516 * and if that is not set, then links are included.
517 * @return string HTML fragment.
519 public function login_info($withlinks = null) {
520 global $USER, $CFG, $DB, $SESSION;
522 if (during_initial_install()) {
523 return '';
526 if (is_null($withlinks)) {
527 $withlinks = empty($this->page->layout_options['nologinlinks']);
530 $loginpage = ((string)$this->page->url === get_login_url());
531 $course = $this->page->course;
532 if (session_is_loggedinas()) {
533 $realuser = session_get_realuser();
534 $fullname = fullname($realuser, true);
535 if ($withlinks) {
536 $loginastitle = get_string('loginas');
537 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
538 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
539 } else {
540 $realuserinfo = " [$fullname] ";
542 } else {
543 $realuserinfo = '';
546 $loginurl = get_login_url();
548 if (empty($course->id)) {
549 // $course->id is not defined during installation
550 return '';
551 } else if (isloggedin()) {
552 $context = context_course::instance($course->id);
554 $fullname = fullname($USER, true);
555 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
556 if ($withlinks) {
557 $linktitle = get_string('viewprofile');
558 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
559 } else {
560 $username = $fullname;
562 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
563 if ($withlinks) {
564 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
565 } else {
566 $username .= " from {$idprovider->name}";
569 if (isguestuser()) {
570 $loggedinas = $realuserinfo.get_string('loggedinasguest');
571 if (!$loginpage && $withlinks) {
572 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
574 } else if (is_role_switched($course->id)) { // Has switched roles
575 $rolename = '';
576 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
577 $rolename = ': '.role_get_name($role, $context);
579 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
580 if ($withlinks) {
581 $loggedinas .= " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
583 } else {
584 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
585 if ($withlinks) {
586 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
589 } else {
590 $loggedinas = get_string('loggedinnot', 'moodle');
591 if (!$loginpage && $withlinks) {
592 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
596 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
598 if (isset($SESSION->justloggedin)) {
599 unset($SESSION->justloggedin);
600 if (!empty($CFG->displayloginfailures)) {
601 if (!isguestuser()) {
602 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
603 $loggedinas .= '&nbsp;<div class="loginfailures">';
604 if (empty($count->accounts)) {
605 $loggedinas .= get_string('failedloginattempts', '', $count);
606 } else {
607 $loggedinas .= get_string('failedloginattemptsall', '', $count);
609 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
610 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
611 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
613 $loggedinas .= '</div>';
619 return $loggedinas;
623 * Return the 'back' link that normally appears in the footer.
625 * @return string HTML fragment.
627 public function home_link() {
628 global $CFG, $SITE;
630 if ($this->page->pagetype == 'site-index') {
631 // Special case for site home page - please do not remove
632 return '<div class="sitelink">' .
633 '<a title="Moodle" href="http://moodle.org/">' .
634 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
636 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
637 // Special case for during install/upgrade.
638 return '<div class="sitelink">'.
639 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
640 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
642 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
643 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
644 get_string('home') . '</a></div>';
646 } else {
647 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
648 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
653 * Redirects the user by any means possible given the current state
655 * This function should not be called directly, it should always be called using
656 * the redirect function in lib/weblib.php
658 * The redirect function should really only be called before page output has started
659 * however it will allow itself to be called during the state STATE_IN_BODY
661 * @param string $encodedurl The URL to send to encoded if required
662 * @param string $message The message to display to the user if any
663 * @param int $delay The delay before redirecting a user, if $message has been
664 * set this is a requirement and defaults to 3, set to 0 no delay
665 * @param boolean $debugdisableredirect this redirect has been disabled for
666 * debugging purposes. Display a message that explains, and don't
667 * trigger the redirect.
668 * @return string The HTML to display to the user before dying, may contain
669 * meta refresh, javascript refresh, and may have set header redirects
671 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
672 global $CFG;
673 $url = str_replace('&amp;', '&', $encodedurl);
675 switch ($this->page->state) {
676 case moodle_page::STATE_BEFORE_HEADER :
677 // No output yet it is safe to delivery the full arsenal of redirect methods
678 if (!$debugdisableredirect) {
679 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
680 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
681 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
683 $output = $this->header();
684 break;
685 case moodle_page::STATE_PRINTING_HEADER :
686 // We should hopefully never get here
687 throw new coding_exception('You cannot redirect while printing the page header');
688 break;
689 case moodle_page::STATE_IN_BODY :
690 // We really shouldn't be here but we can deal with this
691 debugging("You should really redirect before you start page output");
692 if (!$debugdisableredirect) {
693 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
695 $output = $this->opencontainers->pop_all_but_last();
696 break;
697 case moodle_page::STATE_DONE :
698 // Too late to be calling redirect now
699 throw new coding_exception('You cannot redirect after the entire page has been generated');
700 break;
702 $output .= $this->notification($message, 'redirectmessage');
703 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
704 if ($debugdisableredirect) {
705 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
707 $output .= $this->footer();
708 return $output;
712 * Start output by sending the HTTP headers, and printing the HTML <head>
713 * and the start of the <body>.
715 * To control what is printed, you should set properties on $PAGE. If you
716 * are familiar with the old {@link print_header()} function from Moodle 1.9
717 * you will find that there are properties on $PAGE that correspond to most
718 * of the old parameters to could be passed to print_header.
720 * Not that, in due course, the remaining $navigation, $menu parameters here
721 * will be replaced by more properties of $PAGE, but that is still to do.
723 * @return string HTML that you must output this, preferably immediately.
725 public function header() {
726 global $USER, $CFG;
728 if (session_is_loggedinas()) {
729 $this->page->add_body_class('userloggedinas');
732 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
734 // Find the appropriate page layout file, based on $this->page->pagelayout.
735 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
736 // Render the layout using the layout file.
737 $rendered = $this->render_page_layout($layoutfile);
739 // Slice the rendered output into header and footer.
740 $cutpos = strpos($rendered, $this->unique_main_content_token);
741 if ($cutpos === false) {
742 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
743 $token = self::MAIN_CONTENT_TOKEN;
744 } else {
745 $token = $this->unique_main_content_token;
748 if ($cutpos === false) {
749 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.');
751 $header = substr($rendered, 0, $cutpos);
752 $footer = substr($rendered, $cutpos + strlen($token));
754 if (empty($this->contenttype)) {
755 debugging('The page layout file did not call $OUTPUT->doctype()');
756 $header = $this->doctype() . $header;
759 // If this theme version is below 2.4 release and this is a course view page
760 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
761 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
762 // check if course content header/footer have not been output during render of theme layout
763 $coursecontentheader = $this->course_content_header(true);
764 $coursecontentfooter = $this->course_content_footer(true);
765 if (!empty($coursecontentheader)) {
766 // display debug message and add header and footer right above and below main content
767 // Please note that course header and footer (to be displayed above and below the whole page)
768 // are not displayed in this case at all.
769 // Besides the content header and footer are not displayed on any other course page
770 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);
771 $header .= $coursecontentheader;
772 $footer = $coursecontentfooter. $footer;
776 send_headers($this->contenttype, $this->page->cacheable);
778 $this->opencontainers->push('header/footer', $footer);
779 $this->page->set_state(moodle_page::STATE_IN_BODY);
781 return $header . $this->skip_link_target('maincontent');
785 * Renders and outputs the page layout file.
787 * This is done by preparing the normal globals available to a script, and
788 * then including the layout file provided by the current theme for the
789 * requested layout.
791 * @param string $layoutfile The name of the layout file
792 * @return string HTML code
794 protected function render_page_layout($layoutfile) {
795 global $CFG, $SITE, $USER;
796 // The next lines are a bit tricky. The point is, here we are in a method
797 // of a renderer class, and this object may, or may not, be the same as
798 // the global $OUTPUT object. When rendering the page layout file, we want to use
799 // this object. However, people writing Moodle code expect the current
800 // renderer to be called $OUTPUT, not $this, so define a variable called
801 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
802 $OUTPUT = $this;
803 $PAGE = $this->page;
804 $COURSE = $this->page->course;
806 ob_start();
807 include($layoutfile);
808 $rendered = ob_get_contents();
809 ob_end_clean();
810 return $rendered;
814 * Outputs the page's footer
816 * @return string HTML fragment
818 public function footer() {
819 global $CFG, $DB;
821 $output = $this->container_end_all(true);
823 $footer = $this->opencontainers->pop('header/footer');
825 if (debugging() and $DB and $DB->is_transaction_started()) {
826 // TODO: MDL-20625 print warning - transaction will be rolled back
829 // Provide some performance info if required
830 $performanceinfo = '';
831 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
832 $perf = get_performance_info();
833 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
834 error_log("PERF: " . $perf['txt']);
836 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
837 $performanceinfo = $perf['html'];
840 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
842 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
844 $this->page->set_state(moodle_page::STATE_DONE);
846 return $output . $footer;
850 * Close all but the last open container. This is useful in places like error
851 * handling, where you want to close all the open containers (apart from <body>)
852 * before outputting the error message.
854 * @param bool $shouldbenone assert that the stack should be empty now - causes a
855 * developer debug warning if it isn't.
856 * @return string the HTML required to close any open containers inside <body>.
858 public function container_end_all($shouldbenone = false) {
859 return $this->opencontainers->pop_all_but_last($shouldbenone);
863 * Returns course-specific information to be output immediately above content on any course page
864 * (for the current course)
866 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
867 * @return string
869 public function course_content_header($onlyifnotcalledbefore = false) {
870 global $CFG;
871 if ($this->page->course->id == SITEID) {
872 // return immediately and do not include /course/lib.php if not necessary
873 return '';
875 static $functioncalled = false;
876 if ($functioncalled && $onlyifnotcalledbefore) {
877 // we have already output the content header
878 return '';
880 require_once($CFG->dirroot.'/course/lib.php');
881 $functioncalled = true;
882 $courseformat = course_get_format($this->page->course);
883 if (($obj = $courseformat->course_content_header()) !== null) {
884 return $courseformat->get_renderer($this->page)->render($obj);
886 return '';
890 * Returns course-specific information to be output immediately below content on any course page
891 * (for the current course)
893 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
894 * @return string
896 public function course_content_footer($onlyifnotcalledbefore = false) {
897 global $CFG;
898 if ($this->page->course->id == SITEID) {
899 // return immediately and do not include /course/lib.php if not necessary
900 return '';
902 static $functioncalled = false;
903 if ($functioncalled && $onlyifnotcalledbefore) {
904 // we have already output the content footer
905 return '';
907 $functioncalled = true;
908 require_once($CFG->dirroot.'/course/lib.php');
909 $courseformat = course_get_format($this->page->course);
910 if (($obj = $courseformat->course_content_footer()) !== null) {
911 return $courseformat->get_renderer($this->page)->render($obj);
913 return '';
917 * Returns course-specific information to be output on any course page in the header area
918 * (for the current course)
920 * @return string
922 public function course_header() {
923 global $CFG;
924 if ($this->page->course->id == SITEID) {
925 // return immediately and do not include /course/lib.php if not necessary
926 return '';
928 require_once($CFG->dirroot.'/course/lib.php');
929 $courseformat = course_get_format($this->page->course);
930 if (($obj = $courseformat->course_header()) !== null) {
931 return $courseformat->get_renderer($this->page)->render($obj);
933 return '';
937 * Returns course-specific information to be output on any course page in the footer area
938 * (for the current course)
940 * @return string
942 public function course_footer() {
943 global $CFG;
944 if ($this->page->course->id == SITEID) {
945 // return immediately and do not include /course/lib.php if not necessary
946 return '';
948 require_once($CFG->dirroot.'/course/lib.php');
949 $courseformat = course_get_format($this->page->course);
950 if (($obj = $courseformat->course_footer()) !== null) {
951 return $courseformat->get_renderer($this->page)->render($obj);
953 return '';
957 * Returns lang menu or '', this method also checks forcing of languages in courses.
959 * @return string The lang menu HTML or empty string
961 public function lang_menu() {
962 global $CFG;
964 if (empty($CFG->langmenu)) {
965 return '';
968 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
969 // do not show lang menu if language forced
970 return '';
973 $currlang = current_language();
974 $langs = get_string_manager()->get_list_of_translations();
976 if (count($langs) < 2) {
977 return '';
980 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
981 $s->label = get_accesshide(get_string('language'));
982 $s->class = 'langmenu';
983 return $this->render($s);
987 * Output the row of editing icons for a block, as defined by the controls array.
989 * @param array $controls an array like {@link block_contents::$controls}.
990 * @return string HTML fragment.
992 public function block_controls($controls) {
993 if (empty($controls)) {
994 return '';
996 $controlshtml = array();
997 foreach ($controls as $control) {
998 $controlshtml[] = html_writer::tag('a',
999 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
1000 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
1002 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
1006 * Prints a nice side block with an optional header.
1008 * The content is described
1009 * by a {@link core_renderer::block_contents} object.
1011 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1012 * <div class="header"></div>
1013 * <div class="content">
1014 * ...CONTENT...
1015 * <div class="footer">
1016 * </div>
1017 * </div>
1018 * <div class="annotation">
1019 * </div>
1020 * </div>
1022 * @param block_contents $bc HTML for the content
1023 * @param string $region the region the block is appearing in.
1024 * @return string the HTML to be output.
1026 public function block(block_contents $bc, $region) {
1027 $bc = clone($bc); // Avoid messing up the object passed in.
1028 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1029 $bc->collapsible = block_contents::NOT_HIDEABLE;
1031 $skiptitle = strip_tags($bc->title);
1032 if ($bc->blockinstanceid && !empty($skiptitle)) {
1033 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1034 } else if (!empty($bc->arialabel)) {
1035 $bc->attributes['aria-label'] = $bc->arialabel;
1037 if ($bc->collapsible == block_contents::HIDDEN) {
1038 $bc->add_class('hidden');
1040 if (!empty($bc->controls)) {
1041 $bc->add_class('block_with_controls');
1045 if (empty($skiptitle)) {
1046 $output = '';
1047 $skipdest = '';
1048 } else {
1049 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1050 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1053 $output .= html_writer::start_tag('div', $bc->attributes);
1055 $output .= $this->block_header($bc);
1056 $output .= $this->block_content($bc);
1058 $output .= html_writer::end_tag('div');
1060 $output .= $this->block_annotation($bc);
1062 $output .= $skipdest;
1064 $this->init_block_hider_js($bc);
1065 return $output;
1069 * Produces a header for a block
1071 * @param block_contents $bc
1072 * @return string
1074 protected function block_header(block_contents $bc) {
1076 $title = '';
1077 if ($bc->title) {
1078 $attributes = array();
1079 if ($bc->blockinstanceid) {
1080 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1082 $title = html_writer::tag('h2', $bc->title, $attributes);
1085 $controlshtml = $this->block_controls($bc->controls);
1087 $output = '';
1088 if ($title || $controlshtml) {
1089 $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'));
1091 return $output;
1095 * Produces the content area for a block
1097 * @param block_contents $bc
1098 * @return string
1100 protected function block_content(block_contents $bc) {
1101 $output = html_writer::start_tag('div', array('class' => 'content'));
1102 if (!$bc->title && !$this->block_controls($bc->controls)) {
1103 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1105 $output .= $bc->content;
1106 $output .= $this->block_footer($bc);
1107 $output .= html_writer::end_tag('div');
1109 return $output;
1113 * Produces the footer for a block
1115 * @param block_contents $bc
1116 * @return string
1118 protected function block_footer(block_contents $bc) {
1119 $output = '';
1120 if ($bc->footer) {
1121 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1123 return $output;
1127 * Produces the annotation for a block
1129 * @param block_contents $bc
1130 * @return string
1132 protected function block_annotation(block_contents $bc) {
1133 $output = '';
1134 if ($bc->annotation) {
1135 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1137 return $output;
1141 * Calls the JS require function to hide a block.
1143 * @param block_contents $bc A block_contents object
1145 protected function init_block_hider_js(block_contents $bc) {
1146 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1147 $config = new stdClass;
1148 $config->id = $bc->attributes['id'];
1149 $config->title = strip_tags($bc->title);
1150 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1151 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1152 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1154 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1155 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1160 * Render the contents of a block_list.
1162 * @param array $icons the icon for each item.
1163 * @param array $items the content of each item.
1164 * @return string HTML
1166 public function list_block_contents($icons, $items) {
1167 $row = 0;
1168 $lis = array();
1169 foreach ($items as $key => $string) {
1170 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1171 if (!empty($icons[$key])) { //test if the content has an assigned icon
1172 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1174 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1175 $item .= html_writer::end_tag('li');
1176 $lis[] = $item;
1177 $row = 1 - $row; // Flip even/odd.
1179 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1183 * Output all the blocks in a particular region.
1185 * @param string $region the name of a region on this page.
1186 * @return string the HTML to be output.
1188 public function blocks_for_region($region) {
1189 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1191 $output = '';
1192 foreach ($blockcontents as $bc) {
1193 if ($bc instanceof block_contents) {
1194 $output .= $this->block($bc, $region);
1195 } else if ($bc instanceof block_move_target) {
1196 $output .= $this->block_move_target($bc);
1197 } else {
1198 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1201 return $output;
1205 * Output a place where the block that is currently being moved can be dropped.
1207 * @param block_move_target $target with the necessary details.
1208 * @return string the HTML to be output.
1210 public function block_move_target($target) {
1211 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1215 * Renders a special html link with attached action
1217 * @param string|moodle_url $url
1218 * @param string $text HTML fragment
1219 * @param component_action $action
1220 * @param array $attributes associative array of html link attributes + disabled
1221 * @return string HTML fragment
1223 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1224 if (!($url instanceof moodle_url)) {
1225 $url = new moodle_url($url);
1227 $link = new action_link($url, $text, $action, $attributes);
1229 return $this->render($link);
1233 * Renders an action_link object.
1235 * The provided link is renderer and the HTML returned. At the same time the
1236 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1238 * @param action_link $link
1239 * @return string HTML fragment
1241 protected function render_action_link(action_link $link) {
1242 global $CFG;
1244 if ($link->text instanceof renderable) {
1245 $text = $this->render($link->text);
1246 } else {
1247 $text = $link->text;
1250 // A disabled link is rendered as formatted text
1251 if (!empty($link->attributes['disabled'])) {
1252 // do not use div here due to nesting restriction in xhtml strict
1253 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1256 $attributes = $link->attributes;
1257 unset($link->attributes['disabled']);
1258 $attributes['href'] = $link->url;
1260 if ($link->actions) {
1261 if (empty($attributes['id'])) {
1262 $id = html_writer::random_id('action_link');
1263 $attributes['id'] = $id;
1264 } else {
1265 $id = $attributes['id'];
1267 foreach ($link->actions as $action) {
1268 $this->add_action_handler($action, $id);
1272 return html_writer::tag('a', $text, $attributes);
1277 * Renders an action_icon.
1279 * This function uses the {@link core_renderer::action_link()} method for the
1280 * most part. What it does different is prepare the icon as HTML and use it
1281 * as the link text.
1283 * @param string|moodle_url $url A string URL or moodel_url
1284 * @param pix_icon $pixicon
1285 * @param component_action $action
1286 * @param array $attributes associative array of html link attributes + disabled
1287 * @param bool $linktext show title next to image in link
1288 * @return string HTML fragment
1290 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1291 if (!($url instanceof moodle_url)) {
1292 $url = new moodle_url($url);
1294 $attributes = (array)$attributes;
1296 if (empty($attributes['class'])) {
1297 // let ppl override the class via $options
1298 $attributes['class'] = 'action-icon';
1301 $icon = $this->render($pixicon);
1303 if ($linktext) {
1304 $text = $pixicon->attributes['alt'];
1305 } else {
1306 $text = '';
1309 return $this->action_link($url, $text.$icon, $action, $attributes);
1313 * Print a message along with button choices for Continue/Cancel
1315 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1317 * @param string $message The question to ask the user
1318 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1319 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1320 * @return string HTML fragment
1322 public function confirm($message, $continue, $cancel) {
1323 if ($continue instanceof single_button) {
1324 // ok
1325 } else if (is_string($continue)) {
1326 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1327 } else if ($continue instanceof moodle_url) {
1328 $continue = new single_button($continue, get_string('continue'), 'post');
1329 } else {
1330 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1333 if ($cancel instanceof single_button) {
1334 // ok
1335 } else if (is_string($cancel)) {
1336 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1337 } else if ($cancel instanceof moodle_url) {
1338 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1339 } else {
1340 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1343 $output = $this->box_start('generalbox', 'notice');
1344 $output .= html_writer::tag('p', $message);
1345 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1346 $output .= $this->box_end();
1347 return $output;
1351 * Returns a form with a single button.
1353 * @param string|moodle_url $url
1354 * @param string $label button text
1355 * @param string $method get or post submit method
1356 * @param array $options associative array {disabled, title, etc.}
1357 * @return string HTML fragment
1359 public function single_button($url, $label, $method='post', array $options=null) {
1360 if (!($url instanceof moodle_url)) {
1361 $url = new moodle_url($url);
1363 $button = new single_button($url, $label, $method);
1365 foreach ((array)$options as $key=>$value) {
1366 if (array_key_exists($key, $button)) {
1367 $button->$key = $value;
1371 return $this->render($button);
1375 * Renders a single button widget.
1377 * This will return HTML to display a form containing a single button.
1379 * @param single_button $button
1380 * @return string HTML fragment
1382 protected function render_single_button(single_button $button) {
1383 $attributes = array('type' => 'submit',
1384 'value' => $button->label,
1385 'disabled' => $button->disabled ? 'disabled' : null,
1386 'title' => $button->tooltip);
1388 if ($button->actions) {
1389 $id = html_writer::random_id('single_button');
1390 $attributes['id'] = $id;
1391 foreach ($button->actions as $action) {
1392 $this->add_action_handler($action, $id);
1396 // first the input element
1397 $output = html_writer::empty_tag('input', $attributes);
1399 // then hidden fields
1400 $params = $button->url->params();
1401 if ($button->method === 'post') {
1402 $params['sesskey'] = sesskey();
1404 foreach ($params as $var => $val) {
1405 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1408 // then div wrapper for xhtml strictness
1409 $output = html_writer::tag('div', $output);
1411 // now the form itself around it
1412 if ($button->method === 'get') {
1413 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1414 } else {
1415 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1417 if ($url === '') {
1418 $url = '#'; // there has to be always some action
1420 $attributes = array('method' => $button->method,
1421 'action' => $url,
1422 'id' => $button->formid);
1423 $output = html_writer::tag('form', $output, $attributes);
1425 // and finally one more wrapper with class
1426 return html_writer::tag('div', $output, array('class' => $button->class));
1430 * Returns a form with a single select widget.
1432 * @param moodle_url $url form action target, includes hidden fields
1433 * @param string $name name of selection field - the changing parameter in url
1434 * @param array $options list of options
1435 * @param string $selected selected element
1436 * @param array $nothing
1437 * @param string $formid
1438 * @return string HTML fragment
1440 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1441 if (!($url instanceof moodle_url)) {
1442 $url = new moodle_url($url);
1444 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1446 return $this->render($select);
1450 * Internal implementation of single_select rendering
1452 * @param single_select $select
1453 * @return string HTML fragment
1455 protected function render_single_select(single_select $select) {
1456 $select = clone($select);
1457 if (empty($select->formid)) {
1458 $select->formid = html_writer::random_id('single_select_f');
1461 $output = '';
1462 $params = $select->url->params();
1463 if ($select->method === 'post') {
1464 $params['sesskey'] = sesskey();
1466 foreach ($params as $name=>$value) {
1467 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1470 if (empty($select->attributes['id'])) {
1471 $select->attributes['id'] = html_writer::random_id('single_select');
1474 if ($select->disabled) {
1475 $select->attributes['disabled'] = 'disabled';
1478 if ($select->tooltip) {
1479 $select->attributes['title'] = $select->tooltip;
1482 $select->attributes['class'] = 'autosubmit';
1483 if ($select->class) {
1484 $select->attributes['class'] .= ' ' . $select->class;
1487 if ($select->label) {
1488 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1491 if ($select->helpicon instanceof help_icon) {
1492 $output .= $this->render($select->helpicon);
1493 } else if ($select->helpicon instanceof old_help_icon) {
1494 $output .= $this->render($select->helpicon);
1496 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1498 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1499 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1501 $nothing = empty($select->nothing) ? false : key($select->nothing);
1502 $this->page->requires->yui_module('moodle-core-formautosubmit',
1503 'M.core.init_formautosubmit',
1504 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1507 // then div wrapper for xhtml strictness
1508 $output = html_writer::tag('div', $output);
1510 // now the form itself around it
1511 if ($select->method === 'get') {
1512 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1513 } else {
1514 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1516 $formattributes = array('method' => $select->method,
1517 'action' => $url,
1518 'id' => $select->formid);
1519 $output = html_writer::tag('form', $output, $formattributes);
1521 // and finally one more wrapper with class
1522 return html_writer::tag('div', $output, array('class' => $select->class));
1526 * Returns a form with a url select widget.
1528 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1529 * @param string $selected selected element
1530 * @param array $nothing
1531 * @param string $formid
1532 * @return string HTML fragment
1534 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1535 $select = new url_select($urls, $selected, $nothing, $formid);
1536 return $this->render($select);
1540 * Internal implementation of url_select rendering
1542 * @param url_select $select
1543 * @return string HTML fragment
1545 protected function render_url_select(url_select $select) {
1546 global $CFG;
1548 $select = clone($select);
1549 if (empty($select->formid)) {
1550 $select->formid = html_writer::random_id('url_select_f');
1553 if (empty($select->attributes['id'])) {
1554 $select->attributes['id'] = html_writer::random_id('url_select');
1557 if ($select->disabled) {
1558 $select->attributes['disabled'] = 'disabled';
1561 if ($select->tooltip) {
1562 $select->attributes['title'] = $select->tooltip;
1565 $output = '';
1567 if ($select->label) {
1568 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1571 $classes = array();
1572 if (!$select->showbutton) {
1573 $classes[] = 'autosubmit';
1575 if ($select->class) {
1576 $classes[] = $select->class;
1578 if (count($classes)) {
1579 $select->attributes['class'] = implode(' ', $classes);
1582 if ($select->helpicon instanceof help_icon) {
1583 $output .= $this->render($select->helpicon);
1584 } else if ($select->helpicon instanceof old_help_icon) {
1585 $output .= $this->render($select->helpicon);
1588 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1589 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1590 $urls = array();
1591 foreach ($select->urls as $k=>$v) {
1592 if (is_array($v)) {
1593 // optgroup structure
1594 foreach ($v as $optgrouptitle => $optgroupoptions) {
1595 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1596 if (empty($optionurl)) {
1597 $safeoptionurl = '';
1598 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1599 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1600 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1601 } else if (strpos($optionurl, '/') !== 0) {
1602 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1603 continue;
1604 } else {
1605 $safeoptionurl = $optionurl;
1607 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1610 } else {
1611 // plain list structure
1612 if (empty($k)) {
1613 // nothing selected option
1614 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1615 $k = str_replace($CFG->wwwroot, '', $k);
1616 } else if (strpos($k, '/') !== 0) {
1617 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1618 continue;
1620 $urls[$k] = $v;
1623 $selected = $select->selected;
1624 if (!empty($selected)) {
1625 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1626 $selected = str_replace($CFG->wwwroot, '', $selected);
1627 } else if (strpos($selected, '/') !== 0) {
1628 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1632 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1633 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1635 if (!$select->showbutton) {
1636 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1637 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1638 $nothing = empty($select->nothing) ? false : key($select->nothing);
1639 $this->page->requires->yui_module('moodle-core-formautosubmit',
1640 'M.core.init_formautosubmit',
1641 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1643 } else {
1644 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1647 // then div wrapper for xhtml strictness
1648 $output = html_writer::tag('div', $output);
1650 // now the form itself around it
1651 $formattributes = array('method' => 'post',
1652 'action' => new moodle_url('/course/jumpto.php'),
1653 'id' => $select->formid);
1654 $output = html_writer::tag('form', $output, $formattributes);
1656 // and finally one more wrapper with class
1657 return html_writer::tag('div', $output, array('class' => $select->class));
1661 * Returns a string containing a link to the user documentation.
1662 * Also contains an icon by default. Shown to teachers and admin only.
1664 * @param string $path The page link after doc root and language, no leading slash.
1665 * @param string $text The text to be displayed for the link
1666 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1667 * @return string
1669 public function doc_link($path, $text = '', $forcepopup = false) {
1670 global $CFG;
1672 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1674 $url = new moodle_url(get_docs_url($path));
1676 $attributes = array('href'=>$url);
1677 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1678 $attributes['class'] = 'helplinkpopup';
1681 return html_writer::tag('a', $icon.$text, $attributes);
1685 * Return HTML for a pix_icon.
1687 * @param string $pix short pix name
1688 * @param string $alt mandatory alt attribute
1689 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1690 * @param array $attributes htm lattributes
1691 * @return string HTML fragment
1693 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1694 $icon = new pix_icon($pix, $alt, $component, $attributes);
1695 return $this->render($icon);
1699 * Renders a pix_icon widget and returns the HTML to display it.
1701 * @param pix_icon $icon
1702 * @return string HTML fragment
1704 protected function render_pix_icon(pix_icon $icon) {
1705 $attributes = $icon->attributes;
1706 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1707 return html_writer::empty_tag('img', $attributes);
1711 * Return HTML to display an emoticon icon.
1713 * @param pix_emoticon $emoticon
1714 * @return string HTML fragment
1716 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1717 $attributes = $emoticon->attributes;
1718 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1719 return html_writer::empty_tag('img', $attributes);
1723 * Produces the html that represents this rating in the UI
1725 * @param rating $rating the page object on which this rating will appear
1726 * @return string
1728 function render_rating(rating $rating) {
1729 global $CFG, $USER;
1731 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1732 return null;//ratings are turned off
1735 $ratingmanager = new rating_manager();
1736 // Initialise the JavaScript so ratings can be done by AJAX.
1737 $ratingmanager->initialise_rating_javascript($this->page);
1739 $strrate = get_string("rate", "rating");
1740 $ratinghtml = ''; //the string we'll return
1742 // permissions check - can they view the aggregate?
1743 if ($rating->user_can_view_aggregate()) {
1745 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1746 $aggregatestr = $rating->get_aggregate_string();
1748 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1749 if ($rating->count > 0) {
1750 $countstr = "({$rating->count})";
1751 } else {
1752 $countstr = '-';
1754 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1756 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1757 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1759 $nonpopuplink = $rating->get_view_ratings_url();
1760 $popuplink = $rating->get_view_ratings_url(true);
1762 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1763 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1764 } else {
1765 $ratinghtml .= $aggregatehtml;
1769 $formstart = null;
1770 // if the item doesn't belong to the current user, the user has permission to rate
1771 // and we're within the assessable period
1772 if ($rating->user_can_rate()) {
1774 $rateurl = $rating->get_rate_url();
1775 $inputs = $rateurl->params();
1777 //start the rating form
1778 $formattrs = array(
1779 'id' => "postrating{$rating->itemid}",
1780 'class' => 'postratingform',
1781 'method' => 'post',
1782 'action' => $rateurl->out_omit_querystring()
1784 $formstart = html_writer::start_tag('form', $formattrs);
1785 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1787 // add the hidden inputs
1788 foreach ($inputs as $name => $value) {
1789 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1790 $formstart .= html_writer::empty_tag('input', $attributes);
1793 if (empty($ratinghtml)) {
1794 $ratinghtml .= $strrate.': ';
1796 $ratinghtml = $formstart.$ratinghtml;
1798 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1799 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1800 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
1801 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1803 //output submit button
1804 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1806 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1807 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1809 if (!$rating->settings->scale->isnumeric) {
1810 // If a global scale, try to find current course ID from the context
1811 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
1812 $courseid = $coursecontext->instanceid;
1813 } else {
1814 $courseid = $rating->settings->scale->courseid;
1816 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
1818 $ratinghtml .= html_writer::end_tag('span');
1819 $ratinghtml .= html_writer::end_tag('div');
1820 $ratinghtml .= html_writer::end_tag('form');
1823 return $ratinghtml;
1827 * Centered heading with attached help button (same title text)
1828 * and optional icon attached.
1830 * @param string $text A heading text
1831 * @param string $helpidentifier The keyword that defines a help page
1832 * @param string $component component name
1833 * @param string|moodle_url $icon
1834 * @param string $iconalt icon alt text
1835 * @return string HTML fragment
1837 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1838 $image = '';
1839 if ($icon) {
1840 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1843 $help = '';
1844 if ($helpidentifier) {
1845 $help = $this->help_icon($helpidentifier, $component);
1848 return $this->heading($image.$text.$help, 2, 'main help');
1852 * Returns HTML to display a help icon.
1854 * @deprecated since Moodle 2.0
1855 * @param string $helpidentifier The keyword that defines a help page
1856 * @param string $title A descriptive text for accessibility only
1857 * @param string $component component name
1858 * @param string|bool $linktext true means use $title as link text, string means link text value
1859 * @return string HTML fragment
1861 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1862 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1863 $icon = new old_help_icon($helpidentifier, $title, $component);
1864 if ($linktext === true) {
1865 $icon->linktext = $title;
1866 } else if (!empty($linktext)) {
1867 $icon->linktext = $linktext;
1869 return $this->render($icon);
1873 * Implementation of user image rendering.
1875 * @param old_help_icon $helpicon A help icon instance
1876 * @return string HTML fragment
1878 protected function render_old_help_icon(old_help_icon $helpicon) {
1879 global $CFG;
1881 // first get the help image icon
1882 $src = $this->pix_url('help');
1884 if (empty($helpicon->linktext)) {
1885 $alt = $helpicon->title;
1886 } else {
1887 $alt = get_string('helpwiththis');
1890 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1891 $output = html_writer::empty_tag('img', $attributes);
1893 // add the link text if given
1894 if (!empty($helpicon->linktext)) {
1895 // the spacing has to be done through CSS
1896 $output .= $helpicon->linktext;
1899 // now create the link around it - we need https on loginhttps pages
1900 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1902 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1903 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1905 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true');
1906 $id = html_writer::random_id('helpicon');
1907 $attributes['id'] = $id;
1908 $output = html_writer::tag('a', $output, $attributes);
1910 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1911 $this->page->requires->string_for_js('close', 'form');
1913 // and finally span
1914 return html_writer::tag('span', $output, array('class' => 'helplink'));
1918 * Returns HTML to display a help icon.
1920 * @param string $identifier The keyword that defines a help page
1921 * @param string $component component name
1922 * @param string|bool $linktext true means use $title as link text, string means link text value
1923 * @return string HTML fragment
1925 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1926 $icon = new help_icon($identifier, $component);
1927 $icon->diag_strings();
1928 if ($linktext === true) {
1929 $icon->linktext = get_string($icon->identifier, $icon->component);
1930 } else if (!empty($linktext)) {
1931 $icon->linktext = $linktext;
1933 return $this->render($icon);
1937 * Implementation of user image rendering.
1939 * @param help_icon $helpicon A help icon instance
1940 * @return string HTML fragment
1942 protected function render_help_icon(help_icon $helpicon) {
1943 global $CFG;
1945 // first get the help image icon
1946 $src = $this->pix_url('help');
1948 $title = get_string($helpicon->identifier, $helpicon->component);
1950 if (empty($helpicon->linktext)) {
1951 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1952 } else {
1953 $alt = get_string('helpwiththis');
1956 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1957 $output = html_writer::empty_tag('img', $attributes);
1959 // add the link text if given
1960 if (!empty($helpicon->linktext)) {
1961 // the spacing has to be done through CSS
1962 $output .= $helpicon->linktext;
1965 // now create the link around it - we need https on loginhttps pages
1966 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1968 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1969 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1971 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true', 'class' => 'tooltip');
1972 $output = html_writer::tag('a', $output, $attributes);
1974 $this->page->requires->js_init_call('M.util.help_icon.setup');
1975 $this->page->requires->string_for_js('close', 'form');
1977 // and finally span
1978 return html_writer::tag('span', $output, array('class' => 'helplink'));
1982 * Returns HTML to display a scale help icon.
1984 * @param int $courseid
1985 * @param stdClass $scale instance
1986 * @return string HTML fragment
1988 public function help_icon_scale($courseid, stdClass $scale) {
1989 global $CFG;
1991 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1993 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1995 $scaleid = abs($scale->id);
1997 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1998 $action = new popup_action('click', $link, 'ratingscale');
2000 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2004 * Creates and returns a spacer image with optional line break.
2006 * @param array $attributes Any HTML attributes to add to the spaced.
2007 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2008 * laxy do it with CSS which is a much better solution.
2009 * @return string HTML fragment
2011 public function spacer(array $attributes = null, $br = false) {
2012 $attributes = (array)$attributes;
2013 if (empty($attributes['width'])) {
2014 $attributes['width'] = 1;
2016 if (empty($attributes['height'])) {
2017 $attributes['height'] = 1;
2019 $attributes['class'] = 'spacer';
2021 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2023 if (!empty($br)) {
2024 $output .= '<br />';
2027 return $output;
2031 * Returns HTML to display the specified user's avatar.
2033 * User avatar may be obtained in two ways:
2034 * <pre>
2035 * // Option 1: (shortcut for simple cases, preferred way)
2036 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2037 * $OUTPUT->user_picture($user, array('popup'=>true));
2039 * // Option 2:
2040 * $userpic = new user_picture($user);
2041 * // Set properties of $userpic
2042 * $userpic->popup = true;
2043 * $OUTPUT->render($userpic);
2044 * </pre>
2046 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2047 * If any of these are missing, the database is queried. Avoid this
2048 * if at all possible, particularly for reports. It is very bad for performance.
2049 * @param array $options associative array with user picture options, used only if not a user_picture object,
2050 * options are:
2051 * - courseid=$this->page->course->id (course id of user profile in link)
2052 * - size=35 (size of image)
2053 * - link=true (make image clickable - the link leads to user profile)
2054 * - popup=false (open in popup)
2055 * - alttext=true (add image alt attribute)
2056 * - class = image class attribute (default 'userpicture')
2057 * @return string HTML fragment
2059 public function user_picture(stdClass $user, array $options = null) {
2060 $userpicture = new user_picture($user);
2061 foreach ((array)$options as $key=>$value) {
2062 if (array_key_exists($key, $userpicture)) {
2063 $userpicture->$key = $value;
2066 return $this->render($userpicture);
2070 * Internal implementation of user image rendering.
2072 * @param user_picture $userpicture
2073 * @return string
2075 protected function render_user_picture(user_picture $userpicture) {
2076 global $CFG, $DB;
2078 $user = $userpicture->user;
2080 if ($userpicture->alttext) {
2081 if (!empty($user->imagealt)) {
2082 $alt = $user->imagealt;
2083 } else {
2084 $alt = get_string('pictureof', '', fullname($user));
2086 } else {
2087 $alt = '';
2090 if (empty($userpicture->size)) {
2091 $size = 35;
2092 } else if ($userpicture->size === true or $userpicture->size == 1) {
2093 $size = 100;
2094 } else {
2095 $size = $userpicture->size;
2098 $class = $userpicture->class;
2100 if ($user->picture == 0) {
2101 $class .= ' defaultuserpic';
2104 $src = $userpicture->get_url($this->page, $this);
2106 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2108 // get the image html output fisrt
2109 $output = html_writer::empty_tag('img', $attributes);;
2111 // then wrap it in link if needed
2112 if (!$userpicture->link) {
2113 return $output;
2116 if (empty($userpicture->courseid)) {
2117 $courseid = $this->page->course->id;
2118 } else {
2119 $courseid = $userpicture->courseid;
2122 if ($courseid == SITEID) {
2123 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2124 } else {
2125 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2128 $attributes = array('href'=>$url);
2130 if ($userpicture->popup) {
2131 $id = html_writer::random_id('userpicture');
2132 $attributes['id'] = $id;
2133 $this->add_action_handler(new popup_action('click', $url), $id);
2136 return html_writer::tag('a', $output, $attributes);
2140 * Internal implementation of file tree viewer items rendering.
2142 * @param array $dir
2143 * @return string
2145 public function htmllize_file_tree($dir) {
2146 if (empty($dir['subdirs']) and empty($dir['files'])) {
2147 return '';
2149 $result = '<ul>';
2150 foreach ($dir['subdirs'] as $subdir) {
2151 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2153 foreach ($dir['files'] as $file) {
2154 $filename = $file->get_filename();
2155 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2157 $result .= '</ul>';
2159 return $result;
2163 * Returns HTML to display the file picker
2165 * <pre>
2166 * $OUTPUT->file_picker($options);
2167 * </pre>
2169 * @param array $options associative array with file manager options
2170 * options are:
2171 * maxbytes=>-1,
2172 * itemid=>0,
2173 * client_id=>uniqid(),
2174 * acepted_types=>'*',
2175 * return_types=>FILE_INTERNAL,
2176 * context=>$PAGE->context
2177 * @return string HTML fragment
2179 public function file_picker($options) {
2180 $fp = new file_picker($options);
2181 return $this->render($fp);
2185 * Internal implementation of file picker rendering.
2187 * @param file_picker $fp
2188 * @return string
2190 public function render_file_picker(file_picker $fp) {
2191 global $CFG, $OUTPUT, $USER;
2192 $options = $fp->options;
2193 $client_id = $options->client_id;
2194 $strsaved = get_string('filesaved', 'repository');
2195 $straddfile = get_string('openpicker', 'repository');
2196 $strloading = get_string('loading', 'repository');
2197 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2198 $strdroptoupload = get_string('droptoupload', 'moodle');
2199 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2201 $currentfile = $options->currentfile;
2202 if (empty($currentfile)) {
2203 $currentfile = '';
2204 } else {
2205 $currentfile .= ' - ';
2207 if ($options->maxbytes) {
2208 $size = $options->maxbytes;
2209 } else {
2210 $size = get_max_upload_file_size();
2212 if ($size == -1) {
2213 $maxsize = '';
2214 } else {
2215 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2217 if ($options->buttonname) {
2218 $buttonname = ' name="' . $options->buttonname . '"';
2219 } else {
2220 $buttonname = '';
2222 $html = <<<EOD
2223 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2224 $icon_progress
2225 </div>
2226 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2227 <div>
2228 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2229 <span> $maxsize </span>
2230 </div>
2231 EOD;
2232 if ($options->env != 'url') {
2233 $html .= <<<EOD
2234 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2235 <div class="filepicker-filename">
2236 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2237 </div>
2238 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2239 </div>
2240 EOD;
2242 $html .= '</div>';
2243 return $html;
2247 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2249 * @param string $cmid the course_module id.
2250 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2251 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2253 public function update_module_button($cmid, $modulename) {
2254 global $CFG;
2255 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2256 $modulename = get_string('modulename', $modulename);
2257 $string = get_string('updatethis', '', $modulename);
2258 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2259 return $this->single_button($url, $string);
2260 } else {
2261 return '';
2266 * Returns HTML to display a "Turn editing on/off" button in a form.
2268 * @param moodle_url $url The URL + params to send through when clicking the button
2269 * @return string HTML the button
2271 public function edit_button(moodle_url $url) {
2273 $url->param('sesskey', sesskey());
2274 if ($this->page->user_is_editing()) {
2275 $url->param('edit', 'off');
2276 $editstring = get_string('turneditingoff');
2277 } else {
2278 $url->param('edit', 'on');
2279 $editstring = get_string('turneditingon');
2282 return $this->single_button($url, $editstring);
2286 * Returns HTML to display a simple button to close a window
2288 * @param string $text The lang string for the button's label (already output from get_string())
2289 * @return string html fragment
2291 public function close_window_button($text='') {
2292 if (empty($text)) {
2293 $text = get_string('closewindow');
2295 $button = new single_button(new moodle_url('#'), $text, 'get');
2296 $button->add_action(new component_action('click', 'close_window'));
2298 return $this->container($this->render($button), 'closewindow');
2302 * Output an error message. By default wraps the error message in <span class="error">.
2303 * If the error message is blank, nothing is output.
2305 * @param string $message the error message.
2306 * @return string the HTML to output.
2308 public function error_text($message) {
2309 if (empty($message)) {
2310 return '';
2312 return html_writer::tag('span', $message, array('class' => 'error'));
2316 * Do not call this function directly.
2318 * To terminate the current script with a fatal error, call the {@link print_error}
2319 * function, or throw an exception. Doing either of those things will then call this
2320 * function to display the error, before terminating the execution.
2322 * @param string $message The message to output
2323 * @param string $moreinfourl URL where more info can be found about the error
2324 * @param string $link Link for the Continue button
2325 * @param array $backtrace The execution backtrace
2326 * @param string $debuginfo Debugging information
2327 * @return string the HTML to output.
2329 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2330 global $CFG;
2332 $output = '';
2333 $obbuffer = '';
2335 if ($this->has_started()) {
2336 // we can not always recover properly here, we have problems with output buffering,
2337 // html tables, etc.
2338 $output .= $this->opencontainers->pop_all_but_last();
2340 } else {
2341 // It is really bad if library code throws exception when output buffering is on,
2342 // because the buffered text would be printed before our start of page.
2343 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2344 error_reporting(0); // disable notices from gzip compression, etc.
2345 while (ob_get_level() > 0) {
2346 $buff = ob_get_clean();
2347 if ($buff === false) {
2348 break;
2350 $obbuffer .= $buff;
2352 error_reporting($CFG->debug);
2354 // Header not yet printed
2355 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2356 // server protocol should be always present, because this render
2357 // can not be used from command line or when outputting custom XML
2358 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2360 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2361 $this->page->set_url('/'); // no url
2362 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2363 $this->page->set_title(get_string('error'));
2364 $this->page->set_heading($this->page->course->fullname);
2365 $output .= $this->header();
2368 $message = '<p class="errormessage">' . $message . '</p>'.
2369 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2370 get_string('moreinformation') . '</a></p>';
2371 if (empty($CFG->rolesactive)) {
2372 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2373 //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.
2375 $output .= $this->box($message, 'errorbox');
2377 if (debugging('', DEBUG_DEVELOPER)) {
2378 if (!empty($debuginfo)) {
2379 $debuginfo = s($debuginfo); // removes all nasty JS
2380 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2381 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2383 if (!empty($backtrace)) {
2384 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2386 if ($obbuffer !== '' ) {
2387 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2391 if (empty($CFG->rolesactive)) {
2392 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2393 } else if (!empty($link)) {
2394 $output .= $this->continue_button($link);
2397 $output .= $this->footer();
2399 // Padding to encourage IE to display our error page, rather than its own.
2400 $output .= str_repeat(' ', 512);
2402 return $output;
2406 * Output a notification (that is, a status message about something that has
2407 * just happened).
2409 * @param string $message the message to print out
2410 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2411 * @return string the HTML to output.
2413 public function notification($message, $classes = 'notifyproblem') {
2414 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2418 * Returns HTML to display a continue button that goes to a particular URL.
2420 * @param string|moodle_url $url The url the button goes to.
2421 * @return string the HTML to output.
2423 public function continue_button($url) {
2424 if (!($url instanceof moodle_url)) {
2425 $url = new moodle_url($url);
2427 $button = new single_button($url, get_string('continue'), 'get');
2428 $button->class = 'continuebutton';
2430 return $this->render($button);
2434 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2436 * @param int $totalcount The total number of entries available to be paged through
2437 * @param int $page The page you are currently viewing
2438 * @param int $perpage The number of entries that should be shown per page
2439 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2440 * @param string $pagevar name of page parameter that holds the page number
2441 * @return string the HTML to output.
2443 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2444 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2445 return $this->render($pb);
2449 * Internal implementation of paging bar rendering.
2451 * @param paging_bar $pagingbar
2452 * @return string
2454 protected function render_paging_bar(paging_bar $pagingbar) {
2455 $output = '';
2456 $pagingbar = clone($pagingbar);
2457 $pagingbar->prepare($this, $this->page, $this->target);
2459 if ($pagingbar->totalcount > $pagingbar->perpage) {
2460 $output .= get_string('page') . ':';
2462 if (!empty($pagingbar->previouslink)) {
2463 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2466 if (!empty($pagingbar->firstlink)) {
2467 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2470 foreach ($pagingbar->pagelinks as $link) {
2471 $output .= "&#160;&#160;$link";
2474 if (!empty($pagingbar->lastlink)) {
2475 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2478 if (!empty($pagingbar->nextlink)) {
2479 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2483 return html_writer::tag('div', $output, array('class' => 'paging'));
2487 * Output the place a skip link goes to.
2489 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2490 * @return string the HTML to output.
2492 public function skip_link_target($id = null) {
2493 return html_writer::tag('span', '', array('id' => $id));
2497 * Outputs a heading
2499 * @param string $text The text of the heading
2500 * @param int $level The level of importance of the heading. Defaulting to 2
2501 * @param string $classes A space-separated list of CSS classes
2502 * @param string $id An optional ID
2503 * @return string the HTML to output.
2505 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2506 $level = (integer) $level;
2507 if ($level < 1 or $level > 6) {
2508 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2510 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2514 * Outputs a box.
2516 * @param string $contents The contents of the box
2517 * @param string $classes A space-separated list of CSS classes
2518 * @param string $id An optional ID
2519 * @return string the HTML to output.
2521 public function box($contents, $classes = 'generalbox', $id = null) {
2522 return $this->box_start($classes, $id) . $contents . $this->box_end();
2526 * Outputs the opening section of a box.
2528 * @param string $classes A space-separated list of CSS classes
2529 * @param string $id An optional ID
2530 * @return string the HTML to output.
2532 public function box_start($classes = 'generalbox', $id = null) {
2533 $this->opencontainers->push('box', html_writer::end_tag('div'));
2534 return html_writer::start_tag('div', array('id' => $id,
2535 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2539 * Outputs the closing section of a box.
2541 * @return string the HTML to output.
2543 public function box_end() {
2544 return $this->opencontainers->pop('box');
2548 * Outputs a container.
2550 * @param string $contents The contents of the box
2551 * @param string $classes A space-separated list of CSS classes
2552 * @param string $id An optional ID
2553 * @return string the HTML to output.
2555 public function container($contents, $classes = null, $id = null) {
2556 return $this->container_start($classes, $id) . $contents . $this->container_end();
2560 * Outputs the opening section of a container.
2562 * @param string $classes A space-separated list of CSS classes
2563 * @param string $id An optional ID
2564 * @return string the HTML to output.
2566 public function container_start($classes = null, $id = null) {
2567 $this->opencontainers->push('container', html_writer::end_tag('div'));
2568 return html_writer::start_tag('div', array('id' => $id,
2569 'class' => renderer_base::prepare_classes($classes)));
2573 * Outputs the closing section of a container.
2575 * @return string the HTML to output.
2577 public function container_end() {
2578 return $this->opencontainers->pop('container');
2582 * Make nested HTML lists out of the items
2584 * The resulting list will look something like this:
2586 * <pre>
2587 * <<ul>>
2588 * <<li>><div class='tree_item parent'>(item contents)</div>
2589 * <<ul>
2590 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2591 * <</ul>>
2592 * <</li>>
2593 * <</ul>>
2594 * </pre>
2596 * @param array $items
2597 * @param array $attrs html attributes passed to the top ofs the list
2598 * @return string HTML
2600 public function tree_block_contents($items, $attrs = array()) {
2601 // exit if empty, we don't want an empty ul element
2602 if (empty($items)) {
2603 return '';
2605 // array of nested li elements
2606 $lis = array();
2607 foreach ($items as $item) {
2608 // this applies to the li item which contains all child lists too
2609 $content = $item->content($this);
2610 $liclasses = array($item->get_css_type());
2611 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2612 $liclasses[] = 'collapsed';
2614 if ($item->isactive === true) {
2615 $liclasses[] = 'current_branch';
2617 $liattr = array('class'=>join(' ',$liclasses));
2618 // class attribute on the div item which only contains the item content
2619 $divclasses = array('tree_item');
2620 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2621 $divclasses[] = 'branch';
2622 } else {
2623 $divclasses[] = 'leaf';
2625 if (!empty($item->classes) && count($item->classes)>0) {
2626 $divclasses[] = join(' ', $item->classes);
2628 $divattr = array('class'=>join(' ', $divclasses));
2629 if (!empty($item->id)) {
2630 $divattr['id'] = $item->id;
2632 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2633 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2634 $content = html_writer::empty_tag('hr') . $content;
2636 $content = html_writer::tag('li', $content, $liattr);
2637 $lis[] = $content;
2639 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2643 * Return the navbar content so that it can be echoed out by the layout
2645 * @return string XHTML navbar
2647 public function navbar() {
2648 $items = $this->page->navbar->get_items();
2650 $htmlblocks = array();
2651 // Iterate the navarray and display each node
2652 $itemcount = count($items);
2653 $separator = get_separator();
2654 for ($i=0;$i < $itemcount;$i++) {
2655 $item = $items[$i];
2656 $item->hideicon = true;
2657 if ($i===0) {
2658 $content = html_writer::tag('li', $this->render($item));
2659 } else {
2660 $content = html_writer::tag('li', $separator.$this->render($item));
2662 $htmlblocks[] = $content;
2665 //accessibility: heading for navbar list (MDL-20446)
2666 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2667 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2668 // XHTML
2669 return $navbarcontent;
2673 * Renders a navigation node object.
2675 * @param navigation_node $item The navigation node to render.
2676 * @return string HTML fragment
2678 protected function render_navigation_node(navigation_node $item) {
2679 $content = $item->get_content();
2680 $title = $item->get_title();
2681 if ($item->icon instanceof renderable && !$item->hideicon) {
2682 $icon = $this->render($item->icon);
2683 $content = $icon.$content; // use CSS for spacing of icons
2685 if ($item->helpbutton !== null) {
2686 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2688 if ($content === '') {
2689 return '';
2691 if ($item->action instanceof action_link) {
2692 $link = $item->action;
2693 if ($item->hidden) {
2694 $link->add_class('dimmed');
2696 if (!empty($content)) {
2697 // Providing there is content we will use that for the link content.
2698 $link->text = $content;
2700 $content = $this->render($link);
2701 } else if ($item->action instanceof moodle_url) {
2702 $attributes = array();
2703 if ($title !== '') {
2704 $attributes['title'] = $title;
2706 if ($item->hidden) {
2707 $attributes['class'] = 'dimmed_text';
2709 $content = html_writer::link($item->action, $content, $attributes);
2711 } else if (is_string($item->action) || empty($item->action)) {
2712 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2713 if ($title !== '') {
2714 $attributes['title'] = $title;
2716 if ($item->hidden) {
2717 $attributes['class'] = 'dimmed_text';
2719 $content = html_writer::tag('span', $content, $attributes);
2721 return $content;
2725 * Accessibility: Right arrow-like character is
2726 * used in the breadcrumb trail, course navigation menu
2727 * (previous/next activity), calendar, and search forum block.
2728 * If the theme does not set characters, appropriate defaults
2729 * are set automatically. Please DO NOT
2730 * use &lt; &gt; &raquo; - these are confusing for blind users.
2732 * @return string
2734 public function rarrow() {
2735 return $this->page->theme->rarrow;
2739 * Accessibility: Right arrow-like character is
2740 * used in the breadcrumb trail, course navigation menu
2741 * (previous/next activity), calendar, and search forum block.
2742 * If the theme does not set characters, appropriate defaults
2743 * are set automatically. Please DO NOT
2744 * use &lt; &gt; &raquo; - these are confusing for blind users.
2746 * @return string
2748 public function larrow() {
2749 return $this->page->theme->larrow;
2753 * Returns the custom menu if one has been set
2755 * A custom menu can be configured by browsing to
2756 * Settings: Administration > Appearance > Themes > Theme settings
2757 * and then configuring the custommenu config setting as described.
2759 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2760 * @return string
2762 public function custom_menu($custommenuitems = '') {
2763 global $CFG;
2764 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2765 $custommenuitems = $CFG->custommenuitems;
2767 if (empty($custommenuitems)) {
2768 return '';
2770 $custommenu = new custom_menu($custommenuitems, current_language());
2771 return $this->render_custom_menu($custommenu);
2775 * Renders a custom menu object (located in outputcomponents.php)
2777 * The custom menu this method produces makes use of the YUI3 menunav widget
2778 * and requires very specific html elements and classes.
2780 * @staticvar int $menucount
2781 * @param custom_menu $menu
2782 * @return string
2784 protected function render_custom_menu(custom_menu $menu) {
2785 static $menucount = 0;
2786 // If the menu has no children return an empty string
2787 if (!$menu->has_children()) {
2788 return '';
2790 // Increment the menu count. This is used for ID's that get worked with
2791 // in JavaScript as is essential
2792 $menucount++;
2793 // Initialise this custom menu (the custom menu object is contained in javascript-static
2794 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2795 $jscode = "(function(){{$jscode}})";
2796 $this->page->requires->yui_module('node-menunav', $jscode);
2797 // Build the root nodes as required by YUI
2798 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2799 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2800 $content .= html_writer::start_tag('ul');
2801 // Render each child
2802 foreach ($menu->get_children() as $item) {
2803 $content .= $this->render_custom_menu_item($item);
2805 // Close the open tags
2806 $content .= html_writer::end_tag('ul');
2807 $content .= html_writer::end_tag('div');
2808 $content .= html_writer::end_tag('div');
2809 // Return the custom menu
2810 return $content;
2814 * Renders a custom menu node as part of a submenu
2816 * The custom menu this method produces makes use of the YUI3 menunav widget
2817 * and requires very specific html elements and classes.
2819 * @see core:renderer::render_custom_menu()
2821 * @staticvar int $submenucount
2822 * @param custom_menu_item $menunode
2823 * @return string
2825 protected function render_custom_menu_item(custom_menu_item $menunode) {
2826 // Required to ensure we get unique trackable id's
2827 static $submenucount = 0;
2828 if ($menunode->has_children()) {
2829 // If the child has menus render it as a sub menu
2830 $submenucount++;
2831 $content = html_writer::start_tag('li');
2832 if ($menunode->get_url() !== null) {
2833 $url = $menunode->get_url();
2834 } else {
2835 $url = '#cm_submenu_'.$submenucount;
2837 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2838 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2839 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2840 $content .= html_writer::start_tag('ul');
2841 foreach ($menunode->get_children() as $menunode) {
2842 $content .= $this->render_custom_menu_item($menunode);
2844 $content .= html_writer::end_tag('ul');
2845 $content .= html_writer::end_tag('div');
2846 $content .= html_writer::end_tag('div');
2847 $content .= html_writer::end_tag('li');
2848 } else {
2849 // The node doesn't have children so produce a final menuitem
2850 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2851 if ($menunode->get_url() !== null) {
2852 $url = $menunode->get_url();
2853 } else {
2854 $url = '#';
2856 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2857 $content .= html_writer::end_tag('li');
2859 // Return the sub menu
2860 return $content;
2864 * Renders theme links for switching between default and other themes.
2866 * @return string
2868 protected function theme_switch_links() {
2870 $actualdevice = get_device_type();
2871 $currentdevice = $this->page->devicetypeinuse;
2872 $switched = ($actualdevice != $currentdevice);
2874 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2875 // The user is using the a default device and hasn't switched so don't shown the switch
2876 // device links.
2877 return '';
2880 if ($switched) {
2881 $linktext = get_string('switchdevicerecommended');
2882 $devicetype = $actualdevice;
2883 } else {
2884 $linktext = get_string('switchdevicedefault');
2885 $devicetype = 'default';
2887 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2889 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2890 $content .= html_writer::link($linkurl, $linktext);
2891 $content .= html_writer::end_tag('div');
2893 return $content;
2898 * A renderer that generates output for command-line scripts.
2900 * The implementation of this renderer is probably incomplete.
2902 * @copyright 2009 Tim Hunt
2903 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2904 * @since Moodle 2.0
2905 * @package core
2906 * @category output
2908 class core_renderer_cli extends core_renderer {
2911 * Returns the page header.
2913 * @return string HTML fragment
2915 public function header() {
2916 return $this->page->heading . "\n";
2920 * Returns a template fragment representing a Heading.
2922 * @param string $text The text of the heading
2923 * @param int $level The level of importance of the heading
2924 * @param string $classes A space-separated list of CSS classes
2925 * @param string $id An optional ID
2926 * @return string A template fragment for a heading
2928 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2929 $text .= "\n";
2930 switch ($level) {
2931 case 1:
2932 return '=>' . $text;
2933 case 2:
2934 return '-->' . $text;
2935 default:
2936 return $text;
2941 * Returns a template fragment representing a fatal error.
2943 * @param string $message The message to output
2944 * @param string $moreinfourl URL where more info can be found about the error
2945 * @param string $link Link for the Continue button
2946 * @param array $backtrace The execution backtrace
2947 * @param string $debuginfo Debugging information
2948 * @return string A template fragment for a fatal error
2950 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2951 $output = "!!! $message !!!\n";
2953 if (debugging('', DEBUG_DEVELOPER)) {
2954 if (!empty($debuginfo)) {
2955 $output .= $this->notification($debuginfo, 'notifytiny');
2957 if (!empty($backtrace)) {
2958 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2962 return $output;
2966 * Returns a template fragment representing a notification.
2968 * @param string $message The message to include
2969 * @param string $classes A space-separated list of CSS classes
2970 * @return string A template fragment for a notification
2972 public function notification($message, $classes = 'notifyproblem') {
2973 $message = clean_text($message);
2974 if ($classes === 'notifysuccess') {
2975 return "++ $message ++\n";
2977 return "!! $message !!\n";
2983 * A renderer that generates output for ajax scripts.
2985 * This renderer prevents accidental sends back only json
2986 * encoded error messages, all other output is ignored.
2988 * @copyright 2010 Petr Skoda
2989 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2990 * @since Moodle 2.0
2991 * @package core
2992 * @category output
2994 class core_renderer_ajax extends core_renderer {
2997 * Returns a template fragment representing a fatal error.
2999 * @param string $message The message to output
3000 * @param string $moreinfourl URL where more info can be found about the error
3001 * @param string $link Link for the Continue button
3002 * @param array $backtrace The execution backtrace
3003 * @param string $debuginfo Debugging information
3004 * @return string A template fragment for a fatal error
3006 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3007 global $CFG;
3009 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3011 $e = new stdClass();
3012 $e->error = $message;
3013 $e->stacktrace = NULL;
3014 $e->debuginfo = NULL;
3015 $e->reproductionlink = NULL;
3016 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3017 $e->reproductionlink = $link;
3018 if (!empty($debuginfo)) {
3019 $e->debuginfo = $debuginfo;
3021 if (!empty($backtrace)) {
3022 $e->stacktrace = format_backtrace($backtrace, true);
3025 $this->header();
3026 return json_encode($e);
3030 * Used to display a notification.
3031 * For the AJAX notifications are discarded.
3033 * @param string $message
3034 * @param string $classes
3036 public function notification($message, $classes = 'notifyproblem') {}
3039 * Used to display a redirection message.
3040 * AJAX redirections should not occur and as such redirection messages
3041 * are discarded.
3043 * @param moodle_url|string $encodedurl
3044 * @param string $message
3045 * @param int $delay
3046 * @param bool $debugdisableredirect
3048 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3051 * Prepares the start of an AJAX output.
3053 public function header() {
3054 // unfortunately YUI iframe upload does not support application/json
3055 if (!empty($_FILES)) {
3056 @header('Content-type: text/plain; charset=utf-8');
3057 } else {
3058 @header('Content-type: application/json; charset=utf-8');
3061 // Headers to make it not cacheable and json
3062 @header('Cache-Control: no-store, no-cache, must-revalidate');
3063 @header('Cache-Control: post-check=0, pre-check=0', false);
3064 @header('Pragma: no-cache');
3065 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3066 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3067 @header('Accept-Ranges: none');
3071 * There is no footer for an AJAX request, however we must override the
3072 * footer method to prevent the default footer.
3074 public function footer() {}
3077 * No need for headers in an AJAX request... this should never happen.
3078 * @param string $text
3079 * @param int $level
3080 * @param string $classes
3081 * @param string $id
3083 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3088 * Renderer for media files.
3090 * Used in file resources, media filter, and any other places that need to
3091 * output embedded media.
3093 * @copyright 2011 The Open University
3094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3096 class core_media_renderer extends plugin_renderer_base {
3097 /** @var array Array of available 'player' objects */
3098 private $players;
3099 /** @var string Regex pattern for links which may contain embeddable content */
3100 private $embeddablemarkers;
3103 * Constructor requires medialib.php.
3105 * This is needed in the constructor (not later) so that you can use the
3106 * constants and static functions that are defined in core_media class
3107 * before you call renderer functions.
3109 public function __construct() {
3110 global $CFG;
3111 require_once($CFG->libdir . '/medialib.php');
3115 * Obtains the list of core_media_player objects currently in use to render
3116 * items.
3118 * The list is in rank order (highest first) and does not include players
3119 * which are disabled.
3121 * @return array Array of core_media_player objects in rank order
3123 protected function get_players() {
3124 global $CFG;
3126 // Save time by only building the list once.
3127 if (!$this->players) {
3128 // Get raw list of players.
3129 $players = $this->get_players_raw();
3131 // Chuck all the ones that are disabled.
3132 foreach ($players as $key => $player) {
3133 if (!$player->is_enabled()) {
3134 unset($players[$key]);
3138 // Sort in rank order (highest first).
3139 usort($players, array('core_media_player', 'compare_by_rank'));
3140 $this->players = $players;
3142 return $this->players;
3146 * Obtains a raw list of player objects that includes objects regardless
3147 * of whether they are disabled or not, and without sorting.
3149 * You can override this in a subclass if you need to add additional
3150 * players.
3152 * The return array is be indexed by player name to make it easier to
3153 * remove players in a subclass.
3155 * @return array $players Array of core_media_player objects in any order
3157 protected function get_players_raw() {
3158 return array(
3159 'vimeo' => new core_media_player_vimeo(),
3160 'youtube' => new core_media_player_youtube(),
3161 'youtube_playlist' => new core_media_player_youtube_playlist(),
3162 'html5video' => new core_media_player_html5video(),
3163 'html5audio' => new core_media_player_html5audio(),
3164 'mp3' => new core_media_player_mp3(),
3165 'flv' => new core_media_player_flv(),
3166 'wmp' => new core_media_player_wmp(),
3167 'qt' => new core_media_player_qt(),
3168 'rm' => new core_media_player_rm(),
3169 'swf' => new core_media_player_swf(),
3170 'link' => new core_media_player_link(),
3175 * Renders a media file (audio or video) using suitable embedded player.
3177 * See embed_alternatives function for full description of parameters.
3178 * This function calls through to that one.
3180 * When using this function you can also specify width and height in the
3181 * URL by including ?d=100x100 at the end. If specified in the URL, this
3182 * will override the $width and $height parameters.
3184 * @param moodle_url $url Full URL of media file
3185 * @param string $name Optional user-readable name to display in download link
3186 * @param int $width Width in pixels (optional)
3187 * @param int $height Height in pixels (optional)
3188 * @param array $options Array of key/value pairs
3189 * @return string HTML content of embed
3191 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3192 $options = array()) {
3194 // Get width and height from URL if specified (overrides parameters in
3195 // function call).
3196 $rawurl = $url->out(false);
3197 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3198 $width = $matches[1];
3199 $height = $matches[2];
3200 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3203 // Defer to array version of function.
3204 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3208 * Renders media files (audio or video) using suitable embedded player.
3209 * The list of URLs should be alternative versions of the same content in
3210 * multiple formats. If there is only one format it should have a single
3211 * entry.
3213 * If the media files are not in a supported format, this will give students
3214 * a download link to each format. The download link uses the filename
3215 * unless you supply the optional name parameter.
3217 * Width and height are optional. If specified, these are suggested sizes
3218 * and should be the exact values supplied by the user, if they come from
3219 * user input. These will be treated as relating to the size of the video
3220 * content, not including any player control bar.
3222 * For audio files, height will be ignored. For video files, a few formats
3223 * work if you specify only width, but in general if you specify width
3224 * you must specify height as well.
3226 * The $options array is passed through to the core_media_player classes
3227 * that render the object tag. The keys can contain values from
3228 * core_media::OPTION_xx.
3230 * @param array $alternatives Array of moodle_url to media files
3231 * @param string $name Optional user-readable name to display in download link
3232 * @param int $width Width in pixels (optional)
3233 * @param int $height Height in pixels (optional)
3234 * @param array $options Array of key/value pairs
3235 * @return string HTML content of embed
3237 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3238 $options = array()) {
3240 // Get list of player plugins (will also require the library).
3241 $players = $this->get_players();
3243 // Set up initial text which will be replaced by first player that
3244 // supports any of the formats.
3245 $out = core_media_player::PLACEHOLDER;
3247 // Loop through all players that support any of these URLs.
3248 foreach ($players as $player) {
3249 // Option: When no other player matched, don't do the default link player.
3250 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3251 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3252 continue;
3255 $supported = $player->list_supported_urls($alternatives, $options);
3256 if ($supported) {
3257 // Embed.
3258 $text = $player->embed($supported, $name, $width, $height, $options);
3260 // Put this in place of the 'fallback' slot in the previous text.
3261 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3265 // Remove 'fallback' slot from final version and return it.
3266 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3267 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3268 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3270 return $out;
3274 * Checks whether a file can be embedded. If this returns true you will get
3275 * an embedded player; if this returns false, you will just get a download
3276 * link.
3278 * This is a wrapper for can_embed_urls.
3280 * @param moodle_url $url URL of media file
3281 * @param array $options Options (same as when embedding)
3282 * @return bool True if file can be embedded
3284 public function can_embed_url(moodle_url $url, $options = array()) {
3285 return $this->can_embed_urls(array($url), $options);
3289 * Checks whether a file can be embedded. If this returns true you will get
3290 * an embedded player; if this returns false, you will just get a download
3291 * link.
3293 * @param array $urls URL of media file and any alternatives (moodle_url)
3294 * @param array $options Options (same as when embedding)
3295 * @return bool True if file can be embedded
3297 public function can_embed_urls(array $urls, $options = array()) {
3298 // Check all players to see if any of them support it.
3299 foreach ($this->get_players() as $player) {
3300 // Link player (always last on list) doesn't count!
3301 if ($player->get_rank() <= 0) {
3302 break;
3304 // First player that supports it, return true.
3305 if ($player->list_supported_urls($urls, $options)) {
3306 return true;
3309 return false;
3313 * Obtains a list of markers that can be used in a regular expression when
3314 * searching for URLs that can be embedded by any player type.
3316 * This string is used to improve peformance of regex matching by ensuring
3317 * that the (presumably C) regex code can do a quick keyword check on the
3318 * URL part of a link to see if it matches one of these, rather than having
3319 * to go into PHP code for every single link to see if it can be embedded.
3321 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3323 public function get_embeddable_markers() {
3324 if (empty($this->embeddablemarkers)) {
3325 $markers = '';
3326 foreach ($this->get_players() as $player) {
3327 foreach ($player->get_embeddable_markers() as $marker) {
3328 if ($markers !== '') {
3329 $markers .= '|';
3331 $markers .= preg_quote($marker);
3334 $this->embeddablemarkers = $markers;
3336 return $this->embeddablemarkers;