Merge branch 'MDL-37668-m24' of git://github.com/sammarshallou/moodle into MOODLE_24_...
[moodle.git] / lib / outputrenderers.php
blob0e8052d59b25f25e24c92aa6a4b17ca6b4b1cf92
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 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
537 } else {
538 $realuserinfo = " [$fullname] ";
540 } else {
541 $realuserinfo = '';
544 $loginurl = get_login_url();
546 if (empty($course->id)) {
547 // $course->id is not defined during installation
548 return '';
549 } else if (isloggedin()) {
550 $context = context_course::instance($course->id);
552 $fullname = fullname($USER, true);
553 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
554 if ($withlinks) {
555 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
556 } else {
557 $username = $fullname;
559 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
560 if ($withlinks) {
561 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
562 } else {
563 $username .= " from {$idprovider->name}";
566 if (isguestuser()) {
567 $loggedinas = $realuserinfo.get_string('loggedinasguest');
568 if (!$loginpage && $withlinks) {
569 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
571 } else if (is_role_switched($course->id)) { // Has switched roles
572 $rolename = '';
573 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
574 $rolename = ': '.format_string($role->name);
576 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
577 if ($withlinks) {
578 $loggedinas .= " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
580 } else {
581 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
582 if ($withlinks) {
583 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
586 } else {
587 $loggedinas = get_string('loggedinnot', 'moodle');
588 if (!$loginpage && $withlinks) {
589 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
593 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
595 if (isset($SESSION->justloggedin)) {
596 unset($SESSION->justloggedin);
597 if (!empty($CFG->displayloginfailures)) {
598 if (!isguestuser()) {
599 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
600 $loggedinas .= '&nbsp;<div class="loginfailures">';
601 if (empty($count->accounts)) {
602 $loggedinas .= get_string('failedloginattempts', '', $count);
603 } else {
604 $loggedinas .= get_string('failedloginattemptsall', '', $count);
606 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
607 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
608 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
610 $loggedinas .= '</div>';
616 return $loggedinas;
620 * Return the 'back' link that normally appears in the footer.
622 * @return string HTML fragment.
624 public function home_link() {
625 global $CFG, $SITE;
627 if ($this->page->pagetype == 'site-index') {
628 // Special case for site home page - please do not remove
629 return '<div class="sitelink">' .
630 '<a title="Moodle" href="http://moodle.org/">' .
631 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
633 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
634 // Special case for during install/upgrade.
635 return '<div class="sitelink">'.
636 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
637 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
639 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
640 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
641 get_string('home') . '</a></div>';
643 } else {
644 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
645 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
650 * Redirects the user by any means possible given the current state
652 * This function should not be called directly, it should always be called using
653 * the redirect function in lib/weblib.php
655 * The redirect function should really only be called before page output has started
656 * however it will allow itself to be called during the state STATE_IN_BODY
658 * @param string $encodedurl The URL to send to encoded if required
659 * @param string $message The message to display to the user if any
660 * @param int $delay The delay before redirecting a user, if $message has been
661 * set this is a requirement and defaults to 3, set to 0 no delay
662 * @param boolean $debugdisableredirect this redirect has been disabled for
663 * debugging purposes. Display a message that explains, and don't
664 * trigger the redirect.
665 * @return string The HTML to display to the user before dying, may contain
666 * meta refresh, javascript refresh, and may have set header redirects
668 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
669 global $CFG;
670 $url = str_replace('&amp;', '&', $encodedurl);
672 switch ($this->page->state) {
673 case moodle_page::STATE_BEFORE_HEADER :
674 // No output yet it is safe to delivery the full arsenal of redirect methods
675 if (!$debugdisableredirect) {
676 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
677 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
678 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
680 $output = $this->header();
681 break;
682 case moodle_page::STATE_PRINTING_HEADER :
683 // We should hopefully never get here
684 throw new coding_exception('You cannot redirect while printing the page header');
685 break;
686 case moodle_page::STATE_IN_BODY :
687 // We really shouldn't be here but we can deal with this
688 debugging("You should really redirect before you start page output");
689 if (!$debugdisableredirect) {
690 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
692 $output = $this->opencontainers->pop_all_but_last();
693 break;
694 case moodle_page::STATE_DONE :
695 // Too late to be calling redirect now
696 throw new coding_exception('You cannot redirect after the entire page has been generated');
697 break;
699 $output .= $this->notification($message, 'redirectmessage');
700 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
701 if ($debugdisableredirect) {
702 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
704 $output .= $this->footer();
705 return $output;
709 * Start output by sending the HTTP headers, and printing the HTML <head>
710 * and the start of the <body>.
712 * To control what is printed, you should set properties on $PAGE. If you
713 * are familiar with the old {@link print_header()} function from Moodle 1.9
714 * you will find that there are properties on $PAGE that correspond to most
715 * of the old parameters to could be passed to print_header.
717 * Not that, in due course, the remaining $navigation, $menu parameters here
718 * will be replaced by more properties of $PAGE, but that is still to do.
720 * @return string HTML that you must output this, preferably immediately.
722 public function header() {
723 global $USER, $CFG;
725 if (session_is_loggedinas()) {
726 $this->page->add_body_class('userloggedinas');
729 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
731 // Find the appropriate page layout file, based on $this->page->pagelayout.
732 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
733 // Render the layout using the layout file.
734 $rendered = $this->render_page_layout($layoutfile);
736 // Slice the rendered output into header and footer.
737 $cutpos = strpos($rendered, $this->unique_main_content_token);
738 if ($cutpos === false) {
739 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
740 $token = self::MAIN_CONTENT_TOKEN;
741 } else {
742 $token = $this->unique_main_content_token;
745 if ($cutpos === false) {
746 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.');
748 $header = substr($rendered, 0, $cutpos);
749 $footer = substr($rendered, $cutpos + strlen($token));
751 if (empty($this->contenttype)) {
752 debugging('The page layout file did not call $OUTPUT->doctype()');
753 $header = $this->doctype() . $header;
756 // If this theme version is below 2.4 release and this is a course view page
757 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
758 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
759 // check if course content header/footer have not been output during render of theme layout
760 $coursecontentheader = $this->course_content_header(true);
761 $coursecontentfooter = $this->course_content_footer(true);
762 if (!empty($coursecontentheader)) {
763 // display debug message and add header and footer right above and below main content
764 // Please note that course header and footer (to be displayed above and below the whole page)
765 // are not displayed in this case at all.
766 // Besides the content header and footer are not displayed on any other course page
767 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);
768 $header .= $coursecontentheader;
769 $footer = $coursecontentfooter. $footer;
773 send_headers($this->contenttype, $this->page->cacheable);
775 $this->opencontainers->push('header/footer', $footer);
776 $this->page->set_state(moodle_page::STATE_IN_BODY);
778 return $header . $this->skip_link_target('maincontent');
782 * Renders and outputs the page layout file.
784 * This is done by preparing the normal globals available to a script, and
785 * then including the layout file provided by the current theme for the
786 * requested layout.
788 * @param string $layoutfile The name of the layout file
789 * @return string HTML code
791 protected function render_page_layout($layoutfile) {
792 global $CFG, $SITE, $USER;
793 // The next lines are a bit tricky. The point is, here we are in a method
794 // of a renderer class, and this object may, or may not, be the same as
795 // the global $OUTPUT object. When rendering the page layout file, we want to use
796 // this object. However, people writing Moodle code expect the current
797 // renderer to be called $OUTPUT, not $this, so define a variable called
798 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
799 $OUTPUT = $this;
800 $PAGE = $this->page;
801 $COURSE = $this->page->course;
803 ob_start();
804 include($layoutfile);
805 $rendered = ob_get_contents();
806 ob_end_clean();
807 return $rendered;
811 * Outputs the page's footer
813 * @return string HTML fragment
815 public function footer() {
816 global $CFG, $DB;
818 $output = $this->container_end_all(true);
820 $footer = $this->opencontainers->pop('header/footer');
822 if (debugging() and $DB and $DB->is_transaction_started()) {
823 // TODO: MDL-20625 print warning - transaction will be rolled back
826 // Provide some performance info if required
827 $performanceinfo = '';
828 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
829 $perf = get_performance_info();
830 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
831 error_log("PERF: " . $perf['txt']);
833 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
834 $performanceinfo = $perf['html'];
837 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
839 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
841 $this->page->set_state(moodle_page::STATE_DONE);
843 return $output . $footer;
847 * Close all but the last open container. This is useful in places like error
848 * handling, where you want to close all the open containers (apart from <body>)
849 * before outputting the error message.
851 * @param bool $shouldbenone assert that the stack should be empty now - causes a
852 * developer debug warning if it isn't.
853 * @return string the HTML required to close any open containers inside <body>.
855 public function container_end_all($shouldbenone = false) {
856 return $this->opencontainers->pop_all_but_last($shouldbenone);
860 * Returns course-specific information to be output immediately above content on any course page
861 * (for the current course)
863 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
864 * @return string
866 public function course_content_header($onlyifnotcalledbefore = false) {
867 global $CFG;
868 if ($this->page->course->id == SITEID) {
869 // return immediately and do not include /course/lib.php if not necessary
870 return '';
872 static $functioncalled = false;
873 if ($functioncalled && $onlyifnotcalledbefore) {
874 // we have already output the content header
875 return '';
877 require_once($CFG->dirroot.'/course/lib.php');
878 $functioncalled = true;
879 $courseformat = course_get_format($this->page->course);
880 if (($obj = $courseformat->course_content_header()) !== null) {
881 return $courseformat->get_renderer($this->page)->render($obj);
883 return '';
887 * Returns course-specific information to be output immediately below content on any course page
888 * (for the current course)
890 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
891 * @return string
893 public function course_content_footer($onlyifnotcalledbefore = false) {
894 global $CFG;
895 if ($this->page->course->id == SITEID) {
896 // return immediately and do not include /course/lib.php if not necessary
897 return '';
899 static $functioncalled = false;
900 if ($functioncalled && $onlyifnotcalledbefore) {
901 // we have already output the content footer
902 return '';
904 $functioncalled = true;
905 require_once($CFG->dirroot.'/course/lib.php');
906 $courseformat = course_get_format($this->page->course);
907 if (($obj = $courseformat->course_content_footer()) !== null) {
908 return $courseformat->get_renderer($this->page)->render($obj);
910 return '';
914 * Returns course-specific information to be output on any course page in the header area
915 * (for the current course)
917 * @return string
919 public function course_header() {
920 global $CFG;
921 if ($this->page->course->id == SITEID) {
922 // return immediately and do not include /course/lib.php if not necessary
923 return '';
925 require_once($CFG->dirroot.'/course/lib.php');
926 $courseformat = course_get_format($this->page->course);
927 if (($obj = $courseformat->course_header()) !== null) {
928 return $courseformat->get_renderer($this->page)->render($obj);
930 return '';
934 * Returns course-specific information to be output on any course page in the footer area
935 * (for the current course)
937 * @return string
939 public function course_footer() {
940 global $CFG;
941 if ($this->page->course->id == SITEID) {
942 // return immediately and do not include /course/lib.php if not necessary
943 return '';
945 require_once($CFG->dirroot.'/course/lib.php');
946 $courseformat = course_get_format($this->page->course);
947 if (($obj = $courseformat->course_footer()) !== null) {
948 return $courseformat->get_renderer($this->page)->render($obj);
950 return '';
954 * Returns lang menu or '', this method also checks forcing of languages in courses.
956 * @return string The lang menu HTML or empty string
958 public function lang_menu() {
959 global $CFG;
961 if (empty($CFG->langmenu)) {
962 return '';
965 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
966 // do not show lang menu if language forced
967 return '';
970 $currlang = current_language();
971 $langs = get_string_manager()->get_list_of_translations();
973 if (count($langs) < 2) {
974 return '';
977 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
978 $s->label = get_accesshide(get_string('language'));
979 $s->class = 'langmenu';
980 return $this->render($s);
984 * Output the row of editing icons for a block, as defined by the controls array.
986 * @param array $controls an array like {@link block_contents::$controls}.
987 * @return string HTML fragment.
989 public function block_controls($controls) {
990 if (empty($controls)) {
991 return '';
993 $controlshtml = array();
994 foreach ($controls as $control) {
995 $controlshtml[] = html_writer::tag('a',
996 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
997 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
999 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
1003 * Prints a nice side block with an optional header.
1005 * The content is described
1006 * by a {@link core_renderer::block_contents} object.
1008 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1009 * <div class="header"></div>
1010 * <div class="content">
1011 * ...CONTENT...
1012 * <div class="footer">
1013 * </div>
1014 * </div>
1015 * <div class="annotation">
1016 * </div>
1017 * </div>
1019 * @param block_contents $bc HTML for the content
1020 * @param string $region the region the block is appearing in.
1021 * @return string the HTML to be output.
1023 public function block(block_contents $bc, $region) {
1024 $bc = clone($bc); // Avoid messing up the object passed in.
1025 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1026 $bc->collapsible = block_contents::NOT_HIDEABLE;
1028 $skiptitle = strip_tags($bc->title);
1029 if ($bc->blockinstanceid && !empty($skiptitle)) {
1030 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1031 } else if (!empty($bc->arialabel)) {
1032 $bc->attributes['aria-label'] = $bc->arialabel;
1034 if ($bc->collapsible == block_contents::HIDDEN) {
1035 $bc->add_class('hidden');
1037 if (!empty($bc->controls)) {
1038 $bc->add_class('block_with_controls');
1042 if (empty($skiptitle)) {
1043 $output = '';
1044 $skipdest = '';
1045 } else {
1046 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1047 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1050 $output .= html_writer::start_tag('div', $bc->attributes);
1052 $output .= $this->block_header($bc);
1053 $output .= $this->block_content($bc);
1055 $output .= html_writer::end_tag('div');
1057 $output .= $this->block_annotation($bc);
1059 $output .= $skipdest;
1061 $this->init_block_hider_js($bc);
1062 return $output;
1066 * Produces a header for a block
1068 * @param block_contents $bc
1069 * @return string
1071 protected function block_header(block_contents $bc) {
1073 $title = '';
1074 if ($bc->title) {
1075 $attributes = array();
1076 if ($bc->blockinstanceid) {
1077 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1079 $title = html_writer::tag('h2', $bc->title, $attributes);
1082 $controlshtml = $this->block_controls($bc->controls);
1084 $output = '';
1085 if ($title || $controlshtml) {
1086 $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'));
1088 return $output;
1092 * Produces the content area for a block
1094 * @param block_contents $bc
1095 * @return string
1097 protected function block_content(block_contents $bc) {
1098 $output = html_writer::start_tag('div', array('class' => 'content'));
1099 if (!$bc->title && !$this->block_controls($bc->controls)) {
1100 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1102 $output .= $bc->content;
1103 $output .= $this->block_footer($bc);
1104 $output .= html_writer::end_tag('div');
1106 return $output;
1110 * Produces the footer for a block
1112 * @param block_contents $bc
1113 * @return string
1115 protected function block_footer(block_contents $bc) {
1116 $output = '';
1117 if ($bc->footer) {
1118 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1120 return $output;
1124 * Produces the annotation for a block
1126 * @param block_contents $bc
1127 * @return string
1129 protected function block_annotation(block_contents $bc) {
1130 $output = '';
1131 if ($bc->annotation) {
1132 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1134 return $output;
1138 * Calls the JS require function to hide a block.
1140 * @param block_contents $bc A block_contents object
1142 protected function init_block_hider_js(block_contents $bc) {
1143 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1144 $config = new stdClass;
1145 $config->id = $bc->attributes['id'];
1146 $config->title = strip_tags($bc->title);
1147 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1148 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1149 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1151 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1152 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1157 * Render the contents of a block_list.
1159 * @param array $icons the icon for each item.
1160 * @param array $items the content of each item.
1161 * @return string HTML
1163 public function list_block_contents($icons, $items) {
1164 $row = 0;
1165 $lis = array();
1166 foreach ($items as $key => $string) {
1167 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1168 if (!empty($icons[$key])) { //test if the content has an assigned icon
1169 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1171 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1172 $item .= html_writer::end_tag('li');
1173 $lis[] = $item;
1174 $row = 1 - $row; // Flip even/odd.
1176 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1180 * Output all the blocks in a particular region.
1182 * @param string $region the name of a region on this page.
1183 * @return string the HTML to be output.
1185 public function blocks_for_region($region) {
1186 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1188 $output = '';
1189 foreach ($blockcontents as $bc) {
1190 if ($bc instanceof block_contents) {
1191 $output .= $this->block($bc, $region);
1192 } else if ($bc instanceof block_move_target) {
1193 $output .= $this->block_move_target($bc);
1194 } else {
1195 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1198 return $output;
1202 * Output a place where the block that is currently being moved can be dropped.
1204 * @param block_move_target $target with the necessary details.
1205 * @return string the HTML to be output.
1207 public function block_move_target($target) {
1208 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1212 * Renders a special html link with attached action
1214 * @param string|moodle_url $url
1215 * @param string $text HTML fragment
1216 * @param component_action $action
1217 * @param array $attributes associative array of html link attributes + disabled
1218 * @return string HTML fragment
1220 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1221 if (!($url instanceof moodle_url)) {
1222 $url = new moodle_url($url);
1224 $link = new action_link($url, $text, $action, $attributes);
1226 return $this->render($link);
1230 * Renders an action_link object.
1232 * The provided link is renderer and the HTML returned. At the same time the
1233 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1235 * @param action_link $link
1236 * @return string HTML fragment
1238 protected function render_action_link(action_link $link) {
1239 global $CFG;
1241 if ($link->text instanceof renderable) {
1242 $text = $this->render($link->text);
1243 } else {
1244 $text = $link->text;
1247 // A disabled link is rendered as formatted text
1248 if (!empty($link->attributes['disabled'])) {
1249 // do not use div here due to nesting restriction in xhtml strict
1250 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1253 $attributes = $link->attributes;
1254 unset($link->attributes['disabled']);
1255 $attributes['href'] = $link->url;
1257 if ($link->actions) {
1258 if (empty($attributes['id'])) {
1259 $id = html_writer::random_id('action_link');
1260 $attributes['id'] = $id;
1261 } else {
1262 $id = $attributes['id'];
1264 foreach ($link->actions as $action) {
1265 $this->add_action_handler($action, $id);
1269 return html_writer::tag('a', $text, $attributes);
1274 * Renders an action_icon.
1276 * This function uses the {@link core_renderer::action_link()} method for the
1277 * most part. What it does different is prepare the icon as HTML and use it
1278 * as the link text.
1280 * @param string|moodle_url $url A string URL or moodel_url
1281 * @param pix_icon $pixicon
1282 * @param component_action $action
1283 * @param array $attributes associative array of html link attributes + disabled
1284 * @param bool $linktext show title next to image in link
1285 * @return string HTML fragment
1287 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1288 if (!($url instanceof moodle_url)) {
1289 $url = new moodle_url($url);
1291 $attributes = (array)$attributes;
1293 if (empty($attributes['class'])) {
1294 // let ppl override the class via $options
1295 $attributes['class'] = 'action-icon';
1298 $icon = $this->render($pixicon);
1300 if ($linktext) {
1301 $text = $pixicon->attributes['alt'];
1302 } else {
1303 $text = '';
1306 return $this->action_link($url, $text.$icon, $action, $attributes);
1310 * Print a message along with button choices for Continue/Cancel
1312 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1314 * @param string $message The question to ask the user
1315 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1316 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1317 * @return string HTML fragment
1319 public function confirm($message, $continue, $cancel) {
1320 if ($continue instanceof single_button) {
1321 // ok
1322 } else if (is_string($continue)) {
1323 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1324 } else if ($continue instanceof moodle_url) {
1325 $continue = new single_button($continue, get_string('continue'), 'post');
1326 } else {
1327 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1330 if ($cancel instanceof single_button) {
1331 // ok
1332 } else if (is_string($cancel)) {
1333 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1334 } else if ($cancel instanceof moodle_url) {
1335 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1336 } else {
1337 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1340 $output = $this->box_start('generalbox', 'notice');
1341 $output .= html_writer::tag('p', $message);
1342 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1343 $output .= $this->box_end();
1344 return $output;
1348 * Returns a form with a single button.
1350 * @param string|moodle_url $url
1351 * @param string $label button text
1352 * @param string $method get or post submit method
1353 * @param array $options associative array {disabled, title, etc.}
1354 * @return string HTML fragment
1356 public function single_button($url, $label, $method='post', array $options=null) {
1357 if (!($url instanceof moodle_url)) {
1358 $url = new moodle_url($url);
1360 $button = new single_button($url, $label, $method);
1362 foreach ((array)$options as $key=>$value) {
1363 if (array_key_exists($key, $button)) {
1364 $button->$key = $value;
1368 return $this->render($button);
1372 * Renders a single button widget.
1374 * This will return HTML to display a form containing a single button.
1376 * @param single_button $button
1377 * @return string HTML fragment
1379 protected function render_single_button(single_button $button) {
1380 $attributes = array('type' => 'submit',
1381 'value' => $button->label,
1382 'disabled' => $button->disabled ? 'disabled' : null,
1383 'title' => $button->tooltip);
1385 if ($button->actions) {
1386 $id = html_writer::random_id('single_button');
1387 $attributes['id'] = $id;
1388 foreach ($button->actions as $action) {
1389 $this->add_action_handler($action, $id);
1393 // first the input element
1394 $output = html_writer::empty_tag('input', $attributes);
1396 // then hidden fields
1397 $params = $button->url->params();
1398 if ($button->method === 'post') {
1399 $params['sesskey'] = sesskey();
1401 foreach ($params as $var => $val) {
1402 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1405 // then div wrapper for xhtml strictness
1406 $output = html_writer::tag('div', $output);
1408 // now the form itself around it
1409 if ($button->method === 'get') {
1410 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1411 } else {
1412 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1414 if ($url === '') {
1415 $url = '#'; // there has to be always some action
1417 $attributes = array('method' => $button->method,
1418 'action' => $url,
1419 'id' => $button->formid);
1420 $output = html_writer::tag('form', $output, $attributes);
1422 // and finally one more wrapper with class
1423 return html_writer::tag('div', $output, array('class' => $button->class));
1427 * Returns a form with a single select widget.
1429 * @param moodle_url $url form action target, includes hidden fields
1430 * @param string $name name of selection field - the changing parameter in url
1431 * @param array $options list of options
1432 * @param string $selected selected element
1433 * @param array $nothing
1434 * @param string $formid
1435 * @return string HTML fragment
1437 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1438 if (!($url instanceof moodle_url)) {
1439 $url = new moodle_url($url);
1441 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1443 return $this->render($select);
1447 * Internal implementation of single_select rendering
1449 * @param single_select $select
1450 * @return string HTML fragment
1452 protected function render_single_select(single_select $select) {
1453 $select = clone($select);
1454 if (empty($select->formid)) {
1455 $select->formid = html_writer::random_id('single_select_f');
1458 $output = '';
1459 $params = $select->url->params();
1460 if ($select->method === 'post') {
1461 $params['sesskey'] = sesskey();
1463 foreach ($params as $name=>$value) {
1464 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1467 if (empty($select->attributes['id'])) {
1468 $select->attributes['id'] = html_writer::random_id('single_select');
1471 if ($select->disabled) {
1472 $select->attributes['disabled'] = 'disabled';
1475 if ($select->tooltip) {
1476 $select->attributes['title'] = $select->tooltip;
1479 $select->attributes['class'] = 'autosubmit';
1480 if ($select->class) {
1481 $select->attributes['class'] .= ' ' . $select->class;
1484 if ($select->label) {
1485 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1488 if ($select->helpicon instanceof help_icon) {
1489 $output .= $this->render($select->helpicon);
1490 } else if ($select->helpicon instanceof old_help_icon) {
1491 $output .= $this->render($select->helpicon);
1493 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1495 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1496 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1498 $nothing = empty($select->nothing) ? false : key($select->nothing);
1499 $this->page->requires->yui_module('moodle-core-formautosubmit',
1500 'M.core.init_formautosubmit',
1501 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1504 // then div wrapper for xhtml strictness
1505 $output = html_writer::tag('div', $output);
1507 // now the form itself around it
1508 if ($select->method === 'get') {
1509 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1510 } else {
1511 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1513 $formattributes = array('method' => $select->method,
1514 'action' => $url,
1515 'id' => $select->formid);
1516 $output = html_writer::tag('form', $output, $formattributes);
1518 // and finally one more wrapper with class
1519 return html_writer::tag('div', $output, array('class' => $select->class));
1523 * Returns a form with a url select widget.
1525 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1526 * @param string $selected selected element
1527 * @param array $nothing
1528 * @param string $formid
1529 * @return string HTML fragment
1531 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1532 $select = new url_select($urls, $selected, $nothing, $formid);
1533 return $this->render($select);
1537 * Internal implementation of url_select rendering
1539 * @param url_select $select
1540 * @return string HTML fragment
1542 protected function render_url_select(url_select $select) {
1543 global $CFG;
1545 $select = clone($select);
1546 if (empty($select->formid)) {
1547 $select->formid = html_writer::random_id('url_select_f');
1550 if (empty($select->attributes['id'])) {
1551 $select->attributes['id'] = html_writer::random_id('url_select');
1554 if ($select->disabled) {
1555 $select->attributes['disabled'] = 'disabled';
1558 if ($select->tooltip) {
1559 $select->attributes['title'] = $select->tooltip;
1562 $output = '';
1564 if ($select->label) {
1565 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1568 $classes = array();
1569 if (!$select->showbutton) {
1570 $classes[] = 'autosubmit';
1572 if ($select->class) {
1573 $classes[] = $select->class;
1575 if (count($classes)) {
1576 $select->attributes['class'] = implode(' ', $classes);
1579 if ($select->helpicon instanceof help_icon) {
1580 $output .= $this->render($select->helpicon);
1581 } else if ($select->helpicon instanceof old_help_icon) {
1582 $output .= $this->render($select->helpicon);
1585 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1586 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1587 $urls = array();
1588 foreach ($select->urls as $k=>$v) {
1589 if (is_array($v)) {
1590 // optgroup structure
1591 foreach ($v as $optgrouptitle => $optgroupoptions) {
1592 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1593 if (empty($optionurl)) {
1594 $safeoptionurl = '';
1595 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1596 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1597 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1598 } else if (strpos($optionurl, '/') !== 0) {
1599 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1600 continue;
1601 } else {
1602 $safeoptionurl = $optionurl;
1604 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1607 } else {
1608 // plain list structure
1609 if (empty($k)) {
1610 // nothing selected option
1611 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1612 $k = str_replace($CFG->wwwroot, '', $k);
1613 } else if (strpos($k, '/') !== 0) {
1614 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1615 continue;
1617 $urls[$k] = $v;
1620 $selected = $select->selected;
1621 if (!empty($selected)) {
1622 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1623 $selected = str_replace($CFG->wwwroot, '', $selected);
1624 } else if (strpos($selected, '/') !== 0) {
1625 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1629 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1630 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1632 if (!$select->showbutton) {
1633 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1634 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1635 $nothing = empty($select->nothing) ? false : key($select->nothing);
1636 $this->page->requires->yui_module('moodle-core-formautosubmit',
1637 'M.core.init_formautosubmit',
1638 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1640 } else {
1641 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1644 // then div wrapper for xhtml strictness
1645 $output = html_writer::tag('div', $output);
1647 // now the form itself around it
1648 $formattributes = array('method' => 'post',
1649 'action' => new moodle_url('/course/jumpto.php'),
1650 'id' => $select->formid);
1651 $output = html_writer::tag('form', $output, $formattributes);
1653 // and finally one more wrapper with class
1654 return html_writer::tag('div', $output, array('class' => $select->class));
1658 * Returns a string containing a link to the user documentation.
1659 * Also contains an icon by default. Shown to teachers and admin only.
1661 * @param string $path The page link after doc root and language, no leading slash.
1662 * @param string $text The text to be displayed for the link
1663 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1664 * @return string
1666 public function doc_link($path, $text = '', $forcepopup = false) {
1667 global $CFG;
1669 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1671 $url = new moodle_url(get_docs_url($path));
1673 $attributes = array('href'=>$url);
1674 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1675 $attributes['class'] = 'helplinkpopup';
1678 return html_writer::tag('a', $icon.$text, $attributes);
1682 * Return HTML for a pix_icon.
1684 * @param string $pix short pix name
1685 * @param string $alt mandatory alt attribute
1686 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1687 * @param array $attributes htm lattributes
1688 * @return string HTML fragment
1690 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1691 $icon = new pix_icon($pix, $alt, $component, $attributes);
1692 return $this->render($icon);
1696 * Renders a pix_icon widget and returns the HTML to display it.
1698 * @param pix_icon $icon
1699 * @return string HTML fragment
1701 protected function render_pix_icon(pix_icon $icon) {
1702 $attributes = $icon->attributes;
1703 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1704 return html_writer::empty_tag('img', $attributes);
1708 * Return HTML to display an emoticon icon.
1710 * @param pix_emoticon $emoticon
1711 * @return string HTML fragment
1713 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1714 $attributes = $emoticon->attributes;
1715 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1716 return html_writer::empty_tag('img', $attributes);
1720 * Produces the html that represents this rating in the UI
1722 * @param rating $rating the page object on which this rating will appear
1723 * @return string
1725 function render_rating(rating $rating) {
1726 global $CFG, $USER;
1728 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1729 return null;//ratings are turned off
1732 $ratingmanager = new rating_manager();
1733 // Initialise the JavaScript so ratings can be done by AJAX.
1734 $ratingmanager->initialise_rating_javascript($this->page);
1736 $strrate = get_string("rate", "rating");
1737 $ratinghtml = ''; //the string we'll return
1739 // permissions check - can they view the aggregate?
1740 if ($rating->user_can_view_aggregate()) {
1742 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1743 $aggregatestr = $rating->get_aggregate_string();
1745 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1746 if ($rating->count > 0) {
1747 $countstr = "({$rating->count})";
1748 } else {
1749 $countstr = '-';
1751 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1753 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1754 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1756 $nonpopuplink = $rating->get_view_ratings_url();
1757 $popuplink = $rating->get_view_ratings_url(true);
1759 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1760 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1761 } else {
1762 $ratinghtml .= $aggregatehtml;
1766 $formstart = null;
1767 // if the item doesn't belong to the current user, the user has permission to rate
1768 // and we're within the assessable period
1769 if ($rating->user_can_rate()) {
1771 $rateurl = $rating->get_rate_url();
1772 $inputs = $rateurl->params();
1774 //start the rating form
1775 $formattrs = array(
1776 'id' => "postrating{$rating->itemid}",
1777 'class' => 'postratingform',
1778 'method' => 'post',
1779 'action' => $rateurl->out_omit_querystring()
1781 $formstart = html_writer::start_tag('form', $formattrs);
1782 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1784 // add the hidden inputs
1785 foreach ($inputs as $name => $value) {
1786 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1787 $formstart .= html_writer::empty_tag('input', $attributes);
1790 if (empty($ratinghtml)) {
1791 $ratinghtml .= $strrate.': ';
1793 $ratinghtml = $formstart.$ratinghtml;
1795 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1796 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1797 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
1798 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1800 //output submit button
1801 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1803 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1804 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1806 if (!$rating->settings->scale->isnumeric) {
1807 // If a global scale, try to find current course ID from the context
1808 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
1809 $courseid = $coursecontext->instanceid;
1810 } else {
1811 $courseid = $rating->settings->scale->courseid;
1813 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
1815 $ratinghtml .= html_writer::end_tag('span');
1816 $ratinghtml .= html_writer::end_tag('div');
1817 $ratinghtml .= html_writer::end_tag('form');
1820 return $ratinghtml;
1824 * Centered heading with attached help button (same title text)
1825 * and optional icon attached.
1827 * @param string $text A heading text
1828 * @param string $helpidentifier The keyword that defines a help page
1829 * @param string $component component name
1830 * @param string|moodle_url $icon
1831 * @param string $iconalt icon alt text
1832 * @return string HTML fragment
1834 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1835 $image = '';
1836 if ($icon) {
1837 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1840 $help = '';
1841 if ($helpidentifier) {
1842 $help = $this->help_icon($helpidentifier, $component);
1845 return $this->heading($image.$text.$help, 2, 'main help');
1849 * Returns HTML to display a help icon.
1851 * @deprecated since Moodle 2.0
1852 * @param string $helpidentifier The keyword that defines a help page
1853 * @param string $title A descriptive text for accessibility only
1854 * @param string $component component name
1855 * @param string|bool $linktext true means use $title as link text, string means link text value
1856 * @return string HTML fragment
1858 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1859 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1860 $icon = new old_help_icon($helpidentifier, $title, $component);
1861 if ($linktext === true) {
1862 $icon->linktext = $title;
1863 } else if (!empty($linktext)) {
1864 $icon->linktext = $linktext;
1866 return $this->render($icon);
1870 * Implementation of user image rendering.
1872 * @param old_help_icon $helpicon A help icon instance
1873 * @return string HTML fragment
1875 protected function render_old_help_icon(old_help_icon $helpicon) {
1876 global $CFG;
1878 // first get the help image icon
1879 $src = $this->pix_url('help');
1881 if (empty($helpicon->linktext)) {
1882 $alt = $helpicon->title;
1883 } else {
1884 $alt = get_string('helpwiththis');
1887 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1888 $output = html_writer::empty_tag('img', $attributes);
1890 // add the link text if given
1891 if (!empty($helpicon->linktext)) {
1892 // the spacing has to be done through CSS
1893 $output .= $helpicon->linktext;
1896 // now create the link around it - we need https on loginhttps pages
1897 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1899 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1900 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1902 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true');
1903 $id = html_writer::random_id('helpicon');
1904 $attributes['id'] = $id;
1905 $output = html_writer::tag('a', $output, $attributes);
1907 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1908 $this->page->requires->string_for_js('close', 'form');
1910 // and finally span
1911 return html_writer::tag('span', $output, array('class' => 'helplink'));
1915 * Returns HTML to display a help icon.
1917 * @param string $identifier The keyword that defines a help page
1918 * @param string $component component name
1919 * @param string|bool $linktext true means use $title as link text, string means link text value
1920 * @return string HTML fragment
1922 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1923 $icon = new help_icon($identifier, $component);
1924 $icon->diag_strings();
1925 if ($linktext === true) {
1926 $icon->linktext = get_string($icon->identifier, $icon->component);
1927 } else if (!empty($linktext)) {
1928 $icon->linktext = $linktext;
1930 return $this->render($icon);
1934 * Implementation of user image rendering.
1936 * @param help_icon $helpicon A help icon instance
1937 * @return string HTML fragment
1939 protected function render_help_icon(help_icon $helpicon) {
1940 global $CFG;
1942 // first get the help image icon
1943 $src = $this->pix_url('help');
1945 $title = get_string($helpicon->identifier, $helpicon->component);
1947 if (empty($helpicon->linktext)) {
1948 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1949 } else {
1950 $alt = get_string('helpwiththis');
1953 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1954 $output = html_writer::empty_tag('img', $attributes);
1956 // add the link text if given
1957 if (!empty($helpicon->linktext)) {
1958 // the spacing has to be done through CSS
1959 $output .= $helpicon->linktext;
1962 // now create the link around it - we need https on loginhttps pages
1963 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1965 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1966 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1968 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true', 'class' => 'tooltip');
1969 $output = html_writer::tag('a', $output, $attributes);
1971 $this->page->requires->js_init_call('M.util.help_icon.setup');
1972 $this->page->requires->string_for_js('close', 'form');
1974 // and finally span
1975 return html_writer::tag('span', $output, array('class' => 'helplink'));
1979 * Returns HTML to display a scale help icon.
1981 * @param int $courseid
1982 * @param stdClass $scale instance
1983 * @return string HTML fragment
1985 public function help_icon_scale($courseid, stdClass $scale) {
1986 global $CFG;
1988 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1990 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1992 $scaleid = abs($scale->id);
1994 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1995 $action = new popup_action('click', $link, 'ratingscale');
1997 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2001 * Creates and returns a spacer image with optional line break.
2003 * @param array $attributes Any HTML attributes to add to the spaced.
2004 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2005 * laxy do it with CSS which is a much better solution.
2006 * @return string HTML fragment
2008 public function spacer(array $attributes = null, $br = false) {
2009 $attributes = (array)$attributes;
2010 if (empty($attributes['width'])) {
2011 $attributes['width'] = 1;
2013 if (empty($attributes['height'])) {
2014 $attributes['height'] = 1;
2016 $attributes['class'] = 'spacer';
2018 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2020 if (!empty($br)) {
2021 $output .= '<br />';
2024 return $output;
2028 * Returns HTML to display the specified user's avatar.
2030 * User avatar may be obtained in two ways:
2031 * <pre>
2032 * // Option 1: (shortcut for simple cases, preferred way)
2033 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2034 * $OUTPUT->user_picture($user, array('popup'=>true));
2036 * // Option 2:
2037 * $userpic = new user_picture($user);
2038 * // Set properties of $userpic
2039 * $userpic->popup = true;
2040 * $OUTPUT->render($userpic);
2041 * </pre>
2043 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2044 * If any of these are missing, the database is queried. Avoid this
2045 * if at all possible, particularly for reports. It is very bad for performance.
2046 * @param array $options associative array with user picture options, used only if not a user_picture object,
2047 * options are:
2048 * - courseid=$this->page->course->id (course id of user profile in link)
2049 * - size=35 (size of image)
2050 * - link=true (make image clickable - the link leads to user profile)
2051 * - popup=false (open in popup)
2052 * - alttext=true (add image alt attribute)
2053 * - class = image class attribute (default 'userpicture')
2054 * @return string HTML fragment
2056 public function user_picture(stdClass $user, array $options = null) {
2057 $userpicture = new user_picture($user);
2058 foreach ((array)$options as $key=>$value) {
2059 if (array_key_exists($key, $userpicture)) {
2060 $userpicture->$key = $value;
2063 return $this->render($userpicture);
2067 * Internal implementation of user image rendering.
2069 * @param user_picture $userpicture
2070 * @return string
2072 protected function render_user_picture(user_picture $userpicture) {
2073 global $CFG, $DB;
2075 $user = $userpicture->user;
2077 if ($userpicture->alttext) {
2078 if (!empty($user->imagealt)) {
2079 $alt = $user->imagealt;
2080 } else {
2081 $alt = get_string('pictureof', '', fullname($user));
2083 } else {
2084 $alt = '';
2087 if (empty($userpicture->size)) {
2088 $size = 35;
2089 } else if ($userpicture->size === true or $userpicture->size == 1) {
2090 $size = 100;
2091 } else {
2092 $size = $userpicture->size;
2095 $class = $userpicture->class;
2097 if ($user->picture == 0) {
2098 $class .= ' defaultuserpic';
2101 $src = $userpicture->get_url($this->page, $this);
2103 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2105 // get the image html output fisrt
2106 $output = html_writer::empty_tag('img', $attributes);;
2108 // then wrap it in link if needed
2109 if (!$userpicture->link) {
2110 return $output;
2113 if (empty($userpicture->courseid)) {
2114 $courseid = $this->page->course->id;
2115 } else {
2116 $courseid = $userpicture->courseid;
2119 if ($courseid == SITEID) {
2120 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2121 } else {
2122 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2125 $attributes = array('href'=>$url);
2127 if ($userpicture->popup) {
2128 $id = html_writer::random_id('userpicture');
2129 $attributes['id'] = $id;
2130 $this->add_action_handler(new popup_action('click', $url), $id);
2133 return html_writer::tag('a', $output, $attributes);
2137 * Internal implementation of file tree viewer items rendering.
2139 * @param array $dir
2140 * @return string
2142 public function htmllize_file_tree($dir) {
2143 if (empty($dir['subdirs']) and empty($dir['files'])) {
2144 return '';
2146 $result = '<ul>';
2147 foreach ($dir['subdirs'] as $subdir) {
2148 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2150 foreach ($dir['files'] as $file) {
2151 $filename = $file->get_filename();
2152 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2154 $result .= '</ul>';
2156 return $result;
2160 * Returns HTML to display the file picker
2162 * <pre>
2163 * $OUTPUT->file_picker($options);
2164 * </pre>
2166 * @param array $options associative array with file manager options
2167 * options are:
2168 * maxbytes=>-1,
2169 * itemid=>0,
2170 * client_id=>uniqid(),
2171 * acepted_types=>'*',
2172 * return_types=>FILE_INTERNAL,
2173 * context=>$PAGE->context
2174 * @return string HTML fragment
2176 public function file_picker($options) {
2177 $fp = new file_picker($options);
2178 return $this->render($fp);
2182 * Internal implementation of file picker rendering.
2184 * @param file_picker $fp
2185 * @return string
2187 public function render_file_picker(file_picker $fp) {
2188 global $CFG, $OUTPUT, $USER;
2189 $options = $fp->options;
2190 $client_id = $options->client_id;
2191 $strsaved = get_string('filesaved', 'repository');
2192 $straddfile = get_string('openpicker', 'repository');
2193 $strloading = get_string('loading', 'repository');
2194 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2195 $strdroptoupload = get_string('droptoupload', 'moodle');
2196 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2198 $currentfile = $options->currentfile;
2199 if (empty($currentfile)) {
2200 $currentfile = '';
2201 } else {
2202 $currentfile .= ' - ';
2204 if ($options->maxbytes) {
2205 $size = $options->maxbytes;
2206 } else {
2207 $size = get_max_upload_file_size();
2209 if ($size == -1) {
2210 $maxsize = '';
2211 } else {
2212 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2214 if ($options->buttonname) {
2215 $buttonname = ' name="' . $options->buttonname . '"';
2216 } else {
2217 $buttonname = '';
2219 $html = <<<EOD
2220 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2221 $icon_progress
2222 </div>
2223 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2224 <div>
2225 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2226 <span> $maxsize </span>
2227 </div>
2228 EOD;
2229 if ($options->env != 'url') {
2230 $html .= <<<EOD
2231 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2232 <div class="filepicker-filename">
2233 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2234 </div>
2235 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2236 </div>
2237 EOD;
2239 $html .= '</div>';
2240 return $html;
2244 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2246 * @param string $cmid the course_module id.
2247 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2248 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2250 public function update_module_button($cmid, $modulename) {
2251 global $CFG;
2252 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2253 $modulename = get_string('modulename', $modulename);
2254 $string = get_string('updatethis', '', $modulename);
2255 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2256 return $this->single_button($url, $string);
2257 } else {
2258 return '';
2263 * Returns HTML to display a "Turn editing on/off" button in a form.
2265 * @param moodle_url $url The URL + params to send through when clicking the button
2266 * @return string HTML the button
2268 public function edit_button(moodle_url $url) {
2270 $url->param('sesskey', sesskey());
2271 if ($this->page->user_is_editing()) {
2272 $url->param('edit', 'off');
2273 $editstring = get_string('turneditingoff');
2274 } else {
2275 $url->param('edit', 'on');
2276 $editstring = get_string('turneditingon');
2279 return $this->single_button($url, $editstring);
2283 * Returns HTML to display a simple button to close a window
2285 * @param string $text The lang string for the button's label (already output from get_string())
2286 * @return string html fragment
2288 public function close_window_button($text='') {
2289 if (empty($text)) {
2290 $text = get_string('closewindow');
2292 $button = new single_button(new moodle_url('#'), $text, 'get');
2293 $button->add_action(new component_action('click', 'close_window'));
2295 return $this->container($this->render($button), 'closewindow');
2299 * Output an error message. By default wraps the error message in <span class="error">.
2300 * If the error message is blank, nothing is output.
2302 * @param string $message the error message.
2303 * @return string the HTML to output.
2305 public function error_text($message) {
2306 if (empty($message)) {
2307 return '';
2309 return html_writer::tag('span', $message, array('class' => 'error'));
2313 * Do not call this function directly.
2315 * To terminate the current script with a fatal error, call the {@link print_error}
2316 * function, or throw an exception. Doing either of those things will then call this
2317 * function to display the error, before terminating the execution.
2319 * @param string $message The message to output
2320 * @param string $moreinfourl URL where more info can be found about the error
2321 * @param string $link Link for the Continue button
2322 * @param array $backtrace The execution backtrace
2323 * @param string $debuginfo Debugging information
2324 * @return string the HTML to output.
2326 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2327 global $CFG;
2329 $output = '';
2330 $obbuffer = '';
2332 if ($this->has_started()) {
2333 // we can not always recover properly here, we have problems with output buffering,
2334 // html tables, etc.
2335 $output .= $this->opencontainers->pop_all_but_last();
2337 } else {
2338 // It is really bad if library code throws exception when output buffering is on,
2339 // because the buffered text would be printed before our start of page.
2340 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2341 error_reporting(0); // disable notices from gzip compression, etc.
2342 while (ob_get_level() > 0) {
2343 $buff = ob_get_clean();
2344 if ($buff === false) {
2345 break;
2347 $obbuffer .= $buff;
2349 error_reporting($CFG->debug);
2351 // Header not yet printed
2352 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2353 // server protocol should be always present, because this render
2354 // can not be used from command line or when outputting custom XML
2355 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2357 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2358 $this->page->set_url('/'); // no url
2359 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2360 $this->page->set_title(get_string('error'));
2361 $this->page->set_heading($this->page->course->fullname);
2362 $output .= $this->header();
2365 $message = '<p class="errormessage">' . $message . '</p>'.
2366 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2367 get_string('moreinformation') . '</a></p>';
2368 if (empty($CFG->rolesactive)) {
2369 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2370 //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.
2372 $output .= $this->box($message, 'errorbox');
2374 if (debugging('', DEBUG_DEVELOPER)) {
2375 if (!empty($debuginfo)) {
2376 $debuginfo = s($debuginfo); // removes all nasty JS
2377 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2378 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2380 if (!empty($backtrace)) {
2381 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2383 if ($obbuffer !== '' ) {
2384 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2388 if (empty($CFG->rolesactive)) {
2389 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2390 } else if (!empty($link)) {
2391 $output .= $this->continue_button($link);
2394 $output .= $this->footer();
2396 // Padding to encourage IE to display our error page, rather than its own.
2397 $output .= str_repeat(' ', 512);
2399 return $output;
2403 * Output a notification (that is, a status message about something that has
2404 * just happened).
2406 * @param string $message the message to print out
2407 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2408 * @return string the HTML to output.
2410 public function notification($message, $classes = 'notifyproblem') {
2411 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2415 * Returns HTML to display a continue button that goes to a particular URL.
2417 * @param string|moodle_url $url The url the button goes to.
2418 * @return string the HTML to output.
2420 public function continue_button($url) {
2421 if (!($url instanceof moodle_url)) {
2422 $url = new moodle_url($url);
2424 $button = new single_button($url, get_string('continue'), 'get');
2425 $button->class = 'continuebutton';
2427 return $this->render($button);
2431 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2433 * @param int $totalcount The total number of entries available to be paged through
2434 * @param int $page The page you are currently viewing
2435 * @param int $perpage The number of entries that should be shown per page
2436 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2437 * @param string $pagevar name of page parameter that holds the page number
2438 * @return string the HTML to output.
2440 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2441 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2442 return $this->render($pb);
2446 * Internal implementation of paging bar rendering.
2448 * @param paging_bar $pagingbar
2449 * @return string
2451 protected function render_paging_bar(paging_bar $pagingbar) {
2452 $output = '';
2453 $pagingbar = clone($pagingbar);
2454 $pagingbar->prepare($this, $this->page, $this->target);
2456 if ($pagingbar->totalcount > $pagingbar->perpage) {
2457 $output .= get_string('page') . ':';
2459 if (!empty($pagingbar->previouslink)) {
2460 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2463 if (!empty($pagingbar->firstlink)) {
2464 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2467 foreach ($pagingbar->pagelinks as $link) {
2468 $output .= "&#160;&#160;$link";
2471 if (!empty($pagingbar->lastlink)) {
2472 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2475 if (!empty($pagingbar->nextlink)) {
2476 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2480 return html_writer::tag('div', $output, array('class' => 'paging'));
2484 * Output the place a skip link goes to.
2486 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2487 * @return string the HTML to output.
2489 public function skip_link_target($id = null) {
2490 return html_writer::tag('span', '', array('id' => $id));
2494 * Outputs a heading
2496 * @param string $text The text of the heading
2497 * @param int $level The level of importance of the heading. Defaulting to 2
2498 * @param string $classes A space-separated list of CSS classes
2499 * @param string $id An optional ID
2500 * @return string the HTML to output.
2502 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2503 $level = (integer) $level;
2504 if ($level < 1 or $level > 6) {
2505 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2507 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2511 * Outputs a box.
2513 * @param string $contents The contents of the box
2514 * @param string $classes A space-separated list of CSS classes
2515 * @param string $id An optional ID
2516 * @return string the HTML to output.
2518 public function box($contents, $classes = 'generalbox', $id = null) {
2519 return $this->box_start($classes, $id) . $contents . $this->box_end();
2523 * Outputs the opening section of a box.
2525 * @param string $classes A space-separated list of CSS classes
2526 * @param string $id An optional ID
2527 * @return string the HTML to output.
2529 public function box_start($classes = 'generalbox', $id = null) {
2530 $this->opencontainers->push('box', html_writer::end_tag('div'));
2531 return html_writer::start_tag('div', array('id' => $id,
2532 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2536 * Outputs the closing section of a box.
2538 * @return string the HTML to output.
2540 public function box_end() {
2541 return $this->opencontainers->pop('box');
2545 * Outputs a container.
2547 * @param string $contents The contents of the box
2548 * @param string $classes A space-separated list of CSS classes
2549 * @param string $id An optional ID
2550 * @return string the HTML to output.
2552 public function container($contents, $classes = null, $id = null) {
2553 return $this->container_start($classes, $id) . $contents . $this->container_end();
2557 * Outputs the opening section of a container.
2559 * @param string $classes A space-separated list of CSS classes
2560 * @param string $id An optional ID
2561 * @return string the HTML to output.
2563 public function container_start($classes = null, $id = null) {
2564 $this->opencontainers->push('container', html_writer::end_tag('div'));
2565 return html_writer::start_tag('div', array('id' => $id,
2566 'class' => renderer_base::prepare_classes($classes)));
2570 * Outputs the closing section of a container.
2572 * @return string the HTML to output.
2574 public function container_end() {
2575 return $this->opencontainers->pop('container');
2579 * Make nested HTML lists out of the items
2581 * The resulting list will look something like this:
2583 * <pre>
2584 * <<ul>>
2585 * <<li>><div class='tree_item parent'>(item contents)</div>
2586 * <<ul>
2587 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2588 * <</ul>>
2589 * <</li>>
2590 * <</ul>>
2591 * </pre>
2593 * @param array $items
2594 * @param array $attrs html attributes passed to the top ofs the list
2595 * @return string HTML
2597 public function tree_block_contents($items, $attrs = array()) {
2598 // exit if empty, we don't want an empty ul element
2599 if (empty($items)) {
2600 return '';
2602 // array of nested li elements
2603 $lis = array();
2604 foreach ($items as $item) {
2605 // this applies to the li item which contains all child lists too
2606 $content = $item->content($this);
2607 $liclasses = array($item->get_css_type());
2608 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2609 $liclasses[] = 'collapsed';
2611 if ($item->isactive === true) {
2612 $liclasses[] = 'current_branch';
2614 $liattr = array('class'=>join(' ',$liclasses));
2615 // class attribute on the div item which only contains the item content
2616 $divclasses = array('tree_item');
2617 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2618 $divclasses[] = 'branch';
2619 } else {
2620 $divclasses[] = 'leaf';
2622 if (!empty($item->classes) && count($item->classes)>0) {
2623 $divclasses[] = join(' ', $item->classes);
2625 $divattr = array('class'=>join(' ', $divclasses));
2626 if (!empty($item->id)) {
2627 $divattr['id'] = $item->id;
2629 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2630 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2631 $content = html_writer::empty_tag('hr') . $content;
2633 $content = html_writer::tag('li', $content, $liattr);
2634 $lis[] = $content;
2636 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2640 * Return the navbar content so that it can be echoed out by the layout
2642 * @return string XHTML navbar
2644 public function navbar() {
2645 $items = $this->page->navbar->get_items();
2647 $htmlblocks = array();
2648 // Iterate the navarray and display each node
2649 $itemcount = count($items);
2650 $separator = get_separator();
2651 for ($i=0;$i < $itemcount;$i++) {
2652 $item = $items[$i];
2653 $item->hideicon = true;
2654 if ($i===0) {
2655 $content = html_writer::tag('li', $this->render($item));
2656 } else {
2657 $content = html_writer::tag('li', $separator.$this->render($item));
2659 $htmlblocks[] = $content;
2662 //accessibility: heading for navbar list (MDL-20446)
2663 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2664 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2665 // XHTML
2666 return $navbarcontent;
2670 * Renders a navigation node object.
2672 * @param navigation_node $item The navigation node to render.
2673 * @return string HTML fragment
2675 protected function render_navigation_node(navigation_node $item) {
2676 $content = $item->get_content();
2677 $title = $item->get_title();
2678 if ($item->icon instanceof renderable && !$item->hideicon) {
2679 $icon = $this->render($item->icon);
2680 $content = $icon.$content; // use CSS for spacing of icons
2682 if ($item->helpbutton !== null) {
2683 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2685 if ($content === '') {
2686 return '';
2688 if ($item->action instanceof action_link) {
2689 $link = $item->action;
2690 if ($item->hidden) {
2691 $link->add_class('dimmed');
2693 if (!empty($content)) {
2694 // Providing there is content we will use that for the link content.
2695 $link->text = $content;
2697 $content = $this->render($link);
2698 } else if ($item->action instanceof moodle_url) {
2699 $attributes = array();
2700 if ($title !== '') {
2701 $attributes['title'] = $title;
2703 if ($item->hidden) {
2704 $attributes['class'] = 'dimmed_text';
2706 $content = html_writer::link($item->action, $content, $attributes);
2708 } else if (is_string($item->action) || empty($item->action)) {
2709 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2710 if ($title !== '') {
2711 $attributes['title'] = $title;
2713 if ($item->hidden) {
2714 $attributes['class'] = 'dimmed_text';
2716 $content = html_writer::tag('span', $content, $attributes);
2718 return $content;
2722 * Accessibility: Right arrow-like character is
2723 * used in the breadcrumb trail, course navigation menu
2724 * (previous/next activity), calendar, and search forum block.
2725 * If the theme does not set characters, appropriate defaults
2726 * are set automatically. Please DO NOT
2727 * use &lt; &gt; &raquo; - these are confusing for blind users.
2729 * @return string
2731 public function rarrow() {
2732 return $this->page->theme->rarrow;
2736 * Accessibility: Right arrow-like character is
2737 * used in the breadcrumb trail, course navigation menu
2738 * (previous/next activity), calendar, and search forum block.
2739 * If the theme does not set characters, appropriate defaults
2740 * are set automatically. Please DO NOT
2741 * use &lt; &gt; &raquo; - these are confusing for blind users.
2743 * @return string
2745 public function larrow() {
2746 return $this->page->theme->larrow;
2750 * Returns the custom menu if one has been set
2752 * A custom menu can be configured by browsing to
2753 * Settings: Administration > Appearance > Themes > Theme settings
2754 * and then configuring the custommenu config setting as described.
2756 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2757 * @return string
2759 public function custom_menu($custommenuitems = '') {
2760 global $CFG;
2761 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2762 $custommenuitems = $CFG->custommenuitems;
2764 if (empty($custommenuitems)) {
2765 return '';
2767 $custommenu = new custom_menu($custommenuitems, current_language());
2768 return $this->render_custom_menu($custommenu);
2772 * Renders a custom menu object (located in outputcomponents.php)
2774 * The custom menu this method produces makes use of the YUI3 menunav widget
2775 * and requires very specific html elements and classes.
2777 * @staticvar int $menucount
2778 * @param custom_menu $menu
2779 * @return string
2781 protected function render_custom_menu(custom_menu $menu) {
2782 static $menucount = 0;
2783 // If the menu has no children return an empty string
2784 if (!$menu->has_children()) {
2785 return '';
2787 // Increment the menu count. This is used for ID's that get worked with
2788 // in JavaScript as is essential
2789 $menucount++;
2790 // Initialise this custom menu (the custom menu object is contained in javascript-static
2791 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2792 $jscode = "(function(){{$jscode}})";
2793 $this->page->requires->yui_module('node-menunav', $jscode);
2794 // Build the root nodes as required by YUI
2795 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2796 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2797 $content .= html_writer::start_tag('ul');
2798 // Render each child
2799 foreach ($menu->get_children() as $item) {
2800 $content .= $this->render_custom_menu_item($item);
2802 // Close the open tags
2803 $content .= html_writer::end_tag('ul');
2804 $content .= html_writer::end_tag('div');
2805 $content .= html_writer::end_tag('div');
2806 // Return the custom menu
2807 return $content;
2811 * Renders a custom menu node as part of a submenu
2813 * The custom menu this method produces makes use of the YUI3 menunav widget
2814 * and requires very specific html elements and classes.
2816 * @see core:renderer::render_custom_menu()
2818 * @staticvar int $submenucount
2819 * @param custom_menu_item $menunode
2820 * @return string
2822 protected function render_custom_menu_item(custom_menu_item $menunode) {
2823 // Required to ensure we get unique trackable id's
2824 static $submenucount = 0;
2825 if ($menunode->has_children()) {
2826 // If the child has menus render it as a sub menu
2827 $submenucount++;
2828 $content = html_writer::start_tag('li');
2829 if ($menunode->get_url() !== null) {
2830 $url = $menunode->get_url();
2831 } else {
2832 $url = '#cm_submenu_'.$submenucount;
2834 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2835 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2836 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2837 $content .= html_writer::start_tag('ul');
2838 foreach ($menunode->get_children() as $menunode) {
2839 $content .= $this->render_custom_menu_item($menunode);
2841 $content .= html_writer::end_tag('ul');
2842 $content .= html_writer::end_tag('div');
2843 $content .= html_writer::end_tag('div');
2844 $content .= html_writer::end_tag('li');
2845 } else {
2846 // The node doesn't have children so produce a final menuitem
2847 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2848 if ($menunode->get_url() !== null) {
2849 $url = $menunode->get_url();
2850 } else {
2851 $url = '#';
2853 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2854 $content .= html_writer::end_tag('li');
2856 // Return the sub menu
2857 return $content;
2861 * Renders theme links for switching between default and other themes.
2863 * @return string
2865 protected function theme_switch_links() {
2867 $actualdevice = get_device_type();
2868 $currentdevice = $this->page->devicetypeinuse;
2869 $switched = ($actualdevice != $currentdevice);
2871 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2872 // The user is using the a default device and hasn't switched so don't shown the switch
2873 // device links.
2874 return '';
2877 if ($switched) {
2878 $linktext = get_string('switchdevicerecommended');
2879 $devicetype = $actualdevice;
2880 } else {
2881 $linktext = get_string('switchdevicedefault');
2882 $devicetype = 'default';
2884 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2886 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2887 $content .= html_writer::link($linkurl, $linktext);
2888 $content .= html_writer::end_tag('div');
2890 return $content;
2895 * A renderer that generates output for command-line scripts.
2897 * The implementation of this renderer is probably incomplete.
2899 * @copyright 2009 Tim Hunt
2900 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2901 * @since Moodle 2.0
2902 * @package core
2903 * @category output
2905 class core_renderer_cli extends core_renderer {
2908 * Returns the page header.
2910 * @return string HTML fragment
2912 public function header() {
2913 return $this->page->heading . "\n";
2917 * Returns a template fragment representing a Heading.
2919 * @param string $text The text of the heading
2920 * @param int $level The level of importance of the heading
2921 * @param string $classes A space-separated list of CSS classes
2922 * @param string $id An optional ID
2923 * @return string A template fragment for a heading
2925 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2926 $text .= "\n";
2927 switch ($level) {
2928 case 1:
2929 return '=>' . $text;
2930 case 2:
2931 return '-->' . $text;
2932 default:
2933 return $text;
2938 * Returns a template fragment representing a fatal error.
2940 * @param string $message The message to output
2941 * @param string $moreinfourl URL where more info can be found about the error
2942 * @param string $link Link for the Continue button
2943 * @param array $backtrace The execution backtrace
2944 * @param string $debuginfo Debugging information
2945 * @return string A template fragment for a fatal error
2947 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2948 $output = "!!! $message !!!\n";
2950 if (debugging('', DEBUG_DEVELOPER)) {
2951 if (!empty($debuginfo)) {
2952 $output .= $this->notification($debuginfo, 'notifytiny');
2954 if (!empty($backtrace)) {
2955 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2959 return $output;
2963 * Returns a template fragment representing a notification.
2965 * @param string $message The message to include
2966 * @param string $classes A space-separated list of CSS classes
2967 * @return string A template fragment for a notification
2969 public function notification($message, $classes = 'notifyproblem') {
2970 $message = clean_text($message);
2971 if ($classes === 'notifysuccess') {
2972 return "++ $message ++\n";
2974 return "!! $message !!\n";
2980 * A renderer that generates output for ajax scripts.
2982 * This renderer prevents accidental sends back only json
2983 * encoded error messages, all other output is ignored.
2985 * @copyright 2010 Petr Skoda
2986 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2987 * @since Moodle 2.0
2988 * @package core
2989 * @category output
2991 class core_renderer_ajax extends core_renderer {
2994 * Returns a template fragment representing a fatal error.
2996 * @param string $message The message to output
2997 * @param string $moreinfourl URL where more info can be found about the error
2998 * @param string $link Link for the Continue button
2999 * @param array $backtrace The execution backtrace
3000 * @param string $debuginfo Debugging information
3001 * @return string A template fragment for a fatal error
3003 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3004 global $CFG;
3006 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3008 $e = new stdClass();
3009 $e->error = $message;
3010 $e->stacktrace = NULL;
3011 $e->debuginfo = NULL;
3012 $e->reproductionlink = NULL;
3013 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3014 $e->reproductionlink = $link;
3015 if (!empty($debuginfo)) {
3016 $e->debuginfo = $debuginfo;
3018 if (!empty($backtrace)) {
3019 $e->stacktrace = format_backtrace($backtrace, true);
3022 $this->header();
3023 return json_encode($e);
3027 * Used to display a notification.
3028 * For the AJAX notifications are discarded.
3030 * @param string $message
3031 * @param string $classes
3033 public function notification($message, $classes = 'notifyproblem') {}
3036 * Used to display a redirection message.
3037 * AJAX redirections should not occur and as such redirection messages
3038 * are discarded.
3040 * @param moodle_url|string $encodedurl
3041 * @param string $message
3042 * @param int $delay
3043 * @param bool $debugdisableredirect
3045 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3048 * Prepares the start of an AJAX output.
3050 public function header() {
3051 // unfortunately YUI iframe upload does not support application/json
3052 if (!empty($_FILES)) {
3053 @header('Content-type: text/plain; charset=utf-8');
3054 } else {
3055 @header('Content-type: application/json; charset=utf-8');
3058 // Headers to make it not cacheable and json
3059 @header('Cache-Control: no-store, no-cache, must-revalidate');
3060 @header('Cache-Control: post-check=0, pre-check=0', false);
3061 @header('Pragma: no-cache');
3062 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3063 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3064 @header('Accept-Ranges: none');
3068 * There is no footer for an AJAX request, however we must override the
3069 * footer method to prevent the default footer.
3071 public function footer() {}
3074 * No need for headers in an AJAX request... this should never happen.
3075 * @param string $text
3076 * @param int $level
3077 * @param string $classes
3078 * @param string $id
3080 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3085 * Renderer for media files.
3087 * Used in file resources, media filter, and any other places that need to
3088 * output embedded media.
3090 * @copyright 2011 The Open University
3091 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3093 class core_media_renderer extends plugin_renderer_base {
3094 /** @var array Array of available 'player' objects */
3095 private $players;
3096 /** @var string Regex pattern for links which may contain embeddable content */
3097 private $embeddablemarkers;
3100 * Constructor requires medialib.php.
3102 * This is needed in the constructor (not later) so that you can use the
3103 * constants and static functions that are defined in core_media class
3104 * before you call renderer functions.
3106 public function __construct() {
3107 global $CFG;
3108 require_once($CFG->libdir . '/medialib.php');
3112 * Obtains the list of core_media_player objects currently in use to render
3113 * items.
3115 * The list is in rank order (highest first) and does not include players
3116 * which are disabled.
3118 * @return array Array of core_media_player objects in rank order
3120 protected function get_players() {
3121 global $CFG;
3123 // Save time by only building the list once.
3124 if (!$this->players) {
3125 // Get raw list of players.
3126 $players = $this->get_players_raw();
3128 // Chuck all the ones that are disabled.
3129 foreach ($players as $key => $player) {
3130 if (!$player->is_enabled()) {
3131 unset($players[$key]);
3135 // Sort in rank order (highest first).
3136 usort($players, array('core_media_player', 'compare_by_rank'));
3137 $this->players = $players;
3139 return $this->players;
3143 * Obtains a raw list of player objects that includes objects regardless
3144 * of whether they are disabled or not, and without sorting.
3146 * You can override this in a subclass if you need to add additional
3147 * players.
3149 * The return array is be indexed by player name to make it easier to
3150 * remove players in a subclass.
3152 * @return array $players Array of core_media_player objects in any order
3154 protected function get_players_raw() {
3155 return array(
3156 'vimeo' => new core_media_player_vimeo(),
3157 'youtube' => new core_media_player_youtube(),
3158 'youtube_playlist' => new core_media_player_youtube_playlist(),
3159 'html5video' => new core_media_player_html5video(),
3160 'html5audio' => new core_media_player_html5audio(),
3161 'mp3' => new core_media_player_mp3(),
3162 'flv' => new core_media_player_flv(),
3163 'wmp' => new core_media_player_wmp(),
3164 'qt' => new core_media_player_qt(),
3165 'rm' => new core_media_player_rm(),
3166 'swf' => new core_media_player_swf(),
3167 'link' => new core_media_player_link(),
3172 * Renders a media file (audio or video) using suitable embedded player.
3174 * See embed_alternatives function for full description of parameters.
3175 * This function calls through to that one.
3177 * When using this function you can also specify width and height in the
3178 * URL by including ?d=100x100 at the end. If specified in the URL, this
3179 * will override the $width and $height parameters.
3181 * @param moodle_url $url Full URL of media file
3182 * @param string $name Optional user-readable name to display in download link
3183 * @param int $width Width in pixels (optional)
3184 * @param int $height Height in pixels (optional)
3185 * @param array $options Array of key/value pairs
3186 * @return string HTML content of embed
3188 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3189 $options = array()) {
3191 // Get width and height from URL if specified (overrides parameters in
3192 // function call).
3193 $rawurl = $url->out(false);
3194 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3195 $width = $matches[1];
3196 $height = $matches[2];
3197 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3200 // Defer to array version of function.
3201 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3205 * Renders media files (audio or video) using suitable embedded player.
3206 * The list of URLs should be alternative versions of the same content in
3207 * multiple formats. If there is only one format it should have a single
3208 * entry.
3210 * If the media files are not in a supported format, this will give students
3211 * a download link to each format. The download link uses the filename
3212 * unless you supply the optional name parameter.
3214 * Width and height are optional. If specified, these are suggested sizes
3215 * and should be the exact values supplied by the user, if they come from
3216 * user input. These will be treated as relating to the size of the video
3217 * content, not including any player control bar.
3219 * For audio files, height will be ignored. For video files, a few formats
3220 * work if you specify only width, but in general if you specify width
3221 * you must specify height as well.
3223 * The $options array is passed through to the core_media_player classes
3224 * that render the object tag. The keys can contain values from
3225 * core_media::OPTION_xx.
3227 * @param array $alternatives Array of moodle_url to media files
3228 * @param string $name Optional user-readable name to display in download link
3229 * @param int $width Width in pixels (optional)
3230 * @param int $height Height in pixels (optional)
3231 * @param array $options Array of key/value pairs
3232 * @return string HTML content of embed
3234 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3235 $options = array()) {
3237 // Get list of player plugins (will also require the library).
3238 $players = $this->get_players();
3240 // Set up initial text which will be replaced by first player that
3241 // supports any of the formats.
3242 $out = core_media_player::PLACEHOLDER;
3244 // Loop through all players that support any of these URLs.
3245 foreach ($players as $player) {
3246 // Option: When no other player matched, don't do the default link player.
3247 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3248 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3249 continue;
3252 $supported = $player->list_supported_urls($alternatives, $options);
3253 if ($supported) {
3254 // Embed.
3255 $text = $player->embed($supported, $name, $width, $height, $options);
3257 // Put this in place of the 'fallback' slot in the previous text.
3258 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3262 // Remove 'fallback' slot from final version and return it.
3263 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3264 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3265 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3267 return $out;
3271 * Checks whether a file can be embedded. If this returns true you will get
3272 * an embedded player; if this returns false, you will just get a download
3273 * link.
3275 * This is a wrapper for can_embed_urls.
3277 * @param moodle_url $url URL of media file
3278 * @param array $options Options (same as when embedding)
3279 * @return bool True if file can be embedded
3281 public function can_embed_url(moodle_url $url, $options = array()) {
3282 return $this->can_embed_urls(array($url), $options);
3286 * Checks whether a file can be embedded. If this returns true you will get
3287 * an embedded player; if this returns false, you will just get a download
3288 * link.
3290 * @param array $urls URL of media file and any alternatives (moodle_url)
3291 * @param array $options Options (same as when embedding)
3292 * @return bool True if file can be embedded
3294 public function can_embed_urls(array $urls, $options = array()) {
3295 // Check all players to see if any of them support it.
3296 foreach ($this->get_players() as $player) {
3297 // Link player (always last on list) doesn't count!
3298 if ($player->get_rank() <= 0) {
3299 break;
3301 // First player that supports it, return true.
3302 if ($player->list_supported_urls($urls, $options)) {
3303 return true;
3306 return false;
3310 * Obtains a list of markers that can be used in a regular expression when
3311 * searching for URLs that can be embedded by any player type.
3313 * This string is used to improve peformance of regex matching by ensuring
3314 * that the (presumably C) regex code can do a quick keyword check on the
3315 * URL part of a link to see if it matches one of these, rather than having
3316 * to go into PHP code for every single link to see if it can be embedded.
3318 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3320 public function get_embeddable_markers() {
3321 if (empty($this->embeddablemarkers)) {
3322 $markers = '';
3323 foreach ($this->get_players() as $player) {
3324 foreach ($player->get_embeddable_markers() as $marker) {
3325 if ($markers !== '') {
3326 $markers .= '|';
3328 $markers .= preg_quote($marker);
3331 $this->embeddablemarkers = $markers;
3333 return $this->embeddablemarkers;