MDL-19756 Renamed help_icon class to moodle_help_icon
[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
29/**
30 * Base class for classes representing HTML elements, like moodle_select.
31 *
32 * Handles the id and class attributes.
33 *
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @since Moodle 2.0
37 */
38class moodle_html_component {
39 /**
40 * @var string value to use for the id attribute of this HTML tag.
41 */
42 public $id = '';
43 /**
44 * @var string $alt value to use for the alt attribute of this HTML tag.
45 */
46 public $alt = '';
47 /**
48 * @var string $style value to use for the style attribute of this HTML tag.
49 */
50 public $style = '';
51 /**
52 * @var array class names to add to this HTML element.
53 */
54 public $classes = array();
55 /**
56 * @var string $title The title attributes applicable to any XHTML element
57 */
58 public $title = '';
59 /**
60 * An optional array of component_action objects handling the action part of this component.
61 * @var array $actions
62 */
63 protected $actions = array();
64 /**
65 * This array of generated ids is kept static to avoid id collisions
66 * @var array $generated_ids
67 */
68 public static $generated_ids = array();
69
70 /**
71 * Ensure some class names are an array.
72 * @param mixed $classes either an array of class names or a space-separated
73 * string containing class names.
74 * @return array the class names as an array.
75 */
76 public static function clean_classes($classes) {
77 if (is_array($classes)) {
78 return $classes;
79 } else {
80 return explode(' ', trim($classes));
81 }
82 }
83
84 /**
85 * Set the class name array.
86 * @param mixed $classes either an array of class names or a space-separated
87 * string containing class names.
88 * @return void
89 */
90 public function set_classes($classes) {
91 $this->classes = self::clean_classes($classes);
92 }
93
94 /**
95 * Add a class name to the class names array.
96 * @param string $class the new class name to add.
97 * @return void
98 */
99 public function add_class($class) {
100 $this->classes[] = $class;
101 }
102
103 /**
104 * Add a whole lot of class names to the class names array.
105 * @param mixed $classes either an array of class names or a space-separated
106 * string containing class names.
107 * @return void
108 */
109 public function add_classes($classes) {
110 $this->classes += self::clean_classes($classes);
111 }
112
113 /**
114 * Get the class names as a string.
115 * @return string the class names as a space-separated string. Ready to be put in the class="" attribute.
116 */
117 public function get_classes_string() {
118 return implode(' ', $this->classes);
119 }
120
121 /**
122 * Perform any cleanup or final processing that should be done before an
123 * instance of this class is output.
124 * @return void
125 */
126 public function prepare() {
127 $this->classes = array_unique(self::clean_classes($this->classes));
128 }
129
130 /**
131 * This checks developer do not try to assign a property directly
132 * if we have a setter for it. Otherwise, the property is set as expected.
133 * @param string $name The name of the variable to set
134 * @param mixed $value The value to assign to the variable
135 * @return void
136 */
137 public function __set($name, $value) {
138 if ($name == 'class') {
139 debugging('this way of setting css class has been deprecated. use set_classes() method instead.');
140 $this->set_classes($value);
141 } else {
142 $this->{$name} = $value;
143 }
144 }
145
146 /**
147 * Adds a JS action to this component.
148 * Note: the JS function you write must have only two arguments: (string)event and (object|array)args
149 * If you want to add an instantiated component_action (or one of its subclasses), give the object as the only parameter
150 *
151 * @param mixed $event a DOM event (click, mouseover etc.) or a component_action object
152 * @param string $jsfunction The name of the JS function to call. required if argument 1 is a string (event)
153 * @param array $jsfunctionargs An optional array of JS arguments to pass to the function
154 */
155 public function add_action($event, $jsfunction=null, $jsfunctionargs=array()) {
156 if (empty($this->id)) {
157 $this->generate_id();
158 }
159
160 if ($event instanceof component_action) {
161 $this->actions[] = $event;
162 } else {
163 if (empty($jsfunction)) {
164 throw new coding_exception('moodle_html_component::add_action requires a JS function argument if the first argument is a string event');
165 }
166 $this->actions[] = new component_action($event, $jsfunction, $jsfunctionargs);
167 }
168 }
169
170 /**
171 * Internal method for generating a unique ID for the purpose of event handlers.
172 */
173 protected function generate_id() {
174 // Generate an id that is not already used.
175 do {
176 $newid = get_class($this) . '-' . substr(sha1(microtime() * rand(0, 500)), 0, 6);
177 } while (in_array($this->id, moodle_html_component::$generated_ids));
178 $this->id = $newid;
179 moodle_html_component::$generated_ids[] = $newid;
180 }
181
182 /**
183 * Returns the array of component_actions.
184 * @return array Component actions
185 */
186 public function get_actions() {
187 return $this->actions;
188 }
189
190 /**
191 * Adds a descriptive label to the component.
192 *
193 * This can be used in two ways:
194 *
195 * <pre>
196 * $component->set_label($elementlabel, $elementid);
197 * // OR
198 * $label = new html_label();
199 * $label->for = $elementid;
200 * $label->text = $elementlabel;
201 * $component->set_label($label);
202 * </pre>
203 *
204 * Use the second form when you need to add additional HTML attributes
205 * to the label and/or JS actions.
206 *
207 * @param mixed $text Either the text of the label or a html_label object
208 * @param text $for The value of the "for" attribute (the associated element's id)
209 * @return void
210 */
211 public function set_label($text, $for=null) {
212 if ($text instanceof html_label) {
213 $this->label = $text;
214 } else if (!empty($text)) {
215 $this->label = new html_label();
216 $this->label->for = $for;
217 if (empty($for) && !empty($this->id)) {
218 $this->label->for = $this->id;
219 }
220 $this->label->text = $text;
221 }
222 }
223}
224
225
226/**
227 * This class hold all the information required to describe a <select> menu that
228 * will be printed by {@link moodle_core_renderer::select()}. (Or by an overridden
229 * version of that method in a subclass.)
230 *
231 * This component can also hold enough metadata to be used as a popup form. It just
232 * needs a bit more setting up than for a simple menu. See the shortcut methods for
233 * developer-friendly usage.
234 *
235 * All the fields that are not set by the constructor have sensible defaults, so
236 * you only need to set the properties where you want non-default behaviour.
237 *
238 * @copyright 2009 Tim Hunt
239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
240 * @since Moodle 2.0
241 */
242class moodle_select extends moodle_html_component {
243 /**
244 * The moodle_select object parses an array of options into component objects
245 * @see nested attribute
246 * @var mixed $options the choices to show in the menu. An array $value => $display, of html_select_option or of html_select_optgroup objects.
247 */
248 public $options;
249 /**
250 * @var string $name the name of this form control. That is, the name of the GET/POST
251 * variable that will be set if this select is submitted as part of a form.
252 */
253 public $name;
254 /**
255 * @var mixed $label The label for that component. String or html_label object
256 */
257 public $label;
258 /**
259 * @var string $selectedvalue the option to select initially. Should match one
260 * of the $options array keys. Default none.
261 */
262 public $selectedvalue;
263 /**
264 * Defaults to get_string('choosedots').
265 * Set this to '' if you do not want a 'nothing is selected' option.
266 * This is ignored if the rendertype is 'radio' or 'checkbox'
267 * @var string The label for the 'nothing is selected' option.
268 */
269 public $nothinglabel = null;
270 /**
271 * @var string The value returned by the 'nothing is selected' option. Defaults to 0.
272 */
273 public $nothingvalue = 0;
274 /**
275 * @var boolean set this to true if you want the control to appear disabled.
276 */
277 public $disabled = false;
278 /**
279 * @var integer if non-zero, sets the tabindex attribute on the <select> element. Default 0.
280 */
281 public $tabindex = 0;
282 /**
283 * @var mixed Defaults to false, which means display the select as a dropdown menu.
284 * If true, display this select as a list box whose size is chosen automatically.
285 * If an integer, display as list box of that size.
286 */
287 public $listbox = false;
288 /**
289 * @var integer if you are using $listbox === true to get an automatically
290 * sized list box, the size of the list box will be the number of options,
291 * or this number, whichever is smaller.
292 */
293 public $maxautosize = 10;
294 /**
295 * @var boolean if true, allow multiple selection. Only used if $listbox is true, or if
296 * the select is to be output as checkboxes.
297 */
298 public $multiple = false;
299 /**
300 * Another way to use nested menu is to prefix optgroup labels with -- and end the optgroup with --
301 * Leave this setting to false if you are using the latter method.
302 * @var boolean $nested if true, uses $options' keys as option headings (optgroup)
303 */
304 public $nested = false;
305 /**
306 * @var html_form $form An optional html_form component
307 */
308 public $form;
309 /**
94056d9d 310 * @var moodle_help_icon $form An optional moodle_help_icon component
d9c8f425 311 */
312 public $helpicon;
313 /**
314 * @var boolean $rendertype How the select element should be rendered: menu or radio (checkbox is just radio + multiple)
315 */
316 public $rendertype = 'menu';
317
318 /**
319 * @see moodle_html_component::prepare()
320 * @return void
321 */
322 public function prepare() {
323 global $CFG;
324
325 // name may contain [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
326 if (empty($this->id)) {
327 $this->id = 'menu' . str_replace(array('[', ']'), '', $this->name);
328 }
329
330 if (empty($this->classes)) {
331 $this->set_classes(array('menu' . str_replace(array('[', ']'), '', $this->name)));
332 }
333
334 if (is_null($this->nothinglabel)) {
335 $this->nothinglabel = get_string('choosedots');
336 }
337
338 if (!empty($this->label) && !($this->label instanceof html_label)) {
339 $label = new html_label();
340 $label->text = $this->label;
341 $label->for = $this->name;
342 $this->label = $label;
343 }
344
345 $this->add_class('select');
346
347 $this->initialise_options();
348 parent::prepare();
349 }
350
351 /**
352 * This is a shortcut for making a simple select menu. It lets you specify
353 * the options, name and selected option in one line of code.
354 * @param array $options used to initialise {@link $options}.
355 * @param string $name used to initialise {@link $name}.
356 * @param string $selected used to initialise {@link $selected}.
357 * @return moodle_select A moodle_select object with the three common fields initialised.
358 */
359 public static function make($options, $name, $selected = '') {
360 $menu = new moodle_select();
361 $menu->options = $options;
362 $menu->name = $name;
363 $menu->selectedvalue = $selected;
364 return $menu;
365 }
366
367 /**
368 * This is a shortcut for making a yes/no select menu.
369 * @param string $name used to initialise {@link $name}.
370 * @param string $selected used to initialise {@link $selected}.
371 * @return moodle_select A menu initialised with yes/no options.
372 */
373 public static function make_yes_no($name, $selected) {
374 return self::make(array(0 => get_string('no'), 1 => get_string('yes')), $name, $selected);
375 }
376
377 /**
378 * This is a shortcut for making an hour selector menu.
379 * @param string $type The type of selector (years, months, days, hours, minutes)
380 * @param string $name fieldname
381 * @param int $currenttime A default timestamp in GMT
382 * @param int $step minute spacing
383 * @return moodle_select A menu initialised with hour options.
384 */
385 public static function make_time_selector($type, $name, $currenttime=0, $step=5) {
386
387 if (!$currenttime) {
388 $currenttime = time();
389 }
390 $currentdate = usergetdate($currenttime);
391 $userdatetype = $type;
392
393 switch ($type) {
394 case 'years':
395 for ($i=1970; $i<=2020; $i++) {
396 $timeunits[$i] = $i;
397 }
398 $userdatetype = 'year';
399 break;
400 case 'months':
401 for ($i=1; $i<=12; $i++) {
402 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
403 }
404 $userdatetype = 'month';
405 break;
406 case 'days':
407 for ($i=1; $i<=31; $i++) {
408 $timeunits[$i] = $i;
409 }
410 $userdatetype = 'mday';
411 break;
412 case 'hours':
413 for ($i=0; $i<=23; $i++) {
414 $timeunits[$i] = sprintf("%02d",$i);
415 }
416 break;
417 case 'minutes':
418 if ($step != 1) {
419 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
420 }
421
422 for ($i=0; $i<=59; $i+=$step) {
423 $timeunits[$i] = sprintf("%02d",$i);
424 }
425 break;
426 default:
427 throw new coding_exception("Time type $type is not supported by moodle_select::make_time_selector().");
428 }
429
430 $timerselector = self::make($timeunits, $name, $currentdate[$userdatetype]);
431 $timerselector->label = new html_label();
432 $timerselector->label->text = get_string(substr($type, -1), 'form');
433 $timerselector->label->for = "menu$timerselector->name";
434 $timerselector->label->add_class('accesshide');
435 $timerselector->nothinglabel = '';
436
437 return $timerselector;
438 }
439
440 /**
441 * Given an associative array of type => fieldname and an optional timestamp,
442 * returns an array of moodle_select components representing date/time selectors.
443 * @param array $selectors Arrays of type => fieldname. Selectors will be returned in the order of the types given
444 * @param int $currenttime A UNIX timestamp
445 * @param int $step minute spacing
446 * @return array Instantiated date/time selectors
447 */
448 public function make_time_selectors($selectors, $currenttime=0, $step=5) {
449 $selects = array();
450 foreach ($selectors as $type => $name) {
451 $selects[] = moodle_select::make_time_selector($type, $name, $currenttime, $step);
452 }
453 return $selects;
454 }
455
456 /**
457 * This is a shortcut for making a select popup form.
458 * @param mixed $baseurl The target URL, string or moodle_url
459 * @param string $name The variable which this select's options are changing in the URL
460 * @param array $options A list of value-label pairs for the popup list
461 * @param string $formid id for the control. Must be unique on the page. Used in the HTML.
462 * @param string $selected The option that is initially selected
463 * @return moodle_select A menu initialised as a popup form.
464 */
465 public function make_popup_form($baseurl, $name, $options, $formid, $selected=null) {
466 global $CFG;
467
468 $selectedurl = null;
469
470 if (!($baseurl instanceof moodle_url)) {
471 $baseurl = new moodle_url($baseurl);
472 }
473
474 if (!empty($selected)) {
475 $selectedurl = $baseurl->out(false, array($name => $selected), false);
476 }
477
478 if (!($baseurl instanceof moodle_url)) {
479 $baseurl = new moodle_url($baseurl);
480 }
481
482 // Replace real value by formatted URLs
483 foreach ($options as $value => $label) {
484 $options[$baseurl->out(false, array($name => $value), false)] = $label;
485 unset($options[$value]);
486 }
487
488 $select = self::make($options, 'jump', $selectedurl);
489
490 $select->form = new html_form();
491 $select->form->id = $formid;
492 $select->form->method = 'get';
493 $select->form->add_class('popupform');
494 $select->form->url = new moodle_url($CFG->wwwroot . '/course/jumpto.php', array('sesskey' => sesskey()));
495 $select->form->button->text = get_string('go');
496
497 $select->id = $formid . '_jump';
498
499 $select->add_action('change', 'submit_form_by_id', array('id' => $formid, 'selectid' => $select->id));
500
501 return $select;
502 }
503
504 /**
505 * Override the URLs of the default popup_form, which only supports one base URL
506 * @param array $options value=>label pairs representing select options
507 * @return void
508 */
509 public function override_option_values($options) {
510 global $PAGE;
511
512 $this->initialise_options();
513
514 reset($options);
515
516 foreach ($this->options as $optkey => $optgroup) {
517 if ($optgroup instanceof html_select_optgroup) {
518 foreach ($optgroup->options as $key => $option) {
519 next($options);
520 $this->options[$optkey]->options[$key]->value = key($options);
521
522 $optionurl = new moodle_url(key($options));
523
524 if ($optionurl->compare($PAGE->url, URL_MATCH_PARAMS)) {
525 $this->options[$optkey]->options[$key]->selected = 'selected';
526 }
527 }
528 next($options);
529 } else if ($optgroup instanceof html_select_option) {
530 next($options);
531 $this->options[$optkey]->value = key($options);
532 $optionurl = new moodle_url(key($options));
533
534 if ($optionurl->compare($PAGE->url, URL_MATCH_PARAMS)) {
535 $this->options[$optkey]->selected = 'selected';
536 }
537 }
538 }
539 }
540
541 /**
542 * Adds a help icon next to the select menu.
543 *
544 * This can be used in two ways:
545 *
546 * <pre>
547 * $select->set_help_icon($page, $text, $linktext);
548 * // OR
94056d9d 549 * $helpicon = new moodle_help_icon();
d9c8f425 550 * $helpicon->page = $page;
551 * $helpicon->text = $text;
552 * $helpicon->linktext = $linktext;
553 * $select->set_help_icon($helpicon);
554 * </pre>
555 *
556 * Use the second form when you need to add additional HTML attributes
557 * to the label and/or JS actions.
558 *
94056d9d 559 * @param mixed $page Either the keyword that defines a help page or a moodle_help_icon object
d9c8f425 560 * @param text $text The text of the help icon
561 * @param boolean $linktext Whether or not to show text next to the icon
562 * @return void
563 */
564 public function set_help_icon($page, $text, $linktext=false) {
94056d9d 565 if ($page instanceof moodle_help_icon) {
d9c8f425 566 $this->helpicon = $page;
567 } else if (!empty($page)) {
94056d9d 568 $this->helpicon = new moodle_help_icon();
d9c8f425 569 $this->helpicon->page = $page;
570 $this->helpicon->text = $text;
571 $this->helpicon->linktext = $linktext;
572 }
573 }
574
575 /**
576 * Parses the $options array and instantiates html_select_option objects in
577 * the place of the original value => label pairs. This is useful for when you
578 * need to setup extra html attributes and actions on individual options before
579 * the component is sent to the renderer
580 * @return void;
581 */
582 public function initialise_options() {
583 // If options are already instantiated objects, stop here
584 $firstoption = reset($this->options);
585 if ($firstoption instanceof html_select_option || $firstoption instanceof html_select_optgroup) {
586 return;
587 }
588
589 if ($this->rendertype == 'radio' && $this->multiple) {
590 $this->rendertype = 'checkbox';
591 }
592
593 // If nested is on, or if radio/checkbox rendertype is set, remove the default Choose option
594 if ($this->nested || $this->rendertype == 'radio' || $this->rendertype == 'checkbox') {
595 $this->nothinglabel = '';
596 }
597
598 $options = $this->options;
599
600 $this->options = array();
601
602 if ($this->nested && $this->rendertype != 'menu') {
603 throw new coding_exception('moodle_select cannot render nested options as radio buttons or checkboxes.');
604 } else if ($this->nested) {
605 foreach ($options as $section => $values) {
606 $optgroup = new html_select_optgroup();
607 $optgroup->text = $section;
608
609 foreach ($values as $value => $display) {
610 $option = new html_select_option();
611 $option->value = s($value);
612 $option->text = $display;
613 if ($display === '') {
614 $option->text = $value;
615 }
616
617 if ((string) $value == (string) $this->selectedvalue ||
618 (is_array($this->selectedvalue) && in_array($value, $this->selectedvalue))) {
619 $option->selected = 'selected';
620 }
621
622 $optgroup->options[] = $option;
623 }
624
625 $this->options[] = $optgroup;
626 }
627 } else {
628 $inoptgroup = false;
629 $optgroup = false;
630
631 foreach ($options as $value => $display) {
632 if ($display == '--') { /// we are ending previous optgroup
633 // $this->options[] = $optgroup;
634 $inoptgroup = false;
635 continue;
636 } else if (substr($display,0,2) == '--') { /// we are starting a new optgroup
637 if (!empty($optgroup->options)) {
638 $this->options[] = $optgroup;
639 }
640
641 $optgroup = new html_select_optgroup();
642 $optgroup->text = substr($display,2); // stripping the --
643
644 $inoptgroup = true; /// everything following will be in an optgroup
645 continue;
646
647 } else {
648 // Add $nothing option if there are not optgroups
649 if ($this->nothinglabel && empty($this->options[0]) && !$inoptgroup) {
650 $nothingoption = new html_select_option();
651 $nothingoption->value = 0;
652 if (!empty($this->nothingvalue)) {
653 $nothingoption->value = $this->nothingvalue;
654 }
655 $nothingoption->text = $this->nothinglabel;
656 $this->options = array($nothingoption) + $this->options;
657 }
658
659 $option = new html_select_option();
660 $option->text = $display;
661
662 if ($display === '') {
663 $option->text = $value;
664 }
665
666 if ((string) $value == (string) $this->selectedvalue ||
667 (is_array($this->selectedvalue) && in_array($value, $this->selectedvalue))) {
668 $option->selected = 'selected';
669 }
670
671 $option->value = s($value);
672
673 if ($inoptgroup) {
674 $optgroup->options[] = $option;
675 } else {
676 $this->options[] = $option;
677 }
678 }
679 }
680
681 if ($optgroup) {
682 $this->options[] = $optgroup;
683 }
684 }
685 }
686}
687
688/**
689 * This class represents a label element
690 *
691 * @copyright 2009 Nicolas Connault
692 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 * @since Moodle 2.0
694 */
695class html_label extends moodle_html_component {
696 /**
697 * @var string $text The text to display in the label
698 */
699 public $text;
700 /**
701 * @var string $for The name of the form field this label is associated with
702 */
703 public $for;
704
705 /**
706 * @see moodle_html_component::prepare()
707 * @return void
708 */
709 public function prepare() {
710 if (empty($this->text)) {
711 throw new coding_exception('html_label must have a $text value.');
712 }
713 parent::prepare();
714 }
715}
716
717/**
718 * This class represents a select option element
719 *
720 * @copyright 2009 Nicolas Connault
721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
722 * @since Moodle 2.0
723 */
724class html_select_option extends moodle_html_component {
725 /**
726 * @var string $value The value of this option (will be sent with form)
727 */
728 public $value;
729 /**
730 * @var string $text The display value of the option
731 */
732 public $text;
733 /**
734 * @var boolean $selected Whether or not this option is selected
735 */
736 public $selected = false;
737 /**
738 * @var mixed $label The label for that component. String or html_label object
739 */
740 public $label;
741
742 public function __construct() {
743 $this->label = new html_label();
744 }
745
746 /**
747 * @see moodle_html_component::prepare()
748 * @return void
749 */
750 public function prepare() {
751 if (empty($this->text)) {
752 throw new coding_exception('html_select_option requires a $text value.');
753 }
754
755 if (empty($this->label->text)) {
756 $this->set_label($this->text);
757 } else if (!($this->label instanceof html_label)) {
758 $this->set_label($this->label);
759 }
760 if (empty($this->id)) {
761 $this->generate_id();
762 }
763
764 parent::prepare();
765 }
766
767 /**
768 * Shortcut for making a checkbox-ready option
769 * @param string $value The value of the checkbox
770 * @param boolean $checked
771 * @param string $label
772 * @param string $alt
773 * @return html_select_option A component ready for $OUTPUT->checkbox()
774 */
775 public function make_checkbox($value, $checked, $label='', $alt='') {
776 $checkbox = new html_select_option();
777 $checkbox->value = $value;
778 $checkbox->selected = $checked;
779 $checkbox->text = $label;
780 $checkbox->label->text = $label;
781 $checkbox->alt = $alt;
782 return $checkbox;
783 }
784}
785
786/**
787 * This class represents a select optgroup element
788 *
789 * @copyright 2009 Nicolas Connault
790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
791 * @since Moodle 2.0
792 */
793class html_select_optgroup extends moodle_html_component {
794 /**
795 * @var string $text The display value of the optgroup
796 */
797 public $text;
798 /**
799 * @var array $options An array of html_select_option objects
800 */
801 public $options = array();
802
803 public function prepare() {
804 if (empty($this->text)) {
805 throw new coding_exception('html_select_optgroup requires a $text value.');
806 }
807 if (empty($this->options)) {
808 throw new coding_exception('html_select_optgroup requires at least one html_select_option object');
809 }
810 parent::prepare();
811 }
812}
813
814/**
815 * This class represents an input field
816 *
817 * @copyright 2009 Nicolas Connault
818 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
819 * @since Moodle 2.0
820 */
821class html_field extends moodle_html_component {
822 /**
823 * @var string $name The name attribute of the field
824 */
825 public $name;
826 /**
827 * @var string $value The value attribute of the field
828 */
829 public $value;
830 /**
831 * @var string $type The type attribute of the field (text, submit, checkbox etc)
832 */
833 public $type;
834 /**
835 * @var string $maxlength The maxlength attribute of the field (only applies to text type)
836 */
837 public $maxlength;
838 /**
839 * @var mixed $label The label for that component. String or html_label object
840 */
841 public $label;
842
843 public function __construct() {
844 $this->label = new html_label();
845 }
846
847 /**
848 * @see moodle_html_component::prepare()
849 * @return void
850 */
851 public function prepare() {
852 if (empty($this->style)) {
853 $this->style = 'width: 4em;';
854 }
855 if (empty($this->id)) {
856 $this->generate_id();
857 }
858 parent::prepare();
859 }
860
861 /**
862 * Shortcut for creating a text input component.
863 * @param string $name The name of the text field
864 * @param string $value The value of the text field
865 * @param string $alt The info to be inserted in the alt tag
866 * @param int $maxlength Sets the maxlength attribute of the field. Not set by default
867 * @return html_field The field component
868 */
869 public static function make_text($name='unnamed', $value, $alt, $maxlength=0) {
870 $field = new html_field();
871 if (empty($alt)) {
872 $alt = get_string('textfield');
873 }
874 $field->type = 'text';
875 $field->name = $name;
876 $field->value = $value;
877 $field->alt = $alt;
878 $field->maxlength = $maxlength;
879 return $field;
880 }
881}
882
883/**
884 * This class represents how a block appears on a page.
885 *
886 * During output, each block instance is asked to return a block_contents object,
887 * those are then passed to the $OUTPUT->block function for display.
888 *
889 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
890 *
891 * Other block-like things that need to appear on the page, for example the
892 * add new block UI, are also represented as block_contents objects.
893 *
894 * @copyright 2009 Tim Hunt
895 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
896 * @since Moodle 2.0
897 */
898class block_contents extends moodle_html_component {
899 /** @var int used to set $skipid. */
900 protected static $idcounter = 1;
901
902 const NOT_HIDEABLE = 0;
903 const VISIBLE = 1;
904 const HIDDEN = 2;
905
906 /**
907 * @param integer $skipid All the blocks (or things that look like blocks)
908 * printed on a page are given a unique number that can be used to construct
909 * id="" attributes. This is set automatically be the {@link prepare()} method.
910 * Do not try to set it manually.
911 */
912 public $skipid;
913
914 /**
915 * @var integer If this is the contents of a real block, this should be set to
916 * the block_instance.id. Otherwise this should be set to 0.
917 */
918 public $blockinstanceid = 0;
919
920 /**
921 * @var integer if this is a real block instance, and there is a corresponding
922 * block_position.id for the block on this page, this should be set to that id.
923 * Otherwise it should be 0.
924 */
925 public $blockpositionid = 0;
926
927 /**
928 * @param array $attributes an array of attribute => value pairs that are put on the
929 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
930 */
931 public $attributes = array();
932
933 /**
934 * @param string $title The title of this block. If this came from user input,
935 * it should already have had format_string() processing done on it. This will
936 * be output inside <h2> tags. Please do not cause invalid XHTML.
937 */
938 public $title = '';
939
940 /**
941 * @param string $content HTML for the content
942 */
943 public $content = '';
944
945 /**
946 * @param array $list an alternative to $content, it you want a list of things with optional icons.
947 */
948 public $footer = '';
949
950 /**
951 * Any small print that should appear under the block to explain to the
952 * teacher about the block, for example 'This is a sticky block that was
953 * added in the system context.'
954 * @var string
955 */
956 public $annotation = '';
957
958 /**
959 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
960 * the user can toggle whether this block is visible.
961 */
962 public $collapsible = self::NOT_HIDEABLE;
963
964 /**
965 * A (possibly empty) array of editing controls. Each element of this array
966 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
967 * $icon is the icon name. Fed to $OUTPUT->old_icon_url.
968 * @var array
969 */
970 public $controls = array();
971
972 /**
973 * @see moodle_html_component::prepare()
974 * @return void
975 */
976 public function prepare() {
977 $this->skipid = self::$idcounter;
978 self::$idcounter += 1;
979 $this->add_class('sideblock');
980 if (empty($this->blockinstanceid) || !strip_tags($this->title)) {
981 $this->collapsible = self::NOT_HIDEABLE;
982 }
983 if ($this->collapsible == self::HIDDEN) {
984 $this->add_class('hidden');
985 }
986 if (!empty($this->controls)) {
987 $this->add_class('block_with_controls');
988 }
989 parent::prepare();
990 }
991}
992
993
994/**
995 * This class represents a target for where a block can go when it is being moved.
996 *
997 * This needs to be rendered as a form with the given hidden from fields, and
998 * clicking anywhere in the form should submit it. The form action should be
999 * $PAGE->url.
1000 *
1001 * @copyright 2009 Tim Hunt
1002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1003 * @since Moodle 2.0
1004 */
1005class block_move_target extends moodle_html_component {
1006 /**
1007 * List of hidden form fields.
1008 * @var array
1009 */
1010 public $url = array();
1011 /**
1012 * List of hidden form fields.
1013 * @var array
1014 */
1015 public $text = '';
1016}
1017
1018
1019/**
1020 * Holds all the information required to render a <table> by
1021 * {@see moodle_core_renderer::table()} or by an overridden version of that
1022 * method in a subclass.
1023 *
1024 * Example of usage:
1025 * $t = new html_table();
1026 * ... // set various properties of the object $t as described below
1027 * echo $OUTPUT->table($t);
1028 *
1029 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1031 * @since Moodle 2.0
1032 */
1033class html_table extends moodle_html_component {
1034 /**
1035 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1036 *
1037 * Example of usage:
1038 * $t->head = array('Student', 'Grade');
1039 */
1040 public $head;
1041 /**
1042 * @var array can be used to make a heading span multiple columns
1043 *
1044 * Example of usage:
1045 * $t->headspan = array(2,1);
1046 *
1047 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1048 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1049 */
1050 public $headspan;
1051 /**
1052 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1053 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1054 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1055 *
1056 * Examples of usage:
1057 * $t->align = array(null, 'right');
1058 * or
1059 * $t->align[1] = 'right';
1060 *
1061 */
1062 public $align;
1063 /**
1064 * @var array of column sizes. The value is used as CSS 'size' property.
1065 *
1066 * Examples of usage:
1067 * $t->size = array('50%', '50%');
1068 * or
1069 * $t->size[1] = '120px';
1070 */
1071 public $size;
1072 /**
1073 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1074 * CSS property 'white-space' to the value 'nowrap' in the given column.
1075 *
1076 * Example of usage:
1077 * $t->wrap = array(null, 'nowrap');
1078 */
1079 public $wrap;
1080 /**
1081 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1082 * $head specified, the string 'hr' (for horizontal ruler) can be used
1083 * instead of an array of cells data resulting in a divider rendered.
1084 *
1085 * Example of usage with array of arrays:
1086 * $row1 = array('Harry Potter', '76 %');
1087 * $row2 = array('Hermione Granger', '100 %');
1088 * $t->data = array($row1, $row2);
1089 *
1090 * Example with array of html_table_row objects: (used for more fine-grained control)
1091 * $cell1 = new html_table_cell();
1092 * $cell1->text = 'Harry Potter';
1093 * $cell1->colspan = 2;
1094 * $row1 = new html_table_row();
1095 * $row1->cells[] = $cell1;
1096 * $cell2 = new html_table_cell();
1097 * $cell2->text = 'Hermione Granger';
1098 * $cell3 = new html_table_cell();
1099 * $cell3->text = '100 %';
1100 * $row2 = new html_table_row();
1101 * $row2->cells = array($cell2, $cell3);
1102 * $t->data = array($row1, $row2);
1103 */
1104 public $data;
1105 /**
1106 * @var string width of the table, percentage of the page preferred. Defaults to 80% of the page width.
1107 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1108 */
1109 public $width = null;
1110 /**
1111 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1112 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1113 */
1114 public $tablealign = null;
1115 /**
1116 * @var int padding on each cell, in pixels
1117 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1118 */
1119 public $cellpadding = null;
1120 /**
1121 * @var int spacing between cells, in pixels
1122 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1123 */
1124 public $cellspacing = null;
1125 /**
1126 * @var array classes to add to particular rows, space-separated string.
1127 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1128 * respectively. Class 'lastrow' is added automatically for the last row
1129 * in the table.
1130 *
1131 * Example of usage:
1132 * $t->rowclasses[9] = 'tenth'
1133 */
1134 public $rowclasses;
1135 /**
1136 * @var array classes to add to every cell in a particular column,
1137 * space-separated string. Class 'cell' is added automatically by the renderer.
1138 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1139 * respectively. Class 'lastcol' is added automatically for all last cells
1140 * in a row.
1141 *
1142 * Example of usage:
1143 * $t->colclasses = array(null, 'grade');
1144 */
1145 public $colclasses;
1146 /**
1147 * @var string description of the contents for screen readers.
1148 */
1149 public $summary;
1150 /**
1151 * @var bool true causes the contents of the heading cells to be rotated 90 degrees.
1152 */
1153 public $rotateheaders = false;
1154
1155 /**
1156 * @see moodle_html_component::prepare()
1157 * @return void
1158 */
1159 public function prepare() {
1160 if (!empty($this->align)) {
1161 foreach ($this->align as $key => $aa) {
1162 if ($aa) {
1163 $this->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1164 } else {
1165 $this->align[$key] = '';
1166 }
1167 }
1168 }
1169 if (!empty($this->size)) {
1170 foreach ($this->size as $key => $ss) {
1171 if ($ss) {
1172 $this->size[$key] = 'width:'. $ss .';';
1173 } else {
1174 $this->size[$key] = '';
1175 }
1176 }
1177 }
1178 if (!empty($this->wrap)) {
1179 foreach ($this->wrap as $key => $ww) {
1180 if ($ww) {
1181 $this->wrap[$key] = 'white-space:nowrap;';
1182 } else {
1183 $this->wrap[$key] = '';
1184 }
1185 }
1186 }
1187 if (!empty($this->head)) {
1188 foreach ($this->head as $key => $val) {
1189 if (!isset($this->align[$key])) {
1190 $this->align[$key] = '';
1191 }
1192 if (!isset($this->size[$key])) {
1193 $this->size[$key] = '';
1194 }
1195 if (!isset($this->wrap[$key])) {
1196 $this->wrap[$key] = '';
1197 }
1198
1199 }
1200 }
1201 if (empty($this->classes)) { // must be done before align
1202 $this->set_classes(array('generaltable'));
1203 }
1204 if (!empty($this->tablealign)) {
1205 $this->add_class('boxalign' . $this->tablealign);
1206 }
1207 if (!empty($this->rotateheaders)) {
1208 $this->add_class('rotateheaders');
1209 } else {
1210 $this->rotateheaders = false; // Makes life easier later.
1211 }
1212 parent::prepare();
1213 }
1214 /**
1215 * @param string $name The name of the variable to set
1216 * @param mixed $value The value to assign to the variable
1217 * @return void
1218 */
1219 public function __set($name, $value) {
1220 if ($name == 'rowclass') {
1221 debugging('rowclass[] has been deprecated for html_table ' .
1222 'and should be replaced with rowclasses[]. please fix the code.');
1223 $this->rowclasses = $value;
1224 } else {
1225 parent::__set($name, $value);
1226 }
1227 }
1228}
1229
1230/**
1231 * Component representing a table row.
1232 *
1233 * @copyright 2009 Nicolas Connault
1234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1235 * @since Moodle 2.0
1236 */
1237class html_table_row extends moodle_html_component {
1238 /**
1239 * @var array $cells Array of html_table_cell objects
1240 */
1241 public $cells = array();
1242
1243 /**
1244 * @see lib/moodle_html_component#prepare()
1245 * @return void
1246 */
1247 public function prepare() {
1248 parent::prepare();
1249 }
1250}
1251
1252/**
1253 * Component representing a table cell.
1254 *
1255 * @copyright 2009 Nicolas Connault
1256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1257 * @since Moodle 2.0
1258 */
1259class html_table_cell extends moodle_html_component {
1260 /**
1261 * @var string $text The contents of the cell
1262 */
1263 public $text;
1264 /**
1265 * @var string $abbr Abbreviated version of the contents of the cell
1266 */
1267 public $abbr = '';
1268 /**
1269 * @var int $colspan Number of columns this cell should span
1270 */
1271 public $colspan = '';
1272 /**
1273 * @var int $rowspan Number of rows this cell should span
1274 */
1275 public $rowspan = '';
1276 /**
1277 * @var string $scope Defines a way to associate header cells and data cells in a table
1278 */
1279 public $scope = '';
1280
1281 /**
1282 * @see lib/moodle_html_component#prepare()
1283 * @return void
1284 */
1285 public function prepare() {
1286 parent::prepare();
1287 }
1288}
1289
1290/**
1291 * Component representing a XHTML link.
1292 *
1293 * @copyright 2009 Nicolas Connault
1294 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1295 * @since Moodle 2.0
1296 */
1297class html_link extends moodle_html_component {
1298 /**
1299 * URL can be simple text or a moodle_url object
1300 * @var mixed $url
1301 */
1302 public $url;
1303
1304 /**
1305 * @var string $text The text that will appear between the link tags
1306 */
1307 public $text;
1308
1309 /**
1310 * @see lib/moodle_html_component#prepare()
1311 * @return void
1312 */
1313 public function prepare() {
1314 // We can't accept an empty text value
1315 if (empty($this->text)) {
1316 throw new coding_exception('A html_link must have a descriptive text value!');
1317 }
1318
1319 parent::prepare();
1320 }
1321
1322 /**
1323 * Shortcut for creating a link component.
1324 * @param mixed $url String or moodle_url
1325 * @param string $text The text of the link
1326 * @return html_link The link component
1327 */
1328 public function make($url, $text) {
1329 $link = new html_link();
1330 $link->url = $url;
1331 $link->text = $text;
1332 return $link;
1333 }
1334}
1335
1336/**
1337 * Component representing a help icon.
1338 *
1339 * @copyright 2009 Nicolas Connault
1340 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1341 * @since Moodle 2.0
1342 */
94056d9d 1343class moodle_help_icon extends moodle_html_component {
d9c8f425 1344 /**
1345 * @var html_link $link A html_link object that will hold the URL info
1346 */
1347 public $link;
1348 /**
1349 * @var string $text A descriptive text
1350 */
1351 public $text;
1352 /**
1353 * @var string $page The keyword that defines a help page
1354 */
1355 public $page;
1356 /**
1357 * @var string $module Which module is the page defined in
1358 */
1359 public $module = 'moodle';
1360 /**
1361 * @var boolean $linktext Whether or not to show text next to the icon
1362 */
1363 public $linktext = false;
1364 /**
1365 * @var mixed $image The help icon. Can be set to true (will use default help icon),
1366 * false (will not use any icon), the URL to an image, or a full
1367 * html_image object.
1368 */
1369 public $image;
1370
1371 /**
1372 * Constructor: sets up the other components in case they are needed
1373 * @return void
1374 */
1375 public function __construct() {
1376 $this->link = new html_link();
1377 $this->image = new html_image();
1378 }
1379
1380 /**
1381 * @see lib/moodle_html_component#prepare()
1382 * @return void
1383 */
1384 public function prepare() {
1385 global $COURSE, $OUTPUT;
1386
1387 if (empty($this->page)) {
94056d9d 1388 throw new coding_exception('A moodle_help_icon object requires a $page parameter');
d9c8f425 1389 }
1390
1391 if (empty($this->text)) {
94056d9d 1392 throw new coding_exception('A moodle_help_icon object requires a $text parameter');
d9c8f425 1393 }
1394
1395 $this->link->text = $this->text;
1396
1397 // fix for MDL-7734
1398 $this->link->url = new moodle_url('/help.php', array('module' => $this->module, 'file' => $this->page .'.html'));
1399
1400 // fix for MDL-7734
1401 if (!empty($COURSE->lang)) {
1402 $this->link->url->param('forcelang', $COURSE->lang);
1403 }
1404
1405 // Catch references to the old text.html and emoticons.html help files that
1406 // were renamed in MDL-13233.
1407 if (in_array($this->page, array('text', 'emoticons', 'richtext'))) {
1408 $oldname = $this->page;
1409 $this->page .= '2';
1410 debugging("You are referring to the old help file '$oldname'. " .
1411 "This was renamed to '$this->page' because of MDL-13233. " .
1412 "Please update your code.", DEBUG_DEVELOPER);
1413 }
1414
1415 if ($this->module == '') {
1416 $this->module = 'moodle';
1417 }
1418
1419 // Warn users about new window for Accessibility
1420 $this->title = get_string('helpprefix2', '', trim($this->text, ". \t")) .' ('.get_string('newwindow').')';
1421
1422 // Prepare image and linktext
1423 if ($this->image && !($this->image instanceof html_image)) {
1424 $image = fullclone($this->image);
1425 $this->image = new html_image();
1426
1427 if ($image instanceof moodle_url) {
1428 $this->image->src = $image->out();
1429 } else if ($image === true) {
1430 $this->image->src = $OUTPUT->old_icon_url('help');
1431 } else if (is_string($image)) {
1432 $this->image->src = $image;
1433 }
1434 $this->image->alt = $this->text;
1435
1436 if ($this->linktext) {
1437 $this->image->alt = get_string('helpwiththis');
1438 } else {
1439 $this->image->alt = $this->title;
1440 }
1441 $this->image->add_class('iconhelp');
1442 } else if (empty($this->image->src)) {
1443 if (!($this->image instanceof html_image)) {
1444 $this->image = new html_image();
1445 }
1446 $this->image->src = $OUTPUT->old_icon_url('help');
1447 }
1448
1449 parent::prepare();
1450 }
1451
1452 public static function make_scale_menu($courseid, $scale) {
94056d9d 1453 $helpbutton = new moodle_help_icon();
d9c8f425 1454 $strscales = get_string('scales');
1455 $helpbutton->image->alt = $scale->name;
1456 $helpbutton->link->url = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scale->id));
1457 $popupaction = new popup_action('click', $helpbutton->url, 'ratingscale', $popupparams);
1458 $popupaction->width = 500;
1459 $popupaction->height = 400;
1460 $helpbutton->link->add_action($popupaction);
1461 $helpbutton->link->title = $scale->name;
1462 return $helpbutton;
1463 }
1464}
1465
1466
1467/**
1468 * Component representing a XHTML button (input of type 'button').
1469 * The renderer will either output it as a button with an onclick event,
1470 * or as a form with hidden inputs.
1471 *
1472 * @copyright 2009 Nicolas Connault
1473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1474 * @since Moodle 2.0
1475 */
1476class html_button extends moodle_html_component {
1477 /**
1478 * @var string $text
1479 */
1480 public $text;
1481
1482 /**
1483 * @var boolean $disabled Whether or not this button is disabled
1484 */
1485 public $disabled = false;
1486
1487 /**
1488 * @see lib/moodle_html_component#prepare()
1489 * @return void
1490 */
1491 public function prepare() {
1492 $this->add_class('singlebutton');
1493
1494 if (empty($this->text)) {
1495 throw new coding_exception('A html_button must have a text value!');
1496 }
1497
1498 if ($this->disabled) {
1499 $this->disabled = 'disabled';
1500 }
1501
1502 parent::prepare();
1503 }
1504}
1505
1506/**
1507 * Component representing an icon linking to a Moodle page.
1508 *
1509 * @copyright 2009 Nicolas Connault
1510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1511 * @since Moodle 2.0
1512 */
1513class action_icon extends moodle_html_component {
1514 /**
1515 * @var string $linktext Optional text to display next to the icon
1516 */
1517 public $linktext;
1518 /**
1519 * @var html_image $image The icon
1520 */
1521 public $image;
1522 /**
1523 * @var html_link $link The link
1524 */
1525 public $link;
1526
1527 /**
1528 * Constructor: sets up the other components in case they are needed
1529 * @return void
1530 */
1531 public function __construct() {
1532 $this->image = new html_image();
1533 $this->link = new html_link();
1534 }
1535
1536 /**
1537 * @see lib/moodle_html_component#prepare()
1538 * @return void
1539 */
1540 public function prepare() {
1541 $this->image->add_class('action-icon');
1542
1543 parent::prepare();
1544
1545 if (empty($this->image->src)) {
1546 throw new coding_exception('action_icon->image->src must not be empty');
1547 }
1548
1549 if (empty($this->image->alt) && !empty($this->linktext)) {
1550 $this->image->alt = $this->linktext;
1551 } else if (empty($this->image->alt)) {
1552 debugging('action_icon->image->alt should not be empty.', DEBUG_DEVELOPER);
1553 }
1554 }
1555}
1556
1557/**
1558 * Component representing an image.
1559 *
1560 * @copyright 2009 Nicolas Connault
1561 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1562 * @since Moodle 2.0
1563 */
1564class html_image extends moodle_html_component {
1565 /**
1566 * @var string $alt A descriptive text
1567 */
1568 public $alt = HTML_ATTR_EMPTY;
1569 /**
1570 * @var string $src The path to the image being used
1571 */
1572 public $src;
1573
1574 /**
1575 * @see lib/moodle_html_component#prepare()
1576 * @return void
1577 */
1578 public function prepare() {
1579 $this->add_class('image');
1580 parent::prepare();
1581 }
1582}
1583
1584/**
1585 * Component representing a user picture.
1586 *
1587 * @copyright 2009 Nicolas Connault
1588 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1589 * @since Moodle 2.0
1590 */
1591class user_picture extends moodle_html_component {
1592 /**
1593 * @var mixed $user A userid or a user object with at least fields id, picture, imagealrt, firstname and lastname set.
1594 */
1595 public $user;
1596 /**
1597 * @var int $courseid The course id. Used when constructing the link to the user's profile.
1598 */
1599 public $courseid;
1600 /**
1601 * @var html_image $image A custom image used as the user picture.
1602 */
1603 public $image;
1604 /**
1605 * @var mixed $url False: picture not enclosed in a link. True: default link. moodle_url: custom link.
1606 */
1607 public $url;
1608 /**
1609 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
1610 */
1611 public $size;
1612 /**
1613 * @var boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
1614 */
1615 public $alttext = true;
1616 /**
1617 * @var boolean $popup Whether or not to open the link in a popup window
1618 */
1619 public $popup = false;
1620
1621 /**
1622 * Constructor: sets up the other components in case they are needed
1623 * @return void
1624 */
1625 public function __construct() {
1626 $this->image = new html_image();
1627 }
1628
1629 /**
1630 * @see lib/moodle_html_component#prepare()
1631 * @return void
1632 */
1633 public function prepare() {
1634 global $CFG, $DB, $OUTPUT;
1635
1636 if (empty($this->user)) {
1637 throw new coding_exception('A user_picture object must have a $user object before being rendered.');
1638 }
1639
1640 if (empty($this->courseid)) {
1641 throw new coding_exception('A user_picture object must have a courseid value before being rendered.');
1642 }
1643
1644 if (!($this->image instanceof html_image)) {
1645 debugging('user_picture::image must be an instance of html_image', DEBUG_DEVELOPER);
1646 }
1647
1648 $needrec = false;
1649 // only touch the DB if we are missing data...
1650 if (is_object($this->user)) {
1651 // Note - both picture and imagealt _can_ be empty
1652 // what we are trying to see here is if they have been fetched
1653 // from the DB. We should use isset() _except_ that some installs
1654 // have those fields as nullable, and isset() will return false
1655 // on null. The only safe thing is to ask array_key_exists()
1656 // which works on objects. property_exists() isn't quite
1657 // what we want here...
1658 if (! (array_key_exists('picture', $this->user)
1659 && ($this->alttext && array_key_exists('imagealt', $this->user)
1660 || (isset($this->user->firstname) && isset($this->user->lastname)))) ) {
1661 $needrec = true;
1662 $this->user = $this->user->id;
1663 }
1664 } else {
1665 if ($this->alttext) {
1666 // we need firstname, lastname, imagealt, can't escape...
1667 $needrec = true;
1668 } else {
1669 $userobj = new StdClass; // fake it to save DB traffic
1670 $userobj->id = $this->user;
1671 $userobj->picture = $this->image->src;
1672 $this->user = clone($userobj);
1673 unset($userobj);
1674 }
1675 }
1676 if ($needrec) {
1677 $this->user = $DB->get_record('user', array('id' => $this->user), 'id,firstname,lastname,imagealt');
1678 }
1679
1680 if ($this->url === true) {
1681 $this->url = new moodle_url('/user/view.php', array('id' => $this->user->id, 'course' => $this->courseid));
1682 }
1683
1684 if (!empty($this->url) && $this->popup) {
1685 $this->add_action(new popup_action('click', $this->url));
1686 }
1687
1688 if (empty($this->size)) {
1689 $file = 'f2';
1690 $this->size = 35;
1691 } else if ($this->size === true or $this->size == 1) {
1692 $file = 'f1';
1693 $this->size = 100;
1694 } else if ($this->size >= 50) {
1695 $file = 'f1';
1696 } else {
1697 $file = 'f2';
1698 }
1699
1700 if (!empty($this->size)) {
1701 $this->image->width = $this->size;
1702 $this->image->height = $this->size;
1703 }
1704
1705 $this->add_class('userpicture');
1706
1707 if (empty($this->image->src) && !empty($this->user->picture)) {
1708 $this->image->src = $this->user->picture;
1709 }
1710
1711 if (!empty($this->image->src)) {
1712 require_once($CFG->libdir.'/filelib.php');
1713 $this->image->src = new moodle_url(get_file_url($this->user->id.'/'.$file.'.jpg', null, 'user'));
1714 } else { // Print default user pictures (use theme version if available)
1715 $this->add_class('defaultuserpic');
1716 $this->image->src = $OUTPUT->old_icon_url('u/' . $file);
1717 }
1718
1719 if ($this->alttext) {
1720 if (!empty($this->user->imagealt)) {
1721 $this->image->alt = $this->user->imagealt;
1722 } else {
1723 $this->image->alt = get_string('pictureof','',fullname($this->user));
1724 }
1725 }
1726
1727 parent::prepare();
1728 }
1729}
1730
1731/**
1732 * Component representing a textarea.
1733 *
1734 * @copyright 2009 Nicolas Connault
1735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1736 * @since Moodle 2.0
1737 */
1738class html_textarea extends moodle_html_component {
1739 /**
1740 * @param string $name Name to use for the textarea element.
1741 */
1742 public $name;
1743 /**
1744 * @param string $value Initial content to display in the textarea.
1745 */
1746 public $value;
1747 /**
1748 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
1749 */
1750 public $rows;
1751 /**
1752 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
1753 */
1754 public $cols;
1755 /**
1756 * @param bool $usehtmleditor Enables the use of the htmleditor for this field.
1757 */
1758 public $usehtmleditor;
1759
1760 /**
1761 * @see lib/moodle_html_component#prepare()
1762 * @return void
1763 */
1764 public function prepare() {
1765 $this->add_class('form-textarea');
1766
1767 if (empty($this->id)) {
1768 $this->id = "edit-$this->name";
1769 }
1770
1771 if ($this->usehtmleditor) {
1772 editors_head_setup();
1773 $editor = get_preferred_texteditor(FORMAT_HTML);
1774 $editor->use_editor($this->id, array('legacy'=>true));
1775 $this->value = htmlspecialchars($value);
1776 }
1777
1778 parent::prepare();
1779 }
1780}
1781
1782/**
1783 * Component representing a simple form wrapper. Its purpose is mainly to enclose
1784 * a submit input with the appropriate action and hidden inputs.
1785 *
1786 * @copyright 2009 Nicolas Connault
1787 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1788 * @since Moodle 2.0
1789 */
1790class html_form extends moodle_html_component {
1791 /**
1792 * @var string $method post or get
1793 */
1794 public $method = 'post';
1795 /**
1796 * If a string is given, it will be converted to a moodle_url during prepare()
1797 * @var mixed $url A moodle_url including params or a string
1798 */
1799 public $url;
1800 /**
1801 * @var array $params Optional array of parameters. Ignored if $url instanceof moodle_url
1802 */
1803 public $params = array();
1804 /**
1805 * @var boolean $showbutton If true, the submit button will always be shown even if JavaScript is available
1806 */
1807 public $showbutton = false;
1808 /**
1809 * @var string $targetwindow The name of the target page to open the linked page in.
1810 */
1811 public $targetwindow = 'self';
1812 /**
1813 * @var html_button $button A submit button
1814 */
1815 public $button;
1816
1817 /**
1818 * Constructor: sets up the other components in case they are needed
1819 * @return void
1820 */
1821 public function __construct() {
1822 static $yes;
1823 $this->button = new html_button();
1824 if (!isset($yes)) {
1825 $yes = get_string('yes');
1826 $this->button->text = $yes;
1827 }
1828 }
1829
1830 /**
1831 * @see lib/moodle_html_component#prepare()
1832 * @return void
1833 */
1834 public function prepare() {
1835
1836 if (empty($this->url)) {
1837 throw new coding_exception('A html_form must have a $url value (string or moodle_url).');
1838 }
1839
1840 if (!($this->url instanceof moodle_url)) {
1841 $this->url = new moodle_url($this->url, $this->params);
1842 }
1843
1844 if ($this->method == 'post') {
1845 $this->url->param('sesskey', sesskey());
1846 }
1847
1848 parent::prepare();
1849 }
1850}
1851
1852/**
1853 * Component representing a paging bar.
1854 *
1855 * @copyright 2009 Nicolas Connault
1856 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1857 * @since Moodle 2.0
1858 */
1859class moodle_paging_bar extends moodle_html_component {
1860 /**
1861 * @var int $maxdisplay The maximum number of pagelinks to display
1862 */
1863 public $maxdisplay = 18;
1864 /**
1865 * @var int $totalcount post or get
1866 */
1867 public $totalcount;
1868 /**
1869 * @var int $page The page you are currently viewing
1870 */
1871 public $page = 0;
1872 /**
1873 * @var int $perpage The number of entries that should be shown per page
1874 */
1875 public $perpage;
1876 /**
1877 * @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.
1878 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1879 */
1880 public $baseurl;
1881 /**
1882 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1883 */
1884 public $pagevar = 'page';
1885 /**
1886 * @var bool $nocurr do not display the current page as a link
1887 */
1888 public $nocurr;
1889 /**
1890 * @var html_link $previouslink A HTML link representing the "previous" page
1891 */
1892 public $previouslink = null;
1893 /**
1894 * @var html_link $nextlink A HTML link representing the "next" page
1895 */
1896 public $nextlink = null;
1897 /**
1898 * @var html_link $firstlink A HTML link representing the first page
1899 */
1900 public $firstlink = null;
1901 /**
1902 * @var html_link $lastlink A HTML link representing the last page
1903 */
1904 public $lastlink = null;
1905 /**
1906 * @var array $pagelinks An array of html_links. One of them is just a string: the current page
1907 */
1908 public $pagelinks = array();
1909
1910 /**
1911 * @see lib/moodle_html_component#prepare()
1912 * @return void
1913 */
1914 public function prepare() {
1915 if (empty($this->totalcount)) {
1916 throw new coding_exception('moodle_paging_bar requires a totalcount value.');
1917 }
1918 if (!isset($this->page) || is_null($this->page)) {
1919 throw new coding_exception('moodle_paging_bar requires a page value.');
1920 }
1921 if (empty($this->perpage)) {
1922 throw new coding_exception('moodle_paging_bar requires a perpage value.');
1923 }
1924 if (empty($this->baseurl)) {
1925 throw new coding_exception('moodle_paging_bar requires a baseurl value.');
1926 }
1927 if (!($this->baseurl instanceof moodle_url)) {
1928 $this->baseurl = new moodle_url($this->baseurl);
1929 }
1930
1931 if ($this->totalcount > $this->perpage) {
1932 $pagenum = $this->page - 1;
1933
1934 if ($this->page > 0) {
1935 $this->previouslink = new html_link();
1936 $this->previouslink->add_class('previous');
1937 $this->previouslink->url = clone($this->baseurl);
1938 $this->previouslink->url->param($this->pagevar, $pagenum);
1939 $this->previouslink->text = get_string('previous');
1940 }
1941
1942 if ($this->perpage > 0) {
1943 $lastpage = ceil($this->totalcount / $this->perpage);
1944 } else {
1945 $lastpage = 1;
1946 }
1947
1948 if ($this->page > 15) {
1949 $startpage = $this->page - 10;
1950
1951 $this->firstlink = new html_link();
1952 $this->firstlink->url = clone($this->baseurl);
1953 $this->firstlink->url->param($this->pagevar, 0);
1954 $this->firstlink->text = 1;
1955 $this->firstlink->add_class('first');
1956 } else {
1957 $startpage = 0;
1958 }
1959
1960 $currpage = $startpage;
1961 $displaycount = $displaypage = 0;
1962
1963 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1964 $displaypage = $currpage + 1;
1965
1966 if ($this->page == $currpage && empty($this->nocurr)) {
1967 $this->pagelinks[] = $displaypage;
1968 } else {
1969 $pagelink = new html_link();
1970 $pagelink->url = clone($this->baseurl);
1971 $pagelink->url->param($this->pagevar, $currpage);
1972 $pagelink->text = $displaypage;
1973 $this->pagelinks[] = $pagelink;
1974 }
1975
1976 $displaycount++;
1977 $currpage++;
1978 }
1979
1980 if ($currpage < $lastpage) {
1981 $lastpageactual = $lastpage - 1;
1982 $this->lastlink = new html_link();
1983 $this->lastlink->url = clone($this->baseurl);
1984 $this->lastlink->url->param($this->pagevar, $lastpageactual);
1985 $this->lastlink->text = $lastpage;
1986 $this->lastlink->add_class('last');
1987 }
1988
1989 $pagenum = $this->page + 1;
1990
1991 if ($pagenum != $displaypage) {
1992 $this->nextlink = new html_link();
1993 $this->nextlink->url = clone($this->baseurl);
1994 $this->nextlink->url->param($this->pagevar, $pagenum);
1995 $this->nextlink->text = get_string('next');
1996 $this->nextlink->add_class('next');
1997 }
1998 }
1999 }
2000
2001 /**
2002 * Shortcut for initialising a moodle_paging_bar with only the required params.
2003 *
2004 * @param int $totalcount Thetotal number of entries available to be paged through
2005 * @param int $page The page you are currently viewing
2006 * @param int $perpage The number of entries that should be shown per page
2007 * @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.
2008 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
2009 */
2010 public function make($totalcount, $page, $perpage, $baseurl) {
2011 $pagingbar = new moodle_paging_bar();
2012 $pagingbar->totalcount = $totalcount;
2013 $pagingbar->page = $page;
2014 $pagingbar->perpage = $perpage;
2015 $pagingbar->baseurl = $baseurl;
2016 return $pagingbar;
2017 }
2018}
2019
2020/**
2021 * Component representing a list.
2022 *
2023 * The advantage of using this object instead of a flat array is that you can load it
2024 * with metadata (CSS classes, event handlers etc.) which can be used by the renderers.
2025 *
2026 * @copyright 2009 Nicolas Connault
2027 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2028 * @since Moodle 2.0
2029 */
2030class html_list extends moodle_html_component {
2031
2032 /**
2033 * @var array $items An array of html_list_item or html_list objects
2034 */
2035 public $items = array();
2036
2037 /**
2038 * @var string $type The type of list (ordered|unordered), definition type not yet supported
2039 */
2040 public $type = 'unordered';
2041
2042 /**
2043 * @see lib/moodle_html_component#prepare()
2044 * @return void
2045 */
2046 public function prepare() {
2047 parent::prepare();
2048 }
2049
2050 /**
2051 * This function takes a nested array of data and maps it into this list's $items array
2052 * as proper html_list_item and html_list objects, with appropriate metadata.
2053 *
2054 * @param array $tree A nested array (array keys are ignored);
2055 * @param int $row Used in identifying the iteration level and in ul classes
2056 * @return void
2057 */
2058 public function load_data($tree, $level=0) {
2059
2060 $this->add_class("list-$level");
2061
2062 foreach ($tree as $key => $element) {
2063 if (is_array($element)) {
2064 $newhtmllist = new html_list();
2065 $newhtmllist->load_data($element, $level + 1);
2066 $this->items[] = $newhtmllist;
2067 } else {
2068 $listitem = new html_list_item();
2069 $listitem->value = $element;
2070 $listitem->add_class("list-item-$level-$key");
2071 $this->items[] = $listitem;
2072 }
2073 }
2074 }
2075
2076 /**
2077 * Adds a html_list_item or html_list to this list.
2078 * If the param is a string, a html_list_item will be added.
2079 * @param mixed $item String, html_list or html_list_item object
2080 * @return void
2081 */
2082 public function add_item($item) {
2083 if ($item instanceof html_list_item || $item instanceof html_list) {
2084 $this->items[] = $item;
2085 } else {
2086 $listitem = new html_list_item();
2087 $listitem->value = $item;
2088 $this->items[] = $item;
2089 }
2090 }
2091}
2092
2093/**
2094 * Component representing a list item.
2095 *
2096 * @copyright 2009 Nicolas Connault
2097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2098 * @since Moodle 2.0
2099 */
2100class html_list_item extends moodle_html_component {
2101 /**
2102 * @var string $value The value of the list item
2103 */
2104 public $value;
2105
2106 /**
2107 * @see lib/moodle_html_component#prepare()
2108 * @return void
2109 */
2110 public function prepare() {
2111 parent::prepare();
2112 }
2113}