MDL-35669 gravatar Provide default image URL to Gravatar
[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) {
f127b1a5 403 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
4125bdc1 404 } else {
f127b1a5 405 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
4125bdc1 406 }
871a3ec5
SH
407 }
408
faa328c3 409 return $defaulturl;
5c0d03ea
DM
410 }
411}
bf11293a
PS
412
413/**
414 * Data structure representing a help icon.
415 *
416 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
9678c7b8
SH
417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
418 * @since Moodle 2.0
f8129210 419 * @package core
76be40cc 420 * @category output
bf11293a 421 */
596509e4 422class old_help_icon implements renderable {
9678c7b8 423
bf11293a 424 /**
76be40cc 425 * @var string Lang pack identifier
bf11293a 426 */
53a78cef 427 public $helpidentifier;
9678c7b8 428
bf11293a 429 /**
76be40cc 430 * @var string A descriptive text for title tooltip
bf11293a 431 */
97c10099 432 public $title = null;
9678c7b8 433
bf11293a 434 /**
76be40cc 435 * @var string Component name, the same as in get_string()
bf11293a
PS
436 */
437 public $component = 'moodle';
9678c7b8 438
bf11293a 439 /**
76be40cc 440 * @var string Extra descriptive text next to the icon
bf11293a 441 */
97c10099 442 public $linktext = null;
bf11293a
PS
443
444 /**
445 * Constructor: sets up the other components in case they are needed
9678c7b8 446 *
53a78cef 447 * @param string $helpidentifier The keyword that defines a help page
1a10840e 448 * @param string $title A descriptive text for accessibility only
bf11293a 449 * @param string $component
bf11293a 450 */
53a78cef 451 public function __construct($helpidentifier, $title, $component = 'moodle') {
bf11293a
PS
452 if (empty($title)) {
453 throw new coding_exception('A help_icon object requires a $text parameter');
454 }
53a78cef
PS
455 if (empty($helpidentifier)) {
456 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
bf11293a
PS
457 }
458
53a78cef
PS
459 $this->helpidentifier = $helpidentifier;
460 $this->title = $title;
461 $this->component = $component;
bf11293a
PS
462 }
463}
464
49f0d481
PS
465/**
466 * Data structure representing a help icon.
467 *
468 * @copyright 2010 Petr Skoda (info@skodak.org)
9678c7b8
SH
469 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
470 * @since Moodle 2.0
f8129210 471 * @package core
76be40cc 472 * @category output
49f0d481
PS
473 */
474class help_icon implements renderable {
9678c7b8 475
49f0d481 476 /**
76be40cc 477 * @var string lang pack identifier (without the "_help" suffix),
9678c7b8
SH
478 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
479 * must exist.
49f0d481
PS
480 */
481 public $identifier;
9678c7b8 482
49f0d481 483 /**
76be40cc 484 * @var string Component name, the same as in get_string()
49f0d481
PS
485 */
486 public $component;
9678c7b8 487
49f0d481 488 /**
76be40cc 489 * @var string Extra descriptive text next to the icon
49f0d481
PS
490 */
491 public $linktext = null;
492
493 /**
494 * Constructor
9678c7b8
SH
495 *
496 * @param string $identifier string for help page title,
5435c9dc
MD
497 * string with _help suffix is used for the actual help text.
498 * string with _link suffix is used to create a link to further info (if it exists)
49f0d481
PS
499 * @param string $component
500 */
259c165d
PS
501 public function __construct($identifier, $component) {
502 $this->identifier = $identifier;
49f0d481
PS
503 $this->component = $component;
504 }
259c165d
PS
505
506 /**
507 * Verifies that both help strings exists, shows debug warnings if not
508 */
509 public function diag_strings() {
510 $sm = get_string_manager();
511 if (!$sm->string_exists($this->identifier, $this->component)) {
512 debugging("Help title string does not exist: [$this->identifier, $this->component]");
513 }
5435c9dc 514 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
876521ac 515 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
259c165d
PS
516 }
517 }
49f0d481
PS
518}
519
bf11293a 520
000c278c
PS
521/**
522 * Data structure representing an icon.
523 *
524 * @copyright 2010 Petr Skoda
9678c7b8
SH
525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
526 * @since Moodle 2.0
f8129210 527 * @package core
76be40cc 528 * @category output
000c278c
PS
529 */
530class pix_icon implements renderable {
9678c7b8
SH
531
532 /**
76be40cc 533 * @var string The icon name
9678c7b8 534 */
000c278c 535 var $pix;
9678c7b8
SH
536
537 /**
76be40cc 538 * @var string The component the icon belongs to.
9678c7b8 539 */
000c278c 540 var $component;
9678c7b8
SH
541
542 /**
76be40cc 543 * @var array An array of attributes to use on the icon
9678c7b8 544 */
000c278c
PS
545 var $attributes = array();
546
547 /**
548 * Constructor
9678c7b8 549 *
000c278c 550 * @param string $pix short icon name
7749e187 551 * @param string $alt The alt text to use for the icon
000c278c
PS
552 * @param string $component component name
553 * @param array $attributes html attributes
554 */
555 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
556 $this->pix = $pix;
557 $this->component = $component;
000c278c
PS
558 $this->attributes = (array)$attributes;
559
560 $this->attributes['alt'] = $alt;
561 if (empty($this->attributes['class'])) {
562 $this->attributes['class'] = 'smallicon';
563 }
564 if (!isset($this->attributes['title'])) {
565 $this->attributes['title'] = $this->attributes['alt'];
aad982aa
FM
566 } else if (empty($this->attributes['title'])) {
567 // Remove the title attribute if empty, we probably want to use the parent node's title
568 // and some browsers might overwrite it with an empty title.
569 unset($this->attributes['title']);
000c278c
PS
570 }
571 }
572}
573
d63c5073
DM
574/**
575 * Data structure representing an emoticon image
576 *
9678c7b8
SH
577 * @copyright 2010 David Mudrak
578 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
579 * @since Moodle 2.0
f8129210 580 * @package core
76be40cc 581 * @category output
d63c5073
DM
582 */
583class pix_emoticon extends pix_icon implements renderable {
584
585 /**
586 * Constructor
587 * @param string $pix short icon name
b9fadae7
DM
588 * @param string $alt alternative text
589 * @param string $component emoticon image provider
590 * @param array $attributes explicit HTML attributes
d63c5073 591 */
b9fadae7
DM
592 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
593 if (empty($attributes['class'])) {
594 $attributes['class'] = 'emoticon';
595 }
d63c5073
DM
596 parent::__construct($pix, $alt, $component, $attributes);
597 }
598}
000c278c 599
3ba60ee1
PS
600/**
601 * Data structure representing a simple form with only one button.
602 *
603 * @copyright 2009 Petr Skoda
9678c7b8
SH
604 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
605 * @since Moodle 2.0
f8129210 606 * @package core
76be40cc 607 * @category output
3ba60ee1
PS
608 */
609class single_button implements renderable {
9678c7b8 610
574fbea4 611 /**
76be40cc 612 * @var moodle_url Target url
574fbea4 613 */
3ba60ee1 614 var $url;
9678c7b8 615
574fbea4 616 /**
76be40cc 617 * @var string Button label
574fbea4 618 */
3ba60ee1 619 var $label;
9678c7b8 620
574fbea4 621 /**
76be40cc 622 * @var string Form submit method post or get
574fbea4 623 */
3ba60ee1 624 var $method = 'post';
9678c7b8 625
574fbea4 626 /**
76be40cc 627 * @var string Wrapping div class
9678c7b8 628 */
3ba60ee1 629 var $class = 'singlebutton';
9678c7b8 630
574fbea4 631 /**
3d3fae72 632 * @var bool True if button disabled, false if normal
574fbea4 633 */
3ba60ee1 634 var $disabled = false;
9678c7b8 635
574fbea4 636 /**
76be40cc 637 * @var string Button tooltip
574fbea4 638 */
97c10099 639 var $tooltip = null;
9678c7b8 640
574fbea4 641 /**
76be40cc 642 * @var string Form id
574fbea4 643 */
3ba60ee1 644 var $formid;
9678c7b8 645
574fbea4 646 /**
76be40cc 647 * @var array List of attached actions
574fbea4 648 */
3ba60ee1
PS
649 var $actions = array();
650
651 /**
652 * Constructor
9678c7b8 653 * @param moodle_url $url
3ba60ee1
PS
654 * @param string $label button text
655 * @param string $method get or post submit method
3ba60ee1
PS
656 */
657 public function __construct(moodle_url $url, $label, $method='post') {
658 $this->url = clone($url);
659 $this->label = $label;
660 $this->method = $method;
661 }
662
663 /**
574fbea4 664 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1 665 * The message must be a yes/no question.
9678c7b8 666 *
f8129210 667 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
3ba60ee1
PS
668 */
669 public function add_confirm_action($confirmmessage) {
8f78cd5a 670 $this->add_action(new confirm_action($confirmmessage));
3ba60ee1
PS
671 }
672
574fbea4
PS
673 /**
674 * Add action to the button.
675 * @param component_action $action
574fbea4 676 */
3ba60ee1
PS
677 public function add_action(component_action $action) {
678 $this->actions[] = $action;
679 }
680}
681
682
a9967cf5
PS
683/**
684 * Simple form with just one select field that gets submitted automatically.
f8129210 685 *
a9967cf5
PS
686 * If JS not enabled small go button is printed too.
687 *
688 * @copyright 2009 Petr Skoda
9678c7b8
SH
689 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
690 * @since Moodle 2.0
f8129210 691 * @package core
76be40cc 692 * @category output
a9967cf5
PS
693 */
694class single_select implements renderable {
9678c7b8 695
a9967cf5 696 /**
76be40cc 697 * @var moodle_url Target url - includes hidden fields
a9967cf5
PS
698 */
699 var $url;
9678c7b8 700
a9967cf5 701 /**
76be40cc 702 * @var string Name of the select element.
a9967cf5
PS
703 */
704 var $name;
9678c7b8 705
a9967cf5 706 /**
9678c7b8
SH
707 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
708 * it is also possible to specify optgroup as complex label array ex.:
709 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
710 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
a9967cf5
PS
711 */
712 var $options;
9678c7b8 713
a9967cf5 714 /**
76be40cc 715 * @var string Selected option
a9967cf5
PS
716 */
717 var $selected;
9678c7b8 718
a9967cf5 719 /**
76be40cc 720 * @var array Nothing selected
a9967cf5
PS
721 */
722 var $nothing;
9678c7b8 723
a9967cf5 724 /**
76be40cc 725 * @var array Extra select field attributes
a9967cf5
PS
726 */
727 var $attributes = array();
9678c7b8 728
a9967cf5 729 /**
76be40cc 730 * @var string Button label
a9967cf5
PS
731 */
732 var $label = '';
9678c7b8 733
ecc5cc31 734 /**
de7a570c 735 * @var array Button label's attributes
ecc5cc31
RW
736 */
737 var $labelattributes = array();
738
a9967cf5 739 /**
76be40cc 740 * @var string Form submit method post or get
a9967cf5
PS
741 */
742 var $method = 'get';
9678c7b8 743
a9967cf5 744 /**
76be40cc
SH
745 * @var string Wrapping div class
746 */
a9967cf5 747 var $class = 'singleselect';
9678c7b8 748
a9967cf5 749 /**
3d3fae72 750 * @var bool True if button disabled, false if normal
a9967cf5
PS
751 */
752 var $disabled = false;
9678c7b8 753
a9967cf5 754 /**
76be40cc 755 * @var string Button tooltip
a9967cf5
PS
756 */
757 var $tooltip = null;
9678c7b8 758
a9967cf5 759 /**
76be40cc 760 * @var string Form id
a9967cf5
PS
761 */
762 var $formid = null;
9678c7b8 763
a9967cf5 764 /**
76be40cc 765 * @var array List of attached actions
a9967cf5
PS
766 */
767 var $helpicon = null;
9678c7b8 768
a9967cf5
PS
769 /**
770 * Constructor
771 * @param moodle_url $url form action target, includes hidden fields
772 * @param string $name name of selection field - the changing parameter in url
773 * @param array $options list of options
774 * @param string $selected selected element
775 * @param array $nothing
f8dab966 776 * @param string $formid
a9967cf5 777 */
9678c7b8 778 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
a9967cf5
PS
779 $this->url = $url;
780 $this->name = $name;
781 $this->options = $options;
782 $this->selected = $selected;
783 $this->nothing = $nothing;
f8dab966 784 $this->formid = $formid;
a9967cf5
PS
785 }
786
787 /**
788 * Shortcut for adding a JS confirm dialog when the button is clicked.
789 * The message must be a yes/no question.
9678c7b8 790 *
f8129210 791 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
a9967cf5
PS
792 */
793 public function add_confirm_action($confirmmessage) {
794 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
795 }
796
797 /**
798 * Add action to the button.
9678c7b8 799 *
a9967cf5 800 * @param component_action $action
a9967cf5
PS
801 */
802 public function add_action(component_action $action) {
803 $this->actions[] = $action;
804 }
f8dab966
PS
805
806 /**
259c165d 807 * Adds help icon.
9678c7b8 808 *
f8129210 809 * @param string $helppage The keyword that defines a help page
1a10840e 810 * @param string $title A descriptive text for accessibility only
f8dab966 811 * @param string $component
f8dab966 812 */
596509e4
PS
813 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
814 $this->helpicon = new old_help_icon($helppage, $title, $component);
f8dab966
PS
815 }
816
259c165d
PS
817 /**
818 * Adds help icon.
9678c7b8 819 *
259c165d
PS
820 * @param string $identifier The keyword that defines a help page
821 * @param string $component
259c165d
PS
822 */
823 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 824 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
825 }
826
f8dab966 827 /**
995f2d51 828 * Sets select's label
9678c7b8 829 *
f8dab966 830 * @param string $label
ecc5cc31 831 * @param array $attributes (optional)
f8dab966 832 */
ecc5cc31 833 public function set_label($label, $attributes = array()) {
f8dab966 834 $this->label = $label;
ecc5cc31
RW
835 $this->labelattributes = $attributes;
836
f8dab966 837 }
a9967cf5
PS
838}
839
4d10e579
PS
840/**
841 * Simple URL selection widget description.
9678c7b8 842 *
4d10e579 843 * @copyright 2009 Petr Skoda
9678c7b8
SH
844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
845 * @since Moodle 2.0
f8129210 846 * @package core
76be40cc 847 * @category output
4d10e579
PS
848 */
849class url_select implements renderable {
850 /**
9678c7b8
SH
851 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
852 * it is also possible to specify optgroup as complex label array ex.:
853 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
854 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
4d10e579
PS
855 */
856 var $urls;
9678c7b8 857
4d10e579 858 /**
76be40cc 859 * @var string Selected option
4d10e579
PS
860 */
861 var $selected;
9678c7b8 862
4d10e579 863 /**
76be40cc 864 * @var array Nothing selected
4d10e579
PS
865 */
866 var $nothing;
9678c7b8 867
4d10e579 868 /**
76be40cc 869 * @var array Extra select field attributes
4d10e579
PS
870 */
871 var $attributes = array();
9678c7b8 872
4d10e579 873 /**
76be40cc 874 * @var string Button label
4d10e579
PS
875 */
876 var $label = '';
9678c7b8 877
ecc5cc31
RW
878 /**
879 * @var array Button label's attributes
880 */
881 var $labelattributes = array();
882
4d10e579 883 /**
76be40cc
SH
884 * @var string Wrapping div class
885 */
4d10e579 886 var $class = 'urlselect';
9678c7b8 887
4d10e579 888 /**
3d3fae72 889 * @var bool True if button disabled, false if normal
4d10e579
PS
890 */
891 var $disabled = false;
9678c7b8 892
4d10e579 893 /**
76be40cc 894 * @var string Button tooltip
4d10e579
PS
895 */
896 var $tooltip = null;
9678c7b8 897
4d10e579 898 /**
76be40cc 899 * @var string Form id
4d10e579
PS
900 */
901 var $formid = null;
9678c7b8 902
4d10e579 903 /**
76be40cc 904 * @var array List of attached actions
4d10e579
PS
905 */
906 var $helpicon = null;
9678c7b8 907
15e48a1a
SM
908 /**
909 * @var string If set, makes button visible with given name for button
910 */
911 var $showbutton = null;
9678c7b8 912
4d10e579
PS
913 /**
914 * Constructor
915 * @param array $urls list of options
916 * @param string $selected selected element
917 * @param array $nothing
918 * @param string $formid
15e48a1a
SM
919 * @param string $showbutton Set to text of button if it should be visible
920 * or null if it should be hidden (hidden version always has text 'go')
921 */
9678c7b8 922 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
15e48a1a
SM
923 $this->urls = $urls;
924 $this->selected = $selected;
925 $this->nothing = $nothing;
926 $this->formid = $formid;
927 $this->showbutton = $showbutton;
4d10e579
PS
928 }
929
930 /**
259c165d 931 * Adds help icon.
9678c7b8 932 *
f8129210 933 * @param string $helppage The keyword that defines a help page
1a10840e 934 * @param string $title A descriptive text for accessibility only
4d10e579 935 * @param string $component
4d10e579 936 */
596509e4
PS
937 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
938 $this->helpicon = new old_help_icon($helppage, $title, $component);
4d10e579
PS
939 }
940
259c165d
PS
941 /**
942 * Adds help icon.
9678c7b8 943 *
259c165d
PS
944 * @param string $identifier The keyword that defines a help page
945 * @param string $component
259c165d
PS
946 */
947 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 948 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
949 }
950
4d10e579 951 /**
995f2d51 952 * Sets select's label
9678c7b8 953 *
4d10e579 954 * @param string $label
ecc5cc31 955 * @param array $attributes (optional)
4d10e579 956 */
ecc5cc31 957 public function set_label($label, $attributes = array()) {
4d10e579 958 $this->label = $label;
ecc5cc31 959 $this->labelattributes = $attributes;
4d10e579
PS
960 }
961}
962
574fbea4
PS
963/**
964 * Data structure describing html link with special action attached.
9678c7b8 965 *
574fbea4 966 * @copyright 2010 Petr Skoda
9678c7b8
SH
967 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
968 * @since Moodle 2.0
f8129210 969 * @package core
76be40cc 970 * @category output
574fbea4
PS
971 */
972class action_link implements renderable {
9678c7b8 973
574fbea4 974 /**
76be40cc 975 * @var moodle_url Href url
574fbea4
PS
976 */
977 var $url;
9678c7b8 978
574fbea4 979 /**
76be40cc 980 * @var string Link text HTML fragment
574fbea4
PS
981 */
982 var $text;
9678c7b8 983
574fbea4 984 /**
76be40cc 985 * @var array HTML attributes
574fbea4
PS
986 */
987 var $attributes;
9678c7b8 988
574fbea4 989 /**
76be40cc 990 * @var array List of actions attached to link
574fbea4
PS
991 */
992 var $actions;
993
994 /**
995 * Constructor
9678c7b8 996 * @param moodle_url $url
574fbea4
PS
997 * @param string $text HTML fragment
998 * @param component_action $action
11820bac 999 * @param array $attributes associative array of html link attributes + disabled
574fbea4 1000 */
9678c7b8
SH
1001 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
1002 $this->url = clone($url);
1003 $this->text = $text;
b0fef57b 1004 $this->attributes = (array)$attributes;
f14b641b 1005 if ($action) {
574fbea4
PS
1006 $this->add_action($action);
1007 }
1008 }
1009
1010 /**
1011 * Add action to the link.
9678c7b8 1012 *
574fbea4 1013 * @param component_action $action
574fbea4
PS
1014 */
1015 public function add_action(component_action $action) {
1016 $this->actions[] = $action;
1017 }
c63923bd 1018
9678c7b8
SH
1019 /**
1020 * Adds a CSS class to this action link object
1021 * @param string $class
1022 */
c63923bd 1023 public function add_class($class) {
67da0bf7
DM
1024 if (empty($this->attributes['class'])) {
1025 $this->attributes['class'] = $class;
c63923bd 1026 } else {
67da0bf7 1027 $this->attributes['class'] .= ' ' . $class;
c63923bd
PS
1028 }
1029 }
574fbea4 1030}
3ba60ee1 1031
5d0c95a5
PS
1032/**
1033 * Simple html output class
9678c7b8 1034 *
5d0c95a5 1035 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
9678c7b8
SH
1036 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1037 * @since Moodle 2.0
f8129210 1038 * @package core
76be40cc 1039 * @category output
5d0c95a5
PS
1040 */
1041class html_writer {
9678c7b8 1042
5d0c95a5
PS
1043 /**
1044 * Outputs a tag with attributes and contents
9678c7b8 1045 *
5d0c95a5 1046 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
5d0c95a5 1047 * @param string $contents What goes between the opening and closing tags
26acc814 1048 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
5d0c95a5
PS
1049 * @return string HTML fragment
1050 */
26acc814 1051 public static function tag($tagname, $contents, array $attributes = null) {
5d0c95a5
PS
1052 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1053 }
1054
1055 /**
1056 * Outputs an opening tag with attributes
9678c7b8 1057 *
5d0c95a5
PS
1058 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1059 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1060 * @return string HTML fragment
1061 */
1062 public static function start_tag($tagname, array $attributes = null) {
1063 return '<' . $tagname . self::attributes($attributes) . '>';
1064 }
1065
1066 /**
1067 * Outputs a closing tag
9678c7b8 1068 *
5d0c95a5
PS
1069 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1070 * @return string HTML fragment
1071 */
1072 public static function end_tag($tagname) {
1073 return '</' . $tagname . '>';
1074 }
1075
1076 /**
1077 * Outputs an empty tag with attributes
9678c7b8 1078 *
5d0c95a5
PS
1079 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1080 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1081 * @return string HTML fragment
1082 */
1083 public static function empty_tag($tagname, array $attributes = null) {
1084 return '<' . $tagname . self::attributes($attributes) . ' />';
1085 }
1086
836c47d7
TH
1087 /**
1088 * Outputs a tag, but only if the contents are not empty
9678c7b8 1089 *
836c47d7
TH
1090 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1091 * @param string $contents What goes between the opening and closing tags
1092 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1093 * @return string HTML fragment
1094 */
1095 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1096 if ($contents === '' || is_null($contents)) {
1097 return '';
1098 }
1099 return self::tag($tagname, $contents, $attributes);
1100 }
1101
5d0c95a5
PS
1102 /**
1103 * Outputs a HTML attribute and value
9678c7b8 1104 *
5d0c95a5
PS
1105 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1106 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1107 * @return string HTML fragment
1108 */
1109 public static function attribute($name, $value) {
1110 if (is_array($value)) {
1111 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
1112 }
bf11293a
PS
1113 if ($value instanceof moodle_url) {
1114 return ' ' . $name . '="' . $value->out() . '"';
1115 }
97c10099
PS
1116
1117 // special case, we do not want these in output
1118 if ($value === null) {
1119 return '';
5d0c95a5 1120 }
97c10099
PS
1121
1122 // no sloppy trimming here!
1123 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
1124 }
1125
1126 /**
1127 * Outputs a list of HTML attributes and values
9678c7b8 1128 *
5d0c95a5
PS
1129 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1130 * The values will be escaped with {@link s()}
1131 * @return string HTML fragment
1132 */
1133 public static function attributes(array $attributes = null) {
1134 $attributes = (array)$attributes;
1135 $output = '';
1136 foreach ($attributes as $name => $value) {
1137 $output .= self::attribute($name, $value);
1138 }
1139 return $output;
1140 }
1141
1142 /**
1143 * Generates random html element id.
9678c7b8
SH
1144 *
1145 * @staticvar int $counter
1146 * @staticvar type $uniq
3d3fae72
SH
1147 * @param string $base A string fragment that will be included in the random ID.
1148 * @return string A unique ID
5d0c95a5
PS
1149 */
1150 public static function random_id($base='random') {
2c479c8f
PS
1151 static $counter = 0;
1152 static $uniq;
1153
1154 if (!isset($uniq)) {
1155 $uniq = uniqid();
1156 }
1157
1158 $counter++;
1159 return $base.$uniq.$counter;
5d0c95a5 1160 }
0f4c64b7
PS
1161
1162 /**
1163 * Generates a simple html link
9678c7b8 1164 *
3d3fae72
SH
1165 * @param string|moodle_url $url The URL
1166 * @param string $text The text
1167 * @param array $attributes HTML attributes
0f4c64b7
PS
1168 * @return string HTML fragment
1169 */
1170 public static function link($url, $text, array $attributes = null) {
1171 $attributes = (array)$attributes;
1172 $attributes['href'] = $url;
26acc814 1173 return self::tag('a', $text, $attributes);
0f4c64b7 1174 }
3ff163c5 1175
14dce022 1176 /**
9678c7b8
SH
1177 * Generates a simple checkbox with optional label
1178 *
3d3fae72
SH
1179 * @param string $name The name of the checkbox
1180 * @param string $value The value of the checkbox
1181 * @param bool $checked Whether the checkbox is checked
1182 * @param string $label The label for the checkbox
1183 * @param array $attributes Any attributes to apply to the checkbox
14dce022
PS
1184 * @return string html fragment
1185 */
1186 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1187 $attributes = (array)$attributes;
1188 $output = '';
1189
1190 if ($label !== '' and !is_null($label)) {
1191 if (empty($attributes['id'])) {
1192 $attributes['id'] = self::random_id('checkbox_');
1193 }
1194 }
53868425
PS
1195 $attributes['type'] = 'checkbox';
1196 $attributes['value'] = $value;
1197 $attributes['name'] = $name;
621b4d08 1198 $attributes['checked'] = $checked ? 'checked' : null;
53868425 1199
14dce022
PS
1200 $output .= self::empty_tag('input', $attributes);
1201
1202 if ($label !== '' and !is_null($label)) {
26acc814 1203 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
14dce022
PS
1204 }
1205
1206 return $output;
1207 }
1208
78bdac64
PS
1209 /**
1210 * Generates a simple select yes/no form field
9678c7b8 1211 *
78bdac64
PS
1212 * @param string $name name of select element
1213 * @param bool $selected
1214 * @param array $attributes - html select element attributes
9678c7b8 1215 * @return string HTML fragment
78bdac64 1216 */
19f3bbb2 1217 public static function select_yes_no($name, $selected=true, array $attributes = null) {
78bdac64
PS
1218 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1219 return self::select($options, $name, $selected, null, $attributes);
1220 }
1221
3ff163c5
PS
1222 /**
1223 * Generates a simple select form field
9678c7b8 1224 *
6770330d
PS
1225 * @param array $options associative array value=>label ex.:
1226 * array(1=>'One, 2=>Two)
1227 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 1228 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 1229 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5 1230 * @param string $name name of select element
1a10840e 1231 * @param string|array $selected value or array of values depending on multiple attribute
f8129210
SH
1232 * @param array|bool $nothing add nothing selected option, or false of not added
1233 * @param array $attributes html select element attributes
78bdac64 1234 * @return string HTML fragment
3ff163c5 1235 */
9678c7b8 1236 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
3ff163c5
PS
1237 $attributes = (array)$attributes;
1238 if (is_array($nothing)) {
1239 foreach ($nothing as $k=>$v) {
4b9210f3 1240 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
1241 $nothing[$k] = get_string('choosedots');
1242 }
1243 }
1244 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
1245
1246 } else if (is_string($nothing) and $nothing !== '') {
1247 // BC
1248 $options = array(''=>$nothing) + $options;
bde156b3 1249 }
3ff163c5
PS
1250
1251 // we may accept more values if multiple attribute specified
1252 $selected = (array)$selected;
1253 foreach ($selected as $k=>$v) {
1254 $selected[$k] = (string)$v;
1255 }
1256
1257 if (!isset($attributes['id'])) {
1258 $id = 'menu'.$name;
1259 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1260 $id = str_replace('[', '', $id);
1261 $id = str_replace(']', '', $id);
1262 $attributes['id'] = $id;
1263 }
1264
1265 if (!isset($attributes['class'])) {
1266 $class = 'menu'.$name;
1267 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1268 $class = str_replace('[', '', $class);
1269 $class = str_replace(']', '', $class);
1270 $attributes['class'] = $class;
1271 }
f8129210 1272 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
3ff163c5
PS
1273
1274 $attributes['name'] = $name;
1275
1a09fa6d
TH
1276 if (!empty($attributes['disabled'])) {
1277 $attributes['disabled'] = 'disabled';
1278 } else {
1279 unset($attributes['disabled']);
1280 }
1281
3ff163c5
PS
1282 $output = '';
1283 foreach ($options as $value=>$label) {
6770330d
PS
1284 if (is_array($label)) {
1285 // ignore key, it just has to be unique
1286 $output .= self::select_optgroup(key($label), current($label), $selected);
1287 } else {
1288 $output .= self::select_option($label, $value, $selected);
3ff163c5 1289 }
3ff163c5 1290 }
26acc814 1291 return self::tag('select', $output, $attributes);
3ff163c5 1292 }
6770330d 1293
9678c7b8
SH
1294 /**
1295 * Returns HTML to display a select box option.
1296 *
1297 * @param string $label The label to display as the option.
1298 * @param string|int $value The value the option represents
1299 * @param array $selected An array of selected options
1300 * @return string HTML fragment
1301 */
6770330d
PS
1302 private static function select_option($label, $value, array $selected) {
1303 $attributes = array();
1304 $value = (string)$value;
1305 if (in_array($value, $selected, true)) {
1306 $attributes['selected'] = 'selected';
1307 }
1308 $attributes['value'] = $value;
26acc814 1309 return self::tag('option', $label, $attributes);
6770330d
PS
1310 }
1311
9678c7b8
SH
1312 /**
1313 * Returns HTML to display a select box option group.
1314 *
1315 * @param string $groupname The label to use for the group
1316 * @param array $options The options in the group
1317 * @param array $selected An array of selected values.
1318 * @return string HTML fragment.
1319 */
6770330d
PS
1320 private static function select_optgroup($groupname, $options, array $selected) {
1321 if (empty($options)) {
1322 return '';
1323 }
1324 $attributes = array('label'=>$groupname);
1325 $output = '';
1326 foreach ($options as $value=>$label) {
1327 $output .= self::select_option($label, $value, $selected);
1328 }
26acc814 1329 return self::tag('optgroup', $output, $attributes);
6770330d 1330 }
6ea66ff3 1331
f83b9b63
PS
1332 /**
1333 * This is a shortcut for making an hour selector menu.
9678c7b8 1334 *
f83b9b63
PS
1335 * @param string $type The type of selector (years, months, days, hours, minutes)
1336 * @param string $name fieldname
1337 * @param int $currenttime A default timestamp in GMT
1338 * @param int $step minute spacing
1339 * @param array $attributes - html select element attributes
1340 * @return HTML fragment
1341 */
9678c7b8 1342 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
f83b9b63
PS
1343 if (!$currenttime) {
1344 $currenttime = time();
1345 }
1346 $currentdate = usergetdate($currenttime);
1347 $userdatetype = $type;
1348 $timeunits = array();
1349
1350 switch ($type) {
1351 case 'years':
1352 for ($i=1970; $i<=2020; $i++) {
1353 $timeunits[$i] = $i;
1354 }
1355 $userdatetype = 'year';
1356 break;
1357 case 'months':
1358 for ($i=1; $i<=12; $i++) {
1359 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1360 }
1361 $userdatetype = 'month';
0387e003 1362 $currentdate['month'] = (int)$currentdate['mon'];
f83b9b63
PS
1363 break;
1364 case 'days':
1365 for ($i=1; $i<=31; $i++) {
1366 $timeunits[$i] = $i;
1367 }
1368 $userdatetype = 'mday';
1369 break;
1370 case 'hours':
1371 for ($i=0; $i<=23; $i++) {
1372 $timeunits[$i] = sprintf("%02d",$i);
1373 }
1374 break;
1375 case 'minutes':
1376 if ($step != 1) {
1377 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1378 }
1379
1380 for ($i=0; $i<=59; $i+=$step) {
1381 $timeunits[$i] = sprintf("%02d",$i);
1382 }
1383 break;
1384 default:
1385 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1386 }
1387
1388 if (empty($attributes['id'])) {
1389 $attributes['id'] = self::random_id('ts_');
1390 }
1391 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
26acc814 1392 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
f83b9b63
PS
1393
1394 return $label.$timerselector;
1395 }
1396
5be262b6
PS
1397 /**
1398 * Shortcut for quick making of lists
9678c7b8
SH
1399 *
1400 * Note: 'list' is a reserved keyword ;-)
1401 *
5be262b6 1402 * @param array $items
5be262b6 1403 * @param array $attributes
9678c7b8 1404 * @param string $tag ul or ol
5be262b6
PS
1405 * @return string
1406 */
1407 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
5be262b6
PS
1408 $output = '';
1409
1410 foreach ($items as $item) {
1411 $output .= html_writer::start_tag('li') . "\n";
1412 $output .= $item . "\n";
1413 $output .= html_writer::end_tag('li') . "\n";
1414 }
1415
26acc814 1416 return html_writer::tag($tag, $output, $attributes);
5be262b6
PS
1417 }
1418
6ea66ff3
PS
1419 /**
1420 * Returns hidden input fields created from url parameters.
9678c7b8 1421 *
6ea66ff3
PS
1422 * @param moodle_url $url
1423 * @param array $exclude list of excluded parameters
1424 * @return string HTML fragment
1425 */
1426 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1427 $exclude = (array)$exclude;
1428 $params = $url->params();
1429 foreach ($exclude as $key) {
1430 unset($params[$key]);
1431 }
1432
1433 $output = '';
bde156b3 1434 foreach ($params as $key => $value) {
6ea66ff3
PS
1435 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1436 $output .= self::empty_tag('input', $attributes)."\n";
1437 }
1438 return $output;
1439 }
77774f6a
PS
1440
1441 /**
1442 * Generate a script tag containing the the specified code.
1443 *
f8129210
SH
1444 * @param string $jscode the JavaScript code
1445 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
77774f6a
PS
1446 * @return string HTML, the code wrapped in <script> tags.
1447 */
e50b4c89 1448 public static function script($jscode, $url=null) {
77774f6a 1449 if ($jscode) {
e50b4c89 1450 $attributes = array('type'=>'text/javascript');
26acc814 1451 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
e50b4c89
PS
1452
1453 } else if ($url) {
1454 $attributes = array('type'=>'text/javascript', 'src'=>$url);
26acc814 1455 return self::tag('script', '', $attributes) . "\n";
a9967cf5 1456
77774f6a
PS
1457 } else {
1458 return '';
1459 }
1460 }
16be8974
DM
1461
1462 /**
1463 * Renders HTML table
1464 *
1465 * This method may modify the passed instance by adding some default properties if they are not set yet.
1466 * If this is not what you want, you should make a full clone of your data before passing them to this
1467 * method. In most cases this is not an issue at all so we do not clone by default for performance
1468 * and memory consumption reasons.
1469 *
1470 * @param html_table $table data to be rendered
1471 * @return string HTML code
1472 */
1473 public static function table(html_table $table) {
1474 // prepare table data and populate missing properties with reasonable defaults
1475 if (!empty($table->align)) {
1476 foreach ($table->align as $key => $aa) {
1477 if ($aa) {
1478 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1479 } else {
1480 $table->align[$key] = null;
1481 }
1482 }
1483 }
1484 if (!empty($table->size)) {
1485 foreach ($table->size as $key => $ss) {
1486 if ($ss) {
1487 $table->size[$key] = 'width:'. $ss .';';
1488 } else {
1489 $table->size[$key] = null;
1490 }
1491 }
1492 }
1493 if (!empty($table->wrap)) {
1494 foreach ($table->wrap as $key => $ww) {
1495 if ($ww) {
1496 $table->wrap[$key] = 'white-space:nowrap;';
1497 } else {
1498 $table->wrap[$key] = '';
1499 }
1500 }
1501 }
1502 if (!empty($table->head)) {
1503 foreach ($table->head as $key => $val) {
1504 if (!isset($table->align[$key])) {
1505 $table->align[$key] = null;
1506 }
1507 if (!isset($table->size[$key])) {
1508 $table->size[$key] = null;
1509 }
1510 if (!isset($table->wrap[$key])) {
1511 $table->wrap[$key] = null;
1512 }
1513
1514 }
1515 }
1516 if (empty($table->attributes['class'])) {
1517 $table->attributes['class'] = 'generaltable';
1518 }
1519 if (!empty($table->tablealign)) {
1520 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1521 }
1522
1523 // explicitly assigned properties override those defined via $table->attributes
e126c0cc 1524 $table->attributes['class'] = trim($table->attributes['class']);
16be8974
DM
1525 $attributes = array_merge($table->attributes, array(
1526 'id' => $table->id,
1527 'width' => $table->width,
1528 'summary' => $table->summary,
1529 'cellpadding' => $table->cellpadding,
1530 'cellspacing' => $table->cellspacing,
1531 ));
1532 $output = html_writer::start_tag('table', $attributes) . "\n";
1533
1534 $countcols = 0;
1535
1536 if (!empty($table->head)) {
1537 $countcols = count($table->head);
5174f3c5 1538
16be8974
DM
1539 $output .= html_writer::start_tag('thead', array()) . "\n";
1540 $output .= html_writer::start_tag('tr', array()) . "\n";
1541 $keys = array_keys($table->head);
1542 $lastkey = end($keys);
1543
1544 foreach ($table->head as $key => $heading) {
1545 // Convert plain string headings into html_table_cell objects
1546 if (!($heading instanceof html_table_cell)) {
1547 $headingtext = $heading;
1548 $heading = new html_table_cell();
1549 $heading->text = $headingtext;
1550 $heading->header = true;
1551 }
1552
1553 if ($heading->header !== false) {
1554 $heading->header = true;
1555 }
1556
e126c0cc
DM
1557 if ($heading->header && empty($heading->scope)) {
1558 $heading->scope = 'col';
1559 }
1560
16be8974
DM
1561 $heading->attributes['class'] .= ' header c' . $key;
1562 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1563 $heading->colspan = $table->headspan[$key];
1564 $countcols += $table->headspan[$key] - 1;
1565 }
1566
1567 if ($key == $lastkey) {
1568 $heading->attributes['class'] .= ' lastcol';
1569 }
1570 if (isset($table->colclasses[$key])) {
1571 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1572 }
e126c0cc 1573 $heading->attributes['class'] = trim($heading->attributes['class']);
16be8974
DM
1574 $attributes = array_merge($heading->attributes, array(
1575 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1576 'scope' => $heading->scope,
1577 'colspan' => $heading->colspan,
1578 ));
1579
1580 $tagtype = 'td';
1581 if ($heading->header === true) {
1582 $tagtype = 'th';
1583 }
1584 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1585 }
1586 $output .= html_writer::end_tag('tr') . "\n";
1587 $output .= html_writer::end_tag('thead') . "\n";
1588
1589 if (empty($table->data)) {
1590 // For valid XHTML strict every table must contain either a valid tr
1591 // or a valid tbody... both of which must contain a valid td
1592 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1593 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1594 $output .= html_writer::end_tag('tbody');
1595 }
1596 }
1597
1598 if (!empty($table->data)) {
1599 $oddeven = 1;
1600 $keys = array_keys($table->data);
1601 $lastrowkey = end($keys);
1602 $output .= html_writer::start_tag('tbody', array());
1603
1604 foreach ($table->data as $key => $row) {
1605 if (($row === 'hr') && ($countcols)) {
1606 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1607 } else {
1608 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1609 if (!($row instanceof html_table_row)) {
1610 $newrow = new html_table_row();
1611
4954d6ed
FM
1612 foreach ($row as $cell) {
1613 if (!($cell instanceof html_table_cell)) {
1614 $cell = new html_table_cell($cell);
1615 }
16be8974
DM
1616 $newrow->cells[] = $cell;
1617 }
1618 $row = $newrow;
1619 }
1620
1621 $oddeven = $oddeven ? 0 : 1;
1622 if (isset($table->rowclasses[$key])) {
1623 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1624 }
1625
1626 $row->attributes['class'] .= ' r' . $oddeven;
1627 if ($key == $lastrowkey) {
1628 $row->attributes['class'] .= ' lastrow';
1629 }
1630
e126c0cc 1631 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
16be8974
DM
1632 $keys2 = array_keys($row->cells);
1633 $lastkey = end($keys2);
1634
5174f3c5 1635 $gotlastkey = false; //flag for sanity checking
16be8974 1636 foreach ($row->cells as $key => $cell) {
5174f3c5
AD
1637 if ($gotlastkey) {
1638 //This should never happen. Why do we have a cell after the last cell?
1639 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1640 }
1641
16be8974
DM
1642 if (!($cell instanceof html_table_cell)) {
1643 $mycell = new html_table_cell();
1644 $mycell->text = $cell;
1645 $cell = $mycell;
1646 }
1647
e126c0cc
DM
1648 if (($cell->header === true) && empty($cell->scope)) {
1649 $cell->scope = 'row';
1650 }
1651
16be8974
DM
1652 if (isset($table->colclasses[$key])) {
1653 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1654 }
1655
1656 $cell->attributes['class'] .= ' cell c' . $key;
1657 if ($key == $lastkey) {
1658 $cell->attributes['class'] .= ' lastcol';
5174f3c5 1659 $gotlastkey = true;
16be8974
DM
1660 }
1661 $tdstyle = '';
1662 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1663 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1664 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1665 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1666 $tdattributes = array_merge($cell->attributes, array(
1667 'style' => $tdstyle . $cell->style,
1668 'colspan' => $cell->colspan,
1669 'rowspan' => $cell->rowspan,
1670 'id' => $cell->id,
1671 'abbr' => $cell->abbr,
1672 'scope' => $cell->scope,
1673 ));
1674 $tagtype = 'td';
1675 if ($cell->header === true) {
1676 $tagtype = 'th';
1677 }
1678 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1679 }
1680 }
1681 $output .= html_writer::end_tag('tr') . "\n";
1682 }
1683 $output .= html_writer::end_tag('tbody') . "\n";
1684 }
1685 $output .= html_writer::end_tag('table') . "\n";
1686
1687 return $output;
1688 }
1689
995f2d51
DM
1690 /**
1691 * Renders form element label
1692 *
1693 * By default, the label is suffixed with a label separator defined in the
1694 * current language pack (colon by default in the English lang pack).
1695 * Adding the colon can be explicitly disabled if needed. Label separators
1696 * are put outside the label tag itself so they are not read by
1697 * screenreaders (accessibility).
1698 *
1699 * Parameter $for explicitly associates the label with a form control. When
1700 * set, the value of this attribute must be the same as the value of
1701 * the id attribute of the form control in the same document. When null,
1702 * the label being defined is associated with the control inside the label
1703 * element.
1704 *
1705 * @param string $text content of the label tag
1706 * @param string|null $for id of the element this label is associated with, null for no association
1707 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1708 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1709 * @return string HTML of the label element
1710 */
9678c7b8 1711 public static function label($text, $for, $colonize = true, array $attributes=array()) {
995f2d51
DM
1712 if (!is_null($for)) {
1713 $attributes = array_merge($attributes, array('for' => $for));
1714 }
1715 $text = trim($text);
1716 $label = self::tag('label', $text, $attributes);
1717
9678c7b8
SH
1718 // TODO MDL-12192 $colonize disabled for now yet
1719 // if (!empty($text) and $colonize) {
1720 // // the $text may end with the colon already, though it is bad string definition style
1721 // $colon = get_string('labelsep', 'langconfig');
1722 // if (!empty($colon)) {
1723 // $trimmed = trim($colon);
1724 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1725 // //debugging('The label text should not end with colon or other label separator,
1726 // // please fix the string definition.', DEBUG_DEVELOPER);
1727 // } else {
1728 // $label .= $colon;
1729 // }
1730 // }
1731 // }
995f2d51
DM
1732
1733 return $label;
1734 }
5d0c95a5
PS
1735}
1736
227255b8
PS
1737/**
1738 * Simple javascript output class
9678c7b8 1739 *
227255b8 1740 * @copyright 2010 Petr Skoda
9678c7b8
SH
1741 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1742 * @since Moodle 2.0
f8129210 1743 * @package core
76be40cc 1744 * @category output
227255b8
PS
1745 */
1746class js_writer {
9678c7b8 1747
227255b8
PS
1748 /**
1749 * Returns javascript code calling the function
9678c7b8 1750 *
1a10840e 1751 * @param string $function function name, can be complex like Y.Event.purgeElement
227255b8
PS
1752 * @param array $arguments parameters
1753 * @param int $delay execution delay in seconds
1754 * @return string JS code fragment
1755 */
e839dce1 1756 public static function function_call($function, array $arguments = null, $delay=0) {
1b4e41af 1757 if ($arguments) {
b2cb00c2 1758 $arguments = array_map('json_encode', convert_to_array($arguments));
1b4e41af
PS
1759 $arguments = implode(', ', $arguments);
1760 } else {
1761 $arguments = '';
1762 }
227255b8
PS
1763 $js = "$function($arguments);";
1764
1765 if ($delay) {
1766 $delay = $delay * 1000; // in miliseconds
1767 $js = "setTimeout(function() { $js }, $delay);";
1768 }
1769 return $js . "\n";
1770 }
1771
3b01539c 1772 /**
3d3fae72 1773 * Special function which adds Y as first argument of function call.
9678c7b8 1774 *
3d3fae72
SH
1775 * @param string $function The function to call
1776 * @param array $extraarguments Any arguments to pass to it
1777 * @return string Some JS code
3b01539c 1778 */
e839dce1 1779 public static function function_call_with_Y($function, array $extraarguments = null) {
3b01539c 1780 if ($extraarguments) {
b2cb00c2 1781 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
3b01539c
PS
1782 $arguments = 'Y, ' . implode(', ', $extraarguments);
1783 } else {
1784 $arguments = 'Y';
1785 }
1786 return "$function($arguments);\n";
1787 }
1788
1ce15fda
SH
1789 /**
1790 * Returns JavaScript code to initialise a new object
9678c7b8 1791 *
3d3fae72
SH
1792 * @param string $var If it is null then no var is assigned the new object.
1793 * @param string $class The class to initialise an object for.
1794 * @param array $arguments An array of args to pass to the init method.
1795 * @param array $requirements Any modules required for this class.
1796 * @param int $delay The delay before initialisation. 0 = no delay.
1797 * @return string Some JS code
1ce15fda 1798 */
e839dce1 1799 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1ce15fda 1800 if (is_array($arguments)) {
b2cb00c2 1801 $arguments = array_map('json_encode', convert_to_array($arguments));
1ce15fda
SH
1802 $arguments = implode(', ', $arguments);
1803 }
1804
1805 if ($var === null) {
53fc3e70 1806 $js = "new $class(Y, $arguments);";
1ce15fda 1807 } else if (strpos($var, '.')!==false) {
53fc3e70 1808 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1809 } else {
53fc3e70 1810 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1811 }
1812
1813 if ($delay) {
1814 $delay = $delay * 1000; // in miliseconds
1815 $js = "setTimeout(function() { $js }, $delay);";
1816 }
1817
1818 if (count($requirements) > 0) {
1819 $requirements = implode("', '", $requirements);
53fc3e70 1820 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1821 }
1822 return $js."\n";
1823 }
1824
227255b8
PS
1825 /**
1826 * Returns code setting value to variable
9678c7b8 1827 *
227255b8
PS
1828 * @param string $name
1829 * @param mixed $value json serialised value
1830 * @param bool $usevar add var definition, ignored for nested properties
1831 * @return string JS code fragment
1832 */
9678c7b8 1833 public static function set_variable($name, $value, $usevar = true) {
227255b8
PS
1834 $output = '';
1835
1836 if ($usevar) {
1837 if (strpos($name, '.')) {
1838 $output .= '';
1839 } else {
1840 $output .= 'var ';
1841 }
1842 }
1843
1844 $output .= "$name = ".json_encode($value).";";
1845
1846 return $output;
1847 }
1848
1849 /**
1850 * Writes event handler attaching code
9678c7b8 1851 *
f8129210
SH
1852 * @param array|string $selector standard YUI selector for elements, may be
1853 * array or string, element id is in the form "#idvalue"
227255b8
PS
1854 * @param string $event A valid DOM event (click, mousedown, change etc.)
1855 * @param string $function The name of the function to call
9678c7b8 1856 * @param array $arguments An optional array of argument parameters to pass to the function
227255b8
PS
1857 * @return string JS code fragment
1858 */
e839dce1 1859 public static function event_handler($selector, $event, $function, array $arguments = null) {
227255b8
PS
1860 $selector = json_encode($selector);
1861 $output = "Y.on('$event', $function, $selector, null";
1862 if (!empty($arguments)) {
1863 $output .= ', ' . json_encode($arguments);
1864 }
1865 return $output . ");\n";
1866 }
1867}
1868
d9c8f425 1869/**
f8129210 1870 * Holds all the information required to render a <table> by {@link core_renderer::table()}
d9c8f425 1871 *
16be8974
DM
1872 * Example of usage:
1873 * $t = new html_table();
1874 * ... // set various properties of the object $t as described below
1875 * echo html_writer::table($t);
d9c8f425 1876 *
16be8974 1877 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
9678c7b8
SH
1878 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1879 * @since Moodle 2.0
f8129210 1880 * @package core
76be40cc 1881 * @category output
d9c8f425 1882 */
16be8974 1883class html_table {
9678c7b8 1884
d9c8f425 1885 /**
76be40cc 1886 * @var string Value to use for the id attribute of the table
d9c8f425 1887 */
97c10099 1888 public $id = null;
9678c7b8 1889
d9c8f425 1890 /**
76be40cc 1891 * @var array Attributes of HTML attributes for the <table> element
d9c8f425 1892 */
16be8974 1893 public $attributes = array();
9678c7b8 1894
7b1f2c82 1895 /**
76be40cc 1896 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
a0ead5eb 1897 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1898 * can be passed instead of an array of strings.
7b1f2c82 1899 *
1900 * Example of usage:
1901 * $t->head = array('Student', 'Grade');
1902 */
1903 public $head;
9678c7b8 1904
7b1f2c82 1905 /**
76be40cc 1906 * @var array An array that can be used to make a heading span multiple columns.
f8129210
SH
1907 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1908 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
7b1f2c82 1909 *
1910 * Example of usage:
1911 * $t->headspan = array(2,1);
7b1f2c82 1912 */
1913 public $headspan;
9678c7b8 1914
7b1f2c82 1915 /**
76be40cc 1916 * @var array An array of column alignments.
9678c7b8 1917 * The value is used as CSS 'text-align' property. Therefore, possible
7b1f2c82 1918 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1919 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1920 *
beb56299 1921 * Examples of usage:
1922 * $t->align = array(null, 'right');
1923 * or
1924 * $t->align[1] = 'right';
d9c8f425 1925 */
beb56299 1926 public $align;
9678c7b8 1927
d9c8f425 1928 /**
76be40cc 1929 * @var array The value is used as CSS 'size' property.
beb56299 1930 *
1931 * Examples of usage:
1932 * $t->size = array('50%', '50%');
1933 * or
1934 * $t->size[1] = '120px';
d9c8f425 1935 */
beb56299 1936 public $size;
9678c7b8 1937
d9c8f425 1938 /**
76be40cc 1939 * @var array An array of wrapping information.
9678c7b8 1940 * The only possible value is 'nowrap' that sets the
beb56299 1941 * CSS property 'white-space' to the value 'nowrap' in the given column.
1942 *
1943 * Example of usage:
1944 * $t->wrap = array(null, 'nowrap');
d9c8f425 1945 */
beb56299 1946 public $wrap;
9678c7b8 1947
d9c8f425 1948 /**
76be40cc 1949 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
beb56299 1950 * $head specified, the string 'hr' (for horizontal ruler) can be used
1951 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1952 *
beb56299 1953 * Example of usage with array of arrays:
1954 * $row1 = array('Harry Potter', '76 %');
1955 * $row2 = array('Hermione Granger', '100 %');
1956 * $t->data = array($row1, $row2);
d9c8f425 1957 *
beb56299 1958 * Example with array of html_table_row objects: (used for more fine-grained control)
1959 * $cell1 = new html_table_cell();
1960 * $cell1->text = 'Harry Potter';
1961 * $cell1->colspan = 2;
1962 * $row1 = new html_table_row();
1963 * $row1->cells[] = $cell1;
1964 * $cell2 = new html_table_cell();
1965 * $cell2->text = 'Hermione Granger';
1966 * $cell3 = new html_table_cell();
1967 * $cell3->text = '100 %';
1968 * $row2 = new html_table_row();
1969 * $row2->cells = array($cell2, $cell3);
1970 * $t->data = array($row1, $row2);
1971 */
1972 public $data;
9678c7b8 1973
beb56299 1974 /**
beb56299 1975 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 1976 * @var string Width of the table, percentage of the page preferred.
beb56299 1977 */
1978 public $width = null;
9678c7b8 1979
beb56299 1980 /**
beb56299 1981 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 1982 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
beb56299 1983 */
1984 public $tablealign = null;
9678c7b8 1985
beb56299 1986 /**
beb56299 1987 * @deprecated since Moodle 2.0. Styling should be in the CSS.
76be40cc 1988 * @var int Padding on each cell, in pixels
beb56299 1989 */
1990 public $cellpadding = null;
9678c7b8 1991
beb56299 1992 /**
76be40cc 1993 * @var int Spacing between cells, in pixels
beb56299 1994 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1995 */
1996 public $cellspacing = null;
9678c7b8 1997
beb56299 1998 /**
76be40cc 1999 * @var array Array of classes to add to particular rows, space-separated string.
beb56299 2000 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2001 * respectively. Class 'lastrow' is added automatically for the last row
2002 * in the table.
d9c8f425 2003 *
beb56299 2004 * Example of usage:
2005 * $t->rowclasses[9] = 'tenth'
2006 */
2007 public $rowclasses;
9678c7b8 2008
beb56299 2009 /**
76be40cc 2010 * @var array An array of classes to add to every cell in a particular column,
beb56299 2011 * space-separated string. Class 'cell' is added automatically by the renderer.
2012 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2013 * respectively. Class 'lastcol' is added automatically for all last cells
2014 * in a row.
d9c8f425 2015 *
beb56299 2016 * Example of usage:
2017 * $t->colclasses = array(null, 'grade');
d9c8f425 2018 */
beb56299 2019 public $colclasses;
9678c7b8 2020
beb56299 2021 /**
76be40cc 2022 * @var string Description of the contents for screen readers.
beb56299 2023 */
2024 public $summary;
d9c8f425 2025
2026 /**
16be8974 2027 * Constructor
d9c8f425 2028 */
16be8974
DM
2029 public function __construct() {
2030 $this->attributes['class'] = '';
d9c8f425 2031 }
d9c8f425 2032}
2033
2034/**
7b1f2c82 2035 * Component representing a table row.
d9c8f425 2036 *
2037 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2039 * @since Moodle 2.0
f8129210 2040 * @package core
76be40cc 2041 * @category output
d9c8f425 2042 */
16be8974 2043class html_table_row {
9678c7b8 2044
16be8974 2045 /**
76be40cc 2046 * @var string Value to use for the id attribute of the row.
16be8974
DM
2047 */
2048 public $id = null;
9678c7b8 2049
d9c8f425 2050 /**
76be40cc 2051 * @var array Array of html_table_cell objects
d9c8f425 2052 */
7b1f2c82 2053 public $cells = array();
9678c7b8 2054
beb56299 2055 /**
76be40cc 2056 * @var string Value to use for the style attribute of the table row
beb56299 2057 */
16be8974 2058 public $style = null;
9678c7b8 2059
16be8974 2060 /**
76be40cc 2061 * @var array Attributes of additional HTML attributes for the <tr> element
16be8974
DM
2062 */
2063 public $attributes = array();
a0ead5eb 2064
54a007e8 2065 /**
8cea545e 2066 * Constructor
54a007e8 2067 * @param array $cells
8cea545e
PS
2068 */
2069 public function __construct(array $cells=null) {
16be8974 2070 $this->attributes['class'] = '';
8cea545e
PS
2071 $cells = (array)$cells;
2072 foreach ($cells as $cell) {
2073 if ($cell instanceof html_table_cell) {
2074 $this->cells[] = $cell;
a019627a 2075 } else {
8cea545e 2076 $this->cells[] = new html_table_cell($cell);
a019627a 2077 }
2078 }
54a007e8 2079 }
d9c8f425 2080}
2081
2082/**
7b1f2c82 2083 * Component representing a table cell.
d9c8f425 2084 *
2085 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2087 * @since Moodle 2.0
f8129210 2088 * @package core
76be40cc 2089 * @category output
d9c8f425 2090 */
16be8974 2091class html_table_cell {
9678c7b8 2092
16be8974 2093 /**
76be40cc 2094 * @var string Value to use for the id attribute of the cell.
16be8974
DM
2095 */
2096 public $id = null;
9678c7b8 2097
d9c8f425 2098 /**
76be40cc 2099 * @var string The contents of the cell.
d9c8f425 2100 */
7b1f2c82 2101 public $text;
9678c7b8 2102
d9c8f425 2103 /**
76be40cc 2104 * @var string Abbreviated version of the contents of the cell.
d9c8f425 2105 */
97c10099 2106 public $abbr = null;
9678c7b8 2107
d9c8f425 2108 /**
76be40cc 2109 * @var int Number of columns this cell should span.
d9c8f425 2110 */
97c10099 2111 public $colspan = null;
9678c7b8 2112
d9c8f425 2113 /**
76be40cc 2114 * @var int Number of rows this cell should span.
d9c8f425 2115 */
97c10099 2116 public $rowspan = null;
9678c7b8 2117
d9c8f425 2118 /**
76be40cc 2119 * @var string Defines a way to associate header cells and data cells in a table.
d9c8f425 2120 */
97c10099 2121 public $scope = null;
9678c7b8 2122
1ae3767a 2123 /**
3d3fae72 2124 * @var bool Whether or not this cell is a header cell.
1ae3767a 2125 */
a4998d01 2126 public $header = null;
9678c7b8 2127
16be8974 2128 /**
76be40cc 2129 * @var string Value to use for the style attribute of the table cell
16be8974
DM
2130 */
2131 public $style = null;
9678c7b8 2132
16be8974 2133 /**
76be40cc 2134 * @var array Attributes of additional HTML attributes for the <td> element
16be8974
DM
2135 */
2136 public $attributes = array();
d9c8f425 2137
9678c7b8
SH
2138 /**
2139 * Constructs a table cell
2140 *
2141 * @param string $text
2142 */
8cea545e
PS
2143 public function __construct($text = null) {
2144 $this->text = $text;
16be8974 2145 $this->attributes['class'] = '';
d9c8f425 2146 }
2147}
2148
d9c8f425 2149/**
beb56299 2150 * Component representing a paging bar.
d9c8f425 2151 *
2152 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2154 * @since Moodle 2.0
f8129210 2155 * @package core
76be40cc 2156 * @category output
d9c8f425 2157 */
929d7a83 2158class paging_bar implements renderable {
9678c7b8 2159
d9c8f425 2160 /**
76be40cc 2161 * @var int The maximum number of pagelinks to display.
d9c8f425 2162 */
beb56299 2163 public $maxdisplay = 18;
9678c7b8 2164
d9c8f425 2165 /**
76be40cc 2166 * @var int The total number of entries to be pages through..
d9c8f425 2167 */
beb56299 2168 public $totalcount;
9678c7b8 2169
d9c8f425 2170 /**
76be40cc 2171 * @var int The page you are currently viewing.
d9c8f425 2172 */
929d7a83 2173 public $page;
9678c7b8 2174
d9c8f425 2175 /**
76be40cc 2176 * @var int The number of entries that should be shown per page.
d9c8f425 2177 */
beb56299 2178 public $perpage;
9678c7b8 2179
d9c8f425 2180 /**
76be40cc 2181 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
9678c7b8
SH
2182 * an equals sign and the page number.
2183 * If this is a moodle_url object then the pagevar param will be replaced by
2184 * the page no, for each page.
d9c8f425 2185 */
beb56299 2186 public $baseurl;
9678c7b8 2187
d9c8f425 2188 /**
76be40cc 2189 * @var string This is the variable name that you use for the pagenumber in your
9678c7b8 2190 * code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 2191 */
929d7a83 2192 public $pagevar;
9678c7b8 2193
beb56299 2194 /**
76be40cc 2195 * @var string A HTML link representing the "previous" page.
beb56299 2196 */
2197 public $previouslink = null;
9678c7b8 2198
beb56299 2199 /**
76be40cc 2200 * @var string A HTML link representing the "next" page.
beb56299 2201 */
2202 public $nextlink = null;
9678c7b8 2203
beb56299 2204 /**
76be40cc 2205 * @var string A HTML link representing the first page.
beb56299 2206 */
2207 public $firstlink = null;
9678c7b8 2208
beb56299 2209 /**
76be40cc 2210 * @var string A HTML link representing the last page.
beb56299 2211 */
2212 public $lastlink = null;
9678c7b8 2213
beb56299 2214 /**
76be40cc 2215 * @var array An array of strings. One of them is just a string: the current page
beb56299 2216 */
2217 public $pagelinks = array();
d9c8f425 2218
929d7a83
PS
2219 /**
2220 * Constructor paging_bar with only the required params.
2221 *
1a10840e 2222 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2223 * @param int $page The page you are currently viewing
2224 * @param int $perpage The number of entries that should be shown per page
2225 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2226 * @param string $pagevar name of page parameter that holds the page number
2227 */
2228 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2229 $this->totalcount = $totalcount;
2230 $this->page = $page;
2231 $this->perpage = $perpage;
2232 $this->baseurl = $baseurl;
2233 $this->pagevar = $pagevar;
2234 }
2235
d9c8f425 2236 /**
9678c7b8
SH
2237 * Prepares the paging bar for output.
2238 *
2239 * This method validates the arguments set up for the paging bar and then
2240 * produces fragments of HTML to assist display later on.
f8129210
SH
2241 *
2242 * @param renderer_base $output
2243 * @param moodle_page $page
2244 * @param string $target
2245 * @throws coding_exception
d9c8f425 2246 */
34059565 2247 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 2248 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 2249 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 2250 }
2251 if (!isset($this->page) || is_null($this->page)) {
929d7a83 2252 throw new coding_exception('paging_bar requires a page value.');
beb56299 2253 }
2254 if (empty($this->perpage)) {
929d7a83 2255 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 2256 }
2257 if (empty($this->baseurl)) {
929d7a83 2258 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 2259 }
d9c8f425 2260
beb56299 2261 if ($this->totalcount > $this->perpage) {
2262 $pagenum = $this->page - 1;
d9c8f425 2263
beb56299 2264 if ($this->page > 0) {
929d7a83 2265 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 2266 }
d9c8f425 2267
beb56299 2268 if ($this->perpage > 0) {
2269 $lastpage = ceil($this->totalcount / $this->perpage);
2270 } else {
2271 $lastpage = 1;
2272 }
2273
2274 if ($this->page > 15) {
2275 $startpage = $this->page - 10;
2276
929d7a83 2277 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 2278 } else {
2279 $startpage = 0;
2280 }
2281
2282 $currpage = $startpage;
2283 $displaycount = $displaypage = 0;
2284
2285 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2286 $displaypage = $currpage + 1;
2287
f43cdceb 2288 if ($this->page == $currpage) {
beb56299 2289 $this->pagelinks[] = $displaypage;
2290 } else {
56ddb719 2291 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 2292 $this->pagelinks[] = $pagelink;
2293 }
2294
2295 $displaycount++;
2296 $currpage++;
2297 }
2298
2299 if ($currpage < $lastpage) {
2300 $lastpageactual = $lastpage - 1;
abdac127 2301 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 2302 }
2303
2304 $pagenum = $this->page + 1;
2305
2306 if ($pagenum != $displaypage) {
abdac127 2307 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 2308 }
d9c8f425 2309 }
2310 }
d9c8f425 2311}
2312
d9c8f425 2313/**
beb56299 2314 * This class represents how a block appears on a page.
d9c8f425 2315 *
beb56299 2316 * During output, each block instance is asked to return a block_contents object,
2317 * those are then passed to the $OUTPUT->block function for display.
2318 *
f8129210 2319 * contents should probably be generated using a moodle_block_..._renderer.
beb56299 2320 *
2321 * Other block-like things that need to appear on the page, for example the
2322 * add new block UI, are also represented as block_contents objects.
2323 *
2324 * @copyright 2009 Tim Hunt
9678c7b8
SH
2325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2326 * @since Moodle 2.0
f8129210 2327 * @package core
76be40cc 2328 * @category output
d9c8f425 2329 */
dd72b308 2330class block_contents {
beb56299 2331
76be40cc 2332 /** Used when the block cannot be collapsed **/
beb56299 2333 const NOT_HIDEABLE = 0;
76be40cc
SH
2334
2335 /** Used when the block can be collapsed but currently is not **/
beb56299 2336 const VISIBLE = 1;
76be40cc
SH
2337
2338 /** Used when the block has been collapsed **/
beb56299 2339 const HIDDEN = 2;
2340
d9c8f425 2341 /**
76be40cc 2342 * @var int Used to set $skipid.
9678c7b8
SH
2343 */
2344 protected static $idcounter = 1;
2345
2346 /**
3d3fae72 2347 * @var int All the blocks (or things that look like blocks) printed on
76be40cc 2348 * a page are given a unique number that can be used to construct id="" attributes.
9678c7b8 2349 * This is set automatically be the {@link prepare()} method.
beb56299 2350 * Do not try to set it manually.
d9c8f425 2351 */
beb56299 2352 public $skipid;
d9c8f425 2353
2354 /**
3d3fae72 2355 * @var int If this is the contents of a real block, this should be set
76be40cc 2356 * to the block_instance.id. Otherwise this should be set to 0.
beb56299 2357 */
2358 public $blockinstanceid = 0;
2359
2360 /**
3d3fae72 2361 * @var int If this is a real block instance, and there is a corresponding
beb56299 2362 * block_position.id for the block on this page, this should be set to that id.
2363 * Otherwise it should be 0.
2364 */
2365 public $blockpositionid = 0;
2366
2367 /**
76be40cc 2368 * @var array An array of attribute => value pairs that are put on the outer div of this
9678c7b8 2369 * block. {@link $id} and {@link $classes} attributes should be set separately.
beb56299 2370 */
dd72b308 2371 public $attributes;
beb56299 2372
2373 /**
76be40cc 2374 * @var string The title of this block. If this came from user input, it should already
9678c7b8
SH
2375 * have had format_string() processing done on it. This will be output inside
2376 * <h2> tags. Please do not cause invalid XHTML.
beb56299 2377 */
2378 public $title = '';
2379
2380 /**
76be40cc 2381 * @var string HTML for the content
beb56299 2382 */
2383 public $content = '';
2384
2385 /**
76be40cc 2386 * @var array An alternative to $content, it you want a list of things with optional icons.
beb56299 2387 */
2388 public $footer = '';
2389
2390 /**
76be40cc
SH
2391 * @var string Any small print that should appear under the block to explain
2392 * to the teacher about the block, for example 'This is a sticky block that was
beb56299 2393 * added in the system context.'
beb56299 2394 */
2395 public $annotation = '';
2396
2397 /**
3d3fae72 2398 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
beb56299 2399 * the user can toggle whether this block is visible.
2400 */
2401 public $collapsible = self::NOT_HIDEABLE;
2402
2403 /**
76be40cc
SH
2404 * @var array A (possibly empty) array of editing controls. Each element of
2405 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 2406 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 2407 */
2408 public $controls = array();
2409
dd72b308 2410
beb56299 2411 /**
dd72b308
PS
2412 * Create new instance of block content
2413 * @param array $attributes
d9c8f425 2414 */
9678c7b8 2415 public function __construct(array $attributes = null) {
beb56299 2416 $this->skipid = self::$idcounter;
2417 self::$idcounter += 1;
dd72b308
PS
2418
2419 if ($attributes) {
2420 // standard block
2421 $this->attributes = $attributes;
2422 } else {
2423 // simple "fake" blocks used in some modules and "Add new block" block
6605ff8c 2424 $this->attributes = array('class'=>'block');
beb56299 2425 }
dd72b308
PS
2426 }
2427
2428 /**
2429 * Add html class to block
9678c7b8 2430 *
dd72b308 2431 * @param string $class
dd72b308
PS
2432 */
2433 public function add_class($class) {
2434 $this->attributes['class'] .= ' '.$class;
d9c8f425 2435 }
2436}
beb56299 2437
34059565 2438
beb56299 2439/**
2440 * This class represents a target for where a block can go when it is being moved.
2441 *
2442 * This needs to be rendered as a form with the given hidden from fields, and
2443 * clicking anywhere in the form should submit it. The form action should be
2444 * $PAGE->url.
2445 *
2446 * @copyright 2009 Tim Hunt
9678c7b8
SH
2447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2448 * @since Moodle 2.0
f8129210 2449 * @package core
76be40cc 2450 * @category output
beb56299 2451 */
dd72b308 2452class block_move_target {
9678c7b8 2453
beb56299 2454 /**
76be40cc 2455 * @var moodle_url Move url
beb56299 2456 */
dd72b308 2457 public $url;
9678c7b8 2458
beb56299 2459 /**
76be40cc 2460 * @var string label
beb56299 2461 */
dd72b308
PS
2462 public $text;
2463
2464 /**
1a10840e 2465 * Constructor
dd72b308
PS
2466 * @param string $text
2467 * @param moodle_url $url
2468 */
2469 public function __construct($text, moodle_url $url) {
2470 $this->text = $text;
2471 $this->url = $url;
2472 }
beb56299 2473}
d2dbd0c0
SH
2474
2475/**
2476 * Custom menu item
2477 *
2478 * This class is used to represent one item within a custom menu that may or may
2479 * not have children.
2480 *
2481 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2483 * @since Moodle 2.0
f8129210 2484 * @package core
76be40cc 2485 * @category output
d2dbd0c0
SH
2486 */
2487class custom_menu_item implements renderable {
9678c7b8 2488
d2dbd0c0 2489 /**
76be40cc 2490 * @var string The text to show for the item
d2dbd0c0
SH
2491 */
2492 protected $text;
9678c7b8 2493
d2dbd0c0 2494 /**
76be40cc 2495 * @var moodle_url The link to give the icon if it has no children
d2dbd0c0
SH
2496 */
2497 protected $url;
9678c7b8 2498
d2dbd0c0 2499 /**
76be40cc 2500 * @var string A title to apply to the item. By default the text
d2dbd0c0
SH
2501 */
2502 protected $title;
9678c7b8 2503
d2dbd0c0 2504 /**
76be40cc
SH
2505 * @var int A sort order for the item, not necessary if you order things in
2506 * the CFG var.
d2dbd0c0
SH
2507 */
2508 protected $sort;
9678c7b8 2509
d2dbd0c0 2510 /**
76be40cc
SH
2511 * @var custom_menu_item A reference to the parent for this item or NULL if
2512 * it is a top level item
d2dbd0c0
SH
2513 */
2514 protected $parent;
9678c7b8 2515
d2dbd0c0 2516 /**
76be40cc 2517 * @var array A array in which to store children this item has.
d2dbd0c0
SH
2518 */
2519 protected $children = array();
9678c7b8 2520
d2dbd0c0 2521 /**
76be40cc 2522 * @var int A reference to the sort var of the last child that was added
d2dbd0c0
SH
2523 */
2524 protected $lastsort = 0;
9678c7b8 2525
d2dbd0c0
SH
2526 /**
2527 * Constructs the new custom menu item
2528 *
2529 * @param string $text
2530 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2531 * @param string $title A title to apply to this item [Optional]
2532 * @param int $sort A sort or to use if we need to sort differently [Optional]
2533 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2534 * belongs to, only if the child has a parent. [Optional]
2535 */
9678c7b8 2536 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
d2dbd0c0
SH
2537 $this->text = $text;
2538 $this->url = $url;
2539 $this->title = $title;
2540 $this->sort = (int)$sort;
2541 $this->parent = $parent;
2542 }
2543
2544 /**
2545 * Adds a custom menu item as a child of this node given its properties.
2546 *
2547 * @param string $text
2548 * @param moodle_url $url
2549 * @param string $title
2550 * @param int $sort
2551 * @return custom_menu_item
2552 */
9678c7b8 2553 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
d2dbd0c0
SH
2554 $key = count($this->children);
2555 if (empty($sort)) {
2556 $sort = $this->lastsort + 1;
2557 }
2558 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2559 $this->lastsort = (int)$sort;
2560 return $this->children[$key];
2561 }
9678c7b8 2562
d2dbd0c0
SH
2563 /**
2564 * Returns the text for this item
2565 * @return string
2566 */
2567 public function get_text() {
2568 return $this->text;
2569 }
9678c7b8 2570
d2dbd0c0
SH
2571 /**
2572 * Returns the url for this item
2573 * @return moodle_url
2574 */
2575 public function get_url() {
2576 return $this->url;
2577 }
9678c7b8 2578
d2dbd0c0
SH
2579 /**
2580 * Returns the title for this item
2581 * @return string
2582 */
2583 public function get_title() {
2584 return $this->title;
2585 }
9678c7b8 2586
d2dbd0c0
SH
2587 /**
2588 * Sorts and returns the children for this item
2589 * @return array
2590 */
2591 public function get_children() {
2592 $this->sort();
2593 return $this->children;
2594 }
9678c7b8 2595
d2dbd0c0
SH
2596 /**
2597 * Gets the sort order for this child
2598 * @return int
2599 */
2600 public function get_sort_order() {
2601 return $this->sort;
2602 }
9678c7b8 2603
d2dbd0c0
SH
2604 /**
2605 * Gets the parent this child belong to
2606 * @return custom_menu_item
2607 */
2608 public function get_parent() {
2609 return $this->parent;
2610 }
9678c7b8 2611
d2dbd0c0
SH
2612 /**
2613 * Sorts the children this item has
2614 */
2615 public function sort() {
2616 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2617 }
9678c7b8 2618
d2dbd0c0
SH
2619 /**
2620 * Returns true if this item has any children
2621 * @return bool
2622 */
2623 public function has_children() {
2624 return (count($this->children) > 0);
2625 }
f3827323
SH
2626
2627 /**
2628 * Sets the text for the node
2629 * @param string $text
2630 */
2631 public function set_text($text) {
2632 $this->text = (string)$text;
2633 }
2634
2635 /**
2636 * Sets the title for the node
2637 * @param string $title
2638 */
2639 public function set_title($title) {
2640 $this->title = (string)$title;
2641 }
2642
2643 /**
2644 * Sets the url for the node
2645 * @param moodle_url $url
2646 */
2647 public function set_url(moodle_url $url) {
2648 $this->url = $url;
2649 }
d2dbd0c0
SH
2650}
2651
2652/**
2653 * Custom menu class
2654 *
2655 * This class is used to operate a custom menu that can be rendered for the page.
2656 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2657 * of custom_menu_item nodes that can be rendered by the core renderer.
2658 *
2659 * To configure the custom menu:
2660 * Settings: Administration > Appearance > Themes > Theme settings
2661 *
2662 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2663 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2664 * @since Moodle 2.0
f8129210 2665 * @package core
76be40cc 2666 * @category output
d2dbd0c0
SH
2667 */
2668class custom_menu extends custom_menu_item {
155fffe6 2669
9678c7b8 2670 /**
76be40cc 2671 * @var string The language we should render for, null disables multilang support.
9678c7b8 2672 */
4564d58f
DM
2673 protected $currentlanguage = null;
2674
d2dbd0c0
SH
2675 /**
2676 * Creates the custom menu
155fffe6
DM
2677 *
2678 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
f8129210 2679 * @param string $currentlanguage the current language code, null disables multilang support
d2dbd0c0 2680 */
4564d58f 2681 public function __construct($definition = '', $currentlanguage = null) {
4564d58f 2682 $this->currentlanguage = $currentlanguage;
155fffe6
DM
2683 parent::__construct('root'); // create virtual root element of the menu
2684 if (!empty($definition)) {
4564d58f 2685 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
12cc75ae 2686 }
d2dbd0c0
SH
2687 }
2688
2689 /**
2690 * Overrides the children of this custom menu. Useful when getting children
2691 * from $CFG->custommenuitems
9678c7b8
SH
2692 *
2693 * @param array $children
d2dbd0c0
SH
2694 */
2695 public function override_children(array $children) {
2696 $this->children = array();
2697 foreach ($children as $child) {
2698 if ($child instanceof custom_menu_item) {
2699 $this->children[] = $child;
2700 }
2701 }
2702 }
2703
2704 /**
2705 * Converts a string into a structured array of custom_menu_items which can
2706 * then be added to a custom menu.
2707 *
2708 * Structure:
4564d58f
DM
2709 * text|url|title|langs
2710 * The number of hyphens at the start determines the depth of the item. The
2711 * languages are optional, comma separated list of languages the line is for.
d2dbd0c0
SH
2712 *
2713 * Example structure:
2714 * First level first item|http://www.moodle.com/
2715 * -Second level first item|http://www.moodle.com/partners/
2716 * -Second level second item|http://www.moodle.com/hq/
2717 * --Third level first item|http://www.moodle.com/jobs/
2718 * -Second level third item|http://www.moodle.com/development/
2719 * First level second item|http://www.moodle.com/feedback/
2720 * First level third item
4564d58f
DM
2721 * English only|http://moodle.com|English only item|en
2722 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2723 *
4d2ee4c2 2724 *
d2dbd0c0 2725 * @static
4564d58f
DM
2726 * @param string $text the menu items definition
2727 * @param string $language the language code, null disables multilang support
d2dbd0c0
SH
2728 * @return array
2729 */
4564d58f 2730 public static function convert_text_to_menu_nodes($text, $language = null) {
d2dbd0c0
SH
2731 $lines = explode("\n", $text);
2732 $children = array();
2733 $lastchild = null;
2734 $lastdepth = null;
2735 $lastsort = 0;
2736 foreach ($lines as $line) {
2737 $line = trim($line);
4564d58f
DM
2738 $bits = explode('|', $line, 4); // name|url|title|langs
2739 if (!array_key_exists(0, $bits) or empty($bits[0])) {
d2dbd0c0
SH
2740 // Every item must have a name to be valid
2741 continue;
2742 } else {
2743 $bits[0] = ltrim($bits[0],'-');
2744 }
4564d58f 2745 if (!array_key_exists(1, $bits) or empty($bits[1])) {
d2dbd0c0
SH
2746 // Set the url to null
2747 $bits[1] = null;
2748 } else {
2749 // Make sure the url is a moodle url
a26f25ae 2750 $bits[1] = new moodle_url(trim($bits[1]));
d2dbd0c0 2751 }
4564d58f 2752 if (!array_key_exists(2, $bits) or empty($bits[2])) {
d2dbd0c0
SH
2753 // Set the title to null seeing as there isn't one
2754 $bits[2] = $bits[0];
2755 }
4564d58f
DM
2756 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2757 // The item is valid for all languages
2758 $itemlangs = null;
2759 } else {
2760 $itemlangs = array_map('trim', explode(',', $bits[3]));
2761 }
2762 if (!empty($language) and !empty($itemlangs)) {
2763 // check that the item is intended for the current language
2764 if (!in_array($language, $itemlangs)) {
2765 continue;
2766 }
2767 }
d2dbd0c0 2768 // Set an incremental sort order to keep it simple.
4564d58f 2769 $lastsort++;
d2dbd0c0
SH
2770 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2771 $depth = strlen($match[1]);
2772 if ($depth < $lastdepth) {
57bedaee
SH
2773 $difference = $lastdepth - $depth;
2774 if ($lastdepth > 1 && $lastdepth != $difference) {
2775 $tempchild = $lastchild->get_parent();
2776 for ($i =0; $i < $difference; $i++) {
2777 $tempchild = $tempchild->get_parent();
2778 }
4564d58f 2779 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2780 } else {
2781 $depth = 0;
4564d58f 2782 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2783 $children[] = $lastchild;
2784 }
2785 } else if ($depth > $lastdepth) {
2786 $depth = $lastdepth + 1;
4564d58f 2787 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2788 } else {
2789 if ($depth == 0) {
4564d58f 2790 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2791 $children[] = $lastchild;
2792 } else {
4564d58f 2793 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2794 }
2795 }
2796 } else {
2797 $depth = 0;
4564d58f 2798 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2799 $children[] = $lastchild;
2800 }
2801 $lastdepth = $depth;
2802 }
2803 return $children;
2804 }
2805
2806 /**
2807 * Sorts two custom menu items
2808 *
2809 * This function is designed to be used with the usort method
2810 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2811 *
9678c7b8 2812 * @static
d2dbd0c0
SH
2813 * @param custom_menu_item $itema
2814 * @param custom_menu_item $itemb
2815 * @return int
2816 */
2817 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2818 $itema = $itema->get_sort_order();
2819 $itemb = $itemb->get_sort_order();
2820 if ($itema == $itemb) {
2821 return 0;
2822 }
2823 return ($itema > $itemb) ? +1 : -1;
2824 }
de7a570c 2825}