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