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