3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Classes for rendering HTML output for Moodle.
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 * Simple base class for Moodle renderers.
32 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
34 * Also has methods to facilitate generating HTML output.
36 * @copyright 2009 Tim Hunt
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 /** @var xhtml_container_stack the xhtml_container_stack to use. */
42 protected $opencontainers;
43 /** @var moodle_page the page we are rendering for. */
45 /** @var requested rendering target */
50 * @param moodle_page $page the page we are doing output for.
51 * @param string $target one of rendering target constants
53 public function __construct(moodle_page $page, $target) {
54 $this->opencontainers = $page->opencontainers;
56 $this->target = $target;
60 * Returns rendered widget.
61 * @param renderable $widget instance with renderable interface
64 public function render(renderable $widget) {
65 $rendermethod = 'render_'.get_class($widget);
66 if (method_exists($this, $rendermethod)) {
67 return $this->$rendermethod($widget);
69 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
73 * Adds JS handlers needed for event execution for one html element id
74 * @param component_action $actions
76 * @return string id of element, either original submitted or random new if not supplied
78 public function add_action_handler(component_action $action, $id=null) {
80 $id = html_writer::random_id($action->event);
82 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
87 * Have we started output yet?
88 * @return boolean true if the header has been printed.
90 public function has_started() {
91 return $this->page->state >= moodle_page::STATE_IN_BODY;
95 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
96 * @param mixed $classes Space-separated string or array of classes
97 * @return string HTML class attribute value
99 public static function prepare_classes($classes) {
100 if (is_array($classes)) {
101 return implode(' ', array_unique($classes));
107 * Return the moodle_url for an image.
108 * The exact image location and extension is determined
109 * automatically by searching for gif|png|jpg|jpeg, please
110 * note there can not be diferent images with the different
111 * extension. The imagename is for historical reasons
112 * a relative path name, it may be changed later for core
113 * images. It is recommended to not use subdirectories
114 * in plugin and theme pix directories.
116 * There are three types of images:
117 * 1/ theme images - stored in theme/mytheme/pix/,
118 * use component 'theme'
119 * 2/ core images - stored in /pix/,
120 * overridden via theme/mytheme/pix_core/
121 * 3/ plugin images - stored in mod/mymodule/pix,
122 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
123 * example: pix_url('comment', 'mod_glossary')
125 * @param string $imagename the pathname of the image
126 * @param string $component full plugin name (aka component) or 'theme'
129 public function pix_url($imagename, $component = 'moodle') {
130 return $this->page->theme->pix_url($imagename, $component);
136 * Basis for all plugin renderers.
138 * @author Petr Skoda (skodak)
139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
142 class plugin_renderer_base extends renderer_base {
144 * A reference to the current general renderer probably {@see core_renderer}
150 * Constructor method, calls the parent constructor
151 * @param moodle_page $page
152 * @param string $target one of rendering target constants
154 public function __construct(moodle_page $page, $target) {
155 $this->output = $page->get_renderer('core', null, $target);
156 parent::__construct($page, $target);
160 * Returns rendered widget.
161 * @param renderable $widget instance with renderable interface
164 public function render(renderable $widget) {
165 $rendermethod = 'render_'.get_class($widget);
166 if (method_exists($this, $rendermethod)) {
167 return $this->$rendermethod($widget);
169 // pass to core renderer if method not found here
170 return $this->output->render($widget);
174 * Magic method used to pass calls otherwise meant for the standard renderer
175 * to it to ensure we don't go causing unnecessary grief.
177 * @param string $method
178 * @param array $arguments
181 public function __call($method, $arguments) {
182 if (method_exists('renderer_base', $method)) {
183 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
185 if (method_exists($this->output, $method)) {
186 return call_user_func_array(array($this->output, $method), $arguments);
188 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
195 * The standard implementation of the core_renderer interface.
197 * @copyright 2009 Tim Hunt
198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
201 class core_renderer extends renderer_base {
202 /** @var string used in {@link header()}. */
203 const PERFORMANCE_INFO_TOKEN = '%%PERFORMANCEINFO%%';
204 /** @var string used in {@link header()}. */
205 const END_HTML_TOKEN = '%%ENDHTML%%';
206 /** @var string used in {@link header()}. */
207 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
208 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
209 protected $contenttype;
210 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
211 protected $metarefreshtag = '';
214 * Get the DOCTYPE declaration that should be used with this page. Designed to
215 * be called in theme layout.php files.
216 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
218 public function doctype() {
221 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
222 $this->contenttype = 'text/html; charset=utf-8';
224 if (empty($CFG->xmlstrictheaders)) {
228 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
229 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
230 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
231 // Firefox and other browsers that can cope natively with XHTML.
232 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
234 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
235 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
236 $this->contenttype = 'application/xml; charset=utf-8';
237 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
243 return $prolog . $doctype;
247 * The attributes that should be added to the <html> tag. Designed to
248 * be called in theme layout.php files.
249 * @return string HTML fragment.
251 public function htmlattributes() {
252 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
256 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
257 * that should be included in the <head> tag. Designed to be called in theme
259 * @return string HTML fragment.
261 public function standard_head_html() {
262 global $CFG, $SESSION;
264 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
265 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
266 if (!$this->page->cacheable) {
267 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
268 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
270 // This is only set by the {@link redirect()} method
271 $output .= $this->metarefreshtag;
273 // Check if a periodic refresh delay has been set and make sure we arn't
274 // already meta refreshing
275 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
276 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
279 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
281 $focus = $this->page->focuscontrol;
282 if (!empty($focus)) {
283 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
284 // This is a horrifically bad way to handle focus but it is passed in
285 // through messy formslib::moodleform
286 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
287 } else if (strpos($focus, '.')!==false) {
288 // Old style of focus, bad way to do it
289 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);
290 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
292 // Focus element with given id
293 $this->page->requires->js_function_call('focuscontrol', array($focus));
297 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
298 // any other custom CSS can not be overridden via themes and is highly discouraged
299 $urls = $this->page->theme->css_urls($this->page);
300 foreach ($urls as $url) {
301 $this->page->requires->css_theme($url);
304 // Get the theme javascript head and footer
305 $jsurl = $this->page->theme->javascript_url(true);
306 $this->page->requires->js($jsurl, true);
307 $jsurl = $this->page->theme->javascript_url(false);
308 $this->page->requires->js($jsurl);
310 // Perform a browser environment check for the flash version. Should only run once per login session.
311 if (!NO_MOODLE_COOKIES && isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
312 $this->page->requires->js('/lib/swfobject/swfobject.js');
313 $this->page->requires->js_init_call('M.core_flashdetect.init');
316 // Get any HTML from the page_requirements_manager.
317 $output .= $this->page->requires->get_head_code($this->page, $this);
319 // List alternate versions.
320 foreach ($this->page->alternateversions as $type => $alt) {
321 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
322 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
329 * The standard tags (typically skip links) that should be output just inside
330 * the start of the <body> tag. Designed to be called in theme layout.php files.
331 * @return string HTML fragment.
333 public function standard_top_of_body_html() {
334 return $this->page->requires->get_top_of_body_code();
338 * The standard tags (typically performance information and validation links,
339 * if we are in developer debug mode) that should be output in the footer area
340 * of the page. Designed to be called in theme layout.php files.
341 * @return string HTML fragment.
343 public function standard_footer_html() {
346 // This function is normally called from a layout.php file in {@link header()}
347 // but some of the content won't be known until later, so we return a placeholder
348 // for now. This will be replaced with the real content in {@link footer()}.
349 $output = self::PERFORMANCE_INFO_TOKEN;
350 if ($this->page->legacythemeinuse) {
351 // The legacy theme is in use print the notification
352 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
354 if (!empty($CFG->debugpageinfo)) {
355 $output .= '<div class="performanceinfo">This page is: ' . $this->page->debug_summary() . '</div>';
357 if (!empty($CFG->debugvalidators)) {
358 $output .= '<div class="validators"><ul>
359 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
360 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
361 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
368 * The standard tags (typically script tags that are not needed earlier) that
369 * should be output after everything else, . Designed to be called in theme layout.php files.
370 * @return string HTML fragment.
372 public function standard_end_of_body_html() {
373 // This function is normally called from a layout.php file in {@link header()}
374 // but some of the content won't be known until later, so we return a placeholder
375 // for now. This will be replaced with the real content in {@link footer()}.
376 echo self::END_HTML_TOKEN;
380 * Return the standard string that says whether you are logged in (and switched
381 * roles/logged in as another user).
382 * @return string HTML fragment.
384 public function login_info() {
385 global $USER, $CFG, $DB;
387 if (during_initial_install()) {
391 $course = $this->page->course;
393 if (session_is_loggedinas()) {
394 $realuser = session_get_realuser();
395 $fullname = fullname($realuser, true);
396 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
401 $loginurl = get_login_url();
403 if (empty($course->id)) {
404 // $course->id is not defined during installation
406 } else if (isloggedin()) {
407 $context = get_context_instance(CONTEXT_COURSE, $course->id);
409 $fullname = fullname($USER, true);
410 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
411 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
412 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
413 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
415 if (isset($USER->username) && $USER->username == 'guest') {
416 $loggedinas = $realuserinfo.get_string('loggedinasguest').
417 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
418 } else if (!empty($USER->access['rsw'][$context->path])) {
420 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
421 $rolename = ': '.format_string($role->name);
423 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
424 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
426 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
427 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
430 $loggedinas = get_string('loggedinnot', 'moodle').
431 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
434 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
436 if (isset($SESSION->justloggedin)) {
437 unset($SESSION->justloggedin);
438 if (!empty($CFG->displayloginfailures)) {
439 if (!empty($USER->username) and $USER->username != 'guest') {
440 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
441 $loggedinas .= ' <div class="loginfailures">';
442 if (empty($count->accounts)) {
443 $loggedinas .= get_string('failedloginattempts', '', $count);
445 $loggedinas .= get_string('failedloginattemptsall', '', $count);
447 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
448 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
449 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
451 $loggedinas .= '</div>';
461 * Return the 'back' link that normally appears in the footer.
462 * @return string HTML fragment.
464 public function home_link() {
467 if ($this->page->pagetype == 'site-index') {
468 // Special case for site home page - please do not remove
469 return '<div class="sitelink">' .
470 '<a title="Moodle" href="http://moodle.org/">' .
471 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
473 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
474 // Special case for during install/upgrade.
475 return '<div class="sitelink">'.
476 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
477 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
479 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
480 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
481 get_string('home') . '</a></div>';
484 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
485 format_string($this->page->course->shortname) . '</a></div>';
490 * Redirects the user by any means possible given the current state
492 * This function should not be called directly, it should always be called using
493 * the redirect function in lib/weblib.php
495 * The redirect function should really only be called before page output has started
496 * however it will allow itself to be called during the state STATE_IN_BODY
498 * @param string $encodedurl The URL to send to encoded if required
499 * @param string $message The message to display to the user if any
500 * @param int $delay The delay before redirecting a user, if $message has been
501 * set this is a requirement and defaults to 3, set to 0 no delay
502 * @param boolean $debugdisableredirect this redirect has been disabled for
503 * debugging purposes. Display a message that explains, and don't
504 * trigger the redirect.
505 * @return string The HTML to display to the user before dying, may contain
506 * meta refresh, javascript refresh, and may have set header redirects
508 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
510 $url = str_replace('&', '&', $encodedurl);
512 switch ($this->page->state) {
513 case moodle_page::STATE_BEFORE_HEADER :
514 // No output yet it is safe to delivery the full arsenal of redirect methods
515 if (!$debugdisableredirect) {
516 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
517 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
518 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
520 $output = $this->header();
522 case moodle_page::STATE_PRINTING_HEADER :
523 // We should hopefully never get here
524 throw new coding_exception('You cannot redirect while printing the page header');
526 case moodle_page::STATE_IN_BODY :
527 // We really shouldn't be here but we can deal with this
528 debugging("You should really redirect before you start page output");
529 if (!$debugdisableredirect) {
530 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
532 $output = $this->opencontainers->pop_all_but_last();
534 case moodle_page::STATE_DONE :
535 // Too late to be calling redirect now
536 throw new coding_exception('You cannot redirect after the entire page has been generated');
539 $output .= $this->notification($message, 'redirectmessage');
540 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
541 if ($debugdisableredirect) {
542 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
544 $output .= $this->footer();
549 * Start output by sending the HTTP headers, and printing the HTML <head>
550 * and the start of the <body>.
552 * To control what is printed, you should set properties on $PAGE. If you
553 * are familiar with the old {@link print_header()} function from Moodle 1.9
554 * you will find that there are properties on $PAGE that correspond to most
555 * of the old parameters to could be passed to print_header.
557 * Not that, in due course, the remaining $navigation, $menu parameters here
558 * will be replaced by more properties of $PAGE, but that is still to do.
560 * @return string HTML that you must output this, preferably immediately.
562 public function header() {
565 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
567 // Find the appropriate page layout file, based on $this->page->pagelayout.
568 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
569 // Render the layout using the layout file.
570 $rendered = $this->render_page_layout($layoutfile);
572 // Slice the rendered output into header and footer.
573 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
574 if ($cutpos === false) {
575 throw new coding_exception('page layout file ' . $layoutfile .
576 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
578 $header = substr($rendered, 0, $cutpos);
579 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
581 if (empty($this->contenttype)) {
582 debugging('The page layout file did not call $OUTPUT->doctype()');
583 $header = $this->doctype() . $header;
586 send_headers($this->contenttype, $this->page->cacheable);
588 $this->opencontainers->push('header/footer', $footer);
589 $this->page->set_state(moodle_page::STATE_IN_BODY);
591 return $header . $this->skip_link_target('maincontent');
595 * Renders and outputs the page layout file.
596 * @param string $layoutfile The name of the layout file
597 * @return string HTML code
599 protected function render_page_layout($layoutfile) {
600 global $CFG, $SITE, $USER;
601 // The next lines are a bit tricky. The point is, here we are in a method
602 // of a renderer class, and this object may, or may not, be the same as
603 // the global $OUTPUT object. When rendering the page layout file, we want to use
604 // this object. However, people writing Moodle code expect the current
605 // renderer to be called $OUTPUT, not $this, so define a variable called
606 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
609 $COURSE = $this->page->course;
612 include($layoutfile);
613 $rendered = ob_get_contents();
619 * Outputs the page's footer
620 * @return string HTML fragment
622 public function footer() {
625 $output = $this->container_end_all(true);
627 $footer = $this->opencontainers->pop('header/footer');
629 if (debugging() and $DB and $DB->is_transaction_started()) {
630 // TODO: MDL-20625 print warning - transaction will be rolled back
633 // Provide some performance info if required
634 $performanceinfo = '';
635 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
636 $perf = get_performance_info();
637 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
638 error_log("PERF: " . $perf['txt']);
640 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
641 $performanceinfo = $perf['html'];
644 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
646 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
648 $this->page->set_state(moodle_page::STATE_DONE);
650 return $output . $footer;
654 * Close all but the last open container. This is useful in places like error
655 * handling, where you want to close all the open containers (apart from <body>)
656 * before outputting the error message.
657 * @param bool $shouldbenone assert that the stack should be empty now - causes a
658 * developer debug warning if it isn't.
659 * @return string the HTML required to close any open containers inside <body>.
661 public function container_end_all($shouldbenone = false) {
662 return $this->opencontainers->pop_all_but_last($shouldbenone);
666 * Returns lang menu or '', this method also checks forcing of languages in courses.
669 public function lang_menu() {
672 if (empty($CFG->langmenu)) {
676 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
677 // do not show lang menu if language forced
681 $currlang = current_language();
682 $langs = get_string_manager()->get_list_of_translations();
684 if (count($langs) < 2) {
688 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
689 $s->label = get_accesshide(get_string('language'));
690 $s->class = 'langmenu';
691 return $this->render($s);
695 * Output the row of editing icons for a block, as defined by the controls array.
696 * @param array $controls an array like {@link block_contents::$controls}.
697 * @return HTML fragment.
699 public function block_controls($controls) {
700 if (empty($controls)) {
703 $controlshtml = array();
704 foreach ($controls as $control) {
705 $controlshtml[] = html_writer::tag('a',
706 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
707 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
709 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
713 * Prints a nice side block with an optional header.
715 * The content is described
716 * by a {@link block_contents} object.
718 * @param block_contents $bc HTML for the content
719 * @param string $region the region the block is appearing in.
720 * @return string the HTML to be output.
722 function block(block_contents $bc, $region) {
723 $bc = clone($bc); // Avoid messing up the object passed in.
724 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
725 $bc->collapsible = block_contents::NOT_HIDEABLE;
727 if ($bc->collapsible == block_contents::HIDDEN) {
728 $bc->add_class('hidden');
730 if (!empty($bc->controls)) {
731 $bc->add_class('block_with_controls');
734 $skiptitle = strip_tags($bc->title);
735 if (empty($skiptitle)) {
739 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
740 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
743 $output .= html_writer::start_tag('div', $bc->attributes);
745 $controlshtml = $this->block_controls($bc->controls);
749 $title = html_writer::tag('h2', $bc->title, null);
752 if ($title || $controlshtml) {
753 $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'));
756 $output .= html_writer::start_tag('div', array('class' => 'content'));
757 if (!$title && !$controlshtml) {
758 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
760 $output .= $bc->content;
763 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
766 $output .= html_writer::end_tag('div');
767 $output .= html_writer::end_tag('div');
769 if ($bc->annotation) {
770 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
772 $output .= $skipdest;
774 $this->init_block_hider_js($bc);
779 * Calls the JS require function to hide a block.
780 * @param block_contents $bc A block_contents object
783 protected function init_block_hider_js(block_contents $bc) {
784 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
785 $userpref = 'block' . $bc->blockinstanceid . 'hidden';
786 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
787 $this->page->requires->yui2_lib('dom');
788 $this->page->requires->yui2_lib('event');
789 $plaintitle = strip_tags($bc->title);
790 $this->page->requires->js_function_call('new block_hider', array($bc->attributes['id'], $userpref,
791 get_string('hideblocka', 'access', $plaintitle), get_string('showblocka', 'access', $plaintitle),
792 $this->pix_url('t/switch_minus')->out(false), $this->pix_url('t/switch_plus')->out(false)));
797 * Render the contents of a block_list.
798 * @param array $icons the icon for each item.
799 * @param array $items the content of each item.
800 * @return string HTML
802 public function list_block_contents($icons, $items) {
805 foreach ($items as $key => $string) {
806 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
807 if (!empty($icons[$key])) { //test if the content has an assigned icon
808 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
810 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
811 $item .= html_writer::end_tag('li');
813 $row = 1 - $row; // Flip even/odd.
815 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'list'));
819 * Output all the blocks in a particular region.
820 * @param string $region the name of a region on this page.
821 * @return string the HTML to be output.
823 public function blocks_for_region($region) {
824 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
827 foreach ($blockcontents as $bc) {
828 if ($bc instanceof block_contents) {
829 $output .= $this->block($bc, $region);
830 } else if ($bc instanceof block_move_target) {
831 $output .= $this->block_move_target($bc);
833 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
840 * Output a place where the block that is currently being moved can be dropped.
841 * @param block_move_target $target with the necessary details.
842 * @return string the HTML to be output.
844 public function block_move_target($target) {
845 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
849 * Renders a special html link with attached action
851 * @param string|moodle_url $url
852 * @param string $text HTML fragment
853 * @param component_action $action
854 * @param array $attributes associative array of html link attributes + disabled
855 * @return HTML fragment
857 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
858 if (!($url instanceof moodle_url)) {
859 $url = new moodle_url($url);
861 $link = new action_link($url, $text, $action, $attributes);
863 return $this->render($link);
867 * Implementation of action_link rendering
868 * @param action_link $link
869 * @return string HTML fragment
871 protected function render_action_link(action_link $link) {
874 // A disabled link is rendered as formatted text
875 if (!empty($link->attributes['disabled'])) {
876 // do not use div here due to nesting restriction in xhtml strict
877 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
880 $attributes = $link->attributes;
881 unset($link->attributes['disabled']);
882 $attributes['href'] = $link->url;
884 if ($link->actions) {
885 if (empty($attributes['id'])) {
886 $id = html_writer::random_id('action_link');
887 $attributes['id'] = $id;
889 $id = $attributes['id'];
891 foreach ($link->actions as $action) {
892 $this->add_action_handler($action, $id);
896 return html_writer::tag('a', $link->text, $attributes);
901 * Similar to action_link, image is used instead of the text
903 * @param string|moodle_url $url A string URL or moodel_url
904 * @param pix_icon $pixicon
905 * @param component_action $action
906 * @param array $attributes associative array of html link attributes + disabled
907 * @param bool $linktext show title next to image in link
908 * @return string HTML fragment
910 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
911 if (!($url instanceof moodle_url)) {
912 $url = new moodle_url($url);
914 $attributes = (array)$attributes;
916 if (empty($attributes['class'])) {
917 // let ppl override the class via $options
918 $attributes['class'] = 'action-icon';
921 $icon = $this->render($pixicon);
924 $text = $pixicon->attributes['alt'];
929 return $this->action_link($url, $text.$icon, $action, $attributes);
933 * Print a message along with button choices for Continue/Cancel
935 * If a string or moodle_url is given instead of a single_button, method defaults to post.
937 * @param string $message The question to ask the user
938 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
939 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
940 * @return string HTML fragment
942 public function confirm($message, $continue, $cancel) {
943 if ($continue instanceof single_button) {
945 } else if (is_string($continue)) {
946 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
947 } else if ($continue instanceof moodle_url) {
948 $continue = new single_button($continue, get_string('continue'), 'post');
950 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
953 if ($cancel instanceof single_button) {
955 } else if (is_string($cancel)) {
956 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
957 } else if ($cancel instanceof moodle_url) {
958 $cancel = new single_button($cancel, get_string('cancel'), 'get');
960 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
963 $output = $this->box_start('generalbox', 'notice');
964 $output .= html_writer::tag('p', $message);
965 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
966 $output .= $this->box_end();
971 * Returns a form with a single button.
973 * @param string|moodle_url $url
974 * @param string $label button text
975 * @param string $method get or post submit method
976 * @param array $options associative array {disabled, title, etc.}
977 * @return string HTML fragment
979 public function single_button($url, $label, $method='post', array $options=null) {
980 if (!($url instanceof moodle_url)) {
981 $url = new moodle_url($url);
983 $button = new single_button($url, $label, $method);
985 foreach ((array)$options as $key=>$value) {
986 if (array_key_exists($key, $button)) {
987 $button->$key = $value;
991 return $this->render($button);
995 * Internal implementation of single_button rendering
996 * @param single_button $button
997 * @return string HTML fragment
999 protected function render_single_button(single_button $button) {
1000 $attributes = array('type' => 'submit',
1001 'value' => $button->label,
1002 'disabled' => $button->disabled ? 'disabled' : null,
1003 'title' => $button->tooltip);
1005 if ($button->actions) {
1006 $id = html_writer::random_id('single_button');
1007 $attributes['id'] = $id;
1008 foreach ($button->actions as $action) {
1009 $this->add_action_handler($action, $id);
1013 // first the input element
1014 $output = html_writer::empty_tag('input', $attributes);
1016 // then hidden fields
1017 $params = $button->url->params();
1018 if ($button->method === 'post') {
1019 $params['sesskey'] = sesskey();
1021 foreach ($params as $var => $val) {
1022 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1025 // then div wrapper for xhtml strictness
1026 $output = html_writer::tag('div', $output);
1028 // now the form itself around it
1029 $url = $button->url->out_omit_querystring(); // url without params
1031 $url = '#'; // there has to be always some action
1033 $attributes = array('method' => $button->method,
1035 'id' => $button->formid);
1036 $output = html_writer::tag('form', $output, $attributes);
1038 // and finally one more wrapper with class
1039 return html_writer::tag('div', $output, array('class' => $button->class));
1043 * Returns a form with a single select widget.
1044 * @param moodle_url $url form action target, includes hidden fields
1045 * @param string $name name of selection field - the changing parameter in url
1046 * @param array $options list of options
1047 * @param string $selected selected element
1048 * @param array $nothing
1049 * @param string $formid
1050 * @return string HTML fragment
1052 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1053 if (!($url instanceof moodle_url)) {
1054 $url = new moodle_url($url);
1056 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1058 return $this->render($select);
1062 * Internal implementation of single_select rendering
1063 * @param single_select $select
1064 * @return string HTML fragment
1066 protected function render_single_select(single_select $select) {
1067 $select = clone($select);
1068 if (empty($select->formid)) {
1069 $select->formid = html_writer::random_id('single_select_f');
1073 $params = $select->url->params();
1074 if ($select->method === 'post') {
1075 $params['sesskey'] = sesskey();
1077 foreach ($params as $name=>$value) {
1078 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1081 if (empty($select->attributes['id'])) {
1082 $select->attributes['id'] = html_writer::random_id('single_select');
1085 if ($select->disabled) {
1086 $select->attributes['disabled'] = 'disabled';
1089 if ($select->tooltip) {
1090 $select->attributes['title'] = $select->tooltip;
1093 if ($select->label) {
1094 $output .= html_writer::label($select->label, $select->attributes['id']);
1097 if ($select->helpicon instanceof help_icon) {
1098 $output .= $this->render($select->helpicon);
1099 } else if ($select->helpicon instanceof old_help_icon) {
1100 $output .= $this->render($select->helpicon);
1103 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1105 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1106 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
1108 $nothing = empty($select->nothing) ? false : key($select->nothing);
1109 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1111 // then div wrapper for xhtml strictness
1112 $output = html_writer::tag('div', $output);
1114 // now the form itself around it
1115 $formattributes = array('method' => $select->method,
1116 'action' => $select->url->out_omit_querystring(),
1117 'id' => $select->formid);
1118 $output = html_writer::tag('form', $output, $formattributes);
1120 // and finally one more wrapper with class
1121 return html_writer::tag('div', $output, array('class' => $select->class));
1125 * Returns a form with a url select widget.
1126 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1127 * @param string $selected selected element
1128 * @param array $nothing
1129 * @param string $formid
1130 * @return string HTML fragment
1132 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1133 $select = new url_select($urls, $selected, $nothing, $formid);
1134 return $this->render($select);
1138 * Internal implementation of url_select rendering
1139 * @param single_select $select
1140 * @return string HTML fragment
1142 protected function render_url_select(url_select $select) {
1145 $select = clone($select);
1146 if (empty($select->formid)) {
1147 $select->formid = html_writer::random_id('url_select_f');
1150 if (empty($select->attributes['id'])) {
1151 $select->attributes['id'] = html_writer::random_id('url_select');
1154 if ($select->disabled) {
1155 $select->attributes['disabled'] = 'disabled';
1158 if ($select->tooltip) {
1159 $select->attributes['title'] = $select->tooltip;
1164 if ($select->label) {
1165 $output .= html_writer::label($select->label, $select->attributes['id']);
1168 if ($select->helpicon instanceof help_icon) {
1169 $output .= $this->render($select->helpicon);
1170 } else if ($select->helpicon instanceof old_help_icon) {
1171 $output .= $this->render($select->helpicon);
1174 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1175 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1177 foreach ($select->urls as $k=>$v) {
1179 // optgroup structure
1180 foreach ($v as $optgrouptitle => $optgroupoptions) {
1181 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1182 if (empty($optionurl)) {
1183 $safeoptionurl = '';
1184 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1185 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1186 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1187 } else if (strpos($optionurl, '/') !== 0) {
1188 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1191 $safeoptionurl = $optionurl;
1193 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1197 // plain list structure
1199 // nothing selected option
1200 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1201 $k = str_replace($CFG->wwwroot, '', $k);
1202 } else if (strpos($k, '/') !== 0) {
1203 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1209 $selected = $select->selected;
1210 if (!empty($selected)) {
1211 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1212 $selected = str_replace($CFG->wwwroot, '', $selected);
1213 } else if (strpos($selected, '/') !== 0) {
1214 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1218 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1219 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1221 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1222 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
1224 $nothing = empty($select->nothing) ? false : key($select->nothing);
1225 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1227 // then div wrapper for xhtml strictness
1228 $output = html_writer::tag('div', $output);
1230 // now the form itself around it
1231 $formattributes = array('method' => 'post',
1232 'action' => new moodle_url('/course/jumpto.php'),
1233 'id' => $select->formid);
1234 $output = html_writer::tag('form', $output, $formattributes);
1236 // and finally one more wrapper with class
1237 return html_writer::tag('div', $output, array('class' => $select->class));
1241 * Returns a string containing a link to the user documentation.
1242 * Also contains an icon by default. Shown to teachers and admin only.
1243 * @param string $path The page link after doc root and language, no leading slash.
1244 * @param string $text The text to be displayed for the link
1247 public function doc_link($path, $text) {
1250 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1252 $url = new moodle_url(get_docs_url($path));
1254 $attributes = array('href'=>$url);
1255 if (!empty($CFG->doctonewwindow)) {
1256 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1259 return html_writer::tag('a', $icon.$text, $attributes);
1264 * @param string $pix short pix name
1265 * @param string $alt mandatory alt attribute
1266 * @param strin $component standard compoennt name like 'moodle', 'mod_form', etc.
1267 * @param array $attributes htm lattributes
1268 * @return string HTML fragment
1270 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1271 $icon = new pix_icon($pix, $alt, $component, $attributes);
1272 return $this->render($icon);
1277 * @param pix_icon $icon
1278 * @return string HTML fragment
1280 protected function render_pix_icon(pix_icon $icon) {
1281 $attributes = $icon->attributes;
1282 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1283 return html_writer::empty_tag('img', $attributes);
1287 * Produces the html that represents this rating in the UI
1288 * @param $page the page object on which this rating will appear
1290 function render_rating(rating $rating) {
1292 static $havesetupjavascript = false;
1294 if( $rating->settings->aggregationmethod == RATING_AGGREGATE_NONE ){
1295 return null;//ratings are turned off
1298 $useajax = !empty($CFG->enableajax);
1300 //include required Javascript
1301 if( !$havesetupjavascript && $useajax ) {
1302 $this->page->requires->js_init_call('M.core_rating.init');
1303 $havesetupjavascript = true;
1306 //check the item we're rating was created in the assessable time window
1307 $inassessablewindow = true;
1308 if ( $rating->settings->assesstimestart && $rating->settings->assesstimefinish ) {
1309 if ($rating->itemtimecreated < $rating->settings->assesstimestart || $item->itemtimecreated > $rating->settings->assesstimefinish) {
1310 $inassessablewindow = false;
1314 $strrate = get_string("rate", "rating");
1315 $ratinghtml = ''; //the string we'll return
1317 //permissions check - can they view the aggregate?
1318 if ( ($rating->itemuserid==$USER->id
1319 && $rating->settings->permissions->view && $rating->settings->pluginpermissions->view)
1320 || ($rating->itemuserid!=$USER->id
1321 && $rating->settings->permissions->viewany && $rating->settings->pluginpermissions->viewany) ) {
1323 $aggregatelabel = '';
1324 switch ($rating->settings->aggregationmethod) {
1325 case RATING_AGGREGATE_AVERAGE :
1326 $aggregatelabel .= get_string("aggregateavg", "forum");
1328 case RATING_AGGREGATE_COUNT :
1329 $aggregatelabel .= get_string("aggregatecount", "forum");
1331 case RATING_AGGREGATE_MAXIMUM :
1332 $aggregatelabel .= get_string("aggregatemax", "forum");
1334 case RATING_AGGREGATE_MINIMUM :
1335 $aggregatelabel .= get_string("aggregatemin", "forum");
1337 case RATING_AGGREGATE_SUM :
1338 $aggregatelabel .= get_string("aggregatesum", "forum");
1342 //$scalemax = 0;//no longer displaying scale max
1345 //only display aggregate if aggregation method isn't COUNT
1346 if ($rating->aggregate && $rating->settings->aggregationmethod!= RATING_AGGREGATE_COUNT) {
1347 if ($rating->settings->aggregationmethod!= RATING_AGGREGATE_SUM && is_array($rating->settings->scale->scaleitems)) {
1348 $aggregatestr .= $rating->settings->scale->scaleitems[round($rating->aggregate)];//round aggregate as we're using it as an index
1350 else { //aggregation is SUM or the scale is numeric
1351 $aggregatestr .= round($rating->aggregate,1);
1354 $aggregatestr = ' - ';
1357 $countstr = html_writer::start_tag('span', array('id'=>"ratingcount{$rating->itemid}"));
1358 if ($rating->count>0) {
1359 $countstr .= "({$rating->count})";
1361 $countstr .= html_writer::end_tag('span');
1363 //$aggregatehtml = "{$ratingstr} / $scalemax ({$rating->count}) ";
1364 $aggregatehtml = "<span id='ratingaggregate{$rating->itemid}'>{$aggregatestr}</span> $countstr ";
1366 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1367 $url = "/rating/index.php?contextid={$rating->context->id}&itemid={$rating->itemid}&scaleid={$rating->settings->scale->id}";
1368 $nonpopuplink = new moodle_url($url);
1369 $popuplink = new moodle_url("$url&popup=1");
1371 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1372 $ratinghtml .= $aggregatelabel.get_string('labelsep', 'langconfig').$this->action_link($nonpopuplink, $aggregatehtml, $action);
1374 $ratinghtml .= $aggregatelabel.get_string('labelsep', 'langconfig').$aggregatehtml;
1379 //if the item doesn't belong to the current user, the user has permission to rate
1380 //and we're within the assessable period
1381 if ($rating->itemuserid!=$USER->id
1382 && $rating->settings->permissions->rate
1383 && $rating->settings->pluginpermissions->rate
1384 && $inassessablewindow) {
1386 //start the rating form
1387 $formstart = html_writer::start_tag('form',
1388 array('id'=>"postrating{$rating->itemid}", 'class'=>'postratingform', 'method'=>'post', 'action'=>"{$CFG->wwwroot}/rating/rate.php"));
1390 $formstart .= html_writer::start_tag('div', array('class'=>'ratingform'));
1392 //add the hidden inputs
1394 $attributes = array('type'=>'hidden', 'class'=>'ratinginput', 'name'=>'contextid', 'value'=>$rating->context->id);
1395 $formstart .= html_writer::empty_tag('input', $attributes);
1397 $attributes['name'] = 'itemid';
1398 $attributes['value'] = $rating->itemid;
1399 $formstart .= html_writer::empty_tag('input', $attributes);
1401 $attributes['name'] = 'scaleid';
1402 $attributes['value'] = $rating->settings->scale->id;
1403 $formstart .= html_writer::empty_tag('input', $attributes);
1405 $attributes['name'] = 'returnurl';
1406 $attributes['value'] = $rating->settings->returnurl;
1407 $formstart .= html_writer::empty_tag('input', $attributes);
1409 $attributes['name'] = 'rateduserid';
1410 $attributes['value'] = $rating->itemuserid;
1411 $formstart .= html_writer::empty_tag('input', $attributes);
1413 $attributes['name'] = 'aggregation';
1414 $attributes['value'] = $rating->settings->aggregationmethod;
1415 $formstart .= html_writer::empty_tag('input', $attributes);
1417 $attributes['name'] = 'sesskey';
1418 $attributes['value'] = sesskey();;
1419 $formstart .= html_writer::empty_tag('input', $attributes);
1421 if (empty($ratinghtml)) {
1422 $ratinghtml .= $strrate.': ';
1425 $ratinghtml = $formstart.$ratinghtml;
1427 //generate an array of values for numeric scales
1428 $scalearray = $rating->settings->scale->scaleitems;
1429 if (!is_array($scalearray)) { //almost certainly a numerical scale
1430 $intscalearray = intval($scalearray);//just in case they've passed "5" instead of 5
1431 if( is_int($intscalearray) && $intscalearray>0 ){
1432 $scalearray = array();
1433 for($i=0; $i<=$rating->settings->scale->scaleitems; $i++) {
1434 $scalearray[$i] = $i;
1439 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $scalearray;
1440 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid));
1442 //output submit button
1444 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1446 $attributes = array('type'=>'submit', 'class'=>'postratingmenusubmit', 'id'=>'postratingsubmit'.$rating->itemid, 'value'=>s(get_string('rate', 'rating')));
1447 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1449 if (is_array($rating->settings->scale->scaleitems)) {
1450 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1452 $ratinghtml .= html_writer::end_tag('span');
1453 $ratinghtml .= html_writer::end_tag('div');
1454 $ratinghtml .= html_writer::end_tag('form');
1461 * Centered heading with attached help button (same title text)
1462 * and optional icon attached
1463 * @param string $text A heading text
1464 * @param string $helpidentifier The keyword that defines a help page
1465 * @param string $component component name
1466 * @param string|moodle_url $icon
1467 * @param string $iconalt icon alt text
1468 * @return string HTML fragment
1470 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1473 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1477 if ($helpidentifier) {
1478 $help = $this->help_icon($helpidentifier, $component);
1481 return $this->heading($image.$text.$help, 2, 'main help');
1485 * Print a help icon.
1487 * @param string $page The keyword that defines a help page
1488 * @param string $title A descriptive text for accessibility only
1489 * @param string $component component name
1490 * @param string|bool $linktext true means use $title as link text, string means link text value
1491 * @return string HTML fragment
1493 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1494 $icon = new old_help_icon($helpidentifier, $title, $component);
1495 if ($linktext === true) {
1496 $icon->linktext = $title;
1497 } else if (!empty($linktext)) {
1498 $icon->linktext = $linktext;
1500 return $this->render($icon);
1504 * Implementation of user image rendering.
1505 * @param help_icon $helpicon
1506 * @return string HTML fragment
1508 protected function render_old_help_icon(old_help_icon $helpicon) {
1511 // first get the help image icon
1512 $src = $this->pix_url('help');
1514 if (empty($helpicon->linktext)) {
1515 $alt = $helpicon->title;
1517 $alt = get_string('helpwiththis');
1520 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1521 $output = html_writer::empty_tag('img', $attributes);
1523 // add the link text if given
1524 if (!empty($helpicon->linktext)) {
1525 // the spacing has to be done through CSS
1526 $output .= $helpicon->linktext;
1529 // now create the link around it
1530 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1532 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1533 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1535 $attributes = array('href'=>$url, 'title'=>$title);
1536 $id = html_writer::random_id('helpicon');
1537 $attributes['id'] = $id;
1538 $output = html_writer::tag('a', $output, $attributes);
1540 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1543 return html_writer::tag('span', $output, array('class' => 'helplink'));
1547 * Print a help icon.
1549 * @param string $identifier The keyword that defines a help page
1550 * @param string $component component name
1551 * @param string|bool $linktext true means use $title as link text, string means link text value
1552 * @return string HTML fragment
1554 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1555 $icon = new help_icon($identifier, $component);
1556 $icon->diag_strings();
1557 if ($linktext === true) {
1558 $icon->linktext = get_string($icon->identifier, $icon->component);
1559 } else if (!empty($linktext)) {
1560 $icon->linktext = $linktext;
1562 return $this->render($icon);
1566 * Implementation of user image rendering.
1567 * @param help_icon $helpicon
1568 * @return string HTML fragment
1570 protected function render_help_icon(help_icon $helpicon) {
1573 // first get the help image icon
1574 $src = $this->pix_url('help');
1576 $title = get_string($helpicon->identifier, $helpicon->component);
1578 if (empty($helpicon->linktext)) {
1581 $alt = get_string('helpwiththis');
1584 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1585 $output = html_writer::empty_tag('img', $attributes);
1587 // add the link text if given
1588 if (!empty($helpicon->linktext)) {
1589 // the spacing has to be done through CSS
1590 $output .= $helpicon->linktext;
1593 // now create the link around it
1594 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1596 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1597 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1599 $attributes = array('href'=>$url, 'title'=>$title);
1600 $id = html_writer::random_id('helpicon');
1601 $attributes['id'] = $id;
1602 $output = html_writer::tag('a', $output, $attributes);
1604 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1607 return html_writer::tag('span', $output, array('class' => 'helplink'));
1611 * Print scale help icon.
1613 * @param int $courseid
1614 * @param object $scale instance
1615 * @return string HTML fragment
1617 public function help_icon_scale($courseid, stdClass $scale) {
1620 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1622 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1624 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scale->id));
1625 $action = new popup_action('click', $link, 'ratingscale');
1627 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1631 * Creates and returns a spacer image with optional line break.
1633 * @param array $attributes
1635 * @return string HTML fragment
1637 public function spacer(array $attributes = null, $br = false) {
1638 $attributes = (array)$attributes;
1639 if (empty($attributes['width'])) {
1640 $attributes['width'] = 1;
1642 if (empty($options['height'])) {
1643 $attributes['height'] = 1;
1645 $attributes['class'] = 'spacer';
1647 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1650 $output .= '<br />';
1657 * Print the specified user's avatar.
1659 * User avatar may be obtained in two ways:
1661 * // Option 1: (shortcut for simple cases, preferred way)
1662 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1663 * $OUTPUT->user_picture($user, array('popup'=>true));
1666 * $userpic = new user_picture($user);
1667 * // Set properties of $userpic
1668 * $userpic->popup = true;
1669 * $OUTPUT->render($userpic);
1672 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1673 * If any of these are missing, the database is queried. Avoid this
1674 * if at all possible, particularly for reports. It is very bad for performance.
1675 * @param array $options associative array with user picture options, used only if not a user_picture object,
1677 * - courseid=$this->page->course->id (course id of user profile in link)
1678 * - size=35 (size of image)
1679 * - link=true (make image clickable - the link leads to user profile)
1680 * - popup=false (open in popup)
1681 * - alttext=true (add image alt attribute)
1682 * - class = image class attribute (default 'userpicture')
1683 * @return string HTML fragment
1685 public function user_picture(stdClass $user, array $options = null) {
1686 $userpicture = new user_picture($user);
1687 foreach ((array)$options as $key=>$value) {
1688 if (array_key_exists($key, $userpicture)) {
1689 $userpicture->$key = $value;
1692 return $this->render($userpicture);
1696 * Internal implementation of user image rendering.
1697 * @param user_picture $userpicture
1700 protected function render_user_picture(user_picture $userpicture) {
1703 $user = $userpicture->user;
1705 if ($userpicture->alttext) {
1706 if (!empty($user->imagealt)) {
1707 $alt = $user->imagealt;
1709 $alt = get_string('pictureof', '', fullname($user));
1715 if (empty($userpicture->size)) {
1718 } else if ($userpicture->size === true or $userpicture->size == 1) {
1721 } else if ($userpicture->size >= 50) {
1723 $size = $userpicture->size;
1726 $size = $userpicture->size;
1729 $class = $userpicture->class;
1731 if ($user->picture == 1) {
1732 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1733 $src = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', $file);
1735 } else if ($user->picture == 2) {
1736 //TODO: gravatar user icon support
1738 } else { // Print default user pictures (use theme version if available)
1739 $class .= ' defaultuserpic';
1740 $src = $this->pix_url('u/' . $file);
1743 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1745 // get the image html output fisrt
1746 $output = html_writer::empty_tag('img', $attributes);;
1748 // then wrap it in link if needed
1749 if (!$userpicture->link) {
1753 if (empty($userpicture->courseid)) {
1754 $courseid = $this->page->course->id;
1756 $courseid = $userpicture->courseid;
1759 if ($courseid == SITEID) {
1760 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1762 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1765 $attributes = array('href'=>$url);
1767 if ($userpicture->popup) {
1768 $id = html_writer::random_id('userpicture');
1769 $attributes['id'] = $id;
1770 $this->add_action_handler(new popup_action('click', $url), $id);
1773 return html_writer::tag('a', $output, $attributes);
1777 * Internal implementation of file tree viewer items rendering.
1781 public function htmllize_file_tree($dir) {
1782 if (empty($dir['subdirs']) and empty($dir['files'])) {
1786 foreach ($dir['subdirs'] as $subdir) {
1787 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1789 foreach ($dir['files'] as $file) {
1790 $filename = $file->get_filename();
1791 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1798 * Print the file picker
1801 * $OUTPUT->file_picker($options);
1804 * @param array $options associative array with file manager options
1808 * client_id=>uniqid(),
1809 * acepted_types=>'*',
1810 * return_types=>FILE_INTERNAL,
1811 * context=>$PAGE->context
1812 * @return string HTML fragment
1814 public function file_picker($options) {
1815 $fp = new file_picker($options);
1816 return $this->render($fp);
1819 * Internal implementation of file picker rendering.
1820 * @param file_picker $fp
1823 public function render_file_picker(file_picker $fp) {
1824 global $CFG, $OUTPUT, $USER;
1825 $options = $fp->options;
1826 $client_id = $options->client_id;
1827 $strsaved = get_string('filesaved', 'repository');
1828 $straddfile = get_string('openpicker', 'repository');
1829 $strloading = get_string('loading', 'repository');
1830 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1832 $currentfile = $options->currentfile;
1833 if (empty($currentfile)) {
1834 $currentfile = get_string('nofilesattached', 'repository');
1837 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1840 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1842 <button id="filepicker-button-{$client_id}">$straddfile</button>
1845 if ($options->env != 'url') {
1847 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1855 * Prints the 'Update this Modulename' button that appears on module pages.
1857 * @param string $cmid the course_module id.
1858 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1859 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1861 public function update_module_button($cmid, $modulename) {
1863 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1864 $modulename = get_string('modulename', $modulename);
1865 $string = get_string('updatethis', '', $modulename);
1866 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1867 return $this->single_button($url, $string);
1874 * Prints a "Turn editing on/off" button in a form.
1875 * @param moodle_url $url The URL + params to send through when clicking the button
1876 * @return string HTML the button
1878 public function edit_button(moodle_url $url) {
1880 if (!empty($USER->editing)) {
1881 $string = get_string('turneditingoff');
1884 $string = get_string('turneditingon');
1888 $url = new moodle_url($url, array('edit'=>$edit));
1890 return $this->single_button($url, $string);
1894 * Prints a simple button to close a window
1896 * @param string $text The lang string for the button's label (already output from get_string())
1897 * @return string html fragment
1899 public function close_window_button($text='') {
1901 $text = get_string('closewindow');
1903 $button = new single_button(new moodle_url('#'), $text, 'get');
1904 $button->add_action(new component_action('click', 'close_window'));
1906 return $this->container($this->render($button), 'closewindow');
1910 * Output an error message. By default wraps the error message in <span class="error">.
1911 * If the error message is blank, nothing is output.
1912 * @param string $message the error message.
1913 * @return string the HTML to output.
1915 public function error_text($message) {
1916 if (empty($message)) {
1919 return html_writer::tag('span', $message, array('class' => 'error'));
1923 * Do not call this function directly.
1925 * To terminate the current script with a fatal error, call the {@link print_error}
1926 * function, or throw an exception. Doing either of those things will then call this
1927 * function to display the error, before terminating the execution.
1929 * @param string $message The message to output
1930 * @param string $moreinfourl URL where more info can be found about the error
1931 * @param string $link Link for the Continue button
1932 * @param array $backtrace The execution backtrace
1933 * @param string $debuginfo Debugging information
1934 * @return string the HTML to output.
1936 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1941 if ($this->has_started()) {
1942 // we can not always recover properly here, we have problems with output buffering,
1943 // html tables, etc.
1944 $output .= $this->opencontainers->pop_all_but_last();
1947 // It is really bad if library code throws exception when output buffering is on,
1948 // because the buffered text would be printed before our start of page.
1949 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
1950 while (ob_get_level() > 0) {
1951 $obbuffer .= ob_get_clean();
1954 // Header not yet printed
1955 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1956 // server protocol should be always present, because this render
1957 // can not be used from command line or when outputting custom XML
1958 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
1960 $this->page->set_url('/'); // no url
1961 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
1962 $this->page->set_title(get_string('error'));
1963 $this->page->set_heading($this->page->course->fullname);
1964 $output .= $this->header();
1967 $message = '<p class="errormessage">' . $message . '</p>'.
1968 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
1969 get_string('moreinformation') . '</a></p>';
1970 $output .= $this->box($message, 'errorbox');
1972 if (debugging('', DEBUG_DEVELOPER)) {
1973 if (!empty($debuginfo)) {
1974 $debuginfo = s($debuginfo); // removes all nasty JS
1975 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1976 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
1978 if (!empty($backtrace)) {
1979 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
1981 if ($obbuffer !== '' ) {
1982 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
1986 if (!empty($link)) {
1987 $output .= $this->continue_button($link);
1990 $output .= $this->footer();
1992 // Padding to encourage IE to display our error page, rather than its own.
1993 $output .= str_repeat(' ', 512);
1999 * Output a notification (that is, a status message about something that has
2002 * @param string $message the message to print out
2003 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2004 * @return string the HTML to output.
2006 public function notification($message, $classes = 'notifyproblem') {
2007 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2011 * Print a continue button that goes to a particular URL.
2013 * @param string|moodle_url $url The url the button goes to.
2014 * @return string the HTML to output.
2016 public function continue_button($url) {
2017 if (!($url instanceof moodle_url)) {
2018 $url = new moodle_url($url);
2020 $button = new single_button($url, get_string('continue'), 'get');
2021 $button->class = 'continuebutton';
2023 return $this->render($button);
2027 * Prints a single paging bar to provide access to other pages (usually in a search)
2029 * @param int $totalcount The total number of entries available to be paged through
2030 * @param int $page The page you are currently viewing
2031 * @param int $perpage The number of entries that should be shown per page
2032 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2033 * @param string $pagevar name of page parameter that holds the page number
2034 * @return string the HTML to output.
2036 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2037 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2038 return $this->render($pb);
2042 * Internal implementation of paging bar rendering.
2043 * @param paging_bar $pagingbar
2046 protected function render_paging_bar(paging_bar $pagingbar) {
2048 $pagingbar = clone($pagingbar);
2049 $pagingbar->prepare($this, $this->page, $this->target);
2051 if ($pagingbar->totalcount > $pagingbar->perpage) {
2052 $output .= get_string('page') . ':';
2054 if (!empty($pagingbar->previouslink)) {
2055 $output .= ' (' . $pagingbar->previouslink . ') ';
2058 if (!empty($pagingbar->firstlink)) {
2059 $output .= ' ' . $pagingbar->firstlink . ' ...';
2062 foreach ($pagingbar->pagelinks as $link) {
2063 $output .= "  $link";
2066 if (!empty($pagingbar->lastlink)) {
2067 $output .= ' ...' . $pagingbar->lastlink . ' ';
2070 if (!empty($pagingbar->nextlink)) {
2071 $output .= '  (' . $pagingbar->nextlink . ')';
2075 return html_writer::tag('div', $output, array('class' => 'paging'));
2079 * Output the place a skip link goes to.
2080 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2081 * @return string the HTML to output.
2083 public function skip_link_target($id = null) {
2084 return html_writer::tag('span', '', array('id' => $id));
2089 * @param string $text The text of the heading
2090 * @param int $level The level of importance of the heading. Defaulting to 2
2091 * @param string $classes A space-separated list of CSS classes
2092 * @param string $id An optional ID
2093 * @return string the HTML to output.
2095 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2096 $level = (integer) $level;
2097 if ($level < 1 or $level > 6) {
2098 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2100 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2105 * @param string $contents The contents of the box
2106 * @param string $classes A space-separated list of CSS classes
2107 * @param string $id An optional ID
2108 * @return string the HTML to output.
2110 public function box($contents, $classes = 'generalbox', $id = null) {
2111 return $this->box_start($classes, $id) . $contents . $this->box_end();
2115 * Outputs the opening section of a box.
2116 * @param string $classes A space-separated list of CSS classes
2117 * @param string $id An optional ID
2118 * @return string the HTML to output.
2120 public function box_start($classes = 'generalbox', $id = null) {
2121 $this->opencontainers->push('box', html_writer::end_tag('div'));
2122 return html_writer::start_tag('div', array('id' => $id,
2123 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2127 * Outputs the closing section of a box.
2128 * @return string the HTML to output.
2130 public function box_end() {
2131 return $this->opencontainers->pop('box');
2135 * Outputs a container.
2136 * @param string $contents The contents of the box
2137 * @param string $classes A space-separated list of CSS classes
2138 * @param string $id An optional ID
2139 * @return string the HTML to output.
2141 public function container($contents, $classes = null, $id = null) {
2142 return $this->container_start($classes, $id) . $contents . $this->container_end();
2146 * Outputs the opening section of a container.
2147 * @param string $classes A space-separated list of CSS classes
2148 * @param string $id An optional ID
2149 * @return string the HTML to output.
2151 public function container_start($classes = null, $id = null) {
2152 $this->opencontainers->push('container', html_writer::end_tag('div'));
2153 return html_writer::start_tag('div', array('id' => $id,
2154 'class' => renderer_base::prepare_classes($classes)));
2158 * Outputs the closing section of a container.
2159 * @return string the HTML to output.
2161 public function container_end() {
2162 return $this->opencontainers->pop('container');
2166 * Make nested HTML lists out of the items
2168 * The resulting list will look something like this:
2172 * <<li>><div class='tree_item parent'>(item contents)</div>
2174 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2180 * @param array[]tree_item $items
2181 * @param array[string]string $attrs html attributes passed to the top of
2183 * @return string HTML
2185 function tree_block_contents($items, $attrs=array()) {
2186 // exit if empty, we don't want an empty ul element
2187 if (empty($items)) {
2190 // array of nested li elements
2192 foreach ($items as $item) {
2193 // this applies to the li item which contains all child lists too
2194 $content = $item->content($this);
2195 $liclasses = array($item->get_css_type());
2196 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2197 $liclasses[] = 'collapsed';
2199 if ($item->isactive === true) {
2200 $liclasses[] = 'current_branch';
2202 $liattr = array('class'=>join(' ',$liclasses));
2203 // class attribute on the div item which only contains the item content
2204 $divclasses = array('tree_item');
2205 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2206 $divclasses[] = 'branch';
2208 $divclasses[] = 'leaf';
2210 if (!empty($item->classes) && count($item->classes)>0) {
2211 $divclasses[] = join(' ', $item->classes);
2213 $divattr = array('class'=>join(' ', $divclasses));
2214 if (!empty($item->id)) {
2215 $divattr['id'] = $item->id;
2217 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2218 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2219 $content = html_writer::empty_tag('hr') . $content;
2221 $content = html_writer::tag('li', $content, $liattr);
2224 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2228 * Return the navbar content so that it can be echoed out by the layout
2229 * @return string XHTML navbar
2231 public function navbar() {
2232 //return $this->page->navbar->content();
2234 $items = $this->page->navbar->get_items();
2238 $htmlblocks = array();
2239 // Iterate the navarray and display each node
2240 $itemcount = count($items);
2241 $separator = get_separator();
2242 for ($i=0;$i < $itemcount;$i++) {
2244 $item->hideicon = true;
2246 $content = html_writer::tag('li', $this->render($item));
2248 $content = html_writer::tag('li', $separator.$this->render($item));
2250 $htmlblocks[] = $content;
2253 //accessibility: heading for navbar list (MDL-20446)
2254 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2255 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2257 return $navbarcontent;
2260 protected function render_navigation_node(navigation_node $item) {
2261 $content = $item->get_content();
2262 $title = $item->get_title();
2263 if ($item->icon instanceof renderable && !$item->hideicon) {
2264 $icon = $this->render($item->icon);
2265 $content = $icon.$content; // use CSS for spacing of icons
2267 if ($item->helpbutton !== null) {
2268 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton'));
2270 if ($content === '') {
2273 if ($item->action instanceof action_link) {
2274 //TODO: to be replaced with something else
2275 $link = $item->action;
2276 if ($item->hidden) {
2277 $link->add_class('dimmed');
2279 $content = $this->output->render($link);
2280 } else if ($item->action instanceof moodle_url) {
2281 $attributes = array();
2282 if ($title !== '') {
2283 $attributes['title'] = $title;
2285 if ($item->hidden) {
2286 $attributes['class'] = 'dimmed_text';
2288 $content = html_writer::link($item->action, $content, $attributes);
2290 } else if (is_string($item->action) || empty($item->action)) {
2291 $attributes = array();
2292 if ($title !== '') {
2293 $attributes['title'] = $title;
2295 if ($item->hidden) {
2296 $attributes['class'] = 'dimmed_text';
2298 $content = html_writer::tag('span', $content, $attributes);
2304 * Accessibility: Right arrow-like character is
2305 * used in the breadcrumb trail, course navigation menu
2306 * (previous/next activity), calendar, and search forum block.
2307 * If the theme does not set characters, appropriate defaults
2308 * are set automatically. Please DO NOT
2309 * use < > » - these are confusing for blind users.
2312 public function rarrow() {
2313 return $this->page->theme->rarrow;
2317 * Accessibility: Right arrow-like character is
2318 * used in the breadcrumb trail, course navigation menu
2319 * (previous/next activity), calendar, and search forum block.
2320 * If the theme does not set characters, appropriate defaults
2321 * are set automatically. Please DO NOT
2322 * use < > » - these are confusing for blind users.
2325 public function larrow() {
2326 return $this->page->theme->larrow;
2330 * Returns the colours of the small MP3 player
2333 public function filter_mediaplugin_colors() {
2334 return $this->page->theme->filter_mediaplugin_colors;
2338 * Returns the colours of the big MP3 player
2341 public function resource_mp3player_colors() {
2342 return $this->page->theme->resource_mp3player_colors;
2346 * Returns the custom menu if one has been set
2348 * A custom menu can be configured by browsing to
2349 * Settings: Administration > Appearance > Themes > Theme settings
2350 * and then configuring the custommenu config setting as described.
2354 public function custom_menu() {
2356 if (empty($CFG->custommenuitems)) {
2359 $custommenu = new custom_menu();
2360 return $this->render_custom_menu($custommenu);
2364 * Renders a custom menu object (located in outputcomponents.php)
2366 * The custom menu this method produces makes use of the YUI3 menunav widget
2367 * and requires very specific html elements and classes.
2369 * @staticvar int $menucount
2370 * @param custom_menu $menu
2373 protected function render_custom_menu(custom_menu $menu) {
2374 static $menucount = 0;
2375 // If the menu has no children return an empty string
2376 if (!$menu->has_children()) {
2379 // Increment the menu count. This is used for ID's that get worked with
2380 // in JavaScript as is essential
2382 // Initialise this custom menu
2383 $this->page->requires->js_init_call('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2384 // Build the root nodes as required by YUI
2385 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2386 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2387 $content .= html_writer::start_tag('ul');
2388 // Render each child
2389 foreach ($menu->get_children() as $item) {
2390 $content .= $this->render_custom_menu_item($item);
2392 // Close the open tags
2393 $content .= html_writer::end_tag('ul');
2394 $content .= html_writer::end_tag('div');
2395 $content .= html_writer::end_tag('div');
2396 // Return the custom menu
2401 * Renders a custom menu node as part of a submenu
2403 * The custom menu this method produces makes use of the YUI3 menunav widget
2404 * and requires very specific html elements and classes.
2406 * @see render_custom_menu()
2408 * @staticvar int $submenucount
2409 * @param custom_menu_item $menunode
2412 protected function render_custom_menu_item(custom_menu_item $menunode) {
2413 // Required to ensure we get unique trackable id's
2414 static $submenucount = 0;
2415 if ($menunode->has_children()) {
2416 // If the child has menus render it as a sub menu
2418 $content = html_writer::start_tag('li');
2419 if ($menunode->get_url() !== null) {
2420 $url = $menunode->get_url();
2422 $url = '#cm_submenu_'.$submenucount;
2424 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2425 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2426 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2427 $content .= html_writer::start_tag('ul');
2428 foreach ($menunode->get_children() as $menunode) {
2429 $content .= $this->render_custom_menu_item($menunode);
2431 $content .= html_writer::end_tag('ul');
2432 $content .= html_writer::end_tag('div');
2433 $content .= html_writer::end_tag('div');
2434 $content .= html_writer::end_tag('li');
2436 // The node doesn't have children so produce a final menuitem
2437 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2438 if ($menunode->get_url() !== null) {
2439 $url = $menunode->get_url();
2443 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2444 $content .= html_writer::end_tag('li');
2446 // Return the sub menu
2451 * Renders the image_gallery component and initialises its JavaScript
2453 * @param image_gallery $imagegallery
2456 protected function render_image_gallery(image_gallery $imagegallery) {
2457 $this->page->requires->yui_module(array('gallery-lightbox','gallery-lightbox-skin'),
2458 'Y.Lightbox.init', null, '2010.04.08-12-35');
2459 if (count($imagegallery->images) == 0) {
2462 $classes = array('image_gallery');
2463 if ($imagegallery->displayfirstimageonly) {
2464 $classes[] = 'oneimageonly';
2466 $content = html_writer::start_tag('div', array('class'=>join(' ', $classes)));
2467 foreach ($imagegallery->images as $image) {
2468 $content .= html_writer::tag('a', html_writer::empty_tag('img', $image->thumb), $image->link);
2470 $content .= html_writer::end_tag('div');
2479 * A renderer that generates output for command-line scripts.
2481 * The implementation of this renderer is probably incomplete.
2483 * @copyright 2009 Tim Hunt
2484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2487 class core_renderer_cli extends core_renderer {
2489 * Returns the page header.
2490 * @return string HTML fragment
2492 public function header() {
2493 output_starting_hook();
2494 return $this->page->heading . "\n";
2498 * Returns a template fragment representing a Heading.
2499 * @param string $text The text of the heading
2500 * @param int $level The level of importance of the heading
2501 * @param string $classes A space-separated list of CSS classes
2502 * @param string $id An optional ID
2503 * @return string A template fragment for a heading
2505 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2509 return '=>' . $text;
2511 return '-->' . $text;
2518 * Returns a template fragment representing a fatal error.
2519 * @param string $message The message to output
2520 * @param string $moreinfourl URL where more info can be found about the error
2521 * @param string $link Link for the Continue button
2522 * @param array $backtrace The execution backtrace
2523 * @param string $debuginfo Debugging information
2524 * @return string A template fragment for a fatal error
2526 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2527 $output = "!!! $message !!!\n";
2529 if (debugging('', DEBUG_DEVELOPER)) {
2530 if (!empty($debuginfo)) {
2531 $this->notification($debuginfo, 'notifytiny');
2533 if (!empty($backtrace)) {
2534 $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2540 * Returns a template fragment representing a notification.
2541 * @param string $message The message to include
2542 * @param string $classes A space-separated list of CSS classes
2543 * @return string A template fragment for a notification
2545 public function notification($message, $classes = 'notifyproblem') {
2546 $message = clean_text($message);
2547 if ($classes === 'notifysuccess') {
2548 return "++ $message ++\n";
2550 return "!! $message !!\n";
2556 * A renderer that generates output for ajax scripts.
2558 * This renderer prevents accidental sends back only json
2559 * encoded error messages, all other output is ignored.
2561 * @copyright 2010 Petr Skoda
2562 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2565 class core_renderer_ajax extends core_renderer {
2567 * Returns a template fragment representing a fatal error.
2568 * @param string $message The message to output
2569 * @param string $moreinfourl URL where more info can be found about the error
2570 * @param string $link Link for the Continue button
2571 * @param array $backtrace The execution backtrace
2572 * @param string $debuginfo Debugging information
2573 * @return string A template fragment for a fatal error
2575 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2576 $e = new stdClass();
2577 $e->error = $message;
2578 $e->stacktrace = NULL;
2579 $e->debuginfo = NULL;
2580 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2581 if (!empty($debuginfo)) {
2582 $e->debuginfo = $debuginfo;
2584 if (!empty($backtrace)) {
2585 $e->stacktrace = format_backtrace($backtrace, true);
2588 return json_encode($e);
2591 public function notification($message, $classes = 'notifyproblem') {
2593 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2595 public function header() {
2597 public function footer() {
2599 public function heading($text, $level = 2, $classes = 'main', $id = null) {