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