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