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
{
206 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
207 * in layout files instead.
208 * @var string used in {@link header()}.
211 const MAIN_CONTENT_TOKEN
= '[MAIN CONTENT GOES HERE]';
212 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
213 protected $contenttype;
214 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
215 protected $metarefreshtag = '';
216 /** @var string unique token */
217 protected $unique_end_html_token;
218 /** @var string unique token */
219 protected $unique_performance_info_token;
220 /** @var string unique token */
221 protected $unique_main_content_token;
225 * @param moodle_page $page the page we are doing output for.
226 * @param string $target one of rendering target constants
228 public function __construct(moodle_page
$page, $target) {
229 $this->opencontainers
= $page->opencontainers
;
231 $this->target
= $target;
233 $this->unique_end_html_token
= '%%ENDHTML-'.sesskey().'%%';
234 $this->unique_performance_info_token
= '%%PERFORMANCEINFO-'.sesskey().'%%';
235 $this->unique_main_content_token
= '[MAIN CONTENT GOES HERE - '.sesskey().']';
239 * Get the DOCTYPE declaration that should be used with this page. Designed to
240 * be called in theme layout.php files.
241 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
243 public function doctype() {
246 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
247 $this->contenttype
= 'text/html; charset=utf-8';
249 if (empty($CFG->xmlstrictheaders
)) {
253 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
254 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
255 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
256 // Firefox and other browsers that can cope natively with XHTML.
257 $this->contenttype
= 'application/xhtml+xml; charset=utf-8';
259 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
260 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
261 $this->contenttype
= 'application/xml; charset=utf-8';
262 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot
. '/lib/xhtml.xsl"?>' . "\n";
268 return $prolog . $doctype;
272 * The attributes that should be added to the <html> tag. Designed to
273 * be called in theme layout.php files.
274 * @return string HTML fragment.
276 public function htmlattributes() {
277 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
281 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
282 * that should be included in the <head> tag. Designed to be called in theme
284 * @return string HTML fragment.
286 public function standard_head_html() {
287 global $CFG, $SESSION;
289 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
290 $output .= '<meta name="keywords" content="moodle, ' . $this->page
->title
. '" />' . "\n";
291 if (!$this->page
->cacheable
) {
292 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
293 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
295 // This is only set by the {@link redirect()} method
296 $output .= $this->metarefreshtag
;
298 // Check if a periodic refresh delay has been set and make sure we arn't
299 // already meta refreshing
300 if ($this->metarefreshtag
=='' && $this->page
->periodicrefreshdelay
!==null) {
301 $output .= '<meta http-equiv="refresh" content="'.$this->page
->periodicrefreshdelay
.';url='.$this->page
->url
->out().'" />';
304 // flow player embedding support
305 $this->page
->requires
->js_function_call('M.util.load_flowplayer');
307 $this->page
->requires
->js_function_call('setTimeout', array('fix_column_widths()', 20));
309 $focus = $this->page
->focuscontrol
;
310 if (!empty($focus)) {
311 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
312 // This is a horrifically bad way to handle focus but it is passed in
313 // through messy formslib::moodleform
314 $this->page
->requires
->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
315 } else if (strpos($focus, '.')!==false) {
316 // Old style of focus, bad way to do it
317 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
);
318 $this->page
->requires
->js_function_call('old_onload_focus', explode('.', $focus, 2));
320 // Focus element with given id
321 $this->page
->requires
->js_function_call('focuscontrol', array($focus));
325 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
326 // any other custom CSS can not be overridden via themes and is highly discouraged
327 $urls = $this->page
->theme
->css_urls($this->page
);
328 foreach ($urls as $url) {
329 $this->page
->requires
->css_theme($url);
332 // Get the theme javascript head and footer
333 $jsurl = $this->page
->theme
->javascript_url(true);
334 $this->page
->requires
->js($jsurl, true);
335 $jsurl = $this->page
->theme
->javascript_url(false);
336 $this->page
->requires
->js($jsurl);
338 // Get any HTML from the page_requirements_manager.
339 $output .= $this->page
->requires
->get_head_code($this->page
, $this);
341 // List alternate versions.
342 foreach ($this->page
->alternateversions
as $type => $alt) {
343 $output .= html_writer
::empty_tag('link', array('rel' => 'alternate',
344 'type' => $type, 'title' => $alt->title
, 'href' => $alt->url
));
347 if (!empty($CFG->additionalhtmlhead
)) {
348 $output .= "\n".$CFG->additionalhtmlhead
;
355 * The standard tags (typically skip links) that should be output just inside
356 * the start of the <body> tag. Designed to be called in theme layout.php files.
357 * @return string HTML fragment.
359 public function standard_top_of_body_html() {
361 $output = $this->page
->requires
->get_top_of_body_code();
362 if (!empty($CFG->additionalhtmltopofbody
)) {
363 $output .= "\n".$CFG->additionalhtmltopofbody
;
369 * The standard tags (typically performance information and validation links,
370 * if we are in developer debug mode) that should be output in the footer area
371 * of the page. Designed to be called in theme layout.php files.
372 * @return string HTML fragment.
374 public function standard_footer_html() {
375 global $CFG, $SCRIPT;
377 // This function is normally called from a layout.php file in {@link header()}
378 // but some of the content won't be known until later, so we return a placeholder
379 // for now. This will be replaced with the real content in {@link footer()}.
380 $output = $this->unique_performance_info_token
;
381 if ($this->page
->devicetypeinuse
== 'legacy') {
382 // The legacy theme is in use print the notification
383 $output .= html_writer
::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
386 // Get links to switch device types (only shown for users not on a default device)
387 $output .= $this->theme_switch_links();
389 if (!empty($CFG->debugpageinfo
)) {
390 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page
->debug_summary() . '</div>';
392 if (debugging(null, DEBUG_DEVELOPER
) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) { // Only in developer mode
393 // Add link to profiling report if necessary
394 if (function_exists('profiling_is_running') && profiling_is_running()) {
395 $txt = get_string('profiledscript', 'admin');
396 $title = get_string('profiledscriptview', 'admin');
397 $url = $CFG->wwwroot
. '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
398 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
399 $output .= '<div class="profilingfooter">' . $link . '</div>';
401 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/purgecaches.php?confirm=1&sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
403 if (!empty($CFG->debugvalidators
)) {
404 $output .= '<div class="validators"><ul>
405 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
406 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
407 <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>
410 if (!empty($CFG->additionalhtmlfooter
)) {
411 $output .= "\n".$CFG->additionalhtmlfooter
;
417 * Returns standard main content placeholder.
418 * Designed to be called in theme layout.php files.
419 * @return string HTML fragment.
421 public function main_content() {
422 return $this->unique_main_content_token
;
426 * The standard tags (typically script tags that are not needed earlier) that
427 * should be output after everything else, . Designed to be called in theme layout.php files.
428 * @return string HTML fragment.
430 public function standard_end_of_body_html() {
431 // This function is normally called from a layout.php file in {@link header()}
432 // but some of the content won't be known until later, so we return a placeholder
433 // for now. This will be replaced with the real content in {@link footer()}.
434 return $this->unique_end_html_token
;
438 * Return the standard string that says whether you are logged in (and switched
439 * roles/logged in as another user).
440 * @return string HTML fragment.
442 public function login_info() {
443 global $USER, $CFG, $DB, $SESSION;
445 if (during_initial_install()) {
449 $loginapge = ((string)$this->page
->url
=== get_login_url());
450 $course = $this->page
->course
;
452 if (session_is_loggedinas()) {
453 $realuser = session_get_realuser();
454 $fullname = fullname($realuser, true);
455 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\">$fullname</a>] ";
460 $loginurl = get_login_url();
462 if (empty($course->id
)) {
463 // $course->id is not defined during installation
465 } else if (isloggedin()) {
466 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
468 $fullname = fullname($USER, true);
469 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
470 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
471 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid
))) {
472 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
475 $loggedinas = $realuserinfo.get_string('loggedinasguest');
477 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
479 } else if (is_role_switched($course->id
)) { // Has switched roles
481 if ($role = $DB->get_record('role', array('id'=>$USER->access
['rsw'][$context->path
]))) {
482 $rolename = ': '.format_string($role->name
);
484 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
485 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
487 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
488 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
491 $loggedinas = get_string('loggedinnot', 'moodle');
493 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
497 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
499 if (isset($SESSION->justloggedin
)) {
500 unset($SESSION->justloggedin
);
501 if (!empty($CFG->displayloginfailures
)) {
502 if (!isguestuser()) {
503 if ($count = count_login_failures($CFG->displayloginfailures
, $USER->username
, $USER->lastlogin
)) {
504 $loggedinas .= ' <div class="loginfailures">';
505 if (empty($count->accounts
)) {
506 $loggedinas .= get_string('failedloginattempts', '', $count);
508 $loggedinas .= get_string('failedloginattemptsall', '', $count);
510 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM
))) {
511 $loggedinas .= ' (<a href="'.$CFG->wwwroot
.'/report/log/index.php'.
512 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
514 $loggedinas .= '</div>';
524 * Return the 'back' link that normally appears in the footer.
525 * @return string HTML fragment.
527 public function home_link() {
530 if ($this->page
->pagetype
== 'site-index') {
531 // Special case for site home page - please do not remove
532 return '<div class="sitelink">' .
533 '<a title="Moodle" href="http://moodle.org/">' .
534 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
536 } else if (!empty($CFG->target_release
) && $CFG->target_release
!= $CFG->release
) {
537 // Special case for during install/upgrade.
538 return '<div class="sitelink">'.
539 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
540 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
542 } else if ($this->page
->course
->id
== $SITE->id ||
strpos($this->page
->pagetype
, 'course-view') === 0) {
543 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/">' .
544 get_string('home') . '</a></div>';
547 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/course/view.php?id=' . $this->page
->course
->id
. '">' .
548 format_string($this->page
->course
->shortname
, true, array('context' => $this->page
->context
)) . '</a></div>';
553 * Redirects the user by any means possible given the current state
555 * This function should not be called directly, it should always be called using
556 * the redirect function in lib/weblib.php
558 * The redirect function should really only be called before page output has started
559 * however it will allow itself to be called during the state STATE_IN_BODY
561 * @param string $encodedurl The URL to send to encoded if required
562 * @param string $message The message to display to the user if any
563 * @param int $delay The delay before redirecting a user, if $message has been
564 * set this is a requirement and defaults to 3, set to 0 no delay
565 * @param boolean $debugdisableredirect this redirect has been disabled for
566 * debugging purposes. Display a message that explains, and don't
567 * trigger the redirect.
568 * @return string The HTML to display to the user before dying, may contain
569 * meta refresh, javascript refresh, and may have set header redirects
571 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
573 $url = str_replace('&', '&', $encodedurl);
575 switch ($this->page
->state
) {
576 case moodle_page
::STATE_BEFORE_HEADER
:
577 // No output yet it is safe to delivery the full arsenal of redirect methods
578 if (!$debugdisableredirect) {
579 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
580 $this->metarefreshtag
= '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
581 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, ($delay +
3));
583 $output = $this->header();
585 case moodle_page
::STATE_PRINTING_HEADER
:
586 // We should hopefully never get here
587 throw new coding_exception('You cannot redirect while printing the page header');
589 case moodle_page
::STATE_IN_BODY
:
590 // We really shouldn't be here but we can deal with this
591 debugging("You should really redirect before you start page output");
592 if (!$debugdisableredirect) {
593 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, $delay);
595 $output = $this->opencontainers
->pop_all_but_last();
597 case moodle_page
::STATE_DONE
:
598 // Too late to be calling redirect now
599 throw new coding_exception('You cannot redirect after the entire page has been generated');
602 $output .= $this->notification($message, 'redirectmessage');
603 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
604 if ($debugdisableredirect) {
605 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
607 $output .= $this->footer();
612 * Start output by sending the HTTP headers, and printing the HTML <head>
613 * and the start of the <body>.
615 * To control what is printed, you should set properties on $PAGE. If you
616 * are familiar with the old {@link print_header()} function from Moodle 1.9
617 * you will find that there are properties on $PAGE that correspond to most
618 * of the old parameters to could be passed to print_header.
620 * Not that, in due course, the remaining $navigation, $menu parameters here
621 * will be replaced by more properties of $PAGE, but that is still to do.
623 * @return string HTML that you must output this, preferably immediately.
625 public function header() {
628 if (session_is_loggedinas()) {
629 $this->page
->add_body_class('userloggedinas');
632 $this->page
->set_state(moodle_page
::STATE_PRINTING_HEADER
);
634 // Find the appropriate page layout file, based on $this->page->pagelayout.
635 $layoutfile = $this->page
->theme
->layout_file($this->page
->pagelayout
);
636 // Render the layout using the layout file.
637 $rendered = $this->render_page_layout($layoutfile);
639 // Slice the rendered output into header and footer.
640 $cutpos = strpos($rendered, $this->unique_main_content_token
);
641 if ($cutpos === false) {
642 $cutpos = strpos($rendered, self
::MAIN_CONTENT_TOKEN
);
643 $token = self
::MAIN_CONTENT_TOKEN
;
645 $token = $this->unique_main_content_token
;
648 if ($cutpos === false) {
649 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
651 $header = substr($rendered, 0, $cutpos);
652 $footer = substr($rendered, $cutpos +
strlen($token));
654 if (empty($this->contenttype
)) {
655 debugging('The page layout file did not call $OUTPUT->doctype()');
656 $header = $this->doctype() . $header;
659 send_headers($this->contenttype
, $this->page
->cacheable
);
661 $this->opencontainers
->push('header/footer', $footer);
662 $this->page
->set_state(moodle_page
::STATE_IN_BODY
);
664 return $header . $this->skip_link_target('maincontent');
668 * Renders and outputs the page layout file.
669 * @param string $layoutfile The name of the layout file
670 * @return string HTML code
672 protected function render_page_layout($layoutfile) {
673 global $CFG, $SITE, $USER;
674 // The next lines are a bit tricky. The point is, here we are in a method
675 // of a renderer class, and this object may, or may not, be the same as
676 // the global $OUTPUT object. When rendering the page layout file, we want to use
677 // this object. However, people writing Moodle code expect the current
678 // renderer to be called $OUTPUT, not $this, so define a variable called
679 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
682 $COURSE = $this->page
->course
;
685 include($layoutfile);
686 $rendered = ob_get_contents();
692 * Outputs the page's footer
693 * @return string HTML fragment
695 public function footer() {
698 $output = $this->container_end_all(true);
700 $footer = $this->opencontainers
->pop('header/footer');
702 if (debugging() and $DB and $DB->is_transaction_started()) {
703 // TODO: MDL-20625 print warning - transaction will be rolled back
706 // Provide some performance info if required
707 $performanceinfo = '';
708 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
709 $perf = get_performance_info();
710 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
711 error_log("PERF: " . $perf['txt']);
713 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
714 $performanceinfo = $perf['html'];
717 $footer = str_replace($this->unique_performance_info_token
, $performanceinfo, $footer);
719 $footer = str_replace($this->unique_end_html_token
, $this->page
->requires
->get_end_code(), $footer);
721 $this->page
->set_state(moodle_page
::STATE_DONE
);
723 return $output . $footer;
727 * Close all but the last open container. This is useful in places like error
728 * handling, where you want to close all the open containers (apart from <body>)
729 * before outputting the error message.
730 * @param bool $shouldbenone assert that the stack should be empty now - causes a
731 * developer debug warning if it isn't.
732 * @return string the HTML required to close any open containers inside <body>.
734 public function container_end_all($shouldbenone = false) {
735 return $this->opencontainers
->pop_all_but_last($shouldbenone);
739 * Returns lang menu or '', this method also checks forcing of languages in courses.
742 public function lang_menu() {
745 if (empty($CFG->langmenu
)) {
749 if ($this->page
->course
!= SITEID
and !empty($this->page
->course
->lang
)) {
750 // do not show lang menu if language forced
754 $currlang = current_language();
755 $langs = get_string_manager()->get_list_of_translations();
757 if (count($langs) < 2) {
761 $s = new single_select($this->page
->url
, 'lang', $langs, $currlang, null);
762 $s->label
= get_accesshide(get_string('language'));
763 $s->class = 'langmenu';
764 return $this->render($s);
768 * Output the row of editing icons for a block, as defined by the controls array.
769 * @param array $controls an array like {@link block_contents::$controls}.
770 * @return HTML fragment.
772 public function block_controls($controls) {
773 if (empty($controls)) {
776 $controlshtml = array();
777 foreach ($controls as $control) {
778 $controlshtml[] = html_writer
::tag('a',
779 html_writer
::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
780 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
782 return html_writer
::tag('div', implode('', $controlshtml), array('class' => 'commands'));
786 * Prints a nice side block with an optional header.
788 * The content is described
789 * by a {@link block_contents} object.
791 * <div id="inst{$instanceid}" class="block_{$blockname} block">
792 * <div class="header"></div>
793 * <div class="content">
795 * <div class="footer">
798 * <div class="annotation">
802 * @param block_contents $bc HTML for the content
803 * @param string $region the region the block is appearing in.
804 * @return string the HTML to be output.
806 function block(block_contents
$bc, $region) {
807 $bc = clone($bc); // Avoid messing up the object passed in.
808 if (empty($bc->blockinstanceid
) ||
!strip_tags($bc->title
)) {
809 $bc->collapsible
= block_contents
::NOT_HIDEABLE
;
811 if ($bc->collapsible
== block_contents
::HIDDEN
) {
812 $bc->add_class('hidden');
814 if (!empty($bc->controls
)) {
815 $bc->add_class('block_with_controls');
818 $skiptitle = strip_tags($bc->title
);
819 if (empty($skiptitle)) {
823 $output = html_writer
::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid
, 'class' => 'skip-block'));
824 $skipdest = html_writer
::tag('span', '', array('id' => 'sb-' . $bc->skipid
, 'class' => 'skip-block-to'));
827 $output .= html_writer
::start_tag('div', $bc->attributes
);
829 $output .= $this->block_header($bc);
830 $output .= $this->block_content($bc);
832 $output .= html_writer
::end_tag('div');
834 $output .= $this->block_annotation($bc);
836 $output .= $skipdest;
838 $this->init_block_hider_js($bc);
843 * Produces a header for a block
845 * @param block_contents $bc
848 protected function block_header(block_contents
$bc) {
852 $title = html_writer
::tag('h2', $bc->title
, null);
855 $controlshtml = $this->block_controls($bc->controls
);
858 if ($title ||
$controlshtml) {
859 $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'));
865 * Produces the content area for a block
867 * @param block_contents $bc
870 protected function block_content(block_contents
$bc) {
871 $output = html_writer
::start_tag('div', array('class' => 'content'));
872 if (!$bc->title
&& !$this->block_controls($bc->controls
)) {
873 $output .= html_writer
::tag('div', '', array('class'=>'block_action notitle'));
875 $output .= $bc->content
;
876 $output .= $this->block_footer($bc);
877 $output .= html_writer
::end_tag('div');
883 * Produces the footer for a block
885 * @param block_contents $bc
888 protected function block_footer(block_contents
$bc) {
891 $output .= html_writer
::tag('div', $bc->footer
, array('class' => 'footer'));
897 * Produces the annotation for a block
899 * @param block_contents $bc
902 protected function block_annotation(block_contents
$bc) {
904 if ($bc->annotation
) {
905 $output .= html_writer
::tag('div', $bc->annotation
, array('class' => 'blockannotation'));
911 * Calls the JS require function to hide a block.
912 * @param block_contents $bc A block_contents object
915 protected function init_block_hider_js(block_contents
$bc) {
916 if (!empty($bc->attributes
['id']) and $bc->collapsible
!= block_contents
::NOT_HIDEABLE
) {
917 $config = new stdClass
;
918 $config->id
= $bc->attributes
['id'];
919 $config->title
= strip_tags($bc->title
);
920 $config->preference
= 'block' . $bc->blockinstanceid
. 'hidden';
921 $config->tooltipVisible
= get_string('hideblocka', 'access', $config->title
);
922 $config->tooltipHidden
= get_string('showblocka', 'access', $config->title
);
924 $this->page
->requires
->js_init_call('M.util.init_block_hider', array($config));
925 user_preference_allow_ajax_update($config->preference
, PARAM_BOOL
);
930 * Render the contents of a block_list.
931 * @param array $icons the icon for each item.
932 * @param array $items the content of each item.
933 * @return string HTML
935 public function list_block_contents($icons, $items) {
938 foreach ($items as $key => $string) {
939 $item = html_writer
::start_tag('li', array('class' => 'r' . $row));
940 if (!empty($icons[$key])) { //test if the content has an assigned icon
941 $item .= html_writer
::tag('div', $icons[$key], array('class' => 'icon column c0'));
943 $item .= html_writer
::tag('div', $string, array('class' => 'column c1'));
944 $item .= html_writer
::end_tag('li');
946 $row = 1 - $row; // Flip even/odd.
948 return html_writer
::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
952 * Output all the blocks in a particular region.
953 * @param string $region the name of a region on this page.
954 * @return string the HTML to be output.
956 public function blocks_for_region($region) {
957 $blockcontents = $this->page
->blocks
->get_content_for_region($region, $this);
960 foreach ($blockcontents as $bc) {
961 if ($bc instanceof block_contents
) {
962 $output .= $this->block($bc, $region);
963 } else if ($bc instanceof block_move_target
) {
964 $output .= $this->block_move_target($bc);
966 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
973 * Output a place where the block that is currently being moved can be dropped.
974 * @param block_move_target $target with the necessary details.
975 * @return string the HTML to be output.
977 public function block_move_target($target) {
978 return html_writer
::tag('a', html_writer
::tag('span', $target->text
, array('class' => 'accesshide')), array('href' => $target->url
, 'class' => 'blockmovetarget'));
982 * Renders a special html link with attached action
984 * @param string|moodle_url $url
985 * @param string $text HTML fragment
986 * @param component_action $action
987 * @param array $attributes associative array of html link attributes + disabled
988 * @return HTML fragment
990 public function action_link($url, $text, component_action
$action = null, array $attributes=null) {
991 if (!($url instanceof moodle_url
)) {
992 $url = new moodle_url($url);
994 $link = new action_link($url, $text, $action, $attributes);
996 return $this->render($link);
1000 * Implementation of action_link rendering
1001 * @param action_link $link
1002 * @return string HTML fragment
1004 protected function render_action_link(action_link
$link) {
1007 if ($link->text
instanceof renderable
) {
1008 $text = $this->render($link->text
);
1010 $text = $link->text
;
1013 // A disabled link is rendered as formatted text
1014 if (!empty($link->attributes
['disabled'])) {
1015 // do not use div here due to nesting restriction in xhtml strict
1016 return html_writer
::tag('span', $text, array('class'=>'currentlink'));
1019 $attributes = $link->attributes
;
1020 unset($link->attributes
['disabled']);
1021 $attributes['href'] = $link->url
;
1023 if ($link->actions
) {
1024 if (empty($attributes['id'])) {
1025 $id = html_writer
::random_id('action_link');
1026 $attributes['id'] = $id;
1028 $id = $attributes['id'];
1030 foreach ($link->actions
as $action) {
1031 $this->add_action_handler($action, $id);
1035 return html_writer
::tag('a', $text, $attributes);
1040 * Similar to action_link, image is used instead of the text
1042 * @param string|moodle_url $url A string URL or moodel_url
1043 * @param pix_icon $pixicon
1044 * @param component_action $action
1045 * @param array $attributes associative array of html link attributes + disabled
1046 * @param bool $linktext show title next to image in link
1047 * @return string HTML fragment
1049 public function action_icon($url, pix_icon
$pixicon, component_action
$action = null, array $attributes = null, $linktext=false) {
1050 if (!($url instanceof moodle_url
)) {
1051 $url = new moodle_url($url);
1053 $attributes = (array)$attributes;
1055 if (empty($attributes['class'])) {
1056 // let ppl override the class via $options
1057 $attributes['class'] = 'action-icon';
1060 $icon = $this->render($pixicon);
1063 $text = $pixicon->attributes
['alt'];
1068 return $this->action_link($url, $text.$icon, $action, $attributes);
1072 * Print a message along with button choices for Continue/Cancel
1074 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1076 * @param string $message The question to ask the user
1077 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1078 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1079 * @return string HTML fragment
1081 public function confirm($message, $continue, $cancel) {
1082 if ($continue instanceof single_button
) {
1084 } else if (is_string($continue)) {
1085 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1086 } else if ($continue instanceof moodle_url
) {
1087 $continue = new single_button($continue, get_string('continue'), 'post');
1089 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1092 if ($cancel instanceof single_button
) {
1094 } else if (is_string($cancel)) {
1095 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1096 } else if ($cancel instanceof moodle_url
) {
1097 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1099 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1102 $output = $this->box_start('generalbox', 'notice');
1103 $output .= html_writer
::tag('p', $message);
1104 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1105 $output .= $this->box_end();
1110 * Returns a form with a single button.
1112 * @param string|moodle_url $url
1113 * @param string $label button text
1114 * @param string $method get or post submit method
1115 * @param array $options associative array {disabled, title, etc.}
1116 * @return string HTML fragment
1118 public function single_button($url, $label, $method='post', array $options=null) {
1119 if (!($url instanceof moodle_url
)) {
1120 $url = new moodle_url($url);
1122 $button = new single_button($url, $label, $method);
1124 foreach ((array)$options as $key=>$value) {
1125 if (array_key_exists($key, $button)) {
1126 $button->$key = $value;
1130 return $this->render($button);
1134 * Internal implementation of single_button rendering
1135 * @param single_button $button
1136 * @return string HTML fragment
1138 protected function render_single_button(single_button
$button) {
1139 $attributes = array('type' => 'submit',
1140 'value' => $button->label
,
1141 'disabled' => $button->disabled ?
'disabled' : null,
1142 'title' => $button->tooltip
);
1144 if ($button->actions
) {
1145 $id = html_writer
::random_id('single_button');
1146 $attributes['id'] = $id;
1147 foreach ($button->actions
as $action) {
1148 $this->add_action_handler($action, $id);
1152 // first the input element
1153 $output = html_writer
::empty_tag('input', $attributes);
1155 // then hidden fields
1156 $params = $button->url
->params();
1157 if ($button->method
=== 'post') {
1158 $params['sesskey'] = sesskey();
1160 foreach ($params as $var => $val) {
1161 $output .= html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1164 // then div wrapper for xhtml strictness
1165 $output = html_writer
::tag('div', $output);
1167 // now the form itself around it
1168 if ($button->method
=== 'get') {
1169 $url = $button->url
->out_omit_querystring(true); // url without params, the anchor part allowed
1171 $url = $button->url
->out_omit_querystring(); // url without params, the anchor part not allowed
1174 $url = '#'; // there has to be always some action
1176 $attributes = array('method' => $button->method
,
1178 'id' => $button->formid
);
1179 $output = html_writer
::tag('form', $output, $attributes);
1181 // and finally one more wrapper with class
1182 return html_writer
::tag('div', $output, array('class' => $button->class));
1186 * Returns a form with a single select widget.
1187 * @param moodle_url $url form action target, includes hidden fields
1188 * @param string $name name of selection field - the changing parameter in url
1189 * @param array $options list of options
1190 * @param string $selected selected element
1191 * @param array $nothing
1192 * @param string $formid
1193 * @return string HTML fragment
1195 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
1196 if (!($url instanceof moodle_url
)) {
1197 $url = new moodle_url($url);
1199 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1201 return $this->render($select);
1205 * Internal implementation of single_select rendering
1206 * @param single_select $select
1207 * @return string HTML fragment
1209 protected function render_single_select(single_select
$select) {
1210 $select = clone($select);
1211 if (empty($select->formid
)) {
1212 $select->formid
= html_writer
::random_id('single_select_f');
1216 $params = $select->url
->params();
1217 if ($select->method
=== 'post') {
1218 $params['sesskey'] = sesskey();
1220 foreach ($params as $name=>$value) {
1221 $output .= html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1224 if (empty($select->attributes
['id'])) {
1225 $select->attributes
['id'] = html_writer
::random_id('single_select');
1228 if ($select->disabled
) {
1229 $select->attributes
['disabled'] = 'disabled';
1232 if ($select->tooltip
) {
1233 $select->attributes
['title'] = $select->tooltip
;
1236 if ($select->label
) {
1237 $output .= html_writer
::label($select->label
, $select->attributes
['id'], false, $select->labelattributes
);
1240 if ($select->helpicon
instanceof help_icon
) {
1241 $output .= $this->render($select->helpicon
);
1242 } else if ($select->helpicon
instanceof old_help_icon
) {
1243 $output .= $this->render($select->helpicon
);
1245 $output .= html_writer
::select($select->options
, $select->name
, $select->selected
, $select->nothing
, $select->attributes
);
1247 $go = html_writer
::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1248 $output .= html_writer
::tag('noscript', html_writer
::tag('div', $go), array('style'=>'inline'));
1250 $nothing = empty($select->nothing
) ?
false : key($select->nothing
);
1251 $this->page
->requires
->js_init_call('M.util.init_select_autosubmit', array($select->formid
, $select->attributes
['id'], $nothing));
1253 // then div wrapper for xhtml strictness
1254 $output = html_writer
::tag('div', $output);
1256 // now the form itself around it
1257 if ($select->method
=== 'get') {
1258 $url = $select->url
->out_omit_querystring(true); // url without params, the anchor part allowed
1260 $url = $select->url
->out_omit_querystring(); // url without params, the anchor part not allowed
1262 $formattributes = array('method' => $select->method
,
1264 'id' => $select->formid
);
1265 $output = html_writer
::tag('form', $output, $formattributes);
1267 // and finally one more wrapper with class
1268 return html_writer
::tag('div', $output, array('class' => $select->class));
1272 * Returns a form with a url select widget.
1273 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1274 * @param string $selected selected element
1275 * @param array $nothing
1276 * @param string $formid
1277 * @return string HTML fragment
1279 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1280 $select = new url_select($urls, $selected, $nothing, $formid);
1281 return $this->render($select);
1285 * Internal implementation of url_select rendering
1286 * @param single_select $select
1287 * @return string HTML fragment
1289 protected function render_url_select(url_select
$select) {
1292 $select = clone($select);
1293 if (empty($select->formid
)) {
1294 $select->formid
= html_writer
::random_id('url_select_f');
1297 if (empty($select->attributes
['id'])) {
1298 $select->attributes
['id'] = html_writer
::random_id('url_select');
1301 if ($select->disabled
) {
1302 $select->attributes
['disabled'] = 'disabled';
1305 if ($select->tooltip
) {
1306 $select->attributes
['title'] = $select->tooltip
;
1311 if ($select->label
) {
1312 $output .= html_writer
::label($select->label
, $select->attributes
['id'], false, $select->labelattributes
);
1315 if ($select->helpicon
instanceof help_icon
) {
1316 $output .= $this->render($select->helpicon
);
1317 } else if ($select->helpicon
instanceof old_help_icon
) {
1318 $output .= $this->render($select->helpicon
);
1321 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1322 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1324 foreach ($select->urls
as $k=>$v) {
1326 // optgroup structure
1327 foreach ($v as $optgrouptitle => $optgroupoptions) {
1328 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1329 if (empty($optionurl)) {
1330 $safeoptionurl = '';
1331 } else if (strpos($optionurl, $CFG->wwwroot
.'/') === 0) {
1332 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1333 $safeoptionurl = str_replace($CFG->wwwroot
, '', $optionurl);
1334 } else if (strpos($optionurl, '/') !== 0) {
1335 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1338 $safeoptionurl = $optionurl;
1340 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1344 // plain list structure
1346 // nothing selected option
1347 } else if (strpos($k, $CFG->wwwroot
.'/') === 0) {
1348 $k = str_replace($CFG->wwwroot
, '', $k);
1349 } else if (strpos($k, '/') !== 0) {
1350 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1356 $selected = $select->selected
;
1357 if (!empty($selected)) {
1358 if (strpos($select->selected
, $CFG->wwwroot
.'/') === 0) {
1359 $selected = str_replace($CFG->wwwroot
, '', $selected);
1360 } else if (strpos($selected, '/') !== 0) {
1361 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1365 $output .= html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1366 $output .= html_writer
::select($urls, 'jump', $selected, $select->nothing
, $select->attributes
);
1368 if (!$select->showbutton
) {
1369 $go = html_writer
::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1370 $output .= html_writer
::tag('noscript', html_writer
::tag('div', $go), array('style'=>'inline'));
1371 $nothing = empty($select->nothing
) ?
false : key($select->nothing
);
1372 $output .= $this->page
->requires
->js_init_call('M.util.init_url_select', array($select->formid
, $select->attributes
['id'], $nothing));
1374 $output .= html_writer
::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton
));
1377 // then div wrapper for xhtml strictness
1378 $output = html_writer
::tag('div', $output);
1380 // now the form itself around it
1381 $formattributes = array('method' => 'post',
1382 'action' => new moodle_url('/course/jumpto.php'),
1383 'id' => $select->formid
);
1384 $output = html_writer
::tag('form', $output, $formattributes);
1386 // and finally one more wrapper with class
1387 return html_writer
::tag('div', $output, array('class' => $select->class));
1391 * Returns a string containing a link to the user documentation.
1392 * Also contains an icon by default. Shown to teachers and admin only.
1393 * @param string $path The page link after doc root and language, no leading slash.
1394 * @param string $text The text to be displayed for the link
1397 public function doc_link($path, $text = '') {
1400 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1402 $url = new moodle_url(get_docs_url($path));
1404 $attributes = array('href'=>$url);
1405 if (!empty($CFG->doctonewwindow
)) {
1406 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1409 return html_writer
::tag('a', $icon.$text, $attributes);
1414 * @param string $pix short pix name
1415 * @param string $alt mandatory alt attribute
1416 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1417 * @param array $attributes htm lattributes
1418 * @return string HTML fragment
1420 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1421 $icon = new pix_icon($pix, $alt, $component, $attributes);
1422 return $this->render($icon);
1427 * @param pix_icon $icon
1428 * @return string HTML fragment
1430 protected function render_pix_icon(pix_icon
$icon) {
1431 $attributes = $icon->attributes
;
1432 $attributes['src'] = $this->pix_url($icon->pix
, $icon->component
);
1433 return html_writer
::empty_tag('img', $attributes);
1438 * @param pix_emoticon $emoticon
1439 * @return string HTML fragment
1441 protected function render_pix_emoticon(pix_emoticon
$emoticon) {
1442 $attributes = $emoticon->attributes
;
1443 $attributes['src'] = $this->pix_url($emoticon->pix
, $emoticon->component
);
1444 return html_writer
::empty_tag('img', $attributes);
1448 * Produces the html that represents this rating in the UI
1449 * @param $page the page object on which this rating will appear
1451 function render_rating(rating
$rating) {
1454 if ($rating->settings
->aggregationmethod
== RATING_AGGREGATE_NONE
) {
1455 return null;//ratings are turned off
1458 $ratingmanager = new rating_manager();
1459 // Initialise the JavaScript so ratings can be done by AJAX.
1460 $ratingmanager->initialise_rating_javascript($this->page
);
1462 $strrate = get_string("rate", "rating");
1463 $ratinghtml = ''; //the string we'll return
1465 // permissions check - can they view the aggregate?
1466 if ($rating->user_can_view_aggregate()) {
1468 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings
->aggregationmethod
);
1469 $aggregatestr = $rating->get_aggregate_string();
1471 $aggregatehtml = html_writer
::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid
, 'class' => 'ratingaggregate')).' ';
1472 if ($rating->count
> 0) {
1473 $countstr = "({$rating->count})";
1477 $aggregatehtml .= html_writer
::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1479 $ratinghtml .= html_writer
::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1480 if ($rating->settings
->permissions
->viewall
&& $rating->settings
->pluginpermissions
->viewall
) {
1482 $nonpopuplink = $rating->get_view_ratings_url();
1483 $popuplink = $rating->get_view_ratings_url(true);
1485 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1486 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1488 $ratinghtml .= $aggregatehtml;
1493 // if the item doesn't belong to the current user, the user has permission to rate
1494 // and we're within the assessable period
1495 if ($rating->user_can_rate()) {
1497 $rateurl = $rating->get_rate_url();
1498 $inputs = $rateurl->params();
1500 //start the rating form
1502 'id' => "postrating{$rating->itemid}",
1503 'class' => 'postratingform',
1505 'action' => $rateurl->out_omit_querystring()
1507 $formstart = html_writer
::start_tag('form', $formattrs);
1508 $formstart .= html_writer
::start_tag('div', array('class' => 'ratingform'));
1510 // add the hidden inputs
1511 foreach ($inputs as $name => $value) {
1512 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1513 $formstart .= html_writer
::empty_tag('input', $attributes);
1516 if (empty($ratinghtml)) {
1517 $ratinghtml .= $strrate.': ';
1519 $ratinghtml = $formstart.$ratinghtml;
1521 $scalearray = array(RATING_UNSET_RATING
=> $strrate.'...') +
$rating->settings
->scale
->scaleitems
;
1522 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid
);
1523 $ratinghtml .= html_writer
::label($rating->rating
, 'menurating'.$rating->itemid
, false, array('class' => 'accesshide'));
1524 $ratinghtml .= html_writer
::select($scalearray, 'rating', $rating->rating
, false, $scaleattrs);
1526 //output submit button
1527 $ratinghtml .= html_writer
::start_tag('span', array('class'=>"ratingsubmit"));
1529 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid
, 'value' => s(get_string('rate', 'rating')));
1530 $ratinghtml .= html_writer
::empty_tag('input', $attributes);
1532 if (!$rating->settings
->scale
->isnumeric
) {
1533 $ratinghtml .= $this->help_icon_scale($rating->settings
->scale
->courseid
, $rating->settings
->scale
);
1535 $ratinghtml .= html_writer
::end_tag('span');
1536 $ratinghtml .= html_writer
::end_tag('div');
1537 $ratinghtml .= html_writer
::end_tag('form');
1544 * Centered heading with attached help button (same title text)
1545 * and optional icon attached
1546 * @param string $text A heading text
1547 * @param string $helpidentifier The keyword that defines a help page
1548 * @param string $component component name
1549 * @param string|moodle_url $icon
1550 * @param string $iconalt icon alt text
1551 * @return string HTML fragment
1553 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
1556 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1560 if ($helpidentifier) {
1561 $help = $this->help_icon($helpidentifier, $component);
1564 return $this->heading($image.$text.$help, 2, 'main help');
1568 * Print a help icon.
1570 * @deprecated since Moodle 2.0
1571 * @param string $page The keyword that defines a help page
1572 * @param string $title A descriptive text for accessibility only
1573 * @param string $component component name
1574 * @param string|bool $linktext true means use $title as link text, string means link text value
1575 * @return string HTML fragment
1577 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1578 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER
);
1579 $icon = new old_help_icon($helpidentifier, $title, $component);
1580 if ($linktext === true) {
1581 $icon->linktext
= $title;
1582 } else if (!empty($linktext)) {
1583 $icon->linktext
= $linktext;
1585 return $this->render($icon);
1589 * Implementation of user image rendering.
1590 * @param help_icon $helpicon
1591 * @return string HTML fragment
1593 protected function render_old_help_icon(old_help_icon
$helpicon) {
1596 // first get the help image icon
1597 $src = $this->pix_url('help');
1599 if (empty($helpicon->linktext
)) {
1600 $alt = $helpicon->title
;
1602 $alt = get_string('helpwiththis');
1605 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1606 $output = html_writer
::empty_tag('img', $attributes);
1608 // add the link text if given
1609 if (!empty($helpicon->linktext
)) {
1610 // the spacing has to be done through CSS
1611 $output .= $helpicon->linktext
;
1614 // now create the link around it - we need https on loginhttps pages
1615 $url = new moodle_url($CFG->httpswwwroot
.'/help.php', array('component' => $helpicon->component
, 'identifier' => $helpicon->helpidentifier
, 'lang'=>current_language()));
1617 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1618 $title = get_string('helpprefix2', '', trim($helpicon->title
, ". \t"));
1620 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true');
1621 $id = html_writer
::random_id('helpicon');
1622 $attributes['id'] = $id;
1623 $output = html_writer
::tag('a', $output, $attributes);
1625 $this->page
->requires
->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1628 return html_writer
::tag('span', $output, array('class' => 'helplink'));
1632 * Print a help icon.
1634 * @param string $identifier The keyword that defines a help page
1635 * @param string $component component name
1636 * @param string|bool $linktext true means use $title as link text, string means link text value
1637 * @return string HTML fragment
1639 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1640 $icon = new help_icon($identifier, $component);
1641 $icon->diag_strings();
1642 if ($linktext === true) {
1643 $icon->linktext
= get_string($icon->identifier
, $icon->component
);
1644 } else if (!empty($linktext)) {
1645 $icon->linktext
= $linktext;
1647 return $this->render($icon);
1651 * Implementation of user image rendering.
1652 * @param help_icon $helpicon
1653 * @return string HTML fragment
1655 protected function render_help_icon(help_icon
$helpicon) {
1658 // first get the help image icon
1659 $src = $this->pix_url('help');
1661 $title = get_string($helpicon->identifier
, $helpicon->component
);
1663 if (empty($helpicon->linktext
)) {
1664 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1666 $alt = get_string('helpwiththis');
1669 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1670 $output = html_writer
::empty_tag('img', $attributes);
1672 // add the link text if given
1673 if (!empty($helpicon->linktext
)) {
1674 // the spacing has to be done through CSS
1675 $output .= $helpicon->linktext
;
1678 // now create the link around it - we need https on loginhttps pages
1679 $url = new moodle_url($CFG->httpswwwroot
.'/help.php', array('component' => $helpicon->component
, 'identifier' => $helpicon->identifier
, 'lang'=>current_language()));
1681 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1682 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1684 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true');
1685 $id = html_writer
::random_id('helpicon');
1686 $attributes['id'] = $id;
1687 $output = html_writer
::tag('a', $output, $attributes);
1689 $this->page
->requires
->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1692 return html_writer
::tag('span', $output, array('class' => 'helplink'));
1696 * Print scale help icon.
1698 * @param int $courseid
1699 * @param object $scale instance
1700 * @return string HTML fragment
1702 public function help_icon_scale($courseid, stdClass
$scale) {
1705 $title = get_string('helpprefix2', '', $scale->name
) .' ('.get_string('newwindow').')';
1707 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1709 $scaleid = abs($scale->id
);
1711 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1712 $action = new popup_action('click', $link, 'ratingscale');
1714 return html_writer
::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1718 * Creates and returns a spacer image with optional line break.
1720 * @param array $attributes
1722 * @return string HTML fragment
1724 public function spacer(array $attributes = null, $br = false) {
1725 $attributes = (array)$attributes;
1726 if (empty($attributes['width'])) {
1727 $attributes['width'] = 1;
1729 if (empty($attributes['height'])) {
1730 $attributes['height'] = 1;
1732 $attributes['class'] = 'spacer';
1734 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1737 $output .= '<br />';
1744 * Print the specified user's avatar.
1746 * User avatar may be obtained in two ways:
1748 * // Option 1: (shortcut for simple cases, preferred way)
1749 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1750 * $OUTPUT->user_picture($user, array('popup'=>true));
1753 * $userpic = new user_picture($user);
1754 * // Set properties of $userpic
1755 * $userpic->popup = true;
1756 * $OUTPUT->render($userpic);
1759 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
1760 * If any of these are missing, the database is queried. Avoid this
1761 * if at all possible, particularly for reports. It is very bad for performance.
1762 * @param array $options associative array with user picture options, used only if not a user_picture object,
1764 * - courseid=$this->page->course->id (course id of user profile in link)
1765 * - size=35 (size of image)
1766 * - link=true (make image clickable - the link leads to user profile)
1767 * - popup=false (open in popup)
1768 * - alttext=true (add image alt attribute)
1769 * - class = image class attribute (default 'userpicture')
1770 * @return string HTML fragment
1772 public function user_picture(stdClass
$user, array $options = null) {
1773 $userpicture = new user_picture($user);
1774 foreach ((array)$options as $key=>$value) {
1775 if (array_key_exists($key, $userpicture)) {
1776 $userpicture->$key = $value;
1779 return $this->render($userpicture);
1783 * Internal implementation of user image rendering.
1784 * @param user_picture $userpicture
1787 protected function render_user_picture(user_picture
$userpicture) {
1790 $user = $userpicture->user
;
1792 if ($userpicture->alttext
) {
1793 if (!empty($user->imagealt
)) {
1794 $alt = $user->imagealt
;
1796 $alt = get_string('pictureof', '', fullname($user));
1802 if (empty($userpicture->size
)) {
1804 } else if ($userpicture->size
=== true or $userpicture->size
== 1) {
1807 $size = $userpicture->size
;
1810 $class = $userpicture->class;
1812 if ($user->picture
!= 1 && $user->picture
!= 2) {
1813 $class .= ' defaultuserpic';
1816 $src = $userpicture->get_url($this->page
, $this);
1818 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1820 // get the image html output fisrt
1821 $output = html_writer
::empty_tag('img', $attributes);;
1823 // then wrap it in link if needed
1824 if (!$userpicture->link
) {
1828 if (empty($userpicture->courseid
)) {
1829 $courseid = $this->page
->course
->id
;
1831 $courseid = $userpicture->courseid
;
1834 if ($courseid == SITEID
) {
1835 $url = new moodle_url('/user/profile.php', array('id' => $user->id
));
1837 $url = new moodle_url('/user/view.php', array('id' => $user->id
, 'course' => $courseid));
1840 $attributes = array('href'=>$url);
1842 if ($userpicture->popup
) {
1843 $id = html_writer
::random_id('userpicture');
1844 $attributes['id'] = $id;
1845 $this->add_action_handler(new popup_action('click', $url), $id);
1848 return html_writer
::tag('a', $output, $attributes);
1852 * Internal implementation of file tree viewer items rendering.
1856 public function htmllize_file_tree($dir) {
1857 if (empty($dir['subdirs']) and empty($dir['files'])) {
1861 foreach ($dir['subdirs'] as $subdir) {
1862 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1864 foreach ($dir['files'] as $file) {
1865 $filename = $file->get_filename();
1866 $result .= '<li><span>'.html_writer
::link($file->fileurl
, $filename).'</span></li>';
1873 * Print the file picker
1876 * $OUTPUT->file_picker($options);
1879 * @param array $options associative array with file manager options
1883 * client_id=>uniqid(),
1884 * acepted_types=>'*',
1885 * return_types=>FILE_INTERNAL,
1886 * context=>$PAGE->context
1887 * @return string HTML fragment
1889 public function file_picker($options) {
1890 $fp = new file_picker($options);
1891 return $this->render($fp);
1894 * Internal implementation of file picker rendering.
1895 * @param file_picker $fp
1898 public function render_file_picker(file_picker
$fp) {
1899 global $CFG, $OUTPUT, $USER;
1900 $options = $fp->options
;
1901 $client_id = $options->client_id
;
1902 $strsaved = get_string('filesaved', 'repository');
1903 $straddfile = get_string('openpicker', 'repository');
1904 $strloading = get_string('loading', 'repository');
1905 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1907 $currentfile = $options->currentfile
;
1908 if (empty($currentfile)) {
1909 $currentfile = get_string('nofilesattached', 'repository');
1911 if ($options->maxbytes
) {
1912 $size = $options->maxbytes
;
1914 $size = get_max_upload_file_size();
1919 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
1921 if ($options->buttonname
) {
1922 $buttonname = ' name="' . $options->buttonname
. '"';
1927 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1930 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1932 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
1933 <span> $maxsize </span>
1936 if ($options->env
!= 'url') {
1938 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1946 * Prints the 'Update this Modulename' button that appears on module pages.
1948 * @param string $cmid the course_module id.
1949 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1950 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1952 public function update_module_button($cmid, $modulename) {
1954 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE
, $cmid))) {
1955 $modulename = get_string('modulename', $modulename);
1956 $string = get_string('updatethis', '', $modulename);
1957 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1958 return $this->single_button($url, $string);
1965 * Prints a "Turn editing on/off" button in a form.
1966 * @param moodle_url $url The URL + params to send through when clicking the button
1967 * @return string HTML the button
1969 public function edit_button(moodle_url
$url) {
1971 $url->param('sesskey', sesskey());
1972 if ($this->page
->user_is_editing()) {
1973 $url->param('edit', 'off');
1974 $editstring = get_string('turneditingoff');
1976 $url->param('edit', 'on');
1977 $editstring = get_string('turneditingon');
1980 return $this->single_button($url, $editstring);
1984 * Prints a simple button to close a window
1986 * @param string $text The lang string for the button's label (already output from get_string())
1987 * @return string html fragment
1989 public function close_window_button($text='') {
1991 $text = get_string('closewindow');
1993 $button = new single_button(new moodle_url('#'), $text, 'get');
1994 $button->add_action(new component_action('click', 'close_window'));
1996 return $this->container($this->render($button), 'closewindow');
2000 * Output an error message. By default wraps the error message in <span class="error">.
2001 * If the error message is blank, nothing is output.
2002 * @param string $message the error message.
2003 * @return string the HTML to output.
2005 public function error_text($message) {
2006 if (empty($message)) {
2009 return html_writer
::tag('span', $message, array('class' => 'error'));
2013 * Do not call this function directly.
2015 * To terminate the current script with a fatal error, call the {@link print_error}
2016 * function, or throw an exception. Doing either of those things will then call this
2017 * function to display the error, before terminating the execution.
2019 * @param string $message The message to output
2020 * @param string $moreinfourl URL where more info can be found about the error
2021 * @param string $link Link for the Continue button
2022 * @param array $backtrace The execution backtrace
2023 * @param string $debuginfo Debugging information
2024 * @return string the HTML to output.
2026 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2032 if ($this->has_started()) {
2033 // we can not always recover properly here, we have problems with output buffering,
2034 // html tables, etc.
2035 $output .= $this->opencontainers
->pop_all_but_last();
2038 // It is really bad if library code throws exception when output buffering is on,
2039 // because the buffered text would be printed before our start of page.
2040 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2041 error_reporting(0); // disable notices from gzip compression, etc.
2042 while (ob_get_level() > 0) {
2043 $buff = ob_get_clean();
2044 if ($buff === false) {
2049 error_reporting($CFG->debug
);
2051 // Header not yet printed
2052 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2053 // server protocol should be always present, because this render
2054 // can not be used from command line or when outputting custom XML
2055 @header
($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2057 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2058 $this->page
->set_url('/'); // no url
2059 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2060 $this->page
->set_title(get_string('error'));
2061 $this->page
->set_heading($this->page
->course
->fullname
);
2062 $output .= $this->header();
2065 $message = '<p class="errormessage">' . $message . '</p>'.
2066 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2067 get_string('moreinformation') . '</a></p>';
2068 if (empty($CFG->rolesactive
)) {
2069 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2070 //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation.
2072 $output .= $this->box($message, 'errorbox');
2074 if (debugging('', DEBUG_DEVELOPER
)) {
2075 if (!empty($debuginfo)) {
2076 $debuginfo = s($debuginfo); // removes all nasty JS
2077 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2078 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2080 if (!empty($backtrace)) {
2081 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2083 if ($obbuffer !== '' ) {
2084 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2088 if (empty($CFG->rolesactive
)) {
2089 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2090 } else if (!empty($link)) {
2091 $output .= $this->continue_button($link);
2094 $output .= $this->footer();
2096 // Padding to encourage IE to display our error page, rather than its own.
2097 $output .= str_repeat(' ', 512);
2103 * Output a notification (that is, a status message about something that has
2106 * @param string $message the message to print out
2107 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2108 * @return string the HTML to output.
2110 public function notification($message, $classes = 'notifyproblem') {
2111 return html_writer
::tag('div', clean_text($message), array('class' => renderer_base
::prepare_classes($classes)));
2115 * Print a continue button that goes to a particular URL.
2117 * @param string|moodle_url $url The url the button goes to.
2118 * @return string the HTML to output.
2120 public function continue_button($url) {
2121 if (!($url instanceof moodle_url
)) {
2122 $url = new moodle_url($url);
2124 $button = new single_button($url, get_string('continue'), 'get');
2125 $button->class = 'continuebutton';
2127 return $this->render($button);
2131 * Prints a single paging bar to provide access to other pages (usually in a search)
2133 * @param int $totalcount The total number of entries available to be paged through
2134 * @param int $page The page you are currently viewing
2135 * @param int $perpage The number of entries that should be shown per page
2136 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2137 * @param string $pagevar name of page parameter that holds the page number
2138 * @return string the HTML to output.
2140 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2141 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2142 return $this->render($pb);
2146 * Internal implementation of paging bar rendering.
2147 * @param paging_bar $pagingbar
2150 protected function render_paging_bar(paging_bar
$pagingbar) {
2152 $pagingbar = clone($pagingbar);
2153 $pagingbar->prepare($this, $this->page
, $this->target
);
2155 if ($pagingbar->totalcount
> $pagingbar->perpage
) {
2156 $output .= get_string('page') . ':';
2158 if (!empty($pagingbar->previouslink
)) {
2159 $output .= ' (' . $pagingbar->previouslink
. ') ';
2162 if (!empty($pagingbar->firstlink
)) {
2163 $output .= ' ' . $pagingbar->firstlink
. ' ...';
2166 foreach ($pagingbar->pagelinks
as $link) {
2167 $output .= "  $link";
2170 if (!empty($pagingbar->lastlink
)) {
2171 $output .= ' ...' . $pagingbar->lastlink
. ' ';
2174 if (!empty($pagingbar->nextlink
)) {
2175 $output .= '  (' . $pagingbar->nextlink
. ')';
2179 return html_writer
::tag('div', $output, array('class' => 'paging'));
2183 * Output the place a skip link goes to.
2184 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2185 * @return string the HTML to output.
2187 public function skip_link_target($id = null) {
2188 return html_writer
::tag('span', '', array('id' => $id));
2193 * @param string $text The text of the heading
2194 * @param int $level The level of importance of the heading. Defaulting to 2
2195 * @param string $classes A space-separated list of CSS classes
2196 * @param string $id An optional ID
2197 * @return string the HTML to output.
2199 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2200 $level = (integer) $level;
2201 if ($level < 1 or $level > 6) {
2202 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2204 return html_writer
::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base
::prepare_classes($classes)));
2209 * @param string $contents The contents of the box
2210 * @param string $classes A space-separated list of CSS classes
2211 * @param string $id An optional ID
2212 * @return string the HTML to output.
2214 public function box($contents, $classes = 'generalbox', $id = null) {
2215 return $this->box_start($classes, $id) . $contents . $this->box_end();
2219 * Outputs the opening section of a box.
2220 * @param string $classes A space-separated list of CSS classes
2221 * @param string $id An optional ID
2222 * @return string the HTML to output.
2224 public function box_start($classes = 'generalbox', $id = null) {
2225 $this->opencontainers
->push('box', html_writer
::end_tag('div'));
2226 return html_writer
::start_tag('div', array('id' => $id,
2227 'class' => 'box ' . renderer_base
::prepare_classes($classes)));
2231 * Outputs the closing section of a box.
2232 * @return string the HTML to output.
2234 public function box_end() {
2235 return $this->opencontainers
->pop('box');
2239 * Outputs a container.
2240 * @param string $contents The contents of the box
2241 * @param string $classes A space-separated list of CSS classes
2242 * @param string $id An optional ID
2243 * @return string the HTML to output.
2245 public function container($contents, $classes = null, $id = null) {
2246 return $this->container_start($classes, $id) . $contents . $this->container_end();
2250 * Outputs the opening section of a container.
2251 * @param string $classes A space-separated list of CSS classes
2252 * @param string $id An optional ID
2253 * @return string the HTML to output.
2255 public function container_start($classes = null, $id = null) {
2256 $this->opencontainers
->push('container', html_writer
::end_tag('div'));
2257 return html_writer
::start_tag('div', array('id' => $id,
2258 'class' => renderer_base
::prepare_classes($classes)));
2262 * Outputs the closing section of a container.
2263 * @return string the HTML to output.
2265 public function container_end() {
2266 return $this->opencontainers
->pop('container');
2270 * Make nested HTML lists out of the items
2272 * The resulting list will look something like this:
2276 * <<li>><div class='tree_item parent'>(item contents)</div>
2278 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2284 * @param array[]tree_item $items
2285 * @param array[string]string $attrs html attributes passed to the top of
2287 * @return string HTML
2289 function tree_block_contents($items, $attrs=array()) {
2290 // exit if empty, we don't want an empty ul element
2291 if (empty($items)) {
2294 // array of nested li elements
2296 foreach ($items as $item) {
2297 // this applies to the li item which contains all child lists too
2298 $content = $item->content($this);
2299 $liclasses = array($item->get_css_type());
2300 if (!$item->forceopen ||
(!$item->forceopen
&& $item->collapse
) ||
($item->children
->count()==0 && $item->nodetype
==navigation_node
::NODETYPE_BRANCH
)) {
2301 $liclasses[] = 'collapsed';
2303 if ($item->isactive
=== true) {
2304 $liclasses[] = 'current_branch';
2306 $liattr = array('class'=>join(' ',$liclasses));
2307 // class attribute on the div item which only contains the item content
2308 $divclasses = array('tree_item');
2309 if ($item->children
->count()>0 ||
$item->nodetype
==navigation_node
::NODETYPE_BRANCH
) {
2310 $divclasses[] = 'branch';
2312 $divclasses[] = 'leaf';
2314 if (!empty($item->classes
) && count($item->classes
)>0) {
2315 $divclasses[] = join(' ', $item->classes
);
2317 $divattr = array('class'=>join(' ', $divclasses));
2318 if (!empty($item->id
)) {
2319 $divattr['id'] = $item->id
;
2321 $content = html_writer
::tag('p', $content, $divattr) . $this->tree_block_contents($item->children
);
2322 if (!empty($item->preceedwithhr
) && $item->preceedwithhr
===true) {
2323 $content = html_writer
::empty_tag('hr') . $content;
2325 $content = html_writer
::tag('li', $content, $liattr);
2328 return html_writer
::tag('ul', implode("\n", $lis), $attrs);
2332 * Return the navbar content so that it can be echoed out by the layout
2333 * @return string XHTML navbar
2335 public function navbar() {
2336 $items = $this->page
->navbar
->get_items();
2338 $htmlblocks = array();
2339 // Iterate the navarray and display each node
2340 $itemcount = count($items);
2341 $separator = get_separator();
2342 for ($i=0;$i < $itemcount;$i++
) {
2344 $item->hideicon
= true;
2346 $content = html_writer
::tag('li', $this->render($item));
2348 $content = html_writer
::tag('li', $separator.$this->render($item));
2350 $htmlblocks[] = $content;
2353 //accessibility: heading for navbar list (MDL-20446)
2354 $navbarcontent = html_writer
::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2355 $navbarcontent .= html_writer
::tag('ul', join('', $htmlblocks));
2357 return $navbarcontent;
2360 protected function render_navigation_node(navigation_node
$item) {
2361 $content = $item->get_content();
2362 $title = $item->get_title();
2363 if ($item->icon
instanceof renderable
&& !$item->hideicon
) {
2364 $icon = $this->render($item->icon
);
2365 $content = $icon.$content; // use CSS for spacing of icons
2367 if ($item->helpbutton
!== null) {
2368 $content = trim($item->helpbutton
).html_writer
::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2370 if ($content === '') {
2373 if ($item->action
instanceof action_link
) {
2374 $link = $item->action
;
2375 if ($item->hidden
) {
2376 $link->add_class('dimmed');
2378 if (!empty($content)) {
2379 // Providing there is content we will use that for the link content.
2380 $link->text
= $content;
2382 $content = $this->render($link);
2383 } else if ($item->action
instanceof moodle_url
) {
2384 $attributes = array();
2385 if ($title !== '') {
2386 $attributes['title'] = $title;
2388 if ($item->hidden
) {
2389 $attributes['class'] = 'dimmed_text';
2391 $content = html_writer
::link($item->action
, $content, $attributes);
2393 } else if (is_string($item->action
) ||
empty($item->action
)) {
2394 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2395 if ($title !== '') {
2396 $attributes['title'] = $title;
2398 if ($item->hidden
) {
2399 $attributes['class'] = 'dimmed_text';
2401 $content = html_writer
::tag('span', $content, $attributes);
2407 * Accessibility: Right arrow-like character is
2408 * used in the breadcrumb trail, course navigation menu
2409 * (previous/next activity), calendar, and search forum block.
2410 * If the theme does not set characters, appropriate defaults
2411 * are set automatically. Please DO NOT
2412 * use < > » - these are confusing for blind users.
2415 public function rarrow() {
2416 return $this->page
->theme
->rarrow
;
2420 * Accessibility: Right arrow-like character is
2421 * used in the breadcrumb trail, course navigation menu
2422 * (previous/next activity), calendar, and search forum block.
2423 * If the theme does not set characters, appropriate defaults
2424 * are set automatically. Please DO NOT
2425 * use < > » - these are confusing for blind users.
2428 public function larrow() {
2429 return $this->page
->theme
->larrow
;
2433 * Returns the custom menu if one has been set
2435 * A custom menu can be configured by browsing to
2436 * Settings: Administration > Appearance > Themes > Theme settings
2437 * and then configuring the custommenu config setting as described.
2441 public function custom_menu() {
2443 if (empty($CFG->custommenuitems
)) {
2446 $custommenu = new custom_menu($CFG->custommenuitems
, current_language());
2447 return $this->render_custom_menu($custommenu);
2451 * Renders a custom menu object (located in outputcomponents.php)
2453 * The custom menu this method produces makes use of the YUI3 menunav widget
2454 * and requires very specific html elements and classes.
2456 * @staticvar int $menucount
2457 * @param custom_menu $menu
2460 protected function render_custom_menu(custom_menu
$menu) {
2461 static $menucount = 0;
2462 // If the menu has no children return an empty string
2463 if (!$menu->has_children()) {
2466 // Increment the menu count. This is used for ID's that get worked with
2467 // in JavaScript as is essential
2469 // Initialise this custom menu (the custom menu object is contained in javascript-static
2470 $jscode = js_writer
::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2471 $jscode = "(function(){{$jscode}})";
2472 $this->page
->requires
->yui_module('node-menunav', $jscode);
2473 // Build the root nodes as required by YUI
2474 $content = html_writer
::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2475 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
2476 $content .= html_writer
::start_tag('ul');
2477 // Render each child
2478 foreach ($menu->get_children() as $item) {
2479 $content .= $this->render_custom_menu_item($item);
2481 // Close the open tags
2482 $content .= html_writer
::end_tag('ul');
2483 $content .= html_writer
::end_tag('div');
2484 $content .= html_writer
::end_tag('div');
2485 // Return the custom menu
2490 * Renders a custom menu node as part of a submenu
2492 * The custom menu this method produces makes use of the YUI3 menunav widget
2493 * and requires very specific html elements and classes.
2495 * @see render_custom_menu()
2497 * @staticvar int $submenucount
2498 * @param custom_menu_item $menunode
2501 protected function render_custom_menu_item(custom_menu_item
$menunode) {
2502 // Required to ensure we get unique trackable id's
2503 static $submenucount = 0;
2504 if ($menunode->has_children()) {
2505 // If the child has menus render it as a sub menu
2507 $content = html_writer
::start_tag('li');
2508 if ($menunode->get_url() !== null) {
2509 $url = $menunode->get_url();
2511 $url = '#cm_submenu_'.$submenucount;
2513 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2514 $content .= html_writer
::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2515 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
2516 $content .= html_writer
::start_tag('ul');
2517 foreach ($menunode->get_children() as $menunode) {
2518 $content .= $this->render_custom_menu_item($menunode);
2520 $content .= html_writer
::end_tag('ul');
2521 $content .= html_writer
::end_tag('div');
2522 $content .= html_writer
::end_tag('div');
2523 $content .= html_writer
::end_tag('li');
2525 // The node doesn't have children so produce a final menuitem
2526 $content = html_writer
::start_tag('li', array('class'=>'yui3-menuitem'));
2527 if ($menunode->get_url() !== null) {
2528 $url = $menunode->get_url();
2532 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2533 $content .= html_writer
::end_tag('li');
2535 // Return the sub menu
2540 * Renders theme links for switching between default and other themes.
2544 protected function theme_switch_links() {
2546 $actualdevice = get_device_type();
2547 $currentdevice = $this->page
->devicetypeinuse
;
2548 $switched = ($actualdevice != $currentdevice);
2550 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2551 // The user is using the a default device and hasn't switched so don't shown the switch
2557 $linktext = get_string('switchdevicerecommended');
2558 $devicetype = $actualdevice;
2560 $linktext = get_string('switchdevicedefault');
2561 $devicetype = 'default';
2563 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page
->url
, 'device' => $devicetype, 'sesskey' => sesskey()));
2565 $content = html_writer
::start_tag('div', array('id' => 'theme_switch_link'));
2566 $content .= html_writer
::link($linkurl, $linktext);
2567 $content .= html_writer
::end_tag('div');
2576 * A renderer that generates output for command-line scripts.
2578 * The implementation of this renderer is probably incomplete.
2580 * @copyright 2009 Tim Hunt
2581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2584 class core_renderer_cli
extends core_renderer
{
2586 * Returns the page header.
2587 * @return string HTML fragment
2589 public function header() {
2590 return $this->page
->heading
. "\n";
2594 * Returns a template fragment representing a Heading.
2595 * @param string $text The text of the heading
2596 * @param int $level The level of importance of the heading
2597 * @param string $classes A space-separated list of CSS classes
2598 * @param string $id An optional ID
2599 * @return string A template fragment for a heading
2601 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2605 return '=>' . $text;
2607 return '-->' . $text;
2614 * Returns a template fragment representing a fatal error.
2615 * @param string $message The message to output
2616 * @param string $moreinfourl URL where more info can be found about the error
2617 * @param string $link Link for the Continue button
2618 * @param array $backtrace The execution backtrace
2619 * @param string $debuginfo Debugging information
2620 * @return string A template fragment for a fatal error
2622 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2623 $output = "!!! $message !!!\n";
2625 if (debugging('', DEBUG_DEVELOPER
)) {
2626 if (!empty($debuginfo)) {
2627 $output .= $this->notification($debuginfo, 'notifytiny');
2629 if (!empty($backtrace)) {
2630 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2638 * Returns a template fragment representing a notification.
2639 * @param string $message The message to include
2640 * @param string $classes A space-separated list of CSS classes
2641 * @return string A template fragment for a notification
2643 public function notification($message, $classes = 'notifyproblem') {
2644 $message = clean_text($message);
2645 if ($classes === 'notifysuccess') {
2646 return "++ $message ++\n";
2648 return "!! $message !!\n";
2654 * A renderer that generates output for ajax scripts.
2656 * This renderer prevents accidental sends back only json
2657 * encoded error messages, all other output is ignored.
2659 * @copyright 2010 Petr Skoda
2660 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2663 class core_renderer_ajax
extends core_renderer
{
2665 * Returns a template fragment representing a fatal error.
2666 * @param string $message The message to output
2667 * @param string $moreinfourl URL where more info can be found about the error
2668 * @param string $link Link for the Continue button
2669 * @param array $backtrace The execution backtrace
2670 * @param string $debuginfo Debugging information
2671 * @return string A template fragment for a fatal error
2673 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2676 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2678 $e = new stdClass();
2679 $e->error
= $message;
2680 $e->stacktrace
= NULL;
2681 $e->debuginfo
= NULL;
2682 $e->reproductionlink
= NULL;
2683 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
2684 $e->reproductionlink
= $link;
2685 if (!empty($debuginfo)) {
2686 $e->debuginfo
= $debuginfo;
2688 if (!empty($backtrace)) {
2689 $e->stacktrace
= format_backtrace($backtrace, true);
2693 return json_encode($e);
2696 public function notification($message, $classes = 'notifyproblem') {
2699 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2702 public function header() {
2703 // unfortunately YUI iframe upload does not support application/json
2704 if (!empty($_FILES)) {
2705 @header
('Content-type: text/plain; charset=utf-8');
2707 @header
('Content-type: application/json; charset=utf-8');
2710 /// Headers to make it not cacheable and json
2711 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2712 @header
('Cache-Control: post-check=0, pre-check=0', false);
2713 @header
('Pragma: no-cache');
2714 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2715 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2716 @header
('Accept-Ranges: none');
2719 public function footer() {
2722 public function heading($text, $level = 2, $classes = 'main', $id = null) {