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