navigation MDL-20204 Now checks an icon implements renderable interface before trying...
[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
000c278c
PS
183/**
184 * Data structure representing an icon.
185 *
186 * @copyright 2010 Petr Skoda
187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
188 * @since Moodle 2.0
189 */
190class pix_icon implements renderable {
191 var $pix;
192 var $component;
193 var $attributes = array();
194
195 /**
196 * Constructor
197 * @param string $pix short icon name
198 * @param string $component component name
199 * @param array $attributes html attributes
200 */
201 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
202 $this->pix = $pix;
203 $this->component = $component;
000c278c
PS
204 $this->attributes = (array)$attributes;
205
206 $this->attributes['alt'] = $alt;
207 if (empty($this->attributes['class'])) {
208 $this->attributes['class'] = 'smallicon';
209 }
210 if (!isset($this->attributes['title'])) {
211 $this->attributes['title'] = $this->attributes['alt'];
212 }
213 }
214}
215
216
3ba60ee1
PS
217/**
218 * Data structure representing a simple form with only one button.
219 *
220 * @copyright 2009 Petr Skoda
221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
222 * @since Moodle 2.0
223 */
224class single_button implements renderable {
574fbea4
PS
225 /**
226 * Target url
227 * @var moodle_url
228 */
3ba60ee1 229 var $url;
574fbea4
PS
230 /**
231 * Button label
232 * @var string
233 */
3ba60ee1 234 var $label;
574fbea4
PS
235 /**
236 * Form submit method
237 * @var string post or get
238 */
3ba60ee1 239 var $method = 'post';
574fbea4
PS
240 /**
241 * Wrapping div class
242 * @var string
243 * */
3ba60ee1 244 var $class = 'singlebutton';
574fbea4
PS
245 /**
246 * True if button disabled, false if normal
247 * @var boolean
248 */
3ba60ee1 249 var $disabled = false;
574fbea4
PS
250 /**
251 * Button tooltip
252 * @var string
253 */
97c10099 254 var $tooltip = null;
574fbea4
PS
255 /**
256 * Form id
257 * @var string
258 */
3ba60ee1 259 var $formid;
574fbea4
PS
260 /**
261 * List of attached actions
262 * @var array of component_action
263 */
3ba60ee1
PS
264 var $actions = array();
265
266 /**
267 * Constructor
574fbea4 268 * @param string|moodle_url $url
3ba60ee1
PS
269 * @param string $label button text
270 * @param string $method get or post submit method
3ba60ee1
PS
271 */
272 public function __construct(moodle_url $url, $label, $method='post') {
273 $this->url = clone($url);
274 $this->label = $label;
275 $this->method = $method;
276 }
277
278 /**
574fbea4 279 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1
PS
280 * The message must be a yes/no question.
281 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
282 * @return void
283 */
284 public function add_confirm_action($confirmmessage) {
20fb563e 285 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
3ba60ee1
PS
286 }
287
574fbea4
PS
288 /**
289 * Add action to the button.
290 * @param component_action $action
291 * @return void
292 */
3ba60ee1
PS
293 public function add_action(component_action $action) {
294 $this->actions[] = $action;
295 }
296}
297
298
a9967cf5
PS
299/**
300 * Simple form with just one select field that gets submitted automatically.
301 * If JS not enabled small go button is printed too.
302 *
303 * @copyright 2009 Petr Skoda
304 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
305 * @since Moodle 2.0
306 */
307class single_select implements renderable {
308 /**
309 * Target url - includes hidden fields
310 * @var moodle_url
311 */
312 var $url;
313 /**
314 * Name of the select element.
315 * @var string
316 */
317 var $name;
318 /**
319 * @var array $options associative array value=>label ex.:
320 * array(1=>'One, 2=>Two)
321 * it is also possible to specify optgroup as complex label array ex.:
322 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
323 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
324 */
325 var $options;
326 /**
327 * Selected option
328 * @var string
329 */
330 var $selected;
331 /**
332 * Nothing selected
333 * @var array
334 */
335 var $nothing;
336 /**
337 * Extra select field attributes
338 * @var array
339 */
340 var $attributes = array();
341 /**
342 * Button label
343 * @var string
344 */
345 var $label = '';
346 /**
347 * Form submit method
348 * @var string post or get
349 */
350 var $method = 'get';
351 /**
352 * Wrapping div class
353 * @var string
354 * */
355 var $class = 'singleselect';
356 /**
357 * True if button disabled, false if normal
358 * @var boolean
359 */
360 var $disabled = false;
361 /**
362 * Button tooltip
363 * @var string
364 */
365 var $tooltip = null;
366 /**
367 * Form id
368 * @var string
369 */
370 var $formid = null;
371 /**
372 * List of attached actions
373 * @var array of component_action
374 */
375 var $helpicon = null;
376 /**
377 * Constructor
378 * @param moodle_url $url form action target, includes hidden fields
379 * @param string $name name of selection field - the changing parameter in url
380 * @param array $options list of options
381 * @param string $selected selected element
382 * @param array $nothing
f8dab966 383 * @param string $formid
a9967cf5 384 */
f8dab966 385 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
a9967cf5
PS
386 $this->url = $url;
387 $this->name = $name;
388 $this->options = $options;
389 $this->selected = $selected;
390 $this->nothing = $nothing;
f8dab966 391 $this->formid = $formid;
a9967cf5
PS
392 }
393
394 /**
395 * Shortcut for adding a JS confirm dialog when the button is clicked.
396 * The message must be a yes/no question.
397 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
398 * @return void
399 */
400 public function add_confirm_action($confirmmessage) {
401 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
402 }
403
404 /**
405 * Add action to the button.
406 * @param component_action $action
407 * @return void
408 */
409 public function add_action(component_action $action) {
410 $this->actions[] = $action;
411 }
f8dab966
PS
412
413 /**
414 * Constructor: sets up the other components in case they are needed
415 * @param string $page The keyword that defines a help page
416 * @param string $title A descriptive text for accesibility only
417 * @param string $component
418 * @param bool $linktext add extra text to icon
419 * @return void
420 */
421 public function set_help_icon($helppage, $title, $component = 'moodle') {
422 $this->helpicon = new help_icon($helppage, $title, $component);
423 }
424
425 /**
426 * Set's select lable
427 * @param string $label
428 * @return void
429 */
430 public function set_label($label) {
431 $this->label = $label;
432 }
a9967cf5
PS
433}
434
435
4d10e579
PS
436/**
437 * Simple URL selection widget description.
438 * @copyright 2009 Petr Skoda
439 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
440 * @since Moodle 2.0
441 */
442class url_select implements renderable {
443 /**
444 * @var array $urls associative array value=>label ex.:
445 * array(1=>'One, 2=>Two)
446 * it is also possible to specify optgroup as complex label array ex.:
447 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
448 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
449 */
450 var $urls;
451 /**
452 * Selected option
453 * @var string
454 */
455 var $selected;
456 /**
457 * Nothing selected
458 * @var array
459 */
460 var $nothing;
461 /**
462 * Extra select field attributes
463 * @var array
464 */
465 var $attributes = array();
466 /**
467 * Button label
468 * @var string
469 */
470 var $label = '';
471 /**
472 * Wrapping div class
473 * @var string
474 * */
475 var $class = 'urlselect';
476 /**
477 * True if button disabled, false if normal
478 * @var boolean
479 */
480 var $disabled = false;
481 /**
482 * Button tooltip
483 * @var string
484 */
485 var $tooltip = null;
486 /**
487 * Form id
488 * @var string
489 */
490 var $formid = null;
491 /**
492 * List of attached actions
493 * @var array of component_action
494 */
495 var $helpicon = null;
496 /**
497 * Constructor
498 * @param array $urls list of options
499 * @param string $selected selected element
500 * @param array $nothing
501 * @param string $formid
502 */
503 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
504 $this->urls = $urls;
505 $this->selected = $selected;
506 $this->nothing = $nothing;
507 $this->formid = $formid;
508 }
509
510 /**
511 * Constructor: sets up the other components in case they are needed
512 * @param string $page The keyword that defines a help page
513 * @param string $title A descriptive text for accesibility only
514 * @param string $component
515 * @param bool $linktext add extra text to icon
516 * @return void
517 */
518 public function set_help_icon($helppage, $title, $component = 'moodle') {
519 $this->helpicon = new help_icon($helppage, $title, $component);
520 }
521
522 /**
523 * Set's select lable
524 * @param string $label
525 * @return void
526 */
527 public function set_label($label) {
528 $this->label = $label;
529 }
530}
531
532
574fbea4
PS
533/**
534 * Data structure describing html link with special action attached.
535 * @copyright 2010 Petr Skoda
536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
537 * @since Moodle 2.0
538 */
539class action_link implements renderable {
540 /**
541 * Href url
542 * @var moodle_url
543 */
544 var $url;
545 /**
546 * Link text
547 * @var string HTML fragment
548 */
549 var $text;
550 /**
551 * HTML attributes
552 * @var array
553 */
554 var $attributes;
555 /**
556 * List of actions attached to link
557 * @var array of component_action
558 */
559 var $actions;
560
561 /**
562 * Constructor
563 * @param string|moodle_url $url
564 * @param string $text HTML fragment
565 * @param component_action $action
11820bac 566 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
567 */
568 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
569 $this->url = clone($url);
570 $this->text = $text;
f14b641b 571 if ($action) {
574fbea4
PS
572 $this->add_action($action);
573 }
574 }
575
576 /**
577 * Add action to the link.
578 * @param component_action $action
579 * @return void
580 */
581 public function add_action(component_action $action) {
582 $this->actions[] = $action;
583 }
c63923bd
PS
584
585 public function add_class($class) {
586 if (empty($this->atribbutes['class'])) {
587 $this->atribbutes['class'] = $class;
588 } else {
589 $this->atribbutes['class'] = $this->atribbutes['class'].' '.$class;
590 }
591 }
574fbea4 592}
3ba60ee1 593
5d0c95a5 594
227255b8 595// ==== HTML writer and helper classes, will be probably moved elsewhere ======
5d0c95a5
PS
596
597/**
598 * Simple html output class
599 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
600 */
601class html_writer {
602 /**
603 * Outputs a tag with attributes and contents
604 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
605 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
606 * @param string $contents What goes between the opening and closing tags
607 * @return string HTML fragment
608 */
609 public static function tag($tagname, array $attributes = null, $contents) {
610 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
611 }
612
613 /**
614 * Outputs an opening tag with attributes
615 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
616 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
617 * @return string HTML fragment
618 */
619 public static function start_tag($tagname, array $attributes = null) {
620 return '<' . $tagname . self::attributes($attributes) . '>';
621 }
622
623 /**
624 * Outputs a closing tag
625 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
626 * @return string HTML fragment
627 */
628 public static function end_tag($tagname) {
629 return '</' . $tagname . '>';
630 }
631
632 /**
633 * Outputs an empty tag with attributes
634 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
635 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
636 * @return string HTML fragment
637 */
638 public static function empty_tag($tagname, array $attributes = null) {
639 return '<' . $tagname . self::attributes($attributes) . ' />';
640 }
641
642 /**
643 * Outputs a HTML attribute and value
644 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
645 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
646 * @return string HTML fragment
647 */
648 public static function attribute($name, $value) {
649 if (is_array($value)) {
650 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
651 }
bf11293a
PS
652 if ($value instanceof moodle_url) {
653 return ' ' . $name . '="' . $value->out() . '"';
654 }
97c10099
PS
655
656 // special case, we do not want these in output
657 if ($value === null) {
658 return '';
5d0c95a5 659 }
97c10099
PS
660
661 // no sloppy trimming here!
662 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
663 }
664
665 /**
666 * Outputs a list of HTML attributes and values
667 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
668 * The values will be escaped with {@link s()}
669 * @return string HTML fragment
670 */
671 public static function attributes(array $attributes = null) {
672 $attributes = (array)$attributes;
673 $output = '';
674 foreach ($attributes as $name => $value) {
675 $output .= self::attribute($name, $value);
676 }
677 return $output;
678 }
679
680 /**
681 * Generates random html element id.
682 * @param string $base
683 * @return string
684 */
685 public static function random_id($base='random') {
686 return uniqid($base);
687 }
0f4c64b7
PS
688
689 /**
690 * Generates a simple html link
691 * @param string|moodle_url $url
692 * @param string $text link txt
693 * @param array $attributes extra html attributes
694 * @return string HTML fragment
695 */
696 public static function link($url, $text, array $attributes = null) {
697 $attributes = (array)$attributes;
698 $attributes['href'] = $url;
699 return self::tag('a', $attributes, $text);
700 }
3ff163c5 701
14dce022
PS
702 /**
703 * generates a simple checkbox with optional label
704 * @param string $name
705 * @param string $value
706 * @param bool $checked
707 * @param string $label
708 * @param array $attributes
709 * @return string html fragment
710 */
711 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
712 $attributes = (array)$attributes;
713 $output = '';
714
715 if ($label !== '' and !is_null($label)) {
716 if (empty($attributes['id'])) {
717 $attributes['id'] = self::random_id('checkbox_');
718 }
719 }
53868425
PS
720 $attributes['type'] = 'checkbox';
721 $attributes['value'] = $value;
722 $attributes['name'] = $name;
14dce022 723 $attributes['checked'] = $checked ? 'selected' : null;
53868425 724
14dce022
PS
725 $output .= self::empty_tag('input', $attributes);
726
727 if ($label !== '' and !is_null($label)) {
728 $output .= self::tag('label', array('for'=>$attributes['id']), $label);
729 }
730
731 return $output;
732 }
733
78bdac64
PS
734 /**
735 * Generates a simple select yes/no form field
736 * @param string $name name of select element
737 * @param bool $selected
738 * @param array $attributes - html select element attributes
739 * @return string HRML fragment
740 */
741 public function select_yes_no($name, $selected=true, array $attributes = null) {
742 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
743 return self::select($options, $name, $selected, null, $attributes);
744 }
745
3ff163c5
PS
746 /**
747 * Generates a simple select form field
6770330d
PS
748 * @param array $options associative array value=>label ex.:
749 * array(1=>'One, 2=>Two)
750 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 751 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 752 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5
PS
753 * @param string $name name of select element
754 * @param string|array $selected value or arary of values depending on multiple attribute
755 * @param array|bool $nothing, add nothing selected option, or false of not added
756 * @param array $attributes - html select element attributes
78bdac64 757 * @return string HTML fragment
3ff163c5 758 */
aa2dea70 759 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
3ff163c5
PS
760 $attributes = (array)$attributes;
761 if (is_array($nothing)) {
762 foreach ($nothing as $k=>$v) {
4b9210f3 763 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
764 $nothing[$k] = get_string('choosedots');
765 }
766 }
767 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
768
769 } else if (is_string($nothing) and $nothing !== '') {
770 // BC
771 $options = array(''=>$nothing) + $options;
bde156b3 772 }
3ff163c5
PS
773
774 // we may accept more values if multiple attribute specified
775 $selected = (array)$selected;
776 foreach ($selected as $k=>$v) {
777 $selected[$k] = (string)$v;
778 }
779
780 if (!isset($attributes['id'])) {
781 $id = 'menu'.$name;
782 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
783 $id = str_replace('[', '', $id);
784 $id = str_replace(']', '', $id);
785 $attributes['id'] = $id;
786 }
787
788 if (!isset($attributes['class'])) {
789 $class = 'menu'.$name;
790 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
791 $class = str_replace('[', '', $class);
792 $class = str_replace(']', '', $class);
793 $attributes['class'] = $class;
794 }
795 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
796
797 $attributes['name'] = $name;
798
799 $output = '';
800 foreach ($options as $value=>$label) {
6770330d
PS
801 if (is_array($label)) {
802 // ignore key, it just has to be unique
803 $output .= self::select_optgroup(key($label), current($label), $selected);
804 } else {
805 $output .= self::select_option($label, $value, $selected);
3ff163c5 806 }
3ff163c5 807 }
3ff163c5
PS
808 return self::tag('select', $attributes, $output);
809 }
6770330d
PS
810
811 private static function select_option($label, $value, array $selected) {
812 $attributes = array();
813 $value = (string)$value;
814 if (in_array($value, $selected, true)) {
815 $attributes['selected'] = 'selected';
816 }
817 $attributes['value'] = $value;
818 return self::tag('option', $attributes, $label);
819 }
820
821 private static function select_optgroup($groupname, $options, array $selected) {
822 if (empty($options)) {
823 return '';
824 }
825 $attributes = array('label'=>$groupname);
826 $output = '';
827 foreach ($options as $value=>$label) {
828 $output .= self::select_option($label, $value, $selected);
829 }
830 return self::tag('optgroup', $attributes, $output);
831 }
6ea66ff3 832
f83b9b63
PS
833 /**
834 * This is a shortcut for making an hour selector menu.
835 * @param string $type The type of selector (years, months, days, hours, minutes)
836 * @param string $name fieldname
837 * @param int $currenttime A default timestamp in GMT
838 * @param int $step minute spacing
839 * @param array $attributes - html select element attributes
840 * @return HTML fragment
841 */
842 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
843 if (!$currenttime) {
844 $currenttime = time();
845 }
846 $currentdate = usergetdate($currenttime);
847 $userdatetype = $type;
848 $timeunits = array();
849
850 switch ($type) {
851 case 'years':
852 for ($i=1970; $i<=2020; $i++) {
853 $timeunits[$i] = $i;
854 }
855 $userdatetype = 'year';
856 break;
857 case 'months':
858 for ($i=1; $i<=12; $i++) {
859 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
860 }
861 $userdatetype = 'month';
862 $currentdate['month'] = $currentdate['mon'];
863 break;
864 case 'days':
865 for ($i=1; $i<=31; $i++) {
866 $timeunits[$i] = $i;
867 }
868 $userdatetype = 'mday';
869 break;
870 case 'hours':
871 for ($i=0; $i<=23; $i++) {
872 $timeunits[$i] = sprintf("%02d",$i);
873 }
874 break;
875 case 'minutes':
876 if ($step != 1) {
877 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
878 }
879
880 for ($i=0; $i<=59; $i+=$step) {
881 $timeunits[$i] = sprintf("%02d",$i);
882 }
883 break;
884 default:
885 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
886 }
887
888 if (empty($attributes['id'])) {
889 $attributes['id'] = self::random_id('ts_');
890 }
891 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
892 $label = self::tag('label', array('for'=>$attributes['id'], 'class'=>'accesshide'), get_string(substr($type, 0, -1), 'form'));
893
894 return $label.$timerselector;
895 }
896
6ea66ff3
PS
897 /**
898 * Returns hidden input fields created from url parameters.
899 * @param moodle_url $url
900 * @param array $exclude list of excluded parameters
901 * @return string HTML fragment
902 */
903 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
904 $exclude = (array)$exclude;
905 $params = $url->params();
906 foreach ($exclude as $key) {
907 unset($params[$key]);
908 }
909
910 $output = '';
bde156b3 911 foreach ($params as $key => $value) {
6ea66ff3
PS
912 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
913 $output .= self::empty_tag('input', $attributes)."\n";
914 }
915 return $output;
916 }
77774f6a
PS
917
918 /**
919 * Generate a script tag containing the the specified code.
920 *
921 * @param string $js the JavaScript code
e50b4c89 922 * @param moodle_url|string optional url of the external script, $code ignored if specified
77774f6a
PS
923 * @return string HTML, the code wrapped in <script> tags.
924 */
e50b4c89 925 public static function script($jscode, $url=null) {
77774f6a 926 if ($jscode) {
e50b4c89
PS
927 $attributes = array('type'=>'text/javascript');
928 return self::tag('script', $attributes, "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
929
930 } else if ($url) {
931 $attributes = array('type'=>'text/javascript', 'src'=>$url);
932 return self::tag('script', $attributes, '') . "\n";
a9967cf5 933
77774f6a
PS
934 } else {
935 return '';
936 }
937 }
5d0c95a5
PS
938}
939
227255b8
PS
940// ==== JS writer and helper classes, will be probably moved elsewhere ======
941
942/**
943 * Simple javascript output class
944 * @copyright 2010 Petr Skoda
945 */
946class js_writer {
947 /**
948 * Returns javascript code calling the function
949 * @param string $function function name, can be complex lin Y.Event.purgeElement
950 * @param array $arguments parameters
951 * @param int $delay execution delay in seconds
952 * @return string JS code fragment
953 */
954 public function function_call($function, array $arguments = null, $delay=0) {
1b4e41af
PS
955 if ($arguments) {
956 $arguments = array_map('json_encode', $arguments);
957 $arguments = implode(', ', $arguments);
958 } else {
959 $arguments = '';
960 }
227255b8
PS
961 $js = "$function($arguments);";
962
963 if ($delay) {
964 $delay = $delay * 1000; // in miliseconds
965 $js = "setTimeout(function() { $js }, $delay);";
966 }
967 return $js . "\n";
968 }
969
3b01539c
PS
970 /**
971 * Special function which adds Y as first argument of fucntion call.
972 * @param string $function
973 * @param array $extraarguments
974 * @return string
975 */
976 public function function_call_with_Y($function, array $extraarguments = null) {
977 if ($extraarguments) {
978 $extraarguments = array_map('json_encode', $extraarguments);
979 $arguments = 'Y, ' . implode(', ', $extraarguments);
980 } else {
981 $arguments = 'Y';
982 }
983 return "$function($arguments);\n";
984 }
985
1ce15fda
SH
986 /**
987 * Returns JavaScript code to initialise a new object
988 * @param string|null $var If it is null then no var is assigned the new object
989 * @param string $class
990 * @param array $arguments
991 * @param array $requirements
992 * @param int $delay
993 * @return string
994 */
995 public function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
996 if (is_array($arguments)) {
997 $arguments = array_map('json_encode', $arguments);
998 $arguments = implode(', ', $arguments);
999 }
1000
1001 if ($var === null) {
53fc3e70 1002 $js = "new $class(Y, $arguments);";
1ce15fda 1003 } else if (strpos($var, '.')!==false) {
53fc3e70 1004 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1005 } else {
53fc3e70 1006 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1007 }
1008
1009 if ($delay) {
1010 $delay = $delay * 1000; // in miliseconds
1011 $js = "setTimeout(function() { $js }, $delay);";
1012 }
1013
1014 if (count($requirements) > 0) {
1015 $requirements = implode("', '", $requirements);
53fc3e70 1016 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1017 }
1018 return $js."\n";
1019 }
1020
227255b8
PS
1021 /**
1022 * Returns code setting value to variable
1023 * @param string $name
1024 * @param mixed $value json serialised value
1025 * @param bool $usevar add var definition, ignored for nested properties
1026 * @return string JS code fragment
1027 */
1028 public function set_variable($name, $value, $usevar=true) {
1029 $output = '';
1030
1031 if ($usevar) {
1032 if (strpos($name, '.')) {
1033 $output .= '';
1034 } else {
1035 $output .= 'var ';
1036 }
1037 }
1038
1039 $output .= "$name = ".json_encode($value).";";
1040
1041 return $output;
1042 }
1043
1044 /**
1045 * Writes event handler attaching code
1046 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
1047 * @param string $event A valid DOM event (click, mousedown, change etc.)
1048 * @param string $function The name of the function to call
1049 * @param array $arguments An optional array of argument parameters to pass to the function
1050 * @return string JS code fragment
1051 */
1052 public function event_handler($selector, $event, $function, array $arguments = null) {
1053 $selector = json_encode($selector);
1054 $output = "Y.on('$event', $function, $selector, null";
1055 if (!empty($arguments)) {
1056 $output .= ', ' . json_encode($arguments);
1057 }
1058 return $output . ");\n";
1059 }
1060}
1061
5d0c95a5
PS
1062
1063// ===============================================================================================
1064// TODO: Following components will be refactored soon
1065
d9c8f425 1066/**
4ed85790 1067 * Base class for classes representing HTML elements.
d9c8f425 1068 *
1069 * Handles the id and class attributes.
1070 *
1071 * @copyright 2009 Tim Hunt
1072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1073 * @since Moodle 2.0
1074 */
6dd7d7f0 1075class html_component {
d9c8f425 1076 /**
1077 * @var string value to use for the id attribute of this HTML tag.
1078 */
97c10099 1079 public $id = null;
d9c8f425 1080 /**
1081 * @var string $alt value to use for the alt attribute of this HTML tag.
1082 */
97c10099 1083 public $alt = null;
d9c8f425 1084 /**
1085 * @var string $style value to use for the style attribute of this HTML tag.
1086 */
97c10099 1087 public $style = null;
d9c8f425 1088 /**
1089 * @var array class names to add to this HTML element.
1090 */
1091 public $classes = array();
1092 /**
1093 * @var string $title The title attributes applicable to any XHTML element
1094 */
97c10099 1095 public $title = null;
d9c8f425 1096 /**
1097 * An optional array of component_action objects handling the action part of this component.
1098 * @var array $actions
1099 */
1100 protected $actions = array();
d9c8f425 1101
8fa16366
PS
1102 /**
1103 * Compoment constructor.
1104 * @param array $options image attributes such as title, id, alt, style, class
1105 */
1106 public function __construct(array $options = null) {
1107 // not implemented in this class because we want to set only public properties of this component
1108 renderer_base::apply_component_options($this, $options);
1109 }
1110
d9c8f425 1111 /**
1112 * Ensure some class names are an array.
1113 * @param mixed $classes either an array of class names or a space-separated
1114 * string containing class names.
1115 * @return array the class names as an array.
1116 */
1117 public static function clean_classes($classes) {
642816a6 1118 if (empty($classes)) {
3bd6b994 1119 return array();
642816a6 1120 } else if (is_array($classes)) {
d9c8f425 1121 return $classes;
1122 } else {
1123 return explode(' ', trim($classes));
1124 }
1125 }
1126
1127 /**
1128 * Set the class name array.
1129 * @param mixed $classes either an array of class names or a space-separated
1130 * string containing class names.
1131 * @return void
1132 */
1133 public function set_classes($classes) {
1134 $this->classes = self::clean_classes($classes);
1135 }
1136
1137 /**
1138 * Add a class name to the class names array.
1139 * @param string $class the new class name to add.
1140 * @return void
1141 */
1142 public function add_class($class) {
1143 $this->classes[] = $class;
1144 }
1145
1146 /**
1147 * Add a whole lot of class names to the class names array.
1148 * @param mixed $classes either an array of class names or a space-separated
1149 * string containing class names.
1150 * @return void
1151 */
1152 public function add_classes($classes) {
eeecf5a7 1153 $this->classes = array_merge($this->classes, self::clean_classes($classes));
d9c8f425 1154 }
1155
1156 /**
1157 * Get the class names as a string.
1158 * @return string the class names as a space-separated string. Ready to be put in the class="" attribute.
1159 */
1160 public function get_classes_string() {
1161 return implode(' ', $this->classes);
1162 }
1163
1164 /**
1165 * Perform any cleanup or final processing that should be done before an
34059565
PS
1166 * instance of this class is output. This method is supposed to be called
1167 * only from renderers.
1168 *
1169 * @param renderer_base $output output renderer
1170 * @param moodle_page $page
1171 * @param string $target rendering target
d9c8f425 1172 * @return void
1173 */
34059565 1174 public function prepare(renderer_base $output, moodle_page $page, $target) {
d9c8f425 1175 $this->classes = array_unique(self::clean_classes($this->classes));
1176 }
1177
1178 /**
1179 * This checks developer do not try to assign a property directly
1180 * if we have a setter for it. Otherwise, the property is set as expected.
1181 * @param string $name The name of the variable to set
1182 * @param mixed $value The value to assign to the variable
1183 * @return void
1184 */
1185 public function __set($name, $value) {
1186 if ($name == 'class') {
1187 debugging('this way of setting css class has been deprecated. use set_classes() method instead.');
1188 $this->set_classes($value);
1189 } else {
1190 $this->{$name} = $value;
1191 }
1192 }
1193
1194 /**
1195 * Adds a JS action to this component.
1196 * Note: the JS function you write must have only two arguments: (string)event and (object|array)args
1197 * If you want to add an instantiated component_action (or one of its subclasses), give the object as the only parameter
1198 *
1199 * @param mixed $event a DOM event (click, mouseover etc.) or a component_action object
1200 * @param string $jsfunction The name of the JS function to call. required if argument 1 is a string (event)
1201 * @param array $jsfunctionargs An optional array of JS arguments to pass to the function
1202 */
1203 public function add_action($event, $jsfunction=null, $jsfunctionargs=array()) {
1204 if (empty($this->id)) {
1205 $this->generate_id();
1206 }
1207
1208 if ($event instanceof component_action) {
1209 $this->actions[] = $event;
1210 } else {
1211 if (empty($jsfunction)) {
6dd7d7f0 1212 throw new coding_exception('html_component::add_action requires a JS function argument if the first argument is a string event');
d9c8f425 1213 }
1214 $this->actions[] = new component_action($event, $jsfunction, $jsfunctionargs);
1215 }
1216 }
1217
1218 /**
1219 * Internal method for generating a unique ID for the purpose of event handlers.
1220 */
1221 protected function generate_id() {
0c868b08 1222 $this->id = uniqid(get_class($this));
d9c8f425 1223 }
1224
1225 /**
1226 * Returns the array of component_actions.
1227 * @return array Component actions
1228 */
1229 public function get_actions() {
1230 return $this->actions;
1231 }
1232
7a5c78e0 1233 /**
1234 * Shortcut for adding a JS confirm dialog when the component is clicked.
1235 * The message must be a yes/no question.
1236 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
a0ead5eb 1237 * @param string $callback The name of a JS function whose scope will be set to the simpleDialog object and have this
5529f787 1238 * function's arguments set as this.args.
7a5c78e0 1239 * @return void
1240 */
5529f787 1241 public function add_confirm_action($message, $callback=null) {
20fb563e 1242 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $message, 'callback' => $callback)));
7a5c78e0 1243 }
db49be13 1244
1245 /**
1246 * Returns true if this component has an action of the requested type (component_action by default).
1247 * @param string $class The class of the action we are looking for
1248 * @return boolean True if action is found
1249 */
1250 public function has_action($class='component_action') {
1251 foreach ($this->actions as $action) {
1252 if (get_class($action) == $class) {
1253 return true;
1254 }
1255 }
1256 return false;
1257 }
7a5c78e0 1258}
1259
34059565 1260
beb56299 1261/// Components representing HTML elements
d9c8f425 1262
34059565 1263
7b1f2c82 1264/**
1265 * Holds all the information required to render a <table> by
78946b9b 1266 * {@see core_renderer::table()} or by an overridden version of that
7b1f2c82 1267 * method in a subclass.
1268 *
1269 * Example of usage:
1270 * $t = new html_table();
1271 * ... // set various properties of the object $t as described below
1272 * echo $OUTPUT->table($t);
1273 *
1274 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1276 * @since Moodle 2.0
1277 */
f7065efe 1278class html_table extends html_component {
7b1f2c82 1279 /**
a0ead5eb 1280 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1281 * can be passed instead of an array of strings.
7b1f2c82 1282 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1283 *
1284 * Example of usage:
1285 * $t->head = array('Student', 'Grade');
1286 */
1287 public $head;
1288 /**
1289 * @var array can be used to make a heading span multiple columns
1290 *
1291 * Example of usage:
1292 * $t->headspan = array(2,1);
1293 *
1294 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1295 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1296 */
1297 public $headspan;
1298 /**
1299 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1300 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1301 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1302 *
beb56299 1303 * Examples of usage:
1304 * $t->align = array(null, 'right');
1305 * or
1306 * $t->align[1] = 'right';
1307 *
d9c8f425 1308 */
beb56299 1309 public $align;
d9c8f425 1310 /**
beb56299 1311 * @var array of column sizes. The value is used as CSS 'size' property.
1312 *
1313 * Examples of usage:
1314 * $t->size = array('50%', '50%');
1315 * or
1316 * $t->size[1] = '120px';
d9c8f425 1317 */
beb56299 1318 public $size;
d9c8f425 1319 /**
beb56299 1320 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1321 * CSS property 'white-space' to the value 'nowrap' in the given column.
1322 *
1323 * Example of usage:
1324 * $t->wrap = array(null, 'nowrap');
d9c8f425 1325 */
beb56299 1326 public $wrap;
d9c8f425 1327 /**
beb56299 1328 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1329 * $head specified, the string 'hr' (for horizontal ruler) can be used
1330 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1331 *
beb56299 1332 * Example of usage with array of arrays:
1333 * $row1 = array('Harry Potter', '76 %');
1334 * $row2 = array('Hermione Granger', '100 %');
1335 * $t->data = array($row1, $row2);
d9c8f425 1336 *
beb56299 1337 * Example with array of html_table_row objects: (used for more fine-grained control)
1338 * $cell1 = new html_table_cell();
1339 * $cell1->text = 'Harry Potter';
1340 * $cell1->colspan = 2;
1341 * $row1 = new html_table_row();
1342 * $row1->cells[] = $cell1;
1343 * $cell2 = new html_table_cell();
1344 * $cell2->text = 'Hermione Granger';
1345 * $cell3 = new html_table_cell();
1346 * $cell3->text = '100 %';
1347 * $row2 = new html_table_row();
1348 * $row2->cells = array($cell2, $cell3);
1349 * $t->data = array($row1, $row2);
1350 */
1351 public $data;
1352 /**
1353 * @var string width of the table, percentage of the page preferred. Defaults to 80% of the page width.
1354 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1355 */
1356 public $width = null;
1357 /**
1358 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1359 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1360 */
1361 public $tablealign = null;
1362 /**
1363 * @var int padding on each cell, in pixels
1364 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1365 */
1366 public $cellpadding = null;
1367 /**
1368 * @var int spacing between cells, in pixels
1369 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1370 */
1371 public $cellspacing = null;
1372 /**
1373 * @var array classes to add to particular rows, space-separated string.
1374 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1375 * respectively. Class 'lastrow' is added automatically for the last row
1376 * in the table.
d9c8f425 1377 *
beb56299 1378 * Example of usage:
1379 * $t->rowclasses[9] = 'tenth'
1380 */
1381 public $rowclasses;
1382 /**
1383 * @var array classes to add to every cell in a particular column,
1384 * space-separated string. Class 'cell' is added automatically by the renderer.
1385 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1386 * respectively. Class 'lastcol' is added automatically for all last cells
1387 * in a row.
d9c8f425 1388 *
beb56299 1389 * Example of usage:
1390 * $t->colclasses = array(null, 'grade');
d9c8f425 1391 */
beb56299 1392 public $colclasses;
1393 /**
1394 * @var string description of the contents for screen readers.
1395 */
1396 public $summary;
1397 /**
1398 * @var bool true causes the contents of the heading cells to be rotated 90 degrees.
1399 */
1400 public $rotateheaders = false;
319770d7 1401 /**
1402 * @var array $headclasses Array of CSS classes to apply to the table's thead.
1403 */
1404 public $headclasses = array();
1405 /**
1406 * @var array $bodyclasses Array of CSS classes to apply to the table's tbody.
1407 */
1408 public $bodyclasses = array();
1409 /**
1410 * @var array $footclasses Array of CSS classes to apply to the table's tfoot.
1411 */
1412 public $footclasses = array();
a0ead5eb 1413
d9c8f425 1414
1415 /**
6dd7d7f0 1416 * @see html_component::prepare()
beb56299 1417 * @return void
d9c8f425 1418 */
34059565 1419 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 1420 if (!empty($this->align)) {
1421 foreach ($this->align as $key => $aa) {
1422 if ($aa) {
1423 $this->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1424 } else {
97c10099 1425 $this->align[$key] = null;
beb56299 1426 }
1427 }
d9c8f425 1428 }
beb56299 1429 if (!empty($this->size)) {
1430 foreach ($this->size as $key => $ss) {
1431 if ($ss) {
1432 $this->size[$key] = 'width:'. $ss .';';
1433 } else {
97c10099 1434 $this->size[$key] = null;
beb56299 1435 }
1436 }
d9c8f425 1437 }
beb56299 1438 if (!empty($this->wrap)) {
1439 foreach ($this->wrap as $key => $ww) {
1440 if ($ww) {
1441 $this->wrap[$key] = 'white-space:nowrap;';
1442 } else {
1443 $this->wrap[$key] = '';
1444 }
1445 }
d9c8f425 1446 }
beb56299 1447 if (!empty($this->head)) {
1448 foreach ($this->head as $key => $val) {
1449 if (!isset($this->align[$key])) {
97c10099 1450 $this->align[$key] = null;
beb56299 1451 }
1452 if (!isset($this->size[$key])) {
97c10099 1453 $this->size[$key] = null;
beb56299 1454 }
1455 if (!isset($this->wrap[$key])) {
97c10099 1456 $this->wrap[$key] = null;
d9c8f425 1457 }
1458
d9c8f425 1459 }
beb56299 1460 }
1461 if (empty($this->classes)) { // must be done before align
1462 $this->set_classes(array('generaltable'));
1463 }
1464 if (!empty($this->tablealign)) {
1465 $this->add_class('boxalign' . $this->tablealign);
1466 }
1467 if (!empty($this->rotateheaders)) {
1468 $this->add_class('rotateheaders');
d9c8f425 1469 } else {
beb56299 1470 $this->rotateheaders = false; // Makes life easier later.
1471 }
34059565 1472 parent::prepare($output, $page, $target);
beb56299 1473 }
1474 /**
1475 * @param string $name The name of the variable to set
1476 * @param mixed $value The value to assign to the variable
1477 * @return void
1478 */
1479 public function __set($name, $value) {
1480 if ($name == 'rowclass') {
1481 debugging('rowclass[] has been deprecated for html_table ' .
7b1f2c82 1482 'and should be replaced with rowclasses[]. please fix the code.');
1483 $this->rowclasses = $value;
1484 } else {
1485 parent::__set($name, $value);
d9c8f425 1486 }
d9c8f425 1487 }
d9c8f425 1488}
1489
34059565 1490
d9c8f425 1491/**
7b1f2c82 1492 * Component representing a table row.
d9c8f425 1493 *
1494 * @copyright 2009 Nicolas Connault
1495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1496 * @since Moodle 2.0
1497 */
6dd7d7f0 1498class html_table_row extends html_component {
d9c8f425 1499 /**
7b1f2c82 1500 * @var array $cells Array of html_table_cell objects
d9c8f425 1501 */
7b1f2c82 1502 public $cells = array();
d9c8f425 1503
beb56299 1504 /**
6dd7d7f0 1505 * @see lib/html_component#prepare()
beb56299 1506 * @return void
1507 */
34059565
PS
1508 public function prepare(renderer_base $output, moodle_page $page, $target) {
1509 parent::prepare($output, $page, $target);
d9c8f425 1510 }
a0ead5eb 1511
54a007e8 1512 /**
a019627a 1513 * Shortcut method for creating a row with an array of cells. Converts cells to html_table_cell objects.
54a007e8 1514 * @param array $cells
1515 * @return html_table_row
1516 */
8fa16366 1517 public static function make($cells=array()) {
54a007e8 1518 $row = new html_table_row();
a019627a 1519 foreach ($cells as $celltext) {
1520 if (!($celltext instanceof html_table_cell)) {
1521 $cell = new html_table_cell();
1522 $cell->text = $celltext;
1523 $row->cells[] = $cell;
1524 } else {
1525 $row->cells[] = $celltext;
1526 }
1527 }
54a007e8 1528 return $row;
1529 }
d9c8f425 1530}
1531
34059565 1532
d9c8f425 1533/**
7b1f2c82 1534 * Component representing a table cell.
d9c8f425 1535 *
1536 * @copyright 2009 Nicolas Connault
1537 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1538 * @since Moodle 2.0
1539 */
6dd7d7f0 1540class html_table_cell extends html_component {
d9c8f425 1541 /**
7b1f2c82 1542 * @var string $text The contents of the cell
d9c8f425 1543 */
7b1f2c82 1544 public $text;
d9c8f425 1545 /**
7b1f2c82 1546 * @var string $abbr Abbreviated version of the contents of the cell
d9c8f425 1547 */
97c10099 1548 public $abbr = null;
d9c8f425 1549 /**
7b1f2c82 1550 * @var int $colspan Number of columns this cell should span
d9c8f425 1551 */
97c10099 1552 public $colspan = null;
d9c8f425 1553 /**
7b1f2c82 1554 * @var int $rowspan Number of rows this cell should span
d9c8f425 1555 */
97c10099 1556 public $rowspan = null;
d9c8f425 1557 /**
7b1f2c82 1558 * @var string $scope Defines a way to associate header cells and data cells in a table
d9c8f425 1559 */
97c10099 1560 public $scope = null;
1ae3767a 1561 /**
1562 * @var boolean $header Whether or not this cell is a header cell
1563 */
a4998d01 1564 public $header = null;
d9c8f425 1565
1566 /**
6dd7d7f0 1567 * @see lib/html_component#prepare()
d9c8f425 1568 * @return void
1569 */
34059565 1570 public function prepare(renderer_base $output, moodle_page $page, $target) {
54a007e8 1571 if ($this->header && empty($this->scope)) {
1572 $this->scope = 'col';
1573 }
34059565 1574 parent::prepare($output, $page, $target);
d9c8f425 1575 }
1576}
1577
34059565 1578
7b1f2c82 1579/**
1580 * Component representing a list.
1581 *
1582 * The advantage of using this object instead of a flat array is that you can load it
1583 * with metadata (CSS classes, event handlers etc.) which can be used by the renderers.
1584 *
1585 * @copyright 2009 Nicolas Connault
1586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1587 * @since Moodle 2.0
1588 */
6dd7d7f0 1589class html_list extends html_component {
d9c8f425 1590
7b1f2c82 1591 /**
1592 * @var array $items An array of html_list_item or html_list objects
1593 */
1594 public $items = array();
d9c8f425 1595
7b1f2c82 1596 /**
1597 * @var string $type The type of list (ordered|unordered), definition type not yet supported
1598 */
1599 public $type = 'unordered';
d9c8f425 1600
b65bfc3e 1601 /**
1602 * @var string $text An optional descriptive text for the list. Will be output as a list item before opening the new list
1603 */
1604 public $text = false;
1605
7b1f2c82 1606 /**
6dd7d7f0 1607 * @see lib/html_component#prepare()
7b1f2c82 1608 * @return void
1609 */
34059565
PS
1610 public function prepare(renderer_base $output, moodle_page $page, $target) {
1611 parent::prepare($output, $page, $target);
d9c8f425 1612 }
1613
1614 /**
7b1f2c82 1615 * This function takes a nested array of data and maps it into this list's $items array
1616 * as proper html_list_item and html_list objects, with appropriate metadata.
1617 *
1618 * @param array $tree A nested array (array keys are ignored);
1619 * @param int $row Used in identifying the iteration level and in ul classes
beb56299 1620 * @return void
d9c8f425 1621 */
7b1f2c82 1622 public function load_data($tree, $level=0) {
beb56299 1623
7b1f2c82 1624 $this->add_class("list-$level");
beb56299 1625
b65bfc3e 1626 $i = 1;
7b1f2c82 1627 foreach ($tree as $key => $element) {
1628 if (is_array($element)) {
1629 $newhtmllist = new html_list();
b65bfc3e 1630 $newhtmllist->type = $this->type;
7b1f2c82 1631 $newhtmllist->load_data($element, $level + 1);
b65bfc3e 1632 $newhtmllist->text = $key;
7b1f2c82 1633 $this->items[] = $newhtmllist;
1634 } else {
1635 $listitem = new html_list_item();
1636 $listitem->value = $element;
b65bfc3e 1637 $listitem->add_class("list-item-$level-$i");
7b1f2c82 1638 $this->items[] = $listitem;
beb56299 1639 }
b65bfc3e 1640 $i++;
beb56299 1641 }
1642 }
d9c8f425 1643
1644 /**
7b1f2c82 1645 * Adds a html_list_item or html_list to this list.
1646 * If the param is a string, a html_list_item will be added.
1647 * @param mixed $item String, html_list or html_list_item object
d9c8f425 1648 * @return void
1649 */
7b1f2c82 1650 public function add_item($item) {
1651 if ($item instanceof html_list_item || $item instanceof html_list) {
1652 $this->items[] = $item;
1653 } else {
1654 $listitem = new html_list_item();
1655 $listitem->value = $item;
1656 $this->items[] = $item;
beb56299 1657 }
d9c8f425 1658 }
7b1f2c82 1659}
d9c8f425 1660
34059565 1661
7b1f2c82 1662/**
1663 * Component representing a list item.
1664 *
1665 * @copyright 2009 Nicolas Connault
1666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1667 * @since Moodle 2.0
1668 */
6dd7d7f0 1669class html_list_item extends html_component {
d9c8f425 1670 /**
7b1f2c82 1671 * @var string $value The value of the list item
d9c8f425 1672 */
7b1f2c82 1673 public $value;
d9c8f425 1674
7b1f2c82 1675 /**
6dd7d7f0 1676 * @see lib/html_component#prepare()
7b1f2c82 1677 * @return void
1678 */
34059565
PS
1679 public function prepare(renderer_base $output, moodle_page $page, $target) {
1680 parent::prepare($output, $page, $target);
d9c8f425 1681 }
1682}
1683
34059565 1684
54a007e8 1685/**
a0ead5eb 1686 * Component representing a span element. It has no special attributes, so
54a007e8 1687 * it is very low-level and can be used for styling and JS actions.
1688 *
1689 * @copyright 2009 Nicolas Connault
1690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1691 * @since Moodle 2.0
1692 */
6dd7d7f0 1693class html_span extends html_component {
54a007e8 1694 /**
1695 * @var string $text The contents of the span
1696 */
1697 public $contents;
1698 /**
6dd7d7f0 1699 * @see lib/html_component#prepare()
54a007e8 1700 * @return void
1701 */
34059565
PS
1702 public function prepare(renderer_base $output, moodle_page $page, $target) {
1703 parent::prepare($output, $page, $target);
54a007e8 1704 }
1705}
1706
7b1f2c82 1707/// Complex components aggregating simpler components
1708
34059565 1709
d9c8f425 1710/**
beb56299 1711 * Component representing a paging bar.
d9c8f425 1712 *
1713 * @copyright 2009 Nicolas Connault
1714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1715 * @since Moodle 2.0
1716 */
6dd7d7f0 1717class moodle_paging_bar extends html_component {
d9c8f425 1718 /**
beb56299 1719 * @var int $maxdisplay The maximum number of pagelinks to display
d9c8f425 1720 */
beb56299 1721 public $maxdisplay = 18;
d9c8f425 1722 /**
beb56299 1723 * @var int $totalcount post or get
d9c8f425 1724 */
beb56299 1725 public $totalcount;
d9c8f425 1726 /**
beb56299 1727 * @var int $page The page you are currently viewing
d9c8f425 1728 */
beb56299 1729 public $page = 0;
d9c8f425 1730 /**
beb56299 1731 * @var int $perpage The number of entries that should be shown per page
d9c8f425 1732 */
beb56299 1733 public $perpage;
d9c8f425 1734 /**
beb56299 1735 * @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.
1736 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 1737 */
beb56299 1738 public $baseurl;
d9c8f425 1739 /**
beb56299 1740 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 1741 */
beb56299 1742 public $pagevar = 'page';
beb56299 1743 /**
56ddb719 1744 * @var string $previouslink A HTML link representing the "previous" page
beb56299 1745 */
1746 public $previouslink = null;
1747 /**
56ddb719 1748 * @var tring $nextlink A HTML link representing the "next" page
beb56299 1749 */
1750 public $nextlink = null;
1751 /**
56ddb719 1752 * @var tring $firstlink A HTML link representing the first page
beb56299 1753 */
1754 public $firstlink = null;
1755 /**
56ddb719 1756 * @var tring $lastlink A HTML link representing the last page
beb56299 1757 */
1758 public $lastlink = null;
1759 /**
56ddb719 1760 * @var array $pagelinks An array of strings. One of them is just a string: the current page
beb56299 1761 */
1762 public $pagelinks = array();
d9c8f425 1763
1764 /**
6dd7d7f0 1765 * @see lib/html_component#prepare()
d9c8f425 1766 * @return void
1767 */
34059565 1768 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 1769 if (!isset($this->totalcount) || is_null($this->totalcount)) {
beb56299 1770 throw new coding_exception('moodle_paging_bar requires a totalcount value.');
1771 }
1772 if (!isset($this->page) || is_null($this->page)) {
1773 throw new coding_exception('moodle_paging_bar requires a page value.');
1774 }
1775 if (empty($this->perpage)) {
1776 throw new coding_exception('moodle_paging_bar requires a perpage value.');
1777 }
1778 if (empty($this->baseurl)) {
1779 throw new coding_exception('moodle_paging_bar requires a baseurl value.');
1780 }
1781 if (!($this->baseurl instanceof moodle_url)) {
1782 $this->baseurl = new moodle_url($this->baseurl);
1783 }
d9c8f425 1784
beb56299 1785 if ($this->totalcount > $this->perpage) {
1786 $pagenum = $this->page - 1;
d9c8f425 1787
beb56299 1788 if ($this->page > 0) {
56ddb719 1789 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), array('class'=>'previous'), get_string('previous'));
beb56299 1790 }
d9c8f425 1791
beb56299 1792 if ($this->perpage > 0) {
1793 $lastpage = ceil($this->totalcount / $this->perpage);
1794 } else {
1795 $lastpage = 1;
1796 }
1797
1798 if ($this->page > 15) {
1799 $startpage = $this->page - 10;
1800
56ddb719 1801 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), array('class'=>'first'), '1');
beb56299 1802 } else {
1803 $startpage = 0;
1804 }
1805
1806 $currpage = $startpage;
1807 $displaycount = $displaypage = 0;
1808
1809 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1810 $displaypage = $currpage + 1;
1811
f43cdceb 1812 if ($this->page == $currpage) {
beb56299 1813 $this->pagelinks[] = $displaypage;
1814 } else {
56ddb719 1815 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 1816 $this->pagelinks[] = $pagelink;
1817 }
1818
1819 $displaycount++;
1820 $currpage++;
1821 }
1822
1823 if ($currpage < $lastpage) {
1824 $lastpageactual = $lastpage - 1;
abdac127 1825 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 1826 }
1827
1828 $pagenum = $this->page + 1;
1829
1830 if ($pagenum != $displaypage) {
abdac127 1831 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 1832 }
d9c8f425 1833 }
1834 }
d9c8f425 1835
1836 /**
beb56299 1837 * Shortcut for initialising a moodle_paging_bar with only the required params.
1838 *
1839 * @param int $totalcount Thetotal number of entries available to be paged through
1840 * @param int $page The page you are currently viewing
1841 * @param int $perpage The number of entries that should be shown per page
1842 * @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.
1843 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 1844 */
8fa16366 1845 public static function make($totalcount, $page, $perpage, $baseurl) {
beb56299 1846 $pagingbar = new moodle_paging_bar();
1847 $pagingbar->totalcount = $totalcount;
1848 $pagingbar->page = $page;
1849 $pagingbar->perpage = $perpage;
1850 $pagingbar->baseurl = $baseurl;
1851 return $pagingbar;
d9c8f425 1852 }
1853}
1854
34059565 1855
d9c8f425 1856/**
beb56299 1857 * This class represents how a block appears on a page.
d9c8f425 1858 *
beb56299 1859 * During output, each block instance is asked to return a block_contents object,
1860 * those are then passed to the $OUTPUT->block function for display.
1861 *
1862 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
1863 *
1864 * Other block-like things that need to appear on the page, for example the
1865 * add new block UI, are also represented as block_contents objects.
1866 *
1867 * @copyright 2009 Tim Hunt
d9c8f425 1868 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1869 * @since Moodle 2.0
1870 */
6dd7d7f0 1871class block_contents extends html_component {
beb56299 1872 /** @var int used to set $skipid. */
1873 protected static $idcounter = 1;
1874
1875 const NOT_HIDEABLE = 0;
1876 const VISIBLE = 1;
1877 const HIDDEN = 2;
1878
d9c8f425 1879 /**
beb56299 1880 * @param integer $skipid All the blocks (or things that look like blocks)
1881 * printed on a page are given a unique number that can be used to construct
1882 * id="" attributes. This is set automatically be the {@link prepare()} method.
1883 * Do not try to set it manually.
d9c8f425 1884 */
beb56299 1885 public $skipid;
d9c8f425 1886
1887 /**
beb56299 1888 * @var integer If this is the contents of a real block, this should be set to
1889 * the block_instance.id. Otherwise this should be set to 0.
1890 */
1891 public $blockinstanceid = 0;
1892
1893 /**
1894 * @var integer if this is a real block instance, and there is a corresponding
1895 * block_position.id for the block on this page, this should be set to that id.
1896 * Otherwise it should be 0.
1897 */
1898 public $blockpositionid = 0;
1899
1900 /**
1901 * @param array $attributes an array of attribute => value pairs that are put on the
1902 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
1903 */
1904 public $attributes = array();
1905
1906 /**
1907 * @param string $title The title of this block. If this came from user input,
1908 * it should already have had format_string() processing done on it. This will
1909 * be output inside <h2> tags. Please do not cause invalid XHTML.
1910 */
1911 public $title = '';
1912
1913 /**
1914 * @param string $content HTML for the content
1915 */
1916 public $content = '';
1917
1918 /**
1919 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1920 */
1921 public $footer = '';
1922
1923 /**
1924 * Any small print that should appear under the block to explain to the
1925 * teacher about the block, for example 'This is a sticky block that was
1926 * added in the system context.'
1927 * @var string
1928 */
1929 public $annotation = '';
1930
1931 /**
1932 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
1933 * the user can toggle whether this block is visible.
1934 */
1935 public $collapsible = self::NOT_HIDEABLE;
1936
1937 /**
1938 * A (possibly empty) array of editing controls. Each element of this array
1939 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 1940 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 1941 * @var array
1942 */
1943 public $controls = array();
1944
1945 /**
6dd7d7f0 1946 * @see html_component::prepare()
d9c8f425 1947 * @return void
1948 */
34059565 1949 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 1950 $this->skipid = self::$idcounter;
1951 self::$idcounter += 1;
1952 $this->add_class('sideblock');
1953 if (empty($this->blockinstanceid) || !strip_tags($this->title)) {
1954 $this->collapsible = self::NOT_HIDEABLE;
1955 }
1956 if ($this->collapsible == self::HIDDEN) {
1957 $this->add_class('hidden');
1958 }
1959 if (!empty($this->controls)) {
1960 $this->add_class('block_with_controls');
1961 }
34059565 1962 parent::prepare($output, $page, $target);
d9c8f425 1963 }
1964}
beb56299 1965
34059565 1966
beb56299 1967/**
1968 * This class represents a target for where a block can go when it is being moved.
1969 *
1970 * This needs to be rendered as a form with the given hidden from fields, and
1971 * clicking anywhere in the form should submit it. The form action should be
1972 * $PAGE->url.
1973 *
1974 * @copyright 2009 Tim Hunt
1975 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1976 * @since Moodle 2.0
1977 */
6dd7d7f0 1978class block_move_target extends html_component {
beb56299 1979 /**
1980 * List of hidden form fields.
1981 * @var array
1982 */
1983 public $url = array();
1984 /**
1985 * List of hidden form fields.
1986 * @var array
1987 */
1988 public $text = '';
1989}