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