MDL-20204 converting html_list
[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
5be262b6
PS
897 /**
898 * Shortcut for quick making of lists
899 * @param array $items
900 * @param string $tag ul or ol
901 * @param array $attributes
902 * @return string
903 */
904 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
905 //note: 'list' is a reserved keyword ;-)
906
907 $output = '';
908
909 foreach ($items as $item) {
910 $output .= html_writer::start_tag('li') . "\n";
911 $output .= $item . "\n";
912 $output .= html_writer::end_tag('li') . "\n";
913 }
914
915 return html_writer::tag($tag, $attributes, $output);
916 }
917
6ea66ff3
PS
918 /**
919 * Returns hidden input fields created from url parameters.
920 * @param moodle_url $url
921 * @param array $exclude list of excluded parameters
922 * @return string HTML fragment
923 */
924 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
925 $exclude = (array)$exclude;
926 $params = $url->params();
927 foreach ($exclude as $key) {
928 unset($params[$key]);
929 }
930
931 $output = '';
bde156b3 932 foreach ($params as $key => $value) {
6ea66ff3
PS
933 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
934 $output .= self::empty_tag('input', $attributes)."\n";
935 }
936 return $output;
937 }
77774f6a
PS
938
939 /**
940 * Generate a script tag containing the the specified code.
941 *
942 * @param string $js the JavaScript code
e50b4c89 943 * @param moodle_url|string optional url of the external script, $code ignored if specified
77774f6a
PS
944 * @return string HTML, the code wrapped in <script> tags.
945 */
e50b4c89 946 public static function script($jscode, $url=null) {
77774f6a 947 if ($jscode) {
e50b4c89
PS
948 $attributes = array('type'=>'text/javascript');
949 return self::tag('script', $attributes, "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
950
951 } else if ($url) {
952 $attributes = array('type'=>'text/javascript', 'src'=>$url);
953 return self::tag('script', $attributes, '') . "\n";
a9967cf5 954
77774f6a
PS
955 } else {
956 return '';
957 }
958 }
5d0c95a5
PS
959}
960
227255b8
PS
961// ==== JS writer and helper classes, will be probably moved elsewhere ======
962
963/**
964 * Simple javascript output class
965 * @copyright 2010 Petr Skoda
966 */
967class js_writer {
968 /**
969 * Returns javascript code calling the function
970 * @param string $function function name, can be complex lin Y.Event.purgeElement
971 * @param array $arguments parameters
972 * @param int $delay execution delay in seconds
973 * @return string JS code fragment
974 */
975 public function function_call($function, array $arguments = null, $delay=0) {
1b4e41af
PS
976 if ($arguments) {
977 $arguments = array_map('json_encode', $arguments);
978 $arguments = implode(', ', $arguments);
979 } else {
980 $arguments = '';
981 }
227255b8
PS
982 $js = "$function($arguments);";
983
984 if ($delay) {
985 $delay = $delay * 1000; // in miliseconds
986 $js = "setTimeout(function() { $js }, $delay);";
987 }
988 return $js . "\n";
989 }
990
3b01539c
PS
991 /**
992 * Special function which adds Y as first argument of fucntion call.
993 * @param string $function
994 * @param array $extraarguments
995 * @return string
996 */
997 public function function_call_with_Y($function, array $extraarguments = null) {
998 if ($extraarguments) {
999 $extraarguments = array_map('json_encode', $extraarguments);
1000 $arguments = 'Y, ' . implode(', ', $extraarguments);
1001 } else {
1002 $arguments = 'Y';
1003 }
1004 return "$function($arguments);\n";
1005 }
1006
1ce15fda
SH
1007 /**
1008 * Returns JavaScript code to initialise a new object
1009 * @param string|null $var If it is null then no var is assigned the new object
1010 * @param string $class
1011 * @param array $arguments
1012 * @param array $requirements
1013 * @param int $delay
1014 * @return string
1015 */
1016 public function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1017 if (is_array($arguments)) {
1018 $arguments = array_map('json_encode', $arguments);
1019 $arguments = implode(', ', $arguments);
1020 }
1021
1022 if ($var === null) {
53fc3e70 1023 $js = "new $class(Y, $arguments);";
1ce15fda 1024 } else if (strpos($var, '.')!==false) {
53fc3e70 1025 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1026 } else {
53fc3e70 1027 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1028 }
1029
1030 if ($delay) {
1031 $delay = $delay * 1000; // in miliseconds
1032 $js = "setTimeout(function() { $js }, $delay);";
1033 }
1034
1035 if (count($requirements) > 0) {
1036 $requirements = implode("', '", $requirements);
53fc3e70 1037 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1038 }
1039 return $js."\n";
1040 }
1041
227255b8
PS
1042 /**
1043 * Returns code setting value to variable
1044 * @param string $name
1045 * @param mixed $value json serialised value
1046 * @param bool $usevar add var definition, ignored for nested properties
1047 * @return string JS code fragment
1048 */
1049 public function set_variable($name, $value, $usevar=true) {
1050 $output = '';
1051
1052 if ($usevar) {
1053 if (strpos($name, '.')) {
1054 $output .= '';
1055 } else {
1056 $output .= 'var ';
1057 }
1058 }
1059
1060 $output .= "$name = ".json_encode($value).";";
1061
1062 return $output;
1063 }
1064
1065 /**
1066 * Writes event handler attaching code
1067 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
1068 * @param string $event A valid DOM event (click, mousedown, change etc.)
1069 * @param string $function The name of the function to call
1070 * @param array $arguments An optional array of argument parameters to pass to the function
1071 * @return string JS code fragment
1072 */
1073 public function event_handler($selector, $event, $function, array $arguments = null) {
1074 $selector = json_encode($selector);
1075 $output = "Y.on('$event', $function, $selector, null";
1076 if (!empty($arguments)) {
1077 $output .= ', ' . json_encode($arguments);
1078 }
1079 return $output . ");\n";
1080 }
1081}
1082
5d0c95a5
PS
1083
1084// ===============================================================================================
1085// TODO: Following components will be refactored soon
1086
d9c8f425 1087/**
4ed85790 1088 * Base class for classes representing HTML elements.
d9c8f425 1089 *
1090 * Handles the id and class attributes.
1091 *
1092 * @copyright 2009 Tim Hunt
1093 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1094 * @since Moodle 2.0
1095 */
6dd7d7f0 1096class html_component {
d9c8f425 1097 /**
1098 * @var string value to use for the id attribute of this HTML tag.
1099 */
97c10099 1100 public $id = null;
d9c8f425 1101 /**
1102 * @var string $alt value to use for the alt attribute of this HTML tag.
1103 */
97c10099 1104 public $alt = null;
d9c8f425 1105 /**
1106 * @var string $style value to use for the style attribute of this HTML tag.
1107 */
97c10099 1108 public $style = null;
d9c8f425 1109 /**
1110 * @var array class names to add to this HTML element.
1111 */
1112 public $classes = array();
1113 /**
1114 * @var string $title The title attributes applicable to any XHTML element
1115 */
97c10099 1116 public $title = null;
d9c8f425 1117 /**
1118 * An optional array of component_action objects handling the action part of this component.
1119 * @var array $actions
1120 */
1121 protected $actions = array();
d9c8f425 1122
8fa16366
PS
1123 /**
1124 * Compoment constructor.
1125 * @param array $options image attributes such as title, id, alt, style, class
1126 */
1127 public function __construct(array $options = null) {
1128 // not implemented in this class because we want to set only public properties of this component
1129 renderer_base::apply_component_options($this, $options);
1130 }
1131
d9c8f425 1132 /**
1133 * Ensure some class names are an array.
1134 * @param mixed $classes either an array of class names or a space-separated
1135 * string containing class names.
1136 * @return array the class names as an array.
1137 */
1138 public static function clean_classes($classes) {
642816a6 1139 if (empty($classes)) {
3bd6b994 1140 return array();
642816a6 1141 } else if (is_array($classes)) {
d9c8f425 1142 return $classes;
1143 } else {
1144 return explode(' ', trim($classes));
1145 }
1146 }
1147
1148 /**
1149 * Set the class name array.
1150 * @param mixed $classes either an array of class names or a space-separated
1151 * string containing class names.
1152 * @return void
1153 */
1154 public function set_classes($classes) {
1155 $this->classes = self::clean_classes($classes);
1156 }
1157
1158 /**
1159 * Add a class name to the class names array.
1160 * @param string $class the new class name to add.
1161 * @return void
1162 */
1163 public function add_class($class) {
1164 $this->classes[] = $class;
1165 }
1166
1167 /**
1168 * Add a whole lot of class names to the class names array.
1169 * @param mixed $classes either an array of class names or a space-separated
1170 * string containing class names.
1171 * @return void
1172 */
1173 public function add_classes($classes) {
eeecf5a7 1174 $this->classes = array_merge($this->classes, self::clean_classes($classes));
d9c8f425 1175 }
1176
1177 /**
1178 * Get the class names as a string.
1179 * @return string the class names as a space-separated string. Ready to be put in the class="" attribute.
1180 */
1181 public function get_classes_string() {
1182 return implode(' ', $this->classes);
1183 }
1184
1185 /**
1186 * Perform any cleanup or final processing that should be done before an
34059565
PS
1187 * instance of this class is output. This method is supposed to be called
1188 * only from renderers.
1189 *
1190 * @param renderer_base $output output renderer
1191 * @param moodle_page $page
1192 * @param string $target rendering target
d9c8f425 1193 * @return void
1194 */
34059565 1195 public function prepare(renderer_base $output, moodle_page $page, $target) {
d9c8f425 1196 $this->classes = array_unique(self::clean_classes($this->classes));
1197 }
1198
1199 /**
1200 * This checks developer do not try to assign a property directly
1201 * if we have a setter for it. Otherwise, the property is set as expected.
1202 * @param string $name The name of the variable to set
1203 * @param mixed $value The value to assign to the variable
1204 * @return void
1205 */
1206 public function __set($name, $value) {
1207 if ($name == 'class') {
1208 debugging('this way of setting css class has been deprecated. use set_classes() method instead.');
1209 $this->set_classes($value);
1210 } else {
1211 $this->{$name} = $value;
1212 }
1213 }
1214
1215 /**
1216 * Adds a JS action to this component.
1217 * Note: the JS function you write must have only two arguments: (string)event and (object|array)args
1218 * If you want to add an instantiated component_action (or one of its subclasses), give the object as the only parameter
1219 *
1220 * @param mixed $event a DOM event (click, mouseover etc.) or a component_action object
1221 * @param string $jsfunction The name of the JS function to call. required if argument 1 is a string (event)
1222 * @param array $jsfunctionargs An optional array of JS arguments to pass to the function
1223 */
1224 public function add_action($event, $jsfunction=null, $jsfunctionargs=array()) {
1225 if (empty($this->id)) {
1226 $this->generate_id();
1227 }
1228
1229 if ($event instanceof component_action) {
1230 $this->actions[] = $event;
1231 } else {
1232 if (empty($jsfunction)) {
6dd7d7f0 1233 throw new coding_exception('html_component::add_action requires a JS function argument if the first argument is a string event');
d9c8f425 1234 }
1235 $this->actions[] = new component_action($event, $jsfunction, $jsfunctionargs);
1236 }
1237 }
1238
1239 /**
1240 * Internal method for generating a unique ID for the purpose of event handlers.
1241 */
1242 protected function generate_id() {
0c868b08 1243 $this->id = uniqid(get_class($this));
d9c8f425 1244 }
1245
1246 /**
1247 * Returns the array of component_actions.
1248 * @return array Component actions
1249 */
1250 public function get_actions() {
1251 return $this->actions;
1252 }
1253
7a5c78e0 1254 /**
1255 * Shortcut for adding a JS confirm dialog when the component is clicked.
1256 * The message must be a yes/no question.
1257 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
a0ead5eb 1258 * @param string $callback The name of a JS function whose scope will be set to the simpleDialog object and have this
5529f787 1259 * function's arguments set as this.args.
7a5c78e0 1260 * @return void
1261 */
5529f787 1262 public function add_confirm_action($message, $callback=null) {
20fb563e 1263 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $message, 'callback' => $callback)));
7a5c78e0 1264 }
db49be13 1265
1266 /**
1267 * Returns true if this component has an action of the requested type (component_action by default).
1268 * @param string $class The class of the action we are looking for
1269 * @return boolean True if action is found
1270 */
1271 public function has_action($class='component_action') {
1272 foreach ($this->actions as $action) {
1273 if (get_class($action) == $class) {
1274 return true;
1275 }
1276 }
1277 return false;
1278 }
7a5c78e0 1279}
1280
34059565 1281
beb56299 1282/// Components representing HTML elements
d9c8f425 1283
34059565 1284
7b1f2c82 1285/**
1286 * Holds all the information required to render a <table> by
78946b9b 1287 * {@see core_renderer::table()} or by an overridden version of that
7b1f2c82 1288 * method in a subclass.
1289 *
1290 * Example of usage:
1291 * $t = new html_table();
1292 * ... // set various properties of the object $t as described below
1293 * echo $OUTPUT->table($t);
1294 *
1295 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1297 * @since Moodle 2.0
1298 */
f7065efe 1299class html_table extends html_component {
7b1f2c82 1300 /**
a0ead5eb 1301 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1302 * can be passed instead of an array of strings.
7b1f2c82 1303 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1304 *
1305 * Example of usage:
1306 * $t->head = array('Student', 'Grade');
1307 */
1308 public $head;
1309 /**
1310 * @var array can be used to make a heading span multiple columns
1311 *
1312 * Example of usage:
1313 * $t->headspan = array(2,1);
1314 *
1315 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1316 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1317 */
1318 public $headspan;
1319 /**
1320 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1321 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1322 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1323 *
beb56299 1324 * Examples of usage:
1325 * $t->align = array(null, 'right');
1326 * or
1327 * $t->align[1] = 'right';
1328 *
d9c8f425 1329 */
beb56299 1330 public $align;
d9c8f425 1331 /**
beb56299 1332 * @var array of column sizes. The value is used as CSS 'size' property.
1333 *
1334 * Examples of usage:
1335 * $t->size = array('50%', '50%');
1336 * or
1337 * $t->size[1] = '120px';
d9c8f425 1338 */
beb56299 1339 public $size;
d9c8f425 1340 /**
beb56299 1341 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1342 * CSS property 'white-space' to the value 'nowrap' in the given column.
1343 *
1344 * Example of usage:
1345 * $t->wrap = array(null, 'nowrap');
d9c8f425 1346 */
beb56299 1347 public $wrap;
d9c8f425 1348 /**
beb56299 1349 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1350 * $head specified, the string 'hr' (for horizontal ruler) can be used
1351 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1352 *
beb56299 1353 * Example of usage with array of arrays:
1354 * $row1 = array('Harry Potter', '76 %');
1355 * $row2 = array('Hermione Granger', '100 %');
1356 * $t->data = array($row1, $row2);
d9c8f425 1357 *
beb56299 1358 * Example with array of html_table_row objects: (used for more fine-grained control)
1359 * $cell1 = new html_table_cell();
1360 * $cell1->text = 'Harry Potter';
1361 * $cell1->colspan = 2;
1362 * $row1 = new html_table_row();
1363 * $row1->cells[] = $cell1;
1364 * $cell2 = new html_table_cell();
1365 * $cell2->text = 'Hermione Granger';
1366 * $cell3 = new html_table_cell();
1367 * $cell3->text = '100 %';
1368 * $row2 = new html_table_row();
1369 * $row2->cells = array($cell2, $cell3);
1370 * $t->data = array($row1, $row2);
1371 */
1372 public $data;
1373 /**
1374 * @var string width of the table, percentage of the page preferred. Defaults to 80% of the page width.
1375 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1376 */
1377 public $width = null;
1378 /**
1379 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1380 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1381 */
1382 public $tablealign = null;
1383 /**
1384 * @var int padding on each cell, in pixels
1385 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1386 */
1387 public $cellpadding = null;
1388 /**
1389 * @var int spacing between cells, in pixels
1390 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1391 */
1392 public $cellspacing = null;
1393 /**
1394 * @var array classes to add to particular rows, space-separated string.
1395 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1396 * respectively. Class 'lastrow' is added automatically for the last row
1397 * in the table.
d9c8f425 1398 *
beb56299 1399 * Example of usage:
1400 * $t->rowclasses[9] = 'tenth'
1401 */
1402 public $rowclasses;
1403 /**
1404 * @var array classes to add to every cell in a particular column,
1405 * space-separated string. Class 'cell' is added automatically by the renderer.
1406 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1407 * respectively. Class 'lastcol' is added automatically for all last cells
1408 * in a row.
d9c8f425 1409 *
beb56299 1410 * Example of usage:
1411 * $t->colclasses = array(null, 'grade');
d9c8f425 1412 */
beb56299 1413 public $colclasses;
1414 /**
1415 * @var string description of the contents for screen readers.
1416 */
1417 public $summary;
1418 /**
1419 * @var bool true causes the contents of the heading cells to be rotated 90 degrees.
1420 */
1421 public $rotateheaders = false;
319770d7 1422 /**
1423 * @var array $headclasses Array of CSS classes to apply to the table's thead.
1424 */
1425 public $headclasses = array();
1426 /**
1427 * @var array $bodyclasses Array of CSS classes to apply to the table's tbody.
1428 */
1429 public $bodyclasses = array();
1430 /**
1431 * @var array $footclasses Array of CSS classes to apply to the table's tfoot.
1432 */
1433 public $footclasses = array();
a0ead5eb 1434
d9c8f425 1435
1436 /**
6dd7d7f0 1437 * @see html_component::prepare()
beb56299 1438 * @return void
d9c8f425 1439 */
34059565 1440 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 1441 if (!empty($this->align)) {
1442 foreach ($this->align as $key => $aa) {
1443 if ($aa) {
1444 $this->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1445 } else {
97c10099 1446 $this->align[$key] = null;
beb56299 1447 }
1448 }
d9c8f425 1449 }
beb56299 1450 if (!empty($this->size)) {
1451 foreach ($this->size as $key => $ss) {
1452 if ($ss) {
1453 $this->size[$key] = 'width:'. $ss .';';
1454 } else {
97c10099 1455 $this->size[$key] = null;
beb56299 1456 }
1457 }
d9c8f425 1458 }
beb56299 1459 if (!empty($this->wrap)) {
1460 foreach ($this->wrap as $key => $ww) {
1461 if ($ww) {
1462 $this->wrap[$key] = 'white-space:nowrap;';
1463 } else {
1464 $this->wrap[$key] = '';
1465 }
1466 }
d9c8f425 1467 }
beb56299 1468 if (!empty($this->head)) {
1469 foreach ($this->head as $key => $val) {
1470 if (!isset($this->align[$key])) {
97c10099 1471 $this->align[$key] = null;
beb56299 1472 }
1473 if (!isset($this->size[$key])) {
97c10099 1474 $this->size[$key] = null;
beb56299 1475 }
1476 if (!isset($this->wrap[$key])) {
97c10099 1477 $this->wrap[$key] = null;
d9c8f425 1478 }
1479
d9c8f425 1480 }
beb56299 1481 }
1482 if (empty($this->classes)) { // must be done before align
1483 $this->set_classes(array('generaltable'));
1484 }
1485 if (!empty($this->tablealign)) {
1486 $this->add_class('boxalign' . $this->tablealign);
1487 }
1488 if (!empty($this->rotateheaders)) {
1489 $this->add_class('rotateheaders');
d9c8f425 1490 } else {
beb56299 1491 $this->rotateheaders = false; // Makes life easier later.
1492 }
34059565 1493 parent::prepare($output, $page, $target);
beb56299 1494 }
1495 /**
1496 * @param string $name The name of the variable to set
1497 * @param mixed $value The value to assign to the variable
1498 * @return void
1499 */
1500 public function __set($name, $value) {
1501 if ($name == 'rowclass') {
1502 debugging('rowclass[] has been deprecated for html_table ' .
7b1f2c82 1503 'and should be replaced with rowclasses[]. please fix the code.');
1504 $this->rowclasses = $value;
1505 } else {
1506 parent::__set($name, $value);
d9c8f425 1507 }
d9c8f425 1508 }
d9c8f425 1509}
1510
34059565 1511
d9c8f425 1512/**
7b1f2c82 1513 * Component representing a table row.
d9c8f425 1514 *
1515 * @copyright 2009 Nicolas Connault
1516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1517 * @since Moodle 2.0
1518 */
6dd7d7f0 1519class html_table_row extends html_component {
d9c8f425 1520 /**
7b1f2c82 1521 * @var array $cells Array of html_table_cell objects
d9c8f425 1522 */
7b1f2c82 1523 public $cells = array();
d9c8f425 1524
beb56299 1525 /**
6dd7d7f0 1526 * @see lib/html_component#prepare()
beb56299 1527 * @return void
1528 */
34059565
PS
1529 public function prepare(renderer_base $output, moodle_page $page, $target) {
1530 parent::prepare($output, $page, $target);
d9c8f425 1531 }
a0ead5eb 1532
54a007e8 1533 /**
a019627a 1534 * Shortcut method for creating a row with an array of cells. Converts cells to html_table_cell objects.
54a007e8 1535 * @param array $cells
1536 * @return html_table_row
1537 */
8fa16366 1538 public static function make($cells=array()) {
54a007e8 1539 $row = new html_table_row();
a019627a 1540 foreach ($cells as $celltext) {
1541 if (!($celltext instanceof html_table_cell)) {
1542 $cell = new html_table_cell();
1543 $cell->text = $celltext;
1544 $row->cells[] = $cell;
1545 } else {
1546 $row->cells[] = $celltext;
1547 }
1548 }
54a007e8 1549 return $row;
1550 }
d9c8f425 1551}
1552
34059565 1553
d9c8f425 1554/**
7b1f2c82 1555 * Component representing a table cell.
d9c8f425 1556 *
1557 * @copyright 2009 Nicolas Connault
1558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1559 * @since Moodle 2.0
1560 */
6dd7d7f0 1561class html_table_cell extends html_component {
d9c8f425 1562 /**
7b1f2c82 1563 * @var string $text The contents of the cell
d9c8f425 1564 */
7b1f2c82 1565 public $text;
d9c8f425 1566 /**
7b1f2c82 1567 * @var string $abbr Abbreviated version of the contents of the cell
d9c8f425 1568 */
97c10099 1569 public $abbr = null;
d9c8f425 1570 /**
7b1f2c82 1571 * @var int $colspan Number of columns this cell should span
d9c8f425 1572 */
97c10099 1573 public $colspan = null;
d9c8f425 1574 /**
7b1f2c82 1575 * @var int $rowspan Number of rows this cell should span
d9c8f425 1576 */
97c10099 1577 public $rowspan = null;
d9c8f425 1578 /**
7b1f2c82 1579 * @var string $scope Defines a way to associate header cells and data cells in a table
d9c8f425 1580 */
97c10099 1581 public $scope = null;
1ae3767a 1582 /**
1583 * @var boolean $header Whether or not this cell is a header cell
1584 */
a4998d01 1585 public $header = null;
d9c8f425 1586
1587 /**
6dd7d7f0 1588 * @see lib/html_component#prepare()
d9c8f425 1589 * @return void
1590 */
34059565 1591 public function prepare(renderer_base $output, moodle_page $page, $target) {
54a007e8 1592 if ($this->header && empty($this->scope)) {
1593 $this->scope = 'col';
1594 }
34059565 1595 parent::prepare($output, $page, $target);
d9c8f425 1596 }
1597}
1598
34059565 1599
7b1f2c82 1600/// Complex components aggregating simpler components
1601
34059565 1602
d9c8f425 1603/**
beb56299 1604 * Component representing a paging bar.
d9c8f425 1605 *
1606 * @copyright 2009 Nicolas Connault
1607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1608 * @since Moodle 2.0
1609 */
929d7a83 1610class paging_bar implements renderable {
d9c8f425 1611 /**
beb56299 1612 * @var int $maxdisplay The maximum number of pagelinks to display
d9c8f425 1613 */
beb56299 1614 public $maxdisplay = 18;
d9c8f425 1615 /**
beb56299 1616 * @var int $totalcount post or get
d9c8f425 1617 */
beb56299 1618 public $totalcount;
d9c8f425 1619 /**
beb56299 1620 * @var int $page The page you are currently viewing
d9c8f425 1621 */
929d7a83 1622 public $page;
d9c8f425 1623 /**
beb56299 1624 * @var int $perpage The number of entries that should be shown per page
d9c8f425 1625 */
beb56299 1626 public $perpage;
d9c8f425 1627 /**
beb56299 1628 * @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.
1629 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 1630 */
beb56299 1631 public $baseurl;
d9c8f425 1632 /**
beb56299 1633 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 1634 */
929d7a83 1635 public $pagevar;
beb56299 1636 /**
56ddb719 1637 * @var string $previouslink A HTML link representing the "previous" page
beb56299 1638 */
1639 public $previouslink = null;
1640 /**
56ddb719 1641 * @var tring $nextlink A HTML link representing the "next" page
beb56299 1642 */
1643 public $nextlink = null;
1644 /**
56ddb719 1645 * @var tring $firstlink A HTML link representing the first page
beb56299 1646 */
1647 public $firstlink = null;
1648 /**
56ddb719 1649 * @var tring $lastlink A HTML link representing the last page
beb56299 1650 */
1651 public $lastlink = null;
1652 /**
56ddb719 1653 * @var array $pagelinks An array of strings. One of them is just a string: the current page
beb56299 1654 */
1655 public $pagelinks = array();
d9c8f425 1656
929d7a83
PS
1657 /**
1658 * Constructor paging_bar with only the required params.
1659 *
1660 * @param int $totalcount Thetotal number of entries available to be paged through
1661 * @param int $page The page you are currently viewing
1662 * @param int $perpage The number of entries that should be shown per page
1663 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1664 * @param string $pagevar name of page parameter that holds the page number
1665 */
1666 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1667 $this->totalcount = $totalcount;
1668 $this->page = $page;
1669 $this->perpage = $perpage;
1670 $this->baseurl = $baseurl;
1671 $this->pagevar = $pagevar;
1672 }
1673
d9c8f425 1674 /**
6dd7d7f0 1675 * @see lib/html_component#prepare()
d9c8f425 1676 * @return void
1677 */
34059565 1678 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 1679 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 1680 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 1681 }
1682 if (!isset($this->page) || is_null($this->page)) {
929d7a83 1683 throw new coding_exception('paging_bar requires a page value.');
beb56299 1684 }
1685 if (empty($this->perpage)) {
929d7a83 1686 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 1687 }
1688 if (empty($this->baseurl)) {
929d7a83 1689 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 1690 }
d9c8f425 1691
beb56299 1692 if ($this->totalcount > $this->perpage) {
1693 $pagenum = $this->page - 1;
d9c8f425 1694
beb56299 1695 if ($this->page > 0) {
929d7a83 1696 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 1697 }
d9c8f425 1698
beb56299 1699 if ($this->perpage > 0) {
1700 $lastpage = ceil($this->totalcount / $this->perpage);
1701 } else {
1702 $lastpage = 1;
1703 }
1704
1705 if ($this->page > 15) {
1706 $startpage = $this->page - 10;
1707
929d7a83 1708 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 1709 } else {
1710 $startpage = 0;
1711 }
1712
1713 $currpage = $startpage;
1714 $displaycount = $displaypage = 0;
1715
1716 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1717 $displaypage = $currpage + 1;
1718
f43cdceb 1719 if ($this->page == $currpage) {
beb56299 1720 $this->pagelinks[] = $displaypage;
1721 } else {
56ddb719 1722 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 1723 $this->pagelinks[] = $pagelink;
1724 }
1725
1726 $displaycount++;
1727 $currpage++;
1728 }
1729
1730 if ($currpage < $lastpage) {
1731 $lastpageactual = $lastpage - 1;
abdac127 1732 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 1733 }
1734
1735 $pagenum = $this->page + 1;
1736
1737 if ($pagenum != $displaypage) {
abdac127 1738 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 1739 }
d9c8f425 1740 }
1741 }
d9c8f425 1742}
1743
34059565 1744
d9c8f425 1745/**
beb56299 1746 * This class represents how a block appears on a page.
d9c8f425 1747 *
beb56299 1748 * During output, each block instance is asked to return a block_contents object,
1749 * those are then passed to the $OUTPUT->block function for display.
1750 *
1751 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
1752 *
1753 * Other block-like things that need to appear on the page, for example the
1754 * add new block UI, are also represented as block_contents objects.
1755 *
1756 * @copyright 2009 Tim Hunt
d9c8f425 1757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1758 * @since Moodle 2.0
1759 */
6dd7d7f0 1760class block_contents extends html_component {
beb56299 1761 /** @var int used to set $skipid. */
1762 protected static $idcounter = 1;
1763
1764 const NOT_HIDEABLE = 0;
1765 const VISIBLE = 1;
1766 const HIDDEN = 2;
1767
d9c8f425 1768 /**
beb56299 1769 * @param integer $skipid All the blocks (or things that look like blocks)
1770 * printed on a page are given a unique number that can be used to construct
1771 * id="" attributes. This is set automatically be the {@link prepare()} method.
1772 * Do not try to set it manually.
d9c8f425 1773 */
beb56299 1774 public $skipid;
d9c8f425 1775
1776 /**
beb56299 1777 * @var integer If this is the contents of a real block, this should be set to
1778 * the block_instance.id. Otherwise this should be set to 0.
1779 */
1780 public $blockinstanceid = 0;
1781
1782 /**
1783 * @var integer if this is a real block instance, and there is a corresponding
1784 * block_position.id for the block on this page, this should be set to that id.
1785 * Otherwise it should be 0.
1786 */
1787 public $blockpositionid = 0;
1788
1789 /**
1790 * @param array $attributes an array of attribute => value pairs that are put on the
1791 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
1792 */
1793 public $attributes = array();
1794
1795 /**
1796 * @param string $title The title of this block. If this came from user input,
1797 * it should already have had format_string() processing done on it. This will
1798 * be output inside <h2> tags. Please do not cause invalid XHTML.
1799 */
1800 public $title = '';
1801
1802 /**
1803 * @param string $content HTML for the content
1804 */
1805 public $content = '';
1806
1807 /**
1808 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1809 */
1810 public $footer = '';
1811
1812 /**
1813 * Any small print that should appear under the block to explain to the
1814 * teacher about the block, for example 'This is a sticky block that was
1815 * added in the system context.'
1816 * @var string
1817 */
1818 public $annotation = '';
1819
1820 /**
1821 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
1822 * the user can toggle whether this block is visible.
1823 */
1824 public $collapsible = self::NOT_HIDEABLE;
1825
1826 /**
1827 * A (possibly empty) array of editing controls. Each element of this array
1828 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 1829 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 1830 * @var array
1831 */
1832 public $controls = array();
1833
1834 /**
6dd7d7f0 1835 * @see html_component::prepare()
d9c8f425 1836 * @return void
1837 */
34059565 1838 public function prepare(renderer_base $output, moodle_page $page, $target) {
beb56299 1839 $this->skipid = self::$idcounter;
1840 self::$idcounter += 1;
1841 $this->add_class('sideblock');
1842 if (empty($this->blockinstanceid) || !strip_tags($this->title)) {
1843 $this->collapsible = self::NOT_HIDEABLE;
1844 }
1845 if ($this->collapsible == self::HIDDEN) {
1846 $this->add_class('hidden');
1847 }
1848 if (!empty($this->controls)) {
1849 $this->add_class('block_with_controls');
1850 }
34059565 1851 parent::prepare($output, $page, $target);
d9c8f425 1852 }
1853}
beb56299 1854
34059565 1855
beb56299 1856/**
1857 * This class represents a target for where a block can go when it is being moved.
1858 *
1859 * This needs to be rendered as a form with the given hidden from fields, and
1860 * clicking anywhere in the form should submit it. The form action should be
1861 * $PAGE->url.
1862 *
1863 * @copyright 2009 Tim Hunt
1864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1865 * @since Moodle 2.0
1866 */
6dd7d7f0 1867class block_move_target extends html_component {
beb56299 1868 /**
1869 * List of hidden form fields.
1870 * @var array
1871 */
1872 public $url = array();
1873 /**
1874 * List of hidden form fields.
1875 * @var array
1876 */
1877 public $text = '';
1878}