MDL-39814 html_writer: Remove superfluous new lines from html_writer::alist
[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 }
513 if (!isset($this->attributes['title'])) {
514 $this->attributes['title'] = $this->attributes['alt'];
aad982aa
FM
515 } else if (empty($this->attributes['title'])) {
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
PS
921 */
922 var $url;
9678c7b8 923
574fbea4 924 /**
76be40cc 925 * @var string Link text HTML fragment
574fbea4
PS
926 */
927 var $text;
9678c7b8 928
574fbea4 929 /**
76be40cc 930 * @var array HTML attributes
574fbea4
PS
931 */
932 var $attributes;
9678c7b8 933
574fbea4 934 /**
76be40cc 935 * @var array List of actions attached to link
574fbea4
PS
936 */
937 var $actions;
938
939 /**
940 * Constructor
9678c7b8 941 * @param moodle_url $url
574fbea4
PS
942 * @param string $text HTML fragment
943 * @param component_action $action
11820bac 944 * @param array $attributes associative array of html link attributes + disabled
574fbea4 945 */
9678c7b8
SH
946 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
947 $this->url = clone($url);
948 $this->text = $text;
b0fef57b 949 $this->attributes = (array)$attributes;
f14b641b 950 if ($action) {
574fbea4
PS
951 $this->add_action($action);
952 }
953 }
954
955 /**
956 * Add action to the link.
9678c7b8 957 *
574fbea4 958 * @param component_action $action
574fbea4
PS
959 */
960 public function add_action(component_action $action) {
961 $this->actions[] = $action;
962 }
c63923bd 963
9678c7b8
SH
964 /**
965 * Adds a CSS class to this action link object
966 * @param string $class
967 */
c63923bd 968 public function add_class($class) {
67da0bf7
DM
969 if (empty($this->attributes['class'])) {
970 $this->attributes['class'] = $class;
c63923bd 971 } else {
67da0bf7 972 $this->attributes['class'] .= ' ' . $class;
c63923bd
PS
973 }
974 }
574fbea4 975}
3ba60ee1 976
5d0c95a5
PS
977/**
978 * Simple html output class
9678c7b8 979 *
5d0c95a5 980 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
9678c7b8
SH
981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
982 * @since Moodle 2.0
f8129210 983 * @package core
76be40cc 984 * @category output
5d0c95a5
PS
985 */
986class html_writer {
9678c7b8 987
5d0c95a5
PS
988 /**
989 * Outputs a tag with attributes and contents
9678c7b8 990 *
5d0c95a5 991 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
5d0c95a5 992 * @param string $contents What goes between the opening and closing tags
26acc814 993 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
5d0c95a5
PS
994 * @return string HTML fragment
995 */
26acc814 996 public static function tag($tagname, $contents, array $attributes = null) {
5d0c95a5
PS
997 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
998 }
999
1000 /**
1001 * Outputs an opening tag with attributes
9678c7b8 1002 *
5d0c95a5
PS
1003 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1004 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1005 * @return string HTML fragment
1006 */
1007 public static function start_tag($tagname, array $attributes = null) {
1008 return '<' . $tagname . self::attributes($attributes) . '>';
1009 }
1010
1011 /**
1012 * Outputs a closing tag
9678c7b8 1013 *
5d0c95a5
PS
1014 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1015 * @return string HTML fragment
1016 */
1017 public static function end_tag($tagname) {
1018 return '</' . $tagname . '>';
1019 }
1020
1021 /**
1022 * Outputs an empty tag with attributes
9678c7b8 1023 *
5d0c95a5
PS
1024 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1025 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1026 * @return string HTML fragment
1027 */
1028 public static function empty_tag($tagname, array $attributes = null) {
1029 return '<' . $tagname . self::attributes($attributes) . ' />';
1030 }
1031
836c47d7
TH
1032 /**
1033 * Outputs a tag, but only if the contents are not empty
9678c7b8 1034 *
836c47d7
TH
1035 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1036 * @param string $contents What goes between the opening and closing tags
1037 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1038 * @return string HTML fragment
1039 */
1040 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1041 if ($contents === '' || is_null($contents)) {
1042 return '';
1043 }
1044 return self::tag($tagname, $contents, $attributes);
1045 }
1046
5d0c95a5
PS
1047 /**
1048 * Outputs a HTML attribute and value
9678c7b8 1049 *
5d0c95a5
PS
1050 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1051 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1052 * @return string HTML fragment
1053 */
1054 public static function attribute($name, $value) {
bf11293a
PS
1055 if ($value instanceof moodle_url) {
1056 return ' ' . $name . '="' . $value->out() . '"';
1057 }
97c10099
PS
1058
1059 // special case, we do not want these in output
1060 if ($value === null) {
1061 return '';
5d0c95a5 1062 }
97c10099
PS
1063
1064 // no sloppy trimming here!
1065 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
1066 }
1067
1068 /**
1069 * Outputs a list of HTML attributes and values
9678c7b8 1070 *
5d0c95a5
PS
1071 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1072 * The values will be escaped with {@link s()}
1073 * @return string HTML fragment
1074 */
1075 public static function attributes(array $attributes = null) {
1076 $attributes = (array)$attributes;
1077 $output = '';
1078 foreach ($attributes as $name => $value) {
1079 $output .= self::attribute($name, $value);
1080 }
1081 return $output;
1082 }
1083
1084 /**
1085 * Generates random html element id.
9678c7b8
SH
1086 *
1087 * @staticvar int $counter
1088 * @staticvar type $uniq
3d3fae72
SH
1089 * @param string $base A string fragment that will be included in the random ID.
1090 * @return string A unique ID
5d0c95a5
PS
1091 */
1092 public static function random_id($base='random') {
2c479c8f
PS
1093 static $counter = 0;
1094 static $uniq;
1095
1096 if (!isset($uniq)) {
1097 $uniq = uniqid();
1098 }
1099
1100 $counter++;
1101 return $base.$uniq.$counter;
5d0c95a5 1102 }
0f4c64b7
PS
1103
1104 /**
1105 * Generates a simple html link
9678c7b8 1106 *
3d3fae72
SH
1107 * @param string|moodle_url $url The URL
1108 * @param string $text The text
1109 * @param array $attributes HTML attributes
0f4c64b7
PS
1110 * @return string HTML fragment
1111 */
1112 public static function link($url, $text, array $attributes = null) {
1113 $attributes = (array)$attributes;
1114 $attributes['href'] = $url;
26acc814 1115 return self::tag('a', $text, $attributes);
0f4c64b7 1116 }
3ff163c5 1117
14dce022 1118 /**
9678c7b8
SH
1119 * Generates a simple checkbox with optional label
1120 *
3d3fae72
SH
1121 * @param string $name The name of the checkbox
1122 * @param string $value The value of the checkbox
1123 * @param bool $checked Whether the checkbox is checked
1124 * @param string $label The label for the checkbox
1125 * @param array $attributes Any attributes to apply to the checkbox
14dce022
PS
1126 * @return string html fragment
1127 */
1128 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1129 $attributes = (array)$attributes;
1130 $output = '';
1131
1132 if ($label !== '' and !is_null($label)) {
1133 if (empty($attributes['id'])) {
1134 $attributes['id'] = self::random_id('checkbox_');
1135 }
1136 }
53868425
PS
1137 $attributes['type'] = 'checkbox';
1138 $attributes['value'] = $value;
1139 $attributes['name'] = $name;
621b4d08 1140 $attributes['checked'] = $checked ? 'checked' : null;
53868425 1141
14dce022
PS
1142 $output .= self::empty_tag('input', $attributes);
1143
1144 if ($label !== '' and !is_null($label)) {
26acc814 1145 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
14dce022
PS
1146 }
1147
1148 return $output;
1149 }
1150
78bdac64
PS
1151 /**
1152 * Generates a simple select yes/no form field
9678c7b8 1153 *
78bdac64
PS
1154 * @param string $name name of select element
1155 * @param bool $selected
1156 * @param array $attributes - html select element attributes
9678c7b8 1157 * @return string HTML fragment
78bdac64 1158 */
19f3bbb2 1159 public static function select_yes_no($name, $selected=true, array $attributes = null) {
78bdac64
PS
1160 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1161 return self::select($options, $name, $selected, null, $attributes);
1162 }
1163
3ff163c5
PS
1164 /**
1165 * Generates a simple select form field
9678c7b8 1166 *
6770330d
PS
1167 * @param array $options associative array value=>label ex.:
1168 * array(1=>'One, 2=>Two)
1169 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 1170 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 1171 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5 1172 * @param string $name name of select element
1a10840e 1173 * @param string|array $selected value or array of values depending on multiple attribute
f8129210
SH
1174 * @param array|bool $nothing add nothing selected option, or false of not added
1175 * @param array $attributes html select element attributes
78bdac64 1176 * @return string HTML fragment
3ff163c5 1177 */
9678c7b8 1178 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
3ff163c5
PS
1179 $attributes = (array)$attributes;
1180 if (is_array($nothing)) {
1181 foreach ($nothing as $k=>$v) {
4b9210f3 1182 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
1183 $nothing[$k] = get_string('choosedots');
1184 }
1185 }
1186 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
1187
1188 } else if (is_string($nothing) and $nothing !== '') {
1189 // BC
1190 $options = array(''=>$nothing) + $options;
bde156b3 1191 }
3ff163c5
PS
1192
1193 // we may accept more values if multiple attribute specified
1194 $selected = (array)$selected;
1195 foreach ($selected as $k=>$v) {
1196 $selected[$k] = (string)$v;
1197 }
1198
1199 if (!isset($attributes['id'])) {
1200 $id = 'menu'.$name;
1201 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1202 $id = str_replace('[', '', $id);
1203 $id = str_replace(']', '', $id);
1204 $attributes['id'] = $id;
1205 }
1206
1207 if (!isset($attributes['class'])) {
1208 $class = 'menu'.$name;
1209 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1210 $class = str_replace('[', '', $class);
1211 $class = str_replace(']', '', $class);
1212 $attributes['class'] = $class;
1213 }
f8129210 1214 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
3ff163c5
PS
1215
1216 $attributes['name'] = $name;
1217
1a09fa6d
TH
1218 if (!empty($attributes['disabled'])) {
1219 $attributes['disabled'] = 'disabled';
1220 } else {
1221 unset($attributes['disabled']);
1222 }
1223
3ff163c5
PS
1224 $output = '';
1225 foreach ($options as $value=>$label) {
6770330d
PS
1226 if (is_array($label)) {
1227 // ignore key, it just has to be unique
1228 $output .= self::select_optgroup(key($label), current($label), $selected);
1229 } else {
1230 $output .= self::select_option($label, $value, $selected);
3ff163c5 1231 }
3ff163c5 1232 }
26acc814 1233 return self::tag('select', $output, $attributes);
3ff163c5 1234 }
6770330d 1235
9678c7b8
SH
1236 /**
1237 * Returns HTML to display a select box option.
1238 *
1239 * @param string $label The label to display as the option.
1240 * @param string|int $value The value the option represents
1241 * @param array $selected An array of selected options
1242 * @return string HTML fragment
1243 */
6770330d
PS
1244 private static function select_option($label, $value, array $selected) {
1245 $attributes = array();
1246 $value = (string)$value;
1247 if (in_array($value, $selected, true)) {
1248 $attributes['selected'] = 'selected';
1249 }
1250 $attributes['value'] = $value;
26acc814 1251 return self::tag('option', $label, $attributes);
6770330d
PS
1252 }
1253
9678c7b8
SH
1254 /**
1255 * Returns HTML to display a select box option group.
1256 *
1257 * @param string $groupname The label to use for the group
1258 * @param array $options The options in the group
1259 * @param array $selected An array of selected values.
1260 * @return string HTML fragment.
1261 */
6770330d
PS
1262 private static function select_optgroup($groupname, $options, array $selected) {
1263 if (empty($options)) {
1264 return '';
1265 }
1266 $attributes = array('label'=>$groupname);
1267 $output = '';
1268 foreach ($options as $value=>$label) {
1269 $output .= self::select_option($label, $value, $selected);
1270 }
26acc814 1271 return self::tag('optgroup', $output, $attributes);
6770330d 1272 }
6ea66ff3 1273
f83b9b63
PS
1274 /**
1275 * This is a shortcut for making an hour selector menu.
9678c7b8 1276 *
f83b9b63
PS
1277 * @param string $type The type of selector (years, months, days, hours, minutes)
1278 * @param string $name fieldname
1279 * @param int $currenttime A default timestamp in GMT
1280 * @param int $step minute spacing
1281 * @param array $attributes - html select element attributes
1282 * @return HTML fragment
1283 */
9678c7b8 1284 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
f83b9b63
PS
1285 if (!$currenttime) {
1286 $currenttime = time();
1287 }
1288 $currentdate = usergetdate($currenttime);
1289 $userdatetype = $type;
1290 $timeunits = array();
1291
1292 switch ($type) {
1293 case 'years':
1294 for ($i=1970; $i<=2020; $i++) {
1295 $timeunits[$i] = $i;
1296 }
1297 $userdatetype = 'year';
1298 break;
1299 case 'months':
1300 for ($i=1; $i<=12; $i++) {
1301 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1302 }
1303 $userdatetype = 'month';
0387e003 1304 $currentdate['month'] = (int)$currentdate['mon'];
f83b9b63
PS
1305 break;
1306 case 'days':
1307 for ($i=1; $i<=31; $i++) {
1308 $timeunits[$i] = $i;
1309 }
1310 $userdatetype = 'mday';
1311 break;
1312 case 'hours':
1313 for ($i=0; $i<=23; $i++) {
1314 $timeunits[$i] = sprintf("%02d",$i);
1315 }
1316 break;
1317 case 'minutes':
1318 if ($step != 1) {
1319 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1320 }
1321
1322 for ($i=0; $i<=59; $i+=$step) {
1323 $timeunits[$i] = sprintf("%02d",$i);
1324 }
1325 break;
1326 default:
1327 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1328 }
1329
1330 if (empty($attributes['id'])) {
1331 $attributes['id'] = self::random_id('ts_');
1332 }
1333 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
26acc814 1334 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
f83b9b63
PS
1335
1336 return $label.$timerselector;
1337 }
1338
5be262b6
PS
1339 /**
1340 * Shortcut for quick making of lists
9678c7b8
SH
1341 *
1342 * Note: 'list' is a reserved keyword ;-)
1343 *
5be262b6 1344 * @param array $items
5be262b6 1345 * @param array $attributes
9678c7b8 1346 * @param string $tag ul or ol
5be262b6
PS
1347 * @return string
1348 */
1349 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
b69a3f1c 1350 $output = html_writer::start_tag($tag, $attributes)."\n";
5be262b6 1351 foreach ($items as $item) {
b69a3f1c 1352 $output .= html_writer::tag('li', $item)."\n";
5be262b6 1353 }
b69a3f1c
SH
1354 $output .= html_writer::end_tag($tag);
1355 return $output;
5be262b6
PS
1356 }
1357
6ea66ff3
PS
1358 /**
1359 * Returns hidden input fields created from url parameters.
9678c7b8 1360 *
6ea66ff3
PS
1361 * @param moodle_url $url
1362 * @param array $exclude list of excluded parameters
1363 * @return string HTML fragment
1364 */
1365 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1366 $exclude = (array)$exclude;
1367 $params = $url->params();
1368 foreach ($exclude as $key) {
1369 unset($params[$key]);
1370 }
1371
1372 $output = '';
bde156b3 1373 foreach ($params as $key => $value) {
6ea66ff3
PS
1374 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1375 $output .= self::empty_tag('input', $attributes)."\n";
1376 }
1377 return $output;
1378 }
77774f6a
PS
1379
1380 /**
1381 * Generate a script tag containing the the specified code.
1382 *
f8129210
SH
1383 * @param string $jscode the JavaScript code
1384 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
77774f6a
PS
1385 * @return string HTML, the code wrapped in <script> tags.
1386 */
e50b4c89 1387 public static function script($jscode, $url=null) {
77774f6a 1388 if ($jscode) {
e50b4c89 1389 $attributes = array('type'=>'text/javascript');
26acc814 1390 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
e50b4c89
PS
1391
1392 } else if ($url) {
1393 $attributes = array('type'=>'text/javascript', 'src'=>$url);
26acc814 1394 return self::tag('script', '', $attributes) . "\n";
a9967cf5 1395
77774f6a
PS
1396 } else {
1397 return '';
1398 }
1399 }
16be8974
DM
1400
1401 /**
1402 * Renders HTML table
1403 *
1404 * This method may modify the passed instance by adding some default properties if they are not set yet.
1405 * If this is not what you want, you should make a full clone of your data before passing them to this
1406 * method. In most cases this is not an issue at all so we do not clone by default for performance
1407 * and memory consumption reasons.
1408 *
1409 * @param html_table $table data to be rendered
1410 * @return string HTML code
1411 */
1412 public static function table(html_table $table) {
1413 // prepare table data and populate missing properties with reasonable defaults
1414 if (!empty($table->align)) {
1415 foreach ($table->align as $key => $aa) {
1416 if ($aa) {
1417 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1418 } else {
1419 $table->align[$key] = null;
1420 }
1421 }
1422 }
1423 if (!empty($table->size)) {
1424 foreach ($table->size as $key => $ss) {
1425 if ($ss) {
1426 $table->size[$key] = 'width:'. $ss .';';
1427 } else {
1428 $table->size[$key] = null;
1429 }
1430 }
1431 }
1432 if (!empty($table->wrap)) {
1433 foreach ($table->wrap as $key => $ww) {
1434 if ($ww) {
1435 $table->wrap[$key] = 'white-space:nowrap;';
1436 } else {
1437 $table->wrap[$key] = '';
1438 }
1439 }
1440 }
1441 if (!empty($table->head)) {
1442 foreach ($table->head as $key => $val) {
1443 if (!isset($table->align[$key])) {
1444 $table->align[$key] = null;
1445 }
1446 if (!isset($table->size[$key])) {
1447 $table->size[$key] = null;
1448 }
1449 if (!isset($table->wrap[$key])) {
1450 $table->wrap[$key] = null;
1451 }
1452
1453 }
1454 }
1455 if (empty($table->attributes['class'])) {
1456 $table->attributes['class'] = 'generaltable';
1457 }
1458 if (!empty($table->tablealign)) {
1459 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1460 }
1461
1462 // explicitly assigned properties override those defined via $table->attributes
e126c0cc 1463 $table->attributes['class'] = trim($table->attributes['class']);
16be8974
DM
1464 $attributes = array_merge($table->attributes, array(
1465 'id' => $table->id,
1466 'width' => $table->width,
1467 'summary' => $table->summary,
1468 'cellpadding' => $table->cellpadding,
1469 'cellspacing' => $table->cellspacing,
1470 ));
1471 $output = html_writer::start_tag('table', $attributes) . "\n";
1472
1473 $countcols = 0;
1474
1475 if (!empty($table->head)) {
1476 $countcols = count($table->head);
5174f3c5 1477
16be8974
DM
1478 $output .= html_writer::start_tag('thead', array()) . "\n";
1479 $output .= html_writer::start_tag('tr', array()) . "\n";
1480 $keys = array_keys($table->head);
1481 $lastkey = end($keys);
1482
1483 foreach ($table->head as $key => $heading) {
1484 // Convert plain string headings into html_table_cell objects
1485 if (!($heading instanceof html_table_cell)) {
1486 $headingtext = $heading;
1487 $heading = new html_table_cell();
1488 $heading->text = $headingtext;
1489 $heading->header = true;
1490 }
1491
1492 if ($heading->header !== false) {
1493 $heading->header = true;
1494 }
1495
e126c0cc
DM
1496 if ($heading->header && empty($heading->scope)) {
1497 $heading->scope = 'col';
1498 }
1499
16be8974
DM
1500 $heading->attributes['class'] .= ' header c' . $key;
1501 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1502 $heading->colspan = $table->headspan[$key];
1503 $countcols += $table->headspan[$key] - 1;
1504 }
1505
1506 if ($key == $lastkey) {
1507 $heading->attributes['class'] .= ' lastcol';
1508 }
1509 if (isset($table->colclasses[$key])) {
1510 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1511 }
e126c0cc 1512 $heading->attributes['class'] = trim($heading->attributes['class']);
16be8974
DM
1513 $attributes = array_merge($heading->attributes, array(
1514 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1515 'scope' => $heading->scope,
1516 'colspan' => $heading->colspan,
1517 ));
1518
1519 $tagtype = 'td';
1520 if ($heading->header === true) {
1521 $tagtype = 'th';
1522 }
1523 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1524 }
1525 $output .= html_writer::end_tag('tr') . "\n";
1526 $output .= html_writer::end_tag('thead') . "\n";
1527
1528 if (empty($table->data)) {
1529 // For valid XHTML strict every table must contain either a valid tr
1530 // or a valid tbody... both of which must contain a valid td
1531 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1532 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1533 $output .= html_writer::end_tag('tbody');
1534 }
1535 }
1536
1537 if (!empty($table->data)) {
1538 $oddeven = 1;
1539 $keys = array_keys($table->data);
1540 $lastrowkey = end($keys);
1541 $output .= html_writer::start_tag('tbody', array());
1542
1543 foreach ($table->data as $key => $row) {
1544 if (($row === 'hr') && ($countcols)) {
1545 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1546 } else {
1547 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1548 if (!($row instanceof html_table_row)) {
1549 $newrow = new html_table_row();
1550
4954d6ed
FM
1551 foreach ($row as $cell) {
1552 if (!($cell instanceof html_table_cell)) {
1553 $cell = new html_table_cell($cell);
1554 }
16be8974
DM
1555 $newrow->cells[] = $cell;
1556 }
1557 $row = $newrow;
1558 }
1559
1560 $oddeven = $oddeven ? 0 : 1;
1561 if (isset($table->rowclasses[$key])) {
1562 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1563 }
1564
1565 $row->attributes['class'] .= ' r' . $oddeven;
1566 if ($key == $lastrowkey) {
1567 $row->attributes['class'] .= ' lastrow';
1568 }
1569
e126c0cc 1570 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
16be8974
DM
1571 $keys2 = array_keys($row->cells);
1572 $lastkey = end($keys2);
1573
5174f3c5 1574 $gotlastkey = false; //flag for sanity checking
16be8974 1575 foreach ($row->cells as $key => $cell) {
5174f3c5
AD
1576 if ($gotlastkey) {
1577 //This should never happen. Why do we have a cell after the last cell?
1578 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1579 }
1580
16be8974
DM
1581 if (!($cell instanceof html_table_cell)) {
1582 $mycell = new html_table_cell();
1583 $mycell->text = $cell;
1584 $cell = $mycell;
1585 }
1586
e126c0cc
DM
1587 if (($cell->header === true) && empty($cell->scope)) {
1588 $cell->scope = 'row';
1589 }
1590
16be8974
DM
1591 if (isset($table->colclasses[$key])) {
1592 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1593 }
1594
1595 $cell->attributes['class'] .= ' cell c' . $key;
1596 if ($key == $lastkey) {
1597 $cell->attributes['class'] .= ' lastcol';
5174f3c5 1598 $gotlastkey = true;
16be8974
DM
1599 }
1600 $tdstyle = '';
1601 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1602 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1603 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1604 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1605 $tdattributes = array_merge($cell->attributes, array(
1606 'style' => $tdstyle . $cell->style,
1607 'colspan' => $cell->colspan,
1608 'rowspan' => $cell->rowspan,
1609 'id' => $cell->id,
1610 'abbr' => $cell->abbr,
1611 'scope' => $cell->scope,
1612 ));
1613 $tagtype = 'td';
1614 if ($cell->header === true) {
1615 $tagtype = 'th';
1616 }
1617 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1618 }
1619 }
1620 $output .= html_writer::end_tag('tr') . "\n";
1621 }
1622 $output .= html_writer::end_tag('tbody') . "\n";
1623 }
1624 $output .= html_writer::end_tag('table') . "\n";
1625
1626 return $output;
1627 }
1628
995f2d51
DM
1629 /**
1630 * Renders form element label
1631 *
1632 * By default, the label is suffixed with a label separator defined in the
1633 * current language pack (colon by default in the English lang pack).
1634 * Adding the colon can be explicitly disabled if needed. Label separators
1635 * are put outside the label tag itself so they are not read by
1636 * screenreaders (accessibility).
1637 *
1638 * Parameter $for explicitly associates the label with a form control. When
1639 * set, the value of this attribute must be the same as the value of
1640 * the id attribute of the form control in the same document. When null,
1641 * the label being defined is associated with the control inside the label
1642 * element.
1643 *
1644 * @param string $text content of the label tag
1645 * @param string|null $for id of the element this label is associated with, null for no association
1646 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1647 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1648 * @return string HTML of the label element
1649 */
9678c7b8 1650 public static function label($text, $for, $colonize = true, array $attributes=array()) {
995f2d51
DM
1651 if (!is_null($for)) {
1652 $attributes = array_merge($attributes, array('for' => $for));
1653 }
1654 $text = trim($text);
1655 $label = self::tag('label', $text, $attributes);
1656
9678c7b8
SH
1657 // TODO MDL-12192 $colonize disabled for now yet
1658 // if (!empty($text) and $colonize) {
1659 // // the $text may end with the colon already, though it is bad string definition style
1660 // $colon = get_string('labelsep', 'langconfig');
1661 // if (!empty($colon)) {
1662 // $trimmed = trim($colon);
1663 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1664 // //debugging('The label text should not end with colon or other label separator,
1665 // // please fix the string definition.', DEBUG_DEVELOPER);
1666 // } else {
1667 // $label .= $colon;
1668 // }
1669 // }
1670 // }
995f2d51
DM
1671
1672 return $label;
1673 }
4c4e5876 1674
1675 /**
1676 * Combines a class parameter with other attributes. Aids in code reduction
1677 * because the class parameter is very frequently used.
1678 *
1679 * If the class attribute is specified both in the attributes and in the
1680 * class parameter, the two values are combined with a space between.
1681 *
1682 * @param string $class Optional CSS class (or classes as space-separated list)
1683 * @param array $attributes Optional other attributes as array
1684 * @return array Attributes (or null if still none)
1685 */
1686 private static function add_class($class = '', array $attributes = null) {
1687 if ($class !== '') {
1688 $classattribute = array('class' => $class);
1689 if ($attributes) {
1690 if (array_key_exists('class', $attributes)) {
1691 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1692 } else {
1693 $attributes = $classattribute + $attributes;
1694 }
1695 } else {
1696 $attributes = $classattribute;
1697 }
1698 }
1699 return $attributes;
1700 }
1701
1702 /**
1703 * Creates a <div> tag. (Shortcut function.)
1704 *
1705 * @param string $content HTML content of tag
1706 * @param string $class Optional CSS class (or classes as space-separated list)
1707 * @param array $attributes Optional other attributes as array
1708 * @return string HTML code for div
1709 */
1710 public static function div($content, $class = '', array $attributes = null) {
1711 return self::tag('div', $content, self::add_class($class, $attributes));
1712 }
1713
1714 /**
1715 * Starts a <div> tag. (Shortcut function.)
1716 *
1717 * @param string $class Optional CSS class (or classes as space-separated list)
1718 * @param array $attributes Optional other attributes as array
1719 * @return string HTML code for open div tag
1720 */
1721 public static function start_div($class = '', array $attributes = null) {
1722 return self::start_tag('div', self::add_class($class, $attributes));
1723 }
1724
1725 /**
1726 * Ends a <div> tag. (Shortcut function.)
1727 *
1728 * @return string HTML code for close div tag
1729 */
1730 public static function end_div() {
1731 return self::end_tag('div');
1732 }
1733
1734 /**
1735 * Creates a <span> tag. (Shortcut function.)
1736 *
1737 * @param string $content HTML content of tag
1738 * @param string $class Optional CSS class (or classes as space-separated list)
1739 * @param array $attributes Optional other attributes as array
1740 * @return string HTML code for span
1741 */
1742 public static function span($content, $class = '', array $attributes = null) {
1743 return self::tag('span', $content, self::add_class($class, $attributes));
1744 }
1745
1746 /**
1747 * Starts a <span> tag. (Shortcut function.)
1748 *
1749 * @param string $class Optional CSS class (or classes as space-separated list)
1750 * @param array $attributes Optional other attributes as array
1751 * @return string HTML code for open span tag
1752 */
1753 public static function start_span($class = '', array $attributes = null) {
1754 return self::start_tag('span', self::add_class($class, $attributes));
1755 }
1756
1757 /**
1758 * Ends a <span> tag. (Shortcut function.)
1759 *
1760 * @return string HTML code for close span tag
1761 */
1762 public static function end_span() {
1763 return self::end_tag('span');
1764 }
5d0c95a5
PS
1765}
1766
227255b8
PS
1767/**
1768 * Simple javascript output class
9678c7b8 1769 *
227255b8 1770 * @copyright 2010 Petr Skoda
9678c7b8
SH
1771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1772 * @since Moodle 2.0
f8129210 1773 * @package core
76be40cc 1774 * @category output
227255b8
PS
1775 */
1776class js_writer {
9678c7b8 1777
227255b8
PS
1778 /**
1779 * Returns javascript code calling the function
9678c7b8 1780 *
1a10840e 1781 * @param string $function function name, can be complex like Y.Event.purgeElement
227255b8
PS
1782 * @param array $arguments parameters
1783 * @param int $delay execution delay in seconds
1784 * @return string JS code fragment
1785 */
e839dce1 1786 public static function function_call($function, array $arguments = null, $delay=0) {
1b4e41af 1787 if ($arguments) {
b2cb00c2 1788 $arguments = array_map('json_encode', convert_to_array($arguments));
1b4e41af
PS
1789 $arguments = implode(', ', $arguments);
1790 } else {
1791 $arguments = '';
1792 }
227255b8
PS
1793 $js = "$function($arguments);";
1794
1795 if ($delay) {
1796 $delay = $delay * 1000; // in miliseconds
1797 $js = "setTimeout(function() { $js }, $delay);";
1798 }
1799 return $js . "\n";
1800 }
1801
3b01539c 1802 /**
3d3fae72 1803 * Special function which adds Y as first argument of function call.
9678c7b8 1804 *
3d3fae72
SH
1805 * @param string $function The function to call
1806 * @param array $extraarguments Any arguments to pass to it
1807 * @return string Some JS code
3b01539c 1808 */
e839dce1 1809 public static function function_call_with_Y($function, array $extraarguments = null) {
3b01539c 1810 if ($extraarguments) {
b2cb00c2 1811 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
3b01539c
PS
1812 $arguments = 'Y, ' . implode(', ', $extraarguments);
1813 } else {
1814 $arguments = 'Y';
1815 }
1816 return "$function($arguments);\n";
1817 }
1818
1ce15fda
SH
1819 /**
1820 * Returns JavaScript code to initialise a new object
9678c7b8 1821 *
3d3fae72
SH
1822 * @param string $var If it is null then no var is assigned the new object.
1823 * @param string $class The class to initialise an object for.
1824 * @param array $arguments An array of args to pass to the init method.
1825 * @param array $requirements Any modules required for this class.
1826 * @param int $delay The delay before initialisation. 0 = no delay.
1827 * @return string Some JS code
1ce15fda 1828 */
e839dce1 1829 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1ce15fda 1830 if (is_array($arguments)) {
b2cb00c2 1831 $arguments = array_map('json_encode', convert_to_array($arguments));
1ce15fda
SH
1832 $arguments = implode(', ', $arguments);
1833 }
1834
1835 if ($var === null) {
53fc3e70 1836 $js = "new $class(Y, $arguments);";
1ce15fda 1837 } else if (strpos($var, '.')!==false) {
53fc3e70 1838 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1839 } else {
53fc3e70 1840 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1841 }
1842
1843 if ($delay) {
1844 $delay = $delay * 1000; // in miliseconds
1845 $js = "setTimeout(function() { $js }, $delay);";
1846 }
1847
1848 if (count($requirements) > 0) {
1849 $requirements = implode("', '", $requirements);
53fc3e70 1850 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1851 }
1852 return $js."\n";
1853 }
1854
227255b8
PS
1855 /**
1856 * Returns code setting value to variable
9678c7b8 1857 *
227255b8
PS
1858 * @param string $name
1859 * @param mixed $value json serialised value
1860 * @param bool $usevar add var definition, ignored for nested properties
1861 * @return string JS code fragment
1862 */
9678c7b8 1863 public static function set_variable($name, $value, $usevar = true) {
227255b8
PS
1864 $output = '';
1865
1866 if ($usevar) {
1867 if (strpos($name, '.')) {
1868 $output .= '';
1869 } else {
1870 $output .= 'var ';
1871 }
1872 }
1873
1874 $output .= "$name = ".json_encode($value).";";
1875
1876 return $output;
1877 }
1878
1879 /**
1880 * Writes event handler attaching code
9678c7b8 1881 *
f8129210
SH
1882 * @param array|string $selector standard YUI selector for elements, may be
1883 * array or string, element id is in the form "#idvalue"
227255b8
PS
1884 * @param string $event A valid DOM event (click, mousedown, change etc.)
1885 * @param string $function The name of the function to call
9678c7b8 1886 * @param array $arguments An optional array of argument parameters to pass to the function
227255b8
PS
1887 * @return string JS code fragment
1888 */
e839dce1 1889 public static function event_handler($selector, $event, $function, array $arguments = null) {
227255b8
PS
1890 $selector = json_encode($selector);
1891 $output = "Y.on('$event', $function, $selector, null";
1892 if (!empty($arguments)) {
1893 $output .= ', ' . json_encode($arguments);
1894 }
1895 return $output . ");\n";
1896 }
1897}
1898
d9c8f425 1899/**
f8129210 1900 * Holds all the information required to render a <table> by {@link core_renderer::table()}
d9c8f425 1901 *
16be8974
DM
1902 * Example of usage:
1903 * $t = new html_table();
1904 * ... // set various properties of the object $t as described below
1905 * echo html_writer::table($t);
d9c8f425 1906 *
16be8974 1907 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
9678c7b8
SH
1908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1909 * @since Moodle 2.0
f8129210 1910 * @package core
76be40cc 1911 * @category output
d9c8f425 1912 */
16be8974 1913class html_table {
9678c7b8 1914
d9c8f425 1915 /**
76be40cc 1916 * @var string Value to use for the id attribute of the table
d9c8f425 1917 */
97c10099 1918 public $id = null;
9678c7b8 1919
d9c8f425 1920 /**
76be40cc 1921 * @var array Attributes of HTML attributes for the <table> element
d9c8f425 1922 */
16be8974 1923 public $attributes = array();
9678c7b8 1924
7b1f2c82 1925 /**
76be40cc 1926 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
a0ead5eb 1927 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1928 * can be passed instead of an array of strings.
7b1f2c82 1929 *
1930 * Example of usage:
1931 * $t->head = array('Student', 'Grade');
1932 */
1933 public $head;
9678c7b8 1934
7b1f2c82 1935 /**
76be40cc 1936 * @var array An array that can be used to make a heading span multiple columns.
f8129210
SH
1937 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1938 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
7b1f2c82 1939 *
1940 * Example of usage:
1941 * $t->headspan = array(2,1);
7b1f2c82 1942 */
1943 public $headspan;
9678c7b8 1944
7b1f2c82 1945 /**
76be40cc 1946 * @var array An array of column alignments.
9678c7b8 1947 * The value is used as CSS 'text-align' property. Therefore, possible
7b1f2c82 1948 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1949 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1950 *
beb56299 1951 * Examples of usage:
1952 * $t->align = array(null, 'right');
1953 * or
1954 * $t->align[1] = 'right';
d9c8f425 1955 */
beb56299 1956 public $align;
9678c7b8 1957
d9c8f425 1958 /**
76be40cc 1959 * @var array The value is used as CSS 'size' property.
beb56299 1960 *
1961 * Examples of usage:
1962 * $t->size = array('50%', '50%');
1963 * or
1964 * $t->size[1] = '120px';
d9c8f425 1965 */
beb56299 1966 public $size;
9678c7b8 1967
d9c8f425 1968 /**
76be40cc 1969 * @var array An array of wrapping information.
9678c7b8 1970 * The only possible value is 'nowrap' that sets the
beb56299 1971 * CSS property 'white-space' to the value 'nowrap' in the given column.
1972 *
1973 * Example of usage:
1974 * $t->wrap = array(null, 'nowrap');
d9c8f425 1975 */
beb56299 1976 public $wrap;
9678c7b8 1977
d9c8f425 1978 /**
76be40cc 1979 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
beb56299 1980 * $head specified, the string 'hr' (for horizontal ruler) can be used
1981 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1982 *
beb56299 1983 * Example of usage with array of arrays:
1984 * $row1 = array('Harry Potter', '76 %');
1985 * $row2 = array('Hermione Granger', '100 %');
1986 * $t->data = array($row1, $row2);
d9c8f425 1987 *
beb56299 1988 * Example with array of html_table_row objects: (used for more fine-grained control)
1989 * $cell1 = new html_table_cell();
1990 * $cell1->text = 'Harry Potter';
1991 * $cell1->colspan = 2;
1992 * $row1 = new html_table_row();
1993 * $row1->cells[] = $cell1;
1994 * $cell2 = new html_table_cell();
1995 * $cell2->text = 'Hermione Granger';
1996 * $cell3 = new html_table_cell();
1997 * $cell3->text = '100 %';
1998 * $row2 = new html_table_row();
1999 * $row2->cells = array($cell2, $cell3);
2000 * $t->data = array($row1, $row2);
2001 */
2002 public $data;
9678c7b8 2003
beb56299 2004 /**
beb56299 2005 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 2006 * @var string Width of the table, percentage of the page preferred.
beb56299 2007 */
2008 public $width = null;
9678c7b8 2009
beb56299 2010 /**
beb56299 2011 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 2012 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
beb56299 2013 */
2014 public $tablealign = null;
9678c7b8 2015
beb56299 2016 /**
beb56299 2017 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 2018 * @var int Padding on each cell, in pixels
beb56299 2019 */
2020 public $cellpadding = null;
9678c7b8 2021
beb56299 2022 /**
76be40cc 2023 * @var int Spacing between cells, in pixels
beb56299 2024 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2025 */
2026 public $cellspacing = null;
9678c7b8 2027
beb56299 2028 /**
76be40cc 2029 * @var array Array of classes to add to particular rows, space-separated string.
beb56299 2030 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2031 * respectively. Class 'lastrow' is added automatically for the last row
2032 * in the table.
d9c8f425 2033 *
beb56299 2034 * Example of usage:
2035 * $t->rowclasses[9] = 'tenth'
2036 */
2037 public $rowclasses;
9678c7b8 2038
beb56299 2039 /**
76be40cc 2040 * @var array An array of classes to add to every cell in a particular column,
beb56299 2041 * space-separated string. Class 'cell' is added automatically by the renderer.
2042 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2043 * respectively. Class 'lastcol' is added automatically for all last cells
2044 * in a row.
d9c8f425 2045 *
beb56299 2046 * Example of usage:
2047 * $t->colclasses = array(null, 'grade');
d9c8f425 2048 */
beb56299 2049 public $colclasses;
9678c7b8 2050
beb56299 2051 /**
76be40cc 2052 * @var string Description of the contents for screen readers.
beb56299 2053 */
2054 public $summary;
d9c8f425 2055
2056 /**
16be8974 2057 * Constructor
d9c8f425 2058 */
16be8974
DM
2059 public function __construct() {
2060 $this->attributes['class'] = '';
d9c8f425 2061 }
d9c8f425 2062}
2063
2064/**
7b1f2c82 2065 * Component representing a table row.
d9c8f425 2066 *
2067 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2069 * @since Moodle 2.0
f8129210 2070 * @package core
76be40cc 2071 * @category output
d9c8f425 2072 */
16be8974 2073class html_table_row {
9678c7b8 2074
16be8974 2075 /**
76be40cc 2076 * @var string Value to use for the id attribute of the row.
16be8974
DM
2077 */
2078 public $id = null;
9678c7b8 2079
d9c8f425 2080 /**
76be40cc 2081 * @var array Array of html_table_cell objects
d9c8f425 2082 */
7b1f2c82 2083 public $cells = array();
9678c7b8 2084
beb56299 2085 /**
76be40cc 2086 * @var string Value to use for the style attribute of the table row
beb56299 2087 */
16be8974 2088 public $style = null;
9678c7b8 2089
16be8974 2090 /**
76be40cc 2091 * @var array Attributes of additional HTML attributes for the <tr> element
16be8974
DM
2092 */
2093 public $attributes = array();
a0ead5eb 2094
54a007e8 2095 /**
8cea545e 2096 * Constructor
54a007e8 2097 * @param array $cells
8cea545e
PS
2098 */
2099 public function __construct(array $cells=null) {
16be8974 2100 $this->attributes['class'] = '';
8cea545e
PS
2101 $cells = (array)$cells;
2102 foreach ($cells as $cell) {
2103 if ($cell instanceof html_table_cell) {
2104 $this->cells[] = $cell;
a019627a 2105 } else {
8cea545e 2106 $this->cells[] = new html_table_cell($cell);
a019627a 2107 }
2108 }
54a007e8 2109 }
d9c8f425 2110}
2111
2112/**
7b1f2c82 2113 * Component representing a table cell.
d9c8f425 2114 *
2115 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2117 * @since Moodle 2.0
f8129210 2118 * @package core
76be40cc 2119 * @category output
d9c8f425 2120 */
16be8974 2121class html_table_cell {
9678c7b8 2122
16be8974 2123 /**
76be40cc 2124 * @var string Value to use for the id attribute of the cell.
16be8974
DM
2125 */
2126 public $id = null;
9678c7b8 2127
d9c8f425 2128 /**
76be40cc 2129 * @var string The contents of the cell.
d9c8f425 2130 */
7b1f2c82 2131 public $text;
9678c7b8 2132
d9c8f425 2133 /**
76be40cc 2134 * @var string Abbreviated version of the contents of the cell.
d9c8f425 2135 */
97c10099 2136 public $abbr = null;
9678c7b8 2137
d9c8f425 2138 /**
76be40cc 2139 * @var int Number of columns this cell should span.
d9c8f425 2140 */
97c10099 2141 public $colspan = null;
9678c7b8 2142
d9c8f425 2143 /**
76be40cc 2144 * @var int Number of rows this cell should span.
d9c8f425 2145 */
97c10099 2146 public $rowspan = null;
9678c7b8 2147
d9c8f425 2148 /**
76be40cc 2149 * @var string Defines a way to associate header cells and data cells in a table.
d9c8f425 2150 */
97c10099 2151 public $scope = null;
9678c7b8 2152
1ae3767a 2153 /**
3d3fae72 2154 * @var bool Whether or not this cell is a header cell.
1ae3767a 2155 */
a4998d01 2156 public $header = null;
9678c7b8 2157
16be8974 2158 /**
76be40cc 2159 * @var string Value to use for the style attribute of the table cell
16be8974
DM
2160 */
2161 public $style = null;
9678c7b8 2162
16be8974 2163 /**
76be40cc 2164 * @var array Attributes of additional HTML attributes for the <td> element
16be8974
DM
2165 */
2166 public $attributes = array();
d9c8f425 2167
9678c7b8
SH
2168 /**
2169 * Constructs a table cell
2170 *
2171 * @param string $text
2172 */
8cea545e
PS
2173 public function __construct($text = null) {
2174 $this->text = $text;
16be8974 2175 $this->attributes['class'] = '';
d9c8f425 2176 }
2177}
2178
d9c8f425 2179/**
beb56299 2180 * Component representing a paging bar.
d9c8f425 2181 *
2182 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2184 * @since Moodle 2.0
f8129210 2185 * @package core
76be40cc 2186 * @category output
d9c8f425 2187 */
929d7a83 2188class paging_bar implements renderable {
9678c7b8 2189
d9c8f425 2190 /**
76be40cc 2191 * @var int The maximum number of pagelinks to display.
d9c8f425 2192 */
beb56299 2193 public $maxdisplay = 18;
9678c7b8 2194
d9c8f425 2195 /**
76be40cc 2196 * @var int The total number of entries to be pages through..
d9c8f425 2197 */
beb56299 2198 public $totalcount;
9678c7b8 2199
d9c8f425 2200 /**
76be40cc 2201 * @var int The page you are currently viewing.
d9c8f425 2202 */
929d7a83 2203 public $page;
9678c7b8 2204
d9c8f425 2205 /**
76be40cc 2206 * @var int The number of entries that should be shown per page.
d9c8f425 2207 */
beb56299 2208 public $perpage;
9678c7b8 2209
d9c8f425 2210 /**
76be40cc 2211 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
9678c7b8
SH
2212 * an equals sign and the page number.
2213 * If this is a moodle_url object then the pagevar param will be replaced by
2214 * the page no, for each page.
d9c8f425 2215 */
beb56299 2216 public $baseurl;
9678c7b8 2217
d9c8f425 2218 /**
76be40cc 2219 * @var string This is the variable name that you use for the pagenumber in your
9678c7b8 2220 * code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 2221 */
929d7a83 2222 public $pagevar;
9678c7b8 2223
beb56299 2224 /**
76be40cc 2225 * @var string A HTML link representing the "previous" page.
beb56299 2226 */
2227 public $previouslink = null;
9678c7b8 2228
beb56299 2229 /**
76be40cc 2230 * @var string A HTML link representing the "next" page.
beb56299 2231 */
2232 public $nextlink = null;
9678c7b8 2233
beb56299 2234 /**
76be40cc 2235 * @var string A HTML link representing the first page.
beb56299 2236 */
2237 public $firstlink = null;
9678c7b8 2238
beb56299 2239 /**
76be40cc 2240 * @var string A HTML link representing the last page.
beb56299 2241 */
2242 public $lastlink = null;
9678c7b8 2243
beb56299 2244 /**
76be40cc 2245 * @var array An array of strings. One of them is just a string: the current page
beb56299 2246 */
2247 public $pagelinks = array();
d9c8f425 2248
929d7a83
PS
2249 /**
2250 * Constructor paging_bar with only the required params.
2251 *
1a10840e 2252 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2253 * @param int $page The page you are currently viewing
2254 * @param int $perpage The number of entries that should be shown per page
2255 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2256 * @param string $pagevar name of page parameter that holds the page number
2257 */
2258 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2259 $this->totalcount = $totalcount;
2260 $this->page = $page;
2261 $this->perpage = $perpage;
2262 $this->baseurl = $baseurl;
2263 $this->pagevar = $pagevar;
2264 }
2265
d9c8f425 2266 /**
9678c7b8
SH
2267 * Prepares the paging bar for output.
2268 *
2269 * This method validates the arguments set up for the paging bar and then
2270 * produces fragments of HTML to assist display later on.
f8129210
SH
2271 *
2272 * @param renderer_base $output
2273 * @param moodle_page $page
2274 * @param string $target
2275 * @throws coding_exception
d9c8f425 2276 */
34059565 2277 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 2278 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 2279 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 2280 }
2281 if (!isset($this->page) || is_null($this->page)) {
929d7a83 2282 throw new coding_exception('paging_bar requires a page value.');
beb56299 2283 }
2284 if (empty($this->perpage)) {
929d7a83 2285 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 2286 }
2287 if (empty($this->baseurl)) {
929d7a83 2288 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 2289 }
d9c8f425 2290
beb56299 2291 if ($this->totalcount > $this->perpage) {
2292 $pagenum = $this->page - 1;
d9c8f425 2293
beb56299 2294 if ($this->page > 0) {
929d7a83 2295 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 2296 }
d9c8f425 2297
beb56299 2298 if ($this->perpage > 0) {
2299 $lastpage = ceil($this->totalcount / $this->perpage);
2300 } else {
2301 $lastpage = 1;
2302 }
2303
0232fa7b
JF
2304 if ($this->page > round(($this->maxdisplay/3)*2)) {
2305 $currpage = $this->page - round($this->maxdisplay/3);
beb56299 2306
929d7a83 2307 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 2308 } else {
0232fa7b 2309 $currpage = 0;
beb56299 2310 }
2311
beb56299 2312 $displaycount = $displaypage = 0;
2313
2314 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2315 $displaypage = $currpage + 1;
2316
f43cdceb 2317 if ($this->page == $currpage) {
beb56299 2318 $this->pagelinks[] = $displaypage;
2319 } else {
56ddb719 2320 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 2321 $this->pagelinks[] = $pagelink;
2322 }
2323
2324 $displaycount++;
2325 $currpage++;
2326 }
2327
2328 if ($currpage < $lastpage) {
2329 $lastpageactual = $lastpage - 1;
abdac127 2330 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 2331 }
2332
2333 $pagenum = $this->page + 1;
2334
2335 if ($pagenum != $displaypage) {
abdac127 2336 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 2337 }
d9c8f425 2338 }
2339 }
d9c8f425 2340}
2341
d9c8f425 2342/**
beb56299 2343 * This class represents how a block appears on a page.
d9c8f425 2344 *
beb56299 2345 * During output, each block instance is asked to return a block_contents object,
2346 * those are then passed to the $OUTPUT->block function for display.
2347 *
f8129210 2348 * contents should probably be generated using a moodle_block_..._renderer.
beb56299 2349 *
2350 * Other block-like things that need to appear on the page, for example the
2351 * add new block UI, are also represented as block_contents objects.
2352 *
2353 * @copyright 2009 Tim Hunt
9678c7b8
SH
2354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2355 * @since Moodle 2.0
f8129210 2356 * @package core
76be40cc 2357 * @category output
d9c8f425 2358 */
dd72b308 2359class block_contents {
beb56299 2360
76be40cc 2361 /** Used when the block cannot be collapsed **/
beb56299 2362 const NOT_HIDEABLE = 0;
76be40cc
SH
2363
2364 /** Used when the block can be collapsed but currently is not **/
beb56299 2365 const VISIBLE = 1;
76be40cc
SH
2366
2367 /** Used when the block has been collapsed **/
beb56299 2368 const HIDDEN = 2;
2369
d9c8f425 2370 /**
76be40cc 2371 * @var int Used to set $skipid.
9678c7b8
SH
2372 */
2373 protected static $idcounter = 1;
2374
2375 /**
3d3fae72 2376 * @var int All the blocks (or things that look like blocks) printed on
76be40cc 2377 * a page are given a unique number that can be used to construct id="" attributes.
9678c7b8 2378 * This is set automatically be the {@link prepare()} method.
beb56299 2379 * Do not try to set it manually.
d9c8f425 2380 */
beb56299 2381 public $skipid;
d9c8f425 2382
2383 /**
3d3fae72 2384 * @var int If this is the contents of a real block, this should be set
76be40cc 2385 * to the block_instance.id. Otherwise this should be set to 0.
beb56299 2386 */
2387 public $blockinstanceid = 0;
2388
2389 /**
3d3fae72 2390 * @var int If this is a real block instance, and there is a corresponding
beb56299 2391 * block_position.id for the block on this page, this should be set to that id.
2392 * Otherwise it should be 0.
2393 */
2394 public $blockpositionid = 0;
2395
2396 /**
76be40cc 2397 * @var array An array of attribute => value pairs that are put on the outer div of this
9678c7b8 2398 * block. {@link $id} and {@link $classes} attributes should be set separately.
beb56299 2399 */
dd72b308 2400 public $attributes;
beb56299 2401
2402 /**
76be40cc 2403 * @var string The title of this block. If this came from user input, it should already
9678c7b8
SH
2404 * have had format_string() processing done on it. This will be output inside
2405 * <h2> tags. Please do not cause invalid XHTML.
beb56299 2406 */
2407 public $title = '';
2408
91d941c3
SH
2409 /**
2410 * @var string The label to use when the block does not, or will not have a visible title.
2411 * You should never set this as well as title... it will just be ignored.
2412 */
2413 public $arialabel = '';
2414
beb56299 2415 /**
76be40cc 2416 * @var string HTML for the content
beb56299 2417 */
2418 public $content = '';
2419
2420 /**
76be40cc 2421 * @var array An alternative to $content, it you want a list of things with optional icons.
beb56299 2422 */
2423 public $footer = '';
2424
2425 /**
76be40cc
SH
2426 * @var string Any small print that should appear under the block to explain
2427 * to the teacher about the block, for example 'This is a sticky block that was
beb56299 2428 * added in the system context.'
beb56299 2429 */
2430 public $annotation = '';
2431
2432 /**
3d3fae72 2433 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
beb56299 2434 * the user can toggle whether this block is visible.
2435 */
2436 public $collapsible = self::NOT_HIDEABLE;
2437
2438 /**
76be40cc
SH
2439 * @var array A (possibly empty) array of editing controls. Each element of
2440 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 2441 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 2442 */
2443 public $controls = array();
2444
dd72b308 2445
beb56299 2446 /**
dd72b308
PS
2447 * Create new instance of block content
2448 * @param array $attributes
d9c8f425 2449 */
9678c7b8 2450 public function __construct(array $attributes = null) {
beb56299 2451 $this->skipid = self::$idcounter;
2452 self::$idcounter += 1;
dd72b308
PS
2453
2454 if ($attributes) {
2455 // standard block
2456 $this->attributes = $attributes;
2457 } else {
2458 // simple "fake" blocks used in some modules and "Add new block" block
6605ff8c 2459 $this->attributes = array('class'=>'block');
beb56299 2460 }
dd72b308
PS
2461 }
2462
2463 /**
2464 * Add html class to block
9678c7b8 2465 *
dd72b308 2466 * @param string $class
dd72b308
PS
2467 */
2468 public function add_class($class) {
2469 $this->attributes['class'] .= ' '.$class;
d9c8f425 2470 }
2471}
beb56299 2472
34059565 2473
beb56299 2474/**
2475 * This class represents a target for where a block can go when it is being moved.
2476 *
2477 * This needs to be rendered as a form with the given hidden from fields, and
2478 * clicking anywhere in the form should submit it. The form action should be
2479 * $PAGE->url.
2480 *
2481 * @copyright 2009 Tim Hunt
9678c7b8
SH
2482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2483 * @since Moodle 2.0
f8129210 2484 * @package core
76be40cc 2485 * @category output
beb56299 2486 */
dd72b308 2487class block_move_target {
9678c7b8 2488
beb56299 2489 /**
76be40cc 2490 * @var moodle_url Move url
beb56299 2491 */
dd72b308 2492 public $url;
9678c7b8 2493
dd72b308 2494 /**
1a10840e 2495 * Constructor
dd72b308
PS
2496 * @param moodle_url $url
2497 */
6671fa73 2498 public function __construct(moodle_url $url) {
dd72b308
PS
2499 $this->url = $url;
2500 }
beb56299 2501}
d2dbd0c0
SH
2502
2503/**
2504 * Custom menu item
2505 *
2506 * This class is used to represent one item within a custom menu that may or may
2507 * not have children.
2508 *
2509 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2511 * @since Moodle 2.0
f8129210 2512 * @package core
76be40cc 2513 * @category output
d2dbd0c0
SH
2514 */
2515class custom_menu_item implements renderable {
9678c7b8 2516
d2dbd0c0 2517 /**
76be40cc 2518 * @var string The text to show for the item
d2dbd0c0
SH
2519 */
2520 protected $text;
9678c7b8 2521
d2dbd0c0 2522 /**
76be40cc 2523 * @var moodle_url The link to give the icon if it has no children
d2dbd0c0
SH
2524 */
2525 protected $url;
9678c7b8 2526
d2dbd0c0 2527 /**
76be40cc 2528 * @var string A title to apply to the item. By default the text
d2dbd0c0
SH
2529 */
2530 protected $title;
9678c7b8 2531
d2dbd0c0 2532 /**
76be40cc
SH
2533 * @var int A sort order for the item, not necessary if you order things in
2534 * the CFG var.
d2dbd0c0
SH
2535 */
2536 protected $sort;
9678c7b8 2537
d2dbd0c0 2538 /**
76be40cc
SH
2539 * @var custom_menu_item A reference to the parent for this item or NULL if
2540 * it is a top level item
d2dbd0c0
SH
2541 */
2542 protected $parent;
9678c7b8 2543
d2dbd0c0 2544 /**
76be40cc 2545 * @var array A array in which to store children this item has.
d2dbd0c0
SH
2546 */
2547 protected $children = array();
9678c7b8 2548
d2dbd0c0 2549 /**
76be40cc 2550 * @var int A reference to the sort var of the last child that was added
d2dbd0c0
SH
2551 */
2552 protected $lastsort = 0;
9678c7b8 2553
d2dbd0c0
SH
2554 /**
2555 * Constructs the new custom menu item
2556 *
2557 * @param string $text
2558 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2559 * @param string $title A title to apply to this item [Optional]
2560 * @param int $sort A sort or to use if we need to sort differently [Optional]
2561 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2562 * belongs to, only if the child has a parent. [Optional]
2563 */
9678c7b8 2564 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
d2dbd0c0
SH
2565 $this->text = $text;
2566 $this->url = $url;
2567 $this->title = $title;
2568 $this->sort = (int)$sort;
2569 $this->parent = $parent;
2570 }
2571
2572 /**
2573 * Adds a custom menu item as a child of this node given its properties.
2574 *
2575 * @param string $text
2576 * @param moodle_url $url
2577 * @param string $title
2578 * @param int $sort
2579 * @return custom_menu_item
2580 */
9678c7b8 2581 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
d2dbd0c0
SH
2582 $key = count($this->children);
2583 if (empty($sort)) {
2584 $sort = $this->lastsort + 1;
2585 }
2586 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2587 $this->lastsort = (int)$sort;
2588 return $this->children[$key];
2589 }
9678c7b8 2590
d2dbd0c0
SH
2591 /**
2592 * Returns the text for this item
2593 * @return string
2594 */
2595 public function get_text() {
2596 return $this->text;
2597 }
9678c7b8 2598
d2dbd0c0
SH
2599 /**
2600 * Returns the url for this item
2601 * @return moodle_url
2602 */
2603 public function get_url() {
2604 return $this->url;
2605 }
9678c7b8 2606
d2dbd0c0
SH
2607 /**
2608 * Returns the title for this item
2609 * @return string
2610 */
2611 public function get_title() {
2612 return $this->title;
2613 }
9678c7b8 2614
d2dbd0c0
SH
2615 /**
2616 * Sorts and returns the children for this item
2617 * @return array
2618 */
2619 public function get_children() {
2620 $this->sort();
2621 return $this->children;
2622 }
9678c7b8 2623
d2dbd0c0
SH
2624 /**
2625 * Gets the sort order for this child
2626 * @return int
2627 */
2628 public function get_sort_order() {
2629 return $this->sort;
2630 }
9678c7b8 2631
d2dbd0c0
SH
2632 /**
2633 * Gets the parent this child belong to
2634 * @return custom_menu_item
2635 */
2636 public function get_parent() {
2637 return $this->parent;
2638 }
9678c7b8 2639
d2dbd0c0
SH
2640 /**
2641 * Sorts the children this item has
2642 */
2643 public function sort() {
2644 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2645 }
9678c7b8 2646
d2dbd0c0
SH
2647 /**
2648 * Returns true if this item has any children
2649 * @return bool
2650 */
2651 public function has_children() {
2652 return (count($this->children) > 0);
2653 }
f3827323
SH
2654
2655 /**
2656 * Sets the text for the node
2657 * @param string $text
2658 */
2659 public function set_text($text) {
2660 $this->text = (string)$text;
2661 }
2662
2663 /**
2664 * Sets the title for the node
2665 * @param string $title
2666 */
2667 public function set_title($title) {
2668 $this->title = (string)$title;
2669 }
2670
2671 /**
2672 * Sets the url for the node
2673 * @param moodle_url $url
2674 */
2675 public function set_url(moodle_url $url) {
2676 $this->url = $url;
2677 }
d2dbd0c0
SH
2678}
2679
2680/**
2681 * Custom menu class
2682 *
2683 * This class is used to operate a custom menu that can be rendered for the page.
2684 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2685 * of custom_menu_item nodes that can be rendered by the core renderer.
2686 *
2687 * To configure the custom menu:
2688 * Settings: Administration > Appearance > Themes > Theme settings
2689 *
2690 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2692 * @since Moodle 2.0
f8129210 2693 * @package core
76be40cc 2694 * @category output
d2dbd0c0
SH
2695 */
2696class custom_menu extends custom_menu_item {
155fffe6 2697
9678c7b8 2698 /**
76be40cc 2699 * @var string The language we should render for, null disables multilang support.
9678c7b8 2700 */
4564d58f
DM
2701 protected $currentlanguage = null;
2702
d2dbd0c0
SH
2703 /**
2704 * Creates the custom menu
155fffe6
DM
2705 *
2706 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
f8129210 2707 * @param string $currentlanguage the current language code, null disables multilang support
d2dbd0c0 2708 */
4564d58f 2709 public function __construct($definition = '', $currentlanguage = null) {
4564d58f 2710 $this->currentlanguage = $currentlanguage;
155fffe6
DM
2711 parent::__construct('root'); // create virtual root element of the menu
2712 if (!empty($definition)) {
4564d58f 2713 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
12cc75ae 2714 }
d2dbd0c0
SH
2715 }
2716
2717 /**
2718 * Overrides the children of this custom menu. Useful when getting children
2719 * from $CFG->custommenuitems
9678c7b8
SH
2720 *
2721 * @param array $children
d2dbd0c0
SH
2722 */
2723 public function override_children(array $children) {
2724 $this->children = array();
2725 foreach ($children as $child) {
2726 if ($child instanceof custom_menu_item) {
2727 $this->children[] = $child;
2728 }
2729 }
2730 }
2731
2732 /**
2733 * Converts a string into a structured array of custom_menu_items which can
2734 * then be added to a custom menu.
2735 *
2736 * Structure:
4564d58f
DM
2737 * text|url|title|langs
2738 * The number of hyphens at the start determines the depth of the item. The
2739 * languages are optional, comma separated list of languages the line is for.
d2dbd0c0
SH
2740 *
2741 * Example structure:
2742 * First level first item|http://www.moodle.com/
2743 * -Second level first item|http://www.moodle.com/partners/
2744 * -Second level second item|http://www.moodle.com/hq/
2745 * --Third level first item|http://www.moodle.com/jobs/
2746 * -Second level third item|http://www.moodle.com/development/
2747 * First level second item|http://www.moodle.com/feedback/
2748 * First level third item
4564d58f
DM
2749 * English only|http://moodle.com|English only item|en
2750 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2751 *
4d2ee4c2 2752 *
d2dbd0c0 2753 * @static
4564d58f
DM
2754 * @param string $text the menu items definition
2755 * @param string $language the language code, null disables multilang support
d2dbd0c0
SH
2756 * @return array
2757 */
4564d58f 2758 public static function convert_text_to_menu_nodes($text, $language = null) {
d2dbd0c0
SH
2759 $lines = explode("\n", $text);
2760 $children = array();
2761 $lastchild = null;
2762 $lastdepth = null;
2763 $lastsort = 0;
2764 foreach ($lines as $line) {
2765 $line = trim($line);
4564d58f
DM
2766 $bits = explode('|', $line, 4); // name|url|title|langs
2767 if (!array_key_exists(0, $bits) or empty($bits[0])) {
d2dbd0c0
SH
2768 // Every item must have a name to be valid
2769 continue;
2770 } else {
2771 $bits[0] = ltrim($bits[0],'-');
2772 }
4564d58f 2773 if (!array_key_exists(1, $bits) or empty($bits[1])) {
d2dbd0c0
SH
2774 // Set the url to null
2775 $bits[1] = null;
2776 } else {
2777 // Make sure the url is a moodle url
a26f25ae 2778 $bits[1] = new moodle_url(trim($bits[1]));
d2dbd0c0 2779 }
4564d58f 2780 if (!array_key_exists(2, $bits) or empty($bits[2])) {
d2dbd0c0
SH
2781 // Set the title to null seeing as there isn't one
2782 $bits[2] = $bits[0];
2783 }
4564d58f
DM
2784 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2785 // The item is valid for all languages
2786 $itemlangs = null;
2787 } else {
2788 $itemlangs = array_map('trim', explode(',', $bits[3]));
2789 }
2790 if (!empty($language) and !empty($itemlangs)) {
2791 // check that the item is intended for the current language
2792 if (!in_array($language, $itemlangs)) {
2793 continue;
2794 }
2795 }
d2dbd0c0 2796 // Set an incremental sort order to keep it simple.
4564d58f 2797 $lastsort++;
d2dbd0c0
SH
2798 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2799 $depth = strlen($match[1]);
2800 if ($depth < $lastdepth) {
57bedaee
SH
2801 $difference = $lastdepth - $depth;
2802 if ($lastdepth > 1 && $lastdepth != $difference) {
2803 $tempchild = $lastchild->get_parent();
2804 for ($i =0; $i < $difference; $i++) {
2805 $tempchild = $tempchild->get_parent();
2806 }
4564d58f 2807 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2808 } else {
2809 $depth = 0;
4564d58f 2810 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2811 $children[] = $lastchild;
2812 }
2813 } else if ($depth > $lastdepth) {
2814 $depth = $lastdepth + 1;
4564d58f 2815 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2816 } else {
2817 if ($depth == 0) {
4564d58f 2818 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2819 $children[] = $lastchild;
2820 } else {
4564d58f 2821 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2822 }
2823 }
2824 } else {
2825 $depth = 0;
4564d58f 2826 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2827 $children[] = $lastchild;
2828 }
2829 $lastdepth = $depth;
2830 }
2831 return $children;
2832 }
2833
2834 /**
2835 * Sorts two custom menu items
2836 *
2837 * This function is designed to be used with the usort method
2838 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2839 *
9678c7b8 2840 * @static
d2dbd0c0
SH
2841 * @param custom_menu_item $itema
2842 * @param custom_menu_item $itemb
2843 * @return int
2844 */
2845 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2846 $itema = $itema->get_sort_order();
2847 $itemb = $itemb->get_sort_order();
2848 if ($itema == $itemb) {
2849 return 0;
2850 }
2851 return ($itema > $itemb) ? +1 : -1;
2852 }
de7a570c 2853}
c269b9d1
MG
2854
2855/**
2856 * Stores one tab
2857 *
2858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2859 * @package core
2860 */
2861class tabobject implements renderable {
2862 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2863 var $id;
2864 /** @var moodle_url|string link */
2865 var $link;
2866 /** @var string text on the tab */
2867 var $text;
2868 /** @var string title under the link, by defaul equals to text */
2869 var $title;
2870 /** @var bool whether to display a link under the tab name when it's selected */
2871 var $linkedwhenselected = false;
2872 /** @var bool whether the tab is inactive */
2873 var $inactive = false;
2874 /** @var bool indicates that this tab's child is selected */
2875 var $activated = false;
2876 /** @var bool indicates that this tab is selected */
2877 var $selected = false;
2878 /** @var array stores children tabobjects */
2879 var $subtree = array();
2880 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2881 var $level = 1;
2882
2883 /**
2884 * Constructor
2885 *
2886 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2887 * @param string|moodle_url $link
2888 * @param string $text text on the tab
2889 * @param string $title title under the link, by defaul equals to text
2890 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2891 */
2892 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2893 $this->id = $id;
2894 $this->link = $link;
2895 $this->text = $text;
2896 $this->title = $title ? $title : $text;
2897 $this->linkedwhenselected = $linkedwhenselected;
2898 }
2899
2900 /**
2901 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2902 *
2903 * @param string $selected the id of the selected tab (whatever row it's on),
2904 * if null marks all tabs as unselected
2905 * @return bool whether this tab is selected or contains selected tab in its subtree
2906 */
2907 protected function set_selected($selected) {
2908 if ((string)$selected === (string)$this->id) {
2909 $this->selected = true;
2910 // This tab is selected. No need to travel through subtree.
2911 return true;
2912 }
2913 foreach ($this->subtree as $subitem) {
2914 if ($subitem->set_selected($selected)) {
2915 // This tab has child that is selected. Mark it as activated. No need to check other children.
2916 $this->activated = true;
2917 return true;
2918 }
2919 }
2920 return false;
2921 }
2922
2923 /**
2924 * Travels through tree and finds a tab with specified id
2925 *
2926 * @param string $id
2927 * @return tabtree|null
2928 */
2929 public function find($id) {
2930 if ((string)$this->id === (string)$id) {
2931 return $this;
2932 }
2933 foreach ($this->subtree as $tab) {
2934 if ($obj = $tab->find($id)) {
2935 return $obj;
2936 }
2937 }
2938 return null;
2939 }
2940
2941 /**
2942 * Allows to mark each tab's level in the tree before rendering.
2943 *
2944 * @param int $level
2945 */
2946 protected function set_level($level) {
2947 $this->level = $level;
2948 foreach ($this->subtree as $tab) {
2949 $tab->set_level($level + 1);
2950 }
2951 }
2952}
2953
2954/**
2955 * Stores tabs list
2956 *
2957 * Example how to print a single line tabs:
2958 * $rows = array(
2959 * new tabobject(...),
2960 * new tabobject(...)
2961 * );
2962 * echo $OUTPUT->tabtree($rows, $selectedid);
2963 *
2964 * Multiple row tabs may not look good on some devices but if you want to use them
2965 * you can specify ->subtree for the active tabobject.
2966 *
2967 * @copyright 2013 Marina Glancy
2968 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2969 * @since Moodle 2.5
2970 * @package core
2971 * @category output
2972 */
2973class tabtree extends tabobject {
2974 /**
2975 * Constuctor
2976 *
2977 * It is highly recommended to call constructor when list of tabs is already
2978 * populated, this way you ensure that selected and inactive tabs are located
2979 * and attribute level is set correctly.
2980 *
2981 * @param array $tabs array of tabs, each of them may have it's own ->subtree
2982 * @param string|null $selected which tab to mark as selected, all parent tabs will
2983 * automatically be marked as activated
2984 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
2985 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
2986 */
2987 public function __construct($tabs, $selected = null, $inactive = null) {
2988 $this->subtree = $tabs;
2989 if ($selected !== null) {
2990 $this->set_selected($selected);
2991 }
2992 if ($inactive !== null) {
2993 if (is_array($inactive)) {
2994 foreach ($inactive as $id) {
2995 if ($tab = $this->find($id)) {
2996 $tab->inactive = true;
2997 }
2998 }
2999 } else if ($tab = $this->find($inactive)) {
3000 $tab->inactive = true;
3001 }
3002 }
3003 $this->set_level(0);
3004 }
3005}