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