backup MDL-23362 committing restore_gradebook_step including a test for whether the...
[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);
e884f63a 402 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&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 420 }
b3df1764 421 if (isguestuser()) {
244a32c6 422 $loggedinas = $realuserinfo.get_string('loggedinasguest').
4aea3cc7 423 " (<a href=\"$loginurl\">".get_string('login').'</a>)';
f5c1e621 424 } else if (is_role_switched($course->id)) { // Has switched roles
244a32c6
PS
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)) {
b3df1764 445 if (!isguestuser()) {
244a32c6
PS
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
e884f63a
PS
571 if (session_is_loggedinas()) {
572 $this->page->add_body_class('userloggedinas');
573 }
574
d9c8f425 575 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
576
78946b9b
PS
577 // Find the appropriate page layout file, based on $this->page->pagelayout.
578 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
579 // Render the layout using the layout file.
580 $rendered = $this->render_page_layout($layoutfile);
67e84a7f 581
78946b9b
PS
582 // Slice the rendered output into header and footer.
583 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
d9c8f425 584 if ($cutpos === false) {
78946b9b 585 throw new coding_exception('page layout file ' . $layoutfile .
d9c8f425 586 ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
587 }
78946b9b
PS
588 $header = substr($rendered, 0, $cutpos);
589 $footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
d9c8f425 590
591 if (empty($this->contenttype)) {
78946b9b 592 debugging('The page layout file did not call $OUTPUT->doctype()');
67e84a7f 593 $header = $this->doctype() . $header;
d9c8f425 594 }
595
596 send_headers($this->contenttype, $this->page->cacheable);
67e84a7f 597
d9c8f425 598 $this->opencontainers->push('header/footer', $footer);
599 $this->page->set_state(moodle_page::STATE_IN_BODY);
67e84a7f 600
29ba64e5 601 return $header . $this->skip_link_target('maincontent');
d9c8f425 602 }
603
604 /**
78946b9b
PS
605 * Renders and outputs the page layout file.
606 * @param string $layoutfile The name of the layout file
d9c8f425 607 * @return string HTML code
608 */
78946b9b 609 protected function render_page_layout($layoutfile) {
92e01ab7 610 global $CFG, $SITE, $USER;
d9c8f425 611 // The next lines are a bit tricky. The point is, here we are in a method
612 // of a renderer class, and this object may, or may not, be the same as
78946b9b 613 // the global $OUTPUT object. When rendering the page layout file, we want to use
d9c8f425 614 // this object. However, people writing Moodle code expect the current
615 // renderer to be called $OUTPUT, not $this, so define a variable called
616 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
617 $OUTPUT = $this;
618 $PAGE = $this->page;
619 $COURSE = $this->page->course;
620
d9c8f425 621 ob_start();
78946b9b
PS
622 include($layoutfile);
623 $rendered = ob_get_contents();
d9c8f425 624 ob_end_clean();
78946b9b 625 return $rendered;
d9c8f425 626 }
627
628 /**
629 * Outputs the page's footer
630 * @return string HTML fragment
631 */
632 public function footer() {
d5a8d9aa 633 global $CFG, $DB;
0f0801f4 634
f6794ace 635 $output = $this->container_end_all(true);
4d2ee4c2 636
d9c8f425 637 $footer = $this->opencontainers->pop('header/footer');
638
d5a8d9aa 639 if (debugging() and $DB and $DB->is_transaction_started()) {
03221650 640 // TODO: MDL-20625 print warning - transaction will be rolled back
d5a8d9aa
PS
641 }
642
d9c8f425 643 // Provide some performance info if required
644 $performanceinfo = '';
645 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
646 $perf = get_performance_info();
647 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
648 error_log("PERF: " . $perf['txt']);
649 }
650 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
651 $performanceinfo = $perf['html'];
652 }
653 }
654 $footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
655
656 $footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
657
658 $this->page->set_state(moodle_page::STATE_DONE);
d9c8f425 659
660 return $output . $footer;
661 }
662
f6794ace
PS
663 /**
664 * Close all but the last open container. This is useful in places like error
665 * handling, where you want to close all the open containers (apart from <body>)
666 * before outputting the error message.
667 * @param bool $shouldbenone assert that the stack should be empty now - causes a
668 * developer debug warning if it isn't.
669 * @return string the HTML required to close any open containers inside <body>.
670 */
671 public function container_end_all($shouldbenone = false) {
672 return $this->opencontainers->pop_all_but_last($shouldbenone);
673 }
674
244a32c6
PS
675 /**
676 * Returns lang menu or '', this method also checks forcing of languages in courses.
677 * @return string
678 */
679 public function lang_menu() {
680 global $CFG;
681
682 if (empty($CFG->langmenu)) {
683 return '';
684 }
685
686 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
687 // do not show lang menu if language forced
688 return '';
689 }
690
691 $currlang = current_language();
1f96e907 692 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 693
244a32c6
PS
694 if (count($langs) < 2) {
695 return '';
696 }
697
a9967cf5
PS
698 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
699 $s->label = get_accesshide(get_string('language'));
700 $s->class = 'langmenu';
701 return $this->render($s);
244a32c6
PS
702 }
703
d9c8f425 704 /**
705 * Output the row of editing icons for a block, as defined by the controls array.
706 * @param array $controls an array like {@link block_contents::$controls}.
707 * @return HTML fragment.
708 */
709 public function block_controls($controls) {
710 if (empty($controls)) {
711 return '';
712 }
713 $controlshtml = array();
714 foreach ($controls as $control) {
f4ed6fc4 715 $controlshtml[] = html_writer::tag('a',
26acc814 716 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
f4ed6fc4 717 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
d9c8f425 718 }
26acc814 719 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
d9c8f425 720 }
721
722 /**
723 * Prints a nice side block with an optional header.
724 *
725 * The content is described
726 * by a {@link block_contents} object.
727 *
cbb54cce
SH
728 * <div id="inst{$instanceid}" class="block_{$blockname} block">
729 * <div class="header"></div>
730 * <div class="content">
731 * ...CONTENT...
732 * <div class="footer">
733 * </div>
734 * </div>
735 * <div class="annotation">
736 * </div>
737 * </div>
738 *
d9c8f425 739 * @param block_contents $bc HTML for the content
740 * @param string $region the region the block is appearing in.
741 * @return string the HTML to be output.
742 */
dd72b308 743 function block(block_contents $bc, $region) {
d9c8f425 744 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
745 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
746 $bc->collapsible = block_contents::NOT_HIDEABLE;
747 }
748 if ($bc->collapsible == block_contents::HIDDEN) {
749 $bc->add_class('hidden');
750 }
751 if (!empty($bc->controls)) {
752 $bc->add_class('block_with_controls');
753 }
d9c8f425 754
755 $skiptitle = strip_tags($bc->title);
756 if (empty($skiptitle)) {
757 $output = '';
758 $skipdest = '';
759 } else {
26acc814
PS
760 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
761 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
d9c8f425 762 }
4d2ee4c2 763
5d0c95a5 764 $output .= html_writer::start_tag('div', $bc->attributes);
d9c8f425 765
766 $controlshtml = $this->block_controls($bc->controls);
767
768 $title = '';
769 if ($bc->title) {
26acc814 770 $title = html_writer::tag('h2', $bc->title, null);
d9c8f425 771 }
772
773 if ($title || $controlshtml) {
46de77b6 774 $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 775 }
776
5d0c95a5 777 $output .= html_writer::start_tag('div', array('class' => 'content'));
46de77b6
SH
778 if (!$title && !$controlshtml) {
779 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
780 }
d9c8f425 781 $output .= $bc->content;
782
783 if ($bc->footer) {
26acc814 784 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
d9c8f425 785 }
786
5d0c95a5
PS
787 $output .= html_writer::end_tag('div');
788 $output .= html_writer::end_tag('div');
d9c8f425 789
790 if ($bc->annotation) {
26acc814 791 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
d9c8f425 792 }
793 $output .= $skipdest;
794
795 $this->init_block_hider_js($bc);
796 return $output;
797 }
798
799 /**
800 * Calls the JS require function to hide a block.
801 * @param block_contents $bc A block_contents object
802 * @return void
803 */
dd72b308
PS
804 protected function init_block_hider_js(block_contents $bc) {
805 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
cbb54cce
SH
806 $config = new stdClass;
807 $config->id = $bc->attributes['id'];
808 $config->title = strip_tags($bc->title);
809 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
810 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
811 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
812
813 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
814 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
d9c8f425 815 }
816 }
817
818 /**
819 * Render the contents of a block_list.
820 * @param array $icons the icon for each item.
821 * @param array $items the content of each item.
822 * @return string HTML
823 */
824 public function list_block_contents($icons, $items) {
825 $row = 0;
826 $lis = array();
827 foreach ($items as $key => $string) {
5d0c95a5 828 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 829 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 830 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 831 }
26acc814 832 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 833 $item .= html_writer::end_tag('li');
d9c8f425 834 $lis[] = $item;
835 $row = 1 - $row; // Flip even/odd.
836 }
26acc814 837 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'list'));
d9c8f425 838 }
839
840 /**
841 * Output all the blocks in a particular region.
842 * @param string $region the name of a region on this page.
843 * @return string the HTML to be output.
844 */
845 public function blocks_for_region($region) {
846 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
847
848 $output = '';
849 foreach ($blockcontents as $bc) {
850 if ($bc instanceof block_contents) {
851 $output .= $this->block($bc, $region);
852 } else if ($bc instanceof block_move_target) {
853 $output .= $this->block_move_target($bc);
854 } else {
855 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
856 }
857 }
858 return $output;
859 }
860
861 /**
862 * Output a place where the block that is currently being moved can be dropped.
863 * @param block_move_target $target with the necessary details.
864 * @return string the HTML to be output.
865 */
866 public function block_move_target($target) {
6ee744b3 867 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 868 }
869
574fbea4 870 /**
996b1e0c 871 * Renders a special html link with attached action
574fbea4
PS
872 *
873 * @param string|moodle_url $url
874 * @param string $text HTML fragment
875 * @param component_action $action
11820bac 876 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
877 * @return HTML fragment
878 */
c63923bd 879 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
574fbea4
PS
880 if (!($url instanceof moodle_url)) {
881 $url = new moodle_url($url);
882 }
883 $link = new action_link($url, $text, $action, $attributes);
884
f14b641b 885 return $this->render($link);
574fbea4
PS
886 }
887
888 /**
889 * Implementation of action_link rendering
890 * @param action_link $link
891 * @return string HTML fragment
892 */
893 protected function render_action_link(action_link $link) {
894 global $CFG;
895
896 // A disabled link is rendered as formatted text
897 if (!empty($link->attributes['disabled'])) {
898 // do not use div here due to nesting restriction in xhtml strict
899 return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
900 }
11820bac 901
574fbea4
PS
902 $attributes = $link->attributes;
903 unset($link->attributes['disabled']);
904 $attributes['href'] = $link->url;
905
906 if ($link->actions) {
f14b641b 907 if (empty($attributes['id'])) {
574fbea4
PS
908 $id = html_writer::random_id('action_link');
909 $attributes['id'] = $id;
910 } else {
911 $id = $attributes['id'];
912 }
913 foreach ($link->actions as $action) {
c80877aa 914 $this->add_action_handler($action, $id);
574fbea4
PS
915 }
916 }
917
26acc814 918 return html_writer::tag('a', $link->text, $attributes);
574fbea4
PS
919 }
920
c63923bd
PS
921
922 /**
923 * Similar to action_link, image is used instead of the text
924 *
925 * @param string|moodle_url $url A string URL or moodel_url
926 * @param pix_icon $pixicon
927 * @param component_action $action
928 * @param array $attributes associative array of html link attributes + disabled
929 * @param bool $linktext show title next to image in link
930 * @return string HTML fragment
931 */
932 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
933 if (!($url instanceof moodle_url)) {
934 $url = new moodle_url($url);
935 }
936 $attributes = (array)$attributes;
937
524645e7 938 if (empty($attributes['class'])) {
c63923bd
PS
939 // let ppl override the class via $options
940 $attributes['class'] = 'action-icon';
941 }
942
943 $icon = $this->render($pixicon);
944
945 if ($linktext) {
946 $text = $pixicon->attributes['alt'];
947 } else {
948 $text = '';
949 }
950
951 return $this->action_link($url, $text.$icon, $action, $attributes);
952 }
953
d9c8f425 954 /**
0b634d75 955 * Print a message along with button choices for Continue/Cancel
956 *
4ed85790 957 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 958 *
d9c8f425 959 * @param string $message The question to ask the user
3ba60ee1
PS
960 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
961 * @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 962 * @return string HTML fragment
963 */
964 public function confirm($message, $continue, $cancel) {
4871a238 965 if ($continue instanceof single_button) {
11820bac 966 // ok
4871a238
PS
967 } else if (is_string($continue)) {
968 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
969 } else if ($continue instanceof moodle_url) {
26eab8d4 970 $continue = new single_button($continue, get_string('continue'), 'post');
d9c8f425 971 } else {
4ed85790 972 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 973 }
974
4871a238 975 if ($cancel instanceof single_button) {
11820bac 976 // ok
4871a238
PS
977 } else if (is_string($cancel)) {
978 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
979 } else if ($cancel instanceof moodle_url) {
26eab8d4 980 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 981 } else {
4ed85790 982 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 983 }
984
d9c8f425 985 $output = $this->box_start('generalbox', 'notice');
26acc814
PS
986 $output .= html_writer::tag('p', $message);
987 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 988 $output .= $this->box_end();
989 return $output;
990 }
991
3cd5305f 992 /**
3ba60ee1 993 * Returns a form with a single button.
3cd5305f 994 *
3ba60ee1 995 * @param string|moodle_url $url
3cd5305f
PS
996 * @param string $label button text
997 * @param string $method get or post submit method
3ba60ee1 998 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
999 * @return string HTML fragment
1000 */
3ba60ee1 1001 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
1002 if (!($url instanceof moodle_url)) {
1003 $url = new moodle_url($url);
3ba60ee1 1004 }
574fbea4
PS
1005 $button = new single_button($url, $label, $method);
1006
3ba60ee1
PS
1007 foreach ((array)$options as $key=>$value) {
1008 if (array_key_exists($key, $button)) {
1009 $button->$key = $value;
1010 }
3cd5305f
PS
1011 }
1012
3ba60ee1 1013 return $this->render($button);
3cd5305f
PS
1014 }
1015
d9c8f425 1016 /**
3ba60ee1
PS
1017 * Internal implementation of single_button rendering
1018 * @param single_button $button
d9c8f425 1019 * @return string HTML fragment
1020 */
3ba60ee1
PS
1021 protected function render_single_button(single_button $button) {
1022 $attributes = array('type' => 'submit',
1023 'value' => $button->label,
db09524d 1024 'disabled' => $button->disabled ? 'disabled' : null,
3ba60ee1
PS
1025 'title' => $button->tooltip);
1026
1027 if ($button->actions) {
1028 $id = html_writer::random_id('single_button');
1029 $attributes['id'] = $id;
1030 foreach ($button->actions as $action) {
c80877aa 1031 $this->add_action_handler($action, $id);
3ba60ee1 1032 }
d9c8f425 1033 }
d9c8f425 1034
3ba60ee1
PS
1035 // first the input element
1036 $output = html_writer::empty_tag('input', $attributes);
d9c8f425 1037
3ba60ee1
PS
1038 // then hidden fields
1039 $params = $button->url->params();
1040 if ($button->method === 'post') {
1041 $params['sesskey'] = sesskey();
1042 }
1043 foreach ($params as $var => $val) {
1044 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1045 }
d9c8f425 1046
3ba60ee1 1047 // then div wrapper for xhtml strictness
26acc814 1048 $output = html_writer::tag('div', $output);
d9c8f425 1049
3ba60ee1 1050 // now the form itself around it
eb788065 1051 $url = $button->url->out_omit_querystring(); // url without params
a6855934
PS
1052 if ($url === '') {
1053 $url = '#'; // there has to be always some action
1054 }
3ba60ee1 1055 $attributes = array('method' => $button->method,
a6855934 1056 'action' => $url,
3ba60ee1 1057 'id' => $button->formid);
26acc814 1058 $output = html_writer::tag('form', $output, $attributes);
d9c8f425 1059
3ba60ee1 1060 // and finally one more wrapper with class
26acc814 1061 return html_writer::tag('div', $output, array('class' => $button->class));
d9c8f425 1062 }
1063
a9967cf5 1064 /**
ab08be98 1065 * Returns a form with a single select widget.
a9967cf5
PS
1066 * @param moodle_url $url form action target, includes hidden fields
1067 * @param string $name name of selection field - the changing parameter in url
1068 * @param array $options list of options
1069 * @param string $selected selected element
1070 * @param array $nothing
f8dab966 1071 * @param string $formid
a9967cf5
PS
1072 * @return string HTML fragment
1073 */
f8dab966 1074 public function single_select($url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
a9967cf5
PS
1075 if (!($url instanceof moodle_url)) {
1076 $url = new moodle_url($url);
1077 }
f8dab966 1078 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5
PS
1079
1080 return $this->render($select);
1081 }
1082
1083 /**
1084 * Internal implementation of single_select rendering
1085 * @param single_select $select
1086 * @return string HTML fragment
1087 */
1088 protected function render_single_select(single_select $select) {
1089 $select = clone($select);
1090 if (empty($select->formid)) {
1091 $select->formid = html_writer::random_id('single_select_f');
1092 }
1093
1094 $output = '';
1095 $params = $select->url->params();
1096 if ($select->method === 'post') {
1097 $params['sesskey'] = sesskey();
1098 }
1099 foreach ($params as $name=>$value) {
1100 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1101 }
1102
1103 if (empty($select->attributes['id'])) {
1104 $select->attributes['id'] = html_writer::random_id('single_select');
1105 }
1106
0b2cb132
PS
1107 if ($select->disabled) {
1108 $select->attributes['disabled'] = 'disabled';
1109 }
4d10e579 1110
a9967cf5
PS
1111 if ($select->tooltip) {
1112 $select->attributes['title'] = $select->tooltip;
1113 }
1114
1115 if ($select->label) {
995f2d51 1116 $output .= html_writer::label($select->label, $select->attributes['id']);
a9967cf5
PS
1117 }
1118
1119 if ($select->helpicon instanceof help_icon) {
1120 $output .= $this->render($select->helpicon);
259c165d
PS
1121 } else if ($select->helpicon instanceof old_help_icon) {
1122 $output .= $this->render($select->helpicon);
a9967cf5
PS
1123 }
1124
1125 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1126
1127 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
26acc814 1128 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
a9967cf5
PS
1129
1130 $nothing = empty($select->nothing) ? false : key($select->nothing);
edc28287 1131 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
a9967cf5
PS
1132
1133 // then div wrapper for xhtml strictness
26acc814 1134 $output = html_writer::tag('div', $output);
a9967cf5
PS
1135
1136 // now the form itself around it
1137 $formattributes = array('method' => $select->method,
1138 'action' => $select->url->out_omit_querystring(),
1139 'id' => $select->formid);
26acc814 1140 $output = html_writer::tag('form', $output, $formattributes);
4d10e579
PS
1141
1142 // and finally one more wrapper with class
26acc814 1143 return html_writer::tag('div', $output, array('class' => $select->class));
4d10e579
PS
1144 }
1145
1146 /**
ab08be98 1147 * Returns a form with a url select widget.
4d10e579
PS
1148 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1149 * @param string $selected selected element
1150 * @param array $nothing
1151 * @param string $formid
1152 * @return string HTML fragment
1153 */
1154 public function url_select(array $urls, $selected, $nothing=array(''=>'choosedots'), $formid=null) {
1155 $select = new url_select($urls, $selected, $nothing, $formid);
1156 return $this->render($select);
1157 }
1158
1159 /**
ab08be98 1160 * Internal implementation of url_select rendering
4d10e579
PS
1161 * @param single_select $select
1162 * @return string HTML fragment
1163 */
1164 protected function render_url_select(url_select $select) {
c422efcf
PS
1165 global $CFG;
1166
4d10e579
PS
1167 $select = clone($select);
1168 if (empty($select->formid)) {
1169 $select->formid = html_writer::random_id('url_select_f');
1170 }
1171
1172 if (empty($select->attributes['id'])) {
1173 $select->attributes['id'] = html_writer::random_id('url_select');
1174 }
1175
1176 if ($select->disabled) {
1177 $select->attributes['disabled'] = 'disabled';
1178 }
1179
1180 if ($select->tooltip) {
1181 $select->attributes['title'] = $select->tooltip;
1182 }
1183
1184 $output = '';
1185
1186 if ($select->label) {
995f2d51 1187 $output .= html_writer::label($select->label, $select->attributes['id']);
4d10e579
PS
1188 }
1189
1190 if ($select->helpicon instanceof help_icon) {
1191 $output .= $this->render($select->helpicon);
259c165d
PS
1192 } else if ($select->helpicon instanceof old_help_icon) {
1193 $output .= $this->render($select->helpicon);
4d10e579
PS
1194 }
1195
d4dcfc6b
DM
1196 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1197 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
c422efcf
PS
1198 $urls = array();
1199 foreach ($select->urls as $k=>$v) {
d4dcfc6b
DM
1200 if (is_array($v)) {
1201 // optgroup structure
1202 foreach ($v as $optgrouptitle => $optgroupoptions) {
1203 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1204 if (empty($optionurl)) {
1205 $safeoptionurl = '';
1206 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1207 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1208 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1209 } else if (strpos($optionurl, '/') !== 0) {
1210 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1211 continue;
1212 } else {
1213 $safeoptionurl = $optionurl;
1214 }
1215 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1216 }
1217 }
1218 } else {
1219 // plain list structure
1220 if (empty($k)) {
1221 // nothing selected option
1222 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1223 $k = str_replace($CFG->wwwroot, '', $k);
1224 } else if (strpos($k, '/') !== 0) {
1225 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1226 continue;
1227 }
1228 $urls[$k] = $v;
1229 }
1230 }
1231 $selected = $select->selected;
1232 if (!empty($selected)) {
1233 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1234 $selected = str_replace($CFG->wwwroot, '', $selected);
1235 } else if (strpos($selected, '/') !== 0) {
1236 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
c422efcf 1237 }
c422efcf
PS
1238 }
1239
4d10e579 1240 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
d4dcfc6b 1241 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
4d10e579
PS
1242
1243 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
26acc814 1244 $output .= html_writer::tag('noscript', $go, array('style'=>'inline'));
4d10e579
PS
1245
1246 $nothing = empty($select->nothing) ? false : key($select->nothing);
1247 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1248
1249 // then div wrapper for xhtml strictness
26acc814 1250 $output = html_writer::tag('div', $output);
4d10e579
PS
1251
1252 // now the form itself around it
1253 $formattributes = array('method' => 'post',
1254 'action' => new moodle_url('/course/jumpto.php'),
1255 'id' => $select->formid);
26acc814 1256 $output = html_writer::tag('form', $output, $formattributes);
a9967cf5
PS
1257
1258 // and finally one more wrapper with class
26acc814 1259 return html_writer::tag('div', $output, array('class' => $select->class));
a9967cf5
PS
1260 }
1261
d9c8f425 1262 /**
1263 * Returns a string containing a link to the user documentation.
1264 * Also contains an icon by default. Shown to teachers and admin only.
1265 * @param string $path The page link after doc root and language, no leading slash.
1266 * @param string $text The text to be displayed for the link
996b1e0c 1267 * @return string
d9c8f425 1268 */
8ae8bf8a
PS
1269 public function doc_link($path, $text) {
1270 global $CFG;
1271
000c278c 1272 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
8ae8bf8a 1273
000c278c 1274 $url = new moodle_url(get_docs_url($path));
8ae8bf8a 1275
c80877aa 1276 $attributes = array('href'=>$url);
d9c8f425 1277 if (!empty($CFG->doctonewwindow)) {
c80877aa 1278 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
d9c8f425 1279 }
1adaa404 1280
26acc814 1281 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 1282 }
1283
000c278c
PS
1284 /**
1285 * Render icon
1286 * @param string $pix short pix name
1287 * @param string $alt mandatory alt attribute
1288 * @param strin $component standard compoennt name like 'moodle', 'mod_form', etc.
1289 * @param array $attributes htm lattributes
1290 * @return string HTML fragment
1291 */
1292 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1293 $icon = new pix_icon($pix, $alt, $component, $attributes);
1294 return $this->render($icon);
1295 }
1296
1297 /**
1298 * Render icon
1299 * @param pix_icon $icon
1300 * @return string HTML fragment
1301 */
ce0110bf 1302 protected function render_pix_icon(pix_icon $icon) {
000c278c
PS
1303 $attributes = $icon->attributes;
1304 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
c80877aa 1305 return html_writer::empty_tag('img', $attributes);
000c278c
PS
1306 }
1307
a09aeee4
AD
1308 /**
1309 * Produces the html that represents this rating in the UI
1310 * @param $page the page object on which this rating will appear
1311 */
1312 function render_rating(rating $rating) {
7ac928a7 1313 global $CFG, $USER;
a09aeee4
AD
1314 static $havesetupjavascript = false;
1315
63e87951
AD
1316 if( $rating->settings->aggregationmethod == RATING_AGGREGATE_NONE ){
1317 return null;//ratings are turned off
1318 }
1319
b1721f67
AD
1320 $useajax = !empty($CFG->enableajax);
1321
1322 //include required Javascript
1323 if( !$havesetupjavascript && $useajax ) {
3dcdf440 1324 $this->page->requires->js_init_call('M.core_rating.init');
a09aeee4
AD
1325 $havesetupjavascript = true;
1326 }
1327
63e87951
AD
1328 //check the item we're rating was created in the assessable time window
1329 $inassessablewindow = true;
1330 if ( $rating->settings->assesstimestart && $rating->settings->assesstimefinish ) {
55d95d90 1331 if ($rating->itemtimecreated < $rating->settings->assesstimestart || $rating->itemtimecreated > $rating->settings->assesstimefinish) {
63e87951 1332 $inassessablewindow = false;
a09aeee4 1333 }
63e87951 1334 }
a09aeee4 1335
63e87951
AD
1336 $strrate = get_string("rate", "rating");
1337 $ratinghtml = ''; //the string we'll return
1338
d251b259 1339 //permissions check - can they view the aggregate?
66c34e9c 1340 $canviewaggregate = false;
d251b259 1341
66c34e9c
AD
1342 //if its the current user's item and they have permission to view the aggregate on their own items
1343 if ( $rating->itemuserid==$USER->id && $rating->settings->permissions->view && $rating->settings->pluginpermissions->view) {
1344 $canviewaggregate = true;
1345 }
1346
1347 //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
1348 //Note that viewany doesnt mean you can see the aggregate or ratings of your own items
1349 if ( (empty($rating->itemuserid) or $rating->itemuserid!=$USER->id) && $rating->settings->permissions->viewany && $rating->settings->pluginpermissions->viewany ) {
1350 $canviewaggregate = true;
1351 }
1352
1353 if ($canviewaggregate==true) {
d251b259
AD
1354 $aggregatelabel = '';
1355 switch ($rating->settings->aggregationmethod) {
1356 case RATING_AGGREGATE_AVERAGE :
1357 $aggregatelabel .= get_string("aggregateavg", "forum");
1358 break;
1359 case RATING_AGGREGATE_COUNT :
1360 $aggregatelabel .= get_string("aggregatecount", "forum");
1361 break;
1362 case RATING_AGGREGATE_MAXIMUM :
1363 $aggregatelabel .= get_string("aggregatemax", "forum");
1364 break;
1365 case RATING_AGGREGATE_MINIMUM :
1366 $aggregatelabel .= get_string("aggregatemin", "forum");
1367 break;
1368 case RATING_AGGREGATE_SUM :
1369 $aggregatelabel .= get_string("aggregatesum", "forum");
1370 break;
1371 }
a09aeee4 1372
d251b259
AD
1373 //$scalemax = 0;//no longer displaying scale max
1374 $aggregatestr = '';
a09aeee4 1375
50e7d9da
AD
1376 //only display aggregate if aggregation method isn't COUNT
1377 if ($rating->aggregate && $rating->settings->aggregationmethod!= RATING_AGGREGATE_COUNT) {
1378 if ($rating->settings->aggregationmethod!= RATING_AGGREGATE_SUM && is_array($rating->settings->scale->scaleitems)) {
d251b259 1379 $aggregatestr .= $rating->settings->scale->scaleitems[round($rating->aggregate)];//round aggregate as we're using it as an index
63e87951 1380 }
50e7d9da 1381 else { //aggregation is SUM or the scale is numeric
d251b259 1382 $aggregatestr .= round($rating->aggregate,1);
63e87951 1383 }
d251b259
AD
1384 } else {
1385 $aggregatestr = ' - ';
1386 }
1387
771b3fbe 1388 $countstr = html_writer::start_tag('span', array('id'=>"ratingcount{$rating->itemid}"));
d251b259 1389 if ($rating->count>0) {
771b3fbe 1390 $countstr .= "({$rating->count})";
d251b259 1391 }
771b3fbe 1392 $countstr .= html_writer::end_tag('span');
63e87951 1393
d251b259
AD
1394 //$aggregatehtml = "{$ratingstr} / $scalemax ({$rating->count}) ";
1395 $aggregatehtml = "<span id='ratingaggregate{$rating->itemid}'>{$aggregatestr}</span> $countstr ";
63e87951 1396
d251b259
AD
1397 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1398 $url = "/rating/index.php?contextid={$rating->context->id}&itemid={$rating->itemid}&scaleid={$rating->settings->scale->id}";
1399 $nonpopuplink = new moodle_url($url);
1400 $popuplink = new moodle_url("$url&popup=1");
a09aeee4 1401
d251b259 1402 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
995f2d51 1403 $ratinghtml .= $aggregatelabel.get_string('labelsep', 'langconfig').$this->action_link($nonpopuplink, $aggregatehtml, $action);
d251b259 1404 } else {
995f2d51 1405 $ratinghtml .= $aggregatelabel.get_string('labelsep', 'langconfig').$aggregatehtml;
a09aeee4 1406 }
d251b259 1407 }
a09aeee4 1408
d251b259 1409 $formstart = null;
71c03ac1 1410 //if the item doesn't belong to the current user, the user has permission to rate
d251b259
AD
1411 //and we're within the assessable period
1412 if ($rating->itemuserid!=$USER->id
1413 && $rating->settings->permissions->rate
1414 && $rating->settings->pluginpermissions->rate
1415 && $inassessablewindow) {
4d2ee4c2 1416
771b3fbe
AD
1417 //start the rating form
1418 $formstart = html_writer::start_tag('form',
1419 array('id'=>"postrating{$rating->itemid}", 'class'=>'postratingform', 'method'=>'post', 'action'=>"{$CFG->wwwroot}/rating/rate.php"));
1420
1421 $formstart .= html_writer::start_tag('div', array('class'=>'ratingform'));
1422
1423 //add the hidden inputs
1424
1425 $attributes = array('type'=>'hidden', 'class'=>'ratinginput', 'name'=>'contextid', 'value'=>$rating->context->id);
1426 $formstart .= html_writer::empty_tag('input', $attributes);
1427
1428 $attributes['name'] = 'itemid';
1429 $attributes['value'] = $rating->itemid;
1430 $formstart .= html_writer::empty_tag('input', $attributes);
1431
1432 $attributes['name'] = 'scaleid';
1433 $attributes['value'] = $rating->settings->scale->id;
1434 $formstart .= html_writer::empty_tag('input', $attributes);
1435
1436 $attributes['name'] = 'returnurl';
1437 $attributes['value'] = $rating->settings->returnurl;
1438 $formstart .= html_writer::empty_tag('input', $attributes);
1439
1440 $attributes['name'] = 'rateduserid';
1441 $attributes['value'] = $rating->itemuserid;
1442 $formstart .= html_writer::empty_tag('input', $attributes);
1443
1444 $attributes['name'] = 'aggregation';
1445 $attributes['value'] = $rating->settings->aggregationmethod;
1446 $formstart .= html_writer::empty_tag('input', $attributes);
1447
3180bc2c
AD
1448 $attributes['name'] = 'sesskey';
1449 $attributes['value'] = sesskey();;
1450 $formstart .= html_writer::empty_tag('input', $attributes);
1451
d251b259
AD
1452 if (empty($ratinghtml)) {
1453 $ratinghtml .= $strrate.': ';
1454 }
63e87951 1455
d251b259 1456 $ratinghtml = $formstart.$ratinghtml;
63e87951 1457
d251b259
AD
1458 //generate an array of values for numeric scales
1459 $scalearray = $rating->settings->scale->scaleitems;
1460 if (!is_array($scalearray)) { //almost certainly a numerical scale
996b1e0c 1461 $intscalearray = intval($scalearray);//just in case they've passed "5" instead of 5
9f60f914
AD
1462 $scalearray = array();
1463 if( is_int($intscalearray) && $intscalearray>0 ) {
d251b259
AD
1464 for($i=0; $i<=$rating->settings->scale->scaleitems; $i++) {
1465 $scalearray[$i] = $i;
6c5fcef7 1466 }
a09aeee4 1467 }
d251b259 1468 }
6c5fcef7 1469
d251b259
AD
1470 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $scalearray;
1471 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid));
a09aeee4 1472
d251b259 1473 //output submit button
4d2ee4c2 1474
771b3fbe
AD
1475 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1476
1477 $attributes = array('type'=>'submit', 'class'=>'postratingmenusubmit', 'id'=>'postratingsubmit'.$rating->itemid, 'value'=>s(get_string('rate', 'rating')));
1478 $ratinghtml .= html_writer::empty_tag('input', $attributes);
a09aeee4 1479
d251b259
AD
1480 if (is_array($rating->settings->scale->scaleitems)) {
1481 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
a09aeee4 1482 }
771b3fbe
AD
1483 $ratinghtml .= html_writer::end_tag('span');
1484 $ratinghtml .= html_writer::end_tag('div');
1485 $ratinghtml .= html_writer::end_tag('form');
a09aeee4
AD
1486 }
1487
63e87951 1488 return $ratinghtml;
a09aeee4
AD
1489 }
1490
d9c8f425 1491 /*
1492 * Centered heading with attached help button (same title text)
1493 * and optional icon attached
4bcc5118 1494 * @param string $text A heading text
53a78cef 1495 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
1496 * @param string $component component name
1497 * @param string|moodle_url $icon
1498 * @param string $iconalt icon alt text
d9c8f425 1499 * @return string HTML fragment
1500 */
53a78cef 1501 public function heading_with_help($text, $helpidentifier, $component='moodle', $icon='', $iconalt='') {
4bcc5118
PS
1502 $image = '';
1503 if ($icon) {
0029a917 1504 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
d9c8f425 1505 }
4bcc5118 1506
259c165d
PS
1507 $help = '';
1508 if ($helpidentifier) {
1509 $help = $this->help_icon($helpidentifier, $component);
1510 }
4bcc5118
PS
1511
1512 return $this->heading($image.$text.$help, 2, 'main help');
d9c8f425 1513 }
1514
1515 /**
1516 * Print a help icon.
1517 *
cb616be8 1518 * @deprecated since Moodle 2.0
4bcc5118 1519 * @param string $page The keyword that defines a help page
bf11293a 1520 * @param string $title A descriptive text for accessibility only
4bcc5118 1521 * @param string $component component name
bf11293a
PS
1522 * @param string|bool $linktext true means use $title as link text, string means link text value
1523 * @return string HTML fragment
1524 */
596509e4 1525 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
cb616be8 1526 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
596509e4 1527 $icon = new old_help_icon($helpidentifier, $title, $component);
bf11293a
PS
1528 if ($linktext === true) {
1529 $icon->linktext = $title;
1530 } else if (!empty($linktext)) {
1531 $icon->linktext = $linktext;
1532 }
1533 return $this->render($icon);
1534 }
4bcc5118 1535
bf11293a
PS
1536 /**
1537 * Implementation of user image rendering.
1538 * @param help_icon $helpicon
1539 * @return string HTML fragment
d9c8f425 1540 */
596509e4 1541 protected function render_old_help_icon(old_help_icon $helpicon) {
bf11293a 1542 global $CFG;
d9c8f425 1543
bf11293a
PS
1544 // first get the help image icon
1545 $src = $this->pix_url('help');
d9c8f425 1546
bf11293a
PS
1547 if (empty($helpicon->linktext)) {
1548 $alt = $helpicon->title;
1549 } else {
1550 $alt = get_string('helpwiththis');
1551 }
1552
1553 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1554 $output = html_writer::empty_tag('img', $attributes);
1555
1556 // add the link text if given
1557 if (!empty($helpicon->linktext)) {
1558 // the spacing has to be done through CSS
1559 $output .= $helpicon->linktext;
d9c8f425 1560 }
1561
53a78cef
PS
1562 // now create the link around it
1563 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
bf11293a
PS
1564
1565 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1566 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1567
1568 $attributes = array('href'=>$url, 'title'=>$title);
1569 $id = html_writer::random_id('helpicon');
1570 $attributes['id'] = $id;
26acc814 1571 $output = html_writer::tag('a', $output, $attributes);
8af8be4a
DM
1572
1573 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1574
bf11293a 1575 // and finally span
26acc814 1576 return html_writer::tag('span', $output, array('class' => 'helplink'));
d9c8f425 1577 }
1578
259c165d
PS
1579 /**
1580 * Print a help icon.
1581 *
1582 * @param string $identifier The keyword that defines a help page
1583 * @param string $component component name
1584 * @param string|bool $linktext true means use $title as link text, string means link text value
1585 * @return string HTML fragment
1586 */
1587 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2cf81209 1588 $icon = new help_icon($identifier, $component);
259c165d
PS
1589 $icon->diag_strings();
1590 if ($linktext === true) {
1591 $icon->linktext = get_string($icon->identifier, $icon->component);
1592 } else if (!empty($linktext)) {
1593 $icon->linktext = $linktext;
1594 }
1595 return $this->render($icon);
1596 }
1597
1598 /**
1599 * Implementation of user image rendering.
1600 * @param help_icon $helpicon
1601 * @return string HTML fragment
1602 */
1603 protected function render_help_icon(help_icon $helpicon) {
1604 global $CFG;
1605
1606 // first get the help image icon
1607 $src = $this->pix_url('help');
1608
1609 $title = get_string($helpicon->identifier, $helpicon->component);
1610
1611 if (empty($helpicon->linktext)) {
1612 $alt = $title;
1613 } else {
1614 $alt = get_string('helpwiththis');
1615 }
1616
1617 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1618 $output = html_writer::empty_tag('img', $attributes);
1619
1620 // add the link text if given
1621 if (!empty($helpicon->linktext)) {
1622 // the spacing has to be done through CSS
1623 $output .= $helpicon->linktext;
1624 }
1625
1626 // now create the link around it
1627 $url = new moodle_url('/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1628
1629 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1630 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1631
1632 $attributes = array('href'=>$url, 'title'=>$title);
1633 $id = html_writer::random_id('helpicon');
1634 $attributes['id'] = $id;
259c165d
PS
1635 $output = html_writer::tag('a', $output, $attributes);
1636
2cf81209
SH
1637 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1638
259c165d
PS
1639 // and finally span
1640 return html_writer::tag('span', $output, array('class' => 'helplink'));
1641 }
1642
d9c8f425 1643 /**
4bcc5118 1644 * Print scale help icon.
d9c8f425 1645 *
4bcc5118
PS
1646 * @param int $courseid
1647 * @param object $scale instance
1648 * @return string HTML fragment
d9c8f425 1649 */
4bcc5118
PS
1650 public function help_icon_scale($courseid, stdClass $scale) {
1651 global $CFG;
02f64f97 1652
4bcc5118 1653 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 1654
0029a917 1655 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 1656
57cd3739 1657 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scale->id));
230ec401 1658 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 1659
26acc814 1660 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 1661 }
1662
1663 /**
1664 * Creates and returns a spacer image with optional line break.
1665 *
0029a917
PS
1666 * @param array $attributes
1667 * @param boo spacer
d9c8f425 1668 * @return string HTML fragment
1669 */
0029a917
PS
1670 public function spacer(array $attributes = null, $br = false) {
1671 $attributes = (array)$attributes;
1672 if (empty($attributes['width'])) {
1673 $attributes['width'] = 1;
1ba862ec
PS
1674 }
1675 if (empty($options['height'])) {
0029a917 1676 $attributes['height'] = 1;
d9c8f425 1677 }
0029a917 1678 $attributes['class'] = 'spacer';
d9c8f425 1679
0029a917 1680 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 1681
0029a917 1682 if (!empty($br)) {
1ba862ec
PS
1683 $output .= '<br />';
1684 }
d9c8f425 1685
1686 return $output;
1687 }
1688
d9c8f425 1689 /**
1690 * Print the specified user's avatar.
1691 *
5d0c95a5 1692 * User avatar may be obtained in two ways:
d9c8f425 1693 * <pre>
812dbaf7
PS
1694 * // Option 1: (shortcut for simple cases, preferred way)
1695 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1696 * $OUTPUT->user_picture($user, array('popup'=>true));
1697 *
5d0c95a5
PS
1698 * // Option 2:
1699 * $userpic = new user_picture($user);
d9c8f425 1700 * // Set properties of $userpic
812dbaf7 1701 * $userpic->popup = true;
5d0c95a5 1702 * $OUTPUT->render($userpic);
d9c8f425 1703 * </pre>
1704 *
5d0c95a5 1705 * @param object Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 1706 * If any of these are missing, the database is queried. Avoid this
d9c8f425 1707 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
1708 * @param array $options associative array with user picture options, used only if not a user_picture object,
1709 * options are:
1710 * - courseid=$this->page->course->id (course id of user profile in link)
1711 * - size=35 (size of image)
1712 * - link=true (make image clickable - the link leads to user profile)
1713 * - popup=false (open in popup)
1714 * - alttext=true (add image alt attribute)
5d0c95a5 1715 * - class = image class attribute (default 'userpicture')
d9c8f425 1716 * @return string HTML fragment
1717 */
5d0c95a5
PS
1718 public function user_picture(stdClass $user, array $options = null) {
1719 $userpicture = new user_picture($user);
1720 foreach ((array)$options as $key=>$value) {
1721 if (array_key_exists($key, $userpicture)) {
1722 $userpicture->$key = $value;
1723 }
1724 }
1725 return $this->render($userpicture);
1726 }
1727
1728 /**
1729 * Internal implementation of user image rendering.
1730 * @param user_picture $userpicture
1731 * @return string
1732 */
1733 protected function render_user_picture(user_picture $userpicture) {
1734 global $CFG, $DB;
812dbaf7 1735
5d0c95a5
PS
1736 $user = $userpicture->user;
1737
1738 if ($userpicture->alttext) {
1739 if (!empty($user->imagealt)) {
1740 $alt = $user->imagealt;
1741 } else {
1742 $alt = get_string('pictureof', '', fullname($user));
1743 }
d9c8f425 1744 } else {
97c10099 1745 $alt = '';
5d0c95a5
PS
1746 }
1747
1748 if (empty($userpicture->size)) {
1749 $file = 'f2';
1750 $size = 35;
1751 } else if ($userpicture->size === true or $userpicture->size == 1) {
1752 $file = 'f1';
1753 $size = 100;
1754 } else if ($userpicture->size >= 50) {
1755 $file = 'f1';
1756 $size = $userpicture->size;
1757 } else {
1758 $file = 'f2';
1759 $size = $userpicture->size;
d9c8f425 1760 }
1761
5d0c95a5 1762 $class = $userpicture->class;
d9c8f425 1763
edfd6a5e
PS
1764 if ($user->picture == 1) {
1765 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1766 $src = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', $file);
1767
1768 } else if ($user->picture == 2) {
1769 //TODO: gravatar user icon support
1770
5d0c95a5
PS
1771 } else { // Print default user pictures (use theme version if available)
1772 $class .= ' defaultuserpic';
1773 $src = $this->pix_url('u/' . $file);
1774 }
d9c8f425 1775
5d0c95a5
PS
1776 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1777
1778 // get the image html output fisrt
1779 $output = html_writer::empty_tag('img', $attributes);;
1780
1781 // then wrap it in link if needed
1782 if (!$userpicture->link) {
1783 return $output;
d9c8f425 1784 }
1785
5d0c95a5
PS
1786 if (empty($userpicture->courseid)) {
1787 $courseid = $this->page->course->id;
1788 } else {
1789 $courseid = $userpicture->courseid;
1790 }
1791
03d9401e
MD
1792 if ($courseid == SITEID) {
1793 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1794 } else {
1795 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1796 }
5d0c95a5
PS
1797
1798 $attributes = array('href'=>$url);
1799
1800 if ($userpicture->popup) {
1801 $id = html_writer::random_id('userpicture');
1802 $attributes['id'] = $id;
c80877aa 1803 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
1804 }
1805
26acc814 1806 return html_writer::tag('a', $output, $attributes);
d9c8f425 1807 }
b80ef420 1808
b80ef420
DC
1809 /**
1810 * Internal implementation of file tree viewer items rendering.
1811 * @param array $dir
1812 * @return string
1813 */
1814 public function htmllize_file_tree($dir) {
1815 if (empty($dir['subdirs']) and empty($dir['files'])) {
1816 return '';
1817 }
1818 $result = '<ul>';
1819 foreach ($dir['subdirs'] as $subdir) {
1820 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1821 }
1822 foreach ($dir['files'] as $file) {
1823 $filename = $file->get_filename();
1824 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1825 }
1826 $result .= '</ul>';
1827
1828 return $result;
1829 }
bb496de7
DC
1830 /**
1831 * Print the file picker
1832 *
1833 * <pre>
1834 * $OUTPUT->file_picker($options);
1835 * </pre>
1836 *
1837 * @param array $options associative array with file manager options
1838 * options are:
1839 * maxbytes=>-1,
1840 * itemid=>0,
1841 * client_id=>uniqid(),
1842 * acepted_types=>'*',
1843 * return_types=>FILE_INTERNAL,
1844 * context=>$PAGE->context
1845 * @return string HTML fragment
1846 */
1847 public function file_picker($options) {
1848 $fp = new file_picker($options);
1849 return $this->render($fp);
1850 }
b80ef420
DC
1851 /**
1852 * Internal implementation of file picker rendering.
1853 * @param file_picker $fp
1854 * @return string
1855 */
bb496de7
DC
1856 public function render_file_picker(file_picker $fp) {
1857 global $CFG, $OUTPUT, $USER;
1858 $options = $fp->options;
1859 $client_id = $options->client_id;
1860 $strsaved = get_string('filesaved', 'repository');
1861 $straddfile = get_string('openpicker', 'repository');
1862 $strloading = get_string('loading', 'repository');
1863 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
1864
1865 $currentfile = $options->currentfile;
1866 if (empty($currentfile)) {
1867 $currentfile = get_string('nofilesattached', 'repository');
1868 }
1869 $html = <<<EOD
1870<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
1871$icon_progress
1872</div>
1873<div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
1874 <div>
1875 <button id="filepicker-button-{$client_id}">$straddfile</button>
1876 </div>
1877EOD;
1878 if ($options->env != 'url') {
1879 $html .= <<<EOD
1880 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">$currentfile</div>
1881EOD;
1882 }
1883 $html .= '</div>';
1884 return $html;
1885 }
d9c8f425 1886
1887 /**
1888 * Prints the 'Update this Modulename' button that appears on module pages.
1889 *
1890 * @param string $cmid the course_module id.
1891 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
1892 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1893 */
1894 public function update_module_button($cmid, $modulename) {
1895 global $CFG;
1896 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
1897 $modulename = get_string('modulename', $modulename);
1898 $string = get_string('updatethis', '', $modulename);
3ba60ee1
PS
1899 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1900 return $this->single_button($url, $string);
d9c8f425 1901 } else {
1902 return '';
1903 }
1904 }
1905
1906 /**
1907 * Prints a "Turn editing on/off" button in a form.
1908 * @param moodle_url $url The URL + params to send through when clicking the button
1909 * @return string HTML the button
1910 */
1911 public function edit_button(moodle_url $url) {
3362dfdc
EL
1912
1913 $url->param('sesskey', sesskey());
1914 if ($this->page->user_is_editing()) {
1915 $url->param('edit', 'off');
1916 $editstring = get_string('turneditingoff');
d9c8f425 1917 } else {
3362dfdc
EL
1918 $url->param('edit', 'on');
1919 $editstring = get_string('turneditingon');
d9c8f425 1920 }
1921
3362dfdc 1922 return $this->single_button($url, $editstring);
d9c8f425 1923 }
1924
d9c8f425 1925 /**
1926 * Prints a simple button to close a window
1927 *
d9c8f425 1928 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 1929 * @return string html fragment
d9c8f425 1930 */
7a5c78e0 1931 public function close_window_button($text='') {
d9c8f425 1932 if (empty($text)) {
1933 $text = get_string('closewindow');
1934 }
a6855934
PS
1935 $button = new single_button(new moodle_url('#'), $text, 'get');
1936 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
1937
1938 return $this->container($this->render($button), 'closewindow');
d9c8f425 1939 }
1940
d9c8f425 1941 /**
1942 * Output an error message. By default wraps the error message in <span class="error">.
1943 * If the error message is blank, nothing is output.
1944 * @param string $message the error message.
1945 * @return string the HTML to output.
1946 */
1947 public function error_text($message) {
1948 if (empty($message)) {
1949 return '';
1950 }
26acc814 1951 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 1952 }
1953
1954 /**
1955 * Do not call this function directly.
1956 *
1957 * To terminate the current script with a fatal error, call the {@link print_error}
1958 * function, or throw an exception. Doing either of those things will then call this
1959 * function to display the error, before terminating the execution.
1960 *
1961 * @param string $message The message to output
1962 * @param string $moreinfourl URL where more info can be found about the error
1963 * @param string $link Link for the Continue button
1964 * @param array $backtrace The execution backtrace
1965 * @param string $debuginfo Debugging information
d9c8f425 1966 * @return string the HTML to output.
1967 */
83267ec0 1968 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
d9c8f425 1969
1970 $output = '';
6f8f4d83 1971 $obbuffer = '';
e57c283d 1972
d9c8f425 1973 if ($this->has_started()) {
50764d37
PS
1974 // we can not always recover properly here, we have problems with output buffering,
1975 // html tables, etc.
d9c8f425 1976 $output .= $this->opencontainers->pop_all_but_last();
50764d37 1977
d9c8f425 1978 } else {
50764d37
PS
1979 // It is really bad if library code throws exception when output buffering is on,
1980 // because the buffered text would be printed before our start of page.
1981 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
1982 while (ob_get_level() > 0) {
6f8f4d83 1983 $obbuffer .= ob_get_clean();
50764d37 1984 }
6f8f4d83 1985
d9c8f425 1986 // Header not yet printed
85309744 1987 if (isset($_SERVER['SERVER_PROTOCOL'])) {
78946b9b
PS
1988 // server protocol should be always present, because this render
1989 // can not be used from command line or when outputting custom XML
85309744
PS
1990 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
1991 }
eb5bdb35 1992 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
7fde1e4b 1993 $this->page->set_url('/'); // no url
191b267b 1994 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
dcfb9b78 1995 $this->page->set_title(get_string('error'));
8093188f 1996 $this->page->set_heading($this->page->course->fullname);
d9c8f425 1997 $output .= $this->header();
1998 }
1999
2000 $message = '<p class="errormessage">' . $message . '</p>'.
2001 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2002 get_string('moreinformation') . '</a></p>';
2003 $output .= $this->box($message, 'errorbox');
2004
6f8f4d83
PS
2005 if (debugging('', DEBUG_DEVELOPER)) {
2006 if (!empty($debuginfo)) {
c5d18164
PS
2007 $debuginfo = s($debuginfo); // removes all nasty JS
2008 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2009 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
6f8f4d83
PS
2010 }
2011 if (!empty($backtrace)) {
2012 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2013 }
2014 if ($obbuffer !== '' ) {
2015 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2016 }
d9c8f425 2017 }
2018
2019 if (!empty($link)) {
2020 $output .= $this->continue_button($link);
2021 }
2022
2023 $output .= $this->footer();
2024
2025 // Padding to encourage IE to display our error page, rather than its own.
2026 $output .= str_repeat(' ', 512);
2027
2028 return $output;
2029 }
2030
2031 /**
2032 * Output a notification (that is, a status message about something that has
2033 * just happened).
2034 *
2035 * @param string $message the message to print out
2036 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2037 * @return string the HTML to output.
2038 */
2039 public function notification($message, $classes = 'notifyproblem') {
26acc814 2040 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
d9c8f425 2041 }
2042
2043 /**
2044 * Print a continue button that goes to a particular URL.
2045 *
3ba60ee1 2046 * @param string|moodle_url $url The url the button goes to.
d9c8f425 2047 * @return string the HTML to output.
2048 */
3ba60ee1
PS
2049 public function continue_button($url) {
2050 if (!($url instanceof moodle_url)) {
2051 $url = new moodle_url($url);
d9c8f425 2052 }
3ba60ee1
PS
2053 $button = new single_button($url, get_string('continue'), 'get');
2054 $button->class = 'continuebutton';
d9c8f425 2055
3ba60ee1 2056 return $this->render($button);
d9c8f425 2057 }
2058
2059 /**
2060 * Prints a single paging bar to provide access to other pages (usually in a search)
2061 *
71c03ac1 2062 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2063 * @param int $page The page you are currently viewing
2064 * @param int $perpage The number of entries that should be shown per page
2065 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2066 * @param string $pagevar name of page parameter that holds the page number
d9c8f425 2067 * @return string the HTML to output.
2068 */
929d7a83
PS
2069 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2070 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2071 return $this->render($pb);
2072 }
2073
2074 /**
2075 * Internal implementation of paging bar rendering.
2076 * @param paging_bar $pagingbar
2077 * @return string
2078 */
2079 protected function render_paging_bar(paging_bar $pagingbar) {
d9c8f425 2080 $output = '';
2081 $pagingbar = clone($pagingbar);
34059565 2082 $pagingbar->prepare($this, $this->page, $this->target);
d9c8f425 2083
2084 if ($pagingbar->totalcount > $pagingbar->perpage) {
2085 $output .= get_string('page') . ':';
2086
2087 if (!empty($pagingbar->previouslink)) {
56ddb719 2088 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
d9c8f425 2089 }
2090
2091 if (!empty($pagingbar->firstlink)) {
56ddb719 2092 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
d9c8f425 2093 }
2094
2095 foreach ($pagingbar->pagelinks as $link) {
56ddb719 2096 $output .= "&#160;&#160;$link";
d9c8f425 2097 }
2098
2099 if (!empty($pagingbar->lastlink)) {
56ddb719 2100 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
d9c8f425 2101 }
2102
2103 if (!empty($pagingbar->nextlink)) {
56ddb719 2104 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
d9c8f425 2105 }
2106 }
2107
26acc814 2108 return html_writer::tag('div', $output, array('class' => 'paging'));
d9c8f425 2109 }
2110
d9c8f425 2111 /**
2112 * Output the place a skip link goes to.
2113 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2114 * @return string the HTML to output.
2115 */
fe213365 2116 public function skip_link_target($id = null) {
26acc814 2117 return html_writer::tag('span', '', array('id' => $id));
d9c8f425 2118 }
2119
2120 /**
2121 * Outputs a heading
2122 * @param string $text The text of the heading
2123 * @param int $level The level of importance of the heading. Defaulting to 2
2124 * @param string $classes A space-separated list of CSS classes
2125 * @param string $id An optional ID
2126 * @return string the HTML to output.
2127 */
fe213365 2128 public function heading($text, $level = 2, $classes = 'main', $id = null) {
d9c8f425 2129 $level = (integer) $level;
2130 if ($level < 1 or $level > 6) {
2131 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2132 }
26acc814 2133 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 2134 }
2135
2136 /**
2137 * Outputs a box.
2138 * @param string $contents The contents of the box
2139 * @param string $classes A space-separated list of CSS classes
2140 * @param string $id An optional ID
2141 * @return string the HTML to output.
2142 */
fe213365 2143 public function box($contents, $classes = 'generalbox', $id = null) {
d9c8f425 2144 return $this->box_start($classes, $id) . $contents . $this->box_end();
2145 }
2146
2147 /**
2148 * Outputs the opening section of a box.
2149 * @param string $classes A space-separated list of CSS classes
2150 * @param string $id An optional ID
2151 * @return string the HTML to output.
2152 */
fe213365 2153 public function box_start($classes = 'generalbox', $id = null) {
5d0c95a5
PS
2154 $this->opencontainers->push('box', html_writer::end_tag('div'));
2155 return html_writer::start_tag('div', array('id' => $id,
78946b9b 2156 'class' => 'box ' . renderer_base::prepare_classes($classes)));
d9c8f425 2157 }
2158
2159 /**
2160 * Outputs the closing section of a box.
2161 * @return string the HTML to output.
2162 */
2163 public function box_end() {
2164 return $this->opencontainers->pop('box');
2165 }
2166
2167 /**
2168 * Outputs a container.
2169 * @param string $contents The contents of the box
2170 * @param string $classes A space-separated list of CSS classes
2171 * @param string $id An optional ID
2172 * @return string the HTML to output.
2173 */
fe213365 2174 public function container($contents, $classes = null, $id = null) {
d9c8f425 2175 return $this->container_start($classes, $id) . $contents . $this->container_end();
2176 }
2177
2178 /**
2179 * Outputs the opening section of a container.
2180 * @param string $classes A space-separated list of CSS classes
2181 * @param string $id An optional ID
2182 * @return string the HTML to output.
2183 */
fe213365 2184 public function container_start($classes = null, $id = null) {
5d0c95a5
PS
2185 $this->opencontainers->push('container', html_writer::end_tag('div'));
2186 return html_writer::start_tag('div', array('id' => $id,
78946b9b 2187 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 2188 }
2189
2190 /**
2191 * Outputs the closing section of a container.
2192 * @return string the HTML to output.
2193 */
2194 public function container_end() {
2195 return $this->opencontainers->pop('container');
2196 }
7d2a0492 2197
3406acde 2198 /**
7d2a0492 2199 * Make nested HTML lists out of the items
2200 *
2201 * The resulting list will look something like this:
2202 *
2203 * <pre>
2204 * <<ul>>
2205 * <<li>><div class='tree_item parent'>(item contents)</div>
2206 * <<ul>
2207 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2208 * <</ul>>
2209 * <</li>>
2210 * <</ul>>
2211 * </pre>
2212 *
2213 * @param array[]tree_item $items
2214 * @param array[string]string $attrs html attributes passed to the top of
2215 * the list
2216 * @return string HTML
2217 */
2218 function tree_block_contents($items, $attrs=array()) {
2219 // exit if empty, we don't want an empty ul element
2220 if (empty($items)) {
2221 return '';
2222 }
2223 // array of nested li elements
2224 $lis = array();
2225 foreach ($items as $item) {
2226 // this applies to the li item which contains all child lists too
2227 $content = $item->content($this);
2228 $liclasses = array($item->get_css_type());
3406acde 2229 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
7d2a0492 2230 $liclasses[] = 'collapsed';
2231 }
2232 if ($item->isactive === true) {
2233 $liclasses[] = 'current_branch';
2234 }
2235 $liattr = array('class'=>join(' ',$liclasses));
2236 // class attribute on the div item which only contains the item content
2237 $divclasses = array('tree_item');
3406acde 2238 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
7d2a0492 2239 $divclasses[] = 'branch';
2240 } else {
2241 $divclasses[] = 'leaf';
2242 }
2243 if (!empty($item->classes) && count($item->classes)>0) {
2244 $divclasses[] = join(' ', $item->classes);
2245 }
2246 $divattr = array('class'=>join(' ', $divclasses));
2247 if (!empty($item->id)) {
2248 $divattr['id'] = $item->id;
2249 }
26acc814 2250 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
7d2a0492 2251 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
26acc814 2252 $content = html_writer::empty_tag('hr') . $content;
7d2a0492 2253 }
26acc814 2254 $content = html_writer::tag('li', $content, $liattr);
7d2a0492 2255 $lis[] = $content;
2256 }
26acc814 2257 return html_writer::tag('ul', implode("\n", $lis), $attrs);
7d2a0492 2258 }
2259
2260 /**
2261 * Return the navbar content so that it can be echoed out by the layout
2262 * @return string XHTML navbar
2263 */
2264 public function navbar() {
3406acde
SH
2265 //return $this->page->navbar->content();
2266
2267 $items = $this->page->navbar->get_items();
2268
2269 $count = 0;
2270
2271 $htmlblocks = array();
2272 // Iterate the navarray and display each node
ffca6f4b
SH
2273 $itemcount = count($items);
2274 $separator = get_separator();
2275 for ($i=0;$i < $itemcount;$i++) {
2276 $item = $items[$i];
493a48f3 2277 $item->hideicon = true;
ffca6f4b
SH
2278 if ($i===0) {
2279 $content = html_writer::tag('li', $this->render($item));
2280 } else {
2281 $content = html_writer::tag('li', $separator.$this->render($item));
2282 }
2283 $htmlblocks[] = $content;
3406acde
SH
2284 }
2285
dcfb9b78
RW
2286 //accessibility: heading for navbar list (MDL-20446)
2287 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2288 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
3406acde 2289 // XHTML
dcfb9b78 2290 return $navbarcontent;
3406acde
SH
2291 }
2292
2293 protected function render_navigation_node(navigation_node $item) {
2294 $content = $item->get_content();
2295 $title = $item->get_title();
493a48f3 2296 if ($item->icon instanceof renderable && !$item->hideicon) {
3406acde 2297 $icon = $this->render($item->icon);
48fa9484 2298 $content = $icon.$content; // use CSS for spacing of icons
3406acde
SH
2299 }
2300 if ($item->helpbutton !== null) {
2301 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton'));
2302 }
2303 if ($content === '') {
b4c458a3 2304 return '';
3406acde
SH
2305 }
2306 if ($item->action instanceof action_link) {
2307 //TODO: to be replaced with something else
2308 $link = $item->action;
2309 if ($item->hidden) {
2310 $link->add_class('dimmed');
2311 }
2312 $content = $this->output->render($link);
2313 } else if ($item->action instanceof moodle_url) {
2314 $attributes = array();
2315 if ($title !== '') {
2316 $attributes['title'] = $title;
2317 }
2318 if ($item->hidden) {
2319 $attributes['class'] = 'dimmed_text';
2320 }
2321 $content = html_writer::link($item->action, $content, $attributes);
2322
2323 } else if (is_string($item->action) || empty($item->action)) {
2324 $attributes = array();
2325 if ($title !== '') {
2326 $attributes['title'] = $title;
2327 }
2328 if ($item->hidden) {
2329 $attributes['class'] = 'dimmed_text';
2330 }
2331 $content = html_writer::tag('span', $content, $attributes);
2332 }
2333 return $content;
7d2a0492 2334 }
92e01ab7
PS
2335
2336 /**
2337 * Accessibility: Right arrow-like character is
2338 * used in the breadcrumb trail, course navigation menu
2339 * (previous/next activity), calendar, and search forum block.
2340 * If the theme does not set characters, appropriate defaults
2341 * are set automatically. Please DO NOT
2342 * use &lt; &gt; &raquo; - these are confusing for blind users.
2343 * @return string
2344 */
2345 public function rarrow() {
2346 return $this->page->theme->rarrow;
2347 }
2348
2349 /**
2350 * Accessibility: Right arrow-like character is
2351 * used in the breadcrumb trail, course navigation menu
2352 * (previous/next activity), calendar, and search forum block.
2353 * If the theme does not set characters, appropriate defaults
2354 * are set automatically. Please DO NOT
2355 * use &lt; &gt; &raquo; - these are confusing for blind users.
2356 * @return string
2357 */
2358 public function larrow() {
2359 return $this->page->theme->larrow;
2360 }
088ccb43
PS
2361
2362 /**
2363 * Returns the colours of the small MP3 player
2364 * @return string
2365 */
2366 public function filter_mediaplugin_colors() {
2367 return $this->page->theme->filter_mediaplugin_colors;
2368 }
2369
2370 /**
2371 * Returns the colours of the big MP3 player
2372 * @return string
2373 */
2374 public function resource_mp3player_colors() {
2375 return $this->page->theme->resource_mp3player_colors;
2376 }
d2dbd0c0
SH
2377
2378 /**
2379 * Returns the custom menu if one has been set
2380 *
71c03ac1 2381 * A custom menu can be configured by browsing to
d2dbd0c0
SH
2382 * Settings: Administration > Appearance > Themes > Theme settings
2383 * and then configuring the custommenu config setting as described.
4d2ee4c2 2384 *
d2dbd0c0
SH
2385 * @return string
2386 */
2387 public function custom_menu() {
12cc75ae
SH
2388 global $CFG;
2389 if (empty($CFG->custommenuitems)) {
2390 return '';
2391 }
d2dbd0c0
SH
2392 $custommenu = new custom_menu();
2393 return $this->render_custom_menu($custommenu);
2394 }
2395
2396 /**
2397 * Renders a custom menu object (located in outputcomponents.php)
2398 *
2399 * The custom menu this method produces makes use of the YUI3 menunav widget
2400 * and requires very specific html elements and classes.
2401 *
2402 * @staticvar int $menucount
2403 * @param custom_menu $menu
2404 * @return string
2405 */
2406 protected function render_custom_menu(custom_menu $menu) {
2407 static $menucount = 0;
2408 // If the menu has no children return an empty string
2409 if (!$menu->has_children()) {
2410 return '';
2411 }
2412 // Increment the menu count. This is used for ID's that get worked with
2413 // in JavaScript as is essential
2414 $menucount++;
d2dbd0c0 2415 // Initialise this custom menu
d7bd9acd 2416 $this->page->requires->js_init_call('M.core_custom_menu.init', array('custom_menu_'.$menucount));
d2dbd0c0
SH
2417 // Build the root nodes as required by YUI
2418 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2419 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2420 $content .= html_writer::start_tag('ul');
2421 // Render each child
2422 foreach ($menu->get_children() as $item) {
2423 $content .= $this->render_custom_menu_item($item);
2424 }
2425 // Close the open tags
2426 $content .= html_writer::end_tag('ul');
2427 $content .= html_writer::end_tag('div');
2428 $content .= html_writer::end_tag('div');
2429 // Return the custom menu
2430 return $content;
2431 }
2432
2433 /**
2434 * Renders a custom menu node as part of a submenu
2435 *
2436 * The custom menu this method produces makes use of the YUI3 menunav widget
2437 * and requires very specific html elements and classes.
2438 *
2439 * @see render_custom_menu()
2440 *
2441 * @staticvar int $submenucount
2442 * @param custom_menu_item $menunode
2443 * @return string
2444 */
2445 protected function render_custom_menu_item(custom_menu_item $menunode) {
2446 // Required to ensure we get unique trackable id's
2447 static $submenucount = 0;
2448 if ($menunode->has_children()) {
2449 // If the child has menus render it as a sub menu
2450 $submenucount++;
2451 $content = html_writer::start_tag('li');
2452 if ($menunode->get_url() !== null) {
2453 $url = $menunode->get_url();
2454 } else {
2455 $url = '#cm_submenu_'.$submenucount;
2456 }
2457 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2458 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2459 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2460 $content .= html_writer::start_tag('ul');
2461 foreach ($menunode->get_children() as $menunode) {
2462 $content .= $this->render_custom_menu_item($menunode);
2463 }
2464 $content .= html_writer::end_tag('ul');
2465 $content .= html_writer::end_tag('div');
2466 $content .= html_writer::end_tag('div');
2467 $content .= html_writer::end_tag('li');
2468 } else {
2469 // The node doesn't have children so produce a final menuitem
2470 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2471 if ($menunode->get_url() !== null) {
2472 $url = $menunode->get_url();
2473 } else {
2474 $url = '#';
2475 }
2476 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2477 $content .= html_writer::end_tag('li');
2478 }
2479 // Return the sub menu
2480 return $content;
2481 }
2a102b90
SH
2482
2483 /**
2484 * Renders the image_gallery component and initialises its JavaScript
2485 *
2486 * @param image_gallery $imagegallery
2487 * @return string
2488 */
2489 protected function render_image_gallery(image_gallery $imagegallery) {
78bfb562 2490 $this->page->requires->yui_module(array('gallery-lightbox','gallery-lightbox-skin'),
f21b3630 2491 'Y.Lightbox.init', null, '2010.04.08-12-35');
2a102b90
SH
2492 if (count($imagegallery->images) == 0) {
2493 return '';
2494 }
af7c1e29
SH
2495 $classes = array('image_gallery');
2496 if ($imagegallery->displayfirstimageonly) {
2497 $classes[] = 'oneimageonly';
2498 }
2499 $content = html_writer::start_tag('div', array('class'=>join(' ', $classes)));
2a102b90
SH
2500 foreach ($imagegallery->images as $image) {
2501 $content .= html_writer::tag('a', html_writer::empty_tag('img', $image->thumb), $image->link);
2502 }
2503 $content .= html_writer::end_tag('div');
2504 return $content;
2505 }
78946b9b 2506}
d9c8f425 2507
2508
2509/// RENDERERS
2510
2511/**
2512 * A renderer that generates output for command-line scripts.
2513 *
2514 * The implementation of this renderer is probably incomplete.
2515 *
2516 * @copyright 2009 Tim Hunt
2517 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2518 * @since Moodle 2.0
2519 */
56cbc53b 2520class core_renderer_cli extends core_renderer {
d9c8f425 2521 /**
2522 * Returns the page header.
2523 * @return string HTML fragment
2524 */
2525 public function header() {
2526 output_starting_hook();
2527 return $this->page->heading . "\n";
2528 }
2529
2530 /**
2531 * Returns a template fragment representing a Heading.
2532 * @param string $text The text of the heading
2533 * @param int $level The level of importance of the heading
2534 * @param string $classes A space-separated list of CSS classes
2535 * @param string $id An optional ID
2536 * @return string A template fragment for a heading
2537 */
0fddc031 2538 public function heading($text, $level = 2, $classes = 'main', $id = null) {
d9c8f425 2539 $text .= "\n";
2540 switch ($level) {
2541 case 1:
2542 return '=>' . $text;
2543 case 2:
2544 return '-->' . $text;
2545 default:
2546 return $text;
2547 }
2548 }
2549
2550 /**
2551 * Returns a template fragment representing a fatal error.
2552 * @param string $message The message to output
2553 * @param string $moreinfourl URL where more info can be found about the error
2554 * @param string $link Link for the Continue button
2555 * @param array $backtrace The execution backtrace
2556 * @param string $debuginfo Debugging information
d9c8f425 2557 * @return string A template fragment for a fatal error
2558 */
83267ec0 2559 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
d9c8f425 2560 $output = "!!! $message !!!\n";
2561
2562 if (debugging('', DEBUG_DEVELOPER)) {
2563 if (!empty($debuginfo)) {
2564 $this->notification($debuginfo, 'notifytiny');
2565 }
2566 if (!empty($backtrace)) {
2567 $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2568 }
2569 }
2570 }
2571
2572 /**
2573 * Returns a template fragment representing a notification.
2574 * @param string $message The message to include
2575 * @param string $classes A space-separated list of CSS classes
2576 * @return string A template fragment for a notification
2577 */
2578 public function notification($message, $classes = 'notifyproblem') {
2579 $message = clean_text($message);
2580 if ($classes === 'notifysuccess') {
2581 return "++ $message ++\n";
2582 }
2583 return "!! $message !!\n";
2584 }
2585}
2586
1adaa404
PS
2587
2588/**
2589 * A renderer that generates output for ajax scripts.
2590 *
2591 * This renderer prevents accidental sends back only json
2592 * encoded error messages, all other output is ignored.
2593 *
2594 * @copyright 2010 Petr Skoda
2595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2596 * @since Moodle 2.0
2597 */
2598class core_renderer_ajax extends core_renderer {
2599 /**
2600 * Returns a template fragment representing a fatal error.
2601 * @param string $message The message to output
2602 * @param string $moreinfourl URL where more info can be found about the error
2603 * @param string $link Link for the Continue button
2604 * @param array $backtrace The execution backtrace
2605 * @param string $debuginfo Debugging information
2606 * @return string A template fragment for a fatal error
2607 */
2608 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
6db3eee0 2609 global $FULLME, $USER;
eb5bdb35
PS
2610
2611 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2612
1adaa404
PS
2613 $e = new stdClass();
2614 $e->error = $message;
2615 $e->stacktrace = NULL;
2616 $e->debuginfo = NULL;
6db3eee0 2617 $e->reproductionlink = NULL;
1adaa404 2618 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
6db3eee0 2619 $e->reproductionlink = $link;
1adaa404
PS
2620 if (!empty($debuginfo)) {
2621 $e->debuginfo = $debuginfo;
2622 }
2623 if (!empty($backtrace)) {
2624 $e->stacktrace = format_backtrace($backtrace, true);
2625 }
2626 }
bce08d9a 2627 $this->header();
1adaa404
PS
2628 return json_encode($e);
2629 }
2630
2631 public function notification($message, $classes = 'notifyproblem') {
2632 }
bce08d9a 2633
1adaa404
PS
2634 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
2635 }
bce08d9a 2636
1adaa404 2637 public function header() {
bce08d9a
PS
2638 // unfortunately YUI iframe upload does not support application/json
2639 if (!empty($_FILES)) {
2640 @header('Content-type: text/plain');
2641 } else {
2642 @header('Content-type: application/json');
2643 }
2644
2645 /// Headers to make it not cacheable and json
2646 @header('Cache-Control: no-store, no-cache, must-revalidate');
2647 @header('Cache-Control: post-check=0, pre-check=0', false);
2648 @header('Pragma: no-cache');
2649 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2650 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2651 @header('Accept-Ranges: none');
1adaa404 2652 }
bce08d9a 2653
1adaa404
PS
2654 public function footer() {
2655 }
bce08d9a 2656
0fddc031 2657 public function heading($text, $level = 2, $classes = 'main', $id = null) {
1adaa404
PS
2658 }
2659}
2660