output MDLSITE-1070 Added set methods to custom_menu class as properties are protected
[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 *
78bfb562
PS
24 * @package core
25 * @subpackage lib
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d9c8f425 28 */
29
78bfb562 30defined('MOODLE_INTERNAL') || die();
5d0c95a5
PS
31
32/**
33 * Interface marking other classes as suitable for renderer_base::render()
34 * @author 2010 Petr Skoda (skodak) info@skodak.org
35 */
36interface renderable {
37 // intentionally empty
38}
39
bb496de7
DC
40/**
41 * Data structure representing a file picker.
42 *
43 * @copyright 2010 Dongsheng Cai
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 * @since Moodle 2.0
46 */
47class file_picker implements renderable {
48 public $options;
49 public function __construct(stdClass $options) {
50 global $CFG, $USER, $PAGE;
51 require_once($CFG->dirroot. '/repository/lib.php');
52 $defaults = array(
53 'accepted_types'=>'*',
bb496de7
DC
54 'return_types'=>FILE_INTERNAL,
55 'env' => 'filepicker',
56 'client_id' => uniqid(),
57 'itemid' => 0,
58 'maxbytes'=>-1,
59 'maxfiles'=>1,
60 );
61 foreach ($defaults as $key=>$value) {
62 if (empty($options->$key)) {
63 $options->$key = $value;
64 }
65 }
66
67 $options->currentfile = '';
68 if (!empty($options->itemid)) {
69 $fs = get_file_storage();
70 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
e4256380 71 if (empty($options->filename)) {
64f93798 72 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
e4256380
DC
73 $file = reset($files);
74 }
75 } else {
64f93798 76 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
e4256380
DC
77 }
78 if (!empty($file)) {
ee9a4962 79 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
bb496de7
DC
80 }
81 }
82
bb496de7
DC
83 // initilise options, getting files in root path
84 $this->options = initialise_filepicker($options);
85
86 // copying other options
87 foreach ($options as $name=>$value) {
98e7ae63
DC
88 if (!isset($this->options->$name)) {
89 $this->options->$name = $value;
90 }
bb496de7
DC
91 }
92 }
93}
94
5d0c95a5 95/**
bf11293a 96 * Data structure representing a user picture.
5d0c95a5
PS
97 *
98 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
99 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
100 * @since Moodle 2.0
101 */
102class user_picture implements renderable {
103 /**
3a11c09f 104 * @var array List of mandatory fields in user record here. (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
5d0c95a5 105 */
3a11c09f 106 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
5d0c95a5
PS
107
108 /**
3a11c09f 109 * @var object $user A user object with at least fields all columns specified in $fields array constant set.
5d0c95a5
PS
110 */
111 public $user;
112 /**
113 * @var int $courseid The course id. Used when constructing the link to the user's profile,
114 * page course id used if not specified.
115 */
116 public $courseid;
117 /**
118 * @var bool $link add course profile link to image
119 */
120 public $link = true;
121 /**
122 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
123 */
124 public $size = 35;
125 /**
126 * @var boolean $alttext add non-blank alt-text to the image.
127 * Default true, set to false when image alt just duplicates text in screenreaders.
128 */
129 public $alttext = true;
130 /**
131 * @var boolean $popup Whether or not to open the link in a popup window.
132 */
133 public $popup = false;
134 /**
135 * @var string Image class attribute
136 */
137 public $class = 'userpicture';
138
139 /**
140 * User picture constructor.
141 *
142 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
143 * @param array $options such as link, size, link, ...
144 */
145 public function __construct(stdClass $user) {
146 global $DB;
147
5d0c95a5
PS
148 if (empty($user->id)) {
149 throw new coding_exception('User id is required when printing user avatar image.');
150 }
151
152 // only touch the DB if we are missing data and complain loudly...
153 $needrec = false;
3a11c09f 154 foreach (self::$fields as $field) {
5d0c95a5
PS
155 if (!array_key_exists($field, $user)) {
156 $needrec = true;
157 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
158 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
159 break;
160 }
161 }
162
163 if ($needrec) {
3a11c09f 164 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
5d0c95a5
PS
165 } else {
166 $this->user = clone($user);
167 }
168 }
169
170 /**
1a10840e 171 * Returns a list of required user fields, useful when fetching required user info from db.
f3afba4e
PS
172 *
173 * In some cases we have to fetch the user data together with some other information,
174 * the idalias is useful there because the id would otherwise override the main
175 * id of the result record. Please note it has to be converted back to id before rendering.
176 *
5d0c95a5 177 * @param string $tableprefix name of database table prefix in query
3a11c09f 178 * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
f3afba4e 179 * @param string $idalias alias of id field
5d0c95a5
PS
180 * @return string
181 */
3a11c09f
PS
182 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id') {
183 if (!$tableprefix and !$extrafields and !$idalias) {
184 return implode(',', self::$fields);
5d0c95a5 185 }
3a11c09f
PS
186 if ($tableprefix) {
187 $tableprefix .= '.';
188 }
189 $fields = array();
190 foreach (self::$fields as $field) {
191 if ($field === 'id' and $idalias and $idalias !== 'id') {
6f7b89e2 192 $fields[$field] = "$tableprefix$field AS $idalias";
3a11c09f
PS
193 } else {
194 $fields[$field] = $tableprefix.$field;
195 }
196 }
197 // add extra fields if not already there
198 if ($extrafields) {
199 foreach ($extrafields as $e) {
200 if ($e === 'id' or isset($fields[$e])) {
201 continue;
202 }
203 $fields[$e] = $tableprefix.$e;
f3afba4e 204 }
f3afba4e
PS
205 }
206 return implode(',', $fields);
5d0c95a5
PS
207 }
208}
209
bf11293a
PS
210
211/**
212 * Data structure representing a help icon.
213 *
214 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
216 * @since Moodle 2.0
217 */
596509e4 218class old_help_icon implements renderable {
bf11293a 219 /**
49f0d481 220 * @var string $helpidentifier lang pack identifier
bf11293a 221 */
53a78cef 222 public $helpidentifier;
bf11293a
PS
223 /**
224 * @var string $title A descriptive text for title tooltip
225 */
97c10099 226 public $title = null;
bf11293a
PS
227 /**
228 * @var string $component Component name, the same as in get_string()
229 */
230 public $component = 'moodle';
231 /**
232 * @var string $linktext Extra descriptive text next to the icon
233 */
97c10099 234 public $linktext = null;
bf11293a
PS
235
236 /**
237 * Constructor: sets up the other components in case they are needed
53a78cef 238 * @param string $helpidentifier The keyword that defines a help page
1a10840e 239 * @param string $title A descriptive text for accessibility only
bf11293a
PS
240 * @param string $component
241 * @param bool $linktext add extra text to icon
242 * @return void
243 */
53a78cef 244 public function __construct($helpidentifier, $title, $component = 'moodle') {
bf11293a
PS
245 if (empty($title)) {
246 throw new coding_exception('A help_icon object requires a $text parameter');
247 }
53a78cef
PS
248 if (empty($helpidentifier)) {
249 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
bf11293a
PS
250 }
251
53a78cef
PS
252 $this->helpidentifier = $helpidentifier;
253 $this->title = $title;
254 $this->component = $component;
bf11293a
PS
255 }
256}
257
49f0d481
PS
258/**
259 * Data structure representing a help icon.
260 *
261 * @copyright 2010 Petr Skoda (info@skodak.org)
262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
263 * @since Moodle 2.0
264 */
265class help_icon implements renderable {
266 /**
5435c9dc
MD
267 * @var string $identifier lang pack identifier (without the "_help" suffix),
268 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
49f0d481
PS
269 * must exist.
270 */
271 public $identifier;
272 /**
273 * @var string $component Component name, the same as in get_string()
274 */
275 public $component;
276 /**
277 * @var string $linktext Extra descriptive text next to the icon
278 */
279 public $linktext = null;
280
281 /**
282 * Constructor
283 * @param string $identifier string for help page title,
5435c9dc
MD
284 * string with _help suffix is used for the actual help text.
285 * string with _link suffix is used to create a link to further info (if it exists)
49f0d481
PS
286 * @param string $component
287 */
259c165d
PS
288 public function __construct($identifier, $component) {
289 $this->identifier = $identifier;
49f0d481
PS
290 $this->component = $component;
291 }
259c165d
PS
292
293 /**
294 * Verifies that both help strings exists, shows debug warnings if not
295 */
296 public function diag_strings() {
297 $sm = get_string_manager();
298 if (!$sm->string_exists($this->identifier, $this->component)) {
299 debugging("Help title string does not exist: [$this->identifier, $this->component]");
300 }
5435c9dc 301 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
876521ac 302 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
259c165d
PS
303 }
304 }
49f0d481
PS
305}
306
bf11293a 307
000c278c
PS
308/**
309 * Data structure representing an icon.
310 *
311 * @copyright 2010 Petr Skoda
312 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
313 * @since Moodle 2.0
314 */
315class pix_icon implements renderable {
316 var $pix;
317 var $component;
318 var $attributes = array();
319
320 /**
321 * Constructor
322 * @param string $pix short icon name
323 * @param string $component component name
324 * @param array $attributes html attributes
325 */
326 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
327 $this->pix = $pix;
328 $this->component = $component;
000c278c
PS
329 $this->attributes = (array)$attributes;
330
331 $this->attributes['alt'] = $alt;
332 if (empty($this->attributes['class'])) {
333 $this->attributes['class'] = 'smallicon';
334 }
335 if (!isset($this->attributes['title'])) {
336 $this->attributes['title'] = $this->attributes['alt'];
337 }
338 }
339}
340
341
3ba60ee1
PS
342/**
343 * Data structure representing a simple form with only one button.
344 *
345 * @copyright 2009 Petr Skoda
346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
347 * @since Moodle 2.0
348 */
349class single_button implements renderable {
574fbea4
PS
350 /**
351 * Target url
352 * @var moodle_url
353 */
3ba60ee1 354 var $url;
574fbea4
PS
355 /**
356 * Button label
357 * @var string
358 */
3ba60ee1 359 var $label;
574fbea4
PS
360 /**
361 * Form submit method
362 * @var string post or get
363 */
3ba60ee1 364 var $method = 'post';
574fbea4
PS
365 /**
366 * Wrapping div class
367 * @var string
368 * */
3ba60ee1 369 var $class = 'singlebutton';
574fbea4
PS
370 /**
371 * True if button disabled, false if normal
372 * @var boolean
373 */
3ba60ee1 374 var $disabled = false;
574fbea4
PS
375 /**
376 * Button tooltip
377 * @var string
378 */
97c10099 379 var $tooltip = null;
574fbea4
PS
380 /**
381 * Form id
382 * @var string
383 */
3ba60ee1 384 var $formid;
574fbea4
PS
385 /**
386 * List of attached actions
387 * @var array of component_action
388 */
3ba60ee1
PS
389 var $actions = array();
390
391 /**
392 * Constructor
574fbea4 393 * @param string|moodle_url $url
3ba60ee1
PS
394 * @param string $label button text
395 * @param string $method get or post submit method
3ba60ee1
PS
396 */
397 public function __construct(moodle_url $url, $label, $method='post') {
398 $this->url = clone($url);
399 $this->label = $label;
400 $this->method = $method;
401 }
402
403 /**
574fbea4 404 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1
PS
405 * The message must be a yes/no question.
406 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
407 * @return void
408 */
409 public function add_confirm_action($confirmmessage) {
20fb563e 410 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
3ba60ee1
PS
411 }
412
574fbea4
PS
413 /**
414 * Add action to the button.
415 * @param component_action $action
416 * @return void
417 */
3ba60ee1
PS
418 public function add_action(component_action $action) {
419 $this->actions[] = $action;
420 }
421}
422
423
a9967cf5
PS
424/**
425 * Simple form with just one select field that gets submitted automatically.
426 * If JS not enabled small go button is printed too.
427 *
428 * @copyright 2009 Petr Skoda
429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
430 * @since Moodle 2.0
431 */
432class single_select implements renderable {
433 /**
434 * Target url - includes hidden fields
435 * @var moodle_url
436 */
437 var $url;
438 /**
439 * Name of the select element.
440 * @var string
441 */
442 var $name;
443 /**
444 * @var array $options 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 $options;
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 * Form submit method
473 * @var string post or get
474 */
475 var $method = 'get';
476 /**
477 * Wrapping div class
478 * @var string
479 * */
480 var $class = 'singleselect';
481 /**
482 * True if button disabled, false if normal
483 * @var boolean
484 */
485 var $disabled = false;
486 /**
487 * Button tooltip
488 * @var string
489 */
490 var $tooltip = null;
491 /**
492 * Form id
493 * @var string
494 */
495 var $formid = null;
496 /**
497 * List of attached actions
498 * @var array of component_action
499 */
500 var $helpicon = null;
501 /**
502 * Constructor
503 * @param moodle_url $url form action target, includes hidden fields
504 * @param string $name name of selection field - the changing parameter in url
505 * @param array $options list of options
506 * @param string $selected selected element
507 * @param array $nothing
f8dab966 508 * @param string $formid
a9967cf5 509 */
f8dab966 510 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
a9967cf5
PS
511 $this->url = $url;
512 $this->name = $name;
513 $this->options = $options;
514 $this->selected = $selected;
515 $this->nothing = $nothing;
f8dab966 516 $this->formid = $formid;
a9967cf5
PS
517 }
518
519 /**
520 * Shortcut for adding a JS confirm dialog when the button is clicked.
521 * The message must be a yes/no question.
522 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
523 * @return void
524 */
525 public function add_confirm_action($confirmmessage) {
526 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
527 }
528
529 /**
530 * Add action to the button.
531 * @param component_action $action
532 * @return void
533 */
534 public function add_action(component_action $action) {
535 $this->actions[] = $action;
536 }
f8dab966
PS
537
538 /**
259c165d 539 * Adds help icon.
f8dab966 540 * @param string $page The keyword that defines a help page
1a10840e 541 * @param string $title A descriptive text for accessibility only
f8dab966
PS
542 * @param string $component
543 * @param bool $linktext add extra text to icon
544 * @return void
545 */
596509e4
PS
546 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
547 $this->helpicon = new old_help_icon($helppage, $title, $component);
f8dab966
PS
548 }
549
259c165d
PS
550 /**
551 * Adds help icon.
552 * @param string $identifier The keyword that defines a help page
553 * @param string $component
554 * @param bool $linktext add extra text to icon
555 * @return void
556 */
557 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 558 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
559 }
560
f8dab966 561 /**
995f2d51 562 * Sets select's label
f8dab966
PS
563 * @param string $label
564 * @return void
565 */
566 public function set_label($label) {
567 $this->label = $label;
568 }
a9967cf5
PS
569}
570
571
4d10e579
PS
572/**
573 * Simple URL selection widget description.
574 * @copyright 2009 Petr Skoda
575 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
576 * @since Moodle 2.0
577 */
578class url_select implements renderable {
579 /**
580 * @var array $urls associative array value=>label ex.:
581 * array(1=>'One, 2=>Two)
582 * it is also possible to specify optgroup as complex label array ex.:
583 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
584 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
585 */
586 var $urls;
587 /**
588 * Selected option
589 * @var string
590 */
591 var $selected;
592 /**
593 * Nothing selected
594 * @var array
595 */
596 var $nothing;
597 /**
598 * Extra select field attributes
599 * @var array
600 */
601 var $attributes = array();
602 /**
603 * Button label
604 * @var string
605 */
606 var $label = '';
607 /**
608 * Wrapping div class
609 * @var string
610 * */
611 var $class = 'urlselect';
612 /**
613 * True if button disabled, false if normal
614 * @var boolean
615 */
616 var $disabled = false;
617 /**
618 * Button tooltip
619 * @var string
620 */
621 var $tooltip = null;
622 /**
623 * Form id
624 * @var string
625 */
626 var $formid = null;
627 /**
628 * List of attached actions
629 * @var array of component_action
630 */
631 var $helpicon = null;
632 /**
633 * Constructor
634 * @param array $urls list of options
635 * @param string $selected selected element
636 * @param array $nothing
637 * @param string $formid
638 */
639 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
640 $this->urls = $urls;
641 $this->selected = $selected;
642 $this->nothing = $nothing;
643 $this->formid = $formid;
644 }
645
646 /**
259c165d 647 * Adds help icon.
4d10e579 648 * @param string $page The keyword that defines a help page
1a10840e 649 * @param string $title A descriptive text for accessibility only
4d10e579
PS
650 * @param string $component
651 * @param bool $linktext add extra text to icon
652 * @return void
653 */
596509e4
PS
654 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
655 $this->helpicon = new old_help_icon($helppage, $title, $component);
4d10e579
PS
656 }
657
259c165d
PS
658 /**
659 * Adds help icon.
660 * @param string $identifier The keyword that defines a help page
661 * @param string $component
662 * @param bool $linktext add extra text to icon
663 * @return void
664 */
665 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 666 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
667 }
668
4d10e579 669 /**
995f2d51 670 * Sets select's label
4d10e579
PS
671 * @param string $label
672 * @return void
673 */
674 public function set_label($label) {
675 $this->label = $label;
676 }
677}
678
679
574fbea4
PS
680/**
681 * Data structure describing html link with special action attached.
682 * @copyright 2010 Petr Skoda
683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
684 * @since Moodle 2.0
685 */
686class action_link implements renderable {
687 /**
688 * Href url
689 * @var moodle_url
690 */
691 var $url;
692 /**
693 * Link text
694 * @var string HTML fragment
695 */
696 var $text;
697 /**
698 * HTML attributes
699 * @var array
700 */
701 var $attributes;
702 /**
703 * List of actions attached to link
704 * @var array of component_action
705 */
706 var $actions;
707
708 /**
709 * Constructor
710 * @param string|moodle_url $url
711 * @param string $text HTML fragment
712 * @param component_action $action
11820bac 713 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
714 */
715 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
716 $this->url = clone($url);
717 $this->text = $text;
b0fef57b 718 $this->attributes = (array)$attributes;
f14b641b 719 if ($action) {
574fbea4
PS
720 $this->add_action($action);
721 }
722 }
723
724 /**
725 * Add action to the link.
726 * @param component_action $action
727 * @return void
728 */
729 public function add_action(component_action $action) {
730 $this->actions[] = $action;
731 }
c63923bd
PS
732
733 public function add_class($class) {
67da0bf7
DM
734 if (empty($this->attributes['class'])) {
735 $this->attributes['class'] = $class;
c63923bd 736 } else {
67da0bf7 737 $this->attributes['class'] .= ' ' . $class;
c63923bd
PS
738 }
739 }
574fbea4 740}
3ba60ee1 741
227255b8 742// ==== HTML writer and helper classes, will be probably moved elsewhere ======
5d0c95a5
PS
743
744/**
745 * Simple html output class
746 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
747 */
748class html_writer {
749 /**
750 * Outputs a tag with attributes and contents
751 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
5d0c95a5 752 * @param string $contents What goes between the opening and closing tags
26acc814 753 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
5d0c95a5
PS
754 * @return string HTML fragment
755 */
26acc814 756 public static function tag($tagname, $contents, array $attributes = null) {
5d0c95a5
PS
757 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
758 }
759
760 /**
761 * Outputs an opening tag with attributes
762 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
763 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
764 * @return string HTML fragment
765 */
766 public static function start_tag($tagname, array $attributes = null) {
767 return '<' . $tagname . self::attributes($attributes) . '>';
768 }
769
770 /**
771 * Outputs a closing tag
772 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
773 * @return string HTML fragment
774 */
775 public static function end_tag($tagname) {
776 return '</' . $tagname . '>';
777 }
778
779 /**
780 * Outputs an empty tag with attributes
781 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
782 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
783 * @return string HTML fragment
784 */
785 public static function empty_tag($tagname, array $attributes = null) {
786 return '<' . $tagname . self::attributes($attributes) . ' />';
787 }
788
836c47d7
TH
789 /**
790 * Outputs a tag, but only if the contents are not empty
791 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
792 * @param string $contents What goes between the opening and closing tags
793 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
794 * @return string HTML fragment
795 */
796 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
797 if ($contents === '' || is_null($contents)) {
798 return '';
799 }
800 return self::tag($tagname, $contents, $attributes);
801 }
802
5d0c95a5
PS
803 /**
804 * Outputs a HTML attribute and value
805 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
806 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
807 * @return string HTML fragment
808 */
809 public static function attribute($name, $value) {
810 if (is_array($value)) {
811 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
812 }
bf11293a
PS
813 if ($value instanceof moodle_url) {
814 return ' ' . $name . '="' . $value->out() . '"';
815 }
97c10099
PS
816
817 // special case, we do not want these in output
818 if ($value === null) {
819 return '';
5d0c95a5 820 }
97c10099
PS
821
822 // no sloppy trimming here!
823 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
824 }
825
826 /**
827 * Outputs a list of HTML attributes and values
828 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
829 * The values will be escaped with {@link s()}
830 * @return string HTML fragment
831 */
832 public static function attributes(array $attributes = null) {
833 $attributes = (array)$attributes;
834 $output = '';
835 foreach ($attributes as $name => $value) {
836 $output .= self::attribute($name, $value);
837 }
838 return $output;
839 }
840
841 /**
842 * Generates random html element id.
843 * @param string $base
844 * @return string
845 */
846 public static function random_id($base='random') {
847 return uniqid($base);
848 }
0f4c64b7
PS
849
850 /**
851 * Generates a simple html link
852 * @param string|moodle_url $url
853 * @param string $text link txt
854 * @param array $attributes extra html attributes
855 * @return string HTML fragment
856 */
857 public static function link($url, $text, array $attributes = null) {
858 $attributes = (array)$attributes;
859 $attributes['href'] = $url;
26acc814 860 return self::tag('a', $text, $attributes);
0f4c64b7 861 }
3ff163c5 862
14dce022
PS
863 /**
864 * generates a simple checkbox with optional label
865 * @param string $name
866 * @param string $value
867 * @param bool $checked
868 * @param string $label
869 * @param array $attributes
870 * @return string html fragment
871 */
872 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
873 $attributes = (array)$attributes;
874 $output = '';
875
876 if ($label !== '' and !is_null($label)) {
877 if (empty($attributes['id'])) {
878 $attributes['id'] = self::random_id('checkbox_');
879 }
880 }
53868425
PS
881 $attributes['type'] = 'checkbox';
882 $attributes['value'] = $value;
883 $attributes['name'] = $name;
621b4d08 884 $attributes['checked'] = $checked ? 'checked' : null;
53868425 885
14dce022
PS
886 $output .= self::empty_tag('input', $attributes);
887
888 if ($label !== '' and !is_null($label)) {
26acc814 889 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
14dce022
PS
890 }
891
892 return $output;
893 }
894
78bdac64
PS
895 /**
896 * Generates a simple select yes/no form field
897 * @param string $name name of select element
898 * @param bool $selected
899 * @param array $attributes - html select element attributes
900 * @return string HRML fragment
901 */
19f3bbb2 902 public static function select_yes_no($name, $selected=true, array $attributes = null) {
78bdac64
PS
903 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
904 return self::select($options, $name, $selected, null, $attributes);
905 }
906
3ff163c5
PS
907 /**
908 * Generates a simple select form field
6770330d
PS
909 * @param array $options associative array value=>label ex.:
910 * array(1=>'One, 2=>Two)
911 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 912 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 913 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5 914 * @param string $name name of select element
1a10840e 915 * @param string|array $selected value or array of values depending on multiple attribute
3ff163c5
PS
916 * @param array|bool $nothing, add nothing selected option, or false of not added
917 * @param array $attributes - html select element attributes
78bdac64 918 * @return string HTML fragment
3ff163c5 919 */
aa2dea70 920 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
3ff163c5
PS
921 $attributes = (array)$attributes;
922 if (is_array($nothing)) {
923 foreach ($nothing as $k=>$v) {
4b9210f3 924 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
925 $nothing[$k] = get_string('choosedots');
926 }
927 }
928 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
929
930 } else if (is_string($nothing) and $nothing !== '') {
931 // BC
932 $options = array(''=>$nothing) + $options;
bde156b3 933 }
3ff163c5
PS
934
935 // we may accept more values if multiple attribute specified
936 $selected = (array)$selected;
937 foreach ($selected as $k=>$v) {
938 $selected[$k] = (string)$v;
939 }
940
941 if (!isset($attributes['id'])) {
942 $id = 'menu'.$name;
943 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
944 $id = str_replace('[', '', $id);
945 $id = str_replace(']', '', $id);
946 $attributes['id'] = $id;
947 }
948
949 if (!isset($attributes['class'])) {
950 $class = 'menu'.$name;
951 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
952 $class = str_replace('[', '', $class);
953 $class = str_replace(']', '', $class);
954 $attributes['class'] = $class;
955 }
956 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
957
958 $attributes['name'] = $name;
959
960 $output = '';
961 foreach ($options as $value=>$label) {
6770330d
PS
962 if (is_array($label)) {
963 // ignore key, it just has to be unique
964 $output .= self::select_optgroup(key($label), current($label), $selected);
965 } else {
966 $output .= self::select_option($label, $value, $selected);
3ff163c5 967 }
3ff163c5 968 }
26acc814 969 return self::tag('select', $output, $attributes);
3ff163c5 970 }
6770330d
PS
971
972 private static function select_option($label, $value, array $selected) {
973 $attributes = array();
974 $value = (string)$value;
975 if (in_array($value, $selected, true)) {
976 $attributes['selected'] = 'selected';
977 }
978 $attributes['value'] = $value;
26acc814 979 return self::tag('option', $label, $attributes);
6770330d
PS
980 }
981
982 private static function select_optgroup($groupname, $options, array $selected) {
983 if (empty($options)) {
984 return '';
985 }
986 $attributes = array('label'=>$groupname);
987 $output = '';
988 foreach ($options as $value=>$label) {
989 $output .= self::select_option($label, $value, $selected);
990 }
26acc814 991 return self::tag('optgroup', $output, $attributes);
6770330d 992 }
6ea66ff3 993
f83b9b63
PS
994 /**
995 * This is a shortcut for making an hour selector menu.
996 * @param string $type The type of selector (years, months, days, hours, minutes)
997 * @param string $name fieldname
998 * @param int $currenttime A default timestamp in GMT
999 * @param int $step minute spacing
1000 * @param array $attributes - html select element attributes
1001 * @return HTML fragment
1002 */
1003 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1004 if (!$currenttime) {
1005 $currenttime = time();
1006 }
1007 $currentdate = usergetdate($currenttime);
1008 $userdatetype = $type;
1009 $timeunits = array();
1010
1011 switch ($type) {
1012 case 'years':
1013 for ($i=1970; $i<=2020; $i++) {
1014 $timeunits[$i] = $i;
1015 }
1016 $userdatetype = 'year';
1017 break;
1018 case 'months':
1019 for ($i=1; $i<=12; $i++) {
1020 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1021 }
1022 $userdatetype = 'month';
1023 $currentdate['month'] = $currentdate['mon'];
1024 break;
1025 case 'days':
1026 for ($i=1; $i<=31; $i++) {
1027 $timeunits[$i] = $i;
1028 }
1029 $userdatetype = 'mday';
1030 break;
1031 case 'hours':
1032 for ($i=0; $i<=23; $i++) {
1033 $timeunits[$i] = sprintf("%02d",$i);
1034 }
1035 break;
1036 case 'minutes':
1037 if ($step != 1) {
1038 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1039 }
1040
1041 for ($i=0; $i<=59; $i+=$step) {
1042 $timeunits[$i] = sprintf("%02d",$i);
1043 }
1044 break;
1045 default:
1046 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1047 }
1048
1049 if (empty($attributes['id'])) {
1050 $attributes['id'] = self::random_id('ts_');
1051 }
1052 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
26acc814 1053 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
f83b9b63
PS
1054
1055 return $label.$timerselector;
1056 }
1057
5be262b6
PS
1058 /**
1059 * Shortcut for quick making of lists
1060 * @param array $items
1061 * @param string $tag ul or ol
1062 * @param array $attributes
1063 * @return string
1064 */
1065 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1066 //note: 'list' is a reserved keyword ;-)
1067
1068 $output = '';
1069
1070 foreach ($items as $item) {
1071 $output .= html_writer::start_tag('li') . "\n";
1072 $output .= $item . "\n";
1073 $output .= html_writer::end_tag('li') . "\n";
1074 }
1075
26acc814 1076 return html_writer::tag($tag, $output, $attributes);
5be262b6
PS
1077 }
1078
6ea66ff3
PS
1079 /**
1080 * Returns hidden input fields created from url parameters.
1081 * @param moodle_url $url
1082 * @param array $exclude list of excluded parameters
1083 * @return string HTML fragment
1084 */
1085 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1086 $exclude = (array)$exclude;
1087 $params = $url->params();
1088 foreach ($exclude as $key) {
1089 unset($params[$key]);
1090 }
1091
1092 $output = '';
bde156b3 1093 foreach ($params as $key => $value) {
6ea66ff3
PS
1094 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1095 $output .= self::empty_tag('input', $attributes)."\n";
1096 }
1097 return $output;
1098 }
77774f6a
PS
1099
1100 /**
1101 * Generate a script tag containing the the specified code.
1102 *
1103 * @param string $js the JavaScript code
e50b4c89 1104 * @param moodle_url|string optional url of the external script, $code ignored if specified
77774f6a
PS
1105 * @return string HTML, the code wrapped in <script> tags.
1106 */
e50b4c89 1107 public static function script($jscode, $url=null) {
77774f6a 1108 if ($jscode) {
e50b4c89 1109 $attributes = array('type'=>'text/javascript');
26acc814 1110 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
e50b4c89
PS
1111
1112 } else if ($url) {
1113 $attributes = array('type'=>'text/javascript', 'src'=>$url);
26acc814 1114 return self::tag('script', '', $attributes) . "\n";
a9967cf5 1115
77774f6a
PS
1116 } else {
1117 return '';
1118 }
1119 }
16be8974
DM
1120
1121 /**
1122 * Renders HTML table
1123 *
1124 * This method may modify the passed instance by adding some default properties if they are not set yet.
1125 * If this is not what you want, you should make a full clone of your data before passing them to this
1126 * method. In most cases this is not an issue at all so we do not clone by default for performance
1127 * and memory consumption reasons.
1128 *
1129 * @param html_table $table data to be rendered
1130 * @return string HTML code
1131 */
1132 public static function table(html_table $table) {
1133 // prepare table data and populate missing properties with reasonable defaults
1134 if (!empty($table->align)) {
1135 foreach ($table->align as $key => $aa) {
1136 if ($aa) {
1137 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1138 } else {
1139 $table->align[$key] = null;
1140 }
1141 }
1142 }
1143 if (!empty($table->size)) {
1144 foreach ($table->size as $key => $ss) {
1145 if ($ss) {
1146 $table->size[$key] = 'width:'. $ss .';';
1147 } else {
1148 $table->size[$key] = null;
1149 }
1150 }
1151 }
1152 if (!empty($table->wrap)) {
1153 foreach ($table->wrap as $key => $ww) {
1154 if ($ww) {
1155 $table->wrap[$key] = 'white-space:nowrap;';
1156 } else {
1157 $table->wrap[$key] = '';
1158 }
1159 }
1160 }
1161 if (!empty($table->head)) {
1162 foreach ($table->head as $key => $val) {
1163 if (!isset($table->align[$key])) {
1164 $table->align[$key] = null;
1165 }
1166 if (!isset($table->size[$key])) {
1167 $table->size[$key] = null;
1168 }
1169 if (!isset($table->wrap[$key])) {
1170 $table->wrap[$key] = null;
1171 }
1172
1173 }
1174 }
1175 if (empty($table->attributes['class'])) {
1176 $table->attributes['class'] = 'generaltable';
1177 }
1178 if (!empty($table->tablealign)) {
1179 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1180 }
1181
1182 // explicitly assigned properties override those defined via $table->attributes
e126c0cc 1183 $table->attributes['class'] = trim($table->attributes['class']);
16be8974
DM
1184 $attributes = array_merge($table->attributes, array(
1185 'id' => $table->id,
1186 'width' => $table->width,
1187 'summary' => $table->summary,
1188 'cellpadding' => $table->cellpadding,
1189 'cellspacing' => $table->cellspacing,
1190 ));
1191 $output = html_writer::start_tag('table', $attributes) . "\n";
1192
1193 $countcols = 0;
1194
1195 if (!empty($table->head)) {
1196 $countcols = count($table->head);
5174f3c5 1197
16be8974
DM
1198 $output .= html_writer::start_tag('thead', array()) . "\n";
1199 $output .= html_writer::start_tag('tr', array()) . "\n";
1200 $keys = array_keys($table->head);
1201 $lastkey = end($keys);
1202
1203 foreach ($table->head as $key => $heading) {
1204 // Convert plain string headings into html_table_cell objects
1205 if (!($heading instanceof html_table_cell)) {
1206 $headingtext = $heading;
1207 $heading = new html_table_cell();
1208 $heading->text = $headingtext;
1209 $heading->header = true;
1210 }
1211
1212 if ($heading->header !== false) {
1213 $heading->header = true;
1214 }
1215
e126c0cc
DM
1216 if ($heading->header && empty($heading->scope)) {
1217 $heading->scope = 'col';
1218 }
1219
16be8974
DM
1220 $heading->attributes['class'] .= ' header c' . $key;
1221 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1222 $heading->colspan = $table->headspan[$key];
1223 $countcols += $table->headspan[$key] - 1;
1224 }
1225
1226 if ($key == $lastkey) {
1227 $heading->attributes['class'] .= ' lastcol';
1228 }
1229 if (isset($table->colclasses[$key])) {
1230 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1231 }
e126c0cc 1232 $heading->attributes['class'] = trim($heading->attributes['class']);
16be8974
DM
1233 $attributes = array_merge($heading->attributes, array(
1234 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1235 'scope' => $heading->scope,
1236 'colspan' => $heading->colspan,
1237 ));
1238
1239 $tagtype = 'td';
1240 if ($heading->header === true) {
1241 $tagtype = 'th';
1242 }
1243 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1244 }
1245 $output .= html_writer::end_tag('tr') . "\n";
1246 $output .= html_writer::end_tag('thead') . "\n";
1247
1248 if (empty($table->data)) {
1249 // For valid XHTML strict every table must contain either a valid tr
1250 // or a valid tbody... both of which must contain a valid td
1251 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1252 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1253 $output .= html_writer::end_tag('tbody');
1254 }
1255 }
1256
1257 if (!empty($table->data)) {
1258 $oddeven = 1;
1259 $keys = array_keys($table->data);
1260 $lastrowkey = end($keys);
1261 $output .= html_writer::start_tag('tbody', array());
1262
1263 foreach ($table->data as $key => $row) {
1264 if (($row === 'hr') && ($countcols)) {
1265 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1266 } else {
1267 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1268 if (!($row instanceof html_table_row)) {
1269 $newrow = new html_table_row();
1270
e126c0cc 1271 foreach ($row as $item) {
16be8974
DM
1272 $cell = new html_table_cell();
1273 $cell->text = $item;
1274 $newrow->cells[] = $cell;
1275 }
1276 $row = $newrow;
1277 }
1278
1279 $oddeven = $oddeven ? 0 : 1;
1280 if (isset($table->rowclasses[$key])) {
1281 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1282 }
1283
1284 $row->attributes['class'] .= ' r' . $oddeven;
1285 if ($key == $lastrowkey) {
1286 $row->attributes['class'] .= ' lastrow';
1287 }
1288
e126c0cc 1289 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
16be8974
DM
1290 $keys2 = array_keys($row->cells);
1291 $lastkey = end($keys2);
1292
5174f3c5 1293 $gotlastkey = false; //flag for sanity checking
16be8974 1294 foreach ($row->cells as $key => $cell) {
5174f3c5
AD
1295 if ($gotlastkey) {
1296 //This should never happen. Why do we have a cell after the last cell?
1297 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1298 }
1299
16be8974
DM
1300 if (!($cell instanceof html_table_cell)) {
1301 $mycell = new html_table_cell();
1302 $mycell->text = $cell;
1303 $cell = $mycell;
1304 }
1305
e126c0cc
DM
1306 if (($cell->header === true) && empty($cell->scope)) {
1307 $cell->scope = 'row';
1308 }
1309
16be8974
DM
1310 if (isset($table->colclasses[$key])) {
1311 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1312 }
1313
1314 $cell->attributes['class'] .= ' cell c' . $key;
1315 if ($key == $lastkey) {
1316 $cell->attributes['class'] .= ' lastcol';
5174f3c5 1317 $gotlastkey = true;
16be8974
DM
1318 }
1319 $tdstyle = '';
1320 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1321 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1322 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1323 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1324 $tdattributes = array_merge($cell->attributes, array(
1325 'style' => $tdstyle . $cell->style,
1326 'colspan' => $cell->colspan,
1327 'rowspan' => $cell->rowspan,
1328 'id' => $cell->id,
1329 'abbr' => $cell->abbr,
1330 'scope' => $cell->scope,
1331 ));
1332 $tagtype = 'td';
1333 if ($cell->header === true) {
1334 $tagtype = 'th';
1335 }
1336 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1337 }
1338 }
1339 $output .= html_writer::end_tag('tr') . "\n";
1340 }
1341 $output .= html_writer::end_tag('tbody') . "\n";
1342 }
1343 $output .= html_writer::end_tag('table') . "\n";
1344
1345 return $output;
1346 }
1347
995f2d51
DM
1348 /**
1349 * Renders form element label
1350 *
1351 * By default, the label is suffixed with a label separator defined in the
1352 * current language pack (colon by default in the English lang pack).
1353 * Adding the colon can be explicitly disabled if needed. Label separators
1354 * are put outside the label tag itself so they are not read by
1355 * screenreaders (accessibility).
1356 *
1357 * Parameter $for explicitly associates the label with a form control. When
1358 * set, the value of this attribute must be the same as the value of
1359 * the id attribute of the form control in the same document. When null,
1360 * the label being defined is associated with the control inside the label
1361 * element.
1362 *
1363 * @param string $text content of the label tag
1364 * @param string|null $for id of the element this label is associated with, null for no association
1365 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1366 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1367 * @return string HTML of the label element
1368 */
1369 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1370 if (!is_null($for)) {
1371 $attributes = array_merge($attributes, array('for' => $for));
1372 }
1373 $text = trim($text);
1374 $label = self::tag('label', $text, $attributes);
1375
81e62b6f
DM
1376 /*
1377 // TODO $colonize disabled for now yet - see MDL-12192 for details
1ce51635 1378 if (!empty($text) and $colonize) {
995f2d51
DM
1379 // the $text may end with the colon already, though it is bad string definition style
1380 $colon = get_string('labelsep', 'langconfig');
1381 if (!empty($colon)) {
1382 $trimmed = trim($colon);
1383 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1384 //debugging('The label text should not end with colon or other label separator,
1385 // please fix the string definition.', DEBUG_DEVELOPER);
1386 } else {
1387 $label .= $colon;
1388 }
1389 }
1390 }
81e62b6f 1391 */
995f2d51
DM
1392
1393 return $label;
1394 }
5d0c95a5
PS
1395}
1396
227255b8
PS
1397// ==== JS writer and helper classes, will be probably moved elsewhere ======
1398
1399/**
1400 * Simple javascript output class
1401 * @copyright 2010 Petr Skoda
1402 */
1403class js_writer {
1404 /**
1405 * Returns javascript code calling the function
1a10840e 1406 * @param string $function function name, can be complex like Y.Event.purgeElement
227255b8
PS
1407 * @param array $arguments parameters
1408 * @param int $delay execution delay in seconds
1409 * @return string JS code fragment
1410 */
e839dce1 1411 public static function function_call($function, array $arguments = null, $delay=0) {
1b4e41af
PS
1412 if ($arguments) {
1413 $arguments = array_map('json_encode', $arguments);
1414 $arguments = implode(', ', $arguments);
1415 } else {
1416 $arguments = '';
1417 }
227255b8
PS
1418 $js = "$function($arguments);";
1419
1420 if ($delay) {
1421 $delay = $delay * 1000; // in miliseconds
1422 $js = "setTimeout(function() { $js }, $delay);";
1423 }
1424 return $js . "\n";
1425 }
1426
3b01539c
PS
1427 /**
1428 * Special function which adds Y as first argument of fucntion call.
1429 * @param string $function
1430 * @param array $extraarguments
1431 * @return string
1432 */
e839dce1 1433 public static function function_call_with_Y($function, array $extraarguments = null) {
3b01539c
PS
1434 if ($extraarguments) {
1435 $extraarguments = array_map('json_encode', $extraarguments);
1436 $arguments = 'Y, ' . implode(', ', $extraarguments);
1437 } else {
1438 $arguments = 'Y';
1439 }
1440 return "$function($arguments);\n";
1441 }
1442
1ce15fda
SH
1443 /**
1444 * Returns JavaScript code to initialise a new object
1445 * @param string|null $var If it is null then no var is assigned the new object
1446 * @param string $class
1447 * @param array $arguments
1448 * @param array $requirements
1449 * @param int $delay
1450 * @return string
1451 */
e839dce1 1452 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1ce15fda
SH
1453 if (is_array($arguments)) {
1454 $arguments = array_map('json_encode', $arguments);
1455 $arguments = implode(', ', $arguments);
1456 }
1457
1458 if ($var === null) {
53fc3e70 1459 $js = "new $class(Y, $arguments);";
1ce15fda 1460 } else if (strpos($var, '.')!==false) {
53fc3e70 1461 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1462 } else {
53fc3e70 1463 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1464 }
1465
1466 if ($delay) {
1467 $delay = $delay * 1000; // in miliseconds
1468 $js = "setTimeout(function() { $js }, $delay);";
1469 }
1470
1471 if (count($requirements) > 0) {
1472 $requirements = implode("', '", $requirements);
53fc3e70 1473 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1474 }
1475 return $js."\n";
1476 }
1477
227255b8
PS
1478 /**
1479 * Returns code setting value to variable
1480 * @param string $name
1481 * @param mixed $value json serialised value
1482 * @param bool $usevar add var definition, ignored for nested properties
1483 * @return string JS code fragment
1484 */
e839dce1 1485 public static function set_variable($name, $value, $usevar=true) {
227255b8
PS
1486 $output = '';
1487
1488 if ($usevar) {
1489 if (strpos($name, '.')) {
1490 $output .= '';
1491 } else {
1492 $output .= 'var ';
1493 }
1494 }
1495
1496 $output .= "$name = ".json_encode($value).";";
1497
1498 return $output;
1499 }
1500
1501 /**
1502 * Writes event handler attaching code
1a10840e 1503 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
227255b8
PS
1504 * @param string $event A valid DOM event (click, mousedown, change etc.)
1505 * @param string $function The name of the function to call
1506 * @param array $arguments An optional array of argument parameters to pass to the function
1507 * @return string JS code fragment
1508 */
e839dce1 1509 public static function event_handler($selector, $event, $function, array $arguments = null) {
227255b8
PS
1510 $selector = json_encode($selector);
1511 $output = "Y.on('$event', $function, $selector, null";
1512 if (!empty($arguments)) {
1513 $output .= ', ' . json_encode($arguments);
1514 }
1515 return $output . ");\n";
1516 }
1517}
1518
d9c8f425 1519/**
16be8974 1520 * Holds all the information required to render a <table> by {@see core_renderer::table()}
d9c8f425 1521 *
16be8974
DM
1522 * Example of usage:
1523 * $t = new html_table();
1524 * ... // set various properties of the object $t as described below
1525 * echo html_writer::table($t);
d9c8f425 1526 *
16be8974 1527 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
d9c8f425 1528 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1529 * @since Moodle 2.0
1530 */
16be8974 1531class html_table {
d9c8f425 1532 /**
16be8974 1533 * @var string value to use for the id attribute of the table
d9c8f425 1534 */
97c10099 1535 public $id = null;
d9c8f425 1536 /**
16be8974 1537 * @var array attributes of HTML attributes for the <table> element
d9c8f425 1538 */
16be8974 1539 public $attributes = array();
7b1f2c82 1540 /**
a0ead5eb 1541 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1542 * can be passed instead of an array of strings.
7b1f2c82 1543 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1544 *
1545 * Example of usage:
1546 * $t->head = array('Student', 'Grade');
1547 */
1548 public $head;
1549 /**
1550 * @var array can be used to make a heading span multiple columns
1551 *
1552 * Example of usage:
1553 * $t->headspan = array(2,1);
1554 *
1555 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1556 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1557 */
1558 public $headspan;
1559 /**
1560 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1561 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1562 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1563 *
beb56299 1564 * Examples of usage:
1565 * $t->align = array(null, 'right');
1566 * or
1567 * $t->align[1] = 'right';
1568 *
d9c8f425 1569 */
beb56299 1570 public $align;
d9c8f425 1571 /**
beb56299 1572 * @var array of column sizes. The value is used as CSS 'size' property.
1573 *
1574 * Examples of usage:
1575 * $t->size = array('50%', '50%');
1576 * or
1577 * $t->size[1] = '120px';
d9c8f425 1578 */
beb56299 1579 public $size;
d9c8f425 1580 /**
beb56299 1581 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1582 * CSS property 'white-space' to the value 'nowrap' in the given column.
1583 *
1584 * Example of usage:
1585 * $t->wrap = array(null, 'nowrap');
d9c8f425 1586 */
beb56299 1587 public $wrap;
d9c8f425 1588 /**
beb56299 1589 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1590 * $head specified, the string 'hr' (for horizontal ruler) can be used
1591 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1592 *
beb56299 1593 * Example of usage with array of arrays:
1594 * $row1 = array('Harry Potter', '76 %');
1595 * $row2 = array('Hermione Granger', '100 %');
1596 * $t->data = array($row1, $row2);
d9c8f425 1597 *
beb56299 1598 * Example with array of html_table_row objects: (used for more fine-grained control)
1599 * $cell1 = new html_table_cell();
1600 * $cell1->text = 'Harry Potter';
1601 * $cell1->colspan = 2;
1602 * $row1 = new html_table_row();
1603 * $row1->cells[] = $cell1;
1604 * $cell2 = new html_table_cell();
1605 * $cell2->text = 'Hermione Granger';
1606 * $cell3 = new html_table_cell();
1607 * $cell3->text = '100 %';
1608 * $row2 = new html_table_row();
1609 * $row2->cells = array($cell2, $cell3);
1610 * $t->data = array($row1, $row2);
1611 */
1612 public $data;
1613 /**
16be8974 1614 * @var string width of the table, percentage of the page preferred. Defaults to 80%
beb56299 1615 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1616 */
1617 public $width = null;
1618 /**
1619 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1620 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1621 */
1622 public $tablealign = null;
1623 /**
1624 * @var int padding on each cell, in pixels
1625 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1626 */
1627 public $cellpadding = null;
1628 /**
1629 * @var int spacing between cells, in pixels
1630 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1631 */
1632 public $cellspacing = null;
1633 /**
1634 * @var array classes to add to particular rows, space-separated string.
1635 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1636 * respectively. Class 'lastrow' is added automatically for the last row
1637 * in the table.
d9c8f425 1638 *
beb56299 1639 * Example of usage:
1640 * $t->rowclasses[9] = 'tenth'
1641 */
1642 public $rowclasses;
1643 /**
1644 * @var array classes to add to every cell in a particular column,
1645 * space-separated string. Class 'cell' is added automatically by the renderer.
1646 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1647 * respectively. Class 'lastcol' is added automatically for all last cells
1648 * in a row.
d9c8f425 1649 *
beb56299 1650 * Example of usage:
1651 * $t->colclasses = array(null, 'grade');
d9c8f425 1652 */
beb56299 1653 public $colclasses;
1654 /**
1655 * @var string description of the contents for screen readers.
1656 */
1657 public $summary;
d9c8f425 1658
1659 /**
16be8974 1660 * Constructor
d9c8f425 1661 */
16be8974
DM
1662 public function __construct() {
1663 $this->attributes['class'] = '';
d9c8f425 1664 }
d9c8f425 1665}
1666
34059565 1667
d9c8f425 1668/**
7b1f2c82 1669 * Component representing a table row.
d9c8f425 1670 *
1671 * @copyright 2009 Nicolas Connault
1672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1673 * @since Moodle 2.0
1674 */
16be8974
DM
1675class html_table_row {
1676 /**
1677 * @var string value to use for the id attribute of the row
1678 */
1679 public $id = null;
d9c8f425 1680 /**
7b1f2c82 1681 * @var array $cells Array of html_table_cell objects
d9c8f425 1682 */
7b1f2c82 1683 public $cells = array();
beb56299 1684 /**
16be8974 1685 * @var string $style value to use for the style attribute of the table row
beb56299 1686 */
16be8974
DM
1687 public $style = null;
1688 /**
1689 * @var array attributes of additional HTML attributes for the <tr> element
1690 */
1691 public $attributes = array();
a0ead5eb 1692
54a007e8 1693 /**
8cea545e 1694 * Constructor
54a007e8 1695 * @param array $cells
8cea545e
PS
1696 */
1697 public function __construct(array $cells=null) {
16be8974 1698 $this->attributes['class'] = '';
8cea545e
PS
1699 $cells = (array)$cells;
1700 foreach ($cells as $cell) {
1701 if ($cell instanceof html_table_cell) {
1702 $this->cells[] = $cell;
a019627a 1703 } else {
8cea545e 1704 $this->cells[] = new html_table_cell($cell);
a019627a 1705 }
1706 }
54a007e8 1707 }
d9c8f425 1708}
1709
34059565 1710
d9c8f425 1711/**
7b1f2c82 1712 * Component representing a table cell.
d9c8f425 1713 *
1714 * @copyright 2009 Nicolas Connault
1715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1716 * @since Moodle 2.0
1717 */
16be8974
DM
1718class html_table_cell {
1719 /**
1720 * @var string value to use for the id attribute of the cell
1721 */
1722 public $id = null;
d9c8f425 1723 /**
7b1f2c82 1724 * @var string $text The contents of the cell
d9c8f425 1725 */
7b1f2c82 1726 public $text;
d9c8f425 1727 /**
7b1f2c82 1728 * @var string $abbr Abbreviated version of the contents of the cell
d9c8f425 1729 */
97c10099 1730 public $abbr = null;
d9c8f425 1731 /**
7b1f2c82 1732 * @var int $colspan Number of columns this cell should span
d9c8f425 1733 */
97c10099 1734 public $colspan = null;
d9c8f425 1735 /**
7b1f2c82 1736 * @var int $rowspan Number of rows this cell should span
d9c8f425 1737 */
97c10099 1738 public $rowspan = null;
d9c8f425 1739 /**
7b1f2c82 1740 * @var string $scope Defines a way to associate header cells and data cells in a table
d9c8f425 1741 */
97c10099 1742 public $scope = null;
1ae3767a 1743 /**
1744 * @var boolean $header Whether or not this cell is a header cell
1745 */
a4998d01 1746 public $header = null;
16be8974
DM
1747 /**
1748 * @var string $style value to use for the style attribute of the table cell
1749 */
1750 public $style = null;
1751 /**
70dc9b38 1752 * @var array attributes of additional HTML attributes for the <td> element
16be8974
DM
1753 */
1754 public $attributes = array();
d9c8f425 1755
8cea545e
PS
1756 public function __construct($text = null) {
1757 $this->text = $text;
16be8974 1758 $this->attributes['class'] = '';
d9c8f425 1759 }
1760}
1761
34059565 1762
7b1f2c82 1763/// Complex components aggregating simpler components
1764
34059565 1765
d9c8f425 1766/**
beb56299 1767 * Component representing a paging bar.
d9c8f425 1768 *
1769 * @copyright 2009 Nicolas Connault
1770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1771 * @since Moodle 2.0
1772 */
929d7a83 1773class paging_bar implements renderable {
d9c8f425 1774 /**
beb56299 1775 * @var int $maxdisplay The maximum number of pagelinks to display
d9c8f425 1776 */
beb56299 1777 public $maxdisplay = 18;
d9c8f425 1778 /**
beb56299 1779 * @var int $totalcount post or get
d9c8f425 1780 */
beb56299 1781 public $totalcount;
d9c8f425 1782 /**
beb56299 1783 * @var int $page The page you are currently viewing
d9c8f425 1784 */
929d7a83 1785 public $page;
d9c8f425 1786 /**
beb56299 1787 * @var int $perpage The number of entries that should be shown per page
d9c8f425 1788 */
beb56299 1789 public $perpage;
d9c8f425 1790 /**
beb56299 1791 * @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.
1792 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 1793 */
beb56299 1794 public $baseurl;
d9c8f425 1795 /**
beb56299 1796 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 1797 */
929d7a83 1798 public $pagevar;
beb56299 1799 /**
56ddb719 1800 * @var string $previouslink A HTML link representing the "previous" page
beb56299 1801 */
1802 public $previouslink = null;
1803 /**
56ddb719 1804 * @var tring $nextlink A HTML link representing the "next" page
beb56299 1805 */
1806 public $nextlink = null;
1807 /**
56ddb719 1808 * @var tring $firstlink A HTML link representing the first page
beb56299 1809 */
1810 public $firstlink = null;
1811 /**
56ddb719 1812 * @var tring $lastlink A HTML link representing the last page
beb56299 1813 */
1814 public $lastlink = null;
1815 /**
56ddb719 1816 * @var array $pagelinks An array of strings. One of them is just a string: the current page
beb56299 1817 */
1818 public $pagelinks = array();
d9c8f425 1819
929d7a83
PS
1820 /**
1821 * Constructor paging_bar with only the required params.
1822 *
1a10840e 1823 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
1824 * @param int $page The page you are currently viewing
1825 * @param int $perpage The number of entries that should be shown per page
1826 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1827 * @param string $pagevar name of page parameter that holds the page number
1828 */
1829 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1830 $this->totalcount = $totalcount;
1831 $this->page = $page;
1832 $this->perpage = $perpage;
1833 $this->baseurl = $baseurl;
1834 $this->pagevar = $pagevar;
1835 }
1836
d9c8f425 1837 /**
d9c8f425 1838 * @return void
1839 */
34059565 1840 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 1841 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 1842 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 1843 }
1844 if (!isset($this->page) || is_null($this->page)) {
929d7a83 1845 throw new coding_exception('paging_bar requires a page value.');
beb56299 1846 }
1847 if (empty($this->perpage)) {
929d7a83 1848 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 1849 }
1850 if (empty($this->baseurl)) {
929d7a83 1851 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 1852 }
d9c8f425 1853
beb56299 1854 if ($this->totalcount > $this->perpage) {
1855 $pagenum = $this->page - 1;
d9c8f425 1856
beb56299 1857 if ($this->page > 0) {
929d7a83 1858 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 1859 }
d9c8f425 1860
beb56299 1861 if ($this->perpage > 0) {
1862 $lastpage = ceil($this->totalcount / $this->perpage);
1863 } else {
1864 $lastpage = 1;
1865 }
1866
1867 if ($this->page > 15) {
1868 $startpage = $this->page - 10;
1869
929d7a83 1870 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 1871 } else {
1872 $startpage = 0;
1873 }
1874
1875 $currpage = $startpage;
1876 $displaycount = $displaypage = 0;
1877
1878 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1879 $displaypage = $currpage + 1;
1880
f43cdceb 1881 if ($this->page == $currpage) {
beb56299 1882 $this->pagelinks[] = $displaypage;
1883 } else {
56ddb719 1884 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 1885 $this->pagelinks[] = $pagelink;
1886 }
1887
1888 $displaycount++;
1889 $currpage++;
1890 }
1891
1892 if ($currpage < $lastpage) {
1893 $lastpageactual = $lastpage - 1;
abdac127 1894 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 1895 }
1896
1897 $pagenum = $this->page + 1;
1898
1899 if ($pagenum != $displaypage) {
abdac127 1900 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 1901 }
d9c8f425 1902 }
1903 }
d9c8f425 1904}
1905
34059565 1906
d9c8f425 1907/**
beb56299 1908 * This class represents how a block appears on a page.
d9c8f425 1909 *
beb56299 1910 * During output, each block instance is asked to return a block_contents object,
1911 * those are then passed to the $OUTPUT->block function for display.
1912 *
1913 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
1914 *
1915 * Other block-like things that need to appear on the page, for example the
1916 * add new block UI, are also represented as block_contents objects.
1917 *
1918 * @copyright 2009 Tim Hunt
d9c8f425 1919 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1920 * @since Moodle 2.0
1921 */
dd72b308 1922class block_contents {
beb56299 1923 /** @var int used to set $skipid. */
1924 protected static $idcounter = 1;
1925
1926 const NOT_HIDEABLE = 0;
1927 const VISIBLE = 1;
1928 const HIDDEN = 2;
1929
d9c8f425 1930 /**
dd72b308 1931 * @var integer $skipid All the blocks (or things that look like blocks)
beb56299 1932 * printed on a page are given a unique number that can be used to construct
1933 * id="" attributes. This is set automatically be the {@link prepare()} method.
1934 * Do not try to set it manually.
d9c8f425 1935 */
beb56299 1936 public $skipid;
d9c8f425 1937
1938 /**
beb56299 1939 * @var integer If this is the contents of a real block, this should be set to
1940 * the block_instance.id. Otherwise this should be set to 0.
1941 */
1942 public $blockinstanceid = 0;
1943
1944 /**
1945 * @var integer if this is a real block instance, and there is a corresponding
1946 * block_position.id for the block on this page, this should be set to that id.
1947 * Otherwise it should be 0.
1948 */
1949 public $blockpositionid = 0;
1950
1951 /**
1952 * @param array $attributes an array of attribute => value pairs that are put on the
1953 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
1954 */
dd72b308 1955 public $attributes;
beb56299 1956
1957 /**
1958 * @param string $title The title of this block. If this came from user input,
1959 * it should already have had format_string() processing done on it. This will
1960 * be output inside <h2> tags. Please do not cause invalid XHTML.
1961 */
1962 public $title = '';
1963
1964 /**
1965 * @param string $content HTML for the content
1966 */
1967 public $content = '';
1968
1969 /**
1970 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1971 */
1972 public $footer = '';
1973
1974 /**
1975 * Any small print that should appear under the block to explain to the
1976 * teacher about the block, for example 'This is a sticky block that was
1977 * added in the system context.'
1978 * @var string
1979 */
1980 public $annotation = '';
1981
1982 /**
1983 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
1984 * the user can toggle whether this block is visible.
1985 */
1986 public $collapsible = self::NOT_HIDEABLE;
1987
1988 /**
1989 * A (possibly empty) array of editing controls. Each element of this array
1990 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 1991 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 1992 * @var array
1993 */
1994 public $controls = array();
1995
dd72b308 1996
beb56299 1997 /**
dd72b308
PS
1998 * Create new instance of block content
1999 * @param array $attributes
d9c8f425 2000 */
dd72b308 2001 public function __construct(array $attributes=null) {
beb56299 2002 $this->skipid = self::$idcounter;
2003 self::$idcounter += 1;
dd72b308
PS
2004
2005 if ($attributes) {
2006 // standard block
2007 $this->attributes = $attributes;
2008 } else {
2009 // simple "fake" blocks used in some modules and "Add new block" block
6605ff8c 2010 $this->attributes = array('class'=>'block');
beb56299 2011 }
dd72b308
PS
2012 }
2013
2014 /**
2015 * Add html class to block
2016 * @param string $class
2017 * @return void
2018 */
2019 public function add_class($class) {
2020 $this->attributes['class'] .= ' '.$class;
d9c8f425 2021 }
2022}
beb56299 2023
34059565 2024
beb56299 2025/**
2026 * This class represents a target for where a block can go when it is being moved.
2027 *
2028 * This needs to be rendered as a form with the given hidden from fields, and
2029 * clicking anywhere in the form should submit it. The form action should be
2030 * $PAGE->url.
2031 *
2032 * @copyright 2009 Tim Hunt
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2034 * @since Moodle 2.0
2035 */
dd72b308 2036class block_move_target {
beb56299 2037 /**
dd72b308
PS
2038 * Move url
2039 * @var moodle_url
beb56299 2040 */
dd72b308 2041 public $url;
beb56299 2042 /**
dd72b308
PS
2043 * label
2044 * @var string
beb56299 2045 */
dd72b308
PS
2046 public $text;
2047
2048 /**
1a10840e 2049 * Constructor
dd72b308
PS
2050 * @param string $text
2051 * @param moodle_url $url
2052 */
2053 public function __construct($text, moodle_url $url) {
2054 $this->text = $text;
2055 $this->url = $url;
2056 }
beb56299 2057}
d2dbd0c0
SH
2058
2059/**
2060 * Custom menu item
2061 *
2062 * This class is used to represent one item within a custom menu that may or may
2063 * not have children.
2064 *
2065 * @copyright 2010 Sam Hemelryk
2066 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2067 * @since Moodle 2.0
2068 */
2069class custom_menu_item implements renderable {
2070 /**
2071 * The text to show for the item
2072 * @var string
2073 */
2074 protected $text;
2075 /**
2076 * The link to give the icon if it has no children
2077 * @var moodle_url
2078 */
2079 protected $url;
2080 /**
2081 * A title to apply to the item. By default the text
2082 * @var string
2083 */
2084 protected $title;
2085 /**
1a10840e 2086 * A sort order for the item, not necessary if you order things in the CFG var
d2dbd0c0
SH
2087 * @var int
2088 */
2089 protected $sort;
2090 /**
2091 * A reference to the parent for this item or NULL if it is a top level item
2092 * @var custom_menu_item
2093 */
2094 protected $parent;
2095 /**
2096 * A array in which to store children this item has.
2097 * @var array
2098 */
2099 protected $children = array();
2100 /**
2101 * A reference to the sort var of the last child that was added
2102 * @var int
2103 */
2104 protected $lastsort = 0;
2105 /**
2106 * Constructs the new custom menu item
2107 *
2108 * @param string $text
2109 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2110 * @param string $title A title to apply to this item [Optional]
2111 * @param int $sort A sort or to use if we need to sort differently [Optional]
2112 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2113 * belongs to, only if the child has a parent. [Optional]
2114 */
2115 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2116 $this->text = $text;
2117 $this->url = $url;
2118 $this->title = $title;
2119 $this->sort = (int)$sort;
2120 $this->parent = $parent;
2121 }
2122
2123 /**
2124 * Adds a custom menu item as a child of this node given its properties.
2125 *
2126 * @param string $text
2127 * @param moodle_url $url
2128 * @param string $title
2129 * @param int $sort
2130 * @return custom_menu_item
2131 */
2132 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2133 $key = count($this->children);
2134 if (empty($sort)) {
2135 $sort = $this->lastsort + 1;
2136 }
2137 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2138 $this->lastsort = (int)$sort;
2139 return $this->children[$key];
2140 }
2141 /**
2142 * Returns the text for this item
2143 * @return string
2144 */
2145 public function get_text() {
2146 return $this->text;
2147 }
2148 /**
2149 * Returns the url for this item
2150 * @return moodle_url
2151 */
2152 public function get_url() {
2153 return $this->url;
2154 }
2155 /**
2156 * Returns the title for this item
2157 * @return string
2158 */
2159 public function get_title() {
2160 return $this->title;
2161 }
2162 /**
2163 * Sorts and returns the children for this item
2164 * @return array
2165 */
2166 public function get_children() {
2167 $this->sort();
2168 return $this->children;
2169 }
2170 /**
2171 * Gets the sort order for this child
2172 * @return int
2173 */
2174 public function get_sort_order() {
2175 return $this->sort;
2176 }
2177 /**
2178 * Gets the parent this child belong to
2179 * @return custom_menu_item
2180 */
2181 public function get_parent() {
2182 return $this->parent;
2183 }
2184 /**
2185 * Sorts the children this item has
2186 */
2187 public function sort() {
2188 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2189 }
2190 /**
2191 * Returns true if this item has any children
2192 * @return bool
2193 */
2194 public function has_children() {
2195 return (count($this->children) > 0);
2196 }
f3827323
SH
2197
2198 /**
2199 * Sets the text for the node
2200 * @param string $text
2201 */
2202 public function set_text($text) {
2203 $this->text = (string)$text;
2204 }
2205
2206 /**
2207 * Sets the title for the node
2208 * @param string $title
2209 */
2210 public function set_title($title) {
2211 $this->title = (string)$title;
2212 }
2213
2214 /**
2215 * Sets the url for the node
2216 * @param moodle_url $url
2217 */
2218 public function set_url(moodle_url $url) {
2219 $this->url = $url;
2220 }
d2dbd0c0
SH
2221}
2222
2223/**
2224 * Custom menu class
2225 *
2226 * This class is used to operate a custom menu that can be rendered for the page.
2227 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2228 * of custom_menu_item nodes that can be rendered by the core renderer.
2229 *
2230 * To configure the custom menu:
2231 * Settings: Administration > Appearance > Themes > Theme settings
2232 *
2233 * @copyright 2010 Sam Hemelryk
2234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2235 * @since Moodle 2.0
2236 */
2237class custom_menu extends custom_menu_item {
2238 /**
2239 * Creates the custom menu
2240 * @param string $text Sets the text for this custom menu, never gets used and is optional
2241 */
2242 public function __construct($text='base') {
2243 global $CFG;
2244 parent::__construct($text);
12cc75ae
SH
2245 if (!empty($CFG->custommenuitems)) {
2246 $this->override_children(self::convert_text_to_menu_nodes($CFG->custommenuitems));
2247 }
d2dbd0c0
SH
2248 }
2249
2250 /**
2251 * Overrides the children of this custom menu. Useful when getting children
2252 * from $CFG->custommenuitems
2253 */
2254 public function override_children(array $children) {
2255 $this->children = array();
2256 foreach ($children as $child) {
2257 if ($child instanceof custom_menu_item) {
2258 $this->children[] = $child;
2259 }
2260 }
2261 }
2262
2263 /**
2264 * Converts a string into a structured array of custom_menu_items which can
2265 * then be added to a custom menu.
2266 *
2267 * Structure:
2268 * text|url|title
2269 * The number of hyphens at the start determines the depth of the item
2270 *
2271 * Example structure:
2272 * First level first item|http://www.moodle.com/
2273 * -Second level first item|http://www.moodle.com/partners/
2274 * -Second level second item|http://www.moodle.com/hq/
2275 * --Third level first item|http://www.moodle.com/jobs/
2276 * -Second level third item|http://www.moodle.com/development/
2277 * First level second item|http://www.moodle.com/feedback/
2278 * First level third item
4d2ee4c2 2279 *
d2dbd0c0
SH
2280 * @static
2281 * @param string $text
2282 * @return array
2283 */
2284 public static function convert_text_to_menu_nodes($text) {
2285 $lines = explode("\n", $text);
2286 $children = array();
2287 $lastchild = null;
2288 $lastdepth = null;
2289 $lastsort = 0;
2290 foreach ($lines as $line) {
2291 $line = trim($line);
2292 $bits = explode('|', $line ,4); // name|url|title|sort
2293 if (!array_key_exists(0, $bits) || empty($bits[0])) {
2294 // Every item must have a name to be valid
2295 continue;
2296 } else {
2297 $bits[0] = ltrim($bits[0],'-');
2298 }
2299 if (!array_key_exists(1, $bits)) {
2300 // Set the url to null
2301 $bits[1] = null;
2302 } else {
2303 // Make sure the url is a moodle url
a26f25ae 2304 $bits[1] = new moodle_url(trim($bits[1]));
d2dbd0c0
SH
2305 }
2306 if (!array_key_exists(2, $bits)) {
2307 // Set the title to null seeing as there isn't one
2308 $bits[2] = $bits[0];
2309 }
2310 // Set an incremental sort order to keep it simple.
2311 $bits[3] = $lastsort;
2312 $lastsort = $bits[3]+1;
2313 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2314 $depth = strlen($match[1]);
2315 if ($depth < $lastdepth) {
2316 if ($lastdepth > 1) {
2317 $depth = $lastdepth - 1;
2318 $lastchild = $lastchild->get_parent()->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
2319 } else {
2320 $depth = 0;
2321 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2322 $children[] = $lastchild;
2323 }
2324 } else if ($depth > $lastdepth) {
2325 $depth = $lastdepth + 1;
2326 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $bits[3]);
2327 } else {
2328 if ($depth == 0) {
2329 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2330 $children[] = $lastchild;
2331 } else {
2332 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
2333 }
2334 }
2335 } else {
2336 $depth = 0;
2337 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2338 $children[] = $lastchild;
2339 }
2340 $lastdepth = $depth;
2341 }
2342 return $children;
2343 }
2344
2345 /**
2346 * Sorts two custom menu items
2347 *
2348 * This function is designed to be used with the usort method
2349 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2350 *
2351 * @param custom_menu_item $itema
2352 * @param custom_menu_item $itemb
2353 * @return int
2354 */
2355 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2356 $itema = $itema->get_sort_order();
2357 $itemb = $itemb->get_sort_order();
2358 if ($itema == $itemb) {
2359 return 0;
2360 }
2361 return ($itema > $itemb) ? +1 : -1;
2362 }
4d2ee4c2 2363}
2a102b90
SH
2364
2365/**
2366 * Image gallery component
2367 *
2368 * This is the image gallery component that can be used to display several images
2369 * and if JavaScript is enabled uses the gallery-lightbox YUI module to display
2370 * them within a lightbox with appropriate controls and such.
2371 *
2372 * Lib / YUI Module location: lib/gallery/20100601/
2373 *
2374 * @copyright 2010 Sam Hemelryk
2375 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2376 * @since Moodle 2.0
2377 */
2378class image_gallery implements renderable {
2379
2380 /**
2381 * Used to ensure we only initialise the lightbox once... it is shared
2382 * @var bool
2383 */
2384 protected static $jsinit = false;
2385 /**
2386 * An array of images
2387 * @var array
2388 */
2389 public $images = array();
2390 /**
2391 * The grouping to apply in the lightbox
2392 * @var string
2393 */
2394 public $grouping = null;
2395
af7c1e29
SH
2396 /**
2397 * If set to true only the first image is visible.
2398 */
2399 public $displayfirstimageonly = false;
2400
2a102b90
SH
2401 /**
2402 * Constructs an image gallery component
2403 * @param array $images
2404 * @param string $grouping
2405 */
2406 public function __construct(array $images=null, $grouping=null) {
2407 $this->grouping = $grouping;
2408 if (is_array($images)) {
2409 foreach ($images as $image) {
2410 $image = (array)$image;
2411 if (!array_key_exists('imageurl', $image)) {
2412 throw new coding_exception('Image gallery images must specify a url for every image');
2413 }
2414 if (!array_key_exists('thumburl', $image)) {
2415 throw new coding_exception('Image gallery images must specify a url for every image');
2416 }
2417 if (!array_key_exists('title', $image)) {
2418 throw new coding_exception('Image gallery images must specify a title for every image');
2419 }
2420 if (!array_key_exists('alt', $image)) {
2421 $image['alt'] = null;
2422 }
2423 if (!array_key_exists('attributes', $image)) {
2424 $image['attributes'] = null;
2425 }
2426 $this->add_image($image['thumburl'], $image['imageurl'], $image['title'], $image['alt'], $image['attributes']);
2427 }
2428 }
2429 }
2430 /**
2431 * Adds an image to the gallery
2432 *
2433 * @param moodle_url|string $thumburl
2434 * @param moodle_url|string $imageurl
2435 * @param string $title
2436 * @param string $alt
2437 * @param array $attributes
2438 */
2439 public function add_image($thumburl, $imageurl, $title, $alt=null, array $attributes=null) {
2440 $image = new stdClass;
2441 $image->link = array('id'=>'imagelink'.(count($this->images)+1), 'class'=>'imagelink');
2442 $image->thumb = array('id'=>'imagethumb'.(count($this->images)+1), 'class'=>'imagethumb');
2443 if (is_array($attributes)) {
2444 $image->link = $attributes;
2445 }
2446 $image->link['href'] = new moodle_url($imageurl);
2447 $image->link['title'] = $title;
2448 $image->link['rel'] = 'lightbox';
2449 if ($this->grouping !== null) {
2450 $image->link['rel'] .= "[{$this->grouping}]";
2451 }
fb2fb46e 2452
2a102b90
SH
2453 $image->thumb['src'] = new moodle_url($thumburl);
2454 $image->thumb['alt'] = $alt;
fb2fb46e 2455
2a102b90
SH
2456 $this->images[] = $image;
2457 }
621b4d08 2458}