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