Merge branch 'MDL-51501-master' of git://github.com/merrill-oakland/moodle
[moodle.git] / lib / outputcomponents.php
CommitLineData
d9c8f425 1<?php
d9c8f425 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Classes representing HTML elements, used by $OUTPUT methods
19 *
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
22 *
f8129210 23 * @package core
76be40cc 24 * @category output
9678c7b8
SH
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d9c8f425 27 */
28
78bfb562 29defined('MOODLE_INTERNAL') || die();
5d0c95a5
PS
30
31/**
32 * Interface marking other classes as suitable for renderer_base::render()
3d3fae72 33 *
9678c7b8 34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
f8129210 35 * @package core
76be40cc 36 * @category output
5d0c95a5
PS
37 */
38interface renderable {
39 // intentionally empty
40}
41
9bdcf579
DW
42/**
43 * Interface marking other classes having the ability to export their data for use by templates.
44 *
45 * @copyright 2015 Damyon Wiese
46 * @package core
47 * @category output
48 * @since 2.9
49 */
50interface templatable {
51
52 /**
53 * Function to export the renderer data in a format that is suitable for a
54 * mustache template. This means:
55 * 1. No complex types - only stdClass, array, int, string, float, bool
56 * 2. Any additional info that is required for the template is pre-calculated (e.g. capability checks).
57 *
58 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
59 * @return stdClass|array
60 */
61 public function export_for_template(renderer_base $output);
62}
63
bb496de7
DC
64/**
65 * Data structure representing a file picker.
66 *
67 * @copyright 2010 Dongsheng Cai
9678c7b8
SH
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
69 * @since Moodle 2.0
f8129210 70 * @package core
76be40cc 71 * @category output
bb496de7
DC
72 */
73class file_picker implements renderable {
9678c7b8
SH
74
75 /**
76be40cc 76 * @var stdClass An object containing options for the file picker
9678c7b8 77 */
bb496de7 78 public $options;
9678c7b8
SH
79
80 /**
81 * Constructs a file picker object.
82 *
83 * The following are possible options for the filepicker:
84 * - accepted_types (*)
85 * - return_types (FILE_INTERNAL)
86 * - env (filepicker)
87 * - client_id (uniqid)
88 * - itemid (0)
89 * - maxbytes (-1)
90 * - maxfiles (1)
91 * - buttonname (false)
92 *
93 * @param stdClass $options An object containing options for the file picker.
94 */
bb496de7
DC
95 public function __construct(stdClass $options) {
96 global $CFG, $USER, $PAGE;
97 require_once($CFG->dirroot. '/repository/lib.php');
98 $defaults = array(
99 'accepted_types'=>'*',
bb496de7
DC
100 'return_types'=>FILE_INTERNAL,
101 'env' => 'filepicker',
102 'client_id' => uniqid(),
103 'itemid' => 0,
104 'maxbytes'=>-1,
105 'maxfiles'=>1,
f50a61fb 106 'buttonname'=>false
bb496de7
DC
107 );
108 foreach ($defaults as $key=>$value) {
109 if (empty($options->$key)) {
110 $options->$key = $value;
111 }
112 }
113
114 $options->currentfile = '';
115 if (!empty($options->itemid)) {
116 $fs = get_file_storage();
b0c6dc1c 117 $usercontext = context_user::instance($USER->id);
e4256380 118 if (empty($options->filename)) {
64f93798 119 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
e4256380
DC
120 $file = reset($files);
121 }
122 } else {
64f93798 123 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
e4256380
DC
124 }
125 if (!empty($file)) {
ee9a4962 126 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
bb496de7
DC
127 }
128 }
129
bb496de7
DC
130 // initilise options, getting files in root path
131 $this->options = initialise_filepicker($options);
132
133 // copying other options
134 foreach ($options as $name=>$value) {
98e7ae63
DC
135 if (!isset($this->options->$name)) {
136 $this->options->$name = $value;
137 }
bb496de7
DC
138 }
139 }
140}
141
5d0c95a5 142/**
bf11293a 143 * Data structure representing a user picture.
5d0c95a5
PS
144 *
145 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
9678c7b8
SH
146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
147 * @since Modle 2.0
f8129210 148 * @package core
76be40cc 149 * @category output
5d0c95a5
PS
150 */
151class user_picture implements renderable {
152 /**
76be40cc
SH
153 * @var array List of mandatory fields in user record here. (do not include
154 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
5d0c95a5 155 */
a327f25e
AG
156 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic',
157 'middlename', 'alternatename', 'imagealt', 'email');
5d0c95a5
PS
158
159 /**
76be40cc
SH
160 * @var stdClass A user object with at least fields all columns specified
161 * in $fields array constant set.
5d0c95a5
PS
162 */
163 public $user;
9678c7b8 164
5d0c95a5 165 /**
76be40cc
SH
166 * @var int The course id. Used when constructing the link to the user's
167 * profile, page course id used if not specified.
5d0c95a5
PS
168 */
169 public $courseid;
9678c7b8 170
5d0c95a5 171 /**
76be40cc 172 * @var bool Add course profile link to image
5d0c95a5
PS
173 */
174 public $link = true;
9678c7b8 175
5d0c95a5 176 /**
76be40cc
SH
177 * @var int Size in pixels. Special values are (true/1 = 100px) and
178 * (false/0 = 35px)
9678c7b8 179 * for backward compatibility.
5d0c95a5
PS
180 */
181 public $size = 35;
9678c7b8 182
5d0c95a5 183 /**
3d3fae72 184 * @var bool Add non-blank alt-text to the image.
5d0c95a5
PS
185 * Default true, set to false when image alt just duplicates text in screenreaders.
186 */
187 public $alttext = true;
9678c7b8 188
5d0c95a5 189 /**
3d3fae72 190 * @var bool Whether or not to open the link in a popup window.
5d0c95a5
PS
191 */
192 public $popup = false;
9678c7b8 193
5d0c95a5 194 /**
76be40cc 195 * @var string Image class attribute
5d0c95a5
PS
196 */
197 public $class = 'userpicture';
198
e4a1efcb
JC
199 /**
200 * @var bool Whether to be visible to screen readers.
201 */
202 public $visibletoscreenreaders = true;
203
5d0c95a5
PS
204 /**
205 * User picture constructor.
206 *
9678c7b8 207 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
faa328c3 208 * It is recommended to add also contextid of the user for performance reasons.
5d0c95a5
PS
209 */
210 public function __construct(stdClass $user) {
211 global $DB;
212
5d0c95a5
PS
213 if (empty($user->id)) {
214 throw new coding_exception('User id is required when printing user avatar image.');
215 }
216
217 // only touch the DB if we are missing data and complain loudly...
218 $needrec = false;
3a11c09f 219 foreach (self::$fields as $field) {
5d0c95a5
PS
220 if (!array_key_exists($field, $user)) {
221 $needrec = true;
222 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
223 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
224 break;
225 }
226 }
227
228 if ($needrec) {
3a11c09f 229 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
5d0c95a5
PS
230 } else {
231 $this->user = clone($user);
232 }
233 }
234
235 /**
1a10840e 236 * Returns a list of required user fields, useful when fetching required user info from db.
f3afba4e
PS
237 *
238 * In some cases we have to fetch the user data together with some other information,
239 * the idalias is useful there because the id would otherwise override the main
240 * id of the result record. Please note it has to be converted back to id before rendering.
241 *
5d0c95a5 242 * @param string $tableprefix name of database table prefix in query
3a11c09f 243 * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
f3afba4e 244 * @param string $idalias alias of id field
9958e561 245 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
5d0c95a5
PS
246 * @return string
247 */
9958e561 248 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
3a11c09f
PS
249 if (!$tableprefix and !$extrafields and !$idalias) {
250 return implode(',', self::$fields);
5d0c95a5 251 }
3a11c09f
PS
252 if ($tableprefix) {
253 $tableprefix .= '.';
254 }
3a11c09f
PS
255 foreach (self::$fields as $field) {
256 if ($field === 'id' and $idalias and $idalias !== 'id') {
6f7b89e2 257 $fields[$field] = "$tableprefix$field AS $idalias";
3a11c09f 258 } else {
9958e561
DM
259 if ($fieldprefix and $field !== 'id') {
260 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
261 } else {
262 $fields[$field] = "$tableprefix$field";
263 }
3a11c09f
PS
264 }
265 }
266 // add extra fields if not already there
267 if ($extrafields) {
268 foreach ($extrafields as $e) {
269 if ($e === 'id' or isset($fields[$e])) {
270 continue;
271 }
5c0d03ea
DM
272 if ($fieldprefix) {
273 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
274 } else {
275 $fields[$e] = "$tableprefix$e";
276 }
f3afba4e 277 }
f3afba4e
PS
278 }
279 return implode(',', $fields);
5d0c95a5 280 }
5d0c95a5 281
5c0d03ea
DM
282 /**
283 * Extract the aliased user fields from a given record
284 *
285 * Given a record that was previously obtained using {@link self::fields()} with aliases,
286 * this method extracts user related unaliased fields.
287 *
288 * @param stdClass $record containing user picture fields
289 * @param array $extrafields extra fields included in the $record
290 * @param string $idalias alias of the id field
291 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
292 * @return stdClass object with unaliased user fields
293 */
9678c7b8 294 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
5c0d03ea
DM
295
296 if (empty($idalias)) {
297 $idalias = 'id';
298 }
299
300 $return = new stdClass();
301
302 foreach (self::$fields as $field) {
303 if ($field === 'id') {
9ecbf801 304 if (property_exists($record, $idalias)) {
5c0d03ea
DM
305 $return->id = $record->{$idalias};
306 }
307 } else {
9ecbf801 308 if (property_exists($record, $fieldprefix.$field)) {
5c0d03ea
DM
309 $return->{$field} = $record->{$fieldprefix.$field};
310 }
311 }
312 }
313 // add extra fields if not already there
314 if ($extrafields) {
315 foreach ($extrafields as $e) {
9ecbf801 316 if ($e === 'id' or property_exists($return, $e)) {
5c0d03ea
DM
317 continue;
318 }
319 $return->{$e} = $record->{$fieldprefix.$e};
320 }
321 }
322
323 return $return;
871a3ec5
SH
324 }
325
326 /**
327 * Works out the URL for the users picture.
328 *
329 * This method is recommended as it avoids costly redirects of user pictures
330 * if requests are made for non-existent files etc.
331 *
f8129210 332 * @param moodle_page $page
871a3ec5
SH
333 * @param renderer_base $renderer
334 * @return moodle_url
335 */
336 public function get_url(moodle_page $page, renderer_base $renderer = null) {
33dca156 337 global $CFG;
871a3ec5
SH
338
339 if (is_null($renderer)) {
340 $renderer = $page->get_renderer('core');
341 }
342
871a3ec5
SH
343 // Sort out the filename and size. Size is only required for the gravatar
344 // implementation presently.
345 if (empty($this->size)) {
346 $filename = 'f2';
347 $size = 35;
348 } else if ($this->size === true or $this->size == 1) {
349 $filename = 'f1';
350 $size = 100;
33d9f44b
PS
351 } else if ($this->size > 100) {
352 $filename = 'f3';
353 $size = (int)$this->size;
871a3ec5
SH
354 } else if ($this->size >= 50) {
355 $filename = 'f1';
356 $size = (int)$this->size;
357 } else {
358 $filename = 'f2';
359 $size = (int)$this->size;
360 }
361
faa328c3
PS
362 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
363
364 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
365 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
366 // Protect images if login required and not logged in;
367 // also if login is required for profile images and is not logged in or guest
368 // do not use require_login() because it is expensive and not suitable here anyway.
369 return $defaulturl;
03636668 370 }
4125bdc1 371
faa328c3
PS
372 // First try to detect deleted users - but do not read from database for performance reasons!
373 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
374 // All deleted users should have email replaced by md5 hash,
375 // all active users are expected to have valid email.
376 return $defaulturl;
377 }
378
379 // Did the user upload a picture?
4d254790 380 if ($this->user->picture > 0) {
faa328c3
PS
381 if (!empty($this->user->contextid)) {
382 $contextid = $this->user->contextid;
383 } else {
384 $context = context_user::instance($this->user->id, IGNORE_MISSING);
385 if (!$context) {
386 // This must be an incorrectly deleted user, all other users have context.
387 return $defaulturl;
388 }
389 $contextid = $context->id;
390 }
391
871a3ec5
SH
392 $path = '/';
393 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
394 // We append the theme name to the file path if we have it so that
395 // in the circumstance that the profile picture is not available
396 // when the user actually requests it they still get the profile
397 // picture for the correct theme.
398 $path .= $page->theme->name.'/';
399 }
faa328c3 400 // Set the image URL to the URL for the uploaded file and return.
4d254790
PS
401 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
402 $url->param('rev', $this->user->picture);
403 return $url;
faa328c3
PS
404 }
405
4d254790 406 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
4125bdc1
SH
407 // Normalise the size variable to acceptable bounds
408 if ($size < 1 || $size > 512) {
871a3ec5
SH
409 $size = 35;
410 }
4125bdc1 411 // Hash the users email address
871a3ec5 412 $md5 = md5(strtolower(trim($this->user->email)));
4125bdc1 413 // Build a gravatar URL with what we know.
f127b1a5
MA
414
415 // Find the best default image URL we can (MDL-35669)
416 if (empty($CFG->gravatardefaulturl)) {
417 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
418 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
419 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
420 } else {
421 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
422 }
423 } else {
424 $gravatardefault = $CFG->gravatardefaulturl;
425 }
426
4125bdc1
SH
427 // If the currently requested page is https then we'll return an
428 // https gravatar page.
1e31f118 429 if (is_https()) {
b96a15cc 430 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
f127b1a5 431 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
4125bdc1 432 } else {
f127b1a5 433 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
4125bdc1 434 }
871a3ec5
SH
435 }
436
faa328c3 437 return $defaulturl;
5c0d03ea
DM
438 }
439}
bf11293a 440
49f0d481
PS
441/**
442 * Data structure representing a help icon.
443 *
444 * @copyright 2010 Petr Skoda (info@skodak.org)
9678c7b8
SH
445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
446 * @since Moodle 2.0
f8129210 447 * @package core
76be40cc 448 * @category output
49f0d481
PS
449 */
450class help_icon implements renderable {
9678c7b8 451
49f0d481 452 /**
76be40cc 453 * @var string lang pack identifier (without the "_help" suffix),
9678c7b8
SH
454 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
455 * must exist.
49f0d481
PS
456 */
457 public $identifier;
9678c7b8 458
49f0d481 459 /**
76be40cc 460 * @var string Component name, the same as in get_string()
49f0d481
PS
461 */
462 public $component;
9678c7b8 463
49f0d481 464 /**
76be40cc 465 * @var string Extra descriptive text next to the icon
49f0d481
PS
466 */
467 public $linktext = null;
468
469 /**
470 * Constructor
9678c7b8
SH
471 *
472 * @param string $identifier string for help page title,
5435c9dc
MD
473 * string with _help suffix is used for the actual help text.
474 * string with _link suffix is used to create a link to further info (if it exists)
49f0d481
PS
475 * @param string $component
476 */
259c165d
PS
477 public function __construct($identifier, $component) {
478 $this->identifier = $identifier;
49f0d481
PS
479 $this->component = $component;
480 }
259c165d
PS
481
482 /**
483 * Verifies that both help strings exists, shows debug warnings if not
484 */
485 public function diag_strings() {
486 $sm = get_string_manager();
487 if (!$sm->string_exists($this->identifier, $this->component)) {
488 debugging("Help title string does not exist: [$this->identifier, $this->component]");
489 }
5435c9dc 490 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
876521ac 491 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
259c165d
PS
492 }
493 }
49f0d481
PS
494}
495
bf11293a 496
000c278c
PS
497/**
498 * Data structure representing an icon.
499 *
500 * @copyright 2010 Petr Skoda
9678c7b8
SH
501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
502 * @since Moodle 2.0
f8129210 503 * @package core
76be40cc 504 * @category output
000c278c 505 */
eb42bb7e 506class pix_icon implements renderable, templatable {
9678c7b8
SH
507
508 /**
76be40cc 509 * @var string The icon name
9678c7b8 510 */
000c278c 511 var $pix;
9678c7b8
SH
512
513 /**
76be40cc 514 * @var string The component the icon belongs to.
9678c7b8 515 */
000c278c 516 var $component;
9678c7b8
SH
517
518 /**
76be40cc 519 * @var array An array of attributes to use on the icon
9678c7b8 520 */
000c278c
PS
521 var $attributes = array();
522
523 /**
524 * Constructor
9678c7b8 525 *
000c278c 526 * @param string $pix short icon name
7749e187 527 * @param string $alt The alt text to use for the icon
000c278c
PS
528 * @param string $component component name
529 * @param array $attributes html attributes
530 */
531 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
532 $this->pix = $pix;
533 $this->component = $component;
000c278c
PS
534 $this->attributes = (array)$attributes;
535
000c278c
PS
536 if (empty($this->attributes['class'])) {
537 $this->attributes['class'] = 'smallicon';
538 }
0e55333a
EM
539
540 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
541 if (!is_null($alt)) {
542 $this->attributes['alt'] = $alt;
543
544 // If there is no title, set it to the attribute.
545 if (!isset($this->attributes['title'])) {
546 $this->attributes['title'] = $this->attributes['alt'];
547 }
548 } else {
549 unset($this->attributes['alt']);
550 }
551
552 if (empty($this->attributes['title'])) {
aad982aa
FM
553 // Remove the title attribute if empty, we probably want to use the parent node's title
554 // and some browsers might overwrite it with an empty title.
555 unset($this->attributes['title']);
000c278c
PS
556 }
557 }
eb42bb7e
DC
558
559 /**
560 * Export this data so it can be used as the context for a mustache template.
561 *
562 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
563 * @return array
564 */
565 public function export_for_template(renderer_base $output) {
566 $attributes = $this->attributes;
567 $attributes['src'] = $output->pix_url($this->pix, $this->component);
568 $templatecontext = array();
569 foreach ($attributes as $name => $value) {
570 $templatecontext[] = array('name' => $name, 'value' => $value);
571 }
572 $data = array('attributes' => $templatecontext);
573
574 return $data;
575 }
000c278c
PS
576}
577
d63c5073
DM
578/**
579 * Data structure representing an emoticon image
580 *
9678c7b8
SH
581 * @copyright 2010 David Mudrak
582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
583 * @since Moodle 2.0
f8129210 584 * @package core
76be40cc 585 * @category output
d63c5073
DM
586 */
587class pix_emoticon extends pix_icon implements renderable {
588
589 /**
590 * Constructor
591 * @param string $pix short icon name
b9fadae7
DM
592 * @param string $alt alternative text
593 * @param string $component emoticon image provider
594 * @param array $attributes explicit HTML attributes
d63c5073 595 */
b9fadae7
DM
596 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
597 if (empty($attributes['class'])) {
598 $attributes['class'] = 'emoticon';
599 }
d63c5073
DM
600 parent::__construct($pix, $alt, $component, $attributes);
601 }
602}
000c278c 603
3ba60ee1
PS
604/**
605 * Data structure representing a simple form with only one button.
606 *
607 * @copyright 2009 Petr Skoda
9678c7b8
SH
608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
609 * @since Moodle 2.0
f8129210 610 * @package core
76be40cc 611 * @category output
3ba60ee1
PS
612 */
613class single_button implements renderable {
9678c7b8 614
574fbea4 615 /**
76be40cc 616 * @var moodle_url Target url
574fbea4 617 */
3ba60ee1 618 var $url;
9678c7b8 619
574fbea4 620 /**
76be40cc 621 * @var string Button label
574fbea4 622 */
3ba60ee1 623 var $label;
9678c7b8 624
574fbea4 625 /**
76be40cc 626 * @var string Form submit method post or get
574fbea4 627 */
3ba60ee1 628 var $method = 'post';
9678c7b8 629
574fbea4 630 /**
76be40cc 631 * @var string Wrapping div class
9678c7b8 632 */
3ba60ee1 633 var $class = 'singlebutton';
9678c7b8 634
574fbea4 635 /**
3d3fae72 636 * @var bool True if button disabled, false if normal
574fbea4 637 */
3ba60ee1 638 var $disabled = false;
9678c7b8 639
574fbea4 640 /**
76be40cc 641 * @var string Button tooltip
574fbea4 642 */
97c10099 643 var $tooltip = null;
9678c7b8 644
574fbea4 645 /**
76be40cc 646 * @var string Form id
574fbea4 647 */
3ba60ee1 648 var $formid;
9678c7b8 649
574fbea4 650 /**
76be40cc 651 * @var array List of attached actions
574fbea4 652 */
3ba60ee1
PS
653 var $actions = array();
654
9bdcf579
DW
655 /**
656 * @var array $params URL Params
657 */
658 var $params;
659
660 /**
661 * @var string Action id
662 */
663 var $actionid;
664
3ba60ee1
PS
665 /**
666 * Constructor
9678c7b8 667 * @param moodle_url $url
3ba60ee1
PS
668 * @param string $label button text
669 * @param string $method get or post submit method
3ba60ee1
PS
670 */
671 public function __construct(moodle_url $url, $label, $method='post') {
672 $this->url = clone($url);
673 $this->label = $label;
674 $this->method = $method;
675 }
676
677 /**
574fbea4 678 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1 679 * The message must be a yes/no question.
9678c7b8 680 *
f8129210 681 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
3ba60ee1
PS
682 */
683 public function add_confirm_action($confirmmessage) {
8f78cd5a 684 $this->add_action(new confirm_action($confirmmessage));
3ba60ee1
PS
685 }
686
574fbea4
PS
687 /**
688 * Add action to the button.
689 * @param component_action $action
574fbea4 690 */
3ba60ee1
PS
691 public function add_action(component_action $action) {
692 $this->actions[] = $action;
693 }
694}
695
696
a9967cf5
PS
697/**
698 * Simple form with just one select field that gets submitted automatically.
f8129210 699 *
a9967cf5
PS
700 * If JS not enabled small go button is printed too.
701 *
702 * @copyright 2009 Petr Skoda
9678c7b8
SH
703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
704 * @since Moodle 2.0
f8129210 705 * @package core
76be40cc 706 * @category output
a9967cf5
PS
707 */
708class single_select implements renderable {
9678c7b8 709
a9967cf5 710 /**
76be40cc 711 * @var moodle_url Target url - includes hidden fields
a9967cf5
PS
712 */
713 var $url;
9678c7b8 714
a9967cf5 715 /**
76be40cc 716 * @var string Name of the select element.
a9967cf5
PS
717 */
718 var $name;
9678c7b8 719
a9967cf5 720 /**
9678c7b8
SH
721 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
722 * it is also possible to specify optgroup as complex label array ex.:
723 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
724 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
a9967cf5
PS
725 */
726 var $options;
9678c7b8 727
a9967cf5 728 /**
76be40cc 729 * @var string Selected option
a9967cf5
PS
730 */
731 var $selected;
9678c7b8 732
a9967cf5 733 /**
76be40cc 734 * @var array Nothing selected
a9967cf5
PS
735 */
736 var $nothing;
9678c7b8 737
a9967cf5 738 /**
76be40cc 739 * @var array Extra select field attributes
a9967cf5
PS
740 */
741 var $attributes = array();
9678c7b8 742
a9967cf5 743 /**
76be40cc 744 * @var string Button label
a9967cf5
PS
745 */
746 var $label = '';
9678c7b8 747
ecc5cc31 748 /**
de7a570c 749 * @var array Button label's attributes
ecc5cc31
RW
750 */
751 var $labelattributes = array();
752
a9967cf5 753 /**
76be40cc 754 * @var string Form submit method post or get
a9967cf5
PS
755 */
756 var $method = 'get';
9678c7b8 757
a9967cf5 758 /**
76be40cc
SH
759 * @var string Wrapping div class
760 */
a9967cf5 761 var $class = 'singleselect';
9678c7b8 762
a9967cf5 763 /**
3d3fae72 764 * @var bool True if button disabled, false if normal
a9967cf5
PS
765 */
766 var $disabled = false;
9678c7b8 767
a9967cf5 768 /**
76be40cc 769 * @var string Button tooltip
a9967cf5
PS
770 */
771 var $tooltip = null;
9678c7b8 772
a9967cf5 773 /**
76be40cc 774 * @var string Form id
a9967cf5
PS
775 */
776 var $formid = null;
9678c7b8 777
a9967cf5 778 /**
76be40cc 779 * @var array List of attached actions
a9967cf5
PS
780 */
781 var $helpicon = null;
9678c7b8 782
a9967cf5
PS
783 /**
784 * Constructor
785 * @param moodle_url $url form action target, includes hidden fields
786 * @param string $name name of selection field - the changing parameter in url
787 * @param array $options list of options
788 * @param string $selected selected element
789 * @param array $nothing
f8dab966 790 * @param string $formid
a9967cf5 791 */
9678c7b8 792 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
a9967cf5
PS
793 $this->url = $url;
794 $this->name = $name;
795 $this->options = $options;
796 $this->selected = $selected;
797 $this->nothing = $nothing;
f8dab966 798 $this->formid = $formid;
a9967cf5
PS
799 }
800
801 /**
802 * Shortcut for adding a JS confirm dialog when the button is clicked.
803 * The message must be a yes/no question.
9678c7b8 804 *
f8129210 805 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
a9967cf5
PS
806 */
807 public function add_confirm_action($confirmmessage) {
808 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
809 }
810
811 /**
812 * Add action to the button.
9678c7b8 813 *
a9967cf5 814 * @param component_action $action
a9967cf5
PS
815 */
816 public function add_action(component_action $action) {
817 $this->actions[] = $action;
818 }
f8dab966
PS
819
820 /**
259c165d 821 * Adds help icon.
9678c7b8 822 *
a6d81a73 823 * @deprecated since Moodle 2.0
f8dab966 824 */
596509e4 825 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
a6d81a73 826 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
f8dab966
PS
827 }
828
259c165d
PS
829 /**
830 * Adds help icon.
9678c7b8 831 *
259c165d
PS
832 * @param string $identifier The keyword that defines a help page
833 * @param string $component
259c165d
PS
834 */
835 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 836 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
837 }
838
f8dab966 839 /**
995f2d51 840 * Sets select's label
9678c7b8 841 *
f8dab966 842 * @param string $label
ecc5cc31 843 * @param array $attributes (optional)
f8dab966 844 */
ecc5cc31 845 public function set_label($label, $attributes = array()) {
f8dab966 846 $this->label = $label;
ecc5cc31
RW
847 $this->labelattributes = $attributes;
848
f8dab966 849 }
a9967cf5
PS
850}
851
4d10e579
PS
852/**
853 * Simple URL selection widget description.
9678c7b8 854 *
4d10e579 855 * @copyright 2009 Petr Skoda
9678c7b8
SH
856 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
857 * @since Moodle 2.0
f8129210 858 * @package core
76be40cc 859 * @category output
4d10e579
PS
860 */
861class url_select implements renderable {
862 /**
9678c7b8
SH
863 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
864 * it is also possible to specify optgroup as complex label array ex.:
865 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
866 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
4d10e579
PS
867 */
868 var $urls;
9678c7b8 869
4d10e579 870 /**
76be40cc 871 * @var string Selected option
4d10e579
PS
872 */
873 var $selected;
9678c7b8 874
4d10e579 875 /**
76be40cc 876 * @var array Nothing selected
4d10e579
PS
877 */
878 var $nothing;
9678c7b8 879
4d10e579 880 /**
76be40cc 881 * @var array Extra select field attributes
4d10e579
PS
882 */
883 var $attributes = array();
9678c7b8 884
4d10e579 885 /**
76be40cc 886 * @var string Button label
4d10e579
PS
887 */
888 var $label = '';
9678c7b8 889
ecc5cc31
RW
890 /**
891 * @var array Button label's attributes
892 */
893 var $labelattributes = array();
894
4d10e579 895 /**
76be40cc
SH
896 * @var string Wrapping div class
897 */
4d10e579 898 var $class = 'urlselect';
9678c7b8 899
4d10e579 900 /**
3d3fae72 901 * @var bool True if button disabled, false if normal
4d10e579
PS
902 */
903 var $disabled = false;
9678c7b8 904
4d10e579 905 /**
76be40cc 906 * @var string Button tooltip
4d10e579
PS
907 */
908 var $tooltip = null;
9678c7b8 909
4d10e579 910 /**
76be40cc 911 * @var string Form id
4d10e579
PS
912 */
913 var $formid = null;
9678c7b8 914
4d10e579 915 /**
76be40cc 916 * @var array List of attached actions
4d10e579
PS
917 */
918 var $helpicon = null;
9678c7b8 919
15e48a1a
SM
920 /**
921 * @var string If set, makes button visible with given name for button
922 */
923 var $showbutton = null;
9678c7b8 924
4d10e579
PS
925 /**
926 * Constructor
927 * @param array $urls list of options
928 * @param string $selected selected element
929 * @param array $nothing
930 * @param string $formid
15e48a1a
SM
931 * @param string $showbutton Set to text of button if it should be visible
932 * or null if it should be hidden (hidden version always has text 'go')
933 */
9678c7b8 934 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
15e48a1a
SM
935 $this->urls = $urls;
936 $this->selected = $selected;
937 $this->nothing = $nothing;
938 $this->formid = $formid;
939 $this->showbutton = $showbutton;
4d10e579
PS
940 }
941
942 /**
259c165d 943 * Adds help icon.
9678c7b8 944 *
a6d81a73 945 * @deprecated since Moodle 2.0
4d10e579 946 */
596509e4 947 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
a6d81a73 948 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
4d10e579
PS
949 }
950
259c165d
PS
951 /**
952 * Adds help icon.
9678c7b8 953 *
259c165d
PS
954 * @param string $identifier The keyword that defines a help page
955 * @param string $component
259c165d
PS
956 */
957 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 958 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
959 }
960
4d10e579 961 /**
995f2d51 962 * Sets select's label
9678c7b8 963 *
4d10e579 964 * @param string $label
ecc5cc31 965 * @param array $attributes (optional)
4d10e579 966 */
ecc5cc31 967 public function set_label($label, $attributes = array()) {
4d10e579 968 $this->label = $label;
ecc5cc31 969 $this->labelattributes = $attributes;
4d10e579
PS
970 }
971}
972
574fbea4
PS
973/**
974 * Data structure describing html link with special action attached.
9678c7b8 975 *
574fbea4 976 * @copyright 2010 Petr Skoda
9678c7b8
SH
977 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
978 * @since Moodle 2.0
f8129210 979 * @package core
76be40cc 980 * @category output
574fbea4
PS
981 */
982class action_link implements renderable {
9678c7b8 983
574fbea4 984 /**
76be40cc 985 * @var moodle_url Href url
574fbea4 986 */
ea5a01fb 987 public $url;
9678c7b8 988
574fbea4 989 /**
76be40cc 990 * @var string Link text HTML fragment
574fbea4 991 */
ea5a01fb 992 public $text;
9678c7b8 993
574fbea4 994 /**
76be40cc 995 * @var array HTML attributes
574fbea4 996 */
ea5a01fb 997 public $attributes;
9678c7b8 998
574fbea4 999 /**
76be40cc 1000 * @var array List of actions attached to link
574fbea4 1001 */
ea5a01fb 1002 public $actions;
574fbea4 1003
e282c679
SH
1004 /**
1005 * @var pix_icon Optional pix icon to render with the link
1006 */
ea5a01fb 1007 public $icon;
e282c679 1008
574fbea4
PS
1009 /**
1010 * Constructor
9678c7b8 1011 * @param moodle_url $url
574fbea4
PS
1012 * @param string $text HTML fragment
1013 * @param component_action $action
11820bac 1014 * @param array $attributes associative array of html link attributes + disabled
e282c679 1015 * @param pix_icon $icon optional pix_icon to render with the link text
574fbea4 1016 */
e282c679
SH
1017 public function __construct(moodle_url $url,
1018 $text,
1019 component_action $action=null,
1020 array $attributes=null,
1021 pix_icon $icon=null) {
9678c7b8
SH
1022 $this->url = clone($url);
1023 $this->text = $text;
b0fef57b 1024 $this->attributes = (array)$attributes;
f14b641b 1025 if ($action) {
574fbea4
PS
1026 $this->add_action($action);
1027 }
e282c679 1028 $this->icon = $icon;
574fbea4
PS
1029 }
1030
1031 /**
1032 * Add action to the link.
9678c7b8 1033 *
574fbea4 1034 * @param component_action $action
574fbea4
PS
1035 */
1036 public function add_action(component_action $action) {
1037 $this->actions[] = $action;
1038 }
c63923bd 1039
9678c7b8
SH
1040 /**
1041 * Adds a CSS class to this action link object
1042 * @param string $class
1043 */
c63923bd 1044 public function add_class($class) {
67da0bf7
DM
1045 if (empty($this->attributes['class'])) {
1046 $this->attributes['class'] = $class;
c63923bd 1047 } else {
67da0bf7 1048 $this->attributes['class'] .= ' ' . $class;
c63923bd
PS
1049 }
1050 }
e282c679
SH
1051
1052 /**
1053 * Returns true if the specified class has been added to this link.
1054 * @param string $class
1055 * @return bool
1056 */
1057 public function has_class($class) {
1058 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1059 }
574fbea4 1060}
3ba60ee1 1061
5d0c95a5
PS
1062/**
1063 * Simple html output class
9678c7b8 1064 *
5d0c95a5 1065 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
9678c7b8
SH
1066 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1067 * @since Moodle 2.0
f8129210 1068 * @package core
76be40cc 1069 * @category output
5d0c95a5
PS
1070 */
1071class html_writer {
9678c7b8 1072
5d0c95a5
PS
1073 /**
1074 * Outputs a tag with attributes and contents
9678c7b8 1075 *
5d0c95a5 1076 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
5d0c95a5 1077 * @param string $contents What goes between the opening and closing tags
26acc814 1078 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
5d0c95a5
PS
1079 * @return string HTML fragment
1080 */
26acc814 1081 public static function tag($tagname, $contents, array $attributes = null) {
5d0c95a5
PS
1082 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1083 }
1084
1085 /**
1086 * Outputs an opening tag with attributes
9678c7b8 1087 *
5d0c95a5
PS
1088 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1089 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1090 * @return string HTML fragment
1091 */
1092 public static function start_tag($tagname, array $attributes = null) {
1093 return '<' . $tagname . self::attributes($attributes) . '>';
1094 }
1095
1096 /**
1097 * Outputs a closing tag
9678c7b8 1098 *
5d0c95a5
PS
1099 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1100 * @return string HTML fragment
1101 */
1102 public static function end_tag($tagname) {
1103 return '</' . $tagname . '>';
1104 }
1105
1106 /**
1107 * Outputs an empty tag with attributes
9678c7b8 1108 *
5d0c95a5
PS
1109 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1110 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1111 * @return string HTML fragment
1112 */
1113 public static function empty_tag($tagname, array $attributes = null) {
1114 return '<' . $tagname . self::attributes($attributes) . ' />';
1115 }
1116
836c47d7
TH
1117 /**
1118 * Outputs a tag, but only if the contents are not empty
9678c7b8 1119 *
836c47d7
TH
1120 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1121 * @param string $contents What goes between the opening and closing tags
1122 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1123 * @return string HTML fragment
1124 */
1125 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1126 if ($contents === '' || is_null($contents)) {
1127 return '';
1128 }
1129 return self::tag($tagname, $contents, $attributes);
1130 }
1131
5d0c95a5
PS
1132 /**
1133 * Outputs a HTML attribute and value
9678c7b8 1134 *
5d0c95a5
PS
1135 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1136 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1137 * @return string HTML fragment
1138 */
1139 public static function attribute($name, $value) {
bf11293a
PS
1140 if ($value instanceof moodle_url) {
1141 return ' ' . $name . '="' . $value->out() . '"';
1142 }
97c10099
PS
1143
1144 // special case, we do not want these in output
1145 if ($value === null) {
1146 return '';
5d0c95a5 1147 }
97c10099
PS
1148
1149 // no sloppy trimming here!
1150 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
1151 }
1152
1153 /**
1154 * Outputs a list of HTML attributes and values
9678c7b8 1155 *
5d0c95a5
PS
1156 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1157 * The values will be escaped with {@link s()}
1158 * @return string HTML fragment
1159 */
1160 public static function attributes(array $attributes = null) {
1161 $attributes = (array)$attributes;
1162 $output = '';
1163 foreach ($attributes as $name => $value) {
1164 $output .= self::attribute($name, $value);
1165 }
1166 return $output;
1167 }
1168
7b218e86 1169 /**
1170 * Generates a simple image tag with attributes.
1171 *
1172 * @param string $src The source of image
1173 * @param string $alt The alternate text for image
1174 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1175 * @return string HTML fragment
1176 */
1177 public static function img($src, $alt, array $attributes = null) {
1178 $attributes = (array)$attributes;
1179 $attributes['src'] = $src;
1180 $attributes['alt'] = $alt;
1181
1182 return self::empty_tag('img', $attributes);
1183 }
1184
5d0c95a5
PS
1185 /**
1186 * Generates random html element id.
9678c7b8
SH
1187 *
1188 * @staticvar int $counter
1189 * @staticvar type $uniq
3d3fae72
SH
1190 * @param string $base A string fragment that will be included in the random ID.
1191 * @return string A unique ID
5d0c95a5
PS
1192 */
1193 public static function random_id($base='random') {
2c479c8f
PS
1194 static $counter = 0;
1195 static $uniq;
1196
1197 if (!isset($uniq)) {
1198 $uniq = uniqid();
1199 }
1200
1201 $counter++;
1202 return $base.$uniq.$counter;
5d0c95a5 1203 }
0f4c64b7
PS
1204
1205 /**
1206 * Generates a simple html link
9678c7b8 1207 *
3d3fae72
SH
1208 * @param string|moodle_url $url The URL
1209 * @param string $text The text
1210 * @param array $attributes HTML attributes
0f4c64b7
PS
1211 * @return string HTML fragment
1212 */
1213 public static function link($url, $text, array $attributes = null) {
1214 $attributes = (array)$attributes;
1215 $attributes['href'] = $url;
26acc814 1216 return self::tag('a', $text, $attributes);
0f4c64b7 1217 }
3ff163c5 1218
14dce022 1219 /**
9678c7b8
SH
1220 * Generates a simple checkbox with optional label
1221 *
3d3fae72
SH
1222 * @param string $name The name of the checkbox
1223 * @param string $value The value of the checkbox
1224 * @param bool $checked Whether the checkbox is checked
1225 * @param string $label The label for the checkbox
1226 * @param array $attributes Any attributes to apply to the checkbox
14dce022
PS
1227 * @return string html fragment
1228 */
1229 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1230 $attributes = (array)$attributes;
1231 $output = '';
1232
1233 if ($label !== '' and !is_null($label)) {
1234 if (empty($attributes['id'])) {
1235 $attributes['id'] = self::random_id('checkbox_');
1236 }
1237 }
53868425
PS
1238 $attributes['type'] = 'checkbox';
1239 $attributes['value'] = $value;
1240 $attributes['name'] = $name;
621b4d08 1241 $attributes['checked'] = $checked ? 'checked' : null;
53868425 1242
14dce022
PS
1243 $output .= self::empty_tag('input', $attributes);
1244
1245 if ($label !== '' and !is_null($label)) {
26acc814 1246 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
14dce022
PS
1247 }
1248
1249 return $output;
1250 }
1251
78bdac64
PS
1252 /**
1253 * Generates a simple select yes/no form field
9678c7b8 1254 *
78bdac64
PS
1255 * @param string $name name of select element
1256 * @param bool $selected
1257 * @param array $attributes - html select element attributes
9678c7b8 1258 * @return string HTML fragment
78bdac64 1259 */
19f3bbb2 1260 public static function select_yes_no($name, $selected=true, array $attributes = null) {
78bdac64
PS
1261 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1262 return self::select($options, $name, $selected, null, $attributes);
1263 }
1264
3ff163c5
PS
1265 /**
1266 * Generates a simple select form field
9678c7b8 1267 *
6770330d
PS
1268 * @param array $options associative array value=>label ex.:
1269 * array(1=>'One, 2=>Two)
1270 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 1271 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 1272 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5 1273 * @param string $name name of select element
1a10840e 1274 * @param string|array $selected value or array of values depending on multiple attribute
f8129210
SH
1275 * @param array|bool $nothing add nothing selected option, or false of not added
1276 * @param array $attributes html select element attributes
78bdac64 1277 * @return string HTML fragment
3ff163c5 1278 */
9678c7b8 1279 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
3ff163c5
PS
1280 $attributes = (array)$attributes;
1281 if (is_array($nothing)) {
1282 foreach ($nothing as $k=>$v) {
4b9210f3 1283 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
1284 $nothing[$k] = get_string('choosedots');
1285 }
1286 }
1287 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
1288
1289 } else if (is_string($nothing) and $nothing !== '') {
1290 // BC
1291 $options = array(''=>$nothing) + $options;
bde156b3 1292 }
3ff163c5
PS
1293
1294 // we may accept more values if multiple attribute specified
1295 $selected = (array)$selected;
1296 foreach ($selected as $k=>$v) {
1297 $selected[$k] = (string)$v;
1298 }
1299
1300 if (!isset($attributes['id'])) {
1301 $id = 'menu'.$name;
1302 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1303 $id = str_replace('[', '', $id);
1304 $id = str_replace(']', '', $id);
1305 $attributes['id'] = $id;
1306 }
1307
1308 if (!isset($attributes['class'])) {
1309 $class = 'menu'.$name;
1310 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1311 $class = str_replace('[', '', $class);
1312 $class = str_replace(']', '', $class);
1313 $attributes['class'] = $class;
1314 }
f8129210 1315 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
3ff163c5
PS
1316
1317 $attributes['name'] = $name;
1318
1a09fa6d
TH
1319 if (!empty($attributes['disabled'])) {
1320 $attributes['disabled'] = 'disabled';
1321 } else {
1322 unset($attributes['disabled']);
1323 }
1324
3ff163c5
PS
1325 $output = '';
1326 foreach ($options as $value=>$label) {
6770330d
PS
1327 if (is_array($label)) {
1328 // ignore key, it just has to be unique
1329 $output .= self::select_optgroup(key($label), current($label), $selected);
1330 } else {
1331 $output .= self::select_option($label, $value, $selected);
3ff163c5 1332 }
3ff163c5 1333 }
26acc814 1334 return self::tag('select', $output, $attributes);
3ff163c5 1335 }
6770330d 1336
9678c7b8
SH
1337 /**
1338 * Returns HTML to display a select box option.
1339 *
1340 * @param string $label The label to display as the option.
1341 * @param string|int $value The value the option represents
1342 * @param array $selected An array of selected options
1343 * @return string HTML fragment
1344 */
6770330d
PS
1345 private static function select_option($label, $value, array $selected) {
1346 $attributes = array();
1347 $value = (string)$value;
1348 if (in_array($value, $selected, true)) {
1349 $attributes['selected'] = 'selected';
1350 }
1351 $attributes['value'] = $value;
26acc814 1352 return self::tag('option', $label, $attributes);
6770330d
PS
1353 }
1354
9678c7b8
SH
1355 /**
1356 * Returns HTML to display a select box option group.
1357 *
1358 * @param string $groupname The label to use for the group
1359 * @param array $options The options in the group
1360 * @param array $selected An array of selected values.
1361 * @return string HTML fragment.
1362 */
6770330d
PS
1363 private static function select_optgroup($groupname, $options, array $selected) {
1364 if (empty($options)) {
1365 return '';
1366 }
1367 $attributes = array('label'=>$groupname);
1368 $output = '';
1369 foreach ($options as $value=>$label) {
1370 $output .= self::select_option($label, $value, $selected);
1371 }
26acc814 1372 return self::tag('optgroup', $output, $attributes);
6770330d 1373 }
6ea66ff3 1374
f83b9b63
PS
1375 /**
1376 * This is a shortcut for making an hour selector menu.
9678c7b8 1377 *
f83b9b63
PS
1378 * @param string $type The type of selector (years, months, days, hours, minutes)
1379 * @param string $name fieldname
1380 * @param int $currenttime A default timestamp in GMT
1381 * @param int $step minute spacing
1382 * @param array $attributes - html select element attributes
1383 * @return HTML fragment
1384 */
9678c7b8 1385 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
f83b9b63
PS
1386 if (!$currenttime) {
1387 $currenttime = time();
1388 }
1389 $currentdate = usergetdate($currenttime);
1390 $userdatetype = $type;
1391 $timeunits = array();
1392
1393 switch ($type) {
1394 case 'years':
1395 for ($i=1970; $i<=2020; $i++) {
1396 $timeunits[$i] = $i;
1397 }
1398 $userdatetype = 'year';
1399 break;
1400 case 'months':
1401 for ($i=1; $i<=12; $i++) {
1402 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1403 }
1404 $userdatetype = 'month';
0387e003 1405 $currentdate['month'] = (int)$currentdate['mon'];
f83b9b63
PS
1406 break;
1407 case 'days':
1408 for ($i=1; $i<=31; $i++) {
1409 $timeunits[$i] = $i;
1410 }
1411 $userdatetype = 'mday';
1412 break;
1413 case 'hours':
1414 for ($i=0; $i<=23; $i++) {
1415 $timeunits[$i] = sprintf("%02d",$i);
1416 }
1417 break;
1418 case 'minutes':
1419 if ($step != 1) {
1420 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1421 }
1422
1423 for ($i=0; $i<=59; $i+=$step) {
1424 $timeunits[$i] = sprintf("%02d",$i);
1425 }
1426 break;
1427 default:
1428 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1429 }
1430
1431 if (empty($attributes['id'])) {
1432 $attributes['id'] = self::random_id('ts_');
1433 }
db282ba4 1434 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes);
26acc814 1435 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
f83b9b63
PS
1436
1437 return $label.$timerselector;
1438 }
1439
5be262b6
PS
1440 /**
1441 * Shortcut for quick making of lists
9678c7b8
SH
1442 *
1443 * Note: 'list' is a reserved keyword ;-)
1444 *
5be262b6 1445 * @param array $items
5be262b6 1446 * @param array $attributes
9678c7b8 1447 * @param string $tag ul or ol
5be262b6
PS
1448 * @return string
1449 */
1450 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
b69a3f1c 1451 $output = html_writer::start_tag($tag, $attributes)."\n";
5be262b6 1452 foreach ($items as $item) {
b69a3f1c 1453 $output .= html_writer::tag('li', $item)."\n";
5be262b6 1454 }
b69a3f1c
SH
1455 $output .= html_writer::end_tag($tag);
1456 return $output;
5be262b6
PS
1457 }
1458
6ea66ff3
PS
1459 /**
1460 * Returns hidden input fields created from url parameters.
9678c7b8 1461 *
6ea66ff3
PS
1462 * @param moodle_url $url
1463 * @param array $exclude list of excluded parameters
1464 * @return string HTML fragment
1465 */
1466 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1467 $exclude = (array)$exclude;
1468 $params = $url->params();
1469 foreach ($exclude as $key) {
1470 unset($params[$key]);
1471 }
1472
1473 $output = '';
bde156b3 1474 foreach ($params as $key => $value) {
6ea66ff3
PS
1475 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1476 $output .= self::empty_tag('input', $attributes)."\n";
1477 }
1478 return $output;
1479 }
77774f6a
PS
1480
1481 /**
1482 * Generate a script tag containing the the specified code.
1483 *
f8129210
SH
1484 * @param string $jscode the JavaScript code
1485 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
77774f6a
PS
1486 * @return string HTML, the code wrapped in <script> tags.
1487 */
e50b4c89 1488 public static function script($jscode, $url=null) {
77774f6a 1489 if ($jscode) {
e50b4c89 1490 $attributes = array('type'=>'text/javascript');
26acc814 1491 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
e50b4c89
PS
1492
1493 } else if ($url) {
1494 $attributes = array('type'=>'text/javascript', 'src'=>$url);
26acc814 1495 return self::tag('script', '', $attributes) . "\n";
a9967cf5 1496
77774f6a
PS
1497 } else {
1498 return '';
1499 }
1500 }
16be8974
DM
1501
1502 /**
1503 * Renders HTML table
1504 *
1505 * This method may modify the passed instance by adding some default properties if they are not set yet.
1506 * If this is not what you want, you should make a full clone of your data before passing them to this
1507 * method. In most cases this is not an issue at all so we do not clone by default for performance
1508 * and memory consumption reasons.
1509 *
1510 * @param html_table $table data to be rendered
1511 * @return string HTML code
1512 */
1513 public static function table(html_table $table) {
1514 // prepare table data and populate missing properties with reasonable defaults
1515 if (!empty($table->align)) {
1516 foreach ($table->align as $key => $aa) {
1517 if ($aa) {
1518 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1519 } else {
1520 $table->align[$key] = null;
1521 }
1522 }
1523 }
1524 if (!empty($table->size)) {
1525 foreach ($table->size as $key => $ss) {
1526 if ($ss) {
1527 $table->size[$key] = 'width:'. $ss .';';
1528 } else {
1529 $table->size[$key] = null;
1530 }
1531 }
1532 }
1533 if (!empty($table->wrap)) {
1534 foreach ($table->wrap as $key => $ww) {
1535 if ($ww) {
1536 $table->wrap[$key] = 'white-space:nowrap;';
1537 } else {
1538 $table->wrap[$key] = '';
1539 }
1540 }
1541 }
1542 if (!empty($table->head)) {
1543 foreach ($table->head as $key => $val) {
1544 if (!isset($table->align[$key])) {
1545 $table->align[$key] = null;
1546 }
1547 if (!isset($table->size[$key])) {
1548 $table->size[$key] = null;
1549 }
1550 if (!isset($table->wrap[$key])) {
1551 $table->wrap[$key] = null;
1552 }
1553
1554 }
1555 }
1556 if (empty($table->attributes['class'])) {
1557 $table->attributes['class'] = 'generaltable';
1558 }
1559 if (!empty($table->tablealign)) {
1560 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1561 }
1562
1563 // explicitly assigned properties override those defined via $table->attributes
e126c0cc 1564 $table->attributes['class'] = trim($table->attributes['class']);
16be8974
DM
1565 $attributes = array_merge($table->attributes, array(
1566 'id' => $table->id,
1567 'width' => $table->width,
1568 'summary' => $table->summary,
1569 'cellpadding' => $table->cellpadding,
1570 'cellspacing' => $table->cellspacing,
1571 ));
1572 $output = html_writer::start_tag('table', $attributes) . "\n";
1573
1574 $countcols = 0;
1575
3451a51c
JC
1576 // Output a caption if present.
1577 if (!empty($table->caption)) {
1578 $captionattributes = array();
1579 if ($table->captionhide) {
1580 $captionattributes['class'] = 'accesshide';
1581 }
1582 $output .= html_writer::tag(
1583 'caption',
1584 $table->caption,
1585 $captionattributes
1586 );
1587 }
1588
16be8974
DM
1589 if (!empty($table->head)) {
1590 $countcols = count($table->head);
5174f3c5 1591
16be8974
DM
1592 $output .= html_writer::start_tag('thead', array()) . "\n";
1593 $output .= html_writer::start_tag('tr', array()) . "\n";
1594 $keys = array_keys($table->head);
1595 $lastkey = end($keys);
1596
1597 foreach ($table->head as $key => $heading) {
1598 // Convert plain string headings into html_table_cell objects
1599 if (!($heading instanceof html_table_cell)) {
1600 $headingtext = $heading;
1601 $heading = new html_table_cell();
1602 $heading->text = $headingtext;
1603 $heading->header = true;
1604 }
1605
1606 if ($heading->header !== false) {
1607 $heading->header = true;
1608 }
1609
e126c0cc
DM
1610 if ($heading->header && empty($heading->scope)) {
1611 $heading->scope = 'col';
1612 }
1613
16be8974
DM
1614 $heading->attributes['class'] .= ' header c' . $key;
1615 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1616 $heading->colspan = $table->headspan[$key];
1617 $countcols += $table->headspan[$key] - 1;
1618 }
1619
1620 if ($key == $lastkey) {
1621 $heading->attributes['class'] .= ' lastcol';
1622 }
1623 if (isset($table->colclasses[$key])) {
1624 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1625 }
e126c0cc 1626 $heading->attributes['class'] = trim($heading->attributes['class']);
16be8974
DM
1627 $attributes = array_merge($heading->attributes, array(
1628 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1629 'scope' => $heading->scope,
1630 'colspan' => $heading->colspan,
1631 ));
1632
1633 $tagtype = 'td';
1634 if ($heading->header === true) {
1635 $tagtype = 'th';
1636 }
1637 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1638 }
1639 $output .= html_writer::end_tag('tr') . "\n";
1640 $output .= html_writer::end_tag('thead') . "\n";
1641
1642 if (empty($table->data)) {
1643 // For valid XHTML strict every table must contain either a valid tr
1644 // or a valid tbody... both of which must contain a valid td
1645 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1646 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1647 $output .= html_writer::end_tag('tbody');
1648 }
1649 }
1650
1651 if (!empty($table->data)) {
16be8974
DM
1652 $keys = array_keys($table->data);
1653 $lastrowkey = end($keys);
1654 $output .= html_writer::start_tag('tbody', array());
1655
1656 foreach ($table->data as $key => $row) {
1657 if (($row === 'hr') && ($countcols)) {
1658 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1659 } else {
1660 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1661 if (!($row instanceof html_table_row)) {
1662 $newrow = new html_table_row();
1663
4954d6ed
FM
1664 foreach ($row as $cell) {
1665 if (!($cell instanceof html_table_cell)) {
1666 $cell = new html_table_cell($cell);
1667 }
16be8974
DM
1668 $newrow->cells[] = $cell;
1669 }
1670 $row = $newrow;
1671 }
1672
16be8974
DM
1673 if (isset($table->rowclasses[$key])) {
1674 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1675 }
1676
16be8974
DM
1677 if ($key == $lastrowkey) {
1678 $row->attributes['class'] .= ' lastrow';
1679 }
1680
7dfaa3ae
AN
1681 // Explicitly assigned properties should override those defined in the attributes.
1682 $row->attributes['class'] = trim($row->attributes['class']);
1683 $trattributes = array_merge($row->attributes, array(
1684 'id' => $row->id,
1685 'style' => $row->style,
1686 ));
1687 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
16be8974
DM
1688 $keys2 = array_keys($row->cells);
1689 $lastkey = end($keys2);
1690
5174f3c5 1691 $gotlastkey = false; //flag for sanity checking
16be8974 1692 foreach ($row->cells as $key => $cell) {
5174f3c5
AD
1693 if ($gotlastkey) {
1694 //This should never happen. Why do we have a cell after the last cell?
1695 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1696 }
1697
16be8974
DM
1698 if (!($cell instanceof html_table_cell)) {
1699 $mycell = new html_table_cell();
1700 $mycell->text = $cell;
1701 $cell = $mycell;
1702 }
1703
e126c0cc
DM
1704 if (($cell->header === true) && empty($cell->scope)) {
1705 $cell->scope = 'row';
1706 }
1707
16be8974
DM
1708 if (isset($table->colclasses[$key])) {
1709 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1710 }
1711
1712 $cell->attributes['class'] .= ' cell c' . $key;
1713 if ($key == $lastkey) {
1714 $cell->attributes['class'] .= ' lastcol';
5174f3c5 1715 $gotlastkey = true;
16be8974
DM
1716 }
1717 $tdstyle = '';
1718 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1719 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1720 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1721 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1722 $tdattributes = array_merge($cell->attributes, array(
1723 'style' => $tdstyle . $cell->style,
1724 'colspan' => $cell->colspan,
1725 'rowspan' => $cell->rowspan,
1726 'id' => $cell->id,
1727 'abbr' => $cell->abbr,
1728 'scope' => $cell->scope,
1729 ));
1730 $tagtype = 'td';
1731 if ($cell->header === true) {
1732 $tagtype = 'th';
1733 }
1734 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1735 }
1736 }
1737 $output .= html_writer::end_tag('tr') . "\n";
1738 }
1739 $output .= html_writer::end_tag('tbody') . "\n";
1740 }
1741 $output .= html_writer::end_tag('table') . "\n";
1742
1743 return $output;
1744 }
1745
995f2d51
DM
1746 /**
1747 * Renders form element label
1748 *
1749 * By default, the label is suffixed with a label separator defined in the
1750 * current language pack (colon by default in the English lang pack).
1751 * Adding the colon can be explicitly disabled if needed. Label separators
1752 * are put outside the label tag itself so they are not read by
1753 * screenreaders (accessibility).
1754 *
1755 * Parameter $for explicitly associates the label with a form control. When
1756 * set, the value of this attribute must be the same as the value of
1757 * the id attribute of the form control in the same document. When null,
1758 * the label being defined is associated with the control inside the label
1759 * element.
1760 *
1761 * @param string $text content of the label tag
1762 * @param string|null $for id of the element this label is associated with, null for no association
1763 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1764 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1765 * @return string HTML of the label element
1766 */
9678c7b8 1767 public static function label($text, $for, $colonize = true, array $attributes=array()) {
995f2d51
DM
1768 if (!is_null($for)) {
1769 $attributes = array_merge($attributes, array('for' => $for));
1770 }
1771 $text = trim($text);
1772 $label = self::tag('label', $text, $attributes);
1773
9678c7b8
SH
1774 // TODO MDL-12192 $colonize disabled for now yet
1775 // if (!empty($text) and $colonize) {
1776 // // the $text may end with the colon already, though it is bad string definition style
1777 // $colon = get_string('labelsep', 'langconfig');
1778 // if (!empty($colon)) {
1779 // $trimmed = trim($colon);
1780 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1781 // //debugging('The label text should not end with colon or other label separator,
1782 // // please fix the string definition.', DEBUG_DEVELOPER);
1783 // } else {
1784 // $label .= $colon;
1785 // }
1786 // }
1787 // }
995f2d51
DM
1788
1789 return $label;
1790 }
4c4e5876 1791
1792 /**
1793 * Combines a class parameter with other attributes. Aids in code reduction
1794 * because the class parameter is very frequently used.
1795 *
1796 * If the class attribute is specified both in the attributes and in the
1797 * class parameter, the two values are combined with a space between.
1798 *
1799 * @param string $class Optional CSS class (or classes as space-separated list)
1800 * @param array $attributes Optional other attributes as array
1801 * @return array Attributes (or null if still none)
1802 */
1803 private static function add_class($class = '', array $attributes = null) {
1804 if ($class !== '') {
1805 $classattribute = array('class' => $class);
1806 if ($attributes) {
1807 if (array_key_exists('class', $attributes)) {
1808 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1809 } else {
1810 $attributes = $classattribute + $attributes;
1811 }
1812 } else {
1813 $attributes = $classattribute;
1814 }
1815 }
1816 return $attributes;
1817 }
1818
1819 /**
1820 * Creates a <div> tag. (Shortcut function.)
1821 *
1822 * @param string $content HTML content of tag
1823 * @param string $class Optional CSS class (or classes as space-separated list)
1824 * @param array $attributes Optional other attributes as array
1825 * @return string HTML code for div
1826 */
1827 public static function div($content, $class = '', array $attributes = null) {
1828 return self::tag('div', $content, self::add_class($class, $attributes));
1829 }
1830
1831 /**
1832 * Starts a <div> tag. (Shortcut function.)
1833 *
1834 * @param string $class Optional CSS class (or classes as space-separated list)
1835 * @param array $attributes Optional other attributes as array
1836 * @return string HTML code for open div tag
1837 */
1838 public static function start_div($class = '', array $attributes = null) {
1839 return self::start_tag('div', self::add_class($class, $attributes));
1840 }
1841
1842 /**
1843 * Ends a <div> tag. (Shortcut function.)
1844 *
1845 * @return string HTML code for close div tag
1846 */
1847 public static function end_div() {
1848 return self::end_tag('div');
1849 }
1850
1851 /**
1852 * Creates a <span> tag. (Shortcut function.)
1853 *
1854 * @param string $content HTML content of tag
1855 * @param string $class Optional CSS class (or classes as space-separated list)
1856 * @param array $attributes Optional other attributes as array
1857 * @return string HTML code for span
1858 */
1859 public static function span($content, $class = '', array $attributes = null) {
1860 return self::tag('span', $content, self::add_class($class, $attributes));
1861 }
1862
1863 /**
1864 * Starts a <span> tag. (Shortcut function.)
1865 *
1866 * @param string $class Optional CSS class (or classes as space-separated list)
1867 * @param array $attributes Optional other attributes as array
1868 * @return string HTML code for open span tag
1869 */
1870 public static function start_span($class = '', array $attributes = null) {
1871 return self::start_tag('span', self::add_class($class, $attributes));
1872 }
1873
1874 /**
1875 * Ends a <span> tag. (Shortcut function.)
1876 *
1877 * @return string HTML code for close span tag
1878 */
1879 public static function end_span() {
1880 return self::end_tag('span');
1881 }
5d0c95a5
PS
1882}
1883
227255b8
PS
1884/**
1885 * Simple javascript output class
9678c7b8 1886 *
227255b8 1887 * @copyright 2010 Petr Skoda
9678c7b8
SH
1888 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1889 * @since Moodle 2.0
f8129210 1890 * @package core
76be40cc 1891 * @category output
227255b8
PS
1892 */
1893class js_writer {
9678c7b8 1894
227255b8
PS
1895 /**
1896 * Returns javascript code calling the function
9678c7b8 1897 *
1a10840e 1898 * @param string $function function name, can be complex like Y.Event.purgeElement
227255b8
PS
1899 * @param array $arguments parameters
1900 * @param int $delay execution delay in seconds
1901 * @return string JS code fragment
1902 */
e839dce1 1903 public static function function_call($function, array $arguments = null, $delay=0) {
1b4e41af 1904 if ($arguments) {
b2cb00c2 1905 $arguments = array_map('json_encode', convert_to_array($arguments));
1b4e41af
PS
1906 $arguments = implode(', ', $arguments);
1907 } else {
1908 $arguments = '';
1909 }
227255b8
PS
1910 $js = "$function($arguments);";
1911
1912 if ($delay) {
1913 $delay = $delay * 1000; // in miliseconds
1914 $js = "setTimeout(function() { $js }, $delay);";
1915 }
1916 return $js . "\n";
1917 }
1918
3b01539c 1919 /**
3d3fae72 1920 * Special function which adds Y as first argument of function call.
9678c7b8 1921 *
3d3fae72
SH
1922 * @param string $function The function to call
1923 * @param array $extraarguments Any arguments to pass to it
1924 * @return string Some JS code
3b01539c 1925 */
e839dce1 1926 public static function function_call_with_Y($function, array $extraarguments = null) {
3b01539c 1927 if ($extraarguments) {
b2cb00c2 1928 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
3b01539c
PS
1929 $arguments = 'Y, ' . implode(', ', $extraarguments);
1930 } else {
1931 $arguments = 'Y';
1932 }
1933 return "$function($arguments);\n";
1934 }
1935
1ce15fda
SH
1936 /**
1937 * Returns JavaScript code to initialise a new object
9678c7b8 1938 *
3d3fae72
SH
1939 * @param string $var If it is null then no var is assigned the new object.
1940 * @param string $class The class to initialise an object for.
1941 * @param array $arguments An array of args to pass to the init method.
1942 * @param array $requirements Any modules required for this class.
1943 * @param int $delay The delay before initialisation. 0 = no delay.
1944 * @return string Some JS code
1ce15fda 1945 */
e839dce1 1946 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1ce15fda 1947 if (is_array($arguments)) {
b2cb00c2 1948 $arguments = array_map('json_encode', convert_to_array($arguments));
1ce15fda
SH
1949 $arguments = implode(', ', $arguments);
1950 }
1951
1952 if ($var === null) {
53fc3e70 1953 $js = "new $class(Y, $arguments);";
1ce15fda 1954 } else if (strpos($var, '.')!==false) {
53fc3e70 1955 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1956 } else {
53fc3e70 1957 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1958 }
1959
1960 if ($delay) {
1961 $delay = $delay * 1000; // in miliseconds
1962 $js = "setTimeout(function() { $js }, $delay);";
1963 }
1964
1965 if (count($requirements) > 0) {
1966 $requirements = implode("', '", $requirements);
53fc3e70 1967 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1968 }
1969 return $js."\n";
1970 }
1971
227255b8
PS
1972 /**
1973 * Returns code setting value to variable
9678c7b8 1974 *
227255b8
PS
1975 * @param string $name
1976 * @param mixed $value json serialised value
1977 * @param bool $usevar add var definition, ignored for nested properties
1978 * @return string JS code fragment
1979 */
9678c7b8 1980 public static function set_variable($name, $value, $usevar = true) {
227255b8
PS
1981 $output = '';
1982
1983 if ($usevar) {
1984 if (strpos($name, '.')) {
1985 $output .= '';
1986 } else {
1987 $output .= 'var ';
1988 }
1989 }
1990
1991 $output .= "$name = ".json_encode($value).";";
1992
1993 return $output;
1994 }
1995
1996 /**
1997 * Writes event handler attaching code
9678c7b8 1998 *
f8129210
SH
1999 * @param array|string $selector standard YUI selector for elements, may be
2000 * array or string, element id is in the form "#idvalue"
227255b8
PS
2001 * @param string $event A valid DOM event (click, mousedown, change etc.)
2002 * @param string $function The name of the function to call
9678c7b8 2003 * @param array $arguments An optional array of argument parameters to pass to the function
227255b8
PS
2004 * @return string JS code fragment
2005 */
e839dce1 2006 public static function event_handler($selector, $event, $function, array $arguments = null) {
227255b8
PS
2007 $selector = json_encode($selector);
2008 $output = "Y.on('$event', $function, $selector, null";
2009 if (!empty($arguments)) {
2010 $output .= ', ' . json_encode($arguments);
2011 }
2012 return $output . ");\n";
2013 }
2014}
2015
d9c8f425 2016/**
f8129210 2017 * Holds all the information required to render a <table> by {@link core_renderer::table()}
d9c8f425 2018 *
16be8974
DM
2019 * Example of usage:
2020 * $t = new html_table();
2021 * ... // set various properties of the object $t as described below
2022 * echo html_writer::table($t);
d9c8f425 2023 *
16be8974 2024 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
9678c7b8
SH
2025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2026 * @since Moodle 2.0
f8129210 2027 * @package core
76be40cc 2028 * @category output
d9c8f425 2029 */
16be8974 2030class html_table {
9678c7b8 2031
d9c8f425 2032 /**
76be40cc 2033 * @var string Value to use for the id attribute of the table
d9c8f425 2034 */
97c10099 2035 public $id = null;
9678c7b8 2036
d9c8f425 2037 /**
76be40cc 2038 * @var array Attributes of HTML attributes for the <table> element
d9c8f425 2039 */
16be8974 2040 public $attributes = array();
9678c7b8 2041
7b1f2c82 2042 /**
76be40cc 2043 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
a0ead5eb 2044 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 2045 * can be passed instead of an array of strings.
7b1f2c82 2046 *
2047 * Example of usage:
2048 * $t->head = array('Student', 'Grade');
2049 */
2050 public $head;
9678c7b8 2051
7b1f2c82 2052 /**
76be40cc 2053 * @var array An array that can be used to make a heading span multiple columns.
f8129210
SH
2054 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2055 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
7b1f2c82 2056 *
2057 * Example of usage:
2058 * $t->headspan = array(2,1);
7b1f2c82 2059 */
2060 public $headspan;
9678c7b8 2061
7b1f2c82 2062 /**
76be40cc 2063 * @var array An array of column alignments.
9678c7b8 2064 * The value is used as CSS 'text-align' property. Therefore, possible
7b1f2c82 2065 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2066 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2067 *
beb56299 2068 * Examples of usage:
2069 * $t->align = array(null, 'right');
2070 * or
2071 * $t->align[1] = 'right';
d9c8f425 2072 */
beb56299 2073 public $align;
9678c7b8 2074
d9c8f425 2075 /**
76be40cc 2076 * @var array The value is used as CSS 'size' property.
beb56299 2077 *
2078 * Examples of usage:
2079 * $t->size = array('50%', '50%');
2080 * or
2081 * $t->size[1] = '120px';
d9c8f425 2082 */
beb56299 2083 public $size;
9678c7b8 2084
d9c8f425 2085 /**
76be40cc 2086 * @var array An array of wrapping information.
9678c7b8 2087 * The only possible value is 'nowrap' that sets the
beb56299 2088 * CSS property 'white-space' to the value 'nowrap' in the given column.
2089 *
2090 * Example of usage:
2091 * $t->wrap = array(null, 'nowrap');
d9c8f425 2092 */
beb56299 2093 public $wrap;
9678c7b8 2094
d9c8f425 2095 /**
76be40cc 2096 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
beb56299 2097 * $head specified, the string 'hr' (for horizontal ruler) can be used
2098 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 2099 *
beb56299 2100 * Example of usage with array of arrays:
2101 * $row1 = array('Harry Potter', '76 %');
2102 * $row2 = array('Hermione Granger', '100 %');
2103 * $t->data = array($row1, $row2);
d9c8f425 2104 *
beb56299 2105 * Example with array of html_table_row objects: (used for more fine-grained control)
2106 * $cell1 = new html_table_cell();
2107 * $cell1->text = 'Harry Potter';
2108 * $cell1->colspan = 2;
2109 * $row1 = new html_table_row();
2110 * $row1->cells[] = $cell1;
2111 * $cell2 = new html_table_cell();
2112 * $cell2->text = 'Hermione Granger';
2113 * $cell3 = new html_table_cell();
2114 * $cell3->text = '100 %';
2115 * $row2 = new html_table_row();
2116 * $row2->cells = array($cell2, $cell3);
2117 * $t->data = array($row1, $row2);
2118 */
2119 public $data;
9678c7b8 2120
beb56299 2121 /**
beb56299 2122 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 2123 * @var string Width of the table, percentage of the page preferred.
beb56299 2124 */
2125 public $width = null;
9678c7b8 2126
beb56299 2127 /**
beb56299 2128 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 2129 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
beb56299 2130 */
2131 public $tablealign = null;
9678c7b8 2132
beb56299 2133 /**
beb56299 2134 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 2135 * @var int Padding on each cell, in pixels
beb56299 2136 */
2137 public $cellpadding = null;
9678c7b8 2138
beb56299 2139 /**
76be40cc 2140 * @var int Spacing between cells, in pixels
beb56299 2141 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2142 */
2143 public $cellspacing = null;
9678c7b8 2144
beb56299 2145 /**
76be40cc 2146 * @var array Array of classes to add to particular rows, space-separated string.
ba55be91 2147 * Class 'lastrow' is added automatically for the last row in the table.
d9c8f425 2148 *
beb56299 2149 * Example of usage:
2150 * $t->rowclasses[9] = 'tenth'
2151 */
2152 public $rowclasses;
9678c7b8 2153
beb56299 2154 /**
76be40cc 2155 * @var array An array of classes to add to every cell in a particular column,
beb56299 2156 * space-separated string. Class 'cell' is added automatically by the renderer.
2157 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2158 * respectively. Class 'lastcol' is added automatically for all last cells
2159 * in a row.
d9c8f425 2160 *
beb56299 2161 * Example of usage:
2162 * $t->colclasses = array(null, 'grade');
d9c8f425 2163 */
beb56299 2164 public $colclasses;
9678c7b8 2165
beb56299 2166 /**
76be40cc 2167 * @var string Description of the contents for screen readers.
beb56299 2168 */
2169 public $summary;
d9c8f425 2170
3451a51c
JC
2171 /**
2172 * @var string Caption for the table, typically a title.
2173 *
2174 * Example of usage:
2175 * $t->caption = "TV Guide";
2176 */
2177 public $caption;
2178
2179 /**
2180 * @var bool Whether to hide the table's caption from sighted users.
2181 *
2182 * Example of usage:
2183 * $t->caption = "TV Guide";
2184 * $t->captionhide = true;
2185 */
2186 public $captionhide = false;
2187
d9c8f425 2188 /**
16be8974 2189 * Constructor
d9c8f425 2190 */
16be8974
DM
2191 public function __construct() {
2192 $this->attributes['class'] = '';
d9c8f425 2193 }
d9c8f425 2194}
2195
2196/**
7b1f2c82 2197 * Component representing a table row.
d9c8f425 2198 *
2199 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2200 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2201 * @since Moodle 2.0
f8129210 2202 * @package core
76be40cc 2203 * @category output
d9c8f425 2204 */
16be8974 2205class html_table_row {
9678c7b8 2206
16be8974 2207 /**
76be40cc 2208 * @var string Value to use for the id attribute of the row.
16be8974
DM
2209 */
2210 public $id = null;
9678c7b8 2211
d9c8f425 2212 /**
76be40cc 2213 * @var array Array of html_table_cell objects
d9c8f425 2214 */
7b1f2c82 2215 public $cells = array();
9678c7b8 2216
beb56299 2217 /**
76be40cc 2218 * @var string Value to use for the style attribute of the table row
beb56299 2219 */
16be8974 2220 public $style = null;
9678c7b8 2221
16be8974 2222 /**
76be40cc 2223 * @var array Attributes of additional HTML attributes for the <tr> element
16be8974
DM
2224 */
2225 public $attributes = array();
a0ead5eb 2226
54a007e8 2227 /**
8cea545e 2228 * Constructor
54a007e8 2229 * @param array $cells
8cea545e
PS
2230 */
2231 public function __construct(array $cells=null) {
16be8974 2232 $this->attributes['class'] = '';
8cea545e
PS
2233 $cells = (array)$cells;
2234 foreach ($cells as $cell) {
2235 if ($cell instanceof html_table_cell) {
2236 $this->cells[] = $cell;
a019627a 2237 } else {
8cea545e 2238 $this->cells[] = new html_table_cell($cell);
a019627a 2239 }
2240 }
54a007e8 2241 }
d9c8f425 2242}
2243
2244/**
7b1f2c82 2245 * Component representing a table cell.
d9c8f425 2246 *
2247 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2249 * @since Moodle 2.0
f8129210 2250 * @package core
76be40cc 2251 * @category output
d9c8f425 2252 */
16be8974 2253class html_table_cell {
9678c7b8 2254
16be8974 2255 /**
76be40cc 2256 * @var string Value to use for the id attribute of the cell.
16be8974
DM
2257 */
2258 public $id = null;
9678c7b8 2259
d9c8f425 2260 /**
76be40cc 2261 * @var string The contents of the cell.
d9c8f425 2262 */
7b1f2c82 2263 public $text;
9678c7b8 2264
d9c8f425 2265 /**
76be40cc 2266 * @var string Abbreviated version of the contents of the cell.
d9c8f425 2267 */
97c10099 2268 public $abbr = null;
9678c7b8 2269
d9c8f425 2270 /**
76be40cc 2271 * @var int Number of columns this cell should span.
d9c8f425 2272 */
97c10099 2273 public $colspan = null;
9678c7b8 2274
d9c8f425 2275 /**
76be40cc 2276 * @var int Number of rows this cell should span.
d9c8f425 2277 */
97c10099 2278 public $rowspan = null;
9678c7b8 2279
d9c8f425 2280 /**
76be40cc 2281 * @var string Defines a way to associate header cells and data cells in a table.
d9c8f425 2282 */
97c10099 2283 public $scope = null;
9678c7b8 2284
1ae3767a 2285 /**
3d3fae72 2286 * @var bool Whether or not this cell is a header cell.
1ae3767a 2287 */
a4998d01 2288 public $header = null;
9678c7b8 2289
16be8974 2290 /**
76be40cc 2291 * @var string Value to use for the style attribute of the table cell
16be8974
DM
2292 */
2293 public $style = null;
9678c7b8 2294
16be8974 2295 /**
76be40cc 2296 * @var array Attributes of additional HTML attributes for the <td> element
16be8974
DM
2297 */
2298 public $attributes = array();
d9c8f425 2299
9678c7b8
SH
2300 /**
2301 * Constructs a table cell
2302 *
2303 * @param string $text
2304 */
8cea545e
PS
2305 public function __construct($text = null) {
2306 $this->text = $text;
16be8974 2307 $this->attributes['class'] = '';
d9c8f425 2308 }
2309}
2310
d9c8f425 2311/**
beb56299 2312 * Component representing a paging bar.
d9c8f425 2313 *
2314 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2316 * @since Moodle 2.0
f8129210 2317 * @package core
76be40cc 2318 * @category output
d9c8f425 2319 */
929d7a83 2320class paging_bar implements renderable {
9678c7b8 2321
d9c8f425 2322 /**
76be40cc 2323 * @var int The maximum number of pagelinks to display.
d9c8f425 2324 */
beb56299 2325 public $maxdisplay = 18;
9678c7b8 2326
d9c8f425 2327 /**
76be40cc 2328 * @var int The total number of entries to be pages through..
d9c8f425 2329 */
beb56299 2330 public $totalcount;
9678c7b8 2331
d9c8f425 2332 /**
76be40cc 2333 * @var int The page you are currently viewing.
d9c8f425 2334 */
929d7a83 2335 public $page;
9678c7b8 2336
d9c8f425 2337 /**
76be40cc 2338 * @var int The number of entries that should be shown per page.
d9c8f425 2339 */
beb56299 2340 public $perpage;
9678c7b8 2341
d9c8f425 2342 /**
76be40cc 2343 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
9678c7b8
SH
2344 * an equals sign and the page number.
2345 * If this is a moodle_url object then the pagevar param will be replaced by
2346 * the page no, for each page.
d9c8f425 2347 */
beb56299 2348 public $baseurl;
9678c7b8 2349
d9c8f425 2350 /**
76be40cc 2351 * @var string This is the variable name that you use for the pagenumber in your
9678c7b8 2352 * code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 2353 */
929d7a83 2354 public $pagevar;
9678c7b8 2355
beb56299 2356 /**
76be40cc 2357 * @var string A HTML link representing the "previous" page.
beb56299 2358 */
2359 public $previouslink = null;
9678c7b8 2360
beb56299 2361 /**
76be40cc 2362 * @var string A HTML link representing the "next" page.
beb56299 2363 */
2364 public $nextlink = null;
9678c7b8 2365
beb56299 2366 /**
76be40cc 2367 * @var string A HTML link representing the first page.
beb56299 2368 */
2369 public $firstlink = null;
9678c7b8 2370
beb56299 2371 /**
76be40cc 2372 * @var string A HTML link representing the last page.
beb56299 2373 */
2374 public $lastlink = null;
9678c7b8 2375
beb56299 2376 /**
76be40cc 2377 * @var array An array of strings. One of them is just a string: the current page
beb56299 2378 */
2379 public $pagelinks = array();
d9c8f425 2380
929d7a83
PS
2381 /**
2382 * Constructor paging_bar with only the required params.
2383 *
1a10840e 2384 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2385 * @param int $page The page you are currently viewing
2386 * @param int $perpage The number of entries that should be shown per page
2387 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2388 * @param string $pagevar name of page parameter that holds the page number
2389 */
2390 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2391 $this->totalcount = $totalcount;
2392 $this->page = $page;
2393 $this->perpage = $perpage;
2394 $this->baseurl = $baseurl;
2395 $this->pagevar = $pagevar;
2396 }
2397
d9c8f425 2398 /**
9678c7b8
SH
2399 * Prepares the paging bar for output.
2400 *
2401 * This method validates the arguments set up for the paging bar and then
2402 * produces fragments of HTML to assist display later on.
f8129210
SH
2403 *
2404 * @param renderer_base $output
2405 * @param moodle_page $page
2406 * @param string $target
2407 * @throws coding_exception
d9c8f425 2408 */
34059565 2409 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 2410 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 2411 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 2412 }
2413 if (!isset($this->page) || is_null($this->page)) {
929d7a83 2414 throw new coding_exception('paging_bar requires a page value.');
beb56299 2415 }
2416 if (empty($this->perpage)) {
929d7a83 2417 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 2418 }
2419 if (empty($this->baseurl)) {
929d7a83 2420 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 2421 }
d9c8f425 2422
beb56299 2423 if ($this->totalcount > $this->perpage) {
2424 $pagenum = $this->page - 1;
d9c8f425 2425
beb56299 2426 if ($this->page > 0) {
929d7a83 2427 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 2428 }
d9c8f425 2429
beb56299 2430 if ($this->perpage > 0) {
2431 $lastpage = ceil($this->totalcount / $this->perpage);
2432 } else {
2433 $lastpage = 1;
2434 }
2435
0232fa7b
JF
2436 if ($this->page > round(($this->maxdisplay/3)*2)) {
2437 $currpage = $this->page - round($this->maxdisplay/3);
beb56299 2438
929d7a83 2439 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 2440 } else {
0232fa7b 2441 $currpage = 0;
beb56299 2442 }
2443
beb56299 2444 $displaycount = $displaypage = 0;
2445
2446 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2447 $displaypage = $currpage + 1;
2448
f43cdceb 2449 if ($this->page == $currpage) {
1c77e2aa 2450 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
beb56299 2451 } else {
56ddb719 2452 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 2453 $this->pagelinks[] = $pagelink;
2454 }
2455
2456 $displaycount++;
2457 $currpage++;
2458 }
2459
2460 if ($currpage < $lastpage) {
2461 $lastpageactual = $lastpage - 1;
abdac127 2462 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 2463 }
2464
2465 $pagenum = $this->page + 1;
2466
2467 if ($pagenum != $displaypage) {
abdac127 2468 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 2469 }
d9c8f425 2470 }
2471 }
d9c8f425 2472}
2473
d9c8f425 2474/**
beb56299 2475 * This class represents how a block appears on a page.
d9c8f425 2476 *
beb56299 2477 * During output, each block instance is asked to return a block_contents object,
2478 * those are then passed to the $OUTPUT->block function for display.
2479 *
f8129210 2480 * contents should probably be generated using a moodle_block_..._renderer.
beb56299 2481 *
2482 * Other block-like things that need to appear on the page, for example the
2483 * add new block UI, are also represented as block_contents objects.
2484 *
2485 * @copyright 2009 Tim Hunt
9678c7b8
SH
2486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2487 * @since Moodle 2.0
f8129210 2488 * @package core
76be40cc 2489 * @category output
d9c8f425 2490 */
dd72b308 2491class block_contents {
beb56299 2492
76be40cc 2493 /** Used when the block cannot be collapsed **/
beb56299 2494 const NOT_HIDEABLE = 0;
76be40cc
SH
2495
2496 /** Used when the block can be collapsed but currently is not **/
beb56299 2497 const VISIBLE = 1;
76be40cc
SH
2498
2499 /** Used when the block has been collapsed **/
beb56299 2500 const HIDDEN = 2;
2501
d9c8f425 2502 /**
76be40cc 2503 * @var int Used to set $skipid.
9678c7b8
SH
2504 */
2505 protected static $idcounter = 1;
2506
2507 /**
3d3fae72 2508 * @var int All the blocks (or things that look like blocks) printed on
76be40cc 2509 * a page are given a unique number that can be used to construct id="" attributes.
9678c7b8 2510 * This is set automatically be the {@link prepare()} method.
beb56299 2511 * Do not try to set it manually.
d9c8f425 2512 */
beb56299 2513 public $skipid;
d9c8f425 2514
2515 /**
3d3fae72 2516 * @var int If this is the contents of a real block, this should be set
76be40cc 2517 * to the block_instance.id. Otherwise this should be set to 0.
beb56299 2518 */
2519 public $blockinstanceid = 0;
2520
2521 /**
3d3fae72 2522 * @var int If this is a real block instance, and there is a corresponding
beb56299 2523 * block_position.id for the block on this page, this should be set to that id.
2524 * Otherwise it should be 0.
2525 */
2526 public $blockpositionid = 0;
2527
2528 /**
76be40cc 2529 * @var array An array of attribute => value pairs that are put on the outer div of this
9678c7b8 2530 * block. {@link $id} and {@link $classes} attributes should be set separately.
beb56299 2531 */
dd72b308 2532 public $attributes;
beb56299 2533
2534 /**
76be40cc 2535 * @var string The title of this block. If this came from user input, it should already
9678c7b8
SH
2536 * have had format_string() processing done on it. This will be output inside
2537 * <h2> tags. Please do not cause invalid XHTML.
beb56299 2538 */
2539 public $title = '';
2540
91d941c3
SH
2541 /**
2542 * @var string The label to use when the block does not, or will not have a visible title.
2543 * You should never set this as well as title... it will just be ignored.
2544 */
2545 public $arialabel = '';
2546
beb56299 2547 /**
76be40cc 2548 * @var string HTML for the content
beb56299 2549 */
2550 public $content = '';
2551
2552 /**
76be40cc 2553 * @var array An alternative to $content, it you want a list of things with optional icons.
beb56299 2554 */
2555 public $footer = '';
2556
2557 /**
76be40cc
SH
2558 * @var string Any small print that should appear under the block to explain
2559 * to the teacher about the block, for example 'This is a sticky block that was
beb56299 2560 * added in the system context.'
beb56299 2561 */
2562 public $annotation = '';
2563
2564 /**
3d3fae72 2565 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
beb56299 2566 * the user can toggle whether this block is visible.
2567 */
2568 public $collapsible = self::NOT_HIDEABLE;
2569
84192d78
SH
2570 /**
2571 * Set this to true if the block is dockable.
2572 * @var bool
2573 */
2574 public $dockable = false;
2575
beb56299 2576 /**
76be40cc
SH
2577 * @var array A (possibly empty) array of editing controls. Each element of
2578 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 2579 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 2580 */
2581 public $controls = array();
2582
dd72b308 2583
beb56299 2584 /**
dd72b308
PS
2585 * Create new instance of block content
2586 * @param array $attributes
d9c8f425 2587 */
9678c7b8 2588 public function __construct(array $attributes = null) {
beb56299 2589 $this->skipid = self::$idcounter;
2590 self::$idcounter += 1;
dd72b308
PS
2591
2592 if ($attributes) {
2593 // standard block
2594 $this->attributes = $attributes;
2595 } else {
2596 // simple "fake" blocks used in some modules and "Add new block" block
6605ff8c 2597 $this->attributes = array('class'=>'block');
beb56299 2598 }
dd72b308
PS
2599 }
2600
2601 /**
2602 * Add html class to block
9678c7b8 2603 *
dd72b308 2604 * @param string $class
dd72b308
PS
2605 */
2606 public function add_class($class) {
2607 $this->attributes['class'] .= ' '.$class;
d9c8f425 2608 }
2609}
beb56299 2610
34059565 2611
beb56299 2612/**
2613 * This class represents a target for where a block can go when it is being moved.
2614 *
2615 * This needs to be rendered as a form with the given hidden from fields, and
2616 * clicking anywhere in the form should submit it. The form action should be
2617 * $PAGE->url.
2618 *
2619 * @copyright 2009 Tim Hunt
9678c7b8
SH
2620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2621 * @since Moodle 2.0
f8129210 2622 * @package core
76be40cc 2623 * @category output
beb56299 2624 */
dd72b308 2625class block_move_target {
9678c7b8 2626
beb56299 2627 /**
76be40cc 2628 * @var moodle_url Move url
beb56299 2629 */
dd72b308 2630 public $url;
9678c7b8 2631
dd72b308 2632 /**
1a10840e 2633 * Constructor
dd72b308
PS
2634 * @param moodle_url $url
2635 */
6671fa73 2636 public function __construct(moodle_url $url) {
dd72b308
PS
2637 $this->url = $url;
2638 }
beb56299 2639}
d2dbd0c0
SH
2640
2641/**
2642 * Custom menu item
2643 *
2644 * This class is used to represent one item within a custom menu that may or may
2645 * not have children.
2646 *
2647 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2648 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2649 * @since Moodle 2.0
f8129210 2650 * @package core
76be40cc 2651 * @category output
d2dbd0c0
SH
2652 */
2653class custom_menu_item implements renderable {
9678c7b8 2654
d2dbd0c0 2655 /**
76be40cc 2656 * @var string The text to show for the item
d2dbd0c0
SH
2657 */
2658 protected $text;
9678c7b8 2659
d2dbd0c0 2660 /**
76be40cc 2661 * @var moodle_url The link to give the icon if it has no children
d2dbd0c0
SH
2662 */
2663 protected $url;
9678c7b8 2664
d2dbd0c0 2665 /**
76be40cc 2666 * @var string A title to apply to the item. By default the text
d2dbd0c0
SH
2667 */
2668 protected $title;
9678c7b8 2669
d2dbd0c0 2670 /**
76be40cc
SH
2671 * @var int A sort order for the item, not necessary if you order things in
2672 * the CFG var.
d2dbd0c0
SH
2673 */
2674 protected $sort;
9678c7b8 2675
d2dbd0c0 2676 /**
76be40cc
SH
2677 * @var custom_menu_item A reference to the parent for this item or NULL if
2678 * it is a top level item
d2dbd0c0
SH
2679 */
2680 protected $parent;
9678c7b8 2681
d2dbd0c0 2682 /**
76be40cc 2683 * @var array A array in which to store children this item has.
d2dbd0c0
SH
2684 */
2685 protected $children = array();
9678c7b8 2686
d2dbd0c0 2687 /**
76be40cc 2688 * @var int A reference to the sort var of the last child that was added
d2dbd0c0
SH
2689 */
2690 protected $lastsort = 0;
9678c7b8 2691
d2dbd0c0
SH
2692 /**
2693 * Constructs the new custom menu item
2694 *
2695 * @param string $text
2696 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2697 * @param string $title A title to apply to this item [Optional]
2698 * @param int $sort A sort or to use if we need to sort differently [Optional]
2699 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2700 * belongs to, only if the child has a parent. [Optional]
2701 */
9678c7b8 2702 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
d2dbd0c0
SH
2703 $this->text = $text;
2704 $this->url = $url;
2705 $this->title = $title;
2706 $this->sort = (int)$sort;
2707 $this->parent = $parent;
2708 }
2709
2710 /**
2711 * Adds a custom menu item as a child of this node given its properties.
2712 *
2713 * @param string $text
2714 * @param moodle_url $url
2715 * @param string $title
2716 * @param int $sort
2717 * @return custom_menu_item
2718 */
9678c7b8 2719 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
d2dbd0c0
SH
2720 $key = count($this->children);
2721 if (empty($sort)) {
2722 $sort = $this->lastsort + 1;
2723 }
2724 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2725 $this->lastsort = (int)$sort;
2726 return $this->children[$key];
2727 }
9678c7b8 2728
62ffeb4f
PK
2729 /**
2730 * Removes a custom menu item that is a child or descendant to the current menu.
2731 *
2732 * Returns true if child was found and removed.
2733 *
2734 * @param custom_menu_item $menuitem
2735 * @return bool
2736 */
2737 public function remove_child(custom_menu_item $menuitem) {
2738 $removed = false;
2739 if (($key = array_search($menuitem, $this->children)) !== false) {
2740 unset($this->children[$key]);
2741 $this->children = array_values($this->children);
2742 $removed = true;
2743 } else {
2744 foreach ($this->children as $child) {
2745 if ($removed = $child->remove_child($menuitem)) {
2746 break;
2747 }
2748 }
2749 }
2750 return $removed;
2751 }
2752
d2dbd0c0
SH
2753 /**
2754 * Returns the text for this item
2755 * @return string
2756 */
2757 public function get_text() {
2758 return $this->text;
2759 }
9678c7b8 2760
d2dbd0c0
SH
2761 /**
2762 * Returns the url for this item
2763 * @return moodle_url
2764 */
2765 public function get_url() {
2766 return $this->url;
2767 }
9678c7b8 2768
d2dbd0c0
SH
2769 /**
2770 * Returns the title for this item
2771 * @return string
2772 */
2773 public function get_title() {
2774 return $this->title;
2775 }
9678c7b8 2776
d2dbd0c0
SH
2777 /**
2778 * Sorts and returns the children for this item
2779 * @return array
2780 */
2781 public function get_children() {
2782 $this->sort();
2783 return $this->children;
2784 }
9678c7b8 2785
d2dbd0c0
SH
2786 /**
2787 * Gets the sort order for this child
2788 * @return int
2789 */
2790 public function get_sort_order() {
2791 return $this->sort;
2792 }
9678c7b8 2793
d2dbd0c0
SH
2794 /**
2795 * Gets the parent this child belong to
2796 * @return custom_menu_item
2797 */
2798 public function get_parent() {
2799 return $this->parent;
2800 }
9678c7b8 2801
d2dbd0c0
SH
2802 /**
2803 * Sorts the children this item has
2804 */
2805 public function sort() {
2806 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2807 }
9678c7b8 2808
d2dbd0c0
SH
2809 /**
2810 * Returns true if this item has any children
2811 * @return bool
2812 */
2813 public function has_children() {
2814 return (count($this->children) > 0);
2815 }
f3827323
SH
2816
2817 /**
2818 * Sets the text for the node
2819 * @param string $text
2820 */
2821 public function set_text($text) {
2822 $this->text = (string)$text;
2823 }
2824
2825 /**
2826 * Sets the title for the node
2827 * @param string $title
2828 */
2829 public function set_title($title) {
2830 $this->title = (string)$title;
2831 }
2832
2833 /**
2834 * Sets the url for the node
2835 * @param moodle_url $url
2836 */
2837 public function set_url(moodle_url $url) {
2838 $this->url = $url;
2839 }
d2dbd0c0
SH
2840}
2841
2842/**
2843 * Custom menu class
2844 *
2845 * This class is used to operate a custom menu that can be rendered for the page.
2846 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2847 * of custom_menu_item nodes that can be rendered by the core renderer.
2848 *
2849 * To configure the custom menu:
2850 * Settings: Administration > Appearance > Themes > Theme settings
2851 *
2852 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2854 * @since Moodle 2.0
f8129210 2855 * @package core
76be40cc 2856 * @category output
d2dbd0c0
SH
2857 */
2858class custom_menu extends custom_menu_item {
155fffe6 2859
9678c7b8 2860 /**
76be40cc 2861 * @var string The language we should render for, null disables multilang support.
9678c7b8 2862 */
4564d58f
DM
2863 protected $currentlanguage = null;
2864
d2dbd0c0
SH
2865 /**
2866 * Creates the custom menu
155fffe6
DM
2867 *
2868 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
f8129210 2869 * @param string $currentlanguage the current language code, null disables multilang support
d2dbd0c0 2870 */
4564d58f 2871 public function __construct($definition = '', $currentlanguage = null) {
4564d58f 2872 $this->currentlanguage = $currentlanguage;
155fffe6
DM
2873 parent::__construct('root'); // create virtual root element of the menu
2874 if (!empty($definition)) {
4564d58f 2875 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
12cc75ae 2876 }
d2dbd0c0
SH
2877 }
2878
2879 /**
2880 * Overrides the children of this custom menu. Useful when getting children
2881 * from $CFG->custommenuitems
9678c7b8
SH
2882 *
2883 * @param array $children
d2dbd0c0
SH
2884 */
2885 public function override_children(array $children) {
2886 $this->children = array();
2887 foreach ($children as $child) {
2888 if ($child instanceof custom_menu_item) {
2889 $this->children[] = $child;
2890 }
2891 }
2892 }
2893
2894 /**
2895 * Converts a string into a structured array of custom_menu_items which can
2896 * then be added to a custom menu.
2897 *
2898 * Structure:
4564d58f
DM
2899 * text|url|title|langs
2900 * The number of hyphens at the start determines the depth of the item. The
2901 * languages are optional, comma separated list of languages the line is for.
d2dbd0c0
SH
2902 *
2903 * Example structure:
2904 * First level first item|http://www.moodle.com/
2905 * -Second level first item|http://www.moodle.com/partners/
2906 * -Second level second item|http://www.moodle.com/hq/
2907 * --Third level first item|http://www.moodle.com/jobs/
2908 * -Second level third item|http://www.moodle.com/development/
2909 * First level second item|http://www.moodle.com/feedback/
2910 * First level third item
4564d58f
DM
2911 * English only|http://moodle.com|English only item|en
2912 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2913 *
4d2ee4c2 2914 *
d2dbd0c0 2915 * @static
4564d58f
DM
2916 * @param string $text the menu items definition
2917 * @param string $language the language code, null disables multilang support
d2dbd0c0
SH
2918 * @return array
2919 */
4564d58f 2920 public static function convert_text_to_menu_nodes($text, $language = null) {
62ffeb4f
PK
2921 $root = new custom_menu();
2922 $lastitem = $root;
2923 $lastdepth = 0;
2924 $hiddenitems = array();
d2dbd0c0 2925 $lines = explode("\n", $text);
62ffeb4f 2926 foreach ($lines as $linenumber => $line) {
d2dbd0c0 2927 $line = trim($line);
62ffeb4f 2928 if (strlen($line) == 0) {
d2dbd0c0 2929 continue;
d2dbd0c0 2930 }
62ffeb4f
PK
2931 // Parse item settings.
2932 $itemtext = null;
2933 $itemurl = null;
2934 $itemtitle = null;
2935 $itemvisible = true;
2936 $settings = explode('|', $line);
2937 foreach ($settings as $i => $setting) {
2938 $setting = trim($setting);
2939 if (!empty($setting)) {
2940 switch ($i) {
2941 case 0:
2942 $itemtext = ltrim($setting, '-');
2943 $itemtitle = $itemtext;
2944 break;
2945 case 1:
8e371539 2946 try {
2947 $itemurl = new moodle_url($setting);
16dfee4e
SH
2948 } catch (moodle_exception $exception) {
2949 // We're not actually worried about this, we don't want to mess up the display
2950 // just for a wrongly entered URL.
8e371539 2951 $itemurl = null;
2952 }
62ffeb4f
PK
2953 break;
2954 case 2:
2955 $itemtitle = $setting;
2956 break;
2957 case 3:
2958 if (!empty($language)) {
2959 $itemlanguages = array_map('trim', explode(',', $setting));
2960 $itemvisible &= in_array($language, $itemlanguages);
2961 }
2962 break;
d2dbd0c0
SH
2963 }
2964 }
d2dbd0c0 2965 }
62ffeb4f
PK
2966 // Get depth of new item.
2967 preg_match('/^(\-*)/', $line, $match);
2968 $itemdepth = strlen($match[1]) + 1;
2969 // Find parent item for new item.
2970 while (($lastdepth - $itemdepth) >= 0) {
2971 $lastitem = $lastitem->get_parent();
2972 $lastdepth--;
2973 }
2974 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
2975 $lastdepth++;
2976 if (!$itemvisible) {
2977 $hiddenitems[] = $lastitem;
2978 }
2979 }
2980 foreach ($hiddenitems as $item) {
2981 $item->parent->remove_child($item);
d2dbd0c0 2982 }
62ffeb4f 2983 return $root->get_children();
d2dbd0c0
SH
2984 }
2985
2986 /**
2987 * Sorts two custom menu items
2988 *
2989 * This function is designed to be used with the usort method
2990 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2991 *
9678c7b8 2992 * @static
d2dbd0c0
SH
2993 * @param custom_menu_item $itema
2994 * @param custom_menu_item $itemb
2995 * @return int
2996 */
2997 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2998 $itema = $itema->get_sort_order();
2999 $itemb = $itemb->get_sort_order();
3000 if ($itema == $itemb) {
3001 return 0;
3002 }
3003 return ($itema > $itemb) ? +1 : -1;
3004 }
de7a570c 3005}
c269b9d1
MG
3006
3007/**
3008 * Stores one tab
3009 *
3010 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3011 * @package core
3012 */
3013class tabobject implements renderable {
3014 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3015 var $id;
3016 /** @var moodle_url|string link */
3017 var $link;
3018 /** @var string text on the tab */
3019 var $text;
3020 /** @var string title under the link, by defaul equals to text */
3021 var $title;
3022 /** @var bool whether to display a link under the tab name when it's selected */
3023 var $linkedwhenselected = false;
3024 /** @var bool whether the tab is inactive */
3025 var $inactive = false;
3026 /** @var bool indicates that this tab's child is selected */
3027 var $activated = false;
3028 /** @var bool indicates that this tab is selected */
3029 var $selected = false;
3030 /** @var array stores children tabobjects */
3031 var $subtree = array();
3032 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3033 var $level = 1;
3034
3035 /**
3036 * Constructor
3037 *
3038 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3039 * @param string|moodle_url $link
3040 * @param string $text text on the tab
3041 * @param string $title title under the link, by defaul equals to text
3042 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3043 */
3044 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3045 $this->id = $id;
3046 $this->link = $link;
3047 $this->text = $text;
3048 $this->title = $title ? $title : $text;
3049 $this->linkedwhenselected = $linkedwhenselected;
3050 }
3051
3052 /**
3053 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3054 *
3055 * @param string $selected the id of the selected tab (whatever row it's on),
3056 * if null marks all tabs as unselected
3057 * @return bool whether this tab is selected or contains selected tab in its subtree
3058 */
3059 protected function set_selected($selected) {
3060 if ((string)$selected === (string)$this->id) {
3061 $this->selected = true;
3062 // This tab is selected. No need to travel through subtree.
3063 return true;
3064 }
3065 foreach ($this->subtree as $subitem) {
3066 if ($subitem->set_selected($selected)) {
3067 // This tab has child that is selected. Mark it as activated. No need to check other children.
3068 $this->activated = true;
3069 return true;
3070 }
3071 }
3072 return false;
3073 }
3074
3075 /**
3076 * Travels through tree and finds a tab with specified id
3077 *
3078 * @param string $id
3079 * @return tabtree|null
3080 */
3081 public function find($id) {
3082 if ((string)$this->id === (string)$id) {
3083 return $this;
3084 }
3085 foreach ($this->subtree as $tab) {
3086 if ($obj = $tab->find($id)) {
3087 return $obj;
3088 }
3089 }
3090 return null;
3091 }
3092
3093 /**
3094 * Allows to mark each tab's level in the tree before rendering.
3095 *
3096 * @param int $level
3097 */
3098 protected function set_level($level) {
3099 $this->level = $level;
3100 foreach ($this->subtree as $tab) {
3101 $tab->set_level($level + 1);
3102 }
3103 }
3104}
3105
261bdb24
AG
3106/**
3107 * Renderable for the main page header.
3108 *
3109 * @package core
3110 * @category output
3111 * @since 2.9
3112 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3113 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3114 */
3115class context_header implements renderable {
3116
3117 /**
3b927d35
AG
3118 * @var string $heading Main heading.
3119 */
3120 public $heading;
3121 /**
3122 * @var int $headinglevel Main heading 'h' tag level.
3123 */
3124 public $headinglevel;
3125 /**
e35bac3e 3126 * @var string|null $imagedata HTML code for the picture in the page header.
261bdb24
AG
3127 */
3128 public $imagedata;
3129 /**
3130 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3131 * array elements - title => alternate text for the image, or if no image is available the button text.
3132 * url => Link for the button to head to. Should be a moodle_url.
3133 * image => location to the image, or name of the image in /pix/t/{image name}.
3134 * linkattributes => additional attributes for the <a href> element.
3135 * page => page object. Don't include if the image is an external image.
3136 */
3137 public $additionalbuttons;
261bdb24
AG
3138
3139 /**
3140 * Constructor.
3141 *
3b927d35
AG
3142 * @param string $heading Main heading data.
3143 * @param int $headinglevel Main heading 'h' tag level.
e35bac3e 3144 * @param string|null $imagedata HTML code for the picture in the page header.
261bdb24 3145 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
261bdb24 3146 */
3b927d35
AG
3147 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3148
3149 $this->heading = $heading;
3150 $this->headinglevel = $headinglevel;
261bdb24
AG
3151 $this->imagedata = $imagedata;
3152 $this->additionalbuttons = $additionalbuttons;
3b927d35 3153 // If we have buttons then format them.
261bdb24
AG
3154 if (isset($this->additionalbuttons)) {
3155 $this->format_button_images();
3156 }
261bdb24
AG
3157 }
3158
3b927d35
AG
3159 /**
3160 * Adds an array element for a formatted image.
3161 */
261bdb24
AG
3162 protected function format_button_images() {
3163
3164 foreach ($this->additionalbuttons as $buttontype => $button) {
3165 $page = $button['page'];
3b927d35 3166 // If no image is provided then just use the title.
261bdb24
AG
3167 if (!isset($button['image'])) {
3168 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3169 } else {
3b927d35 3170 // Check to see if this is an internal Moodle icon.
261bdb24 3171 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3b927d35 3172 if ($internalimage) {
261bdb24 3173 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3b927d35
AG
3174