Continuing work on boxxie theme
[moodle.git] / lib / outputrenderers.php
CommitLineData
d9c8f425 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
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.
9//
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.
14//
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/>.
17
18/**
19 * Classes for rendering HTML output for Moodle.
20 *
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
23 *
24 * @package moodlecore
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29/**
30 * Simple base class for Moodle renderers.
31 *
32 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
33 *
34 * Also has methods to facilitate generating HTML output.
35 *
36 * @copyright 2009 Tim Hunt
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.0
39 */
78946b9b 40class renderer_base {
d9c8f425 41 /** @var xhtml_container_stack the xhtml_container_stack to use. */
42 protected $opencontainers;
43 /** @var moodle_page the page we are rendering for. */
44 protected $page;
c927e35c
PS
45 /** @var requested rendering target conatnt */
46 protected $target;
d9c8f425 47
48 /**
49 * Constructor
50 * @param moodle_page $page the page we are doing output for.
c927e35c 51 * @param string $target one of rendering target constants
d9c8f425 52 */
c927e35c 53 public function __construct(moodle_page $page, $target) {
d9c8f425 54 $this->opencontainers = $page->opencontainers;
55 $this->page = $page;
c927e35c 56 $this->target = $target;
d9c8f425 57 }
58
59 /**
5d0c95a5
PS
60 * Returns rendered widget.
61 * @param renderable $widget intence with renderable interface
62 * @return string
d9c8f425 63 */
5d0c95a5
PS
64 public function render(renderable $widget) {
65 $rendermethod = 'render_'.get_class($widget);
66 if (method_exists($this, $rendermethod)) {
67 return $this->$rendermethod($widget);
68 }
69 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
d9c8f425 70 }
71
72 /**
5d0c95a5 73 * Adds JS handlers needed for event execution for one html element id
5d0c95a5 74 * @param component_action $actions
c80877aa
PS
75 * @param string $id
76 * @return string id of element, either original submitted or random new if not supplied
d9c8f425 77 */
c80877aa
PS
78 public function add_action_handler(component_action $action, $id=null) {
79 if (!$id) {
80 $id = html_writer::random_id($action->event);
81 }
d96d8f03 82 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
c80877aa 83 return $id;
d9c8f425 84 }
85
86 /**
5d0c95a5
PS
87 * Have we started output yet?
88 * @return boolean true if the header has been printed.
d9c8f425 89 */
5d0c95a5
PS
90 public function has_started() {
91 return $this->page->state >= moodle_page::STATE_IN_BODY;
d9c8f425 92 }
93
94 /**
95 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
96 * @param mixed $classes Space-separated string or array of classes
97 * @return string HTML class attribute value
98 */
99 public static function prepare_classes($classes) {
100 if (is_array($classes)) {
101 return implode(' ', array_unique($classes));
102 }
103 return $classes;
104 }
105
d9c8f425 106 /**
897e902b
PS
107 * Return the moodle_url for an image.
108 * The exact image location and extension is determined
109 * automatically by searching for gif|png|jpg|jpeg, please
110 * note there can not be diferent images with the different
111 * extension. The imagename is for historical reasons
112 * a relative path name, it may be changed later for core
113 * images. It is recommended to not use subdirectories
114 * in plugin and theme pix directories.
d9c8f425 115 *
897e902b
PS
116 * There are three types of images:
117 * 1/ theme images - stored in theme/mytheme/pix/,
118 * use component 'theme'
119 * 2/ core images - stored in /pix/,
120 * overridden via theme/mytheme/pix_core/
121 * 3/ plugin images - stored in mod/mymodule/pix,
122 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
123 * example: pix_url('comment', 'mod_glossary')
124 *
125 * @param string $imagename the pathname of the image
126 * @param string $component full plugin name (aka component) or 'theme'
78946b9b 127 * @return moodle_url
d9c8f425 128 */
c927e35c 129 public function pix_url($imagename, $component = 'moodle') {
c39e5ba2 130 return $this->page->theme->pix_url($imagename, $component);
d9c8f425 131 }
d9c8f425 132}
133
c927e35c 134
75590935
PS
135/**
136 * Basis for all plugin renderers.
137 *
c927e35c
PS
138 * @author Petr Skoda (skodak)
139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
140 * @since Moodle 2.0
75590935
PS
141 */
142class plugin_renderer_base extends renderer_base {
143 /**
144 * A reference to the current general renderer probably {@see core_renderer}
145 * @var renderer_base
146 */
147 protected $output;
148
149 /**
150 * Contructor method, calls the parent constructor
151 * @param moodle_page $page
c927e35c 152 * @param string $target one of rendering target constants
75590935 153 */
c927e35c
PS
154 public function __construct(moodle_page $page, $target) {
155 $this->output = $page->get_renderer('core', null, $target);
156 parent::__construct($page, $target);
75590935 157 }
ff5265c6 158
5d0c95a5
PS
159 /**
160 * Returns rendered widget.
161 * @param renderable $widget intence with renderable interface
162 * @return string
163 */
164 public function render(renderable $widget) {
165 $rendermethod = 'render_'.get_class($widget);
166 if (method_exists($this, $rendermethod)) {
167 return $this->$rendermethod($widget);
168 }
169 // pass to core renderer if method not found here
170 $this->output->render($widget);
171 }
172
ff5265c6
PS
173 /**
174 * Magic method used to pass calls otherwise meant for the standard renderer
175 * to it to ensure we don't go causing unnessecary greif.
176 *
177 * @param string $method
178 * @param array $arguments
179 * @return mixed
180 */
181 public function __call($method, $arguments) {
37b5b18e
PS
182 if (method_exists('renderer_base', $method)) {
183 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
184 }
ff5265c6
PS
185 if (method_exists($this->output, $method)) {
186 return call_user_func_array(array($this->output, $method), $arguments);
187 } else {
188 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
189 }
190 }
75590935 191}
d9c8f425 192
c927e35c 193
d9c8f425 194/**
78946b9b 195 * The standard implementation of the core_renderer interface.
d9c8f425 196 *
197 * @copyright 2009 Tim Hunt
198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
199 * @since Moodle 2.0
200 */
78946b9b 201class core_renderer extends renderer_base {
d9c8f425 202 /** @var string used in {@link header()}. */
203 const PERFORMANCE_INFO_TOKEN = '%%PERFORMANCEINFO%%';
204 /** @var string used in {@link header()}. */
205 const END_HTML_TOKEN = '%%ENDHTML%%';
206 /** @var string used in {@link header()}. */
207 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
208 /** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
209 protected $contenttype;
210 /** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
211 protected $metarefreshtag = '';
212
213 /**
214 * Get the DOCTYPE declaration that should be used with this page. Designed to
215 * be called in theme layout.php files.
216 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
217 */
218 public function doctype() {
219 global $CFG;
220
221 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
222 $this->contenttype = 'text/html; charset=utf-8';
223
224 if (empty($CFG->xmlstrictheaders)) {
225 return $doctype;
226 }
227
228 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
229 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
230 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
231 // Firefox and other browsers that can cope natively with XHTML.
232 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
233
234 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
235 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
236 $this->contenttype = 'application/xml; charset=utf-8';
237 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
238
239 } else {
240 $prolog = '';
241 }
242
243 return $prolog . $doctype;
244 }
245
246 /**
247 * The attributes that should be added to the <html> tag. Designed to
248 * be called in theme layout.php files.
249 * @return string HTML fragment.
250 */
251 public function htmlattributes() {
252 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
253 }
254
255 /**
256 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
257 * that should be included in the <head> tag. Designed to be called in theme
258 * layout.php files.
259 * @return string HTML fragment.
260 */
261 public function standard_head_html() {
b5bbeaf0 262 global $CFG, $SESSION;
d9c8f425 263 $output = '';
264 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
265 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
266 if (!$this->page->cacheable) {
267 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
268 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
269 }
270 // This is only set by the {@link redirect()} method
271 $output .= $this->metarefreshtag;
272
273 // Check if a periodic refresh delay has been set and make sure we arn't
274 // already meta refreshing
275 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
276 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
277 }
278
7d2a0492 279 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
d9c8f425 280
281 $focus = $this->page->focuscontrol;
282 if (!empty($focus)) {
283 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
284 // This is a horrifically bad way to handle focus but it is passed in
285 // through messy formslib::moodleform
7d2a0492 286 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
d9c8f425 287 } else if (strpos($focus, '.')!==false) {
288 // Old style of focus, bad way to do it
289 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
290 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
291 } else {
292 // Focus element with given id
7d2a0492 293 $this->page->requires->js_function_call('focuscontrol', array($focus));
d9c8f425 294 }
295 }
296
78946b9b
PS
297 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
298 // any other custom CSS can not be overridden via themes and is highly discouraged
efaa4c08 299 $urls = $this->page->theme->css_urls($this->page);
78946b9b 300 foreach ($urls as $url) {
c0467479 301 $this->page->requires->css_theme($url);
78946b9b
PS
302 }
303
04c01408 304 // Get the theme javascript head and footer
04c01408 305 $jsurl = $this->page->theme->javascript_url(true);
baeb20bb
PS
306 $this->page->requires->js($jsurl, true);
307 $jsurl = $this->page->theme->javascript_url(false);
8ce04d51 308 $this->page->requires->js($jsurl);
5d0c95a5 309
78946b9b 310 // Perform a browser environment check for the flash version. Should only run once per login session.
2c0d7839 311 if (!NO_MOODLE_COOKIES && isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
4abd5b9b
PS
312 $this->page->requires->js('/lib/swfobject/swfobject.js');
313 $this->page->requires->js_init_call('M.core_flashdetect.init');
b5bbeaf0 314 }
315
d9c8f425 316 // Get any HTML from the page_requirements_manager.
945f19f7 317 $output .= $this->page->requires->get_head_code($this->page, $this);
d9c8f425 318
319 // List alternate versions.
320 foreach ($this->page->alternateversions as $type => $alt) {
5d0c95a5 321 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
d9c8f425 322 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
323 }
324
325 return $output;
326 }
327
328 /**
329 * The standard tags (typically skip links) that should be output just inside
330 * the start of the <body> tag. Designed to be called in theme layout.php files.
331 * @return string HTML fragment.
332 */
333 public function standard_top_of_body_html() {
334 return $this->page->requires->get_top_of_body_code();
335 }
336
337 /**
338 * The standard tags (typically performance information and validation links,
339 * if we are in developer debug mode) that should be output in the footer area
340 * of the page. Designed to be called in theme layout.php files.
341 * @return string HTML fragment.
342 */
343 public function standard_footer_html() {
344 global $CFG;
345
346 // This function is normally called from a layout.php file in {@link header()}
347 // but some of the content won't be known until later, so we return a placeholder
348 // for now. This will be replaced with the real content in {@link footer()}.
349 $output = self::PERFORMANCE_INFO_TOKEN;
350 if (!empty($CFG->debugpageinfo)) {
351 $output .= '<div class="performanceinfo">This page is: ' . $this->page->debug_summary() . '</div>';
352 }
353 if (!empty($CFG->debugvalidators)) {
354 $output .= '<div class="validators"><ul>
355 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
356 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
357 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
358 </ul></div>';
359 }
360 return $output;
361 }
362
363 /**
364 * The standard tags (typically script tags that are not needed earlier) that
365 * should be output after everything else, . Designed to be called in theme layout.php files.
366 * @return string HTML fragment.
367 */
368 public function standard_end_of_body_html() {
369 // This function is normally called from a layout.php file in {@link header()}
370 // but some of the content won't be known until later, so we return a placeholder
371 // for now. This will be replaced with the real content in {@link footer()}.
372 echo self::END_HTML_TOKEN;
373 }
374
375 /**
376 * Return the standard string that says whether you are logged in (and switched
377 * roles/logged in as another user).
378 * @return string HTML fragment.
379 */
380 public function login_info() {
244a32c6 381 global $USER, $CFG, $DB;
4bcc5118 382
244a32c6
PS
383 if (during_initial_install()) {
384 return '';
385 }
4bcc5118 386
244a32c6 387 $course = $this->page->course;
4bcc5118 388
244a32c6
PS
389 if (session_is_loggedinas()) {
390 $realuser = session_get_realuser();
391 $fullname = fullname($realuser, true);
4aea3cc7 392 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
244a32c6
PS
393 } else {
394 $realuserinfo = '';
395 }
4bcc5118 396
244a32c6 397 $loginurl = get_login_url();
4bcc5118 398
244a32c6
PS
399 if (empty($course->id)) {
400 // $course->id is not defined during installation
401 return '';
4f0c2d00 402 } else if (isloggedin()) {
244a32c6 403 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4bcc5118 404
244a32c6 405 $fullname = fullname($USER, true);
4aea3cc7 406 $username = "<a href=\"$CFG->wwwroot/user/view.php?id=$USER->id&amp;course=$course->id\">$fullname</a>";
244a32c6 407 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
4aea3cc7 408 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
244a32c6
PS
409 }
410 if (isset($USER->username) && $USER->username == 'guest') {
411 $loggedinas = $realuserinfo.get_string('loggedinasguest').
4aea3cc7 412 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
244a32c6
PS
413 } else if (!empty($USER->access['rsw'][$context->path])) {
414 $rolename = '';
415 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
416 $rolename = ': '.format_string($role->name);
417 }
418 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
4aea3cc7 419 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
244a32c6
PS
420 } else {
421 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
4aea3cc7 422 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
244a32c6
PS
423 }
424 } else {
425 $loggedinas = get_string('loggedinnot', 'moodle').
4aea3cc7 426 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
244a32c6 427 }
4bcc5118 428
244a32c6 429 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
4bcc5118 430
244a32c6
PS
431 if (isset($SESSION->justloggedin)) {
432 unset($SESSION->justloggedin);
433 if (!empty($CFG->displayloginfailures)) {
434 if (!empty($USER->username) and $USER->username != 'guest') {
435 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
436 $loggedinas .= '&nbsp;<div class="loginfailures">';
437 if (empty($count->accounts)) {
438 $loggedinas .= get_string('failedloginattempts', '', $count);
439 } else {
440 $loggedinas .= get_string('failedloginattemptsall', '', $count);
441 }
442 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
443 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
444 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
445 }
446 $loggedinas .= '</div>';
447 }
448 }
449 }
450 }
4bcc5118 451
244a32c6 452 return $loggedinas;
d9c8f425 453 }
454
455 /**
456 * Return the 'back' link that normally appears in the footer.
457 * @return string HTML fragment.
458 */
459 public function home_link() {
460 global $CFG, $SITE;
461
462 if ($this->page->pagetype == 'site-index') {
463 // Special case for site home page - please do not remove
464 return '<div class="sitelink">' .
34dff6aa 465 '<a title="Moodle" href="http://moodle.org/">' .
53228896 466 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
d9c8f425 467
468 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
469 // Special case for during install/upgrade.
470 return '<div class="sitelink">'.
34dff6aa 471 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
53228896 472 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
d9c8f425 473
474 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
475 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
476 get_string('home') . '</a></div>';
477
478 } else {
479 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
480 format_string($this->page->course->shortname) . '</a></div>';
481 }
482 }
483
484 /**
485 * Redirects the user by any means possible given the current state
486 *
487 * This function should not be called directly, it should always be called using
488 * the redirect function in lib/weblib.php
489 *
490 * The redirect function should really only be called before page output has started
491 * however it will allow itself to be called during the state STATE_IN_BODY
492 *
493 * @param string $encodedurl The URL to send to encoded if required
494 * @param string $message The message to display to the user if any
495 * @param int $delay The delay before redirecting a user, if $message has been
496 * set this is a requirement and defaults to 3, set to 0 no delay
497 * @param boolean $debugdisableredirect this redirect has been disabled for
498 * debugging purposes. Display a message that explains, and don't
499 * trigger the redirect.
500 * @return string The HTML to display to the user before dying, may contain
501 * meta refresh, javascript refresh, and may have set header redirects
502 */
503 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
504 global $CFG;
505 $url = str_replace('&amp;', '&', $encodedurl);
506
507 switch ($this->page->state) {
508 case moodle_page::STATE_BEFORE_HEADER :
509 // No output yet it is safe to delivery the full arsenal of redirect methods
510 if (!$debugdisableredirect) {
511 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
512 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
593f9b87 513 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
d9c8f425 514 }
515 $output = $this->header();
516 break;
517 case moodle_page::STATE_PRINTING_HEADER :
518 // We should hopefully never get here
519 throw new coding_exception('You cannot redirect while printing the page header');
520 break;
521 case moodle_page::STATE_IN_BODY :
522 // We really shouldn't be here but we can deal with this
523 debugging("You should really redirect before you start page output");
524 if (!$debugdisableredirect) {
593f9b87 525 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
d9c8f425 526 }
527 $output = $this->opencontainers->pop_all_but_last();
528 break;
529 case moodle_page::STATE_DONE :
530 // Too late to be calling redirect now
531 throw new coding_exception('You cannot redirect after the entire page has been generated');
532 break;
533 }
534 $output .= $this->notification($message, 'redirectmessage');
535 $output .= '<a href="'. $encodedurl .'">'. get_string('continue') .'</a>';
536 if ($debugdisableredirect) {
537 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
538 }
539 $output .= $this->footer();
540 return $output;
541 }
542
543 /**
544 * Start output by sending the HTTP headers, and printing the HTML <head>
545 * and the start of the <body>.
546 *
547 * To control what is printed, you should set properties on $PAGE. If you
548 * are familiar with the old {@link print_header()} function from Moodle 1.9
549 * you will find that there are properties on $PAGE that correspond to most
550 * of the old parameters to could be passed to print_header.
551 *
552 * Not that, in due course, the remaining $navigation, $menu parameters here
553 * will be replaced by more properties of $PAGE, but that is still to do.
554 *
d9c8f425 555 * @return string HTML that you must output this, preferably immediately.
556 */
e120c61d 557 public function header() {
d9c8f425 558 global $USER, $CFG;
559
560 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
561
78946b9b
PS
562 // Find the appropriate page layout file, based on $this->page->pagelayout.
563 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
564 // Render the layout using the layout file.
565 $rendered = $this->render_page_layout($layoutfile);
67e84a7f 566
78946b9b
PS
567 // Slice the rendered output into header and footer.
568 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
d9c8f425 569 if ($cutpos === false) {
78946b9b 570 throw new coding_exception('page layout file ' . $layoutfile .
d9c8f425 571 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
572 }
78946b9b
PS
573 $header = substr($rendered, 0, $cutpos);
574 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
d9c8f425 575
576 if (empty($this->contenttype)) {
78946b9b 577 debugging('The page layout file did not call $OUTPUT->doctype()');
67e84a7f 578 $header = $this->doctype() . $header;
d9c8f425 579 }
580
581 send_headers($this->contenttype, $this->page->cacheable);
67e84a7f 582
d9c8f425 583 $this->opencontainers->push('header/footer', $footer);
584 $this->page->set_state(moodle_page::STATE_IN_BODY);
67e84a7f 585
d9c8f425 586 return $header . $this->skip_link_target();
587 }
588
589 /**
78946b9b
PS
590 * Renders and outputs the page layout file.
591 * @param string $layoutfile The name of the layout file
d9c8f425 592 * @return string HTML code
593 */
78946b9b 594 protected function render_page_layout($layoutfile) {
92e01ab7 595 global $CFG, $SITE, $USER;
d9c8f425 596 // The next lines are a bit tricky. The point is, here we are in a method
597 // of a renderer class, and this object may, or may not, be the same as
78946b9b 598 // the global $OUTPUT object. When rendering the page layout file, we want to use
d9c8f425 599 // this object. However, people writing Moodle code expect the current
600 // renderer to be called $OUTPUT, not $this, so define a variable called
601 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
602 $OUTPUT = $this;
603 $PAGE = $this->page;
604 $COURSE = $this->page->course;
605
d9c8f425 606 ob_start();
78946b9b
PS
607 include($layoutfile);
608 $rendered = ob_get_contents();
d9c8f425 609 ob_end_clean();
78946b9b 610 return $rendered;
d9c8f425 611 }
612
613 /**
614 * Outputs the page's footer
615 * @return string HTML fragment
616 */
617 public function footer() {
d5a8d9aa 618 global $CFG, $DB;
0f0801f4 619
f6794ace 620 $output = $this->container_end_all(true);
d9c8f425 621
622 $footer = $this->opencontainers->pop('header/footer');
623
d5a8d9aa 624 if (debugging() and $DB and $DB->is_transaction_started()) {
03221650 625 // TODO: MDL-20625 print warning - transaction will be rolled back
d5a8d9aa
PS
626 }
627
d9c8f425 628 // Provide some performance info if required
629 $performanceinfo = '';
630 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
631 $perf = get_performance_info();
632 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
633 error_log("PERF: " . $perf['txt']);
634 }
635 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
636 $performanceinfo = $perf['html'];
637 }
638 }
639 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
640
641 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
642
643 $this->page->set_state(moodle_page::STATE_DONE);
644
645
646 return $output . $footer;
647 }
648
f6794ace
PS
649 /**
650 * Close all but the last open container. This is useful in places like error
651 * handling, where you want to close all the open containers (apart from <body>)
652 * before outputting the error message.
653 * @param bool $shouldbenone assert that the stack should be empty now - causes a
654 * developer debug warning if it isn't.
655 * @return string the HTML required to close any open containers inside <body>.
656 */
657 public function container_end_all($shouldbenone = false) {
658 return $this->opencontainers->pop_all_but_last($shouldbenone);
659 }
660
244a32c6
PS
661 /**
662 * Returns lang menu or '', this method also checks forcing of languages in courses.
663 * @return string
664 */
665 public function lang_menu() {
666 global $CFG;
667
668 if (empty($CFG->langmenu)) {
669 return '';
670 }
671
672 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
673 // do not show lang menu if language forced
674 return '';
675 }
676
677 $currlang = current_language();
1f96e907 678 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 679
244a32c6
PS
680 if (count($langs) < 2) {
681 return '';
682 }
683
a9967cf5
PS
684 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
685 $s->label = get_accesshide(get_string('language'));
686 $s->class = 'langmenu';
687 return $this->render($s);
244a32c6
PS
688 }
689
d9c8f425 690 /**
691 * Output the row of editing icons for a block, as defined by the controls array.
692 * @param array $controls an array like {@link block_contents::$controls}.
693 * @return HTML fragment.
694 */
695 public function block_controls($controls) {
696 if (empty($controls)) {
697 return '';
698 }
699 $controlshtml = array();
700 foreach ($controls as $control) {
f4ed6fc4 701 $controlshtml[] = html_writer::tag('a',
26acc814 702 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
f4ed6fc4 703 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
d9c8f425 704 }
26acc814 705 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
d9c8f425 706 }
707
708 /**
709 * Prints a nice side block with an optional header.
710 *
711 * The content is described
712 * by a {@link block_contents} object.
713 *
714 * @param block_contents $bc HTML for the content
715 * @param string $region the region the block is appearing in.
716 * @return string the HTML to be output.
717 */
dd72b308 718 function block(block_contents $bc, $region) {
d9c8f425 719 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
720 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
721 $bc->collapsible = block_contents::NOT_HIDEABLE;
722 }
723 if ($bc->collapsible == block_contents::HIDDEN) {
724 $bc->add_class('hidden');
725 }
726 if (!empty($bc->controls)) {
727 $bc->add_class('block_with_controls');
728 }
d9c8f425 729
730 $skiptitle = strip_tags($bc->title);
731 if (empty($skiptitle)) {
732 $output = '';
733 $skipdest = '';
734 } else {
26acc814
PS
735 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
736 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
d9c8f425 737 }
738
5d0c95a5 739 $output .= html_writer::start_tag('div', $bc->attributes);
d9c8f425 740
741 $controlshtml = $this->block_controls($bc->controls);
742
743 $title = '';
744 if ($bc->title) {
26acc814 745 $title = html_writer::tag('h2', $bc->title, null);
d9c8f425 746 }
747
748 if ($title || $controlshtml) {
46de77b6 749 $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'));
d9c8f425 750 }
751
5d0c95a5 752 $output .= html_writer::start_tag('div', array('class' => 'content'));
46de77b6
SH
753 if (!$title && !$controlshtml) {
754 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
755 }
d9c8f425 756 $output .= $bc->content;
757
758 if ($bc->footer) {
26acc814 759 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
d9c8f425 760 }
761
5d0c95a5
PS
762 $output .= html_writer::end_tag('div');
763 $output .= html_writer::end_tag('div');
d9c8f425 764
765 if ($bc->annotation) {
26acc814 766 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
d9c8f425 767 }
768 $output .= $skipdest;
769
770 $this->init_block_hider_js($bc);
771 return $output;
772 }
773
774 /**
775 * Calls the JS require function to hide a block.
776 * @param block_contents $bc A block_contents object
777 * @return void
778 */
dd72b308
PS
779 protected function init_block_hider_js(block_contents $bc) {
780 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
d9c8f425 781 $userpref = 'block' . $bc->blockinstanceid . 'hidden';
782 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
f44b10ed
PS
783 $this->page->requires->yui2_lib('dom');
784 $this->page->requires->yui2_lib('event');
d9c8f425 785 $plaintitle = strip_tags($bc->title);
dd72b308 786 $this->page->requires->js_function_call('new block_hider', array($bc->attributes['id'], $userpref,
d9c8f425 787 get_string('hideblocka', 'access', $plaintitle), get_string('showblocka', 'access', $plaintitle),
b9bc2019 788 $this->pix_url('t/switch_minus')->out(false), $this->pix_url('t/switch_plus')->out(false)));
d9c8f425 789 }
790 }
791
792 /**
793 * Render the contents of a block_list.
794 * @param array $icons the icon for each item.
795 * @param array $items the content of each item.
796 * @return string HTML
797 */
798 public function list_block_contents($icons, $items) {
799 $row = 0;
800 $lis = array();
801 foreach ($items as $key => $string) {
5d0c95a5 802 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 803 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 804 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 805 }
26acc814 806 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 807 $item .= html_writer::end_tag('li');
d9c8f425 808 $lis[] = $item;
809 $row = 1 - $row; // Flip even/odd.
810 }
26acc814 811 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'list'));
d9c8f425 812 }
813
814 /**
815 * Output all the blocks in a particular region.
816 * @param string $region the name of a region on this page.
817 * @return string the HTML to be output.
818 */
819 public function blocks_for_region($region) {
820 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
821
822 $output = '';
823 foreach ($blockcontents as $bc) {
824 if ($bc instanceof block_contents) {
825 $output .= $this->block($bc, $region);
826 } else if ($bc instanceof block_move_target) {
827 $output .= $this->block_move_target($bc);
828 } else {
829 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
830 }
831 }
832 return $output;
833 }
834
835 /**
836 * Output a place where the block that is currently being moved can be dropped.
837 * @param block_move_target $target with the necessary details.
838 * @return string the HTML to be output.
839 */
840 public function block_move_target($target) {
6ee744b3 841 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 842 }
843
574fbea4
PS
844 /**
845 * Renders a sepcial html link with attached action
846 *
847 * @param string|moodle_url $url
848 * @param string $text HTML fragment
849 * @param component_action $action
11820bac 850 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
851 * @return HTML fragment
852 */
c63923bd 853 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
574fbea4
PS
854 if (!($url instanceof moodle_url)) {
855 $url = new moodle_url($url);
856 }
857 $link = new action_link($url, $text, $action, $attributes);
858
f14b641b 859 return $this->render($link);
574fbea4
PS
860 }
861
862 /**
863 * Implementation of action_link rendering
864 * @param action_link $link
865 * @return string HTML fragment
866 */
867 protected function render_action_link(action_link $link) {
868 global $CFG;
869
870 // A disabled link is rendered as formatted text
871 if (!empty($link->attributes['disabled'])) {
872 // do not use div here due to nesting restriction in xhtml strict
873 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
874 }
11820bac 875
574fbea4
PS
876 $attributes = $link->attributes;
877 unset($link->attributes['disabled']);
878 $attributes['href'] = $link->url;
879
880 if ($link->actions) {
f14b641b 881 if (empty($attributes['id'])) {
574fbea4
PS
882 $id = html_writer::random_id('action_link');
883 $attributes['id'] = $id;
884 } else {
885 $id = $attributes['id'];
886 }
887 foreach ($link->actions as $action) {
c80877aa 888 $this->add_action_handler($action, $id);
574fbea4
PS
889 }
890 }
891
26acc814 892 return html_writer::tag('a', $link->text, $attributes);
574fbea4
PS
893 }
894
c63923bd
PS
895
896 /**
897 * Similar to action_link, image is used instead of the text
898 *
899 * @param string|moodle_url $url A string URL or moodel_url
900 * @param pix_icon $pixicon
901 * @param component_action $action
902 * @param array $attributes associative array of html link attributes + disabled
903 * @param bool $linktext show title next to image in link
904 * @return string HTML fragment
905 */
906 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
907 if (!($url instanceof moodle_url)) {
908 $url = new moodle_url($url);
909 }
910 $attributes = (array)$attributes;
911
524645e7 912 if (empty($attributes['class'])) {
c63923bd
PS
913 // let ppl override the class via $options
914 $attributes['class'] = 'action-icon';
915 }
916
917 $icon = $this->render($pixicon);
918
919 if ($linktext) {
920 $text = $pixicon->attributes['alt'];
921 } else {
922 $text = '';
923 }
924
925 return $this->action_link($url, $text.$icon, $action, $attributes);
926 }
927
d9c8f425 928 /**
0b634d75 929 * Print a message along with button choices for Continue/Cancel
930 *
4ed85790 931 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 932 *
d9c8f425 933 * @param string $message The question to ask the user
3ba60ee1
PS
934 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
935 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
d9c8f425 936 * @return string HTML fragment
937 */
938 public function confirm($message, $continue, $cancel) {
4871a238 939 if ($continue instanceof single_button) {
11820bac 940 // ok
4871a238
PS
941 } else if (is_string($continue)) {
942 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
943 } else if ($continue instanceof moodle_url) {
26eab8d4 944 $continue = new single_button($continue, get_string('continue'), 'post');
d9c8f425 945 } else {
4ed85790 946 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 947 }
948
4871a238 949 if ($cancel instanceof single_button) {
11820bac 950 // ok
4871a238
PS
951 } else if (is_string($cancel)) {
952 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
953 } else if ($cancel instanceof moodle_url) {
26eab8d4 954 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 955 } else {
4ed85790 956 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 957 }
958
d9c8f425 959 $output = $this->box_start('generalbox', 'notice');
26acc814
PS
960 $output .= html_writer::tag('p', $message);
961 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 962 $output .= $this->box_end();
963 return $output;
964 }
965
3cd5305f 966 /**
3ba60ee1 967 * Returns a form with a single button.
3cd5305f 968 *
3ba60ee1 969 * @param string|moodle_url $url
3cd5305f
PS
970 * @param string $label button text
971 * @param string $method get or post submit method
3ba60ee1 972 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
973 * @return string HTML fragment
974 */
3ba60ee1 975 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
976 if (!($url instanceof moodle_url)) {
977 $url = new moodle_url($url);
3ba60ee1 978 }
574fbea4
PS
979 $button = new single_button($url, $label, $method);
980
3ba60ee1
PS
981 foreach ((array)$options as $key=>$value) {
982 if (array_key_exists($key, $button)) {
983 $button->$key = $value;
984 }
3cd5305f
PS
985 }
986
3ba60ee1 987 return $this->render($button);
3cd5305f
PS
988 }
989
d9c8f425 990 /**
3ba60ee1
PS
991 * Internal implementation of single_button rendering
992 * @param single_button $button
d9c8f425 993 * @return string HTML fragment
994 */
3ba60ee1
PS
995 protected function render_single_button(single_button $button) {
996 $attributes = array('type' => 'submit',
997 'value' => $button->label,
db09524d 998 'disabled' => $button->disabled ? 'disabled' : null,
3ba60ee1
PS
999 'title' => $button->tooltip);
1000
1001 if ($button->actions) {
1002 $id = html_writer::random_id('single_button');
1003 $attributes['id'] = $id;
1004 foreach ($button->actions as $action) {
c80877aa 1005 $this->add_action_handler($action, $id);
3ba60ee1 1006 }
d9c8f425 1007 }
d9c8f425 1008
3ba60ee1
PS
1009 // first the input element
1010 $output = html_writer::empty_tag('input', $attributes);
d9c8f425 1011
3ba60ee1
PS
1012 // then hidden fields
1013 $params = $button->url->params();
1014 if ($button->method === 'post') {
1015 $params['sesskey'] = sesskey();
1016 }
1017 foreach ($params as $var => $val) {
1018 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1019 }
d9c8f425 1020
3ba60ee1 1021 // then div wrapper for xhtml strictness
26acc814 1022 $output = html_writer::tag('div', $output);
d9c8f425 1023
3ba60ee1 1024 // now the form itself around it
eb788065 1025 $url = $button->url->out_omit_querystring(); // url without params
a6855934
PS
1026 if ($url === '') {
1027 $url = '#'; // there has to be always some action
1028 }
3ba60ee1 1029 $attributes = array('method' => $button->method,
a6855934 1030 'action' => $url,
3ba60ee1 1031 'id' => $button->formid);
26acc814 1032 $output = html_writer::tag('form', $output, $attributes);
d9c8f425 1033
3ba60ee1 1034 // and finally one more wrapper with class
26acc814 1035 return html_writer::tag('div', $output, array('class' => $button->class));
d9c8f425 1036 }
1037
a9967cf5 1038 /**
ab08be98 1039 * Returns a form with a single select widget.
a9967cf5
PS
1040 * @param moodle_url $url form action target, includes hidden fields
1041 * @param string $name name of selection field - the changing parameter in url
1042 * @param array $options list of options
1043 * @param string $selected selected element
1044 * @param array $nothing
f8dab966 1045 * @param string $formid
a9967cf5
PS
1046 * @return string HTML fragment
1047 */
f8dab966 1048 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
a9967cf5
PS
1049 if (!($url instanceof moodle_url)) {
1050 $url = new moodle_url($url);
1051 }
f8dab966 1052 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5
PS
1053
1054 return $this->render($select);
1055 }
1056
1057 /**
1058 * Internal implementation of single_select rendering
1059 * @param single_select $select
1060 * @return string HTML fragment
1061 */
1062 protected function render_single_select(single_select $select) {
1063 $select = clone($select);
1064 if (empty($select->formid)) {
1065 $select->formid = html_writer::random_id('single_select_f');
1066 }
1067
1068 $output = '';
1069 $params = $select->url->params();
1070 if ($select->method === 'post') {
1071 $params['sesskey'] = sesskey();
1072 }
1073 foreach ($params as $name=>$value) {
1074 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1075 }
1076
1077 if (empty($select->attributes['id'])) {
1078 $select->attributes['id'] = html_writer::random_id('single_select');
1079 }
1080
0b2cb132
PS
1081 if ($select->disabled) {
1082 $select->attributes['disabled'] = 'disabled';
1083 }
4d10e579 1084
a9967cf5
PS
1085 if ($select->tooltip) {
1086 $select->attributes['title'] = $select->tooltip;
1087 }
1088
1089 if ($select->label) {
26acc814 1090 $output .= html_writer::tag('label', $select->label, array('for'=>$select->attributes['id']));
a9967cf5
PS
1091 }
1092
1093 if ($select->helpicon instanceof help_icon) {
1094 $output .= $this->render($select->helpicon);
259c165d
PS
1095 } else if ($select->helpicon instanceof old_help_icon) {
1096 $output .= $this->render($select->helpicon);
a9967cf5
PS
1097 }
1098
1099 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1100
1101 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
26acc814 1102 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
a9967cf5
PS
1103
1104 $nothing = empty($select->nothing) ? false : key($select->nothing);
edc28287 1105 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
a9967cf5
PS
1106
1107 // then div wrapper for xhtml strictness
26acc814 1108 $output = html_writer::tag('div', $output);
a9967cf5
PS
1109
1110 // now the form itself around it
1111 $formattributes = array('method' => $select->method,
1112 'action' => $select->url->out_omit_querystring(),
1113 'id' => $select->formid);
26acc814 1114 $output = html_writer::tag('form', $output, $formattributes);
4d10e579
PS
1115
1116 // and finally one more wrapper with class
26acc814 1117 return html_writer::tag('div', $output, array('class' => $select->class));
4d10e579
PS
1118 }
1119
1120 /**
ab08be98 1121 * Returns a form with a url select widget.
4d10e579
PS
1122 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1123 * @param string $selected selected element
1124 * @param array $nothing
1125 * @param string $formid
1126 * @return string HTML fragment
1127 */
1128 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1129 $select = new url_select($urls, $selected, $nothing, $formid);
1130 return $this->render($select);
1131 }
1132
1133 /**
ab08be98 1134 * Internal implementation of url_select rendering
4d10e579
PS
1135 * @param single_select $select
1136 * @return string HTML fragment
1137 */
1138 protected function render_url_select(url_select $select) {
1139 $select = clone($select);
1140 if (empty($select->formid)) {
1141 $select->formid = html_writer::random_id('url_select_f');
1142 }
1143
1144 if (empty($select->attributes['id'])) {
1145 $select->attributes['id'] = html_writer::random_id('url_select');
1146 }
1147
1148 if ($select->disabled) {
1149 $select->attributes['disabled'] = 'disabled';
1150 }
1151
1152 if ($select->tooltip) {
1153 $select->attributes['title'] = $select->tooltip;
1154 }
1155
1156 $output = '';
1157
1158 if ($select->label) {
26acc814 1159 $output .= html_writer::tag('label', $select->label, array('for'=>$select->attributes['id']));
4d10e579
PS
1160 }
1161
1162 if ($select->helpicon instanceof help_icon) {
1163 $output .= $this->render($select->helpicon);
259c165d
PS
1164 } else if ($select->helpicon instanceof old_help_icon) {
1165 $output .= $this->render($select->helpicon);
4d10e579
PS
1166 }
1167
1168 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1169 $output .= html_writer::select($select->urls, 'jump', $select->selected, $select->nothing, $select->attributes);
1170
1171 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
26acc814 1172 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
4d10e579
PS
1173
1174 $nothing = empty($select->nothing) ? false : key($select->nothing);
1175 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1176
1177 // then div wrapper for xhtml strictness
26acc814 1178 $output = html_writer::tag('div', $output);
4d10e579
PS
1179
1180 // now the form itself around it
1181 $formattributes = array('method' => 'post',
1182 'action' => new moodle_url('/course/jumpto.php'),
1183 'id' => $select->formid);
26acc814 1184 $output = html_writer::tag('form', $output, $formattributes);
a9967cf5
PS
1185
1186 // and finally one more wrapper with class
26acc814 1187 return html_writer::tag('div', $output, array('class' => $select->class));
a9967cf5
PS
1188 }
1189
d9c8f425 1190 /**
1191 * Returns a string containing a link to the user documentation.
1192 * Also contains an icon by default. Shown to teachers and admin only.
1193 * @param string $path The page link after doc root and language, no leading slash.
1194 * @param string $text The text to be displayed for the link
8ae8bf8a 1195 * @retrun string
d9c8f425 1196 */
8ae8bf8a
PS
1197 public function doc_link($path, $text) {
1198 global $CFG;
1199
000c278c 1200 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
8ae8bf8a 1201
000c278c 1202 $url = new moodle_url(get_docs_url($path));
8ae8bf8a 1203
c80877aa 1204 $attributes = array('href'=>$url);
d9c8f425 1205 if (!empty($CFG->doctonewwindow)) {
c80877aa 1206 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
d9c8f425 1207 }
1adaa404 1208
26acc814 1209 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 1210 }
1211
000c278c
PS
1212 /**
1213 * Render icon
1214 * @param string $pix short pix name
1215 * @param string $alt mandatory alt attribute
1216 * @param strin $component standard compoennt name like 'moodle', 'mod_form', etc.
1217 * @param array $attributes htm lattributes
1218 * @return string HTML fragment
1219 */
1220 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1221 $icon = new pix_icon($pix, $alt, $component, $attributes);
1222 return $this->render($icon);
1223 }
1224
1225 /**
1226 * Render icon
1227 * @param pix_icon $icon
1228 * @return string HTML fragment
1229 */
ce0110bf 1230 protected function render_pix_icon(pix_icon $icon) {
000c278c
PS
1231 $attributes = $icon->attributes;
1232 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
c80877aa 1233 return html_writer::empty_tag('img', $attributes);
000c278c
PS
1234 }
1235
a09aeee4
AD
1236 /**
1237 * Produces the html that represents this rating in the UI
1238 * @param $page the page object on which this rating will appear
1239 */
1240 function render_rating(rating $rating) {
7ac928a7 1241 global $CFG, $USER;
a09aeee4
AD
1242 static $havesetupjavascript = false;
1243
b1721f67
AD
1244 $useajax = !empty($CFG->enableajax);
1245
1246 //include required Javascript
1247 if( !$havesetupjavascript && $useajax ) {
3dcdf440 1248 $this->page->requires->js_init_call('M.core_rating.init');
a09aeee4
AD
1249 $havesetupjavascript = true;
1250 }
1251
f1f6a755
AD
1252 $strrate = get_string("rate", "rating");
1253 $strratings = ''; //the string we'll return
a09aeee4 1254
8b69c341 1255 if($rating->settings->permissions->canview || $rating->settings->permissions->canviewall) {
a09aeee4
AD
1256 switch ($rating->settings->aggregationmethod) {
1257 case RATING_AGGREGATE_AVERAGE :
1258 $strratings .= get_string("aggregateavg", "forum");
1259 break;
1260 case RATING_AGGREGATE_COUNT :
1261 $strratings .= get_string("aggregatecount", "forum");
1262 break;
1263 case RATING_AGGREGATE_MAXIMUM :
1264 $strratings .= get_string("aggregatemax", "forum");
1265 break;
1266 case RATING_AGGREGATE_MINIMUM :
1267 $strratings .= get_string("aggregatemin", "forum");
1268 break;
1269 case RATING_AGGREGATE_SUM :
1270 $strratings .= get_string("aggregatesum", "forum");
1271 break;
1272 }
1273
1274 if (empty($strratings)) {
1275 $strratings .= $strrate;
1276 }
1277 $strratings .= ': ';
1278
1279 $scalemax = 0;
1280 $ratingstr = null;
1281
1282 if ( is_array($rating->settings->scale->scaleitems) ) {
1283 $scalemax = $rating->settings->scale->scaleitems[ count($rating->settings->scale->scaleitems)-1 ];
1284 $ratingstr = $rating->settings->scale->scaleitems[$rating->rating];
1285 }
1286 else { //its numeric
1287 $scalemax = $rating->settings->scale->scaleitems;
1288 $ratingstr = round($rating->aggregate,1);
1289 }
1adaa404 1290
a09aeee4
AD
1291 $aggstr = "{$ratingstr} / $scalemax ({$rating->count}) ";
1292
8b69c341 1293 if ($rating->settings->permissions->canviewall) {
a09aeee4
AD
1294 $link = new moodle_url("/rating/index.php?contextid={$rating->context->id}&itemid={$rating->itemid}&scaleid={$rating->scaleid}");
1295 $action = new popup_action('click', $link, 'ratings', array('height' => 400, 'width' => 600));
1296 $strratings .= $this->action_link($link, $aggstr, $action);
8b69c341 1297 } else if ($rating->settings->permissions->canview) {
a09aeee4
AD
1298 $strratings .= $aggstr;
1299 }
1300 }
1301
1302 //todo andrew alter the below if to deny guest users the ability to post ratings.
1303 //Petr to define "guest"
1304 $formstart = null;
8b69c341 1305 if($rating->settings->permissions->canrate) {
a09aeee4
AD
1306 //dont use $rating->userid below as it will be null if the user hasnt already rated the item
1307 $formstart = <<<END
1308<form id="postrating{$rating->itemid}" class="postratingform" method="post" action="rating/rate.php">
1309<div class="ratingform">
1310<input type="hidden" class="ratinginput" name="contextid" value="{$rating->context->id}" />
1311<input type="hidden" class="ratinginput" name="itemid" value="{$rating->itemid}" />
1312<input type="hidden" class="ratinginput" name="scaleid" value="{$rating->settings->scale->id}" />
1313<input type="hidden" class="ratinginput" name="returnurl" value="{$rating->settings->returnurl}" />
1314END;
1315 $strratings = $formstart.$strratings;
1316
1317 //generate an array of values for numeric scales
1318 $scalearray = $rating->settings->scale->scaleitems;
6c5fcef7
AD
1319 if( !is_array($scalearray) ) { //almost certainly a numerical scale
1320 $intscalearray = intval($scalearray);//just in case theyve passed "5" instead of 5
1321 if( is_int($intscalearray) && $intscalearray>0 ){
1322 $scalearray = array();
1323 for($i=0; $i<=$rating->settings->scale->scaleitems; $i++) {
1324 $scalearray[$i] = $i;
1325 }
a09aeee4
AD
1326 }
1327 }
6c5fcef7 1328
a09aeee4 1329 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $scalearray;
c82ed0a8 1330 $strratings .= html_writer::select($scalearray, 'rating', $rating->rating, false, array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid));
a09aeee4
AD
1331
1332 //output submit button
f1f6a755 1333 $strratings .= '<span class="ratingsubmit"><input type="submit" class="postratingmenusubmit" id="postratingsubmit'.$rating->itemid.'" value="'.s(get_string('rate', 'rating')).'" />';
a09aeee4 1334
a09aeee4
AD
1335 if ( is_array($rating->settings->scale) ) {
1336 //todo andrew where can we get the course id from?
1337 //$strratings .= $this->help_icon_scale($course->id, $scale);
1338 $strratings .= $this->help_icon_scale(1, $rating->settings->scale);
1339 }
1340 $strratings .= '</span></div></form>';
1341 }
1342
1343 return $strratings;
1344 }
1345
d9c8f425 1346 /*
1347 * Centered heading with attached help button (same title text)
1348 * and optional icon attached
4bcc5118 1349 * @param string $text A heading text
53a78cef 1350 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
1351 * @param string $component component name
1352 * @param string|moodle_url $icon
1353 * @param string $iconalt icon alt text
d9c8f425 1354 * @return string HTML fragment
1355 */
53a78cef 1356 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
4bcc5118
PS
1357 $image = '';
1358 if ($icon) {
0029a917 1359 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
d9c8f425 1360 }
4bcc5118 1361
259c165d
PS
1362 $help = '';
1363 if ($helpidentifier) {
1364 $help = $this->help_icon($helpidentifier, $component);
1365 }
4bcc5118
PS
1366
1367 return $this->heading($image.$text.$help, 2, 'main help');
d9c8f425 1368 }
1369
1370 /**
1371 * Print a help icon.
1372 *
4bcc5118 1373 * @param string $page The keyword that defines a help page
bf11293a 1374 * @param string $title A descriptive text for accessibility only
4bcc5118 1375 * @param string $component component name
bf11293a
PS
1376 * @param string|bool $linktext true means use $title as link text, string means link text value
1377 * @return string HTML fragment
1378 */
596509e4
PS
1379 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1380 $icon = new old_help_icon($helpidentifier, $title, $component);
bf11293a
PS
1381 if ($linktext === true) {
1382 $icon->linktext = $title;
1383 } else if (!empty($linktext)) {
1384 $icon->linktext = $linktext;
1385 }
1386 return $this->render($icon);
1387 }
4bcc5118 1388
bf11293a
PS
1389 /**
1390 * Implementation of user image rendering.
1391 * @param help_icon $helpicon
1392 * @return string HTML fragment
d9c8f425 1393 */
596509e4 1394 protected function render_old_help_icon(old_help_icon $helpicon) {
bf11293a 1395 global $CFG;
d9c8f425 1396
bf11293a
PS
1397 // first get the help image icon
1398 $src = $this->pix_url('help');
d9c8f425 1399
bf11293a
PS
1400 if (empty($helpicon->linktext)) {
1401 $alt = $helpicon->title;
1402 } else {
1403 $alt = get_string('helpwiththis');
1404 }
1405
1406 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1407 $output = html_writer::empty_tag('img', $attributes);
1408
1409 // add the link text if given
1410 if (!empty($helpicon->linktext)) {
1411 // the spacing has to be done through CSS
1412 $output .= $helpicon->linktext;
d9c8f425 1413 }
1414
53a78cef
PS
1415 // now create the link around it
1416 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
bf11293a
PS
1417
1418 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1419 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1420
1421 $attributes = array('href'=>$url, 'title'=>$title);
1422 $id = html_writer::random_id('helpicon');
1423 $attributes['id'] = $id;
c80877aa 1424 $this->add_action_handler(new popup_action('click', $url), $id);
26acc814 1425 $output = html_writer::tag('a', $output, $attributes);
bf11293a
PS
1426
1427 // and finally span
26acc814 1428 return html_writer::tag('span', $output, array('class' => 'helplink'));
d9c8f425 1429 }
1430
259c165d
PS
1431 /**
1432 * Print a help icon.
1433 *
1434 * @param string $identifier The keyword that defines a help page
1435 * @param string $component component name
1436 * @param string|bool $linktext true means use $title as link text, string means link text value
1437 * @return string HTML fragment
1438 */
1439 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1440 $icon = new help_icon($identifier, $component);
1441 $icon->diag_strings();
1442 if ($linktext === true) {
1443 $icon->linktext = get_string($icon->identifier, $icon->component);
1444 } else if (!empty($linktext)) {
1445 $icon->linktext = $linktext;
1446 }
1447 return $this->render($icon);
1448 }
1449
1450 /**
1451 * Implementation of user image rendering.
1452 * @param help_icon $helpicon
1453 * @return string HTML fragment
1454 */
1455 protected function render_help_icon(help_icon $helpicon) {
1456 global $CFG;
1457
1458 // first get the help image icon
1459 $src = $this->pix_url('help');
1460
1461 $title = get_string($helpicon->identifier, $helpicon->component);
1462
1463 if (empty($helpicon->linktext)) {
1464 $alt = $title;
1465 } else {
1466 $alt = get_string('helpwiththis');
1467 }
1468
1469 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1470 $output = html_writer::empty_tag('img', $attributes);
1471
1472 // add the link text if given
1473 if (!empty($helpicon->linktext)) {
1474 // the spacing has to be done through CSS
1475 $output .= $helpicon->linktext;
1476 }
1477
1478 // now create the link around it
1479 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1480
1481 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1482 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1483
1484 $attributes = array('href'=>$url, 'title'=>$title);
1485 $id = html_writer::random_id('helpicon');
1486 $attributes['id'] = $id;
1487 $this->add_action_handler(new popup_action('click', $url), $id);
1488 $output = html_writer::tag('a', $output, $attributes);
1489
1490 // and finally span
1491 return html_writer::tag('span', $output, array('class' => 'helplink'));
1492 }
1493
d9c8f425 1494 /**
4bcc5118 1495 * Print scale help icon.
d9c8f425 1496 *
4bcc5118
PS
1497 * @param int $courseid
1498 * @param object $scale instance
1499 * @return string HTML fragment
d9c8f425 1500 */
4bcc5118
PS
1501 public function help_icon_scale($courseid, stdClass $scale) {
1502 global $CFG;
02f64f97 1503
4bcc5118 1504 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 1505
0029a917 1506 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 1507
57cd3739 1508 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scale->id));
230ec401 1509 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 1510
26acc814 1511 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 1512 }
1513
1514 /**
1515 * Creates and returns a spacer image with optional line break.
1516 *
0029a917
PS
1517 * @param array $attributes
1518 * @param boo spacer
d9c8f425 1519 * @return string HTML fragment
1520 */
0029a917
PS
1521 public function spacer(array $attributes = null, $br = false) {
1522 $attributes = (array)$attributes;
1523 if (empty($attributes['width'])) {
1524 $attributes['width'] = 1;
1ba862ec
PS
1525 }
1526 if (empty($options['height'])) {
0029a917 1527 $attributes['height'] = 1;
d9c8f425 1528 }
0029a917 1529 $attributes['class'] = 'spacer';
d9c8f425 1530
0029a917 1531 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 1532
0029a917 1533 if (!empty($br)) {
1ba862ec
PS
1534 $output .= '<br />';
1535 }
d9c8f425 1536
1537 return $output;
1538 }
1539
d9c8f425 1540 /**
1541 * Print the specified user's avatar.
1542 *
5d0c95a5 1543 * User avatar may be obtained in two ways:
d9c8f425 1544 * <pre>
812dbaf7
PS
1545 * // Option 1: (shortcut for simple cases, preferred way)
1546 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1547 * $OUTPUT->user_picture($user, array('popup'=>true));
1548 *
5d0c95a5
PS
1549 * // Option 2:
1550 * $userpic = new user_picture($user);
d9c8f425 1551 * // Set properties of $userpic
812dbaf7 1552 * $userpic->popup = true;
5d0c95a5 1553 * $OUTPUT->render($userpic);
d9c8f425 1554 * </pre>
1555 *
5d0c95a5 1556 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 1557 * If any of these are missing, the database is queried. Avoid this
d9c8f425 1558 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
1559 * @param array $options associative array with user picture options, used only if not a user_picture object,
1560 * options are:
1561 * - courseid=$this->page->course->id (course id of user profile in link)
1562 * - size=35 (size of image)
1563 * - link=true (make image clickable - the link leads to user profile)
1564 * - popup=false (open in popup)
1565 * - alttext=true (add image alt attribute)
5d0c95a5 1566 * - class = image class attribute (default 'userpicture')
d9c8f425 1567 * @return string HTML fragment
1568 */
5d0c95a5
PS
1569 public function user_picture(stdClass $user, array $options = null) {
1570 $userpicture = new user_picture($user);
1571 foreach ((array)$options as $key=>$value) {
1572 if (array_key_exists($key, $userpicture)) {
1573 $userpicture->$key = $value;
1574 }
1575 }
1576 return $this->render($userpicture);
1577 }
1578
1579 /**
1580 * Internal implementation of user image rendering.
1581 * @param user_picture $userpicture
1582 * @return string
1583 */
1584 protected function render_user_picture(user_picture $userpicture) {
1585 global $CFG, $DB;
812dbaf7 1586
5d0c95a5
PS
1587 $user = $userpicture->user;
1588
1589 if ($userpicture->alttext) {
1590 if (!empty($user->imagealt)) {
1591 $alt = $user->imagealt;
1592 } else {
1593 $alt = get_string('pictureof', '', fullname($user));
1594 }
d9c8f425 1595 } else {
97c10099 1596 $alt = '';
5d0c95a5
PS
1597 }
1598
1599 if (empty($userpicture->size)) {
1600 $file = 'f2';
1601 $size = 35;
1602 } else if ($userpicture->size === true or $userpicture->size == 1) {
1603 $file = 'f1';
1604 $size = 100;
1605 } else if ($userpicture->size >= 50) {
1606 $file = 'f1';
1607 $size = $userpicture->size;
1608 } else {
1609 $file = 'f2';
1610 $size = $userpicture->size;
d9c8f425 1611 }
1612
5d0c95a5 1613 $class = $userpicture->class;
d9c8f425 1614
5d0c95a5
PS
1615 if (!empty($user->picture)) {
1616 require_once($CFG->libdir.'/filelib.php');
1617 $src = new moodle_url(get_file_url($user->id.'/'.$file.'.jpg', null, 'user'));
1618 } else { // Print default user pictures (use theme version if available)
1619 $class .= ' defaultuserpic';
1620 $src = $this->pix_url('u/' . $file);
1621 }
d9c8f425 1622
5d0c95a5
PS
1623 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1624
1625 // get the image html output fisrt
1626 $output = html_writer::empty_tag('img', $attributes);;
1627
1628 // then wrap it in link if needed
1629 if (!$userpicture->link) {
1630 return $output;
d9c8f425 1631 }
1632
5d0c95a5
PS
1633 if (empty($userpicture->courseid)) {
1634 $courseid = $this->page->course->id;
1635 } else {
1636 $courseid = $userpicture->courseid;
1637 }
1638
a6855934 1639 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
5d0c95a5
PS
1640
1641 $attributes = array('href'=>$url);
1642
1643 if ($userpicture->popup) {
1644 $id = html_writer::random_id('userpicture');
1645 $attributes['id'] = $id;
c80877aa 1646 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
1647 }
1648
26acc814 1649 return html_writer::tag('a', $output, $attributes);
d9c8f425 1650 }
1651
1652 /**
1653 * Prints the 'Update this Modulename' button that appears on module pages.
1654 *
1655 * @param string $cmid the course_module id.
1656 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1657 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1658 */
1659 public function update_module_button($cmid, $modulename) {
1660 global $CFG;
1661 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1662 $modulename = get_string('modulename', $modulename);
1663 $string = get_string('updatethis', '', $modulename);
3ba60ee1
PS
1664 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1665 return $this->single_button($url, $string);
d9c8f425 1666 } else {
1667 return '';
1668 }
1669 }
1670
1671 /**
1672 * Prints a "Turn editing on/off" button in a form.
1673 * @param moodle_url $url The URL + params to send through when clicking the button
1674 * @return string HTML the button
1675 */
1676 public function edit_button(moodle_url $url) {
1677 global $USER;
1678 if (!empty($USER->editing)) {
1679 $string = get_string('turneditingoff');
1680 $edit = '0';
1681 } else {
1682 $string = get_string('turneditingon');
1683 $edit = '1';
1684 }
1685
3ba60ee1 1686 $url = new moodle_url($url, array('edit'=>$edit));
d9c8f425 1687
3ba60ee1 1688 return $this->single_button($url, $string);
d9c8f425 1689 }
1690
d9c8f425 1691 /**
1692 * Prints a simple button to close a window
1693 *
d9c8f425 1694 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 1695 * @return string html fragment
d9c8f425 1696 */
7a5c78e0 1697 public function close_window_button($text='') {
d9c8f425 1698 if (empty($text)) {
1699 $text = get_string('closewindow');
1700 }
a6855934
PS
1701 $button = new single_button(new moodle_url('#'), $text, 'get');
1702 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
1703
1704 return $this->container($this->render($button), 'closewindow');
d9c8f425 1705 }
1706
d9c8f425 1707 /**
1708 * Output an error message. By default wraps the error message in <span class="error">.
1709 * If the error message is blank, nothing is output.
1710 * @param string $message the error message.
1711 * @return string the HTML to output.
1712 */
1713 public function error_text($message) {
1714 if (empty($message)) {
1715 return '';
1716 }
26acc814 1717 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 1718 }
1719
1720 /**
1721 * Do not call this function directly.
1722 *
1723 * To terminate the current script with a fatal error, call the {@link print_error}
1724 * function, or throw an exception. Doing either of those things will then call this
1725 * function to display the error, before terminating the execution.
1726 *
1727 * @param string $message The message to output
1728 * @param string $moreinfourl URL where more info can be found about the error
1729 * @param string $link Link for the Continue button
1730 * @param array $backtrace The execution backtrace
1731 * @param string $debuginfo Debugging information
d9c8f425 1732 * @return string the HTML to output.
1733 */
83267ec0 1734 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
d9c8f425 1735
1736 $output = '';
6f8f4d83 1737 $obbuffer = '';
e57c283d 1738
d9c8f425 1739 if ($this->has_started()) {
50764d37
PS
1740 // we can not always recover properly here, we have problems with output buffering,
1741 // html tables, etc.
d9c8f425 1742 $output .= $this->opencontainers->pop_all_but_last();
50764d37 1743
d9c8f425 1744 } else {
50764d37
PS
1745 // It is really bad if library code throws exception when output buffering is on,
1746 // because the buffered text would be printed before our start of page.
1747 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
1748 while (ob_get_level() > 0) {
6f8f4d83 1749 $obbuffer .= ob_get_clean();
50764d37 1750 }
6f8f4d83 1751
d9c8f425 1752 // Header not yet printed
85309744 1753 if (isset($_SERVER['SERVER_PROTOCOL'])) {
78946b9b
PS
1754 // server protocol should be always present, because this render
1755 // can not be used from command line or when outputting custom XML
85309744
PS
1756 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
1757 }
7fde1e4b 1758 $this->page->set_url('/'); // no url
191b267b 1759 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
d9c8f425 1760 $this->page->set_title(get_string('error'));
1761 $output .= $this->header();
1762 }
1763
1764 $message = '<p class="errormessage">' . $message . '</p>'.
1765 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
1766 get_string('moreinformation') . '</a></p>';
1767 $output .= $this->box($message, 'errorbox');
1768
6f8f4d83
PS
1769 if (debugging('', DEBUG_DEVELOPER)) {
1770 if (!empty($debuginfo)) {
c5d18164
PS
1771 $debuginfo = s($debuginfo); // removes all nasty JS
1772 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1773 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
6f8f4d83
PS
1774 }
1775 if (!empty($backtrace)) {
1776 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
1777 }
1778 if ($obbuffer !== '' ) {
1779 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
1780 }
d9c8f425 1781 }
1782
1783 if (!empty($link)) {
1784 $output .= $this->continue_button($link);
1785 }
1786
1787 $output .= $this->footer();
1788
1789 // Padding to encourage IE to display our error page, rather than its own.
1790 $output .= str_repeat(' ', 512);
1791
1792 return $output;
1793 }
1794
1795 /**
1796 * Output a notification (that is, a status message about something that has
1797 * just happened).
1798 *
1799 * @param string $message the message to print out
1800 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
1801 * @return string the HTML to output.
1802 */
1803 public function notification($message, $classes = 'notifyproblem') {
26acc814 1804 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
d9c8f425 1805 }
1806
1807 /**
1808 * Print a continue button that goes to a particular URL.
1809 *
3ba60ee1 1810 * @param string|moodle_url $url The url the button goes to.
d9c8f425 1811 * @return string the HTML to output.
1812 */
3ba60ee1
PS
1813 public function continue_button($url) {
1814 if (!($url instanceof moodle_url)) {
1815 $url = new moodle_url($url);
d9c8f425 1816 }
3ba60ee1
PS
1817 $button = new single_button($url, get_string('continue'), 'get');
1818 $button->class = 'continuebutton';
d9c8f425 1819
3ba60ee1 1820 return $this->render($button);
d9c8f425 1821 }
1822
1823 /**
1824 * Prints a single paging bar to provide access to other pages (usually in a search)
1825 *
929d7a83
PS
1826 * @param int $totalcount Thetotal number of entries available to be paged through
1827 * @param int $page The page you are currently viewing
1828 * @param int $perpage The number of entries that should be shown per page
1829 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1830 * @param string $pagevar name of page parameter that holds the page number
d9c8f425 1831 * @return string the HTML to output.
1832 */
929d7a83
PS
1833 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1834 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
1835 return $this->render($pb);
1836 }
1837
1838 /**
1839 * Internal implementation of paging bar rendering.
1840 * @param paging_bar $pagingbar
1841 * @return string
1842 */
1843 protected function render_paging_bar(paging_bar $pagingbar) {
d9c8f425 1844 $output = '';
1845 $pagingbar = clone($pagingbar);
34059565 1846 $pagingbar->prepare($this, $this->page, $this->target);
d9c8f425 1847
1848 if ($pagingbar->totalcount > $pagingbar->perpage) {
1849 $output .= get_string('page') . ':';
1850
1851 if (!empty($pagingbar->previouslink)) {
56ddb719 1852 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
d9c8f425 1853 }
1854
1855 if (!empty($pagingbar->firstlink)) {
56ddb719 1856 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
d9c8f425 1857 }
1858
1859 foreach ($pagingbar->pagelinks as $link) {
56ddb719 1860 $output .= "&#160;&#160;$link";
d9c8f425 1861 }
1862
1863 if (!empty($pagingbar->lastlink)) {
56ddb719 1864 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
d9c8f425 1865 }
1866
1867 if (!empty($pagingbar->nextlink)) {
56ddb719 1868 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
d9c8f425 1869 }
1870 }
1871
26acc814 1872 return html_writer::tag('div', $output, array('class' => 'paging'));
d9c8f425 1873 }
1874
d9c8f425 1875 /**
1876 * Output the place a skip link goes to.
1877 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
1878 * @return string the HTML to output.
1879 */
fe213365 1880 public function skip_link_target($id = null) {
26acc814 1881 return html_writer::tag('span', '', array('id' => $id));
d9c8f425 1882 }
1883
1884 /**
1885 * Outputs a heading
1886 * @param string $text The text of the heading
1887 * @param int $level The level of importance of the heading. Defaulting to 2
1888 * @param string $classes A space-separated list of CSS classes
1889 * @param string $id An optional ID
1890 * @return string the HTML to output.
1891 */
fe213365 1892 public function heading($text, $level = 2, $classes = 'main', $id = null) {
d9c8f425 1893 $level = (integer) $level;
1894 if ($level < 1 or $level > 6) {
1895 throw new coding_exception('Heading level must be an integer between 1 and 6.');
1896 }
26acc814 1897 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 1898 }
1899
1900 /**
1901 * Outputs a box.
1902 * @param string $contents The contents of the box
1903 * @param string $classes A space-separated list of CSS classes
1904 * @param string $id An optional ID
1905 * @return string the HTML to output.
1906 */
fe213365 1907 public function box($contents, $classes = 'generalbox', $id = null) {
d9c8f425 1908 return $this->box_start($classes, $id) . $contents . $this->box_end();
1909 }
1910
1911 /**
1912 * Outputs the opening section of a box.
1913 * @param string $classes A space-separated list of CSS classes
1914 * @param string $id An optional ID
1915 * @return string the HTML to output.
1916 */
fe213365 1917 public function box_start($classes = 'generalbox', $id = null) {
5d0c95a5
PS
1918 $this->opencontainers->push('box', html_writer::end_tag('div'));
1919 return html_writer::start_tag('div', array('id' => $id,
78946b9b 1920 'class' => 'box ' . renderer_base::prepare_classes($classes)));
d9c8f425 1921 }
1922
1923 /**
1924 * Outputs the closing section of a box.
1925 * @return string the HTML to output.
1926 */
1927 public function box_end() {
1928 return $this->opencontainers->pop('box');
1929 }
1930
1931 /**
1932 * Outputs a container.
1933 * @param string $contents The contents of the box
1934 * @param string $classes A space-separated list of CSS classes
1935 * @param string $id An optional ID
1936 * @return string the HTML to output.
1937 */
fe213365 1938 public function container($contents, $classes = null, $id = null) {
d9c8f425 1939 return $this->container_start($classes, $id) . $contents . $this->container_end();
1940 }
1941
1942 /**
1943 * Outputs the opening section of a container.
1944 * @param string $classes A space-separated list of CSS classes
1945 * @param string $id An optional ID
1946 * @return string the HTML to output.
1947 */
fe213365 1948 public function container_start($classes = null, $id = null) {
5d0c95a5
PS
1949 $this->opencontainers->push('container', html_writer::end_tag('div'));
1950 return html_writer::start_tag('div', array('id' => $id,
78946b9b 1951 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 1952 }
1953
1954 /**
1955 * Outputs the closing section of a container.
1956 * @return string the HTML to output.
1957 */
1958 public function container_end() {
1959 return $this->opencontainers->pop('container');
1960 }
7d2a0492 1961
1962 /**
1963 * Make nested HTML lists out of the items
1964 *
1965 * The resulting list will look something like this:
1966 *
1967 * <pre>
1968 * <<ul>>
1969 * <<li>><div class='tree_item parent'>(item contents)</div>
1970 * <<ul>
1971 * <<li>><div class='tree_item'>(item contents)</div><</li>>
1972 * <</ul>>
1973 * <</li>>
1974 * <</ul>>
1975 * </pre>
1976 *
1977 * @param array[]tree_item $items
1978 * @param array[string]string $attrs html attributes passed to the top of
1979 * the list
1980 * @return string HTML
1981 */
1982 function tree_block_contents($items, $attrs=array()) {
1983 // exit if empty, we don't want an empty ul element
1984 if (empty($items)) {
1985 return '';
1986 }
1987 // array of nested li elements
1988 $lis = array();
1989 foreach ($items as $item) {
1990 // this applies to the li item which contains all child lists too
1991 $content = $item->content($this);
1992 $liclasses = array($item->get_css_type());
1993 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || (count($item->children)==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
1994 $liclasses[] = 'collapsed';
1995 }
1996 if ($item->isactive === true) {
1997 $liclasses[] = 'current_branch';
1998 }
1999 $liattr = array('class'=>join(' ',$liclasses));
2000 // class attribute on the div item which only contains the item content
2001 $divclasses = array('tree_item');
2002 if (!empty($item->children) || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2003 $divclasses[] = 'branch';
2004 } else {
2005 $divclasses[] = 'leaf';
2006 }
2007 if (!empty($item->classes) && count($item->classes)>0) {
2008 $divclasses[] = join(' ', $item->classes);
2009 }
2010 $divattr = array('class'=>join(' ', $divclasses));
2011 if (!empty($item->id)) {
2012 $divattr['id'] = $item->id;
2013 }
26acc814 2014 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
7d2a0492 2015 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
26acc814 2016 $content = html_writer::empty_tag('hr') . $content;
7d2a0492 2017 }
26acc814 2018 $content = html_writer::tag('li', $content, $liattr);
7d2a0492 2019 $lis[] = $content;
2020 }
26acc814 2021 return html_writer::tag('ul', implode("\n", $lis), $attrs);
7d2a0492 2022 }
2023
2024 /**
2025 * Return the navbar content so that it can be echoed out by the layout
2026 * @return string XHTML navbar
2027 */
2028 public function navbar() {
2029 return $this->page->navbar->content();
2030 }
92e01ab7
PS
2031
2032 /**
2033 * Accessibility: Right arrow-like character is
2034 * used in the breadcrumb trail, course navigation menu
2035 * (previous/next activity), calendar, and search forum block.
2036 * If the theme does not set characters, appropriate defaults
2037 * are set automatically. Please DO NOT
2038 * use &lt; &gt; &raquo; - these are confusing for blind users.
2039 * @return string
2040 */
2041 public function rarrow() {
2042 return $this->page->theme->rarrow;
2043 }
2044
2045 /**
2046 * Accessibility: Right arrow-like character is
2047 * used in the breadcrumb trail, course navigation menu
2048 * (previous/next activity), calendar, and search forum block.
2049 * If the theme does not set characters, appropriate defaults
2050 * are set automatically. Please DO NOT
2051 * use &lt; &gt; &raquo; - these are confusing for blind users.
2052 * @return string
2053 */
2054 public function larrow() {
2055 return $this->page->theme->larrow;
2056 }
088ccb43
PS
2057
2058 /**
2059 * Returns the colours of the small MP3 player
2060 * @return string
2061 */
2062 public function filter_mediaplugin_colors() {
2063 return $this->page->theme->filter_mediaplugin_colors;
2064 }
2065
2066 /**
2067 * Returns the colours of the big MP3 player
2068 * @return string
2069 */
2070 public function resource_mp3player_colors() {
2071 return $this->page->theme->resource_mp3player_colors;
2072 }
78946b9b 2073}
d9c8f425 2074
2075
2076/// RENDERERS
2077
2078/**
2079 * A renderer that generates output for command-line scripts.
2080 *
2081 * The implementation of this renderer is probably incomplete.
2082 *
2083 * @copyright 2009 Tim Hunt
2084 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2085 * @since Moodle 2.0
2086 */
56cbc53b 2087class core_renderer_cli extends core_renderer {
d9c8f425 2088 /**
2089 * Returns the page header.
2090 * @return string HTML fragment
2091 */
2092 public function header() {
2093 output_starting_hook();
2094 return $this->page->heading . "\n";
2095 }
2096
2097 /**
2098 * Returns a template fragment representing a Heading.
2099 * @param string $text The text of the heading
2100 * @param int $level The level of importance of the heading
2101 * @param string $classes A space-separated list of CSS classes
2102 * @param string $id An optional ID
2103 * @return string A template fragment for a heading
2104 */
0fddc031 2105 public function heading($text, $level = 2, $classes = 'main', $id = null) {
d9c8f425 2106 $text .= "\n";
2107 switch ($level) {
2108 case 1:
2109 return '=>' . $text;
2110 case 2:
2111 return '-->' . $text;
2112 default:
2113 return $text;
2114 }
2115 }
2116
2117 /**
2118 * Returns a template fragment representing a fatal error.
2119 * @param string $message The message to output
2120 * @param string $moreinfourl URL where more info can be found about the error
2121 * @param string $link Link for the Continue button
2122 * @param array $backtrace The execution backtrace
2123 * @param string $debuginfo Debugging information
d9c8f425 2124 * @return string A template fragment for a fatal error
2125 */
83267ec0 2126 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
d9c8f425 2127 $output = "!!! $message !!!\n";
2128
2129 if (debugging('', DEBUG_DEVELOPER)) {
2130 if (!empty($debuginfo)) {
2131 $this->notification($debuginfo, 'notifytiny');
2132 }
2133 if (!empty($backtrace)) {
2134 $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2135 }
2136 }
2137 }
2138
2139 /**
2140 * Returns a template fragment representing a notification.
2141 * @param string $message The message to include
2142 * @param string $classes A space-separated list of CSS classes
2143 * @return string A template fragment for a notification
2144 */
2145 public function notification($message, $classes = 'notifyproblem') {
2146 $message = clean_text($message);
2147 if ($classes === 'notifysuccess') {
2148 return "++ $message ++\n";
2149 }
2150 return "!! $message !!\n";
2151 }
2152}
2153
1adaa404
PS
2154
2155/**
2156 * A renderer that generates output for ajax scripts.
2157 *
2158 * This renderer prevents accidental sends back only json
2159 * encoded error messages, all other output is ignored.
2160 *
2161 * @copyright 2010 Petr Skoda
2162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2163 * @since Moodle 2.0
2164 */
2165class core_renderer_ajax extends core_renderer {
2166 /**
2167 * Returns a template fragment representing a fatal error.
2168 * @param string $message The message to output
2169 * @param string $moreinfourl URL where more info can be found about the error
2170 * @param string $link Link for the Continue button
2171 * @param array $backtrace The execution backtrace
2172 * @param string $debuginfo Debugging information
2173 * @return string A template fragment for a fatal error
2174 */
2175 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2176 $e = new stdClass();
2177 $e->error = $message;
2178 $e->stacktrace = NULL;
2179 $e->debuginfo = NULL;
2180 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2181 if (!empty($debuginfo)) {
2182 $e->debuginfo = $debuginfo;
2183 }
2184 if (!empty($backtrace)) {
2185 $e->stacktrace = format_backtrace($backtrace, true);
2186 }
2187 }
2188 return json_encode($e);
2189 }
2190
2191 public function notification($message, $classes = 'notifyproblem') {
2192 }
2193 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2194 }
2195 public function header() {
2196 }
2197 public function footer() {
2198 }
0fddc031 2199 public function heading($text, $level = 2, $classes = 'main', $id = null) {
1adaa404
PS
2200 }
2201}
2202