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