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