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