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
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
33 * Simple base class for Moodle renderers.
35 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
37 * Also has methods to facilitate generating HTML output.
39 * @copyright 2009 Tim Hunt
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 /** @var xhtml_container_stack the xhtml_container_stack to use. */
45 protected $opencontainers;
46 /** @var moodle_page the page we are rendering for. */
48 /** @var requested rendering target */
53 * @param moodle_page $page the page we are doing output for.
54 * @param string $target one of rendering target constants
56 public function __construct(moodle_page $page, $target) {
57 $this->opencontainers = $page->opencontainers;
59 $this->target = $target;
63 * Returns rendered widget.
64 * @param renderable $widget instance with renderable interface
67 public function render(renderable $widget) {
68 $rendermethod = 'render_'.get_class($widget);
69 if (method_exists($this, $rendermethod)) {
70 return $this->$rendermethod($widget);
72 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
76 * Adds JS handlers needed for event execution for one html element id
77 * @param component_action $actions
79 * @return string id of element, either original submitted or random new if not supplied
81 public function add_action_handler(component_action $action, $id=null) {
83 $id = html_writer::random_id($action->event);
85 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
90 * Have we started output yet?
91 * @return boolean true if the header has been printed.
93 public function has_started() {
94 return $this->page->state >= moodle_page::STATE_IN_BODY;
98 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
99 * @param mixed $classes Space-separated string or array of classes
100 * @return string HTML class attribute value
102 public static function prepare_classes($classes) {
103 if (is_array($classes)) {
104 return implode(' ', array_unique($classes));
110 * Return the moodle_url for an image.
111 * The exact image location and extension is determined
112 * automatically by searching for gif|png|jpg|jpeg, please
113 * note there can not be diferent images with the different
114 * extension. The imagename is for historical reasons
115 * a relative path name, it may be changed later for core
116 * images. It is recommended to not use subdirectories
117 * in plugin and theme pix directories.
119 * There are three types of images:
120 * 1/ theme images - stored in theme/mytheme/pix/,
121 * use component 'theme'
122 * 2/ core images - stored in /pix/,
123 * overridden via theme/mytheme/pix_core/
124 * 3/ plugin images - stored in mod/mymodule/pix,
125 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
126 * example: pix_url('comment', 'mod_glossary')
128 * @param string $imagename the pathname of the image
129 * @param string $component full plugin name (aka component) or 'theme'
132 public function pix_url($imagename, $component = 'moodle') {
133 return $this->page->theme->pix_url($imagename, $component);
139 * Basis for all plugin renderers.
141 * @author Petr Skoda (skodak)
142 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
145 class plugin_renderer_base extends renderer_base {
147 * A reference to the current general renderer probably {@see core_renderer}
153 * Constructor method, calls the parent constructor
154 * @param moodle_page $page
155 * @param string $target one of rendering target constants
157 public function __construct(moodle_page $page, $target) {
158 $this->output = $page->get_renderer('core', null, $target);
159 parent::__construct($page, $target);
163 * Returns rendered widget.
164 * @param renderable $widget instance with renderable interface
167 public function render(renderable $widget) {
168 $rendermethod = 'render_'.get_class($widget);
169 if (method_exists($this, $rendermethod)) {
170 return $this->$rendermethod($widget);
172 // pass to core renderer if method not found here
173 return $this->output->render($widget);
177 * Magic method used to pass calls otherwise meant for the standard renderer
178 * to it to ensure we don't go causing unnecessary grief.
180 * @param string $method
181 * @param array $arguments
184 public function __call($method, $arguments) {
185 if (method_exists('renderer_base', $method)) {
186 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
188 if (method_exists($this->output, $method)) {
189 return call_user_func_array(array($this->output, $method), $arguments);
191 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
198 * The standard implementation of the core_renderer interface.
200 * @copyright 2009 Tim Hunt
201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
204 class core_renderer extends renderer_base {
205 /** @var string used in {@link header()}. */
206 const PERFORMANCE_INFO_TOKEN = '%%PERFORMANCEINFO%%';
207 /** @var string used in {@link header()}. */
208 const END_HTML_TOKEN = '%%ENDHTML%%';
209 /** @var string used in {@link header()}. */
210 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
211 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
212 protected $contenttype;
213 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
214 protected $metarefreshtag = '';
217 * Get the DOCTYPE declaration that should be used with this page. Designed to
218 * be called in theme layout.php files.
219 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
221 public function doctype() {
224 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
225 $this->contenttype = 'text/html; charset=utf-8';
227 if (empty($CFG->xmlstrictheaders)) {
231 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
232 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
233 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
234 // Firefox and other browsers that can cope natively with XHTML.
235 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
237 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
238 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
239 $this->contenttype = 'application/xml; charset=utf-8';
240 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
246 return $prolog . $doctype;
250 * The attributes that should be added to the <html> tag. Designed to
251 * be called in theme layout.php files.
252 * @return string HTML fragment.
254 public function htmlattributes() {
255 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
259 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
260 * that should be included in the <head> tag. Designed to be called in theme
262 * @return string HTML fragment.
264 public function standard_head_html() {
265 global $CFG, $SESSION;
267 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
268 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
269 if (!$this->page->cacheable) {
270 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
271 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
273 // This is only set by the {@link redirect()} method
274 $output .= $this->metarefreshtag;
276 // Check if a periodic refresh delay has been set and make sure we arn't
277 // already meta refreshing
278 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
279 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
282 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
284 $focus = $this->page->focuscontrol;
285 if (!empty($focus)) {
286 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
287 // This is a horrifically bad way to handle focus but it is passed in
288 // through messy formslib::moodleform
289 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
290 } else if (strpos($focus, '.')!==false) {
291 // Old style of focus, bad way to do it
292 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);
293 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
295 // Focus element with given id
296 $this->page->requires->js_function_call('focuscontrol', array($focus));
300 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
301 // any other custom CSS can not be overridden via themes and is highly discouraged
302 $urls = $this->page->theme->css_urls($this->page);
303 foreach ($urls as $url) {
304 $this->page->requires->css_theme($url);
307 // Get the theme javascript head and footer
308 $jsurl = $this->page->theme->javascript_url(true);
309 $this->page->requires->js($jsurl, true);
310 $jsurl = $this->page->theme->javascript_url(false);
311 $this->page->requires->js($jsurl);
313 // Perform a browser environment check for the flash version. Should only run once per login session.
314 if (!NO_MOODLE_COOKIES && isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
315 $this->page->requires->js('/lib/swfobject/swfobject.js');
316 $this->page->requires->js_init_call('M.core_flashdetect.init');
319 // Get any HTML from the page_requirements_manager.
320 $output .= $this->page->requires->get_head_code($this->page, $this);
322 // List alternate versions.
323 foreach ($this->page->alternateversions as $type => $alt) {
324 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
325 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
332 * The standard tags (typically skip links) that should be output just inside
333 * the start of the <body> tag. Designed to be called in theme layout.php files.
334 * @return string HTML fragment.
336 public function standard_top_of_body_html() {
337 return $this->page->requires->get_top_of_body_code();
341 * The standard tags (typically performance information and validation links,
342 * if we are in developer debug mode) that should be output in the footer area
343 * of the page. Designed to be called in theme layout.php files.
344 * @return string HTML fragment.
346 public function standard_footer_html() {
349 // This function is normally called from a layout.php file in {@link header()}
350 // but some of the content won't be known until later, so we return a placeholder
351 // for now. This will be replaced with the real content in {@link footer()}.
352 $output = self::PERFORMANCE_INFO_TOKEN;
353 if ($this->page->legacythemeinuse) {
354 // The legacy theme is in use print the notification
355 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
357 if (!empty($CFG->debugpageinfo)) {
358 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
360 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
361 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/admin/purgecaches.php?confirm=1&sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
363 if (!empty($CFG->debugvalidators)) {
364 $output .= '<div class="validators"><ul>
365 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
366 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
367 <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>
374 * The standard tags (typically script tags that are not needed earlier) that
375 * should be output after everything else, . Designed to be called in theme layout.php files.
376 * @return string HTML fragment.
378 public function standard_end_of_body_html() {
379 // This function is normally called from a layout.php file in {@link header()}
380 // but some of the content won't be known until later, so we return a placeholder
381 // for now. This will be replaced with the real content in {@link footer()}.
382 echo self::END_HTML_TOKEN;
386 * Return the standard string that says whether you are logged in (and switched
387 * roles/logged in as another user).
388 * @return string HTML fragment.
390 public function login_info() {
391 global $USER, $CFG, $DB, $SESSION;
393 if (during_initial_install()) {
397 $loginapge = ((string)$this->page->url === get_login_url());
398 $course = $this->page->course;
400 if (session_is_loggedinas()) {
401 $realuser = session_get_realuser();
402 $fullname = fullname($realuser, true);
403 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\">$fullname</a>] ";
408 $loginurl = get_login_url();
410 if (empty($course->id)) {
411 // $course->id is not defined during installation
413 } else if (isloggedin()) {
414 $context = get_context_instance(CONTEXT_COURSE, $course->id);
416 $fullname = fullname($USER, true);
417 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
418 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
419 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
420 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
423 $loggedinas = $realuserinfo.get_string('loggedinasguest');
425 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
427 } else if (is_role_switched($course->id)) { // Has switched roles
429 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
430 $rolename = ': '.format_string($role->name);
432 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
433 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
435 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
436 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
439 $loggedinas = get_string('loggedinnot', 'moodle');
441 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
445 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
447 if (isset($SESSION->justloggedin)) {
448 unset($SESSION->justloggedin);
449 if (!empty($CFG->displayloginfailures)) {
450 if (!isguestuser()) {
451 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
452 $loggedinas .= ' <div class="loginfailures">';
453 if (empty($count->accounts)) {
454 $loggedinas .= get_string('failedloginattempts', '', $count);
456 $loggedinas .= get_string('failedloginattemptsall', '', $count);
458 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
459 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
460 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
462 $loggedinas .= '</div>';
472 * Return the 'back' link that normally appears in the footer.
473 * @return string HTML fragment.
475 public function home_link() {
478 if ($this->page->pagetype == 'site-index') {
479 // Special case for site home page - please do not remove
480 return '<div class="sitelink">' .
481 '<a title="Moodle" href="http://moodle.org/">' .
482 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
484 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
485 // Special case for during install/upgrade.
486 return '<div class="sitelink">'.
487 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
488 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
490 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
491 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
492 get_string('home') . '</a></div>';
495 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
496 format_string($this->page->course->shortname) . '</a></div>';
501 * Redirects the user by any means possible given the current state
503 * This function should not be called directly, it should always be called using
504 * the redirect function in lib/weblib.php
506 * The redirect function should really only be called before page output has started
507 * however it will allow itself to be called during the state STATE_IN_BODY
509 * @param string $encodedurl The URL to send to encoded if required
510 * @param string $message The message to display to the user if any
511 * @param int $delay The delay before redirecting a user, if $message has been
512 * set this is a requirement and defaults to 3, set to 0 no delay
513 * @param boolean $debugdisableredirect this redirect has been disabled for
514 * debugging purposes. Display a message that explains, and don't
515 * trigger the redirect.
516 * @return string The HTML to display to the user before dying, may contain
517 * meta refresh, javascript refresh, and may have set header redirects
519 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
521 $url = str_replace('&', '&', $encodedurl);
523 switch ($this->page->state) {
524 case moodle_page::STATE_BEFORE_HEADER :
525 // No output yet it is safe to delivery the full arsenal of redirect methods
526 if (!$debugdisableredirect) {
527 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
528 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
529 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
531 $output = $this->header();
533 case moodle_page::STATE_PRINTING_HEADER :
534 // We should hopefully never get here
535 throw new coding_exception('You cannot redirect while printing the page header');
537 case moodle_page::STATE_IN_BODY :
538 // We really shouldn't be here but we can deal with this
539 debugging("You should really redirect before you start page output");
540 if (!$debugdisableredirect) {
541 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
543 $output = $this->opencontainers->pop_all_but_last();
545 case moodle_page::STATE_DONE :
546 // Too late to be calling redirect now
547 throw new coding_exception('You cannot redirect after the entire page has been generated');
550 $output .= $this->notification($message, 'redirectmessage');
551 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
552 if ($debugdisableredirect) {
553 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
555 $output .= $this->footer();
560 * Start output by sending the HTTP headers, and printing the HTML <head>
561 * and the start of the <body>.
563 * To control what is printed, you should set properties on $PAGE. If you
564 * are familiar with the old {@link print_header()} function from Moodle 1.9
565 * you will find that there are properties on $PAGE that correspond to most
566 * of the old parameters to could be passed to print_header.
568 * Not that, in due course, the remaining $navigation, $menu parameters here
569 * will be replaced by more properties of $PAGE, but that is still to do.
571 * @return string HTML that you must output this, preferably immediately.
573 public function header() {
576 if (session_is_loggedinas()) {
577 $this->page->add_body_class('userloggedinas');
580 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
582 // Find the appropriate page layout file, based on $this->page->pagelayout.
583 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
584 // Render the layout using the layout file.
585 $rendered = $this->render_page_layout($layoutfile);
587 // Slice the rendered output into header and footer.
588 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
589 if ($cutpos === false) {
590 throw new coding_exception('page layout file ' . $layoutfile .
591 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
593 $header = substr($rendered, 0, $cutpos);
594 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
596 if (empty($this->contenttype)) {
597 debugging('The page layout file did not call $OUTPUT->doctype()');
598 $header = $this->doctype() . $header;
601 send_headers($this->contenttype, $this->page->cacheable);
603 $this->opencontainers->push('header/footer', $footer);
604 $this->page->set_state(moodle_page::STATE_IN_BODY);
606 return $header . $this->skip_link_target('maincontent');
610 * Renders and outputs the page layout file.
611 * @param string $layoutfile The name of the layout file
612 * @return string HTML code
614 protected function render_page_layout($layoutfile) {
615 global $CFG, $SITE, $USER;
616 // The next lines are a bit tricky. The point is, here we are in a method
617 // of a renderer class, and this object may, or may not, be the same as
618 // the global $OUTPUT object. When rendering the page layout file, we want to use
619 // this object. However, people writing Moodle code expect the current
620 // renderer to be called $OUTPUT, not $this, so define a variable called
621 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
624 $COURSE = $this->page->course;
627 include($layoutfile);
628 $rendered = ob_get_contents();
634 * Outputs the page's footer
635 * @return string HTML fragment
637 public function footer() {
640 $output = $this->container_end_all(true);
642 $footer = $this->opencontainers->pop('header/footer');
644 if (debugging() and $DB and $DB->is_transaction_started()) {
645 // TODO: MDL-20625 print warning - transaction will be rolled back
648 // Provide some performance info if required
649 $performanceinfo = '';
650 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
651 $perf = get_performance_info();
652 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
653 error_log("PERF: " . $perf['txt']);
655 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
656 $performanceinfo = $perf['html'];
659 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
661 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
663 $this->page->set_state(moodle_page::STATE_DONE);
665 return $output . $footer;
669 * Close all but the last open container. This is useful in places like error
670 * handling, where you want to close all the open containers (apart from <body>)
671 * before outputting the error message.
672 * @param bool $shouldbenone assert that the stack should be empty now - causes a
673 * developer debug warning if it isn't.
674 * @return string the HTML required to close any open containers inside <body>.
676 public function container_end_all($shouldbenone = false) {
677 return $this->opencontainers->pop_all_but_last($shouldbenone);
681 * Returns lang menu or '', this method also checks forcing of languages in courses.
684 public function lang_menu() {
687 if (empty($CFG->langmenu)) {
691 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
692 // do not show lang menu if language forced
696 $currlang = current_language();
697 $langs = get_string_manager()->get_list_of_translations();
699 if (count($langs) < 2) {
703 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
704 $s->label = get_accesshide(get_string('language'));
705 $s->class = 'langmenu';
706 return $this->render($s);
710 * Output the row of editing icons for a block, as defined by the controls array.
711 * @param array $controls an array like {@link block_contents::$controls}.
712 * @return HTML fragment.
714 public function block_controls($controls) {
715 if (empty($controls)) {
718 $controlshtml = array();
719 foreach ($controls as $control) {
720 $controlshtml[] = html_writer::tag('a',
721 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
722 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
724 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
728 * Prints a nice side block with an optional header.
730 * The content is described
731 * by a {@link block_contents} object.
733 * <div id="inst{$instanceid}" class="block_{$blockname} block">
734 * <div class="header"></div>
735 * <div class="content">
737 * <div class="footer">
740 * <div class="annotation">
744 * @param block_contents $bc HTML for the content
745 * @param string $region the region the block is appearing in.
746 * @return string the HTML to be output.
748 function block(block_contents $bc, $region) {
749 $bc = clone($bc); // Avoid messing up the object passed in.
750 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
751 $bc->collapsible = block_contents::NOT_HIDEABLE;
753 if ($bc->collapsible == block_contents::HIDDEN) {
754 $bc->add_class('hidden');
756 if (!empty($bc->controls)) {
757 $bc->add_class('block_with_controls');
760 $skiptitle = strip_tags($bc->title);
761 if (empty($skiptitle)) {
765 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
766 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
769 $output .= html_writer::start_tag('div', $bc->attributes);
771 $output .= $this->block_header($bc);
772 $output .= $this->block_content($bc);
774 $output .= html_writer::end_tag('div');
776 $output .= $this->block_annotation($bc);
778 $output .= $skipdest;
780 $this->init_block_hider_js($bc);
785 * Produces a header for a block
787 * @param block_contents $bc
790 protected function block_header(block_contents $bc) {
794 $title = html_writer::tag('h2', $bc->title, null);
797 $controlshtml = $this->block_controls($bc->controls);
800 if ($title || $controlshtml) {
801 $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'));
807 * Produces the content area for a block
809 * @param block_contents $bc
812 protected function block_content(block_contents $bc) {
813 $output = html_writer::start_tag('div', array('class' => 'content'));
814 if (!$bc->title && !$this->block_controls($bc->controls)) {
815 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
817 $output .= $bc->content;
818 $output .= $this->block_footer($bc);
819 $output .= html_writer::end_tag('div');
825 * Produces the footer for a block
827 * @param block_contents $bc
830 protected function block_footer(block_contents $bc) {
833 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
839 * Produces the annotation for a block
841 * @param block_contents $bc
844 protected function block_annotation(block_contents $bc) {
846 if ($bc->annotation) {
847 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
853 * Calls the JS require function to hide a block.
854 * @param block_contents $bc A block_contents object
857 protected function init_block_hider_js(block_contents $bc) {
858 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
859 $config = new stdClass;
860 $config->id = $bc->attributes['id'];
861 $config->title = strip_tags($bc->title);
862 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
863 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
864 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
866 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
867 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
872 * Render the contents of a block_list.
873 * @param array $icons the icon for each item.
874 * @param array $items the content of each item.
875 * @return string HTML
877 public function list_block_contents($icons, $items) {
880 foreach ($items as $key => $string) {
881 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
882 if (!empty($icons[$key])) { //test if the content has an assigned icon
883 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
885 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
886 $item .= html_writer::end_tag('li');
888 $row = 1 - $row; // Flip even/odd.
890 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'list'));
894 * Output all the blocks in a particular region.
895 * @param string $region the name of a region on this page.
896 * @return string the HTML to be output.
898 public function blocks_for_region($region) {
899 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
902 foreach ($blockcontents as $bc) {
903 if ($bc instanceof block_contents) {
904 $output .= $this->block($bc, $region);
905 } else if ($bc instanceof block_move_target) {
906 $output .= $this->block_move_target($bc);
908 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
915 * Output a place where the block that is currently being moved can be dropped.
916 * @param block_move_target $target with the necessary details.
917 * @return string the HTML to be output.
919 public function block_move_target($target) {
920 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
924 * Renders a special html link with attached action
926 * @param string|moodle_url $url
927 * @param string $text HTML fragment
928 * @param component_action $action
929 * @param array $attributes associative array of html link attributes + disabled
930 * @return HTML fragment
932 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
933 if (!($url instanceof moodle_url)) {
934 $url = new moodle_url($url);
936 $link = new action_link($url, $text, $action, $attributes);
938 return $this->render($link);
942 * Implementation of action_link rendering
943 * @param action_link $link
944 * @return string HTML fragment
946 protected function render_action_link(action_link $link) {
949 // A disabled link is rendered as formatted text
950 if (!empty($link->attributes['disabled'])) {
951 // do not use div here due to nesting restriction in xhtml strict
952 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
955 $attributes = $link->attributes;
956 unset($link->attributes['disabled']);
957 $attributes['href'] = $link->url;
959 if ($link->actions) {
960 if (empty($attributes['id'])) {
961 $id = html_writer::random_id('action_link');
962 $attributes['id'] = $id;
964 $id = $attributes['id'];
966 foreach ($link->actions as $action) {
967 $this->add_action_handler($action, $id);
971 return html_writer::tag('a', $link->text, $attributes);
976 * Similar to action_link, image is used instead of the text
978 * @param string|moodle_url $url A string URL or moodel_url
979 * @param pix_icon $pixicon
980 * @param component_action $action
981 * @param array $attributes associative array of html link attributes + disabled
982 * @param bool $linktext show title next to image in link
983 * @return string HTML fragment
985 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
986 if (!($url instanceof moodle_url)) {
987 $url = new moodle_url($url);
989 $attributes = (array)$attributes;
991 if (empty($attributes['class'])) {
992 // let ppl override the class via $options
993 $attributes['class'] = 'action-icon';
996 $icon = $this->render($pixicon);
999 $text = $pixicon->attributes['alt'];
1004 return $this->action_link($url, $text.$icon, $action, $attributes);
1008 * Print a message along with button choices for Continue/Cancel
1010 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1012 * @param string $message The question to ask the user
1013 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1014 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1015 * @return string HTML fragment
1017 public function confirm($message, $continue, $cancel) {
1018 if ($continue instanceof single_button) {
1020 } else if (is_string($continue)) {
1021 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1022 } else if ($continue instanceof moodle_url) {
1023 $continue = new single_button($continue, get_string('continue'), 'post');
1025 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1028 if ($cancel instanceof single_button) {
1030 } else if (is_string($cancel)) {
1031 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1032 } else if ($cancel instanceof moodle_url) {
1033 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1035 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1038 $output = $this->box_start('generalbox', 'notice');
1039 $output .= html_writer::tag('p', $message);
1040 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1041 $output .= $this->box_end();
1046 * Returns a form with a single button.
1048 * @param string|moodle_url $url
1049 * @param string $label button text
1050 * @param string $method get or post submit method
1051 * @param array $options associative array {disabled, title, etc.}
1052 * @return string HTML fragment
1054 public function single_button($url, $label, $method='post', array $options=null) {
1055 if (!($url instanceof moodle_url)) {
1056 $url = new moodle_url($url);
1058 $button = new single_button($url, $label, $method);
1060 foreach ((array)$options as $key=>$value) {
1061 if (array_key_exists($key, $button)) {
1062 $button->$key = $value;
1066 return $this->render($button);
1070 * Internal implementation of single_button rendering
1071 * @param single_button $button
1072 * @return string HTML fragment
1074 protected function render_single_button(single_button $button) {
1075 $attributes = array('type' => 'submit',
1076 'value' => $button->label,
1077 'disabled' => $button->disabled ? 'disabled' : null,
1078 'title' => $button->tooltip);
1080 if ($button->actions) {
1081 $id = html_writer::random_id('single_button');
1082 $attributes['id'] = $id;
1083 foreach ($button->actions as $action) {
1084 $this->add_action_handler($action, $id);
1088 // first the input element
1089 $output = html_writer::empty_tag('input', $attributes);
1091 // then hidden fields
1092 $params = $button->url->params();
1093 if ($button->method === 'post') {
1094 $params['sesskey'] = sesskey();
1096 foreach ($params as $var => $val) {
1097 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1100 // then div wrapper for xhtml strictness
1101 $output = html_writer::tag('div', $output);
1103 // now the form itself around it
1104 $url = $button->url->out_omit_querystring(); // url without params
1106 $url = '#'; // there has to be always some action
1108 $attributes = array('method' => $button->method,
1110 'id' => $button->formid);
1111 $output = html_writer::tag('form', $output, $attributes);
1113 // and finally one more wrapper with class
1114 return html_writer::tag('div', $output, array('class' => $button->class));
1118 * Returns a form with a single select widget.
1119 * @param moodle_url $url form action target, includes hidden fields
1120 * @param string $name name of selection field - the changing parameter in url
1121 * @param array $options list of options
1122 * @param string $selected selected element
1123 * @param array $nothing
1124 * @param string $formid
1125 * @return string HTML fragment
1127 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1128 if (!($url instanceof moodle_url)) {
1129 $url = new moodle_url($url);
1131 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1133 return $this->render($select);
1137 * Internal implementation of single_select rendering
1138 * @param single_select $select
1139 * @return string HTML fragment
1141 protected function render_single_select(single_select $select) {
1142 $select = clone($select);
1143 if (empty($select->formid)) {
1144 $select->formid = html_writer::random_id('single_select_f');
1148 $params = $select->url->params();
1149 if ($select->method === 'post') {
1150 $params['sesskey'] = sesskey();
1152 foreach ($params as $name=>$value) {
1153 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1156 if (empty($select->attributes['id'])) {
1157 $select->attributes['id'] = html_writer::random_id('single_select');
1160 if ($select->disabled) {
1161 $select->attributes['disabled'] = 'disabled';
1164 if ($select->tooltip) {
1165 $select->attributes['title'] = $select->tooltip;
1168 if ($select->label) {
1169 $output .= html_writer::label($select->label, $select->attributes['id']);
1172 if ($select->helpicon instanceof help_icon) {
1173 $output .= $this->render($select->helpicon);
1174 } else if ($select->helpicon instanceof old_help_icon) {
1175 $output .= $this->render($select->helpicon);
1178 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1180 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1181 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1183 $nothing = empty($select->nothing) ? false : key($select->nothing);
1184 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1186 // then div wrapper for xhtml strictness
1187 $output = html_writer::tag('div', $output);
1189 // now the form itself around it
1190 $formattributes = array('method' => $select->method,
1191 'action' => $select->url->out_omit_querystring(),
1192 'id' => $select->formid);
1193 $output = html_writer::tag('form', $output, $formattributes);
1195 // and finally one more wrapper with class
1196 return html_writer::tag('div', $output, array('class' => $select->class));
1200 * Returns a form with a url select widget.
1201 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1202 * @param string $selected selected element
1203 * @param array $nothing
1204 * @param string $formid
1205 * @return string HTML fragment
1207 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1208 $select = new url_select($urls, $selected, $nothing, $formid);
1209 return $this->render($select);
1213 * Internal implementation of url_select rendering
1214 * @param single_select $select
1215 * @return string HTML fragment
1217 protected function render_url_select(url_select $select) {
1220 $select = clone($select);
1221 if (empty($select->formid)) {
1222 $select->formid = html_writer::random_id('url_select_f');
1225 if (empty($select->attributes['id'])) {
1226 $select->attributes['id'] = html_writer::random_id('url_select');
1229 if ($select->disabled) {
1230 $select->attributes['disabled'] = 'disabled';
1233 if ($select->tooltip) {
1234 $select->attributes['title'] = $select->tooltip;
1239 if ($select->label) {
1240 $output .= html_writer::label($select->label, $select->attributes['id']);
1243 if ($select->helpicon instanceof help_icon) {
1244 $output .= $this->render($select->helpicon);
1245 } else if ($select->helpicon instanceof old_help_icon) {
1246 $output .= $this->render($select->helpicon);
1249 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1250 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1252 foreach ($select->urls as $k=>$v) {
1254 // optgroup structure
1255 foreach ($v as $optgrouptitle => $optgroupoptions) {
1256 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1257 if (empty($optionurl)) {
1258 $safeoptionurl = '';
1259 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1260 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1261 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1262 } else if (strpos($optionurl, '/') !== 0) {
1263 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1266 $safeoptionurl = $optionurl;
1268 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1272 // plain list structure
1274 // nothing selected option
1275 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1276 $k = str_replace($CFG->wwwroot, '', $k);
1277 } else if (strpos($k, '/') !== 0) {
1278 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1284 $selected = $select->selected;
1285 if (!empty($selected)) {
1286 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1287 $selected = str_replace($CFG->wwwroot, '', $selected);
1288 } else if (strpos($selected, '/') !== 0) {
1289 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1293 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1294 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1296 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1297 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1299 $nothing = empty($select->nothing) ? false : key($select->nothing);
1300 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1302 // then div wrapper for xhtml strictness
1303 $output = html_writer::tag('div', $output);
1305 // now the form itself around it
1306 $formattributes = array('method' => 'post',
1307 'action' => new moodle_url('/course/jumpto.php'),
1308 'id' => $select->formid);
1309 $output = html_writer::tag('form', $output, $formattributes);
1311 // and finally one more wrapper with class
1312 return html_writer::tag('div', $output, array('class' => $select->class));
1316 * Returns a string containing a link to the user documentation.
1317 * Also contains an icon by default. Shown to teachers and admin only.
1318 * @param string $path The page link after doc root and language, no leading slash.
1319 * @param string $text The text to be displayed for the link
1322 public function doc_link($path, $text = '') {
1325 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1327 $url = new moodle_url(get_docs_url($path));
1329 $attributes = array('href'=>$url);
1330 if (!empty($CFG->doctonewwindow)) {
1331 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1334 return html_writer::tag('a', $icon.$text, $attributes);
1339 * @param string $pix short pix name
1340 * @param string $alt mandatory alt attribute
1341 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1342 * @param array $attributes htm lattributes
1343 * @return string HTML fragment
1345 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1346 $icon = new pix_icon($pix, $alt, $component, $attributes);
1347 return $this->render($icon);
1352 * @param pix_icon $icon
1353 * @return string HTML fragment
1355 protected function render_pix_icon(pix_icon $icon) {
1356 $attributes = $icon->attributes;
1357 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1358 return html_writer::empty_tag('img', $attributes);
1362 * Produces the html that represents this rating in the UI
1363 * @param $page the page object on which this rating will appear
1365 function render_rating(rating $rating) {
1367 static $havesetupjavascript = false;
1369 if( $rating->settings->aggregationmethod == RATING_AGGREGATE_NONE ){
1370 return null;//ratings are turned off
1373 $useajax = !empty($CFG->enableajax);
1375 //include required Javascript
1376 if( !$havesetupjavascript && $useajax ) {
1377 $this->page->requires->js_init_call('M.core_rating.init');
1378 $havesetupjavascript = true;
1381 //check the item we're rating was created in the assessable time window
1382 $inassessablewindow = true;
1383 if ( $rating->settings->assesstimestart && $rating->settings->assesstimefinish ) {
1384 if ($rating->itemtimecreated < $rating->settings->assesstimestart || $rating->itemtimecreated > $rating->settings->assesstimefinish) {
1385 $inassessablewindow = false;
1389 $strrate = get_string("rate", "rating");
1390 $ratinghtml = ''; //the string we'll return
1392 //permissions check - can they view the aggregate?
1393 $canviewaggregate = false;
1395 //if its the current user's item and they have permission to view the aggregate on their own items
1396 if ( $rating->itemuserid==$USER->id && $rating->settings->permissions->view && $rating->settings->pluginpermissions->view) {
1397 $canviewaggregate = true;
1400 //if the item doesnt belong to anyone or its another user's items and they can see the aggregate on items they don't own
1401 //Note that viewany doesnt mean you can see the aggregate or ratings of your own items
1402 if ( (empty($rating->itemuserid) or $rating->itemuserid!=$USER->id) && $rating->settings->permissions->viewany && $rating->settings->pluginpermissions->viewany ) {
1403 $canviewaggregate = true;
1406 if ($canviewaggregate==true) {
1407 $aggregatelabel = '';
1408 switch ($rating->settings->aggregationmethod) {
1409 case RATING_AGGREGATE_AVERAGE :
1410 $aggregatelabel .= get_string("aggregateavg", "rating");
1412 case RATING_AGGREGATE_COUNT :
1413 $aggregatelabel .= get_string("aggregatecount", "rating");
1415 case RATING_AGGREGATE_MAXIMUM :
1416 $aggregatelabel .= get_string("aggregatemax", "rating");
1418 case RATING_AGGREGATE_MINIMUM :
1419 $aggregatelabel .= get_string("aggregatemin", "rating");
1421 case RATING_AGGREGATE_SUM :
1422 $aggregatelabel .= get_string("aggregatesum", "rating");
1425 $aggregatelabel .= get_string('labelsep', 'langconfig');
1427 //$scalemax = 0;//no longer displaying scale max
1430 //only display aggregate if aggregation method isn't COUNT
1431 if ($rating->aggregate && $rating->settings->aggregationmethod!= RATING_AGGREGATE_COUNT) {
1432 if ($rating->settings->aggregationmethod!= RATING_AGGREGATE_SUM && is_array($rating->settings->scale->scaleitems)) {
1433 $aggregatestr .= $rating->settings->scale->scaleitems[round($rating->aggregate)];//round aggregate as we're using it as an index
1435 else { //aggregation is SUM or the scale is numeric
1436 $aggregatestr .= round($rating->aggregate,1);
1442 $countstr = html_writer::start_tag('span', array('id'=>"ratingcount{$rating->itemid}"));
1443 if ($rating->count>0) {
1444 $countstr .= "({$rating->count})";
1446 $countstr .= html_writer::end_tag('span');
1448 //$aggregatehtml = "{$ratingstr} / $scalemax ({$rating->count}) ";
1449 $aggregatehtml = "<span id='ratingaggregate{$rating->itemid}'>{$aggregatestr}</span> $countstr ";
1451 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1452 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1453 $url = "/rating/index.php?contextid={$rating->context->id}&itemid={$rating->itemid}&scaleid={$rating->settings->scale->id}";
1454 $nonpopuplink = new moodle_url($url);
1455 $popuplink = new moodle_url("$url&popup=1");
1457 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1458 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1460 $ratinghtml .= $aggregatehtml;
1465 //if the item doesn't belong to the current user, the user has permission to rate
1466 //and we're within the assessable period
1467 if ($rating->itemuserid!=$USER->id
1468 && $rating->settings->permissions->rate
1469 && $rating->settings->pluginpermissions->rate
1470 && $inassessablewindow) {
1472 //start the rating form
1473 $formstart = html_writer::start_tag('form',
1474 array('id'=>"postrating{$rating->itemid}", 'class'=>'postratingform', 'method'=>'post', 'action'=>"{$CFG->wwwroot}/rating/rate.php"));
1476 $formstart .= html_writer::start_tag('div', array('class'=>'ratingform'));
1478 //add the hidden inputs
1480 $attributes = array('type'=>'hidden', 'class'=>'ratinginput', 'name'=>'contextid', 'value'=>$rating->context->id);
1481 $formstart .= html_writer::empty_tag('input', $attributes);
1483 $attributes['name'] = 'itemid';
1484 $attributes['value'] = $rating->itemid;
1485 $formstart .= html_writer::empty_tag('input', $attributes);
1487 $attributes['name'] = 'scaleid';
1488 $attributes['value'] = $rating->settings->scale->id;
1489 $formstart .= html_writer::empty_tag('input', $attributes);
1491 $attributes['name'] = 'returnurl';
1492 $attributes['value'] = $rating->settings->returnurl;
1493 $formstart .= html_writer::empty_tag('input', $attributes);
1495 $attributes['name'] = 'rateduserid';
1496 $attributes['value'] = $rating->itemuserid;
1497 $formstart .= html_writer::empty_tag('input', $attributes);
1499 $attributes['name'] = 'aggregation';
1500 $attributes['value'] = $rating->settings->aggregationmethod;
1501 $formstart .= html_writer::empty_tag('input', $attributes);
1503 $attributes['name'] = 'sesskey';
1504 $attributes['value'] = sesskey();;
1505 $formstart .= html_writer::empty_tag('input', $attributes);
1507 if (empty($ratinghtml)) {
1508 $ratinghtml .= $strrate.': ';
1511 $ratinghtml = $formstart.$ratinghtml;
1513 //generate an array of values for numeric scales
1514 $scalearray = $rating->settings->scale->scaleitems;
1515 if (!is_array($scalearray)) { //almost certainly a numerical scale
1516 $intscalearray = intval($scalearray);//just in case they've passed "5" instead of 5
1517 $scalearray = array();
1518 if( is_int($intscalearray) && $intscalearray>0 ) {
1519 for($i=0; $i<=$rating->settings->scale->scaleitems; $i++) {
1520 $scalearray[$i] = $i;
1525 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $scalearray;
1526 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid));
1528 //output submit button
1530 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1532 $attributes = array('type'=>'submit', 'class'=>'postratingmenusubmit', 'id'=>'postratingsubmit'.$rating->itemid, 'value'=>s(get_string('rate', 'rating')));
1533 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1535 if (is_array($rating->settings->scale->scaleitems)) {
1536 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1538 $ratinghtml .= html_writer::end_tag('span');
1539 $ratinghtml .= html_writer::end_tag('div');
1540 $ratinghtml .= html_writer::end_tag('form');
1547 * Centered heading with attached help button (same title text)
1548 * and optional icon attached
1549 * @param string $text A heading text
1550 * @param string $helpidentifier The keyword that defines a help page
1551 * @param string $component component name
1552 * @param string|moodle_url $icon
1553 * @param string $iconalt icon alt text
1554 * @return string HTML fragment
1556 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1559 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1563 if ($helpidentifier) {
1564 $help = $this->help_icon($helpidentifier, $component);
1567 return $this->heading($image.$text.$help, 2, 'main help');
1571 * Print a help icon.
1573 * @deprecated since Moodle 2.0
1574 * @param string $page The keyword that defines a help page
1575 * @param string $title A descriptive text for accessibility only
1576 * @param string $component component name
1577 * @param string|bool $linktext true means use $title as link text, string means link text value
1578 * @return string HTML fragment
1580 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1581 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1582 $icon = new old_help_icon($helpidentifier, $title, $component);
1583 if ($linktext === true) {
1584 $icon->linktext = $title;
1585 } else if (!empty($linktext)) {
1586 $icon->linktext = $linktext;
1588 return $this->render($icon);
1592 * Implementation of user image rendering.
1593 * @param help_icon $helpicon
1594 * @return string HTML fragment
1596 protected function render_old_help_icon(old_help_icon $helpicon) {
1599 // first get the help image icon
1600 $src = $this->pix_url('help');
1602 if (empty($helpicon->linktext)) {
1603 $alt = $helpicon->title;
1605 $alt = get_string('helpwiththis');
1608 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1609 $output = html_writer::empty_tag('img', $attributes);
1611 // add the link text if given
1612 if (!empty($helpicon->linktext)) {
1613 // the spacing has to be done through CSS
1614 $output .= $helpicon->linktext;
1617 // now create the link around it
1618 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1620 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1621 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1623 $attributes = array('href'=>$url, 'title'=>$title);
1624 $id = html_writer::random_id('helpicon');
1625 $attributes['id'] = $id;
1626 $output = html_writer::tag('a', $output, $attributes);
1628 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1631 return html_writer::tag('span', $output, array('class' => 'helplink'));
1635 * Print a help icon.
1637 * @param string $identifier The keyword that defines a help page
1638 * @param string $component component name
1639 * @param string|bool $linktext true means use $title as link text, string means link text value
1640 * @return string HTML fragment
1642 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1643 $icon = new help_icon($identifier, $component);
1644 $icon->diag_strings();
1645 if ($linktext === true) {
1646 $icon->linktext = get_string($icon->identifier, $icon->component);
1647 } else if (!empty($linktext)) {
1648 $icon->linktext = $linktext;
1650 return $this->render($icon);
1654 * Implementation of user image rendering.
1655 * @param help_icon $helpicon
1656 * @return string HTML fragment
1658 protected function render_help_icon(help_icon $helpicon) {
1661 // first get the help image icon
1662 $src = $this->pix_url('help');
1664 $title = get_string($helpicon->identifier, $helpicon->component);
1666 if (empty($helpicon->linktext)) {
1669 $alt = get_string('helpwiththis');
1672 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1673 $output = html_writer::empty_tag('img', $attributes);
1675 // add the link text if given
1676 if (!empty($helpicon->linktext)) {
1677 // the spacing has to be done through CSS
1678 $output .= $helpicon->linktext;
1681 // now create the link around it
1682 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1684 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1685 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1687 $attributes = array('href'=>$url, 'title'=>$title);
1688 $id = html_writer::random_id('helpicon');
1689 $attributes['id'] = $id;
1690 $output = html_writer::tag('a', $output, $attributes);
1692 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1695 return html_writer::tag('span', $output, array('class' => 'helplink'));
1699 * Print scale help icon.
1701 * @param int $courseid
1702 * @param object $scale instance
1703 * @return string HTML fragment
1705 public function help_icon_scale($courseid, stdClass $scale) {
1708 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1710 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1712 $scaleid = abs($scale->id);
1714 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1715 $action = new popup_action('click', $link, 'ratingscale');
1717 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1721 * Creates and returns a spacer image with optional line break.
1723 * @param array $attributes
1725 * @return string HTML fragment
1727 public function spacer(array $attributes = null, $br = false) {
1728 $attributes = (array)$attributes;
1729 if (empty($attributes['width'])) {
1730 $attributes['width'] = 1;
1732 if (empty($attributes['height'])) {
1733 $attributes['height'] = 1;
1735 $attributes['class'] = 'spacer';
1737 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1740 $output .= '<br />';
1747 * Print the specified user's avatar.
1749 * User avatar may be obtained in two ways:
1751 * // Option 1: (shortcut for simple cases, preferred way)
1752 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1753 * $OUTPUT->user_picture($user, array('popup'=>true));
1756 * $userpic = new user_picture($user);
1757 * // Set properties of $userpic
1758 * $userpic->popup = true;
1759 * $OUTPUT->render($userpic);
1762 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1763 * If any of these are missing, the database is queried. Avoid this
1764 * if at all possible, particularly for reports. It is very bad for performance.
1765 * @param array $options associative array with user picture options, used only if not a user_picture object,
1767 * - courseid=$this->page->course->id (course id of user profile in link)
1768 * - size=35 (size of image)
1769 * - link=true (make image clickable - the link leads to user profile)
1770 * - popup=false (open in popup)
1771 * - alttext=true (add image alt attribute)
1772 * - class = image class attribute (default 'userpicture')
1773 * @return string HTML fragment
1775 public function user_picture(stdClass $user, array $options = null) {
1776 $userpicture = new user_picture($user);
1777 foreach ((array)$options as $key=>$value) {
1778 if (array_key_exists($key, $userpicture)) {
1779 $userpicture->$key = $value;
1782 return $this->render($userpicture);
1786 * Internal implementation of user image rendering.
1787 * @param user_picture $userpicture
1790 protected function render_user_picture(user_picture $userpicture) {
1793 $user = $userpicture->user;
1795 if ($userpicture->alttext) {
1796 if (!empty($user->imagealt)) {
1797 $alt = $user->imagealt;
1799 $alt = get_string('pictureof', '', fullname($user));
1805 if (empty($userpicture->size)) {
1808 } else if ($userpicture->size === true or $userpicture->size == 1) {
1811 } else if ($userpicture->size >= 50) {
1813 $size = $userpicture->size;
1816 $size = $userpicture->size;
1819 $class = $userpicture->class;
1821 if ($user->picture == 1) {
1822 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1823 $src = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', $file);
1825 } else if ($user->picture == 2) {
1826 //TODO: gravatar user icon support
1828 } else { // Print default user pictures (use theme version if available)
1829 $class .= ' defaultuserpic';
1830 $src = $this->pix_url('u/' . $file);
1833 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1835 // get the image html output fisrt
1836 $output = html_writer::empty_tag('img', $attributes);;
1838 // then wrap it in link if needed
1839 if (!$userpicture->link) {
1843 if (empty($userpicture->courseid)) {
1844 $courseid = $this->page->course->id;
1846 $courseid = $userpicture->courseid;
1849 if ($courseid == SITEID) {
1850 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1852 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1855 $attributes = array('href'=>$url);
1857 if ($userpicture->popup) {
1858 $id = html_writer::random_id('userpicture');
1859 $attributes['id'] = $id;
1860 $this->add_action_handler(new popup_action('click', $url), $id);
1863 return html_writer::tag('a', $output, $attributes);
1867 * Internal implementation of file tree viewer items rendering.
1871 public function htmllize_file_tree($dir) {
1872 if (empty($dir['subdirs']) and empty($dir['files'])) {
1876 foreach ($dir['subdirs'] as $subdir) {
1877 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1879 foreach ($dir['files'] as $file) {
1880 $filename = $file->get_filename();
1881 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1888 * Print the file picker
1891 * $OUTPUT->file_picker($options);
1894 * @param array $options associative array with file manager options
1898 * client_id=>uniqid(),
1899 * acepted_types=>'*',
1900 * return_types=>FILE_INTERNAL,
1901 * context=>$PAGE->context
1902 * @return string HTML fragment
1904 public function file_picker($options) {
1905 $fp = new file_picker($options);
1906 return $this->render($fp);
1909 * Internal implementation of file picker rendering.
1910 * @param file_picker $fp
1913 public function render_file_picker(file_picker $fp) {
1914 global $CFG, $OUTPUT, $USER;
1915 $options = $fp->options;
1916 $client_id = $options->client_id;
1917 $strsaved = get_string('filesaved', 'repository');
1918 $straddfile = get_string('openpicker', 'repository');
1919 $strloading = get_string('loading', 'repository');
1920 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1922 $currentfile = $options->currentfile;
1923 if (empty($currentfile)) {
1924 $currentfile = get_string('nofilesattached', 'repository');
1926 if ($options->maxbytes) {
1927 $size = $options->maxbytes;
1929 $size = get_max_upload_file_size();
1934 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
1937 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1940 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1942 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}" />
1943 <span> $maxsize </span>
1946 if ($options->env != 'url') {
1948 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1956 * Prints the 'Update this Modulename' button that appears on module pages.
1958 * @param string $cmid the course_module id.
1959 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1960 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1962 public function update_module_button($cmid, $modulename) {
1964 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1965 $modulename = get_string('modulename', $modulename);
1966 $string = get_string('updatethis', '', $modulename);
1967 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1968 return $this->single_button($url, $string);
1975 * Prints a "Turn editing on/off" button in a form.
1976 * @param moodle_url $url The URL + params to send through when clicking the button
1977 * @return string HTML the button
1979 public function edit_button(moodle_url $url) {
1981 $url->param('sesskey', sesskey());
1982 if ($this->page->user_is_editing()) {
1983 $url->param('edit', 'off');
1984 $editstring = get_string('turneditingoff');
1986 $url->param('edit', 'on');
1987 $editstring = get_string('turneditingon');
1990 return $this->single_button($url, $editstring);
1994 * Prints a simple button to close a window
1996 * @param string $text The lang string for the button's label (already output from get_string())
1997 * @return string html fragment
1999 public function close_window_button($text='') {
2001 $text = get_string('closewindow');
2003 $button = new single_button(new moodle_url('#'), $text, 'get');
2004 $button->add_action(new component_action('click', 'close_window'));
2006 return $this->container($this->render($button), 'closewindow');
2010 * Output an error message. By default wraps the error message in <span class="error">.
2011 * If the error message is blank, nothing is output.
2012 * @param string $message the error message.
2013 * @return string the HTML to output.
2015 public function error_text($message) {
2016 if (empty($message)) {
2019 return html_writer::tag('span', $message, array('class' => 'error'));
2023 * Do not call this function directly.
2025 * To terminate the current script with a fatal error, call the {@link print_error}
2026 * function, or throw an exception. Doing either of those things will then call this
2027 * function to display the error, before terminating the execution.
2029 * @param string $message The message to output
2030 * @param string $moreinfourl URL where more info can be found about the error
2031 * @param string $link Link for the Continue button
2032 * @param array $backtrace The execution backtrace
2033 * @param string $debuginfo Debugging information
2034 * @return string the HTML to output.
2036 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2041 if ($this->has_started()) {
2042 // we can not always recover properly here, we have problems with output buffering,
2043 // html tables, etc.
2044 $output .= $this->opencontainers->pop_all_but_last();
2047 // It is really bad if library code throws exception when output buffering is on,
2048 // because the buffered text would be printed before our start of page.
2049 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2050 while (ob_get_level() > 0) {
2051 $obbuffer .= ob_get_clean();
2054 // Header not yet printed
2055 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2056 // server protocol should be always present, because this render
2057 // can not be used from command line or when outputting custom XML
2058 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2060 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2061 $this->page->set_url('/'); // no url
2062 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2063 $this->page->set_title(get_string('error'));
2064 $this->page->set_heading($this->page->course->fullname);
2065 $output .= $this->header();
2068 $message = '<p class="errormessage">' . $message . '</p>'.
2069 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2070 get_string('moreinformation') . '</a></p>';
2071 $output .= $this->box($message, 'errorbox');
2073 if (debugging('', DEBUG_DEVELOPER)) {
2074 if (!empty($debuginfo)) {
2075 $debuginfo = s($debuginfo); // removes all nasty JS
2076 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2077 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2079 if (!empty($backtrace)) {
2080 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2082 if ($obbuffer !== '' ) {
2083 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2087 if (!empty($link)) {
2088 $output .= $this->continue_button($link);
2091 $output .= $this->footer();
2093 // Padding to encourage IE to display our error page, rather than its own.
2094 $output .= str_repeat(' ', 512);
2100 * Output a notification (that is, a status message about something that has
2103 * @param string $message the message to print out
2104 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2105 * @return string the HTML to output.
2107 public function notification($message, $classes = 'notifyproblem') {
2108 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2112 * Print a continue button that goes to a particular URL.
2114 * @param string|moodle_url $url The url the button goes to.
2115 * @return string the HTML to output.
2117 public function continue_button($url) {
2118 if (!($url instanceof moodle_url)) {
2119 $url = new moodle_url($url);
2121 $button = new single_button($url, get_string('continue'), 'get');
2122 $button->class = 'continuebutton';
2124 return $this->render($button);
2128 * Prints a single paging bar to provide access to other pages (usually in a search)
2130 * @param int $totalcount The total number of entries available to be paged through
2131 * @param int $page The page you are currently viewing
2132 * @param int $perpage The number of entries that should be shown per page
2133 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2134 * @param string $pagevar name of page parameter that holds the page number
2135 * @return string the HTML to output.
2137 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2138 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2139 return $this->render($pb);
2143 * Internal implementation of paging bar rendering.
2144 * @param paging_bar $pagingbar
2147 protected function render_paging_bar(paging_bar $pagingbar) {
2149 $pagingbar = clone($pagingbar);
2150 $pagingbar->prepare($this, $this->page, $this->target);
2152 if ($pagingbar->totalcount > $pagingbar->perpage) {
2153 $output .= get_string('page') . ':';
2155 if (!empty($pagingbar->previouslink)) {
2156 $output .= ' (' . $pagingbar->previouslink . ') ';
2159 if (!empty($pagingbar->firstlink)) {
2160 $output .= ' ' . $pagingbar->firstlink . ' ...';
2163 foreach ($pagingbar->pagelinks as $link) {
2164 $output .= "  $link";
2167 if (!empty($pagingbar->lastlink)) {
2168 $output .= ' ...' . $pagingbar->lastlink . ' ';
2171 if (!empty($pagingbar->nextlink)) {
2172 $output .= '  (' . $pagingbar->nextlink . ')';
2176 return html_writer::tag('div', $output, array('class' => 'paging'));
2180 * Output the place a skip link goes to.
2181 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2182 * @return string the HTML to output.
2184 public function skip_link_target($id = null) {
2185 return html_writer::tag('span', '', array('id' => $id));
2190 * @param string $text The text of the heading
2191 * @param int $level The level of importance of the heading. Defaulting to 2
2192 * @param string $classes A space-separated list of CSS classes
2193 * @param string $id An optional ID
2194 * @return string the HTML to output.
2196 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2197 $level = (integer) $level;
2198 if ($level < 1 or $level > 6) {
2199 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2201 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2206 * @param string $contents The contents of the box
2207 * @param string $classes A space-separated list of CSS classes
2208 * @param string $id An optional ID
2209 * @return string the HTML to output.
2211 public function box($contents, $classes = 'generalbox', $id = null) {
2212 return $this->box_start($classes, $id) . $contents . $this->box_end();
2216 * Outputs the opening section of a box.
2217 * @param string $classes A space-separated list of CSS classes
2218 * @param string $id An optional ID
2219 * @return string the HTML to output.
2221 public function box_start($classes = 'generalbox', $id = null) {
2222 $this->opencontainers->push('box', html_writer::end_tag('div'));
2223 return html_writer::start_tag('div', array('id' => $id,
2224 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2228 * Outputs the closing section of a box.
2229 * @return string the HTML to output.
2231 public function box_end() {
2232 return $this->opencontainers->pop('box');
2236 * Outputs a container.
2237 * @param string $contents The contents of the box
2238 * @param string $classes A space-separated list of CSS classes
2239 * @param string $id An optional ID
2240 * @return string the HTML to output.
2242 public function container($contents, $classes = null, $id = null) {
2243 return $this->container_start($classes, $id) . $contents . $this->container_end();
2247 * Outputs the opening section of a container.
2248 * @param string $classes A space-separated list of CSS classes
2249 * @param string $id An optional ID
2250 * @return string the HTML to output.
2252 public function container_start($classes = null, $id = null) {
2253 $this->opencontainers->push('container', html_writer::end_tag('div'));
2254 return html_writer::start_tag('div', array('id' => $id,
2255 'class' => renderer_base::prepare_classes($classes)));
2259 * Outputs the closing section of a container.
2260 * @return string the HTML to output.
2262 public function container_end() {
2263 return $this->opencontainers->pop('container');
2267 * Make nested HTML lists out of the items
2269 * The resulting list will look something like this:
2273 * <<li>><div class='tree_item parent'>(item contents)</div>
2275 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2281 * @param array[]tree_item $items
2282 * @param array[string]string $attrs html attributes passed to the top of
2284 * @return string HTML
2286 function tree_block_contents($items, $attrs=array()) {
2287 // exit if empty, we don't want an empty ul element
2288 if (empty($items)) {
2291 // array of nested li elements
2293 foreach ($items as $item) {
2294 // this applies to the li item which contains all child lists too
2295 $content = $item->content($this);
2296 $liclasses = array($item->get_css_type());
2297 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2298 $liclasses[] = 'collapsed';
2300 if ($item->isactive === true) {
2301 $liclasses[] = 'current_branch';
2303 $liattr = array('class'=>join(' ',$liclasses));
2304 // class attribute on the div item which only contains the item content
2305 $divclasses = array('tree_item');
2306 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2307 $divclasses[] = 'branch';
2309 $divclasses[] = 'leaf';
2311 if (!empty($item->classes) && count($item->classes)>0) {
2312 $divclasses[] = join(' ', $item->classes);
2314 $divattr = array('class'=>join(' ', $divclasses));
2315 if (!empty($item->id)) {
2316 $divattr['id'] = $item->id;
2318 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2319 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2320 $content = html_writer::empty_tag('hr') . $content;
2322 $content = html_writer::tag('li', $content, $liattr);
2325 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2329 * Return the navbar content so that it can be echoed out by the layout
2330 * @return string XHTML navbar
2332 public function navbar() {
2333 //return $this->page->navbar->content();
2335 $items = $this->page->navbar->get_items();
2339 $htmlblocks = array();
2340 // Iterate the navarray and display each node
2341 $itemcount = count($items);
2342 $separator = get_separator();
2343 for ($i=0;$i < $itemcount;$i++) {
2345 $item->hideicon = true;
2347 $content = html_writer::tag('li', $this->render($item));
2349 $content = html_writer::tag('li', $separator.$this->render($item));
2351 $htmlblocks[] = $content;
2354 //accessibility: heading for navbar list (MDL-20446)
2355 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2356 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2358 return $navbarcontent;
2361 protected function render_navigation_node(navigation_node $item) {
2362 $content = $item->get_content();
2363 $title = $item->get_title();
2364 if ($item->icon instanceof renderable && !$item->hideicon) {
2365 $icon = $this->render($item->icon);
2366 $content = $icon.$content; // use CSS for spacing of icons
2368 if ($item->helpbutton !== null) {
2369 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton'));
2371 if ($content === '') {
2374 if ($item->action instanceof action_link) {
2375 //TODO: to be replaced with something else
2376 $link = $item->action;
2377 if ($item->hidden) {
2378 $link->add_class('dimmed');
2380 $content = $this->output->render($link);
2381 } else if ($item->action instanceof moodle_url) {
2382 $attributes = array();
2383 if ($title !== '') {
2384 $attributes['title'] = $title;
2386 if ($item->hidden) {
2387 $attributes['class'] = 'dimmed_text';
2389 $content = html_writer::link($item->action, $content, $attributes);
2391 } else if (is_string($item->action) || empty($item->action)) {
2392 $attributes = array();
2393 if ($title !== '') {
2394 $attributes['title'] = $title;
2396 if ($item->hidden) {
2397 $attributes['class'] = 'dimmed_text';
2399 $content = html_writer::tag('span', $content, $attributes);
2405 * Accessibility: Right arrow-like character is
2406 * used in the breadcrumb trail, course navigation menu
2407 * (previous/next activity), calendar, and search forum block.
2408 * If the theme does not set characters, appropriate defaults
2409 * are set automatically. Please DO NOT
2410 * use < > » - these are confusing for blind users.
2413 public function rarrow() {
2414 return $this->page->theme->rarrow;
2418 * Accessibility: Right arrow-like character is
2419 * used in the breadcrumb trail, course navigation menu
2420 * (previous/next activity), calendar, and search forum block.
2421 * If the theme does not set characters, appropriate defaults
2422 * are set automatically. Please DO NOT
2423 * use < > » - these are confusing for blind users.
2426 public function larrow() {
2427 return $this->page->theme->larrow;
2431 * Returns the colours of the small MP3 player
2434 public function filter_mediaplugin_colors() {
2435 return $this->page->theme->filter_mediaplugin_colors;
2439 * Returns the colours of the big MP3 player
2442 public function resource_mp3player_colors() {
2443 return $this->page->theme->resource_mp3player_colors;
2447 * Returns the custom menu if one has been set
2449 * A custom menu can be configured by browsing to
2450 * Settings: Administration > Appearance > Themes > Theme settings
2451 * and then configuring the custommenu config setting as described.
2455 public function custom_menu() {
2457 if (empty($CFG->custommenuitems)) {
2460 $custommenu = new custom_menu();
2461 return $this->render_custom_menu($custommenu);
2465 * Renders a custom menu object (located in outputcomponents.php)
2467 * The custom menu this method produces makes use of the YUI3 menunav widget
2468 * and requires very specific html elements and classes.
2470 * @staticvar int $menucount
2471 * @param custom_menu $menu
2474 protected function render_custom_menu(custom_menu $menu) {
2475 static $menucount = 0;
2476 // If the menu has no children return an empty string
2477 if (!$menu->has_children()) {
2480 // Increment the menu count. This is used for ID's that get worked with
2481 // in JavaScript as is essential
2483 // Initialise this custom menu
2484 $this->page->requires->js_init_call('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2485 // Build the root nodes as required by YUI
2486 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2487 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2488 $content .= html_writer::start_tag('ul');
2489 // Render each child
2490 foreach ($menu->get_children() as $item) {
2491 $content .= $this->render_custom_menu_item($item);
2493 // Close the open tags
2494 $content .= html_writer::end_tag('ul');
2495 $content .= html_writer::end_tag('div');
2496 $content .= html_writer::end_tag('div');
2497 // Return the custom menu
2502 * Renders a custom menu node as part of a submenu
2504 * The custom menu this method produces makes use of the YUI3 menunav widget
2505 * and requires very specific html elements and classes.
2507 * @see render_custom_menu()
2509 * @staticvar int $submenucount
2510 * @param custom_menu_item $menunode
2513 protected function render_custom_menu_item(custom_menu_item $menunode) {
2514 // Required to ensure we get unique trackable id's
2515 static $submenucount = 0;
2516 if ($menunode->has_children()) {
2517 // If the child has menus render it as a sub menu
2519 $content = html_writer::start_tag('li');
2520 if ($menunode->get_url() !== null) {
2521 $url = $menunode->get_url();
2523 $url = '#cm_submenu_'.$submenucount;
2525 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2526 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2527 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2528 $content .= html_writer::start_tag('ul');
2529 foreach ($menunode->get_children() as $menunode) {
2530 $content .= $this->render_custom_menu_item($menunode);
2532 $content .= html_writer::end_tag('ul');
2533 $content .= html_writer::end_tag('div');
2534 $content .= html_writer::end_tag('div');
2535 $content .= html_writer::end_tag('li');
2537 // The node doesn't have children so produce a final menuitem
2538 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2539 if ($menunode->get_url() !== null) {
2540 $url = $menunode->get_url();
2544 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2545 $content .= html_writer::end_tag('li');
2547 // Return the sub menu
2552 * Renders the image_gallery component and initialises its JavaScript
2554 * @param image_gallery $imagegallery
2557 protected function render_image_gallery(image_gallery $imagegallery) {
2558 $this->page->requires->yui_module(array('gallery-lightbox','gallery-lightbox-skin'),
2559 'Y.Lightbox.init', null, '2010.04.08-12-35');
2560 if (count($imagegallery->images) == 0) {
2563 $classes = array('image_gallery');
2564 if ($imagegallery->displayfirstimageonly) {
2565 $classes[] = 'oneimageonly';
2567 $content = html_writer::start_tag('div', array('class'=>join(' ', $classes)));
2568 foreach ($imagegallery->images as $image) {
2569 $content .= html_writer::tag('a', html_writer::empty_tag('img', $image->thumb), $image->link);
2571 $content .= html_writer::end_tag('div');
2580 * A renderer that generates output for command-line scripts.
2582 * The implementation of this renderer is probably incomplete.
2584 * @copyright 2009 Tim Hunt
2585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2588 class core_renderer_cli extends core_renderer {
2590 * Returns the page header.
2591 * @return string HTML fragment
2593 public function header() {
2594 return $this->page->heading . "\n";
2598 * Returns a template fragment representing a Heading.
2599 * @param string $text The text of the heading
2600 * @param int $level The level of importance of the heading
2601 * @param string $classes A space-separated list of CSS classes
2602 * @param string $id An optional ID
2603 * @return string A template fragment for a heading
2605 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2609 return '=>' . $text;
2611 return '-->' . $text;
2618 * Returns a template fragment representing a fatal error.
2619 * @param string $message The message to output
2620 * @param string $moreinfourl URL where more info can be found about the error
2621 * @param string $link Link for the Continue button
2622 * @param array $backtrace The execution backtrace
2623 * @param string $debuginfo Debugging information
2624 * @return string A template fragment for a fatal error
2626 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2627 $output = "!!! $message !!!\n";
2629 if (debugging('', DEBUG_DEVELOPER)) {
2630 if (!empty($debuginfo)) {
2631 $this->notification($debuginfo, 'notifytiny');
2633 if (!empty($backtrace)) {
2634 $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2640 * Returns a template fragment representing a notification.
2641 * @param string $message The message to include
2642 * @param string $classes A space-separated list of CSS classes
2643 * @return string A template fragment for a notification
2645 public function notification($message, $classes = 'notifyproblem') {
2646 $message = clean_text($message);
2647 if ($classes === 'notifysuccess') {
2648 return "++ $message ++\n";
2650 return "!! $message !!\n";
2656 * A renderer that generates output for ajax scripts.
2658 * This renderer prevents accidental sends back only json
2659 * encoded error messages, all other output is ignored.
2661 * @copyright 2010 Petr Skoda
2662 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2665 class core_renderer_ajax extends core_renderer {
2667 * Returns a template fragment representing a fatal error.
2668 * @param string $message The message to output
2669 * @param string $moreinfourl URL where more info can be found about the error
2670 * @param string $link Link for the Continue button
2671 * @param array $backtrace The execution backtrace
2672 * @param string $debuginfo Debugging information
2673 * @return string A template fragment for a fatal error
2675 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2678 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2680 $e = new stdClass();
2681 $e->error = $message;
2682 $e->stacktrace = NULL;
2683 $e->debuginfo = NULL;
2684 $e->reproductionlink = NULL;
2685 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2686 $e->reproductionlink = $link;
2687 if (!empty($debuginfo)) {
2688 $e->debuginfo = $debuginfo;
2690 if (!empty($backtrace)) {
2691 $e->stacktrace = format_backtrace($backtrace, true);
2695 return json_encode($e);
2698 public function notification($message, $classes = 'notifyproblem') {
2701 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2704 public function header() {
2705 // unfortunately YUI iframe upload does not support application/json
2706 if (!empty($_FILES)) {
2707 @header('Content-type: text/plain');
2709 @header('Content-type: application/json');
2712 /// Headers to make it not cacheable and json
2713 @header('Cache-Control: no-store, no-cache, must-revalidate');
2714 @header('Cache-Control: post-check=0, pre-check=0', false);
2715 @header('Pragma: no-cache');
2716 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2717 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2718 @header('Accept-Ranges: none');
2721 public function footer() {
2724 public function heading($text, $level = 2, $classes = 'main', $id = null) {