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