MDL-21235 fixed select method name
[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 *
24 * @package moodlecore
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
5d0c95a5
PS
29/**
30 * This constant is used for html attributes which need to have an empty
31 * value and still be output by the renderers (e.g. alt="");
32 *
33 * @constant @EMPTY@
34 */
35define('HTML_ATTR_EMPTY', '@EMPTY@');
36
37
38/**
39 * Interface marking other classes as suitable for renderer_base::render()
40 * @author 2010 Petr Skoda (skodak) info@skodak.org
41 */
42interface renderable {
43 // intentionally empty
44}
45
46
47/**
bf11293a 48 * Data structure representing a user picture.
5d0c95a5
PS
49 *
50 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 * @since Moodle 2.0
53 */
54class user_picture implements renderable {
55 /**
56 * List of mandatory fields in user record here.
57 * @var string
58 */
59 const FIELDS = 'id,picture,firstname,lastname,imagealt';
60
61 /**
62 * @var object $user A user object with at least fields id, picture, imagealt, firstname and lastname set.
63 */
64 public $user;
65 /**
66 * @var int $courseid The course id. Used when constructing the link to the user's profile,
67 * page course id used if not specified.
68 */
69 public $courseid;
70 /**
71 * @var bool $link add course profile link to image
72 */
73 public $link = true;
74 /**
75 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
76 */
77 public $size = 35;
78 /**
79 * @var boolean $alttext add non-blank alt-text to the image.
80 * Default true, set to false when image alt just duplicates text in screenreaders.
81 */
82 public $alttext = true;
83 /**
84 * @var boolean $popup Whether or not to open the link in a popup window.
85 */
86 public $popup = false;
87 /**
88 * @var string Image class attribute
89 */
90 public $class = 'userpicture';
91
92 /**
93 * User picture constructor.
94 *
95 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
96 * @param array $options such as link, size, link, ...
97 */
98 public function __construct(stdClass $user) {
99 global $DB;
100
101 static $fields = null;
102 if (is_null($fields)) {
103 $fields = explode(',', self::FIELDS);
104 }
105
106 if (empty($user->id)) {
107 throw new coding_exception('User id is required when printing user avatar image.');
108 }
109
110 // only touch the DB if we are missing data and complain loudly...
111 $needrec = false;
112 foreach ($fields as $field) {
113 if (!array_key_exists($field, $user)) {
114 $needrec = true;
115 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
116 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
117 break;
118 }
119 }
120
121 if ($needrec) {
122 $this->user = $DB->get_record('user', array('id'=>$user->id), self::FIELDS, MUST_EXIST);
123 } else {
124 $this->user = clone($user);
125 }
126 }
127
128 /**
129 * Returns a list of required user fields, usefull when fetching required user info from db.
130 * @param string $tableprefix name of database table prefix in query
131 * @return string
132 */
133 public static function fields($tableprefix = '') {
134 if ($tableprefix === '') {
135 return self::FIELDS;
136 } else {
137 return "$tableprefix." . str_replace(',', ",$tableprefix.", self::FIELDS);
138 }
139 }
140}
141
bf11293a
PS
142
143/**
144 * Data structure representing a help icon.
145 *
146 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
147 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
148 * @since Moodle 2.0
149 */
150class help_icon implements renderable {
151 /**
152 * @var string $page name of help page
153 */
154 public $helppage;
155 /**
156 * @var string $title A descriptive text for title tooltip
157 */
158 public $title = '';
159 /**
160 * @var string $component Component name, the same as in get_string()
161 */
162 public $component = 'moodle';
163 /**
164 * @var string $linktext Extra descriptive text next to the icon
165 */
166 public $linktext = '';
167
168 /**
169 * Constructor: sets up the other components in case they are needed
170 * @param string $page The keyword that defines a help page
171 * @param string $title A descriptive text for accesibility only
172 * @param string $component
173 * @param bool $linktext add extra text to icon
174 * @return void
175 */
176 public function __construct($helppage, $title, $component = 'moodle') {
177 if (empty($title)) {
178 throw new coding_exception('A help_icon object requires a $text parameter');
179 }
180 if (empty($helppage)) {
181 throw new coding_exception('A help_icon object requires a $helppage parameter');
182 }
183
184 $this->helppage = $helppage;
185 $this->title = $title;
186 $this->component = $component;
187 }
188}
189
190
3ba60ee1
PS
191/**
192 * Data structure representing a simple form with only one button.
193 *
194 * @copyright 2009 Petr Skoda
195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
196 * @since Moodle 2.0
197 */
198class single_button implements renderable {
574fbea4
PS
199 /**
200 * Target url
201 * @var moodle_url
202 */
3ba60ee1 203 var $url;
574fbea4
PS
204 /**
205 * Button label
206 * @var string
207 */
3ba60ee1 208 var $label;
574fbea4
PS
209 /**
210 * Form submit method
211 * @var string post or get
212 */
3ba60ee1 213 var $method = 'post';
574fbea4
PS
214 /**
215 * Wrapping div class
216 * @var string
217 * */
3ba60ee1 218 var $class = 'singlebutton';
574fbea4
PS
219 /**
220 * True if button disabled, false if normal
221 * @var boolean
222 */
3ba60ee1 223 var $disabled = false;
574fbea4
PS
224 /**
225 * Button tooltip
226 * @var string
227 */
3ba60ee1 228 var $tooltip = '';
574fbea4
PS
229 /**
230 * Form id
231 * @var string
232 */
3ba60ee1 233 var $formid;
574fbea4
PS
234 /**
235 * List of attached actions
236 * @var array of component_action
237 */
3ba60ee1
PS
238 var $actions = array();
239
240 /**
241 * Constructor
574fbea4 242 * @param string|moodle_url $url
3ba60ee1
PS
243 * @param string $label button text
244 * @param string $method get or post submit method
3ba60ee1
PS
245 */
246 public function __construct(moodle_url $url, $label, $method='post') {
247 $this->url = clone($url);
248 $this->label = $label;
249 $this->method = $method;
250 }
251
252 /**
574fbea4 253 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1
PS
254 * The message must be a yes/no question.
255 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
256 * @return void
257 */
258 public function add_confirm_action($confirmmessage) {
259 $this->add_action(new component_action('click', 'confirm_dialog', array('message' => $confirmmessage)));
260 }
261
574fbea4
PS
262 /**
263 * Add action to the button.
264 * @param component_action $action
265 * @return void
266 */
3ba60ee1
PS
267 public function add_action(component_action $action) {
268 $this->actions[] = $action;
269 }
270}
271
272
574fbea4
PS
273/**
274 * Data structure describing html link with special action attached.
275 * @copyright 2010 Petr Skoda
276 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
277 * @since Moodle 2.0
278 */
279class action_link implements renderable {
280 /**
281 * Href url
282 * @var moodle_url
283 */
284 var $url;
285 /**
286 * Link text
287 * @var string HTML fragment
288 */
289 var $text;
290 /**
291 * HTML attributes
292 * @var array
293 */
294 var $attributes;
295 /**
296 * List of actions attached to link
297 * @var array of component_action
298 */
299 var $actions;
300
301 /**
302 * Constructor
303 * @param string|moodle_url $url
304 * @param string $text HTML fragment
305 * @param component_action $action
11820bac 306 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
307 */
308 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
309 $this->url = clone($url);
310 $this->text = $text;
f14b641b 311 if ($action) {
574fbea4
PS
312 $this->add_action($action);
313 }
314 }
315
316 /**
317 * Add action to the link.
318 * @param component_action $action
319 * @return void
320 */
321 public function add_action(component_action $action) {
322 $this->actions[] = $action;
323 }
324}
3ba60ee1 325
5d0c95a5
PS
326// ==== HTML writer and helper classes, will be probably moved elsewhere ======
327
328
329/**
330 * Simple html output class
331 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
332 */
333class html_writer {
334 /**
335 * Outputs a tag with attributes and contents
336 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
337 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
338 * @param string $contents What goes between the opening and closing tags
339 * @return string HTML fragment
340 */
341 public static function tag($tagname, array $attributes = null, $contents) {
342 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
343 }
344
345 /**
346 * Outputs an opening tag with attributes
347 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
348 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
349 * @return string HTML fragment
350 */
351 public static function start_tag($tagname, array $attributes = null) {
352 return '<' . $tagname . self::attributes($attributes) . '>';
353 }
354
355 /**
356 * Outputs a closing tag
357 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
358 * @return string HTML fragment
359 */
360 public static function end_tag($tagname) {
361 return '</' . $tagname . '>';
362 }
363
364 /**
365 * Outputs an empty tag with attributes
366 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
367 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
368 * @return string HTML fragment
369 */
370 public static function empty_tag($tagname, array $attributes = null) {
371 return '<' . $tagname . self::attributes($attributes) . ' />';
372 }
373
374 /**
375 * Outputs a HTML attribute and value
376 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
377 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
378 * @return string HTML fragment
379 */
380 public static function attribute($name, $value) {
381 if (is_array($value)) {
382 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
383 }
bf11293a
PS
384 if ($value instanceof moodle_url) {
385 return ' ' . $name . '="' . $value->out() . '"';
386 }
5d0c95a5
PS
387 $value = trim($value);
388 if ($value == HTML_ATTR_EMPTY) {
389 return ' ' . $name . '=""';
390 } else if ($value || is_numeric($value)) { // We want 0 to be output.
391 return ' ' . $name . '="' . s($value) . '"';
392 }
393 }
394
395 /**
396 * Outputs a list of HTML attributes and values
397 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
398 * The values will be escaped with {@link s()}
399 * @return string HTML fragment
400 */
401 public static function attributes(array $attributes = null) {
402 $attributes = (array)$attributes;
403 $output = '';
404 foreach ($attributes as $name => $value) {
405 $output .= self::attribute($name, $value);
406 }
407 return $output;
408 }
409
410 /**
411 * Generates random html element id.
412 * @param string $base
413 * @return string
414 */
415 public static function random_id($base='random') {
416 return uniqid($base);
417 }
0f4c64b7
PS
418
419 /**
420 * Generates a simple html link
421 * @param string|moodle_url $url
422 * @param string $text link txt
423 * @param array $attributes extra html attributes
424 * @return string HTML fragment
425 */
426 public static function link($url, $text, array $attributes = null) {
427 $attributes = (array)$attributes;
428 $attributes['href'] = $url;
429 return self::tag('a', $attributes, $text);
430 }
3ff163c5
PS
431
432 /**
433 * Generates a simple select form field
434 * @param array $options associative array value=>label
435 * @param string $name name of select element
436 * @param string|array $selected value or arary of values depending on multiple attribute
437 * @param array|bool $nothing, add nothing selected option, or false of not added
438 * @param array $attributes - html select element attributes
439 * @return string HRML fragment
440 */
d776d59e 441 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choose'), array $attributes = null) {
3ff163c5
PS
442 $attributes = (array)$attributes;
443 if (is_array($nothing)) {
444 foreach ($nothing as $k=>$v) {
4b9210f3 445 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
446 $nothing[$k] = get_string('choosedots');
447 }
448 }
449 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
450
451 } else if (is_string($nothing) and $nothing !== '') {
452 // BC
453 $options = array(''=>$nothing) + $options;
454 }
3ff163c5
PS
455
456 // we may accept more values if multiple attribute specified
457 $selected = (array)$selected;
458 foreach ($selected as $k=>$v) {
459 $selected[$k] = (string)$v;
460 }
461
462 if (!isset($attributes['id'])) {
463 $id = 'menu'.$name;
464 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
465 $id = str_replace('[', '', $id);
466 $id = str_replace(']', '', $id);
467 $attributes['id'] = $id;
468 }
469
470 if (!isset($attributes['class'])) {
471 $class = 'menu'.$name;
472 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
473 $class = str_replace('[', '', $class);
474 $class = str_replace(']', '', $class);
475 $attributes['class'] = $class;
476 }
477 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
478
479 $attributes['name'] = $name;
480
481 $output = '';
482 foreach ($options as $value=>$label) {
483 $ias = array();
484 $value = (string)$value; //TODO: add support for opt groups as nested arrays
485 if (in_array($value, $selected, true)) {
486 $ias['selected'] = 'selected';
487 }
488 $ias['value'] = $value;
489 $output .= self::tag('option', $ias, $label);
490 }
491
492 return self::tag('select', $attributes, $output);
493 }
5d0c95a5
PS
494}
495
496
497// ===============================================================================================
498// TODO: Following components will be refactored soon
499
d9c8f425 500/**
7b1f2c82 501 * Base class for classes representing HTML elements, like html_select.
d9c8f425 502 *
503 * Handles the id and class attributes.
504 *
505 * @copyright 2009 Tim Hunt
506 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
507 * @since Moodle 2.0
508 */
6dd7d7f0 509class html_component {
d9c8f425 510 /**
511 * @var string value to use for the id attribute of this HTML tag.
512 */
513 public $id = '';
514 /**
515 * @var string $alt value to use for the alt attribute of this HTML tag.
516 */
517 public $alt = '';
518 /**
519 * @var string $style value to use for the style attribute of this HTML tag.
520 */
521 public $style = '';
522 /**
523 * @var array class names to add to this HTML element.
524 */
525 public $classes = array();
526 /**
527 * @var string $title The title attributes applicable to any XHTML element
528 */
529 public $title = '';
530 /**
531 * An optional array of component_action objects handling the action part of this component.
532 * @var array $actions
533 */
534 protected $actions = array();
d9c8f425 535
8fa16366
PS
536 /**
537 * Compoment constructor.
538 * @param array $options image attributes such as title, id, alt, style, class
539 */
540 public function __construct(array $options = null) {
541 // not implemented in this class because we want to set only public properties of this component
542 renderer_base::apply_component_options($this, $options);
543 }
544
d9c8f425 545 /**
546 * Ensure some class names are an array.
547 * @param mixed $classes either an array of class names or a space-separated
548 * string containing class names.
549 * @return array the class names as an array.
550 */
551 public static function clean_classes($classes) {
642816a6 552 if (empty($classes)) {
3bd6b994 553 return array();
642816a6 554 } else if (is_array($classes)) {
d9c8f425 555 return $classes;
556 } else {
557 return explode(' ', trim($classes));
558 }
559 }
560
561 /**
562 * Set the class name array.
563 * @param mixed $classes either an array of class names or a space-separated
564 * string containing class names.
565 * @return void
566 */
567 public function set_classes($classes) {
568 $this->classes = self::clean_classes($classes);
569 }
570
571 /**
572 * Add a class name to the class names array.
573 * @param string $class the new class name to add.
574 * @return void
575 */
576 public function add_class($class) {
577 $this->classes[] = $class;
578 }
579
580 /**
581 * Add a whole lot of class names to the class names array.
582 * @param mixed $classes either an array of class names or a space-separated
583 * string containing class names.
584 * @return void
585 */
586 public function add_classes($classes) {
eeecf5a7 587 $this->classes = array_merge($this->classes, self::clean_classes($classes));
d9c8f425 588 }
589
590 /**
591 * Get the class names as a string.
592 * @return string the class names as a space-separated string. Ready to be put in the class="" attribute.
593 */
594 public function get_classes_string() {
595 return implode(' ', $this->classes);
596 }
597
598 /**
599 * Perform any cleanup or final processing that should be done before an
34059565
PS
600 * instance of this class is output. This method is supposed to be called
601 * only from renderers.
602 *
603 * @param renderer_base $output output renderer
604 * @param moodle_page $page
605 * @param string $target rendering target
d9c8f425 606 * @return void
607 */
34059565 608 public function prepare(renderer_base $output, moodle_page $page, $target) {
d9c8f425 609 $this->classes = array_unique(self::clean_classes($this->classes));
610 }
611
612 /**
613 * This checks developer do not try to assign a property directly
614 * if we have a setter for it. Otherwise, the property is set as expected.
615 * @param string $name The name of the variable to set
616 * @param mixed $value The value to assign to the variable
617 * @return void
618 */
619 public function __set($name, $value) {
620 if ($name == 'class') {
621 debugging('this way of setting css class has been deprecated. use set_classes() method instead.');
622 $this->set_classes($value);
623 } else {
624 $this->{$name} = $value;
625 }
626 }
627
628 /**
629 * Adds a JS action to this component.
630 * Note: the JS function you write must have only two arguments: (string)event and (object|array)args
631 * If you want to add an instantiated component_action (or one of its subclasses), give the object as the only parameter
632 *
633 * @param mixed $event a DOM event (click, mouseover etc.) or a component_action object
634 * @param string $jsfunction The name of the JS function to call. required if argument 1 is a string (event)
635 * @param array $jsfunctionargs An optional array of JS arguments to pass to the function
636 */
637 public function add_action($event, $jsfunction=null, $jsfunctionargs=array()) {
638 if (empty($this->id)) {
639 $this->generate_id();
640 }
641
642 if ($event instanceof component_action) {
643 $this->actions[] = $event;
644 } else {
645 if (empty($jsfunction)) {
6dd7d7f0 646 throw new coding_exception('html_component::add_action requires a JS function argument if the first argument is a string event');
d9c8f425 647 }
648 $this->actions[] = new component_action($event, $jsfunction, $jsfunctionargs);
649 }
650 }
651
652 /**
653 * Internal method for generating a unique ID for the purpose of event handlers.
654 */
655 protected function generate_id() {
0c868b08 656 $this->id = uniqid(get_class($this));
d9c8f425 657 }
658
659 /**
660 * Returns the array of component_actions.
661 * @return array Component actions
662 */
663 public function get_actions() {
664 return $this->actions;
665 }
666
7a5c78e0 667 /**
668 * Shortcut for adding a JS confirm dialog when the component is clicked.
669 * The message must be a yes/no question.
670 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
a0ead5eb 671 * @param string $callback The name of a JS function whose scope will be set to the simpleDialog object and have this
5529f787 672 * function's arguments set as this.args.
7a5c78e0 673 * @return void
674 */
5529f787 675 public function add_confirm_action($message, $callback=null) {
676 $this->add_action(new component_action('click', 'confirm_dialog', array('message' => $message, 'callback' => $callback)));
7a5c78e0 677 }
db49be13 678
679 /**
680 * Returns true if this component has an action of the requested type (component_action by default).
681 * @param string $class The class of the action we are looking for
682 * @return boolean True if action is found
683 */
684 public function has_action($class='component_action') {
685 foreach ($this->actions as $action) {
686 if (get_class($action) == $class) {
687 return true;
688 }
689 }
690 return false;
691 }
7a5c78e0 692}
693
34059565 694
6dd7d7f0 695class labelled_html_component extends html_component {
7a5c78e0 696 /**
697 * @var mixed $label The label for that component. String or html_label object
698 */
699 public $label;
700
8fa16366
PS
701 /**
702 * Compoment constructor.
703 * @param array $options image attributes such as title, id, alt, style, class
704 */
705 public function __construct(array $options = null) {
706 parent::__construct($options);
707 }
708
d9c8f425 709 /**
710 * Adds a descriptive label to the component.
711 *
712 * This can be used in two ways:
713 *
714 * <pre>
715 * $component->set_label($elementlabel, $elementid);
716 * // OR
717 * $label = new html_label();
718 * $label->for = $elementid;
719 * $label->text = $elementlabel;
720 * $component->set_label($label);
721 * </pre>
722 *
723 * Use the second form when you need to add additional HTML attributes
724 * to the label and/or JS actions.
725 *
726 * @param mixed $text Either the text of the label or a html_label object
727 * @param text $for The value of the "for" attribute (the associated element's id)
728 * @return void
729 */
730 public function set_label($text, $for=null) {
731 if ($text instanceof html_label) {
732 $this->label = $text;
733 } else if (!empty($text)) {
734 $this->label = new html_label();
735 $this->label->for = $for;
1ae3767a 736 if (empty($for)) {
3cc457db 737 if (empty($this->id)) {
738 $this->generate_id();
739 }
d9c8f425 740 $this->label->for = $this->id;
741 }
742 $this->label->text = $text;
743 }
744 }
745}
746
beb56299 747/// Components representing HTML elements
d9c8f425 748
749/**
beb56299 750 * This class represents a label element
d9c8f425 751 *
beb56299 752 * @copyright 2009 Nicolas Connault
d9c8f425 753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
754 * @since Moodle 2.0
755 */
6dd7d7f0 756class html_label extends html_component {
d9c8f425 757 /**
beb56299 758 * @var string $text The text to display in the label
d9c8f425 759 */
beb56299 760 public $text;
d9c8f425 761 /**
beb56299 762 * @var string $for The name of the form field this label is associated with
d9c8f425 763 */
beb56299 764 public $for;
765
d9c8f425 766 /**
6dd7d7f0 767 * @see html_component::prepare()
beb56299 768 * @return void
d9c8f425 769 */
34059565 770 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 771 if (empty($this->text)) {
772 throw new coding_exception('html_label must have a $text value.');
773 }
34059565 774 parent::prepare($output, $page, $target);
beb56299 775 }
776}
777
34059565 778
beb56299 779/**
7b1f2c82 780 * This class hold all the information required to describe a <select> menu that
78946b9b 781 * will be printed by {@link core_renderer::select()}. (Or by an overridden
7b1f2c82 782 * version of that method in a subclass.)
beb56299 783 *
7b1f2c82 784 * This component can also hold enough metadata to be used as a popup form. It just
785 * needs a bit more setting up than for a simple menu. See the shortcut methods for
786 * developer-friendly usage.
787 *
788 * All the fields that are not set by the constructor have sensible defaults, so
789 * you only need to set the properties where you want non-default behaviour.
790 *
791 * @copyright 2009 Tim Hunt
beb56299 792 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
793 * @since Moodle 2.0
794 */
7a5c78e0 795class html_select extends labelled_html_component {
d9c8f425 796 /**
7b1f2c82 797 * The html_select object parses an array of options into component objects
798 * @see nested attribute
799 * @var mixed $options the choices to show in the menu. An array $value => $display, of html_select_option or of html_select_optgroup objects.
d9c8f425 800 */
7b1f2c82 801 public $options;
d9c8f425 802 /**
7b1f2c82 803 * @var string $name the name of this form control. That is, the name of the GET/POST
804 * variable that will be set if this select is submitted as part of a form.
d9c8f425 805 */
7b1f2c82 806 public $name;
d9c8f425 807 /**
7b1f2c82 808 * @var string $selectedvalue the option to select initially. Should match one
809 * of the $options array keys. Default none.
d9c8f425 810 */
7b1f2c82 811 public $selectedvalue;
d9c8f425 812 /**
7b1f2c82 813 * Defaults to get_string('choosedots').
814 * Set this to '' if you do not want a 'nothing is selected' option.
815 * This is ignored if the rendertype is 'radio' or 'checkbox'
816 * @var string The label for the 'nothing is selected' option.
d9c8f425 817 */
7b1f2c82 818 public $nothinglabel = null;
d9c8f425 819 /**
7b1f2c82 820 * @var string The value returned by the 'nothing is selected' option. Defaults to 0.
d9c8f425 821 */
7b1f2c82 822 public $nothingvalue = 0;
d9c8f425 823 /**
7b1f2c82 824 * @var boolean set this to true if you want the control to appear disabled.
d9c8f425 825 */
7b1f2c82 826 public $disabled = false;
d9c8f425 827 /**
7b1f2c82 828 * @var integer if non-zero, sets the tabindex attribute on the <select> element. Default 0.
d9c8f425 829 */
7b1f2c82 830 public $tabindex = 0;
d9c8f425 831 /**
7b1f2c82 832 * @var mixed Defaults to false, which means display the select as a dropdown menu.
833 * If true, display this select as a list box whose size is chosen automatically.
834 * If an integer, display as list box of that size.
d9c8f425 835 */
7b1f2c82 836 public $listbox = false;
d9c8f425 837 /**
7b1f2c82 838 * @var integer if you are using $listbox === true to get an automatically
839 * sized list box, the size of the list box will be the number of options,
840 * or this number, whichever is smaller.
d9c8f425 841 */
7b1f2c82 842 public $maxautosize = 10;
d9c8f425 843 /**
7b1f2c82 844 * @var boolean if true, allow multiple selection. Only used if $listbox is true, or if
845 * the select is to be output as checkboxes.
d9c8f425 846 */
7b1f2c82 847 public $multiple = false;
beb56299 848 /**
7b1f2c82 849 * Another way to use nested menu is to prefix optgroup labels with -- and end the optgroup with --
850 * Leave this setting to false if you are using the latter method.
851 * @var boolean $nested if true, uses $options' keys as option headings (optgroup)
beb56299 852 */
7b1f2c82 853 public $nested = false;
854 /**
855 * @var html_form $form An optional html_form component
856 */
857 public $form;
858 /**
4bcc5118 859 * @var help_icon $array help icon params
7b1f2c82 860 */
861 public $helpicon;
862 /**
863 * @var boolean $rendertype How the select element should be rendered: menu or radio (checkbox is just radio + multiple)
864 */
865 public $rendertype = 'menu';
d9c8f425 866
867 /**
6dd7d7f0 868 * @see html_component::prepare()
d9c8f425 869 * @return void
870 */
34059565 871 public function prepare(renderer_base $output, moodle_page $page, $target) {
7b1f2c82 872 global $CFG;
873
874 // name may contain [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
beb56299 875 if (empty($this->id)) {
7b1f2c82 876 $this->id = 'menu' . str_replace(array('[', ']'), '', $this->name);
877 }
878
879 if (empty($this->classes)) {
880 $this->set_classes(array('menu' . str_replace(array('[', ']'), '', $this->name)));
881 }
882
883 if (is_null($this->nothinglabel)) {
884 $this->nothinglabel = get_string('choosedots');
885 }
886
887 if (!empty($this->label) && !($this->label instanceof html_label)) {
888 $label = new html_label();
889 $label->text = $this->label;
890 $label->for = $this->name;
891 $this->label = $label;
d9c8f425 892 }
7b1f2c82 893
894 $this->add_class('select');
895
896 $this->initialise_options();
34059565 897 parent::prepare($output, $page, $target);
d9c8f425 898 }
899
900 /**
7b1f2c82 901 * This is a shortcut for making a simple select menu. It lets you specify
902 * the options, name and selected option in one line of code.
903 * @param array $options used to initialise {@link $options}.
904 * @param string $name used to initialise {@link $name}.
905 * @param string $selected used to initialise {@link $selected}.
54b16692 906 * @param string $nothinglabel The label for the 'nothing is selected' option. Defaults to "Choose..."
7b1f2c82 907 * @return html_select A html_select object with the three common fields initialised.
d9c8f425 908 */
54b16692 909 public static function make($options, $name, $selected = '', $nothinglabel='choosedots') {
7b1f2c82 910 $menu = new html_select();
911 $menu->options = $options;
912 $menu->name = $name;
913 $menu->selectedvalue = $selected;
914 return $menu;
d9c8f425 915 }
916
917 /**
7b1f2c82 918 * This is a shortcut for making a yes/no select menu.
919 * @param string $name used to initialise {@link $name}.
920 * @param string $selected used to initialise {@link $selected}.
921 * @return html_select A menu initialised with yes/no options.
beb56299 922 */
7b1f2c82 923 public static function make_yes_no($name, $selected) {
924 return self::make(array(0 => get_string('no'), 1 => get_string('yes')), $name, $selected);
925 }
926
d9c8f425 927 /**
7b1f2c82 928 * This is a shortcut for making an hour selector menu.
929 * @param string $type The type of selector (years, months, days, hours, minutes)
930 * @param string $name fieldname
931 * @param int $currenttime A default timestamp in GMT
932 * @param int $step minute spacing
933 * @return html_select A menu initialised with hour options.
d9c8f425 934 */
7b1f2c82 935 public static function make_time_selector($type, $name, $currenttime=0, $step=5) {
936
937 if (!$currenttime) {
938 $currenttime = time();
939 }
940 $currentdate = usergetdate($currenttime);
941 $userdatetype = $type;
942
943 switch ($type) {
944 case 'years':
945 for ($i=1970; $i<=2020; $i++) {
946 $timeunits[$i] = $i;
947 }
948 $userdatetype = 'year';
949 break;
950 case 'months':
951 for ($i=1; $i<=12; $i++) {
952 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
953 }
954 $userdatetype = 'month';
1ae3767a 955 $currentdate['month'] = $currentdate['mon'];
7b1f2c82 956 break;
957 case 'days':
958 for ($i=1; $i<=31; $i++) {
959 $timeunits[$i] = $i;
960 }
961 $userdatetype = 'mday';
962 break;
963 case 'hours':
964 for ($i=0; $i<=23; $i++) {
965 $timeunits[$i] = sprintf("%02d",$i);
966 }
967 break;
968 case 'minutes':
969 if ($step != 1) {
970 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
971 }
972
973 for ($i=0; $i<=59; $i+=$step) {
974 $timeunits[$i] = sprintf("%02d",$i);
975 }
976 break;
977 default:
978 throw new coding_exception("Time type $type is not supported by html_select::make_time_selector().");
979 }
980
981 $timerselector = self::make($timeunits, $name, $currentdate[$userdatetype]);
982 $timerselector->label = new html_label();
1ae3767a 983
984 $timerselector->label->text = get_string(substr($type, 0, -1), 'form');
7b1f2c82 985 $timerselector->label->for = "menu$timerselector->name";
986 $timerselector->label->add_class('accesshide');
987 $timerselector->nothinglabel = '';
988
989 return $timerselector;
990 }
991
992 /**
993 * Given an associative array of type => fieldname and an optional timestamp,
994 * returns an array of html_select components representing date/time selectors.
995 * @param array $selectors Arrays of type => fieldname. Selectors will be returned in the order of the types given
996 * @param int $currenttime A UNIX timestamp
997 * @param int $step minute spacing
998 * @return array Instantiated date/time selectors
999 */
8fa16366 1000 public static function make_time_selectors($selectors, $currenttime=0, $step=5) {
7b1f2c82 1001 $selects = array();
1002 foreach ($selectors as $type => $name) {
1003 $selects[] = html_select::make_time_selector($type, $name, $currenttime, $step);
1004 }
1005 return $selects;
1006 }
1007
1008 /**
1009 * This is a shortcut for making a select popup form.
1010 * @param mixed $baseurl The target URL, string or moodle_url
1011 * @param string $name The variable which this select's options are changing in the URL
1012 * @param array $options A list of value-label pairs for the popup list
1013 * @param string $formid id for the control. Must be unique on the page. Used in the HTML.
1014 * @param string $selected The option that is initially selected
1015 * @return html_select A menu initialised as a popup form.
1016 */
8fa16366 1017 public static function make_popup_form($baseurl, $name, $options, $formid, $selected=null) {
7b1f2c82 1018 global $CFG;
1019
1020 $selectedurl = null;
1021
1022 if (!($baseurl instanceof moodle_url)) {
1023 $baseurl = new moodle_url($baseurl);
1024 }
1025
1026 if (!empty($selected)) {
1027 $selectedurl = $baseurl->out(false, array($name => $selected), false);
1028 }
1029
7b1f2c82 1030 // Replace real value by formatted URLs
1031 foreach ($options as $value => $label) {
1032 $options[$baseurl->out(false, array($name => $value), false)] = $label;
1033 unset($options[$value]);
1034 }
1035
1036 $select = self::make($options, 'jump', $selectedurl);
1037
1038 $select->form = new html_form();
1039 $select->form->id = $formid;
1040 $select->form->method = 'get';
b65bfc3e 1041 $select->form->jssubmitaction = true;
7b1f2c82 1042 $select->form->add_class('popupform');
a6855934 1043 $select->form->url = new moodle_url('/course/jumpto.php', array('sesskey' => sesskey()));
7b1f2c82 1044 $select->form->button->text = get_string('go');
1045
1046 $select->id = $formid . '_jump';
1047
1048 $select->add_action('change', 'submit_form_by_id', array('id' => $formid, 'selectid' => $select->id));
1049
1050 return $select;
1051 }
1052
1053 /**
1054 * Override the URLs of the default popup_form, which only supports one base URL
1055 * @param array $options value=>label pairs representing select options
1056 * @return void
1057 */
1058 public function override_option_values($options) {
5acf9cd3
PS
1059 // TODO: this is ugly hack because components shoudl never touch global $PAGE with the exception in prepare(),
1060 // in any case this methods needs to be revisited because it does not make much sense to use the same $menu in
1061 // html_select::make_popup_form() and then again in this method!
1062 global $PAGE; //TODO: remove
1063
e4c5abdc 1064 $originalcount = count($options);
7b1f2c82 1065 $this->initialise_options();
e4c5abdc 1066 $newcount = count($this->options);
1067 $first = true;
7b1f2c82 1068
1069 reset($options);
1070
1071 foreach ($this->options as $optkey => $optgroup) {
1072 if ($optgroup instanceof html_select_optgroup) {
1073 foreach ($optgroup->options as $key => $option) {
1074 next($options);
1075 $this->options[$optkey]->options[$key]->value = key($options);
1076
1077 $optionurl = new moodle_url(key($options));
1078
5acf9cd3 1079 if ($optionurl->compare($PAGE->url, URL_MATCH_PARAMS)) {
7b1f2c82 1080 $this->options[$optkey]->options[$key]->selected = 'selected';
1081 }
1082 }
1083 next($options);
e4c5abdc 1084 } else if ($optgroup instanceof html_select_option && !($first && $originalcount < $newcount)) {
7b1f2c82 1085 $this->options[$optkey]->value = key($options);
1086 $optionurl = new moodle_url(key($options));
1087
5acf9cd3 1088 if ($optionurl->compare($PAGE->url, URL_MATCH_PARAMS)) {
7b1f2c82 1089 $this->options[$optkey]->selected = 'selected';
1090 }
e4c5abdc 1091 next($options);
7b1f2c82 1092 }
e4c5abdc 1093 $first = false;
7b1f2c82 1094 }
1095 }
1096
1097 /**
1098 * Adds a help icon next to the select menu.
1099 *
7b1f2c82 1100 * <pre>
4bcc5118 1101 * $select->set_help_icon($page, $text, $component);
7b1f2c82 1102 * </pre>
1103 *
4bcc5118 1104 * @param string $helppage Either the keyword that defines a help page or a help_icon object
7b1f2c82 1105 * @param text $text The text of the help icon
4bcc5118 1106 * @param component $component
7b1f2c82 1107 * @param boolean $linktext Whether or not to show text next to the icon
1108 * @return void
1109 */
4bcc5118
PS
1110 public function set_help_icon($helppage='', $text='', $component='moodle') {
1111 if ($helppage) {
1112 $this->helpicon = array('helppage'=>$helppage, 'text'=>$text, 'component'=>$component);
1113 } else {
1114 $this->helpicon = null;
7b1f2c82 1115 }
1116 }
1117
1118 /**
1119 * Parses the $options array and instantiates html_select_option objects in
1120 * the place of the original value => label pairs. This is useful for when you
1121 * need to setup extra html attributes and actions on individual options before
1122 * the component is sent to the renderer
1123 * @return void;
1124 */
1125 public function initialise_options() {
1126 // If options are already instantiated objects, stop here
1127 $firstoption = reset($this->options);
1128 if ($firstoption instanceof html_select_option || $firstoption instanceof html_select_optgroup) {
1129 return;
1130 }
1131
1132 if ($this->rendertype == 'radio' && $this->multiple) {
1133 $this->rendertype = 'checkbox';
1134 }
1135
1136 // If nested is on, or if radio/checkbox rendertype is set, remove the default Choose option
1137 if ($this->nested || $this->rendertype == 'radio' || $this->rendertype == 'checkbox') {
1138 $this->nothinglabel = '';
1139 }
1140
1141 $options = $this->options;
1142
1143 $this->options = array();
1144
1145 if ($this->nested && $this->rendertype != 'menu') {
1146 throw new coding_exception('html_select cannot render nested options as radio buttons or checkboxes.');
1147 } else if ($this->nested) {
1148 foreach ($options as $section => $values) {
1149 $optgroup = new html_select_optgroup();
1150 $optgroup->text = $section;
1151
1152 foreach ($values as $value => $display) {
1153 $option = new html_select_option();
1154 $option->value = s($value);
1155 $option->text = $display;
1156 if ($display === '') {
1157 $option->text = $value;
1158 }
1159
1160 if ((string) $value == (string) $this->selectedvalue ||
1161 (is_array($this->selectedvalue) && in_array($value, $this->selectedvalue))) {
1162 $option->selected = 'selected';
1163 }
1164
1165 $optgroup->options[] = $option;
1166 }
1167
1168 $this->options[] = $optgroup;
1169 }
1170 } else {
1171 $inoptgroup = false;
1172 $optgroup = false;
1173
1174 foreach ($options as $value => $display) {
1175 if ($display == '--') { /// we are ending previous optgroup
1176 // $this->options[] = $optgroup;
1177 $inoptgroup = false;
1178 continue;
1179 } else if (substr($display,0,2) == '--') { /// we are starting a new optgroup
1180 if (!empty($optgroup->options)) {
1181 $this->options[] = $optgroup;
1182 }
1183
1184 $optgroup = new html_select_optgroup();
1185 $optgroup->text = substr($display,2); // stripping the --
1186
1187 $inoptgroup = true; /// everything following will be in an optgroup
1188 continue;
1189
1190 } else {
1191 // Add $nothing option if there are not optgroups
1192 if ($this->nothinglabel && empty($this->options[0]) && !$inoptgroup) {
1193 $nothingoption = new html_select_option();
1194 $nothingoption->value = 0;
1195 if (!empty($this->nothingvalue)) {
1196 $nothingoption->value = $this->nothingvalue;
1197 }
1198 $nothingoption->text = $this->nothinglabel;
1199 $this->options = array($nothingoption) + $this->options;
1200 }
1201
1202 $option = new html_select_option();
1203 $option->text = $display;
1204
1205 if ($display === '') {
1206 $option->text = $value;
1207 }
1208
1209 if ((string) $value == (string) $this->selectedvalue ||
1210 (is_array($this->selectedvalue) && in_array($value, $this->selectedvalue))) {
1211 $option->selected = 'selected';
1212 }
1213
1214 $option->value = s($value);
1215
1216 if ($inoptgroup) {
1217 $optgroup->options[] = $option;
1218 } else {
1219 $this->options[] = $option;
1220 }
1221 }
1222 }
1223
1224 if ($optgroup) {
1225 $this->options[] = $optgroup;
1226 }
1227 }
1228 }
1229}
1230
34059565 1231
7b1f2c82 1232/**
1233 * This class represents a select option element
1234 *
1235 * @copyright 2009 Nicolas Connault
1236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1237 * @since Moodle 2.0
1238 */
7a5c78e0 1239class html_select_option extends labelled_html_component {
7b1f2c82 1240 /**
1241 * @var string $value The value of this option (will be sent with form)
1242 */
1243 public $value;
1244 /**
1245 * @var string $text The display value of the option
1246 */
1247 public $text;
1248 /**
1249 * @var boolean $selected Whether or not this option is selected
1250 */
1251 public $selected = false;
a4998d01 1252 /**
1253 * @var boolean $disabled Whether or not this option is disabled
1254 */
1255 public $disabled = false;
7b1f2c82 1256
1257 public function __construct() {
1258 $this->label = new html_label();
1259 }
1260
1261 /**
6dd7d7f0 1262 * @see html_component::prepare()
7b1f2c82 1263 * @return void
1264 */
34059565 1265 public function prepare(renderer_base $output, moodle_page $page, $target) {
c7e4c7b7 1266 if (empty($this->text) && (string)$this->text!=='0') {
7b1f2c82 1267 throw new coding_exception('html_select_option requires a $text value.');
1268 }
1269
1270 if (empty($this->label->text)) {
1271 $this->set_label($this->text);
1272 } else if (!($this->label instanceof html_label)) {
1273 $this->set_label($this->label);
1274 }
1275 if (empty($this->id)) {
1276 $this->generate_id();
1277 }
1278
34059565 1279 parent::prepare($output, $page, $target);
7b1f2c82 1280 }
1281
1282 /**
1283 * Shortcut for making a checkbox-ready option
1284 * @param string $value The value of the checkbox
1285 * @param boolean $checked
1286 * @param string $label
1287 * @param string $alt
1288 * @return html_select_option A component ready for $OUTPUT->checkbox()
1289 */
8fa16366 1290 public static function make_checkbox($value, $checked, $label, $alt='') {
7b1f2c82 1291 $checkbox = new html_select_option();
1292 $checkbox->value = $value;
1293 $checkbox->selected = $checked;
1294 $checkbox->text = $label;
1295 $checkbox->label->text = $label;
1296 $checkbox->alt = $alt;
1297 return $checkbox;
1298 }
1299}
1300
34059565 1301
7b1f2c82 1302/**
1303 * This class represents a select optgroup element
1304 *
1305 * @copyright 2009 Nicolas Connault
1306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1307 * @since Moodle 2.0
1308 */
6dd7d7f0 1309class html_select_optgroup extends html_component {
7b1f2c82 1310 /**
1311 * @var string $text The display value of the optgroup
1312 */
1313 public $text;
1314 /**
1315 * @var array $options An array of html_select_option objects
1316 */
1317 public $options = array();
1318
34059565 1319 public function prepare(renderer_base $output, moodle_page $page, $target) {
7b1f2c82 1320 if (empty($this->text)) {
1321 throw new coding_exception('html_select_optgroup requires a $text value.');
1322 }
1323 if (empty($this->options)) {
1324 throw new coding_exception('html_select_optgroup requires at least one html_select_option object');
1325 }
34059565 1326 parent::prepare($output, $page, $target);
7b1f2c82 1327 }
1328}
1329
34059565 1330
7b1f2c82 1331/**
1332 * This class represents an input field
1333 *
1334 * @copyright 2009 Nicolas Connault
1335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1336 * @since Moodle 2.0
1337 */
7a5c78e0 1338class html_field extends labelled_html_component {
7b1f2c82 1339 /**
1340 * @var string $name The name attribute of the field
1341 */
1342 public $name;
1343 /**
1344 * @var string $value The value attribute of the field
1345 */
1346 public $value;
1347 /**
1348 * @var string $type The type attribute of the field (text, submit, checkbox etc)
1349 */
1350 public $type;
1351 /**
1352 * @var string $maxlength The maxlength attribute of the field (only applies to text type)
1353 */
1354 public $maxlength;
5fc6d585 1355 /**
1356 * @var boolean $disabled Whether or not this field is disabled
1357 */
1358 public $disabled = false;
7b1f2c82 1359
1360 public function __construct() {
1361 $this->label = new html_label();
1362 }
1363
1364 /**
6dd7d7f0 1365 * @see html_component::prepare()
7b1f2c82 1366 * @return void
1367 */
34059565 1368 public function prepare(renderer_base $output, moodle_page $page, $target) {
7b1f2c82 1369 if (empty($this->style)) {
1370 $this->style = 'width: 4em;';
1371 }
1372 if (empty($this->id)) {
1373 $this->generate_id();
1374 }
34059565 1375 parent::prepare($output, $page, $target);
7b1f2c82 1376 }
1377
1378 /**
1379 * Shortcut for creating a text input component.
1380 * @param string $name The name of the text field
1381 * @param string $value The value of the text field
1382 * @param string $alt The info to be inserted in the alt tag
1383 * @param int $maxlength Sets the maxlength attribute of the field. Not set by default
1384 * @return html_field The field component
1385 */
a0ead5eb 1386 public static function make_text($name='unnamed', $value='', $alt='', $maxlength=0) {
7b1f2c82 1387 $field = new html_field();
1388 if (empty($alt)) {
a0ead5eb 1389 $alt = $name;
7b1f2c82 1390 }
1391 $field->type = 'text';
1392 $field->name = $name;
1393 $field->value = $value;
1394 $field->alt = $alt;
1395 $field->maxlength = $maxlength;
1396 return $field;
1397 }
1398}
1399
34059565 1400
7b1f2c82 1401/**
1402 * Holds all the information required to render a <table> by
78946b9b 1403 * {@see core_renderer::table()} or by an overridden version of that
7b1f2c82 1404 * method in a subclass.
1405 *
1406 * Example of usage:
1407 * $t = new html_table();
1408 * ... // set various properties of the object $t as described below
1409 * echo $OUTPUT->table($t);
1410 *
1411 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1413 * @since Moodle 2.0
1414 */
7a5c78e0 1415class html_table extends labelled_html_component {
7b1f2c82 1416 /**
a0ead5eb 1417 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1418 * can be passed instead of an array of strings.
7b1f2c82 1419 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1420 *
1421 * Example of usage:
1422 * $t->head = array('Student', 'Grade');
1423 */
1424 public $head;
1425 /**
1426 * @var array can be used to make a heading span multiple columns
1427 *
1428 * Example of usage:
1429 * $t->headspan = array(2,1);
1430 *
1431 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1432 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1433 */
1434 public $headspan;
1435 /**
1436 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1437 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1438 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1439 *
beb56299 1440 * Examples of usage:
1441 * $t->align = array(null, 'right');
1442 * or
1443 * $t->align[1] = 'right';
1444 *
d9c8f425 1445 */
beb56299 1446 public $align;
d9c8f425 1447 /**
beb56299 1448 * @var array of column sizes. The value is used as CSS 'size' property.
1449 *
1450 * Examples of usage:
1451 * $t->size = array('50%', '50%');
1452 * or
1453 * $t->size[1] = '120px';
d9c8f425 1454 */
beb56299 1455 public $size;
d9c8f425 1456 /**
beb56299 1457 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1458 * CSS property 'white-space' to the value 'nowrap' in the given column.
1459 *
1460 * Example of usage:
1461 * $t->wrap = array(null, 'nowrap');
d9c8f425 1462 */
beb56299 1463 public $wrap;
d9c8f425 1464 /**
beb56299 1465 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1466 * $head specified, the string 'hr' (for horizontal ruler) can be used
1467 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1468 *
beb56299 1469 * Example of usage with array of arrays:
1470 * $row1 = array('Harry Potter', '76 %');
1471 * $row2 = array('Hermione Granger', '100 %');
1472 * $t->data = array($row1, $row2);
d9c8f425 1473 *
beb56299 1474 * Example with array of html_table_row objects: (used for more fine-grained control)
1475 * $cell1 = new html_table_cell();
1476 * $cell1->text = 'Harry Potter';
1477 * $cell1->colspan = 2;
1478 * $row1 = new html_table_row();
1479 * $row1->cells[] = $cell1;
1480 * $cell2 = new html_table_cell();
1481 * $cell2->text = 'Hermione Granger';
1482 * $cell3 = new html_table_cell();
1483 * $cell3->text = '100 %';
1484 * $row2 = new html_table_row();
1485 * $row2->cells = array($cell2, $cell3);
1486 * $t->data = array($row1, $row2);
1487 */
1488 public $data;
1489 /**
1490 * @var string width of the table, percentage of the page preferred. Defaults to 80% of the page width.
1491 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1492 */
1493 public $width = null;
1494 /**
1495 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1496 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1497 */
1498 public $tablealign = null;
1499 /**
1500 * @var int padding on each cell, in pixels
1501 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1502 */
1503 public $cellpadding = null;
1504 /**
1505 * @var int spacing between cells, in pixels
1506 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1507 */
1508 public $cellspacing = null;
1509 /**
1510 * @var array classes to add to particular rows, space-separated string.
1511 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1512 * respectively. Class 'lastrow' is added automatically for the last row
1513 * in the table.
d9c8f425 1514 *
beb56299 1515 * Example of usage:
1516 * $t->rowclasses[9] = 'tenth'
1517 */
1518 public $rowclasses;
1519 /**
1520 * @var array classes to add to every cell in a particular column,
1521 * space-separated string. Class 'cell' is added automatically by the renderer.
1522 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1523 * respectively. Class 'lastcol' is added automatically for all last cells
1524 * in a row.
d9c8f425 1525 *
beb56299 1526 * Example of usage:
1527 * $t->colclasses = array(null, 'grade');
d9c8f425 1528 */
beb56299 1529 public $colclasses;
1530 /**
1531 * @var string description of the contents for screen readers.
1532 */
1533 public $summary;
1534 /**
1535 * @var bool true causes the contents of the heading cells to be rotated 90 degrees.
1536 */
1537 public $rotateheaders = false;
319770d7 1538 /**
1539 * @var array $headclasses Array of CSS classes to apply to the table's thead.
1540 */
1541 public $headclasses = array();
1542 /**
1543 * @var array $bodyclasses Array of CSS classes to apply to the table's tbody.
1544 */
1545 public $bodyclasses = array();
1546 /**
1547 * @var array $footclasses Array of CSS classes to apply to the table's tfoot.
1548 */
1549 public $footclasses = array();
a0ead5eb 1550
d9c8f425 1551
1552 /**
6dd7d7f0 1553 * @see html_component::prepare()
beb56299 1554 * @return void
d9c8f425 1555 */
34059565 1556 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 1557 if (!empty($this->align)) {
1558 foreach ($this->align as $key => $aa) {
1559 if ($aa) {
1560 $this->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1561 } else {
1562 $this->align[$key] = '';
1563 }
1564 }
d9c8f425 1565 }
beb56299 1566 if (!empty($this->size)) {
1567 foreach ($this->size as $key => $ss) {
1568 if ($ss) {
1569 $this->size[$key] = 'width:'. $ss .';';
1570 } else {
1571 $this->size[$key] = '';
1572 }
1573 }
d9c8f425 1574 }
beb56299 1575 if (!empty($this->wrap)) {
1576 foreach ($this->wrap as $key => $ww) {
1577 if ($ww) {
1578 $this->wrap[$key] = 'white-space:nowrap;';
1579 } else {
1580 $this->wrap[$key] = '';
1581 }
1582 }
d9c8f425 1583 }
beb56299 1584 if (!empty($this->head)) {
1585 foreach ($this->head as $key => $val) {
1586 if (!isset($this->align[$key])) {
1587 $this->align[$key] = '';
1588 }
1589 if (!isset($this->size[$key])) {
1590 $this->size[$key] = '';
1591 }
1592 if (!isset($this->wrap[$key])) {
1593 $this->wrap[$key] = '';
d9c8f425 1594 }
1595
d9c8f425 1596 }
beb56299 1597 }
1598 if (empty($this->classes)) { // must be done before align
1599 $this->set_classes(array('generaltable'));
1600 }
1601 if (!empty($this->tablealign)) {
1602 $this->add_class('boxalign' . $this->tablealign);
1603 }
1604 if (!empty($this->rotateheaders)) {
1605 $this->add_class('rotateheaders');
d9c8f425 1606 } else {
beb56299 1607 $this->rotateheaders = false; // Makes life easier later.
1608 }
34059565 1609 parent::prepare($output, $page, $target);
beb56299 1610 }
1611 /**
1612 * @param string $name The name of the variable to set
1613 * @param mixed $value The value to assign to the variable
1614 * @return void
1615 */
1616 public function __set($name, $value) {
1617 if ($name == 'rowclass') {
1618 debugging('rowclass[] has been deprecated for html_table ' .
7b1f2c82 1619 'and should be replaced with rowclasses[]. please fix the code.');
1620 $this->rowclasses = $value;
1621 } else {
1622 parent::__set($name, $value);
d9c8f425 1623 }
d9c8f425 1624 }
d9c8f425 1625}
1626
34059565 1627
d9c8f425 1628/**
7b1f2c82 1629 * Component representing a table row.
d9c8f425 1630 *
1631 * @copyright 2009 Nicolas Connault
1632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1633 * @since Moodle 2.0
1634 */
6dd7d7f0 1635class html_table_row extends html_component {
d9c8f425 1636 /**
7b1f2c82 1637 * @var array $cells Array of html_table_cell objects
d9c8f425 1638 */
7b1f2c82 1639 public $cells = array();
d9c8f425 1640
beb56299 1641 /**
6dd7d7f0 1642 * @see lib/html_component#prepare()
beb56299 1643 * @return void
1644 */
34059565
PS
1645 public function prepare(renderer_base $output, moodle_page $page, $target) {
1646 parent::prepare($output, $page, $target);
d9c8f425 1647 }
a0ead5eb 1648
54a007e8 1649 /**
a019627a 1650 * Shortcut method for creating a row with an array of cells. Converts cells to html_table_cell objects.
54a007e8 1651 * @param array $cells
1652 * @return html_table_row
1653 */
8fa16366 1654 public static function make($cells=array()) {
54a007e8 1655 $row = new html_table_row();
a019627a 1656 foreach ($cells as $celltext) {
1657 if (!($celltext instanceof html_table_cell)) {
1658 $cell = new html_table_cell();
1659 $cell->text = $celltext;
1660 $row->cells[] = $cell;
1661 } else {
1662 $row->cells[] = $celltext;
1663 }
1664 }
54a007e8 1665 return $row;
1666 }
d9c8f425 1667}
1668
34059565 1669
d9c8f425 1670/**
7b1f2c82 1671 * Component representing a table cell.
d9c8f425 1672 *
1673 * @copyright 2009 Nicolas Connault
1674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1675 * @since Moodle 2.0
1676 */
6dd7d7f0 1677class html_table_cell extends html_component {
d9c8f425 1678 /**
7b1f2c82 1679 * @var string $text The contents of the cell
d9c8f425 1680 */
7b1f2c82 1681 public $text;
d9c8f425 1682 /**
7b1f2c82 1683 * @var string $abbr Abbreviated version of the contents of the cell
d9c8f425 1684 */
7b1f2c82 1685 public $abbr = '';
d9c8f425 1686 /**
7b1f2c82 1687 * @var int $colspan Number of columns this cell should span
d9c8f425 1688 */
7b1f2c82 1689 public $colspan = '';
d9c8f425 1690 /**
7b1f2c82 1691 * @var int $rowspan Number of rows this cell should span
d9c8f425 1692 */
7b1f2c82 1693 public $rowspan = '';
d9c8f425 1694 /**
7b1f2c82 1695 * @var string $scope Defines a way to associate header cells and data cells in a table
d9c8f425 1696 */
7b1f2c82 1697 public $scope = '';
1ae3767a 1698 /**
1699 * @var boolean $header Whether or not this cell is a header cell
1700 */
a4998d01 1701 public $header = null;
d9c8f425 1702
1703 /**
6dd7d7f0 1704 * @see lib/html_component#prepare()
d9c8f425 1705 * @return void
1706 */
34059565 1707 public function prepare(renderer_base $output, moodle_page $page, $target) {
54a007e8 1708 if ($this->header && empty($this->scope)) {
1709 $this->scope = 'col';
1710 }
34059565 1711 parent::prepare($output, $page, $target);
d9c8f425 1712 }
1713}
1714
34059565 1715
d9c8f425 1716/**
7b1f2c82 1717 * Component representing a XHTML link.
d9c8f425 1718 *
beb56299 1719 * @copyright 2009 Nicolas Connault
d9c8f425 1720 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1721 * @since Moodle 2.0
1722 */
6dd7d7f0 1723class html_link extends html_component {
d9c8f425 1724 /**
7b1f2c82 1725 * URL can be simple text or a moodle_url object
1726 * @var mixed $url
d9c8f425 1727 */
beb56299 1728 public $url;
d9c8f425 1729
1730 /**
5d77fc1d 1731 * @var string $text The HTML text that will appear between the link tags
d9c8f425 1732 */
5d77fc1d 1733 public $text = '';
d9c8f425 1734
1735 /**
a0ead5eb 1736 * @var boolean $disabled Whether or not this link is disabled (will be rendered as plain text)
1737 */
1738 public $disabled = false;
1739
284943fc 1740 /**
1741 * @var boolean $disableifcurrent Whether or not this link should be disabled if it the same as the current page
1742 */
1743 public $disableifcurrent = false;
1744
5d77fc1d
PS
1745 /**
1746 * New link constructor.
1747 *
1748 * @param moodle_url|string $url url of the image
1749 * @param array $options link attributes such as title, id, disabled, disableifcurrent, etc.
1750 */
1751 public function __construct($url = null, $text = '', array $options = null) {
1752 parent::__construct($options);
1753
1754 if (is_null($url)) {
1755 // to be filled later
1756
1757 } else if ($url instanceof moodle_url) {
4bcc5118 1758 $this->url = clone($url);
5d77fc1d
PS
1759
1760 } else if (is_string($url)) {
4bcc5118 1761 $this->url = new moodle_url($url);
5d77fc1d
PS
1762
1763 } else {
1764 throw new coding_style_exception('Image can be constructed only from moodle_url or string url.');
1765 }
1766
1767 $this->text = $text;
1768 }
1769
a0ead5eb 1770 /**
6dd7d7f0 1771 * @see lib/html_component#prepare() Disables the link if it links to the current page.
beb56299 1772 * @return void
d9c8f425 1773 */
34059565 1774 public function prepare(renderer_base $output, moodle_page $page, $target) {
7b1f2c82 1775 // We can't accept an empty text value
5d77fc1d 1776 if ($this->text === '' or is_null($this->text)) { // 0 is valid value, do not use empty()
7b1f2c82 1777 throw new coding_exception('A html_link must have a descriptive text value!');
beb56299 1778 }
1779
a0ead5eb 1780 if (!($this->url instanceof moodle_url)) {
1781 $this->url = new moodle_url($this->url);
1782 }
1783
5d77fc1d 1784 if ($this->disableifcurrent and $this->url->compare($page->url, URL_MATCH_PARAMS)) {
a0ead5eb 1785 $this->disabled = true;
1786 }
5d77fc1d 1787
34059565 1788 parent::prepare($output, $page, $target);
beb56299 1789 }
d9c8f425 1790
1791 /**
7b1f2c82 1792 * Shortcut for creating a link component.
1793 * @param mixed $url String or moodle_url
1794 * @param string $text The text of the link
1795 * @return html_link The link component
d9c8f425 1796 */
8fa16366 1797 public static function make($url, $text) {
5d77fc1d 1798 return new html_link($url, $text);
d9c8f425 1799 }
1800}
1801
34059565 1802
d9c8f425 1803/**
7b1f2c82 1804 * Component representing a XHTML button (input of type 'button').
1805 * The renderer will either output it as a button with an onclick event,
1806 * or as a form with hidden inputs.
d9c8f425 1807 *
beb56299 1808 * @copyright 2009 Nicolas Connault
d9c8f425 1809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1810 * @since Moodle 2.0
1811 */
7a5c78e0 1812class html_button extends labelled_html_component {
d9c8f425 1813 /**
7b1f2c82 1814 * @var string $text
d9c8f425 1815 */
7b1f2c82 1816 public $text;
d9c8f425 1817
d9c8f425 1818 /**
7b1f2c82 1819 * @var boolean $disabled Whether or not this button is disabled
d9c8f425 1820 */
beb56299 1821 public $disabled = false;
7b1f2c82 1822
d9c8f425 1823 /**
6dd7d7f0 1824 * @see lib/html_component#prepare()
7b1f2c82 1825 * @return void
d9c8f425 1826 */
34059565 1827 public function prepare(renderer_base $output, moodle_page $page, $target) {
7b1f2c82 1828 $this->add_class('singlebutton');
1829
1830 if (empty($this->text)) {
b65bfc3e 1831 $this->text = get_string('submit');
7b1f2c82 1832 }
1833
1834 if ($this->disabled) {
1835 $this->disabled = 'disabled';
1836 }
1837
34059565 1838 parent::prepare($output, $page, $target);
7b1f2c82 1839 }
1840}
1841
1842/**
1843 * Component representing an image.
1844 *
1845 * @copyright 2009 Nicolas Connault
1846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1847 * @since Moodle 2.0
1848 */
7a5c78e0 1849class html_image extends labelled_html_component {
d9c8f425 1850 /**
7b1f2c82 1851 * @var string $src The path to the image being used
d9c8f425 1852 */
7b1f2c82 1853 public $src;
1ba862ec
PS
1854 /**
1855 * @var int $width of image
1856 */
1857 public $width;
1858 /**
1859 * @var int $height of image
1860 */
1861 public $height;
7b1f2c82 1862
8fa16366
PS
1863 /**
1864 * New image constructor.
1865 *
1866 * @param moodle_url|string $url url of the image
1867 * @param array $options image attributes such as title, id, alt, widht, height
1868 */
4bcc5118 1869 public function __construct($src = null, array $options = null) {
8fa16366
PS
1870 parent::__construct($options);
1871
4bcc5118 1872 if (is_null($src)) {
8fa16366
PS
1873 // to be filled later
1874
4bcc5118
PS
1875 } else if ($src instanceof moodle_url) {
1876 $this->src = clone($src);
8fa16366 1877
4bcc5118
PS
1878 } else if (is_string($src)) {
1879 $this->src = new moodle_url($src);
8fa16366
PS
1880
1881 } else {
1882 throw new coding_style_exception('Image can be constructed only from moodle_url or string url.');
1883 }
1884 }
1885
d9c8f425 1886 /**
6dd7d7f0 1887 * @see lib/html_component#prepare()
7b1f2c82 1888 * @return void
d9c8f425 1889 */
34059565 1890 public function prepare(renderer_base $output, moodle_page $page, $target) {
b65bfc3e 1891 if (empty($this->src)) {
1892 throw new coding_exception('html_image requires a $src value (moodle_url).');
1893 }
1894
1ba862ec 1895 // no general class here, use custom class instead or img element directly in css selectors
34059565 1896 parent::prepare($output, $page, $target);
8fa16366
PS
1897
1898 if ($this->alt === '') {
1899 // needs to be set for accessibility reasons
1900 $this->alt = HTML_ATTR_EMPTY;
1901 }
7b1f2c82 1902 }
1903}
1904
34059565 1905
7b1f2c82 1906/**
1907 * Component representing a textarea.
1908 *
1909 * @copyright 2009 Nicolas Connault
1910 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 * @since Moodle 2.0
1912 */
6dd7d7f0 1913class html_textarea extends html_component {
d9c8f425 1914 /**
7b1f2c82 1915 * @param string $name Name to use for the textarea element.
d9c8f425 1916 */
7b1f2c82 1917 public $name;
d9c8f425 1918 /**
7b1f2c82 1919 * @param string $value Initial content to display in the textarea.
d9c8f425 1920 */
7b1f2c82 1921 public $value;
d9c8f425 1922 /**
7b1f2c82 1923 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
d9c8f425 1924 */
7b1f2c82 1925 public $rows;
beb56299 1926 /**
7b1f2c82 1927 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
beb56299 1928 */
7b1f2c82 1929 public $cols;
1930 /**
1931 * @param bool $usehtmleditor Enables the use of the htmleditor for this field.
1932 */
1933 public $usehtmleditor;
d9c8f425 1934
1935 /**
6dd7d7f0 1936 * @see lib/html_component#prepare()
d9c8f425 1937 * @return void
1938 */
34059565 1939 public function prepare(renderer_base $output, moodle_page $page, $target) {
7b1f2c82 1940 $this->add_class('form-textarea');
d9c8f425 1941
beb56299 1942 if (empty($this->id)) {
7b1f2c82 1943 $this->id = "edit-$this->name";
d9c8f425 1944 }
beb56299 1945
7b1f2c82 1946 if ($this->usehtmleditor) {
1947 editors_head_setup();
1948 $editor = get_preferred_texteditor(FORMAT_HTML);
1949 $editor->use_editor($this->id, array('legacy'=>true));
1950 $this->value = htmlspecialchars($value);
d9c8f425 1951 }
beb56299 1952
34059565 1953 parent::prepare($output, $page, $target);
d9c8f425 1954 }
7b1f2c82 1955}
beb56299 1956
34059565 1957
7b1f2c82 1958/**
1959 * Component representing a simple form wrapper. Its purpose is mainly to enclose
1960 * a submit input with the appropriate action and hidden inputs.
1961 *
1962 * @copyright 2009 Nicolas Connault
1963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1964 * @since Moodle 2.0
1965 */
6dd7d7f0 1966class html_form extends html_component {
d9c8f425 1967 /**
7b1f2c82 1968 * @var string $method post or get
d9c8f425 1969 */
7b1f2c82 1970 public $method = 'post';
d9c8f425 1971 /**
7b1f2c82 1972 * If a string is given, it will be converted to a moodle_url during prepare()
1973 * @var mixed $url A moodle_url including params or a string
d9c8f425 1974 */
7b1f2c82 1975 public $url;
7b1f2c82 1976 /**
1977 * @var boolean $showbutton If true, the submit button will always be shown even if JavaScript is available
1978 */
1979 public $showbutton = false;
1980 /**
1981 * @var string $targetwindow The name of the target page to open the linked page in.
1982 */
1983 public $targetwindow = 'self';
1984 /**
1985 * @var html_button $button A submit button
1986 */
1987 public $button;
b65bfc3e 1988 /**
1989 * @var boolean $jssubmitaction If true, the submit button will be hidden when JS is enabled
1990 */
1991 public $jssubmitaction = false;
d9c8f425 1992 /**
7b1f2c82 1993 * Constructor: sets up the other components in case they are needed
1994 * @return void
d9c8f425 1995 */
3cd5305f
PS
1996 public function __construct(array $options = null) {
1997 parent::__construct($options);
7b1f2c82 1998 $this->button = new html_button();
d894edd4 1999 $this->button->text = get_string('go');
beb56299 2000 }
2001
d9c8f425 2002 /**
6dd7d7f0 2003 * @see lib/html_component#prepare()
7b1f2c82 2004 * @return void
d9c8f425 2005 */
34059565 2006 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 2007
7b1f2c82 2008 if (empty($this->url)) {
2009 throw new coding_exception('A html_form must have a $url value (string or moodle_url).');
beb56299 2010 }
2011
d894edd4
PS
2012 if (is_string($this->url)) {
2013 $this->url = new moodle_url($this->url);
beb56299 2014 }
2015
7b1f2c82 2016 if ($this->method == 'post') {
d894edd4 2017 // automatic CSRF protection
7b1f2c82 2018 $this->url->param('sesskey', sesskey());
beb56299 2019 }
d9c8f425 2020
34059565 2021 parent::prepare($output, $page, $target);
7b1f2c82 2022 }
d894edd4
PS
2023}
2024
2025
7b1f2c82 2026/**
2027 * Component representing a list.
2028 *
2029 * The advantage of using this object instead of a flat array is that you can load it
2030 * with metadata (CSS classes, event handlers etc.) which can be used by the renderers.
2031 *
2032 * @copyright 2009 Nicolas Connault
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2034 * @since Moodle 2.0
2035 */
6dd7d7f0 2036class html_list extends html_component {
d9c8f425 2037
7b1f2c82 2038 /**
2039 * @var array $items An array of html_list_item or html_list objects
2040 */
2041 public $items = array();
d9c8f425 2042
7b1f2c82 2043 /**
2044 * @var string $type The type of list (ordered|unordered), definition type not yet supported
2045 */
2046 public $type = 'unordered';
d9c8f425 2047
b65bfc3e 2048 /**
2049 * @var string $text An optional descriptive text for the list. Will be output as a list item before opening the new list
2050 */
2051 public $text = false;
2052
7b1f2c82 2053 /**
6dd7d7f0 2054 * @see lib/html_component#prepare()
7b1f2c82 2055 * @return void
2056 */
34059565
PS
2057 public function prepare(renderer_base $output, moodle_page $page, $target) {
2058 parent::prepare($output, $page, $target);
d9c8f425 2059 }
2060
2061 /**
7b1f2c82 2062 * This function takes a nested array of data and maps it into this list's $items array
2063 * as proper html_list_item and html_list objects, with appropriate metadata.
2064 *
2065 * @param array $tree A nested array (array keys are ignored);
2066 * @param int $row Used in identifying the iteration level and in ul classes
beb56299 2067 * @return void
d9c8f425 2068 */
7b1f2c82 2069 public function load_data($tree, $level=0) {
beb56299 2070
7b1f2c82 2071 $this->add_class("list-$level");
beb56299 2072
b65bfc3e 2073 $i = 1;
7b1f2c82 2074 foreach ($tree as $key => $element) {
2075 if (is_array($element)) {
2076 $newhtmllist = new html_list();
b65bfc3e 2077 $newhtmllist->type = $this->type;
7b1f2c82 2078 $newhtmllist->load_data($element, $level + 1);
b65bfc3e 2079 $newhtmllist->text = $key;
7b1f2c82 2080 $this->items[] = $newhtmllist;
2081 } else {
2082 $listitem = new html_list_item();
2083 $listitem->value = $element;
b65bfc3e 2084 $listitem->add_class("list-item-$level-$i");
7b1f2c82 2085 $this->items[] = $listitem;
beb56299 2086 }
b65bfc3e 2087 $i++;
beb56299 2088 }
2089 }
d9c8f425 2090
2091 /**
7b1f2c82 2092 * Adds a html_list_item or html_list to this list.
2093 * If the param is a string, a html_list_item will be added.
2094 * @param mixed $item String, html_list or html_list_item object
d9c8f425 2095 * @return void
2096 */
7b1f2c82 2097 public function add_item($item) {
2098 if ($item instanceof html_list_item || $item instanceof html_list) {
2099 $this->items[] = $item;
2100 } else {
2101 $listitem = new html_list_item();
2102 $listitem->value = $item;
2103 $this->items[] = $item;
beb56299 2104 }
d9c8f425 2105 }
7b1f2c82 2106}
d9c8f425 2107
34059565 2108
7b1f2c82 2109/**
2110 * Component representing a list item.
2111 *
2112 * @copyright 2009 Nicolas Connault
2113 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2114 * @since Moodle 2.0
2115 */
6dd7d7f0 2116class html_list_item extends html_component {
d9c8f425 2117 /**
7b1f2c82 2118 * @var string $value The value of the list item
d9c8f425 2119 */
7b1f2c82 2120 public $value;
d9c8f425 2121
7b1f2c82 2122 /**
6dd7d7f0 2123 * @see lib/html_component#prepare()
7b1f2c82 2124 * @return void
2125 */
34059565
PS
2126 public function prepare(renderer_base $output, moodle_page $page, $target) {
2127 parent::prepare($output, $page, $target);
d9c8f425 2128 }
2129}
2130
34059565 2131
54a007e8 2132/**
a0ead5eb 2133 * Component representing a span element. It has no special attributes, so
54a007e8 2134 * it is very low-level and can be used for styling and JS actions.
2135 *
2136 * @copyright 2009 Nicolas Connault
2137 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2138 * @since Moodle 2.0
2139 */
6dd7d7f0 2140class html_span extends html_component {
54a007e8 2141 /**
2142 * @var string $text The contents of the span
2143 */
2144 public $contents;
2145 /**
6dd7d7f0 2146 * @see lib/html_component#prepare()
54a007e8 2147 * @return void
2148 */
34059565
PS
2149 public function prepare(renderer_base $output, moodle_page $page, $target) {
2150 parent::prepare($output, $page, $target);
54a007e8 2151 }
2152}
2153
7b1f2c82 2154/// Complex components aggregating simpler components
2155
34059565 2156
d9c8f425 2157/**
beb56299 2158 * Component representing a paging bar.
d9c8f425 2159 *
2160 * @copyright 2009 Nicolas Connault
2161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2162 * @since Moodle 2.0
2163 */
6dd7d7f0 2164class moodle_paging_bar extends html_component {
d9c8f425 2165 /**
beb56299 2166 * @var int $maxdisplay The maximum number of pagelinks to display
d9c8f425 2167 */
beb56299 2168 public $maxdisplay = 18;
d9c8f425 2169 /**
beb56299 2170 * @var int $totalcount post or get
d9c8f425 2171 */
beb56299 2172 public $totalcount;
d9c8f425 2173 /**
beb56299 2174 * @var int $page The page you are currently viewing
d9c8f425 2175 */
beb56299 2176 public $page = 0;
d9c8f425 2177 /**
beb56299 2178 * @var int $perpage The number of entries that should be shown per page
d9c8f425 2179 */
beb56299 2180 public $perpage;
d9c8f425 2181 /**
beb56299 2182 * @var string $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
2183 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 2184 */
beb56299 2185 public $baseurl;
d9c8f425 2186 /**
beb56299 2187 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 2188 */
beb56299 2189 public $pagevar = 'page';
beb56299 2190 /**
2191 * @var html_link $previouslink A HTML link representing the "previous" page
2192 */
2193 public $previouslink = null;
2194 /**
2195 * @var html_link $nextlink A HTML link representing the "next" page
2196 */
2197 public $nextlink = null;
2198 /**
2199 * @var html_link $firstlink A HTML link representing the first page
2200 */
2201 public $firstlink = null;
2202 /**
2203 * @var html_link $lastlink A HTML link representing the last page
2204 */
2205 public $lastlink = null;
2206 /**
2207 * @var array $pagelinks An array of html_links. One of them is just a string: the current page
2208 */
2209 public $pagelinks = array();
d9c8f425 2210
2211 /**
6dd7d7f0 2212 * @see lib/html_component#prepare()
d9c8f425 2213 * @return void
2214 */
34059565 2215 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 2216 if (!isset($this->totalcount) || is_null($this->totalcount)) {
beb56299 2217 throw new coding_exception('moodle_paging_bar requires a totalcount value.');
2218 }
2219 if (!isset($this->page) || is_null($this->page)) {
2220 throw new coding_exception('moodle_paging_bar requires a page value.');
2221 }
2222 if (empty($this->perpage)) {
2223 throw new coding_exception('moodle_paging_bar requires a perpage value.');
2224 }
2225 if (empty($this->baseurl)) {
2226 throw new coding_exception('moodle_paging_bar requires a baseurl value.');
2227 }
2228 if (!($this->baseurl instanceof moodle_url)) {
2229 $this->baseurl = new moodle_url($this->baseurl);
2230 }
d9c8f425 2231
beb56299 2232 if ($this->totalcount > $this->perpage) {
2233 $pagenum = $this->page - 1;
d9c8f425 2234
beb56299 2235 if ($this->page > 0) {
2236 $this->previouslink = new html_link();
2237 $this->previouslink->add_class('previous');
2238 $this->previouslink->url = clone($this->baseurl);
2239 $this->previouslink->url->param($this->pagevar, $pagenum);
2240 $this->previouslink->text = get_string('previous');
2241 }
d9c8f425 2242
beb56299 2243 if ($this->perpage > 0) {
2244 $lastpage = ceil($this->totalcount / $this->perpage);
2245 } else {
2246 $lastpage = 1;
2247 }
2248
2249 if ($this->page > 15) {
2250 $startpage = $this->page - 10;
2251
2252 $this->firstlink = new html_link();
2253 $this->firstlink->url = clone($this->baseurl);
2254 $this->firstlink->url->param($this->pagevar, 0);
2255 $this->firstlink->text = 1;
2256 $this->firstlink->add_class('first');
2257 } else {
2258 $startpage = 0;
2259 }
2260
2261 $currpage = $startpage;
2262 $displaycount = $displaypage = 0;
2263
2264 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2265 $displaypage = $currpage + 1;
2266
f43cdceb 2267 if ($this->page == $currpage) {
beb56299 2268 $this->pagelinks[] = $displaypage;
2269 } else {
2270 $pagelink = new html_link();
2271 $pagelink->url = clone($this->baseurl);
2272 $pagelink->url->param($this->pagevar, $currpage);
2273 $pagelink->text = $displaypage;
2274 $this->pagelinks[] = $pagelink;
2275 }
2276
2277 $displaycount++;
2278 $currpage++;
2279 }
2280
2281 if ($currpage < $lastpage) {
2282 $lastpageactual = $lastpage - 1;
2283 $this->lastlink = new html_link();
2284 $this->lastlink->url = clone($this->baseurl);
2285 $this->lastlink->url->param($this->pagevar, $lastpageactual);
2286 $this->lastlink->text = $lastpage;
2287 $this->lastlink->add_class('last');
2288 }
2289
2290 $pagenum = $this->page + 1;
2291
2292 if ($pagenum != $displaypage) {
2293 $this->nextlink = new html_link();
2294 $this->nextlink->url = clone($this->baseurl);
2295 $this->nextlink->url->param($this->pagevar, $pagenum);
2296 $this->nextlink->text = get_string('next');
2297 $this->nextlink->add_class('next');
2298 }
d9c8f425 2299 }
2300 }
d9c8f425 2301
2302 /**
beb56299 2303 * Shortcut for initialising a moodle_paging_bar with only the required params.
2304 *
2305 * @param int $totalcount Thetotal number of entries available to be paged through
2306 * @param int $page The page you are currently viewing
2307 * @param int $perpage The number of entries that should be shown per page
2308 * @param mixed $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
2309 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 2310 */
8fa16366 2311 public static function make($totalcount, $page, $perpage, $baseurl) {
beb56299 2312 $pagingbar = new moodle_paging_bar();
2313 $pagingbar->totalcount = $totalcount;
2314 $pagingbar->page = $page;
2315 $pagingbar->perpage = $perpage;
2316 $pagingbar->baseurl = $baseurl;
2317 return $pagingbar;
d9c8f425 2318 }
2319}
2320
34059565 2321
d9c8f425 2322/**
beb56299 2323 * This class represents how a block appears on a page.
d9c8f425 2324 *
beb56299 2325 * During output, each block instance is asked to return a block_contents object,
2326 * those are then passed to the $OUTPUT->block function for display.
2327 *
2328 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2329 *
2330 * Other block-like things that need to appear on the page, for example the
2331 * add new block UI, are also represented as block_contents objects.
2332 *
2333 * @copyright 2009 Tim Hunt
d9c8f425 2334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2335 * @since Moodle 2.0
2336 */
6dd7d7f0 2337class block_contents extends html_component {
beb56299 2338 /** @var int used to set $skipid. */
2339 protected static $idcounter = 1;
2340
2341 const NOT_HIDEABLE = 0;
2342 const VISIBLE = 1;
2343 const HIDDEN = 2;
2344
d9c8f425 2345 /**
beb56299 2346 * @param integer $skipid All the blocks (or things that look like blocks)
2347 * printed on a page are given a unique number that can be used to construct
2348 * id="" attributes. This is set automatically be the {@link prepare()} method.
2349 * Do not try to set it manually.
d9c8f425 2350 */
beb56299 2351 public $skipid;
d9c8f425 2352
2353 /**
beb56299 2354 * @var integer If this is the contents of a real block, this should be set to
2355 * the block_instance.id. Otherwise this should be set to 0.
2356 */
2357 public $blockinstanceid = 0;
2358
2359 /**
2360 * @var integer if this is a real block instance, and there is a corresponding
2361 * block_position.id for the block on this page, this should be set to that id.
2362 * Otherwise it should be 0.
2363 */
2364 public $blockpositionid = 0;
2365
2366 /**
2367 * @param array $attributes an array of attribute => value pairs that are put on the
2368 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2369 */
2370 public $attributes = array();
2371
2372 /**
2373 * @param string $title The title of this block. If this came from user input,
2374 * it should already have had format_string() processing done on it. This will
2375 * be output inside <h2> tags. Please do not cause invalid XHTML.
2376 */
2377 public $title = '';
2378
2379 /**
2380 * @param string $content HTML for the content
2381 */
2382 public $content = '';
2383
2384 /**
2385 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2386 */
2387 public $footer = '';
2388
2389 /**
2390 * Any small print that should appear under the block to explain to the
2391 * teacher about the block, for example 'This is a sticky block that was
2392 * added in the system context.'
2393 * @var string
2394 */
2395 public $annotation = '';
2396
2397 /**
2398 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2399 * the user can toggle whether this block is visible.
2400 */
2401 public $collapsible = self::NOT_HIDEABLE;
2402
2403 /**
2404 * A (possibly empty) array of editing controls. Each element of this array
2405 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 2406 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 2407 * @var array
2408 */
2409 public $controls = array();
2410
2411 /**
6dd7d7f0 2412 * @see html_component::prepare()
d9c8f425 2413 * @return void
2414 */
34059565 2415 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 2416 $this->skipid = self::$idcounter;
2417 self::$idcounter += 1;
2418 $this->add_class('sideblock');
2419 if (empty($this->blockinstanceid) || !strip_tags($this->title)) {
2420 $this->collapsible = self::NOT_HIDEABLE;
2421 }
2422 if ($this->collapsible == self::HIDDEN) {
2423 $this->add_class('hidden');
2424 }
2425 if (!empty($this->controls)) {
2426 $this->add_class('block_with_controls');
2427 }
34059565 2428 parent::prepare($output, $page, $target);
d9c8f425 2429 }
2430}
beb56299 2431
34059565 2432
beb56299 2433/**
2434 * This class represents a target for where a block can go when it is being moved.
2435 *
2436 * This needs to be rendered as a form with the given hidden from fields, and
2437 * clicking anywhere in the form should submit it. The form action should be
2438 * $PAGE->url.
2439 *
2440 * @copyright 2009 Tim Hunt
2441 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2442 * @since Moodle 2.0
2443 */
6dd7d7f0 2444class block_move_target extends html_component {
beb56299 2445 /**
2446 * List of hidden form fields.
2447 * @var array
2448 */
2449 public $url = array();
2450 /**
2451 * List of hidden form fields.
2452 * @var array
2453 */
2454 public $text = '';
2455}