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