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