MDL-30979 output: Fixed up phpdocs for page requirements code
[moodle.git] / lib / outputcomponents.php
CommitLineData
d9c8f425 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Classes representing HTML elements, used by $OUTPUT methods
20 *
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
23 *
9678c7b8
SH
24 * @package core
25 * @subpackage output
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d9c8f425 28 */
29
78bfb562 30defined('MOODLE_INTERNAL') || die();
5d0c95a5
PS
31
32/**
33 * Interface marking other classes as suitable for renderer_base::render()
9678c7b8
SH
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
35 * @package core
36 * @subpackage 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
48 * @package core
49 * @subpackage output
bb496de7
DC
50 */
51class file_picker implements renderable {
9678c7b8
SH
52
53 /**
54 * An object containing options for the file picker
55 * @var stdClass
56 */
bb496de7 57 public $options;
9678c7b8
SH
58
59 /**
60 * Constructs a file picker object.
61 *
62 * The following are possible options for the filepicker:
63 * - accepted_types (*)
64 * - return_types (FILE_INTERNAL)
65 * - env (filepicker)
66 * - client_id (uniqid)
67 * - itemid (0)
68 * - maxbytes (-1)
69 * - maxfiles (1)
70 * - buttonname (false)
71 *
72 * @param stdClass $options An object containing options for the file picker.
73 */
bb496de7
DC
74 public function __construct(stdClass $options) {
75 global $CFG, $USER, $PAGE;
76 require_once($CFG->dirroot. '/repository/lib.php');
77 $defaults = array(
78 'accepted_types'=>'*',
bb496de7
DC
79 'return_types'=>FILE_INTERNAL,
80 'env' => 'filepicker',
81 'client_id' => uniqid(),
82 'itemid' => 0,
83 'maxbytes'=>-1,
84 'maxfiles'=>1,
f50a61fb 85 'buttonname'=>false
bb496de7
DC
86 );
87 foreach ($defaults as $key=>$value) {
88 if (empty($options->$key)) {
89 $options->$key = $value;
90 }
91 }
92
93 $options->currentfile = '';
94 if (!empty($options->itemid)) {
95 $fs = get_file_storage();
96 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
e4256380 97 if (empty($options->filename)) {
64f93798 98 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
e4256380
DC
99 $file = reset($files);
100 }
101 } else {
64f93798 102 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
e4256380
DC
103 }
104 if (!empty($file)) {
ee9a4962 105 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
bb496de7
DC
106 }
107 }
108
bb496de7
DC
109 // initilise options, getting files in root path
110 $this->options = initialise_filepicker($options);
111
112 // copying other options
113 foreach ($options as $name=>$value) {
98e7ae63
DC
114 if (!isset($this->options->$name)) {
115 $this->options->$name = $value;
116 }
bb496de7
DC
117 }
118 }
119}
120
5d0c95a5 121/**
bf11293a 122 * Data structure representing a user picture.
5d0c95a5
PS
123 *
124 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
9678c7b8
SH
125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 * @since Modle 2.0
127 * @package core
128 * @subpackage output
5d0c95a5
PS
129 */
130class user_picture implements renderable {
131 /**
9678c7b8
SH
132 * List of mandatory fields in user record here. (do not include TEXT columns
133 * because it would break SELECT DISTINCT in MSSQL and ORACLE)
134 * @var array
5d0c95a5 135 */
03636668 136 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email'); //TODO: add deleted
5d0c95a5
PS
137
138 /**
9678c7b8
SH
139 * A user object with at least fields all columns specified in $fields array constant set.
140 * @var object $user
5d0c95a5
PS
141 */
142 public $user;
9678c7b8 143
5d0c95a5 144 /**
9678c7b8 145 * The course id. Used when constructing the link to the user's profile,
5d0c95a5 146 * page course id used if not specified.
9678c7b8 147 * @var int $courseid
5d0c95a5
PS
148 */
149 public $courseid;
9678c7b8 150
5d0c95a5 151 /**
9678c7b8
SH
152 * Add course profile link to image
153 * @var bool $link
5d0c95a5
PS
154 */
155 public $link = true;
9678c7b8 156
5d0c95a5 157 /**
9678c7b8
SH
158 * Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px)
159 * for backward compatibility.
160 * @var int $size
5d0c95a5
PS
161 */
162 public $size = 35;
9678c7b8 163
5d0c95a5 164 /**
9678c7b8 165 * Add non-blank alt-text to the image.
5d0c95a5 166 * Default true, set to false when image alt just duplicates text in screenreaders.
9678c7b8 167 * @var boolean $alttext
5d0c95a5
PS
168 */
169 public $alttext = true;
9678c7b8 170
5d0c95a5 171 /**
9678c7b8
SH
172 * Whether or not to open the link in a popup window.
173 * @var boolean $popup
5d0c95a5
PS
174 */
175 public $popup = false;
9678c7b8 176
5d0c95a5 177 /**
9678c7b8
SH
178 * Image class attribute
179 * @var string
5d0c95a5
PS
180 */
181 public $class = 'userpicture';
182
183 /**
184 * User picture constructor.
185 *
9678c7b8 186 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
5d0c95a5
PS
187 */
188 public function __construct(stdClass $user) {
189 global $DB;
190
5d0c95a5
PS
191 if (empty($user->id)) {
192 throw new coding_exception('User id is required when printing user avatar image.');
193 }
194
195 // only touch the DB if we are missing data and complain loudly...
196 $needrec = false;
3a11c09f 197 foreach (self::$fields as $field) {
5d0c95a5
PS
198 if (!array_key_exists($field, $user)) {
199 $needrec = true;
200 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
201 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
202 break;
203 }
204 }
205
206 if ($needrec) {
3a11c09f 207 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
5d0c95a5
PS
208 } else {
209 $this->user = clone($user);
210 }
211 }
212
213 /**
1a10840e 214 * Returns a list of required user fields, useful when fetching required user info from db.
f3afba4e
PS
215 *
216 * In some cases we have to fetch the user data together with some other information,
217 * the idalias is useful there because the id would otherwise override the main
218 * id of the result record. Please note it has to be converted back to id before rendering.
219 *
5d0c95a5 220 * @param string $tableprefix name of database table prefix in query
3a11c09f 221 * @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 222 * @param string $idalias alias of id field
9958e561 223 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
5d0c95a5
PS
224 * @return string
225 */
9958e561 226 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
3a11c09f
PS
227 if (!$tableprefix and !$extrafields and !$idalias) {
228 return implode(',', self::$fields);
5d0c95a5 229 }
3a11c09f
PS
230 if ($tableprefix) {
231 $tableprefix .= '.';
232 }
233 $fields = array();
234 foreach (self::$fields as $field) {
235 if ($field === 'id' and $idalias and $idalias !== 'id') {
6f7b89e2 236 $fields[$field] = "$tableprefix$field AS $idalias";
3a11c09f 237 } else {
9958e561
DM
238 if ($fieldprefix and $field !== 'id') {
239 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
240 } else {
241 $fields[$field] = "$tableprefix$field";
242 }
3a11c09f
PS
243 }
244 }
245 // add extra fields if not already there
246 if ($extrafields) {
247 foreach ($extrafields as $e) {
248 if ($e === 'id' or isset($fields[$e])) {
249 continue;
250 }
5c0d03ea
DM
251 if ($fieldprefix) {
252 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
253 } else {
254 $fields[$e] = "$tableprefix$e";
255 }
f3afba4e 256 }
f3afba4e
PS
257 }
258 return implode(',', $fields);
5d0c95a5 259 }
5d0c95a5 260
5c0d03ea
DM
261 /**
262 * Extract the aliased user fields from a given record
263 *
264 * Given a record that was previously obtained using {@link self::fields()} with aliases,
265 * this method extracts user related unaliased fields.
266 *
267 * @param stdClass $record containing user picture fields
268 * @param array $extrafields extra fields included in the $record
269 * @param string $idalias alias of the id field
270 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
271 * @return stdClass object with unaliased user fields
272 */
9678c7b8 273 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
5c0d03ea
DM
274
275 if (empty($idalias)) {
276 $idalias = 'id';
277 }
278
279 $return = new stdClass();
280
281 foreach (self::$fields as $field) {
282 if ($field === 'id') {
9ecbf801 283 if (property_exists($record, $idalias)) {
5c0d03ea
DM
284 $return->id = $record->{$idalias};
285 }
286 } else {
9ecbf801 287 if (property_exists($record, $fieldprefix.$field)) {
5c0d03ea
DM
288 $return->{$field} = $record->{$fieldprefix.$field};
289 }
290 }
291 }
292 // add extra fields if not already there
293 if ($extrafields) {
294 foreach ($extrafields as $e) {
9ecbf801 295 if ($e === 'id' or property_exists($return, $e)) {
5c0d03ea
DM
296 continue;
297 }
298 $return->{$e} = $record->{$fieldprefix.$e};
299 }
300 }
301
302 return $return;
871a3ec5
SH
303 }
304
305 /**
306 * Works out the URL for the users picture.
307 *
308 * This method is recommended as it avoids costly redirects of user pictures
309 * if requests are made for non-existent files etc.
310 *
311 * @param renderer_base $renderer
312 * @return moodle_url
313 */
314 public function get_url(moodle_page $page, renderer_base $renderer = null) {
33dca156 315 global $CFG;
871a3ec5
SH
316
317 if (is_null($renderer)) {
318 $renderer = $page->get_renderer('core');
319 }
320
90911c4f
EL
321 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
322 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
871a3ec5 323 // protect images if login required and not logged in;
90911c4f 324 // also if login is required for profile images and is not logged in or guest
871a3ec5
SH
325 // do not use require_login() because it is expensive and not suitable here anyway
326 return $renderer->pix_url('u/f1');
327 }
328
329 // Sort out the filename and size. Size is only required for the gravatar
330 // implementation presently.
331 if (empty($this->size)) {
332 $filename = 'f2';
333 $size = 35;
334 } else if ($this->size === true or $this->size == 1) {
335 $filename = 'f1';
336 $size = 100;
337 } else if ($this->size >= 50) {
338 $filename = 'f1';
339 $size = (int)$this->size;
340 } else {
341 $filename = 'f2';
342 $size = (int)$this->size;
343 }
344
4125bdc1
SH
345 // First we need to determine whether the user has uploaded a profile
346 // picture of not.
03636668
PS
347 if (!empty($this->user->deleted) or !$context = context_user::instance($this->user->id, IGNORE_MISSING)) {
348 $hasuploadedfile = false;
349 } else {
350 $fs = get_file_storage();
351 $hasuploadedfile = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg'));
352 }
4125bdc1
SH
353
354 $imageurl = $renderer->pix_url('u/'.$filename);
355 if ($hasuploadedfile && $this->user->picture == 1) {
871a3ec5
SH
356 $path = '/';
357 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
358 // We append the theme name to the file path if we have it so that
359 // in the circumstance that the profile picture is not available
360 // when the user actually requests it they still get the profile
361 // picture for the correct theme.
362 $path .= $page->theme->name.'/';
363 }
4125bdc1
SH
364 // Set the image URL to the URL for the uploaded file.
365 $imageurl = moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, $path, $filename);
366 } else if (!empty($CFG->enablegravatar)) {
367 // Normalise the size variable to acceptable bounds
368 if ($size < 1 || $size > 512) {
871a3ec5
SH
369 $size = 35;
370 }
4125bdc1 371 // Hash the users email address
871a3ec5 372 $md5 = md5(strtolower(trim($this->user->email)));
4125bdc1
SH
373 // Build a gravatar URL with what we know.
374 // If the currently requested page is https then we'll return an
375 // https gravatar page.
33dca156 376 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
4125bdc1
SH
377 $imageurl = new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
378 } else {
379 $imageurl = new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
380 }
871a3ec5
SH
381 }
382
4125bdc1
SH
383 // Return the URL that has been generated.
384 return $imageurl;
5c0d03ea
DM
385 }
386}
bf11293a
PS
387
388/**
389 * Data structure representing a help icon.
390 *
391 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
9678c7b8
SH
392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
393 * @since Moodle 2.0
394 * @package core
395 * @subpackage output
bf11293a 396 */
596509e4 397class old_help_icon implements renderable {
9678c7b8 398
bf11293a 399 /**
9678c7b8
SH
400 * Lang pack identifier
401 * @var string $helpidentifier
bf11293a 402 */
53a78cef 403 public $helpidentifier;
9678c7b8 404
bf11293a 405 /**
9678c7b8
SH
406 * A descriptive text for title tooltip
407 * @var string $title
bf11293a 408 */
97c10099 409 public $title = null;
9678c7b8 410
bf11293a 411 /**
9678c7b8
SH
412 * Component name, the same as in get_string()
413 * @var string $component
bf11293a
PS
414 */
415 public $component = 'moodle';
9678c7b8 416
bf11293a 417 /**
9678c7b8
SH
418 * Extra descriptive text next to the icon
419 * @var string $linktext
bf11293a 420 */
97c10099 421 public $linktext = null;
bf11293a
PS
422
423 /**
424 * Constructor: sets up the other components in case they are needed
9678c7b8 425 *
53a78cef 426 * @param string $helpidentifier The keyword that defines a help page
1a10840e 427 * @param string $title A descriptive text for accessibility only
bf11293a
PS
428 * @param string $component
429 * @param bool $linktext add extra text to icon
bf11293a 430 */
53a78cef 431 public function __construct($helpidentifier, $title, $component = 'moodle') {
bf11293a
PS
432 if (empty($title)) {
433 throw new coding_exception('A help_icon object requires a $text parameter');
434 }
53a78cef
PS
435 if (empty($helpidentifier)) {
436 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
bf11293a
PS
437 }
438
53a78cef
PS
439 $this->helpidentifier = $helpidentifier;
440 $this->title = $title;
441 $this->component = $component;
bf11293a
PS
442 }
443}
444
49f0d481
PS
445/**
446 * Data structure representing a help icon.
447 *
448 * @copyright 2010 Petr Skoda (info@skodak.org)
9678c7b8
SH
449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450 * @since Moodle 2.0
451 * @package core
452 * @subpackage output
49f0d481
PS
453 */
454class help_icon implements renderable {
9678c7b8 455
49f0d481 456 /**
9678c7b8
SH
457 * lang pack identifier (without the "_help" suffix),
458 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
459 * must exist.
460 * @var string $identifier
49f0d481
PS
461 */
462 public $identifier;
9678c7b8 463
49f0d481 464 /**
9678c7b8
SH
465 * Component name, the same as in get_string()
466 * @var string $component
49f0d481
PS
467 */
468 public $component;
9678c7b8 469
49f0d481 470 /**
9678c7b8
SH
471 * Extra descriptive text next to the icon
472 * @var string $linktext
49f0d481
PS
473 */
474 public $linktext = null;
475
476 /**
477 * Constructor
9678c7b8
SH
478 *
479 * @param string $identifier string for help page title,
5435c9dc
MD
480 * string with _help suffix is used for the actual help text.
481 * string with _link suffix is used to create a link to further info (if it exists)
49f0d481
PS
482 * @param string $component
483 */
259c165d
PS
484 public function __construct($identifier, $component) {
485 $this->identifier = $identifier;
49f0d481
PS
486 $this->component = $component;
487 }
259c165d
PS
488
489 /**
490 * Verifies that both help strings exists, shows debug warnings if not
491 */
492 public function diag_strings() {
493 $sm = get_string_manager();
494 if (!$sm->string_exists($this->identifier, $this->component)) {
495 debugging("Help title string does not exist: [$this->identifier, $this->component]");
496 }
5435c9dc 497 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
876521ac 498 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
259c165d
PS
499 }
500 }
49f0d481
PS
501}
502
bf11293a 503
000c278c
PS
504/**
505 * Data structure representing an icon.
506 *
507 * @copyright 2010 Petr Skoda
9678c7b8
SH
508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
509 * @since Moodle 2.0
510 * @package core
511 * @subpackage output
000c278c
PS
512 */
513class pix_icon implements renderable {
9678c7b8
SH
514
515 /**
516 * The icon name
517 * @var string
518 */
000c278c 519 var $pix;
9678c7b8
SH
520
521 /**
522 * The component the icon belongs to.
523 * @var string
524 */
000c278c 525 var $component;
9678c7b8
SH
526
527 /**
528 * An array of attributes to use on the icon
529 * @var array
530 */
000c278c
PS
531 var $attributes = array();
532
533 /**
534 * Constructor
9678c7b8 535 *
000c278c 536 * @param string $pix short icon name
7749e187 537 * @param string $alt The alt text to use for the icon
000c278c
PS
538 * @param string $component component name
539 * @param array $attributes html attributes
540 */
541 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
542 $this->pix = $pix;
543 $this->component = $component;
000c278c
PS
544 $this->attributes = (array)$attributes;
545
546 $this->attributes['alt'] = $alt;
547 if (empty($this->attributes['class'])) {
548 $this->attributes['class'] = 'smallicon';
549 }
550 if (!isset($this->attributes['title'])) {
551 $this->attributes['title'] = $this->attributes['alt'];
552 }
553 }
554}
555
d63c5073
DM
556/**
557 * Data structure representing an emoticon image
558 *
9678c7b8
SH
559 * @copyright 2010 David Mudrak
560 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
561 * @since Moodle 2.0
562 * @package core
563 * @subpackage output
d63c5073
DM
564 */
565class pix_emoticon extends pix_icon implements renderable {
566
567 /**
568 * Constructor
569 * @param string $pix short icon name
b9fadae7
DM
570 * @param string $alt alternative text
571 * @param string $component emoticon image provider
572 * @param array $attributes explicit HTML attributes
d63c5073 573 */
b9fadae7
DM
574 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
575 if (empty($attributes['class'])) {
576 $attributes['class'] = 'emoticon';
577 }
d63c5073
DM
578 parent::__construct($pix, $alt, $component, $attributes);
579 }
580}
000c278c 581
3ba60ee1
PS
582/**
583 * Data structure representing a simple form with only one button.
584 *
585 * @copyright 2009 Petr Skoda
9678c7b8
SH
586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
587 * @since Moodle 2.0
588 * @package core
589 * @subpackage output
3ba60ee1
PS
590 */
591class single_button implements renderable {
9678c7b8 592
574fbea4
PS
593 /**
594 * Target url
595 * @var moodle_url
596 */
3ba60ee1 597 var $url;
9678c7b8 598
574fbea4
PS
599 /**
600 * Button label
601 * @var string
602 */
3ba60ee1 603 var $label;
9678c7b8 604
574fbea4
PS
605 /**
606 * Form submit method
607 * @var string post or get
608 */
3ba60ee1 609 var $method = 'post';
9678c7b8 610
574fbea4
PS
611 /**
612 * Wrapping div class
613 * @var string
9678c7b8 614 */
3ba60ee1 615 var $class = 'singlebutton';
9678c7b8 616
574fbea4
PS
617 /**
618 * True if button disabled, false if normal
619 * @var boolean
620 */
3ba60ee1 621 var $disabled = false;
9678c7b8 622
574fbea4
PS
623 /**
624 * Button tooltip
625 * @var string
626 */
97c10099 627 var $tooltip = null;
9678c7b8 628
574fbea4
PS
629 /**
630 * Form id
631 * @var string
632 */
3ba60ee1 633 var $formid;
9678c7b8 634
574fbea4
PS
635 /**
636 * List of attached actions
637 * @var array of component_action
638 */
3ba60ee1
PS
639 var $actions = array();
640
641 /**
642 * Constructor
9678c7b8 643 * @param moodle_url $url
3ba60ee1
PS
644 * @param string $label button text
645 * @param string $method get or post submit method
3ba60ee1
PS
646 */
647 public function __construct(moodle_url $url, $label, $method='post') {
648 $this->url = clone($url);
649 $this->label = $label;
650 $this->method = $method;
651 }
652
653 /**
574fbea4 654 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1 655 * The message must be a yes/no question.
9678c7b8 656 *
3ba60ee1 657 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
3ba60ee1
PS
658 */
659 public function add_confirm_action($confirmmessage) {
8f78cd5a 660 $this->add_action(new confirm_action($confirmmessage));
3ba60ee1
PS
661 }
662
574fbea4
PS
663 /**
664 * Add action to the button.
665 * @param component_action $action
574fbea4 666 */
3ba60ee1
PS
667 public function add_action(component_action $action) {
668 $this->actions[] = $action;
669 }
670}
671
672
a9967cf5
PS
673/**
674 * Simple form with just one select field that gets submitted automatically.
675 * If JS not enabled small go button is printed too.
676 *
677 * @copyright 2009 Petr Skoda
9678c7b8
SH
678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
679 * @since Moodle 2.0
680 * @package core
681 * @subpackage output
a9967cf5
PS
682 */
683class single_select implements renderable {
9678c7b8 684
a9967cf5
PS
685 /**
686 * Target url - includes hidden fields
687 * @var moodle_url
688 */
689 var $url;
9678c7b8 690
a9967cf5
PS
691 /**
692 * Name of the select element.
693 * @var string
694 */
695 var $name;
9678c7b8 696
a9967cf5 697 /**
9678c7b8
SH
698 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
699 * it is also possible to specify optgroup as complex label array ex.:
700 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
701 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
a9967cf5
PS
702 */
703 var $options;
9678c7b8 704
a9967cf5
PS
705 /**
706 * Selected option
707 * @var string
708 */
709 var $selected;
9678c7b8 710
a9967cf5
PS
711 /**
712 * Nothing selected
713 * @var array
714 */
715 var $nothing;
9678c7b8 716
a9967cf5
PS
717 /**
718 * Extra select field attributes
719 * @var array
720 */
721 var $attributes = array();
9678c7b8 722
a9967cf5
PS
723 /**
724 * Button label
725 * @var string
726 */
727 var $label = '';
9678c7b8 728
a9967cf5
PS
729 /**
730 * Form submit method
731 * @var string post or get
732 */
733 var $method = 'get';
9678c7b8 734
a9967cf5
PS
735 /**
736 * Wrapping div class
737 * @var string
738 * */
739 var $class = 'singleselect';
9678c7b8 740
a9967cf5
PS
741 /**
742 * True if button disabled, false if normal
743 * @var boolean
744 */
745 var $disabled = false;
9678c7b8 746
a9967cf5
PS
747 /**
748 * Button tooltip
749 * @var string
750 */
751 var $tooltip = null;
9678c7b8 752
a9967cf5
PS
753 /**
754 * Form id
755 * @var string
756 */
757 var $formid = null;
9678c7b8 758
a9967cf5
PS
759 /**
760 * List of attached actions
761 * @var array of component_action
762 */
763 var $helpicon = null;
9678c7b8 764
a9967cf5
PS
765 /**
766 * Constructor
767 * @param moodle_url $url form action target, includes hidden fields
768 * @param string $name name of selection field - the changing parameter in url
769 * @param array $options list of options
770 * @param string $selected selected element
771 * @param array $nothing
f8dab966 772 * @param string $formid
a9967cf5 773 */
9678c7b8 774 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
a9967cf5
PS
775 $this->url = $url;
776 $this->name = $name;
777 $this->options = $options;
778 $this->selected = $selected;
779 $this->nothing = $nothing;
f8dab966 780 $this->formid = $formid;
a9967cf5
PS
781 }
782
783 /**
784 * Shortcut for adding a JS confirm dialog when the button is clicked.
785 * The message must be a yes/no question.
9678c7b8 786 *
a9967cf5 787 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
a9967cf5
PS
788 */
789 public function add_confirm_action($confirmmessage) {
790 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
791 }
792
793 /**
794 * Add action to the button.
9678c7b8 795 *
a9967cf5 796 * @param component_action $action
a9967cf5
PS
797 */
798 public function add_action(component_action $action) {
799 $this->actions[] = $action;
800 }
f8dab966
PS
801
802 /**
259c165d 803 * Adds help icon.
9678c7b8 804 *
f8dab966 805 * @param string $page The keyword that defines a help page
1a10840e 806 * @param string $title A descriptive text for accessibility only
f8dab966
PS
807 * @param string $component
808 * @param bool $linktext add extra text to icon
f8dab966 809 */
596509e4
PS
810 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
811 $this->helpicon = new old_help_icon($helppage, $title, $component);
f8dab966
PS
812 }
813
259c165d
PS
814 /**
815 * Adds help icon.
9678c7b8 816 *
259c165d
PS
817 * @param string $identifier The keyword that defines a help page
818 * @param string $component
259c165d
PS
819 */
820 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 821 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
822 }
823
f8dab966 824 /**
995f2d51 825 * Sets select's label
9678c7b8 826 *
f8dab966 827 * @param string $label
f8dab966
PS
828 */
829 public function set_label($label) {
830 $this->label = $label;
831 }
a9967cf5
PS
832}
833
4d10e579
PS
834/**
835 * Simple URL selection widget description.
9678c7b8 836 *
4d10e579 837 * @copyright 2009 Petr Skoda
9678c7b8
SH
838 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
839 * @since Moodle 2.0
840 * @package core
841 * @subpackage output
4d10e579
PS
842 */
843class url_select implements renderable {
844 /**
9678c7b8
SH
845 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
846 * it is also possible to specify optgroup as complex label array ex.:
847 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
848 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
4d10e579
PS
849 */
850 var $urls;
9678c7b8 851
4d10e579
PS
852 /**
853 * Selected option
854 * @var string
855 */
856 var $selected;
9678c7b8 857
4d10e579
PS
858 /**
859 * Nothing selected
860 * @var array
861 */
862 var $nothing;
9678c7b8 863
4d10e579
PS
864 /**
865 * Extra select field attributes
866 * @var array
867 */
868 var $attributes = array();
9678c7b8 869
4d10e579
PS
870 /**
871 * Button label
872 * @var string
873 */
874 var $label = '';
9678c7b8 875
4d10e579
PS
876 /**
877 * Wrapping div class
878 * @var string
879 * */
880 var $class = 'urlselect';
9678c7b8 881
4d10e579
PS
882 /**
883 * True if button disabled, false if normal
884 * @var boolean
885 */
886 var $disabled = false;
9678c7b8 887
4d10e579
PS
888 /**
889 * Button tooltip
890 * @var string
891 */
892 var $tooltip = null;
9678c7b8 893
4d10e579
PS
894 /**
895 * Form id
896 * @var string
897 */
898 var $formid = null;
9678c7b8 899
4d10e579
PS
900 /**
901 * List of attached actions
902 * @var array of component_action
903 */
904 var $helpicon = null;
9678c7b8 905
15e48a1a
SM
906 /**
907 * @var string If set, makes button visible with given name for button
908 */
909 var $showbutton = null;
9678c7b8 910
4d10e579
PS
911 /**
912 * Constructor
913 * @param array $urls list of options
914 * @param string $selected selected element
915 * @param array $nothing
916 * @param string $formid
15e48a1a
SM
917 * @param string $showbutton Set to text of button if it should be visible
918 * or null if it should be hidden (hidden version always has text 'go')
919 */
9678c7b8 920 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
15e48a1a
SM
921 $this->urls = $urls;
922 $this->selected = $selected;
923 $this->nothing = $nothing;
924 $this->formid = $formid;
925 $this->showbutton = $showbutton;
4d10e579
PS
926 }
927
928 /**
259c165d 929 * Adds help icon.
9678c7b8 930 *
4d10e579 931 * @param string $page The keyword that defines a help page
1a10840e 932 * @param string $title A descriptive text for accessibility only
4d10e579 933 * @param string $component
4d10e579 934 */
596509e4
PS
935 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
936 $this->helpicon = new old_help_icon($helppage, $title, $component);
4d10e579
PS
937 }
938
259c165d
PS
939 /**
940 * Adds help icon.
9678c7b8 941 *
259c165d
PS
942 * @param string $identifier The keyword that defines a help page
943 * @param string $component
259c165d
PS
944 */
945 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 946 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
947 }
948
4d10e579 949 /**
995f2d51 950 * Sets select's label
9678c7b8 951 *
4d10e579 952 * @param string $label
4d10e579
PS
953 */
954 public function set_label($label) {
955 $this->label = $label;
956 }
957}
958
574fbea4
PS
959/**
960 * Data structure describing html link with special action attached.
9678c7b8 961 *
574fbea4 962 * @copyright 2010 Petr Skoda
9678c7b8
SH
963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
964 * @since Moodle 2.0
965 * @package core
966 * @subpackage output
574fbea4
PS
967 */
968class action_link implements renderable {
9678c7b8 969
574fbea4
PS
970 /**
971 * Href url
972 * @var moodle_url
973 */
974 var $url;
9678c7b8 975
574fbea4
PS
976 /**
977 * Link text
978 * @var string HTML fragment
979 */
980 var $text;
9678c7b8 981
574fbea4
PS
982 /**
983 * HTML attributes
984 * @var array
985 */
986 var $attributes;
9678c7b8 987
574fbea4
PS
988 /**
989 * List of actions attached to link
990 * @var array of component_action
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
1038 * @package core
1039 * @subpackage 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
1147 * @param type $base
1148 * @return type
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 *
0f4c64b7
PS
1165 * @param string|moodle_url $url
1166 * @param string $text link txt
1167 * @param array $attributes extra html attributes
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 *
14dce022
PS
1179 * @param string $name
1180 * @param string $value
1181 * @param bool $checked
1182 * @param string $label
1183 * @param array $attributes
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
3ff163c5
PS
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 }
1272 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
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 *
1444 * @param string $js the JavaScript code
9678c7b8 1445 * @param moodle_url|string 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
e126c0cc 1612 foreach ($row as $item) {
16be8974
DM
1613 $cell = new html_table_cell();
1614 $cell->text = $item;
1615 $newrow->cells[] = $cell;
1616 }
1617 $row = $newrow;
1618 }
1619
1620 $oddeven = $oddeven ? 0 : 1;
1621 if (isset($table->rowclasses[$key])) {
1622 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1623 }
1624
1625 $row->attributes['class'] .= ' r' . $oddeven;
1626 if ($key == $lastrowkey) {
1627 $row->attributes['class'] .= ' lastrow';
1628 }
1629
e126c0cc 1630 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
16be8974
DM
1631 $keys2 = array_keys($row->cells);
1632 $lastkey = end($keys2);
1633
5174f3c5 1634 $gotlastkey = false; //flag for sanity checking
16be8974 1635 foreach ($row->cells as $key => $cell) {
5174f3c5
AD
1636 if ($gotlastkey) {
1637 //This should never happen. Why do we have a cell after the last cell?
1638 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1639 }
1640
16be8974
DM
1641 if (!($cell instanceof html_table_cell)) {
1642 $mycell = new html_table_cell();
1643 $mycell->text = $cell;
1644 $cell = $mycell;
1645 }
1646
e126c0cc
DM
1647 if (($cell->header === true) && empty($cell->scope)) {
1648 $cell->scope = 'row';
1649 }
1650
16be8974
DM
1651 if (isset($table->colclasses[$key])) {
1652 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1653 }
1654
1655 $cell->attributes['class'] .= ' cell c' . $key;
1656 if ($key == $lastkey) {
1657 $cell->attributes['class'] .= ' lastcol';
5174f3c5 1658 $gotlastkey = true;
16be8974
DM
1659 }
1660 $tdstyle = '';
1661 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1662 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1663 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1664 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1665 $tdattributes = array_merge($cell->attributes, array(
1666 'style' => $tdstyle . $cell->style,
1667 'colspan' => $cell->colspan,
1668 'rowspan' => $cell->rowspan,
1669 'id' => $cell->id,
1670 'abbr' => $cell->abbr,
1671 'scope' => $cell->scope,
1672 ));
1673 $tagtype = 'td';
1674 if ($cell->header === true) {
1675 $tagtype = 'th';
1676 }
1677 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1678 }
1679 }
1680 $output .= html_writer::end_tag('tr') . "\n";
1681 }
1682 $output .= html_writer::end_tag('tbody') . "\n";
1683 }
1684 $output .= html_writer::end_tag('table') . "\n";
1685
1686 return $output;
1687 }
1688
995f2d51
DM
1689 /**
1690 * Renders form element label
1691 *
1692 * By default, the label is suffixed with a label separator defined in the
1693 * current language pack (colon by default in the English lang pack).
1694 * Adding the colon can be explicitly disabled if needed. Label separators
1695 * are put outside the label tag itself so they are not read by
1696 * screenreaders (accessibility).
1697 *
1698 * Parameter $for explicitly associates the label with a form control. When
1699 * set, the value of this attribute must be the same as the value of
1700 * the id attribute of the form control in the same document. When null,
1701 * the label being defined is associated with the control inside the label
1702 * element.
1703 *
1704 * @param string $text content of the label tag
1705 * @param string|null $for id of the element this label is associated with, null for no association
1706 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1707 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1708 * @return string HTML of the label element
1709 */
9678c7b8 1710 public static function label($text, $for, $colonize = true, array $attributes=array()) {
995f2d51
DM
1711 if (!is_null($for)) {
1712 $attributes = array_merge($attributes, array('for' => $for));
1713 }
1714 $text = trim($text);
1715 $label = self::tag('label', $text, $attributes);
1716
9678c7b8
SH
1717 // TODO MDL-12192 $colonize disabled for now yet
1718 // if (!empty($text) and $colonize) {
1719 // // the $text may end with the colon already, though it is bad string definition style
1720 // $colon = get_string('labelsep', 'langconfig');
1721 // if (!empty($colon)) {
1722 // $trimmed = trim($colon);
1723 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1724 // //debugging('The label text should not end with colon or other label separator,
1725 // // please fix the string definition.', DEBUG_DEVELOPER);
1726 // } else {
1727 // $label .= $colon;
1728 // }
1729 // }
1730 // }
995f2d51
DM
1731
1732 return $label;
1733 }
5d0c95a5
PS
1734}
1735
227255b8
PS
1736/**
1737 * Simple javascript output class
9678c7b8 1738 *
227255b8 1739 * @copyright 2010 Petr Skoda
9678c7b8
SH
1740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1741 * @since Moodle 2.0
1742 * @package core
1743 * @subpackage output
227255b8
PS
1744 */
1745class js_writer {
9678c7b8 1746
227255b8
PS
1747 /**
1748 * Returns javascript code calling the function
9678c7b8 1749 *
1a10840e 1750 * @param string $function function name, can be complex like Y.Event.purgeElement
227255b8
PS
1751 * @param array $arguments parameters
1752 * @param int $delay execution delay in seconds
1753 * @return string JS code fragment
1754 */
e839dce1 1755 public static function function_call($function, array $arguments = null, $delay=0) {
1b4e41af
PS
1756 if ($arguments) {
1757 $arguments = array_map('json_encode', $arguments);
1758 $arguments = implode(', ', $arguments);
1759 } else {
1760 $arguments = '';
1761 }
227255b8
PS
1762 $js = "$function($arguments);";
1763
1764 if ($delay) {
1765 $delay = $delay * 1000; // in miliseconds
1766 $js = "setTimeout(function() { $js }, $delay);";
1767 }
1768 return $js . "\n";
1769 }
1770
3b01539c
PS
1771 /**
1772 * Special function which adds Y as first argument of fucntion call.
9678c7b8 1773 *
3b01539c
PS
1774 * @param string $function
1775 * @param array $extraarguments
1776 * @return string
1777 */
e839dce1 1778 public static function function_call_with_Y($function, array $extraarguments = null) {
3b01539c
PS
1779 if ($extraarguments) {
1780 $extraarguments = array_map('json_encode', $extraarguments);
1781 $arguments = 'Y, ' . implode(', ', $extraarguments);
1782 } else {
1783 $arguments = 'Y';
1784 }
1785 return "$function($arguments);\n";
1786 }
1787
1ce15fda
SH
1788 /**
1789 * Returns JavaScript code to initialise a new object
9678c7b8
SH
1790 *
1791 * @param string $var If it is null then no var is assigned the new object
1ce15fda
SH
1792 * @param string $class
1793 * @param array $arguments
1794 * @param array $requirements
1795 * @param int $delay
1796 * @return string
1797 */
e839dce1 1798 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1ce15fda
SH
1799 if (is_array($arguments)) {
1800 $arguments = array_map('json_encode', $arguments);
1801 $arguments = implode(', ', $arguments);
1802 }
1803
1804 if ($var === null) {
53fc3e70 1805 $js = "new $class(Y, $arguments);";
1ce15fda 1806 } else if (strpos($var, '.')!==false) {
53fc3e70 1807 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1808 } else {
53fc3e70 1809 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1810 }
1811
1812 if ($delay) {
1813 $delay = $delay * 1000; // in miliseconds
1814 $js = "setTimeout(function() { $js }, $delay);";
1815 }
1816
1817 if (count($requirements) > 0) {
1818 $requirements = implode("', '", $requirements);
53fc3e70 1819 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1820 }
1821 return $js."\n";
1822 }
1823
227255b8
PS
1824 /**
1825 * Returns code setting value to variable
9678c7b8 1826 *
227255b8
PS
1827 * @param string $name
1828 * @param mixed $value json serialised value
1829 * @param bool $usevar add var definition, ignored for nested properties
1830 * @return string JS code fragment
1831 */
9678c7b8 1832 public static function set_variable($name, $value, $usevar = true) {
227255b8
PS
1833 $output = '';
1834
1835 if ($usevar) {
1836 if (strpos($name, '.')) {
1837 $output .= '';
1838 } else {
1839 $output .= 'var ';
1840 }
1841 }
1842
1843 $output .= "$name = ".json_encode($value).";";
1844
1845 return $output;
1846 }
1847
1848 /**
1849 * Writes event handler attaching code
9678c7b8
SH
1850 *
1851 * @param array|string $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
227255b8
PS
1852 * @param string $event A valid DOM event (click, mousedown, change etc.)
1853 * @param string $function The name of the function to call
9678c7b8 1854 * @param array $arguments An optional array of argument parameters to pass to the function
227255b8
PS
1855 * @return string JS code fragment
1856 */
e839dce1 1857 public static function event_handler($selector, $event, $function, array $arguments = null) {
227255b8
PS
1858 $selector = json_encode($selector);
1859 $output = "Y.on('$event', $function, $selector, null";
1860 if (!empty($arguments)) {
1861 $output .= ', ' . json_encode($arguments);
1862 }
1863 return $output . ");\n";
1864 }
1865}
1866
d9c8f425 1867/**
16be8974 1868 * Holds all the information required to render a <table> by {@see core_renderer::table()}
d9c8f425 1869 *
16be8974
DM
1870 * Example of usage:
1871 * $t = new html_table();
1872 * ... // set various properties of the object $t as described below
1873 * echo html_writer::table($t);
d9c8f425 1874 *
16be8974 1875 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
9678c7b8
SH
1876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1877 * @since Moodle 2.0
1878 * @package core
1879 * @subpackage output
d9c8f425 1880 */
16be8974 1881class html_table {
9678c7b8 1882
d9c8f425 1883 /**
9678c7b8
SH
1884 * Value to use for the id attribute of the table
1885 * @var string
d9c8f425 1886 */
97c10099 1887 public $id = null;
9678c7b8 1888
d9c8f425 1889 /**
9678c7b8
SH
1890 * Attributes of HTML attributes for the <table> element
1891 * @var array
d9c8f425 1892 */
16be8974 1893 public $attributes = array();
9678c7b8 1894
7b1f2c82 1895 /**
9678c7b8 1896 * 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');
9678c7b8
SH
1902 *
1903 * @var array
7b1f2c82 1904 */
1905 public $head;
9678c7b8 1906
7b1f2c82 1907 /**
9678c7b8
SH
1908 * An array that can be used to make a heading span multiple columns.
1909 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1910 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
7b1f2c82 1911 *
1912 * Example of usage:
1913 * $t->headspan = array(2,1);
1914 *
9678c7b8 1915 * @var array
7b1f2c82 1916 */
1917 public $headspan;
9678c7b8 1918
7b1f2c82 1919 /**
9678c7b8
SH
1920 * An array of column alignments.
1921 * The value is used as CSS 'text-align' property. Therefore, possible
7b1f2c82 1922 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1923 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1924 *
beb56299 1925 * Examples of usage:
1926 * $t->align = array(null, 'right');
1927 * or
1928 * $t->align[1] = 'right';
1929 *
9678c7b8 1930 * @var array
d9c8f425 1931 */
beb56299 1932 public $align;
9678c7b8 1933
d9c8f425 1934 /**
9678c7b8 1935 * The value is used as CSS 'size' property.
beb56299 1936 *
1937 * Examples of usage:
1938 * $t->size = array('50%', '50%');
1939 * or
1940 * $t->size[1] = '120px';
9678c7b8
SH
1941 *
1942 * @var array of column sizes.
d9c8f425 1943 */
beb56299 1944 public $size;
9678c7b8 1945
d9c8f425 1946 /**
9678c7b8
SH
1947 * An array of wrapping information.
1948 * The only possible value is 'nowrap' that sets the
beb56299 1949 * CSS property 'white-space' to the value 'nowrap' in the given column.
1950 *
1951 * Example of usage:
1952 * $t->wrap = array(null, 'nowrap');
9678c7b8
SH
1953 *
1954 * @var array
d9c8f425 1955 */
beb56299 1956 public $wrap;
9678c7b8 1957
d9c8f425 1958 /**
9678c7b8 1959 * Array of arrays or html_table_row objects containing the data. Alternatively, if you have
beb56299 1960 * $head specified, the string 'hr' (for horizontal ruler) can be used
1961 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1962 *
beb56299 1963 * Example of usage with array of arrays:
1964 * $row1 = array('Harry Potter', '76 %');
1965 * $row2 = array('Hermione Granger', '100 %');
1966 * $t->data = array($row1, $row2);
d9c8f425 1967 *
beb56299 1968 * Example with array of html_table_row objects: (used for more fine-grained control)
1969 * $cell1 = new html_table_cell();
1970 * $cell1->text = 'Harry Potter';
1971 * $cell1->colspan = 2;
1972 * $row1 = new html_table_row();
1973 * $row1->cells[] = $cell1;
1974 * $cell2 = new html_table_cell();
1975 * $cell2->text = 'Hermione Granger';
1976 * $cell3 = new html_table_cell();
1977 * $cell3->text = '100 %';
1978 * $row2 = new html_table_row();
1979 * $row2->cells = array($cell2, $cell3);
1980 * $t->data = array($row1, $row2);
9678c7b8
SH
1981 *
1982 * @var array
beb56299 1983 */
1984 public $data;
9678c7b8 1985
beb56299 1986 /**
9678c7b8 1987 * Width of the table, percentage of the page preferred.
beb56299 1988 * @deprecated since Moodle 2.0. Styling should be in the CSS.
9678c7b8 1989 * @var string
beb56299 1990 */
1991 public $width = null;
9678c7b8 1992
beb56299 1993 /**
9678c7b8 1994 * Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
beb56299 1995 * @deprecated since Moodle 2.0. Styling should be in the CSS.
9678c7b8 1996 * @var string
beb56299 1997 */
1998 public $tablealign = null;
9678c7b8 1999
beb56299 2000 /**
9678c7b8 2001 * Padding on each cell, in pixels
beb56299 2002 * @deprecated since Moodle 2.0. Styling should be in the CSS.
9678c7b8 2003 * @var int
beb56299 2004 */
2005 public $cellpadding = null;
9678c7b8 2006
beb56299 2007 /**
9678c7b8 2008 * Spacing between cells, in pixels
beb56299 2009 * @deprecated since Moodle 2.0. Styling should be in the CSS.
9678c7b8 2010 * @var int
beb56299 2011 */
2012 public $cellspacing = null;
9678c7b8 2013
beb56299 2014 /**
9678c7b8 2015 * Array of classes to add to particular rows, space-separated string.
beb56299 2016 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2017 * respectively. Class 'lastrow' is added automatically for the last row
2018 * in the table.
d9c8f425 2019 *
beb56299 2020 * Example of usage:
2021 * $t->rowclasses[9] = 'tenth'
9678c7b8
SH
2022 *
2023 * @var array
beb56299 2024 */
2025 public $rowclasses;
9678c7b8 2026
beb56299 2027 /**
9678c7b8 2028 * An array of classes to add to every cell in a particular column,
beb56299 2029 * space-separated string. Class 'cell' is added automatically by the renderer.
2030 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2031 * respectively. Class 'lastcol' is added automatically for all last cells
2032 * in a row.
d9c8f425 2033 *
beb56299 2034 * Example of usage:
2035 * $t->colclasses = array(null, 'grade');
9678c7b8
SH
2036 *
2037 * @var array
d9c8f425 2038 */
beb56299 2039 public $colclasses;
9678c7b8 2040
beb56299 2041 /**
9678c7b8
SH
2042 * Description of the contents for screen readers.
2043 * @var string
beb56299 2044 */
2045 public $summary;
d9c8f425 2046
2047 /**
16be8974 2048 * Constructor
d9c8f425 2049 */
16be8974
DM
2050 public function __construct() {
2051 $this->attributes['class'] = '';
d9c8f425 2052 }
d9c8f425 2053}
2054
2055/**
7b1f2c82 2056 * Component representing a table row.
d9c8f425 2057 *
2058 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2059 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2060 * @since Moodle 2.0
2061 * @package core
2062 * @subpackage output
d9c8f425 2063 */
16be8974 2064class html_table_row {
9678c7b8 2065
16be8974 2066 /**
9678c7b8
SH
2067 * Value to use for the id attribute of the row.
2068 * @var string
16be8974
DM
2069 */
2070 public $id = null;
9678c7b8 2071
d9c8f425 2072 /**
9678c7b8
SH
2073 * Array of html_table_cell objects
2074 * @var array
d9c8f425 2075 */
7b1f2c82 2076 public $cells = array();
9678c7b8 2077
beb56299 2078 /**
9678c7b8
SH
2079 * Value to use for the style attribute of the table row
2080 * @var string
beb56299 2081 */
16be8974 2082 public $style = null;
9678c7b8 2083
16be8974 2084 /**
9678c7b8
SH
2085 * Attributes of additional HTML attributes for the <tr> element
2086 * @var array
16be8974
DM
2087 */
2088 public $attributes = array();
a0ead5eb 2089
54a007e8 2090 /**
8cea545e 2091 * Constructor
54a007e8 2092 * @param array $cells
8cea545e
PS
2093 */
2094 public function __construct(array $cells=null) {
16be8974 2095 $this->attributes['class'] = '';
8cea545e
PS
2096 $cells = (array)$cells;
2097 foreach ($cells as $cell) {
2098 if ($cell instanceof html_table_cell) {
2099 $this->cells[] = $cell;
a019627a 2100 } else {
8cea545e 2101 $this->cells[] = new html_table_cell($cell);
a019627a 2102 }
2103 }
54a007e8 2104 }
d9c8f425 2105}
2106
2107/**
7b1f2c82 2108 * Component representing a table cell.
d9c8f425 2109 *
2110 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2112 * @since Moodle 2.0
2113 * @package core
2114 * @subpackage output
d9c8f425 2115 */
16be8974 2116class html_table_cell {
9678c7b8 2117
16be8974 2118 /**
9678c7b8
SH
2119 * Value to use for the id attribute of the cell.
2120 * @var string
16be8974
DM
2121 */
2122 public $id = null;
9678c7b8 2123
d9c8f425 2124 /**
9678c7b8
SH
2125 * The contents of the cell.
2126 * @var string
d9c8f425 2127 */
7b1f2c82 2128 public $text;
9678c7b8 2129
d9c8f425 2130 /**
9678c7b8
SH
2131 * Abbreviated version of the contents of the cell.
2132 * @var string
d9c8f425 2133 */
97c10099 2134 public $abbr = null;
9678c7b8 2135
d9c8f425 2136 /**
9678c7b8
SH
2137 * Number of columns this cell should span.
2138 * @var int
d9c8f425 2139 */
97c10099 2140 public $colspan = null;
9678c7b8 2141
d9c8f425 2142 /**
9678c7b8
SH
2143 * Number of rows this cell should span.
2144 * @var int
d9c8f425 2145 */
97c10099 2146 public $rowspan = null;
9678c7b8 2147
d9c8f425 2148 /**
9678c7b8
SH
2149 * Defines a way to associate header cells and data cells in a table.
2150 * @var string
d9c8f425 2151 */
97c10099 2152 public $scope = null;
9678c7b8 2153
1ae3767a 2154 /**
9678c7b8
SH
2155 * Whether or not this cell is a header cell.
2156 * @var boolean
1ae3767a 2157 */
a4998d01 2158 public $header = null;
9678c7b8 2159
16be8974 2160 /**
9678c7b8
SH
2161 * Value to use for the style attribute of the table cell
2162 * @var string
16be8974
DM
2163 */
2164 public $style = null;
9678c7b8 2165
16be8974 2166 /**
9678c7b8
SH
2167 * Attributes of additional HTML attributes for the <td> element
2168 * @var array
16be8974
DM
2169 */
2170 public $attributes = array();
d9c8f425 2171
9678c7b8
SH
2172 /**
2173 * Constructs a table cell
2174 *
2175 * @param string $text
2176 */
8cea545e
PS
2177 public function __construct($text = null) {
2178 $this->text = $text;
16be8974 2179 $this->attributes['class'] = '';
d9c8f425 2180 }
2181}
2182
d9c8f425 2183/**
beb56299 2184 * Component representing a paging bar.
d9c8f425 2185 *
2186 * @copyright 2009 Nicolas Connault
9678c7b8
SH
2187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2188 * @since Moodle 2.0
2189 * @package core
2190 * @subpackage output
d9c8f425 2191 */
929d7a83 2192class paging_bar implements renderable {
9678c7b8 2193
d9c8f425 2194 /**
9678c7b8
SH
2195 * The maximum number of pagelinks to display.
2196 * @var int
d9c8f425 2197 */
beb56299 2198 public $maxdisplay = 18;
9678c7b8 2199
d9c8f425 2200 /**
9678c7b8
SH
2201 * The total number of entries to be pages through..
2202 * @var int
d9c8f425 2203 */
beb56299 2204 public $totalcount;
9678c7b8 2205
d9c8f425 2206 /**
9678c7b8
SH
2207 * The page you are currently viewing.
2208 * @var int
d9c8f425 2209 */
929d7a83 2210 public $page;
9678c7b8 2211
d9c8f425 2212 /**
9678c7b8
SH
2213 * The number of entries that should be shown per page.
2214 * @var int
d9c8f425 2215 */
beb56299 2216 public $perpage;
9678c7b8 2217
d9c8f425 2218 /**
9678c7b8
SH
2219 * If this is a string then it is the url which will be appended with $pagevar,
2220 * an equals sign and the page number.
2221 * If this is a moodle_url object then the pagevar param will be replaced by
2222 * the page no, for each page.
2223 * @var string|moodle_url
d9c8f425 2224 */
beb56299 2225 public $baseurl;
9678c7b8 2226
d9c8f425 2227 /**
9678c7b8
SH
2228 * This is the variable name that you use for the pagenumber in your
2229 * code (ie. 'tablepage', 'blogpage', etc)
2230 * @var string
d9c8f425 2231 */
929d7a83 2232 public $pagevar;
9678c7b8 2233
beb56299 2234 /**
9678c7b8
SH
2235 * A HTML link representing the "previous" page.
2236 * @var string
beb56299 2237 */
2238 public $previouslink = null;
9678c7b8 2239
beb56299 2240 /**
9678c7b8
SH
2241 * A HTML link representing the "next" page.
2242 * @var string
beb56299 2243 */
2244 public $nextlink = null;
9678c7b8 2245
beb56299 2246 /**
9678c7b8
SH
2247 * A HTML link representing the first page.
2248 * @var string
beb56299 2249 */
2250 public $firstlink = null;
9678c7b8 2251
beb56299 2252 /**
9678c7b8
SH
2253 * A HTML link representing the last page.
2254 * @var string
beb56299 2255 */
2256 public $lastlink = null;
9678c7b8 2257
beb56299 2258 /**
9678c7b8
SH
2259 * An array of strings. One of them is just a string: the current page
2260 * @var array
beb56299 2261 */
2262 public $pagelinks = array();
d9c8f425 2263
929d7a83
PS
2264 /**
2265 * Constructor paging_bar with only the required params.
2266 *
1a10840e 2267 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2268 * @param int $page The page you are currently viewing
2269 * @param int $perpage The number of entries that should be shown per page
2270 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2271 * @param string $pagevar name of page parameter that holds the page number
2272 */
2273 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2274 $this->totalcount = $totalcount;
2275 $this->page = $page;
2276 $this->perpage = $perpage;
2277 $this->baseurl = $baseurl;
2278 $this->pagevar = $pagevar;
2279 }
2280
d9c8f425 2281 /**
9678c7b8
SH
2282 * Prepares the paging bar for output.
2283 *
2284 * This method validates the arguments set up for the paging bar and then
2285 * produces fragments of HTML to assist display later on.
d9c8f425 2286 */
34059565 2287 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 2288 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 2289 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 2290 }
2291 if (!isset($this->page) || is_null($this->page)) {
929d7a83 2292 throw new coding_exception('paging_bar requires a page value.');
beb56299 2293 }
2294 if (empty($this->perpage)) {
929d7a83 2295 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 2296 }
2297 if (empty($this->baseurl)) {
929d7a83 2298 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 2299 }
d9c8f425 2300
beb56299 2301 if ($this->totalcount > $this->perpage) {
2302 $pagenum = $this->page - 1;
d9c8f425 2303
beb56299 2304 if ($this->page > 0) {
929d7a83 2305 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 2306 }
d9c8f425 2307
beb56299 2308 if ($this->perpage > 0) {
2309 $lastpage = ceil($this->totalcount / $this->perpage);
2310 } else {
2311 $lastpage = 1;
2312 }
2313
2314 if ($this->page > 15) {
2315 $startpage = $this->page - 10;
2316
929d7a83 2317 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 2318 } else {
2319 $startpage = 0;
2320 }
2321
2322 $currpage = $startpage;
2323 $displaycount = $displaypage = 0;
2324
2325 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2326 $displaypage = $currpage + 1;
2327
f43cdceb 2328 if ($this->page == $currpage) {
beb56299 2329 $this->pagelinks[] = $displaypage;
2330 } else {
56ddb719 2331 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 2332 $this->pagelinks[] = $pagelink;
2333 }
2334
2335 $displaycount++;
2336 $currpage++;
2337 }
2338
2339 if ($currpage < $lastpage) {
2340 $lastpageactual = $lastpage - 1;
abdac127 2341 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 2342 }
2343
2344 $pagenum = $this->page + 1;
2345
2346 if ($pagenum != $displaypage) {
abdac127 2347 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 2348 }
d9c8f425 2349 }
2350 }
d9c8f425 2351}
2352
d9c8f425 2353/**
beb56299 2354 * This class represents how a block appears on a page.
d9c8f425 2355 *
beb56299 2356 * During output, each block instance is asked to return a block_contents object,
2357 * those are then passed to the $OUTPUT->block function for display.
2358 *
2359 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2360 *
2361 * Other block-like things that need to appear on the page, for example the
2362 * add new block UI, are also represented as block_contents objects.
2363 *
2364 * @copyright 2009 Tim Hunt
9678c7b8
SH
2365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2366 * @since Moodle 2.0
2367 * @package core
2368 * @subpackage output
d9c8f425 2369 */
dd72b308 2370class block_contents {
beb56299 2371
9678c7b8
SH
2372 /**#@+
2373 * These are the collapsible states that a blocks content can be in.
2374 * Default self::NOT_HIDEABLE
2375 */
beb56299 2376 const NOT_HIDEABLE = 0;
2377 const VISIBLE = 1;
2378 const HIDDEN = 2;
9678c7b8 2379 /**#@-*/
beb56299 2380
d9c8f425 2381 /**
9678c7b8
SH
2382 * Used to set $skipid.
2383 * @var int
2384 */
2385 protected static $idcounter = 1;
2386
2387 /**
2388 * All the blocks (or things that look like blocks) printed on a page are
2389 * given a unique number that can be used to construct id="" attributes.
2390 * This is set automatically be the {@link prepare()} method.
beb56299 2391 * Do not try to set it manually.
9678c7b8 2392 * @var integer
d9c8f425 2393 */
beb56299 2394 public $skipid;
d9c8f425 2395
2396 /**
9678c7b8 2397 * If this is the contents of a real block, this should be set to
beb56299 2398 * the block_instance.id. Otherwise this should be set to 0.
9678c7b8 2399 * @var integer
beb56299 2400 */
2401 public $blockinstanceid = 0;
2402
2403 /**
9678c7b8 2404 * If this is a real block instance, and there is a corresponding
beb56299 2405 * block_position.id for the block on this page, this should be set to that id.
2406 * Otherwise it should be 0.
9678c7b8 2407 * @var integer
beb56299 2408 */
2409 public $blockpositionid = 0;
2410
2411 /**
9678c7b8
SH
2412 * An array of attribute => value pairs that are put on the outer div of this
2413 * block. {@link $id} and {@link $classes} attributes should be set separately.
2414 * @var array
beb56299 2415 */
dd72b308 2416 public $attributes;
beb56299 2417
2418 /**
9678c7b8
SH
2419 * The title of this block. If this came from user input, it should already
2420 * have had format_string() processing done on it. This will be output inside
2421 * <h2> tags. Please do not cause invalid XHTML.
2422 * @var string
beb56299 2423 */
2424 public $title = '';
2425
2426 /**
9678c7b8
SH
2427 * HTML for the content
2428 * @var string
beb56299 2429 */
2430 public $content = '';
2431
2432 /**
9678c7b8
SH
2433 * An alternative to $content, it you want a list of things with optional icons.
2434 * @var array
beb56299 2435 */
2436 public $footer = '';
2437
2438 /**
2439 * Any small print that should appear under the block to explain to the
2440 * teacher about the block, for example 'This is a sticky block that was
2441 * added in the system context.'
2442 * @var string
2443 */
2444 public $annotation = '';
2445
2446 /**
9678c7b8 2447 * One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
beb56299 2448 * the user can toggle whether this block is visible.
9678c7b8 2449 * @var integer
beb56299 2450 */
2451 public $collapsible = self::NOT_HIDEABLE;
2452
2453 /**
2454 * A (possibly empty) array of editing controls. Each element of this array
2455 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 2456 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 2457 * @var array
2458 */
2459 public $controls = array();
2460
dd72b308 2461
beb56299 2462 /**
dd72b308
PS
2463 * Create new instance of block content
2464 * @param array $attributes
d9c8f425 2465 */
9678c7b8 2466 public function __construct(array $attributes = null) {
beb56299 2467 $this->skipid = self::$idcounter;
2468 self::$idcounter += 1;
dd72b308
PS
2469
2470 if ($attributes) {
2471 // standard block
2472 $this->attributes = $attributes;
2473 } else {
2474 // simple "fake" blocks used in some modules and "Add new block" block
6605ff8c 2475 $this->attributes = array('class'=>'block');
beb56299 2476 }
dd72b308
PS
2477 }
2478
2479 /**
2480 * Add html class to block
9678c7b8 2481 *
dd72b308 2482 * @param string $class
dd72b308
PS
2483 */
2484 public function add_class($class) {
2485 $this->attributes['class'] .= ' '.$class;
d9c8f425 2486 }
2487}
beb56299 2488
34059565 2489
beb56299 2490/**
2491 * This class represents a target for where a block can go when it is being moved.
2492 *
2493 * This needs to be rendered as a form with the given hidden from fields, and
2494 * clicking anywhere in the form should submit it. The form action should be
2495 * $PAGE->url.
2496 *
2497 * @copyright 2009 Tim Hunt
9678c7b8
SH
2498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2499 * @since Moodle 2.0
2500 * @package core
2501 * @subpackage output
beb56299 2502 */
dd72b308 2503class block_move_target {
9678c7b8 2504
beb56299 2505 /**
dd72b308
PS
2506 * Move url
2507 * @var moodle_url
beb56299 2508 */
dd72b308 2509 public $url;
9678c7b8 2510
beb56299 2511 /**
dd72b308
PS
2512 * label
2513 * @var string
beb56299 2514 */
dd72b308
PS
2515 public $text;
2516
2517 /**
1a10840e 2518 * Constructor
dd72b308
PS
2519 * @param string $text
2520 * @param moodle_url $url
2521 */
2522 public function __construct($text, moodle_url $url) {
2523 $this->text = $text;
2524 $this->url = $url;
2525 }
beb56299 2526}
d2dbd0c0
SH
2527
2528/**
2529 * Custom menu item
2530 *
2531 * This class is used to represent one item within a custom menu that may or may
2532 * not have children.
2533 *
2534 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2535 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2536 * @since Moodle 2.0
2537 * @package core
2538 * @subpackage output
d2dbd0c0
SH
2539 */
2540class custom_menu_item implements renderable {
9678c7b8 2541
d2dbd0c0
SH
2542 /**
2543 * The text to show for the item
2544 * @var string
2545 */
2546 protected $text;
9678c7b8 2547
d2dbd0c0
SH
2548 /**
2549 * The link to give the icon if it has no children
2550 * @var moodle_url
2551 */
2552 protected $url;
9678c7b8 2553
d2dbd0c0
SH
2554 /**
2555 * A title to apply to the item. By default the text
2556 * @var string
2557 */
2558 protected $title;
9678c7b8 2559
d2dbd0c0 2560 /**
1a10840e 2561 * A sort order for the item, not necessary if you order things in the CFG var
d2dbd0c0
SH
2562 * @var int
2563 */
2564 protected $sort;
9678c7b8 2565
d2dbd0c0
SH
2566 /**
2567 * A reference to the parent for this item or NULL if it is a top level item
2568 * @var custom_menu_item
2569 */
2570 protected $parent;
9678c7b8 2571
d2dbd0c0
SH
2572 /**
2573 * A array in which to store children this item has.
2574 * @var array
2575 */
2576 protected $children = array();
9678c7b8 2577
d2dbd0c0
SH
2578 /**
2579 * A reference to the sort var of the last child that was added
2580 * @var int
2581 */
2582 protected $lastsort = 0;
9678c7b8 2583
d2dbd0c0
SH
2584 /**
2585 * Constructs the new custom menu item
2586 *
2587 * @param string $text
2588 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2589 * @param string $title A title to apply to this item [Optional]
2590 * @param int $sort A sort or to use if we need to sort differently [Optional]
2591 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2592 * belongs to, only if the child has a parent. [Optional]
2593 */
9678c7b8 2594 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
d2dbd0c0
SH
2595 $this->text = $text;
2596 $this->url = $url;
2597 $this->title = $title;
2598 $this->sort = (int)$sort;
2599 $this->parent = $parent;
2600 }
2601
2602 /**
2603 * Adds a custom menu item as a child of this node given its properties.
2604 *
2605 * @param string $text
2606 * @param moodle_url $url
2607 * @param string $title
2608 * @param int $sort
2609 * @return custom_menu_item
2610 */
9678c7b8 2611 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
d2dbd0c0
SH
2612 $key = count($this->children);
2613 if (empty($sort)) {
2614 $sort = $this->lastsort + 1;
2615 }
2616 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2617 $this->lastsort = (int)$sort;
2618 return $this->children[$key];
2619 }
9678c7b8 2620
d2dbd0c0
SH
2621 /**
2622 * Returns the text for this item
2623 * @return string
2624 */
2625 public function get_text() {
2626 return $this->text;
2627 }
9678c7b8 2628
d2dbd0c0
SH
2629 /**
2630 * Returns the url for this item
2631 * @return moodle_url
2632 */
2633 public function get_url() {
2634 return $this->url;
2635 }
9678c7b8 2636
d2dbd0c0
SH
2637 /**
2638 * Returns the title for this item
2639 * @return string
2640 */
2641 public function get_title() {
2642 return $this->title;
2643 }
9678c7b8 2644
d2dbd0c0
SH
2645 /**
2646 * Sorts and returns the children for this item
2647 * @return array
2648 */
2649 public function get_children() {
2650 $this->sort();
2651 return $this->children;
2652 }
9678c7b8 2653
d2dbd0c0
SH
2654 /**
2655 * Gets the sort order for this child
2656 * @return int
2657 */
2658 public function get_sort_order() {
2659 return $this->sort;
2660 }
9678c7b8 2661
d2dbd0c0
SH
2662 /**
2663 * Gets the parent this child belong to
2664 * @return custom_menu_item
2665 */
2666 public function get_parent() {
2667 return $this->parent;
2668 }
9678c7b8 2669
d2dbd0c0
SH
2670 /**
2671 * Sorts the children this item has
2672 */
2673 public function sort() {
2674 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2675 }
9678c7b8 2676
d2dbd0c0
SH
2677 /**
2678 * Returns true if this item has any children
2679 * @return bool
2680 */
2681 public function has_children() {
2682 return (count($this->children) > 0);
2683 }
f3827323
SH
2684
2685 /**
2686 * Sets the text for the node
2687 * @param string $text
2688 */
2689 public function set_text($text) {
2690 $this->text = (string)$text;
2691 }
2692
2693 /**
2694 * Sets the title for the node
2695 * @param string $title
2696 */
2697 public function set_title($title) {
2698 $this->title = (string)$title;
2699 }
2700
2701 /**
2702 * Sets the url for the node
2703 * @param moodle_url $url
2704 */
2705 public function set_url(moodle_url $url) {
2706 $this->url = $url;
2707 }
d2dbd0c0
SH
2708}
2709
2710/**
2711 * Custom menu class
2712 *
2713 * This class is used to operate a custom menu that can be rendered for the page.
2714 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2715 * of custom_menu_item nodes that can be rendered by the core renderer.
2716 *
2717 * To configure the custom menu:
2718 * Settings: Administration > Appearance > Themes > Theme settings
2719 *
2720 * @copyright 2010 Sam Hemelryk
9678c7b8
SH
2721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2722 * @since Moodle 2.0
2723 * @package core
2724 * @subpackage output
d2dbd0c0
SH
2725 */
2726class custom_menu extends custom_menu_item {
155fffe6 2727
9678c7b8
SH
2728 /**
2729 * The language we should render for, null disables multilang support.
2730 * @var string
2731 */
4564d58f
DM
2732 protected $currentlanguage = null;
2733
d2dbd0c0
SH
2734 /**
2735 * Creates the custom menu
155fffe6
DM
2736 *
2737 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
4564d58f 2738 * @param string $language the current language code, null disables multilang support
d2dbd0c0 2739 */
4564d58f 2740 public function __construct($definition = '', $currentlanguage = null) {
4564d58f 2741 $this->currentlanguage = $currentlanguage;
155fffe6
DM
2742 parent::__construct('root'); // create virtual root element of the menu
2743 if (!empty($definition)) {
4564d58f 2744 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
12cc75ae 2745 }
d2dbd0c0
SH
2746 }
2747
2748 /**
2749 * Overrides the children of this custom menu. Useful when getting children
2750 * from $CFG->custommenuitems
9678c7b8
SH
2751 *
2752 * @param array $children
d2dbd0c0
SH
2753 */
2754 public function override_children(array $children) {
2755 $this->children = array();
2756 foreach ($children as $child) {
2757 if ($child instanceof custom_menu_item) {
2758 $this->children[] = $child;
2759 }
2760 }
2761 }
2762
2763 /**
2764 * Converts a string into a structured array of custom_menu_items which can
2765 * then be added to a custom menu.
2766 *
2767 * Structure:
4564d58f
DM
2768 * text|url|title|langs
2769 * The number of hyphens at the start determines the depth of the item. The
2770 * languages are optional, comma separated list of languages the line is for.
d2dbd0c0
SH
2771 *
2772 * Example structure:
2773 * First level first item|http://www.moodle.com/
2774 * -Second level first item|http://www.moodle.com/partners/
2775 * -Second level second item|http://www.moodle.com/hq/
2776 * --Third level first item|http://www.moodle.com/jobs/
2777 * -Second level third item|http://www.moodle.com/development/
2778 * First level second item|http://www.moodle.com/feedback/
2779 * First level third item
4564d58f
DM
2780 * English only|http://moodle.com|English only item|en
2781 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2782 *
4d2ee4c2 2783 *
d2dbd0c0 2784 * @static
4564d58f
DM
2785 * @param string $text the menu items definition
2786 * @param string $language the language code, null disables multilang support
d2dbd0c0
SH
2787 * @return array
2788 */
4564d58f 2789 public static function convert_text_to_menu_nodes($text, $language = null) {
d2dbd0c0
SH
2790 $lines = explode("\n", $text);
2791 $children = array();
2792 $lastchild = null;
2793 $lastdepth = null;
2794 $lastsort = 0;
2795 foreach ($lines as $line) {
2796 $line = trim($line);
4564d58f
DM
2797 $bits = explode('|', $line, 4); // name|url|title|langs
2798 if (!array_key_exists(0, $bits) or empty($bits[0])) {
d2dbd0c0
SH
2799 // Every item must have a name to be valid
2800 continue;
2801 } else {
2802 $bits[0] = ltrim($bits[0],'-');
2803 }
4564d58f 2804 if (!array_key_exists(1, $bits) or empty($bits[1])) {
d2dbd0c0
SH
2805 // Set the url to null
2806 $bits[1] = null;
2807 } else {
2808 // Make sure the url is a moodle url
a26f25ae 2809 $bits[1] = new moodle_url(trim($bits[1]));
d2dbd0c0 2810 }
4564d58f 2811 if (!array_key_exists(2, $bits) or empty($bits[2])) {
d2dbd0c0
SH
2812 // Set the title to null seeing as there isn't one
2813 $bits[2] = $bits[0];
2814 }
4564d58f
DM
2815 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2816 // The item is valid for all languages
2817 $itemlangs = null;
2818 } else {
2819 $itemlangs = array_map('trim', explode(',', $bits[3]));
2820 }
2821 if (!empty($language) and !empty($itemlangs)) {
2822 // check that the item is intended for the current language
2823 if (!in_array($language, $itemlangs)) {
2824 continue;
2825 }
2826 }
d2dbd0c0 2827 // Set an incremental sort order to keep it simple.
4564d58f 2828 $lastsort++;
d2dbd0c0
SH
2829 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2830 $depth = strlen($match[1]);
2831 if ($depth < $lastdepth) {
57bedaee
SH
2832 $difference = $lastdepth - $depth;
2833 if ($lastdepth > 1 && $lastdepth != $difference) {
2834 $tempchild = $lastchild->get_parent();
2835 for ($i =0; $i < $difference; $i++) {
2836 $tempchild = $tempchild->get_parent();
2837 }
4564d58f 2838 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2839 } else {
2840 $depth = 0;
4564d58f 2841 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2842 $children[] = $lastchild;
2843 }
2844 } else if ($depth > $lastdepth) {
2845 $depth = $lastdepth + 1;
4564d58f 2846 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2847 } else {
2848 if ($depth == 0) {
4564d58f 2849 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2850 $children[] = $lastchild;
2851 } else {
4564d58f 2852 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2853 }
2854 }
2855 } else {
2856 $depth = 0;
4564d58f 2857 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2858 $children[] = $lastchild;
2859 }
2860 $lastdepth = $depth;
2861 }
2862 return $children;
2863 }
2864
2865 /**
2866 * Sorts two custom menu items
2867 *
2868 * This function is designed to be used with the usort method
2869 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2870 *
9678c7b8 2871 * @static
d2dbd0c0
SH
2872 * @param custom_menu_item $itema
2873 * @param custom_menu_item $itemb
2874 * @return int
2875 */
2876 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2877 $itema = $itema->get_sort_order();
2878 $itemb = $itemb->get_sort_order();
2879 if ($itema == $itemb) {
2880 return 0;
2881 }
2882 return ($itema > $itemb) ? +1 : -1;
2883 }
9678c7b8 2884}