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