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