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