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