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