MDL-39814 html_writer: Remove superfluous new lines from html_writer::alist
[moodle.git] / lib / outputcomponents.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Classes representing HTML elements, used by $OUTPUT methods
19  *
20  * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21  * for an overview.
22  *
23  * @package core
24  * @category output
25  * @copyright 2009 Tim Hunt
26  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27  */
29 defined('MOODLE_INTERNAL') || die();
31 /**
32  * Interface marking other classes as suitable for renderer_base::render()
33  *
34  * @copyright 2010 Petr Skoda (skodak) info@skodak.org
35  * @package core
36  * @category output
37  */
38 interface renderable {
39     // intentionally empty
40 }
42 /**
43  * Data structure representing a file picker.
44  *
45  * @copyright 2010 Dongsheng Cai
46  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47  * @since Moodle 2.0
48  * @package core
49  * @category output
50  */
51 class file_picker implements renderable {
53     /**
54      * @var stdClass An object containing options for the file picker
55      */
56     public $options;
58     /**
59      * Constructs a file picker object.
60      *
61      * The following are possible options for the filepicker:
62      *    - accepted_types  (*)
63      *    - return_types    (FILE_INTERNAL)
64      *    - env             (filepicker)
65      *    - client_id       (uniqid)
66      *    - itemid          (0)
67      *    - maxbytes        (-1)
68      *    - maxfiles        (1)
69      *    - buttonname      (false)
70      *
71      * @param stdClass $options An object containing options for the file picker.
72      */
73     public function __construct(stdClass $options) {
74         global $CFG, $USER, $PAGE;
75         require_once($CFG->dirroot. '/repository/lib.php');
76         $defaults = array(
77             'accepted_types'=>'*',
78             'return_types'=>FILE_INTERNAL,
79             'env' => 'filepicker',
80             'client_id' => uniqid(),
81             'itemid' => 0,
82             'maxbytes'=>-1,
83             'maxfiles'=>1,
84             'buttonname'=>false
85         );
86         foreach ($defaults as $key=>$value) {
87             if (empty($options->$key)) {
88                 $options->$key = $value;
89             }
90         }
92         $options->currentfile = '';
93         if (!empty($options->itemid)) {
94             $fs = get_file_storage();
95             $usercontext = context_user::instance($USER->id);
96             if (empty($options->filename)) {
97                 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
98                     $file = reset($files);
99                 }
100             } else {
101                 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
102             }
103             if (!empty($file)) {
104                 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
105             }
106         }
108         // initilise options, getting files in root path
109         $this->options = initialise_filepicker($options);
111         // copying other options
112         foreach ($options as $name=>$value) {
113             if (!isset($this->options->$name)) {
114                 $this->options->$name = $value;
115             }
116         }
117     }
120 /**
121  * Data structure representing a user picture.
122  *
123  * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
124  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
125  * @since Modle 2.0
126  * @package core
127  * @category output
128  */
129 class user_picture implements renderable {
130     /**
131      * @var array List of mandatory fields in user record here. (do not include
132      * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
133      */
134     protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic',
135             'middlename', 'alternatename', 'imagealt', 'email');
137     /**
138      * @var stdClass A user object with at least fields all columns specified
139      * in $fields array constant set.
140      */
141     public $user;
143     /**
144      * @var int The course id. Used when constructing the link to the user's
145      * profile, page course id used if not specified.
146      */
147     public $courseid;
149     /**
150      * @var bool Add course profile link to image
151      */
152     public $link = true;
154     /**
155      * @var int Size in pixels. Special values are (true/1 = 100px) and
156      * (false/0 = 35px)
157      * for backward compatibility.
158      */
159     public $size = 35;
161     /**
162      * @var bool Add non-blank alt-text to the image.
163      * Default true, set to false when image alt just duplicates text in screenreaders.
164      */
165     public $alttext = true;
167     /**
168      * @var bool Whether or not to open the link in a popup window.
169      */
170     public $popup = false;
172     /**
173      * @var string Image class attribute
174      */
175     public $class = 'userpicture';
177     /**
178      * User picture constructor.
179      *
180      * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
181      *                 It is recommended to add also contextid of the user for performance reasons.
182      */
183     public function __construct(stdClass $user) {
184         global $DB;
186         if (empty($user->id)) {
187             throw new coding_exception('User id is required when printing user avatar image.');
188         }
190         // only touch the DB if we are missing data and complain loudly...
191         $needrec = false;
192         foreach (self::$fields as $field) {
193             if (!array_key_exists($field, $user)) {
194                 $needrec = true;
195                 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
196                           .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
197                 break;
198             }
199         }
201         if ($needrec) {
202             $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
203         } else {
204             $this->user = clone($user);
205         }
206     }
208     /**
209      * Returns a list of required user fields, useful when fetching required user info from db.
210      *
211      * In some cases we have to fetch the user data together with some other information,
212      * the idalias is useful there because the id would otherwise override the main
213      * id of the result record. Please note it has to be converted back to id before rendering.
214      *
215      * @param string $tableprefix name of database table prefix in query
216      * @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)
217      * @param string $idalias alias of id field
218      * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
219      * @return string
220      */
221     public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
222         if (!$tableprefix and !$extrafields and !$idalias) {
223             return implode(',', self::$fields);
224         }
225         if ($tableprefix) {
226             $tableprefix .= '.';
227         }
228         foreach (self::$fields as $field) {
229             if ($field === 'id' and $idalias and $idalias !== 'id') {
230                 $fields[$field] = "$tableprefix$field AS $idalias";
231             } else {
232                 if ($fieldprefix and $field !== 'id') {
233                     $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
234                 } else {
235                     $fields[$field] = "$tableprefix$field";
236                 }
237             }
238         }
239         // add extra fields if not already there
240         if ($extrafields) {
241             foreach ($extrafields as $e) {
242                 if ($e === 'id' or isset($fields[$e])) {
243                     continue;
244                 }
245                 if ($fieldprefix) {
246                     $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
247                 } else {
248                     $fields[$e] = "$tableprefix$e";
249                 }
250             }
251         }
252         return implode(',', $fields);
253     }
255     /**
256      * Extract the aliased user fields from a given record
257      *
258      * Given a record that was previously obtained using {@link self::fields()} with aliases,
259      * this method extracts user related unaliased fields.
260      *
261      * @param stdClass $record containing user picture fields
262      * @param array $extrafields extra fields included in the $record
263      * @param string $idalias alias of the id field
264      * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
265      * @return stdClass object with unaliased user fields
266      */
267     public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
269         if (empty($idalias)) {
270             $idalias = 'id';
271         }
273         $return = new stdClass();
275         foreach (self::$fields as $field) {
276             if ($field === 'id') {
277                 if (property_exists($record, $idalias)) {
278                     $return->id = $record->{$idalias};
279                 }
280             } else {
281                 if (property_exists($record, $fieldprefix.$field)) {
282                     $return->{$field} = $record->{$fieldprefix.$field};
283                 }
284             }
285         }
286         // add extra fields if not already there
287         if ($extrafields) {
288             foreach ($extrafields as $e) {
289                 if ($e === 'id' or property_exists($return, $e)) {
290                     continue;
291                 }
292                 $return->{$e} = $record->{$fieldprefix.$e};
293             }
294         }
296         return $return;
297     }
299     /**
300      * Works out the URL for the users picture.
301      *
302      * This method is recommended as it avoids costly redirects of user pictures
303      * if requests are made for non-existent files etc.
304      *
305      * @param moodle_page $page
306      * @param renderer_base $renderer
307      * @return moodle_url
308      */
309     public function get_url(moodle_page $page, renderer_base $renderer = null) {
310         global $CFG;
312         if (is_null($renderer)) {
313             $renderer = $page->get_renderer('core');
314         }
316         // Sort out the filename and size. Size is only required for the gravatar
317         // implementation presently.
318         if (empty($this->size)) {
319             $filename = 'f2';
320             $size = 35;
321         } else if ($this->size === true or $this->size == 1) {
322             $filename = 'f1';
323             $size = 100;
324         } else if ($this->size > 100) {
325             $filename = 'f3';
326             $size = (int)$this->size;
327         } else if ($this->size >= 50) {
328             $filename = 'f1';
329             $size = (int)$this->size;
330         } else {
331             $filename = 'f2';
332             $size = (int)$this->size;
333         }
335         $defaulturl = $renderer->pix_url('u/'.$filename); // default image
337         if ((!empty($CFG->forcelogin) and !isloggedin()) ||
338             (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
339             // Protect images if login required and not logged in;
340             // also if login is required for profile images and is not logged in or guest
341             // do not use require_login() because it is expensive and not suitable here anyway.
342             return $defaulturl;
343         }
345         // First try to detect deleted users - but do not read from database for performance reasons!
346         if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
347             // All deleted users should have email replaced by md5 hash,
348             // all active users are expected to have valid email.
349             return $defaulturl;
350         }
352         // Did the user upload a picture?
353         if ($this->user->picture > 0) {
354             if (!empty($this->user->contextid)) {
355                 $contextid = $this->user->contextid;
356             } else {
357                 $context = context_user::instance($this->user->id, IGNORE_MISSING);
358                 if (!$context) {
359                     // This must be an incorrectly deleted user, all other users have context.
360                     return $defaulturl;
361                 }
362                 $contextid = $context->id;
363             }
365             $path = '/';
366             if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
367                 // We append the theme name to the file path if we have it so that
368                 // in the circumstance that the profile picture is not available
369                 // when the user actually requests it they still get the profile
370                 // picture for the correct theme.
371                 $path .= $page->theme->name.'/';
372             }
373             // Set the image URL to the URL for the uploaded file and return.
374             $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
375             $url->param('rev', $this->user->picture);
376             return $url;
377         }
379         if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
380             // Normalise the size variable to acceptable bounds
381             if ($size < 1 || $size > 512) {
382                 $size = 35;
383             }
384             // Hash the users email address
385             $md5 = md5(strtolower(trim($this->user->email)));
386             // Build a gravatar URL with what we know.
388             // Find the best default image URL we can (MDL-35669)
389             if (empty($CFG->gravatardefaulturl)) {
390                 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
391                 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
392                     $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
393                 } else {
394                     $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
395                 }
396             } else {
397                 $gravatardefault = $CFG->gravatardefaulturl;
398             }
400             // If the currently requested page is https then we'll return an
401             // https gravatar page.
402             if (strpos($CFG->httpswwwroot, 'https:') === 0) {
403                 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
404                 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
405             } else {
406                 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
407             }
408         }
410         return $defaulturl;
411     }
414 /**
415  * Data structure representing a help icon.
416  *
417  * @copyright 2010 Petr Skoda (info@skodak.org)
418  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419  * @since Moodle 2.0
420  * @package core
421  * @category output
422  */
423 class help_icon implements renderable {
425     /**
426      * @var string lang pack identifier (without the "_help" suffix),
427      * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
428      * must exist.
429      */
430     public $identifier;
432     /**
433      * @var string Component name, the same as in get_string()
434      */
435     public $component;
437     /**
438      * @var string Extra descriptive text next to the icon
439      */
440     public $linktext = null;
442     /**
443      * Constructor
444      *
445      * @param string $identifier string for help page title,
446      *  string with _help suffix is used for the actual help text.
447      *  string with _link suffix is used to create a link to further info (if it exists)
448      * @param string $component
449      */
450     public function __construct($identifier, $component) {
451         $this->identifier = $identifier;
452         $this->component  = $component;
453     }
455     /**
456      * Verifies that both help strings exists, shows debug warnings if not
457      */
458     public function diag_strings() {
459         $sm = get_string_manager();
460         if (!$sm->string_exists($this->identifier, $this->component)) {
461             debugging("Help title string does not exist: [$this->identifier, $this->component]");
462         }
463         if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
464             debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
465         }
466     }
470 /**
471  * Data structure representing an icon.
472  *
473  * @copyright 2010 Petr Skoda
474  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
475  * @since Moodle 2.0
476  * @package core
477  * @category output
478  */
479 class pix_icon implements renderable {
481     /**
482      * @var string The icon name
483      */
484     var $pix;
486     /**
487      * @var string The component the icon belongs to.
488      */
489     var $component;
491     /**
492      * @var array An array of attributes to use on the icon
493      */
494     var $attributes = array();
496     /**
497      * Constructor
498      *
499      * @param string $pix short icon name
500      * @param string $alt The alt text to use for the icon
501      * @param string $component component name
502      * @param array $attributes html attributes
503      */
504     public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
505         $this->pix        = $pix;
506         $this->component  = $component;
507         $this->attributes = (array)$attributes;
509         $this->attributes['alt'] = $alt;
510         if (empty($this->attributes['class'])) {
511             $this->attributes['class'] = 'smallicon';
512         }
513         if (!isset($this->attributes['title'])) {
514             $this->attributes['title'] = $this->attributes['alt'];
515         } else if (empty($this->attributes['title'])) {
516             // Remove the title attribute if empty, we probably want to use the parent node's title
517             // and some browsers might overwrite it with an empty title.
518             unset($this->attributes['title']);
519         }
520     }
523 /**
524  * Data structure representing an emoticon image
525  *
526  * @copyright 2010 David Mudrak
527  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
528  * @since Moodle 2.0
529  * @package core
530  * @category output
531  */
532 class pix_emoticon extends pix_icon implements renderable {
534     /**
535      * Constructor
536      * @param string $pix short icon name
537      * @param string $alt alternative text
538      * @param string $component emoticon image provider
539      * @param array $attributes explicit HTML attributes
540      */
541     public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
542         if (empty($attributes['class'])) {
543             $attributes['class'] = 'emoticon';
544         }
545         parent::__construct($pix, $alt, $component, $attributes);
546     }
549 /**
550  * Data structure representing a simple form with only one button.
551  *
552  * @copyright 2009 Petr Skoda
553  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
554  * @since Moodle 2.0
555  * @package core
556  * @category output
557  */
558 class single_button implements renderable {
560     /**
561      * @var moodle_url Target url
562      */
563     var $url;
565     /**
566      * @var string Button label
567      */
568     var $label;
570     /**
571      * @var string Form submit method post or get
572      */
573     var $method = 'post';
575     /**
576      * @var string Wrapping div class
577      */
578     var $class = 'singlebutton';
580     /**
581      * @var bool True if button disabled, false if normal
582      */
583     var $disabled = false;
585     /**
586      * @var string Button tooltip
587      */
588     var $tooltip = null;
590     /**
591      * @var string Form id
592      */
593     var $formid;
595     /**
596      * @var array List of attached actions
597      */
598     var $actions = array();
600     /**
601      * Constructor
602      * @param moodle_url $url
603      * @param string $label button text
604      * @param string $method get or post submit method
605      */
606     public function __construct(moodle_url $url, $label, $method='post') {
607         $this->url    = clone($url);
608         $this->label  = $label;
609         $this->method = $method;
610     }
612     /**
613      * Shortcut for adding a JS confirm dialog when the button is clicked.
614      * The message must be a yes/no question.
615      *
616      * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
617      */
618     public function add_confirm_action($confirmmessage) {
619         $this->add_action(new confirm_action($confirmmessage));
620     }
622     /**
623      * Add action to the button.
624      * @param component_action $action
625      */
626     public function add_action(component_action $action) {
627         $this->actions[] = $action;
628     }
632 /**
633  * Simple form with just one select field that gets submitted automatically.
634  *
635  * If JS not enabled small go button is printed too.
636  *
637  * @copyright 2009 Petr Skoda
638  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
639  * @since Moodle 2.0
640  * @package core
641  * @category output
642  */
643 class single_select implements renderable {
645     /**
646      * @var moodle_url Target url - includes hidden fields
647      */
648     var $url;
650     /**
651      * @var string Name of the select element.
652      */
653     var $name;
655     /**
656      * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
657      *     it is also possible to specify optgroup as complex label array ex.:
658      *         array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
659      *         array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
660      */
661     var $options;
663     /**
664      * @var string Selected option
665      */
666     var $selected;
668     /**
669      * @var array Nothing selected
670      */
671     var $nothing;
673     /**
674      * @var array Extra select field attributes
675      */
676     var $attributes = array();
678     /**
679      * @var string Button label
680      */
681     var $label = '';
683     /**
684      * @var array Button label's attributes
685      */
686     var $labelattributes = array();
688     /**
689      * @var string Form submit method post or get
690      */
691     var $method = 'get';
693     /**
694      * @var string Wrapping div class
695      */
696     var $class = 'singleselect';
698     /**
699      * @var bool True if button disabled, false if normal
700      */
701     var $disabled = false;
703     /**
704      * @var string Button tooltip
705      */
706     var $tooltip = null;
708     /**
709      * @var string Form id
710      */
711     var $formid = null;
713     /**
714      * @var array List of attached actions
715      */
716     var $helpicon = null;
718     /**
719      * Constructor
720      * @param moodle_url $url form action target, includes hidden fields
721      * @param string $name name of selection field - the changing parameter in url
722      * @param array $options list of options
723      * @param string $selected selected element
724      * @param array $nothing
725      * @param string $formid
726      */
727     public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
728         $this->url      = $url;
729         $this->name     = $name;
730         $this->options  = $options;
731         $this->selected = $selected;
732         $this->nothing  = $nothing;
733         $this->formid   = $formid;
734     }
736     /**
737      * Shortcut for adding a JS confirm dialog when the button is clicked.
738      * The message must be a yes/no question.
739      *
740      * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
741      */
742     public function add_confirm_action($confirmmessage) {
743         $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
744     }
746     /**
747      * Add action to the button.
748      *
749      * @param component_action $action
750      */
751     public function add_action(component_action $action) {
752         $this->actions[] = $action;
753     }
755     /**
756      * Adds help icon.
757      *
758      * @deprecated since Moodle 2.0
759      */
760     public function set_old_help_icon($helppage, $title, $component = 'moodle') {
761         throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
762     }
764     /**
765      * Adds help icon.
766      *
767      * @param string $identifier The keyword that defines a help page
768      * @param string $component
769      */
770     public function set_help_icon($identifier, $component = 'moodle') {
771         $this->helpicon = new help_icon($identifier, $component);
772     }
774     /**
775      * Sets select's label
776      *
777      * @param string $label
778      * @param array $attributes (optional)
779      */
780     public function set_label($label, $attributes = array()) {
781         $this->label = $label;
782         $this->labelattributes = $attributes;
784     }
787 /**
788  * Simple URL selection widget description.
789  *
790  * @copyright 2009 Petr Skoda
791  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
792  * @since Moodle 2.0
793  * @package core
794  * @category output
795  */
796 class url_select implements renderable {
797     /**
798      * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
799      *     it is also possible to specify optgroup as complex label array ex.:
800      *         array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
801      *         array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
802      */
803     var $urls;
805     /**
806      * @var string Selected option
807      */
808     var $selected;
810     /**
811      * @var array Nothing selected
812      */
813     var $nothing;
815     /**
816      * @var array Extra select field attributes
817      */
818     var $attributes = array();
820     /**
821      * @var string Button label
822      */
823     var $label = '';
825     /**
826      * @var array Button label's attributes
827      */
828     var $labelattributes = array();
830     /**
831      * @var string Wrapping div class
832      */
833     var $class = 'urlselect';
835     /**
836      * @var bool True if button disabled, false if normal
837      */
838     var $disabled = false;
840     /**
841      * @var string Button tooltip
842      */
843     var $tooltip = null;
845     /**
846      * @var string Form id
847      */
848     var $formid = null;
850     /**
851      * @var array List of attached actions
852      */
853     var $helpicon = null;
855     /**
856      * @var string If set, makes button visible with given name for button
857      */
858     var $showbutton = null;
860     /**
861      * Constructor
862      * @param array $urls list of options
863      * @param string $selected selected element
864      * @param array $nothing
865      * @param string $formid
866      * @param string $showbutton Set to text of button if it should be visible
867      *   or null if it should be hidden (hidden version always has text 'go')
868      */
869     public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
870         $this->urls       = $urls;
871         $this->selected   = $selected;
872         $this->nothing    = $nothing;
873         $this->formid     = $formid;
874         $this->showbutton = $showbutton;
875     }
877     /**
878      * Adds help icon.
879      *
880      * @deprecated since Moodle 2.0
881      */
882     public function set_old_help_icon($helppage, $title, $component = 'moodle') {
883         throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
884     }
886     /**
887      * Adds help icon.
888      *
889      * @param string $identifier The keyword that defines a help page
890      * @param string $component
891      */
892     public function set_help_icon($identifier, $component = 'moodle') {
893         $this->helpicon = new help_icon($identifier, $component);
894     }
896     /**
897      * Sets select's label
898      *
899      * @param string $label
900      * @param array $attributes (optional)
901      */
902     public function set_label($label, $attributes = array()) {
903         $this->label = $label;
904         $this->labelattributes = $attributes;
905     }
908 /**
909  * Data structure describing html link with special action attached.
910  *
911  * @copyright 2010 Petr Skoda
912  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
913  * @since Moodle 2.0
914  * @package core
915  * @category output
916  */
917 class action_link implements renderable {
919     /**
920      * @var moodle_url Href url
921      */
922     var $url;
924     /**
925      * @var string Link text HTML fragment
926      */
927     var $text;
929     /**
930      * @var array HTML attributes
931      */
932     var $attributes;
934     /**
935      * @var array List of actions attached to link
936      */
937     var $actions;
939     /**
940      * Constructor
941      * @param moodle_url $url
942      * @param string $text HTML fragment
943      * @param component_action $action
944      * @param array $attributes associative array of html link attributes + disabled
945      */
946     public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
947         $this->url = clone($url);
948         $this->text = $text;
949         $this->attributes = (array)$attributes;
950         if ($action) {
951             $this->add_action($action);
952         }
953     }
955     /**
956      * Add action to the link.
957      *
958      * @param component_action $action
959      */
960     public function add_action(component_action $action) {
961         $this->actions[] = $action;
962     }
964     /**
965      * Adds a CSS class to this action link object
966      * @param string $class
967      */
968     public function add_class($class) {
969         if (empty($this->attributes['class'])) {
970             $this->attributes['class'] = $class;
971         } else {
972             $this->attributes['class'] .= ' ' . $class;
973         }
974     }
977 /**
978  * Simple html output class
979  *
980  * @copyright 2009 Tim Hunt, 2010 Petr Skoda
981  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
982  * @since Moodle 2.0
983  * @package core
984  * @category output
985  */
986 class html_writer {
988     /**
989      * Outputs a tag with attributes and contents
990      *
991      * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
992      * @param string $contents What goes between the opening and closing tags
993      * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
994      * @return string HTML fragment
995      */
996     public static function tag($tagname, $contents, array $attributes = null) {
997         return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
998     }
1000     /**
1001      * Outputs an opening tag with attributes
1002      *
1003      * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1004      * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1005      * @return string HTML fragment
1006      */
1007     public static function start_tag($tagname, array $attributes = null) {
1008         return '<' . $tagname . self::attributes($attributes) . '>';
1009     }
1011     /**
1012      * Outputs a closing tag
1013      *
1014      * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1015      * @return string HTML fragment
1016      */
1017     public static function end_tag($tagname) {
1018         return '</' . $tagname . '>';
1019     }
1021     /**
1022      * Outputs an empty tag with attributes
1023      *
1024      * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1025      * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1026      * @return string HTML fragment
1027      */
1028     public static function empty_tag($tagname, array $attributes = null) {
1029         return '<' . $tagname . self::attributes($attributes) . ' />';
1030     }
1032     /**
1033      * Outputs a tag, but only if the contents are not empty
1034      *
1035      * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1036      * @param string $contents What goes between the opening and closing tags
1037      * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1038      * @return string HTML fragment
1039      */
1040     public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1041         if ($contents === '' || is_null($contents)) {
1042             return '';
1043         }
1044         return self::tag($tagname, $contents, $attributes);
1045     }
1047     /**
1048      * Outputs a HTML attribute and value
1049      *
1050      * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1051      * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1052      * @return string HTML fragment
1053      */
1054     public static function attribute($name, $value) {
1055         if ($value instanceof moodle_url) {
1056             return ' ' . $name . '="' . $value->out() . '"';
1057         }
1059         // special case, we do not want these in output
1060         if ($value === null) {
1061             return '';
1062         }
1064         // no sloppy trimming here!
1065         return ' ' . $name . '="' . s($value) . '"';
1066     }
1068     /**
1069      * Outputs a list of HTML attributes and values
1070      *
1071      * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1072      *       The values will be escaped with {@link s()}
1073      * @return string HTML fragment
1074      */
1075     public static function attributes(array $attributes = null) {
1076         $attributes = (array)$attributes;
1077         $output = '';
1078         foreach ($attributes as $name => $value) {
1079             $output .= self::attribute($name, $value);
1080         }
1081         return $output;
1082     }
1084     /**
1085      * Generates random html element id.
1086      *
1087      * @staticvar int $counter
1088      * @staticvar type $uniq
1089      * @param string $base A string fragment that will be included in the random ID.
1090      * @return string A unique ID
1091      */
1092     public static function random_id($base='random') {
1093         static $counter = 0;
1094         static $uniq;
1096         if (!isset($uniq)) {
1097             $uniq = uniqid();
1098         }
1100         $counter++;
1101         return $base.$uniq.$counter;
1102     }
1104     /**
1105      * Generates a simple html link
1106      *
1107      * @param string|moodle_url $url The URL
1108      * @param string $text The text
1109      * @param array $attributes HTML attributes
1110      * @return string HTML fragment
1111      */
1112     public static function link($url, $text, array $attributes = null) {
1113         $attributes = (array)$attributes;
1114         $attributes['href']  = $url;
1115         return self::tag('a', $text, $attributes);
1116     }
1118     /**
1119      * Generates a simple checkbox with optional label
1120      *
1121      * @param string $name The name of the checkbox
1122      * @param string $value The value of the checkbox
1123      * @param bool $checked Whether the checkbox is checked
1124      * @param string $label The label for the checkbox
1125      * @param array $attributes Any attributes to apply to the checkbox
1126      * @return string html fragment
1127      */
1128     public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1129         $attributes = (array)$attributes;
1130         $output = '';
1132         if ($label !== '' and !is_null($label)) {
1133             if (empty($attributes['id'])) {
1134                 $attributes['id'] = self::random_id('checkbox_');
1135             }
1136         }
1137         $attributes['type']    = 'checkbox';
1138         $attributes['value']   = $value;
1139         $attributes['name']    = $name;
1140         $attributes['checked'] = $checked ? 'checked' : null;
1142         $output .= self::empty_tag('input', $attributes);
1144         if ($label !== '' and !is_null($label)) {
1145             $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1146         }
1148         return $output;
1149     }
1151     /**
1152      * Generates a simple select yes/no form field
1153      *
1154      * @param string $name name of select element
1155      * @param bool $selected
1156      * @param array $attributes - html select element attributes
1157      * @return string HTML fragment
1158      */
1159     public static function select_yes_no($name, $selected=true, array $attributes = null) {
1160         $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1161         return self::select($options, $name, $selected, null, $attributes);
1162     }
1164     /**
1165      * Generates a simple select form field
1166      *
1167      * @param array $options associative array value=>label ex.:
1168      *                array(1=>'One, 2=>Two)
1169      *              it is also possible to specify optgroup as complex label array ex.:
1170      *                array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1171      *                array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1172      * @param string $name name of select element
1173      * @param string|array $selected value or array of values depending on multiple attribute
1174      * @param array|bool $nothing add nothing selected option, or false of not added
1175      * @param array $attributes html select element attributes
1176      * @return string HTML fragment
1177      */
1178     public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1179         $attributes = (array)$attributes;
1180         if (is_array($nothing)) {
1181             foreach ($nothing as $k=>$v) {
1182                 if ($v === 'choose' or $v === 'choosedots') {
1183                     $nothing[$k] = get_string('choosedots');
1184                 }
1185             }
1186             $options = $nothing + $options; // keep keys, do not override
1188         } else if (is_string($nothing) and $nothing !== '') {
1189             // BC
1190             $options = array(''=>$nothing) + $options;
1191         }
1193         // we may accept more values if multiple attribute specified
1194         $selected = (array)$selected;
1195         foreach ($selected as $k=>$v) {
1196             $selected[$k] = (string)$v;
1197         }
1199         if (!isset($attributes['id'])) {
1200             $id = 'menu'.$name;
1201             // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1202             $id = str_replace('[', '', $id);
1203             $id = str_replace(']', '', $id);
1204             $attributes['id'] = $id;
1205         }
1207         if (!isset($attributes['class'])) {
1208             $class = 'menu'.$name;
1209             // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1210             $class = str_replace('[', '', $class);
1211             $class = str_replace(']', '', $class);
1212             $attributes['class'] = $class;
1213         }
1214         $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1216         $attributes['name'] = $name;
1218         if (!empty($attributes['disabled'])) {
1219             $attributes['disabled'] = 'disabled';
1220         } else {
1221             unset($attributes['disabled']);
1222         }
1224         $output = '';
1225         foreach ($options as $value=>$label) {
1226             if (is_array($label)) {
1227                 // ignore key, it just has to be unique
1228                 $output .= self::select_optgroup(key($label), current($label), $selected);
1229             } else {
1230                 $output .= self::select_option($label, $value, $selected);
1231             }
1232         }
1233         return self::tag('select', $output, $attributes);
1234     }
1236     /**
1237      * Returns HTML to display a select box option.
1238      *
1239      * @param string $label The label to display as the option.
1240      * @param string|int $value The value the option represents
1241      * @param array $selected An array of selected options
1242      * @return string HTML fragment
1243      */
1244     private static function select_option($label, $value, array $selected) {
1245         $attributes = array();
1246         $value = (string)$value;
1247         if (in_array($value, $selected, true)) {
1248             $attributes['selected'] = 'selected';
1249         }
1250         $attributes['value'] = $value;
1251         return self::tag('option', $label, $attributes);
1252     }
1254     /**
1255      * Returns HTML to display a select box option group.
1256      *
1257      * @param string $groupname The label to use for the group
1258      * @param array $options The options in the group
1259      * @param array $selected An array of selected values.
1260      * @return string HTML fragment.
1261      */
1262     private static function select_optgroup($groupname, $options, array $selected) {
1263         if (empty($options)) {
1264             return '';
1265         }
1266         $attributes = array('label'=>$groupname);
1267         $output = '';
1268         foreach ($options as $value=>$label) {
1269             $output .= self::select_option($label, $value, $selected);
1270         }
1271         return self::tag('optgroup', $output, $attributes);
1272     }
1274     /**
1275      * This is a shortcut for making an hour selector menu.
1276      *
1277      * @param string $type The type of selector (years, months, days, hours, minutes)
1278      * @param string $name fieldname
1279      * @param int $currenttime A default timestamp in GMT
1280      * @param int $step minute spacing
1281      * @param array $attributes - html select element attributes
1282      * @return HTML fragment
1283      */
1284     public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1285         if (!$currenttime) {
1286             $currenttime = time();
1287         }
1288         $currentdate = usergetdate($currenttime);
1289         $userdatetype = $type;
1290         $timeunits = array();
1292         switch ($type) {
1293             case 'years':
1294                 for ($i=1970; $i<=2020; $i++) {
1295                     $timeunits[$i] = $i;
1296                 }
1297                 $userdatetype = 'year';
1298                 break;
1299             case 'months':
1300                 for ($i=1; $i<=12; $i++) {
1301                     $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1302                 }
1303                 $userdatetype = 'month';
1304                 $currentdate['month'] = (int)$currentdate['mon'];
1305                 break;
1306             case 'days':
1307                 for ($i=1; $i<=31; $i++) {
1308                     $timeunits[$i] = $i;
1309                 }
1310                 $userdatetype = 'mday';
1311                 break;
1312             case 'hours':
1313                 for ($i=0; $i<=23; $i++) {
1314                     $timeunits[$i] = sprintf("%02d",$i);
1315                 }
1316                 break;
1317             case 'minutes':
1318                 if ($step != 1) {
1319                     $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1320                 }
1322                 for ($i=0; $i<=59; $i+=$step) {
1323                     $timeunits[$i] = sprintf("%02d",$i);
1324                 }
1325                 break;
1326             default:
1327                 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1328         }
1330         if (empty($attributes['id'])) {
1331             $attributes['id'] = self::random_id('ts_');
1332         }
1333         $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1334         $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1336         return $label.$timerselector;
1337     }
1339     /**
1340      * Shortcut for quick making of lists
1341      *
1342      * Note: 'list' is a reserved keyword ;-)
1343      *
1344      * @param array $items
1345      * @param array $attributes
1346      * @param string $tag ul or ol
1347      * @return string
1348      */
1349     public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1350         $output = html_writer::start_tag($tag, $attributes)."\n";
1351         foreach ($items as $item) {
1352             $output .= html_writer::tag('li', $item)."\n";
1353         }
1354         $output .= html_writer::end_tag($tag);
1355         return $output;
1356     }
1358     /**
1359      * Returns hidden input fields created from url parameters.
1360      *
1361      * @param moodle_url $url
1362      * @param array $exclude list of excluded parameters
1363      * @return string HTML fragment
1364      */
1365     public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1366         $exclude = (array)$exclude;
1367         $params = $url->params();
1368         foreach ($exclude as $key) {
1369             unset($params[$key]);
1370         }
1372         $output = '';
1373         foreach ($params as $key => $value) {
1374             $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1375             $output .= self::empty_tag('input', $attributes)."\n";
1376         }
1377         return $output;
1378     }
1380     /**
1381      * Generate a script tag containing the the specified code.
1382      *
1383      * @param string $jscode the JavaScript code
1384      * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1385      * @return string HTML, the code wrapped in <script> tags.
1386      */
1387     public static function script($jscode, $url=null) {
1388         if ($jscode) {
1389             $attributes = array('type'=>'text/javascript');
1390             return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1392         } else if ($url) {
1393             $attributes = array('type'=>'text/javascript', 'src'=>$url);
1394             return self::tag('script', '', $attributes) . "\n";
1396         } else {
1397             return '';
1398         }
1399     }
1401     /**
1402      * Renders HTML table
1403      *
1404      * This method may modify the passed instance by adding some default properties if they are not set yet.
1405      * If this is not what you want, you should make a full clone of your data before passing them to this
1406      * method. In most cases this is not an issue at all so we do not clone by default for performance
1407      * and memory consumption reasons.
1408      *
1409      * @param html_table $table data to be rendered
1410      * @return string HTML code
1411      */
1412     public static function table(html_table $table) {
1413         // prepare table data and populate missing properties with reasonable defaults
1414         if (!empty($table->align)) {
1415             foreach ($table->align as $key => $aa) {
1416                 if ($aa) {
1417                     $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';';  // Fix for RTL languages
1418                 } else {
1419                     $table->align[$key] = null;
1420                 }
1421             }
1422         }
1423         if (!empty($table->size)) {
1424             foreach ($table->size as $key => $ss) {
1425                 if ($ss) {
1426                     $table->size[$key] = 'width:'. $ss .';';
1427                 } else {
1428                     $table->size[$key] = null;
1429                 }
1430             }
1431         }
1432         if (!empty($table->wrap)) {
1433             foreach ($table->wrap as $key => $ww) {
1434                 if ($ww) {
1435                     $table->wrap[$key] = 'white-space:nowrap;';
1436                 } else {
1437                     $table->wrap[$key] = '';
1438                 }
1439             }
1440         }
1441         if (!empty($table->head)) {
1442             foreach ($table->head as $key => $val) {
1443                 if (!isset($table->align[$key])) {
1444                     $table->align[$key] = null;
1445                 }
1446                 if (!isset($table->size[$key])) {
1447                     $table->size[$key] = null;
1448                 }
1449                 if (!isset($table->wrap[$key])) {
1450                     $table->wrap[$key] = null;
1451                 }
1453             }
1454         }
1455         if (empty($table->attributes['class'])) {
1456             $table->attributes['class'] = 'generaltable';
1457         }
1458         if (!empty($table->tablealign)) {
1459             $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1460         }
1462         // explicitly assigned properties override those defined via $table->attributes
1463         $table->attributes['class'] = trim($table->attributes['class']);
1464         $attributes = array_merge($table->attributes, array(
1465                 'id'            => $table->id,
1466                 'width'         => $table->width,
1467                 'summary'       => $table->summary,
1468                 'cellpadding'   => $table->cellpadding,
1469                 'cellspacing'   => $table->cellspacing,
1470             ));
1471         $output = html_writer::start_tag('table', $attributes) . "\n";
1473         $countcols = 0;
1475         if (!empty($table->head)) {
1476             $countcols = count($table->head);
1478             $output .= html_writer::start_tag('thead', array()) . "\n";
1479             $output .= html_writer::start_tag('tr', array()) . "\n";
1480             $keys = array_keys($table->head);
1481             $lastkey = end($keys);
1483             foreach ($table->head as $key => $heading) {
1484                 // Convert plain string headings into html_table_cell objects
1485                 if (!($heading instanceof html_table_cell)) {
1486                     $headingtext = $heading;
1487                     $heading = new html_table_cell();
1488                     $heading->text = $headingtext;
1489                     $heading->header = true;
1490                 }
1492                 if ($heading->header !== false) {
1493                     $heading->header = true;
1494                 }
1496                 if ($heading->header && empty($heading->scope)) {
1497                     $heading->scope = 'col';
1498                 }
1500                 $heading->attributes['class'] .= ' header c' . $key;
1501                 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1502                     $heading->colspan = $table->headspan[$key];
1503                     $countcols += $table->headspan[$key] - 1;
1504                 }
1506                 if ($key == $lastkey) {
1507                     $heading->attributes['class'] .= ' lastcol';
1508                 }
1509                 if (isset($table->colclasses[$key])) {
1510                     $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1511                 }
1512                 $heading->attributes['class'] = trim($heading->attributes['class']);
1513                 $attributes = array_merge($heading->attributes, array(
1514                         'style'     => $table->align[$key] . $table->size[$key] . $heading->style,
1515                         'scope'     => $heading->scope,
1516                         'colspan'   => $heading->colspan,
1517                     ));
1519                 $tagtype = 'td';
1520                 if ($heading->header === true) {
1521                     $tagtype = 'th';
1522                 }
1523                 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1524             }
1525             $output .= html_writer::end_tag('tr') . "\n";
1526             $output .= html_writer::end_tag('thead') . "\n";
1528             if (empty($table->data)) {
1529                 // For valid XHTML strict every table must contain either a valid tr
1530                 // or a valid tbody... both of which must contain a valid td
1531                 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1532                 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1533                 $output .= html_writer::end_tag('tbody');
1534             }
1535         }
1537         if (!empty($table->data)) {
1538             $oddeven    = 1;
1539             $keys       = array_keys($table->data);
1540             $lastrowkey = end($keys);
1541             $output .= html_writer::start_tag('tbody', array());
1543             foreach ($table->data as $key => $row) {
1544                 if (($row === 'hr') && ($countcols)) {
1545                     $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1546                 } else {
1547                     // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1548                     if (!($row instanceof html_table_row)) {
1549                         $newrow = new html_table_row();
1551                         foreach ($row as $cell) {
1552                             if (!($cell instanceof html_table_cell)) {
1553                                 $cell = new html_table_cell($cell);
1554                             }
1555                             $newrow->cells[] = $cell;
1556                         }
1557                         $row = $newrow;
1558                     }
1560                     $oddeven = $oddeven ? 0 : 1;
1561                     if (isset($table->rowclasses[$key])) {
1562                         $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1563                     }
1565                     $row->attributes['class'] .= ' r' . $oddeven;
1566                     if ($key == $lastrowkey) {
1567                         $row->attributes['class'] .= ' lastrow';
1568                     }
1570                     $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1571                     $keys2 = array_keys($row->cells);
1572                     $lastkey = end($keys2);
1574                     $gotlastkey = false; //flag for sanity checking
1575                     foreach ($row->cells as $key => $cell) {
1576                         if ($gotlastkey) {
1577                             //This should never happen. Why do we have a cell after the last cell?
1578                             mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1579                         }
1581                         if (!($cell instanceof html_table_cell)) {
1582                             $mycell = new html_table_cell();
1583                             $mycell->text = $cell;
1584                             $cell = $mycell;
1585                         }
1587                         if (($cell->header === true) && empty($cell->scope)) {
1588                             $cell->scope = 'row';
1589                         }
1591                         if (isset($table->colclasses[$key])) {
1592                             $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1593                         }
1595                         $cell->attributes['class'] .= ' cell c' . $key;
1596                         if ($key == $lastkey) {
1597                             $cell->attributes['class'] .= ' lastcol';
1598                             $gotlastkey = true;
1599                         }
1600                         $tdstyle = '';
1601                         $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1602                         $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1603                         $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1604                         $cell->attributes['class'] = trim($cell->attributes['class']);
1605                         $tdattributes = array_merge($cell->attributes, array(
1606                                 'style' => $tdstyle . $cell->style,
1607                                 'colspan' => $cell->colspan,
1608                                 'rowspan' => $cell->rowspan,
1609                                 'id' => $cell->id,
1610                                 'abbr' => $cell->abbr,
1611                                 'scope' => $cell->scope,
1612                             ));
1613                         $tagtype = 'td';
1614                         if ($cell->header === true) {
1615                             $tagtype = 'th';
1616                         }
1617                         $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1618                     }
1619                 }
1620                 $output .= html_writer::end_tag('tr') . "\n";
1621             }
1622             $output .= html_writer::end_tag('tbody') . "\n";
1623         }
1624         $output .= html_writer::end_tag('table') . "\n";
1626         return $output;
1627     }
1629     /**
1630      * Renders form element label
1631      *
1632      * By default, the label is suffixed with a label separator defined in the
1633      * current language pack (colon by default in the English lang pack).
1634      * Adding the colon can be explicitly disabled if needed. Label separators
1635      * are put outside the label tag itself so they are not read by
1636      * screenreaders (accessibility).
1637      *
1638      * Parameter $for explicitly associates the label with a form control. When
1639      * set, the value of this attribute must be the same as the value of
1640      * the id attribute of the form control in the same document. When null,
1641      * the label being defined is associated with the control inside the label
1642      * element.
1643      *
1644      * @param string $text content of the label tag
1645      * @param string|null $for id of the element this label is associated with, null for no association
1646      * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1647      * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1648      * @return string HTML of the label element
1649      */
1650     public static function label($text, $for, $colonize = true, array $attributes=array()) {
1651         if (!is_null($for)) {
1652             $attributes = array_merge($attributes, array('for' => $for));
1653         }
1654         $text = trim($text);
1655         $label = self::tag('label', $text, $attributes);
1657         // TODO MDL-12192 $colonize disabled for now yet
1658         // if (!empty($text) and $colonize) {
1659         //     // the $text may end with the colon already, though it is bad string definition style
1660         //     $colon = get_string('labelsep', 'langconfig');
1661         //     if (!empty($colon)) {
1662         //         $trimmed = trim($colon);
1663         //         if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1664         //             //debugging('The label text should not end with colon or other label separator,
1665         //             //           please fix the string definition.', DEBUG_DEVELOPER);
1666         //         } else {
1667         //             $label .= $colon;
1668         //         }
1669         //     }
1670         // }
1672         return $label;
1673     }
1675     /**
1676      * Combines a class parameter with other attributes. Aids in code reduction
1677      * because the class parameter is very frequently used.
1678      *
1679      * If the class attribute is specified both in the attributes and in the
1680      * class parameter, the two values are combined with a space between.
1681      *
1682      * @param string $class Optional CSS class (or classes as space-separated list)
1683      * @param array $attributes Optional other attributes as array
1684      * @return array Attributes (or null if still none)
1685      */
1686     private static function add_class($class = '', array $attributes = null) {
1687         if ($class !== '') {
1688             $classattribute = array('class' => $class);
1689             if ($attributes) {
1690                 if (array_key_exists('class', $attributes)) {
1691                     $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1692                 } else {
1693                     $attributes = $classattribute + $attributes;
1694                 }
1695             } else {
1696                 $attributes = $classattribute;
1697             }
1698         }
1699         return $attributes;
1700     }
1702     /**
1703      * Creates a <div> tag. (Shortcut function.)
1704      *
1705      * @param string $content HTML content of tag
1706      * @param string $class Optional CSS class (or classes as space-separated list)
1707      * @param array $attributes Optional other attributes as array
1708      * @return string HTML code for div
1709      */
1710     public static function div($content, $class = '', array $attributes = null) {
1711         return self::tag('div', $content, self::add_class($class, $attributes));
1712     }
1714     /**
1715      * Starts a <div> tag. (Shortcut function.)
1716      *
1717      * @param string $class Optional CSS class (or classes as space-separated list)
1718      * @param array $attributes Optional other attributes as array
1719      * @return string HTML code for open div tag
1720      */
1721     public static function start_div($class = '', array $attributes = null) {
1722         return self::start_tag('div', self::add_class($class, $attributes));
1723     }
1725     /**
1726      * Ends a <div> tag. (Shortcut function.)
1727      *
1728      * @return string HTML code for close div tag
1729      */
1730     public static function end_div() {
1731         return self::end_tag('div');
1732     }
1734     /**
1735      * Creates a <span> tag. (Shortcut function.)
1736      *
1737      * @param string $content HTML content of tag
1738      * @param string $class Optional CSS class (or classes as space-separated list)
1739      * @param array $attributes Optional other attributes as array
1740      * @return string HTML code for span
1741      */
1742     public static function span($content, $class = '', array $attributes = null) {
1743         return self::tag('span', $content, self::add_class($class, $attributes));
1744     }
1746     /**
1747      * Starts a <span> tag. (Shortcut function.)
1748      *
1749      * @param string $class Optional CSS class (or classes as space-separated list)
1750      * @param array $attributes Optional other attributes as array
1751      * @return string HTML code for open span tag
1752      */
1753     public static function start_span($class = '', array $attributes = null) {
1754         return self::start_tag('span', self::add_class($class, $attributes));
1755     }
1757     /**
1758      * Ends a <span> tag. (Shortcut function.)
1759      *
1760      * @return string HTML code for close span tag
1761      */
1762     public static function end_span() {
1763         return self::end_tag('span');
1764     }
1767 /**
1768  * Simple javascript output class
1769  *
1770  * @copyright 2010 Petr Skoda
1771  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1772  * @since Moodle 2.0
1773  * @package core
1774  * @category output
1775  */
1776 class js_writer {
1778     /**
1779      * Returns javascript code calling the function
1780      *
1781      * @param string $function function name, can be complex like Y.Event.purgeElement
1782      * @param array $arguments parameters
1783      * @param int $delay execution delay in seconds
1784      * @return string JS code fragment
1785      */
1786     public static function function_call($function, array $arguments = null, $delay=0) {
1787         if ($arguments) {
1788             $arguments = array_map('json_encode', convert_to_array($arguments));
1789             $arguments = implode(', ', $arguments);
1790         } else {
1791             $arguments = '';
1792         }
1793         $js = "$function($arguments);";
1795         if ($delay) {
1796             $delay = $delay * 1000; // in miliseconds
1797             $js = "setTimeout(function() { $js }, $delay);";
1798         }
1799         return $js . "\n";
1800     }
1802     /**
1803      * Special function which adds Y as first argument of function call.
1804      *
1805      * @param string $function The function to call
1806      * @param array $extraarguments Any arguments to pass to it
1807      * @return string Some JS code
1808      */
1809     public static function function_call_with_Y($function, array $extraarguments = null) {
1810         if ($extraarguments) {
1811             $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1812             $arguments = 'Y, ' . implode(', ', $extraarguments);
1813         } else {
1814             $arguments = 'Y';
1815         }
1816         return "$function($arguments);\n";
1817     }
1819     /**
1820      * Returns JavaScript code to initialise a new object
1821      *
1822      * @param string $var If it is null then no var is assigned the new object.
1823      * @param string $class The class to initialise an object for.
1824      * @param array $arguments An array of args to pass to the init method.
1825      * @param array $requirements Any modules required for this class.
1826      * @param int $delay The delay before initialisation. 0 = no delay.
1827      * @return string Some JS code
1828      */
1829     public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1830         if (is_array($arguments)) {
1831             $arguments = array_map('json_encode', convert_to_array($arguments));
1832             $arguments = implode(', ', $arguments);
1833         }
1835         if ($var === null) {
1836             $js = "new $class(Y, $arguments);";
1837         } else if (strpos($var, '.')!==false) {
1838             $js = "$var = new $class(Y, $arguments);";
1839         } else {
1840             $js = "var $var = new $class(Y, $arguments);";
1841         }
1843         if ($delay) {
1844             $delay = $delay * 1000; // in miliseconds
1845             $js = "setTimeout(function() { $js }, $delay);";
1846         }
1848         if (count($requirements) > 0) {
1849             $requirements = implode("', '", $requirements);
1850             $js = "Y.use('$requirements', function(Y){ $js });";
1851         }
1852         return $js."\n";
1853     }
1855     /**
1856      * Returns code setting value to variable
1857      *
1858      * @param string $name
1859      * @param mixed $value json serialised value
1860      * @param bool $usevar add var definition, ignored for nested properties
1861      * @return string JS code fragment
1862      */
1863     public static function set_variable($name, $value, $usevar = true) {
1864         $output = '';
1866         if ($usevar) {
1867             if (strpos($name, '.')) {
1868                 $output .= '';
1869             } else {
1870                 $output .= 'var ';
1871             }
1872         }
1874         $output .= "$name = ".json_encode($value).";";
1876         return $output;
1877     }
1879     /**
1880      * Writes event handler attaching code
1881      *
1882      * @param array|string $selector standard YUI selector for elements, may be
1883      *     array or string, element id is in the form "#idvalue"
1884      * @param string $event A valid DOM event (click, mousedown, change etc.)
1885      * @param string $function The name of the function to call
1886      * @param array $arguments An optional array of argument parameters to pass to the function
1887      * @return string JS code fragment
1888      */
1889     public static function event_handler($selector, $event, $function, array $arguments = null) {
1890         $selector = json_encode($selector);
1891         $output = "Y.on('$event', $function, $selector, null";
1892         if (!empty($arguments)) {
1893             $output .= ', ' . json_encode($arguments);
1894         }
1895         return $output . ");\n";
1896     }
1899 /**
1900  * Holds all the information required to render a <table> by {@link core_renderer::table()}
1901  *
1902  * Example of usage:
1903  * $t = new html_table();
1904  * ... // set various properties of the object $t as described below
1905  * echo html_writer::table($t);
1906  *
1907  * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1908  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1909  * @since Moodle 2.0
1910  * @package core
1911  * @category output
1912  */
1913 class html_table {
1915     /**
1916      * @var string Value to use for the id attribute of the table
1917      */
1918     public $id = null;
1920     /**
1921      * @var array Attributes of HTML attributes for the <table> element
1922      */
1923     public $attributes = array();
1925     /**
1926      * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1927      * For more control over the rendering of the headers, an array of html_table_cell objects
1928      * can be passed instead of an array of strings.
1929      *
1930      * Example of usage:
1931      * $t->head = array('Student', 'Grade');
1932      */
1933     public $head;
1935     /**
1936      * @var array An array that can be used to make a heading span multiple columns.
1937      * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1938      * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1939      *
1940      * Example of usage:
1941      * $t->headspan = array(2,1);
1942      */
1943     public $headspan;
1945     /**
1946      * @var array An array of column alignments.
1947      * The value is used as CSS 'text-align' property. Therefore, possible
1948      * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1949      * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1950      *
1951      * Examples of usage:
1952      * $t->align = array(null, 'right');
1953      * or
1954      * $t->align[1] = 'right';
1955      */
1956     public $align;
1958     /**
1959      * @var array The value is used as CSS 'size' property.
1960      *
1961      * Examples of usage:
1962      * $t->size = array('50%', '50%');
1963      * or
1964      * $t->size[1] = '120px';
1965      */
1966     public $size;
1968     /**
1969      * @var array An array of wrapping information.
1970      * The only possible value is 'nowrap' that sets the
1971      * CSS property 'white-space' to the value 'nowrap' in the given column.
1972      *
1973      * Example of usage:
1974      * $t->wrap = array(null, 'nowrap');
1975      */
1976     public $wrap;
1978     /**
1979      * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1980      * $head specified, the string 'hr' (for horizontal ruler) can be used
1981      * instead of an array of cells data resulting in a divider rendered.
1982      *
1983      * Example of usage with array of arrays:
1984      * $row1 = array('Harry Potter', '76 %');
1985      * $row2 = array('Hermione Granger', '100 %');
1986      * $t->data = array($row1, $row2);
1987      *
1988      * Example with array of html_table_row objects: (used for more fine-grained control)
1989      * $cell1 = new html_table_cell();
1990      * $cell1->text = 'Harry Potter';
1991      * $cell1->colspan = 2;
1992      * $row1 = new html_table_row();
1993      * $row1->cells[] = $cell1;
1994      * $cell2 = new html_table_cell();
1995      * $cell2->text = 'Hermione Granger';
1996      * $cell3 = new html_table_cell();
1997      * $cell3->text = '100 %';
1998      * $row2 = new html_table_row();
1999      * $row2->cells = array($cell2, $cell3);
2000      * $t->data = array($row1, $row2);
2001      */
2002     public $data;
2004     /**
2005      * @deprecated since Moodle 2.0. Styling should be in the CSS.
2006      * @var string Width of the table, percentage of the page preferred.
2007      */
2008     public $width = null;
2010     /**
2011      * @deprecated since Moodle 2.0. Styling should be in the CSS.
2012      * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2013      */
2014     public $tablealign = null;
2016     /**
2017      * @deprecated since Moodle 2.0. Styling should be in the CSS.
2018      * @var int Padding on each cell, in pixels
2019      */
2020     public $cellpadding = null;
2022     /**
2023      * @var int Spacing between cells, in pixels
2024      * @deprecated since Moodle 2.0. Styling should be in the CSS.
2025      */
2026     public $cellspacing = null;
2028     /**
2029      * @var array Array of classes to add to particular rows, space-separated string.
2030      * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2031      * respectively. Class 'lastrow' is added automatically for the last row
2032      * in the table.
2033      *
2034      * Example of usage:
2035      * $t->rowclasses[9] = 'tenth'
2036      */
2037     public $rowclasses;
2039     /**
2040      * @var array An array of classes to add to every cell in a particular column,
2041      * space-separated string. Class 'cell' is added automatically by the renderer.
2042      * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2043      * respectively. Class 'lastcol' is added automatically for all last cells
2044      * in a row.
2045      *
2046      * Example of usage:
2047      * $t->colclasses = array(null, 'grade');
2048      */
2049     public $colclasses;
2051     /**
2052      * @var string Description of the contents for screen readers.
2053      */
2054     public $summary;
2056     /**
2057      * Constructor
2058      */
2059     public function __construct() {
2060         $this->attributes['class'] = '';
2061     }
2064 /**
2065  * Component representing a table row.
2066  *
2067  * @copyright 2009 Nicolas Connault
2068  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2069  * @since Moodle 2.0
2070  * @package core
2071  * @category output
2072  */
2073 class html_table_row {
2075     /**
2076      * @var string Value to use for the id attribute of the row.
2077      */
2078     public $id = null;
2080     /**
2081      * @var array Array of html_table_cell objects
2082      */
2083     public $cells = array();
2085     /**
2086      * @var string Value to use for the style attribute of the table row
2087      */
2088     public $style = null;
2090     /**
2091      * @var array Attributes of additional HTML attributes for the <tr> element
2092      */
2093     public $attributes = array();
2095     /**
2096      * Constructor
2097      * @param array $cells
2098      */
2099     public function __construct(array $cells=null) {
2100         $this->attributes['class'] = '';
2101         $cells = (array)$cells;
2102         foreach ($cells as $cell) {
2103             if ($cell instanceof html_table_cell) {
2104                 $this->cells[] = $cell;
2105             } else {
2106                 $this->cells[] = new html_table_cell($cell);
2107             }
2108         }
2109     }
2112 /**
2113  * Component representing a table cell.
2114  *
2115  * @copyright 2009 Nicolas Connault
2116  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2117  * @since Moodle 2.0
2118  * @package core
2119  * @category output
2120  */
2121 class html_table_cell {
2123     /**
2124      * @var string Value to use for the id attribute of the cell.
2125      */
2126     public $id = null;
2128     /**
2129      * @var string The contents of the cell.
2130      */
2131     public $text;
2133     /**
2134      * @var string Abbreviated version of the contents of the cell.
2135      */
2136     public $abbr = null;
2138     /**
2139      * @var int Number of columns this cell should span.
2140      */
2141     public $colspan = null;
2143     /**
2144      * @var int Number of rows this cell should span.
2145      */
2146     public $rowspan = null;
2148     /**
2149      * @var string Defines a way to associate header cells and data cells in a table.
2150      */
2151     public $scope = null;
2153     /**
2154      * @var bool Whether or not this cell is a header cell.
2155      */
2156     public $header = null;
2158     /**
2159      * @var string Value to use for the style attribute of the table cell
2160      */
2161     public $style = null;
2163     /**
2164      * @var array Attributes of additional HTML attributes for the <td> element
2165      */
2166     public $attributes = array();
2168     /**
2169      * Constructs a table cell
2170      *
2171      * @param string $text
2172      */
2173     public function __construct($text = null) {
2174         $this->text = $text;
2175         $this->attributes['class'] = '';
2176     }
2179 /**
2180  * Component representing a paging bar.
2181  *
2182  * @copyright 2009 Nicolas Connault
2183  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2184  * @since Moodle 2.0
2185  * @package core
2186  * @category output
2187  */
2188 class paging_bar implements renderable {
2190     /**
2191      * @var int The maximum number of pagelinks to display.
2192      */
2193     public $maxdisplay = 18;
2195     /**
2196      * @var int The total number of entries to be pages through..
2197      */
2198     public $totalcount;
2200     /**
2201      * @var int The page you are currently viewing.
2202      */
2203     public $page;
2205     /**
2206      * @var int The number of entries that should be shown per page.
2207      */
2208     public $perpage;
2210     /**
2211      * @var string|moodle_url If this  is a string then it is the url which will be appended with $pagevar,
2212      * an equals sign and the page number.
2213      * If this is a moodle_url object then the pagevar param will be replaced by
2214      * the page no, for each page.
2215      */
2216     public $baseurl;
2218     /**
2219      * @var string This is the variable name that you use for the pagenumber in your
2220      * code (ie. 'tablepage', 'blogpage', etc)
2221      */
2222     public $pagevar;
2224     /**
2225      * @var string A HTML link representing the "previous" page.
2226      */
2227     public $previouslink = null;
2229     /**
2230      * @var string A HTML link representing the "next" page.
2231      */
2232     public $nextlink = null;
2234     /**
2235      * @var string A HTML link representing the first page.
2236      */
2237     public $firstlink = null;
2239     /**
2240      * @var string A HTML link representing the last page.
2241      */
2242     public $lastlink = null;
2244     /**
2245      * @var array An array of strings. One of them is just a string: the current page
2246      */
2247     public $pagelinks = array();
2249     /**
2250      * Constructor paging_bar with only the required params.
2251      *
2252      * @param int $totalcount The total number of entries available to be paged through
2253      * @param int $page The page you are currently viewing
2254      * @param int $perpage The number of entries that should be shown per page
2255      * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2256      * @param string $pagevar name of page parameter that holds the page number
2257      */
2258     public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2259         $this->totalcount = $totalcount;
2260         $this->page       = $page;
2261         $this->perpage    = $perpage;
2262         $this->baseurl    = $baseurl;
2263         $this->pagevar    = $pagevar;
2264     }
2266     /**
2267      * Prepares the paging bar for output.
2268      *
2269      * This method validates the arguments set up for the paging bar and then
2270      * produces fragments of HTML to assist display later on.
2271      *
2272      * @param renderer_base $output
2273      * @param moodle_page $page
2274      * @param string $target
2275      * @throws coding_exception
2276      */
2277     public function prepare(renderer_base $output, moodle_page $page, $target) {
2278         if (!isset($this->totalcount) || is_null($this->totalcount)) {
2279             throw new coding_exception('paging_bar requires a totalcount value.');
2280         }
2281         if (!isset($this->page) || is_null($this->page)) {
2282             throw new coding_exception('paging_bar requires a page value.');
2283         }
2284         if (empty($this->perpage)) {
2285             throw new coding_exception('paging_bar requires a perpage value.');
2286         }
2287         if (empty($this->baseurl)) {
2288             throw new coding_exception('paging_bar requires a baseurl value.');
2289         }
2291         if ($this->totalcount > $this->perpage) {
2292             $pagenum = $this->page - 1;
2294             if ($this->page > 0) {
2295                 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2296             }
2298             if ($this->perpage > 0) {
2299                 $lastpage = ceil($this->totalcount / $this->perpage);
2300             } else {
2301                 $lastpage = 1;
2302             }
2304             if ($this->page > round(($this->maxdisplay/3)*2)) {
2305                 $currpage = $this->page - round($this->maxdisplay/3);
2307                 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2308             } else {
2309                 $currpage = 0;
2310             }
2312             $displaycount = $displaypage = 0;
2314             while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2315                 $displaypage = $currpage + 1;
2317                 if ($this->page == $currpage) {
2318                     $this->pagelinks[] = $displaypage;
2319                 } else {
2320                     $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2321                     $this->pagelinks[] = $pagelink;
2322                 }
2324                 $displaycount++;
2325                 $currpage++;
2326             }
2328             if ($currpage < $lastpage) {
2329                 $lastpageactual = $lastpage - 1;
2330                 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2331             }
2333             $pagenum = $this->page + 1;
2335             if ($pagenum != $displaypage) {
2336                 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2337             }
2338         }
2339     }
2342 /**
2343  * This class represents how a block appears on a page.
2344  *
2345  * During output, each block instance is asked to return a block_contents object,
2346  * those are then passed to the $OUTPUT->block function for display.
2347  *
2348  * contents should probably be generated using a moodle_block_..._renderer.
2349  *
2350  * Other block-like things that need to appear on the page, for example the
2351  * add new block UI, are also represented as block_contents objects.
2352  *
2353  * @copyright 2009 Tim Hunt
2354  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2355  * @since Moodle 2.0
2356  * @package core
2357  * @category output
2358  */
2359 class block_contents {
2361     /** Used when the block cannot be collapsed **/
2362     const NOT_HIDEABLE = 0;
2364     /** Used when the block can be collapsed but currently is not **/
2365     const VISIBLE = 1;
2367     /** Used when the block has been collapsed **/
2368     const HIDDEN = 2;
2370     /**
2371      * @var int Used to set $skipid.
2372      */
2373     protected static $idcounter = 1;
2375     /**
2376      * @var int All the blocks (or things that look like blocks) printed on
2377      * a page are given a unique number that can be used to construct id="" attributes.
2378      * This is set automatically be the {@link prepare()} method.
2379      * Do not try to set it manually.
2380      */
2381     public $skipid;
2383     /**
2384      * @var int If this is the contents of a real block, this should be set
2385      * to the block_instance.id. Otherwise this should be set to 0.
2386      */
2387     public $blockinstanceid = 0;
2389     /**
2390      * @var int If this is a real block instance, and there is a corresponding
2391      * block_position.id for the block on this page, this should be set to that id.
2392      * Otherwise it should be 0.
2393      */
2394     public $blockpositionid = 0;
2396     /**
2397      * @var array An array of attribute => value pairs that are put on the outer div of this
2398      * block. {@link $id} and {@link $classes} attributes should be set separately.
2399      */
2400     public $attributes;
2402     /**
2403      * @var string The title of this block. If this came from user input, it should already
2404      * have had format_string() processing done on it. This will be output inside
2405      * <h2> tags. Please do not cause invalid XHTML.
2406      */
2407     public $title = '';
2409     /**
2410      * @var string The label to use when the block does not, or will not have a visible title.
2411      * You should never set this as well as title... it will just be ignored.
2412      */
2413     public $arialabel = '';
2415     /**
2416      * @var string HTML for the content
2417      */
2418     public $content = '';
2420     /**
2421      * @var array An alternative to $content, it you want a list of things with optional icons.
2422      */
2423     public $footer = '';
2425     /**
2426      * @var string Any small print that should appear under the block to explain
2427      * to the teacher about the block, for example 'This is a sticky block that was
2428      * added in the system context.'
2429      */
2430     public $annotation = '';
2432     /**
2433      * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2434      * the user can toggle whether this block is visible.
2435      */
2436     public $collapsible = self::NOT_HIDEABLE;
2438     /**
2439      * @var array A (possibly empty) array of editing controls. Each element of
2440      * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2441      * $icon is the icon name. Fed to $OUTPUT->pix_url.
2442      */
2443     public $controls = array();
2446     /**
2447      * Create new instance of block content
2448      * @param array $attributes
2449      */
2450     public function __construct(array $attributes = null) {
2451         $this->skipid = self::$idcounter;
2452         self::$idcounter += 1;
2454         if ($attributes) {
2455             // standard block
2456             $this->attributes = $attributes;
2457         } else {
2458             // simple "fake" blocks used in some modules and "Add new block" block
2459             $this->attributes = array('class'=>'block');
2460         }
2461     }
2463     /**
2464      * Add html class to block
2465      *
2466      * @param string $class
2467      */
2468     public function add_class($class) {
2469         $this->attributes['class'] .= ' '.$class;
2470     }
2474 /**
2475  * This class represents a target for where a block can go when it is being moved.
2476  *
2477  * This needs to be rendered as a form with the given hidden from fields, and
2478  * clicking anywhere in the form should submit it. The form action should be
2479  * $PAGE->url.
2480  *
2481  * @copyright 2009 Tim Hunt
2482  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2483  * @since Moodle 2.0
2484  * @package core
2485  * @category output
2486  */
2487 class block_move_target {
2489     /**
2490      * @var moodle_url Move url
2491      */
2492     public $url;
2494     /**
2495      * Constructor
2496      * @param moodle_url $url
2497      */
2498     public function __construct(moodle_url $url) {
2499         $this->url  = $url;
2500     }
2503 /**
2504  * Custom menu item
2505  *
2506  * This class is used to represent one item within a custom menu that may or may
2507  * not have children.
2508  *
2509  * @copyright 2010 Sam Hemelryk
2510  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2511  * @since Moodle 2.0
2512  * @package core
2513  * @category output
2514  */
2515 class custom_menu_item implements renderable {
2517     /**
2518      * @var string The text to show for the item
2519      */
2520     protected $text;
2522     /**
2523      * @var moodle_url The link to give the icon if it has no children
2524      */
2525     protected $url;
2527     /**
2528      * @var string A title to apply to the item. By default the text
2529      */
2530     protected $title;
2532     /**
2533      * @var int A sort order for the item, not necessary if you order things in
2534      * the CFG var.
2535      */
2536     protected $sort;
2538     /**
2539      * @var custom_menu_item A reference to the parent for this item or NULL if
2540      * it is a top level item
2541      */
2542     protected $parent;
2544     /**
2545      * @var array A array in which to store children this item has.
2546      */
2547     protected $children = array();
2549     /**
2550      * @var int A reference to the sort var of the last child that was added
2551      */
2552     protected $lastsort = 0;
2554     /**
2555      * Constructs the new custom menu item
2556      *
2557      * @param string $text
2558      * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2559      * @param string $title A title to apply to this item [Optional]
2560      * @param int $sort A sort or to use if we need to sort differently [Optional]
2561      * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2562      *        belongs to, only if the child has a parent. [Optional]
2563      */
2564     public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2565         $this->text = $text;
2566         $this->url = $url;
2567         $this->title = $title;
2568         $this->sort = (int)$sort;
2569         $this->parent = $parent;
2570     }
2572     /**
2573      * Adds a custom menu item as a child of this node given its properties.
2574      *
2575      * @param string $text
2576      * @param moodle_url $url
2577      * @param string $title
2578      * @param int $sort
2579      * @return custom_menu_item
2580      */
2581     public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2582         $key = count($this->children);
2583         if (empty($sort)) {
2584             $sort = $this->lastsort + 1;
2585         }
2586         $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2587         $this->lastsort = (int)$sort;
2588         return $this->children[$key];
2589     }
2591     /**
2592      * Returns the text for this item
2593      * @return string
2594      */
2595     public function get_text() {
2596         return $this->text;
2597     }
2599     /**
2600      * Returns the url for this item
2601      * @return moodle_url
2602      */
2603     public function get_url() {
2604         return $this->url;
2605     }
2607     /**
2608      * Returns the title for this item
2609      * @return string
2610      */
2611     public function get_title() {
2612         return $this->title;
2613     }
2615     /**
2616      * Sorts and returns the children for this item
2617      * @return array
2618      */
2619     public function get_children() {
2620         $this->sort();
2621         return $this->children;
2622     }
2624     /**
2625      * Gets the sort order for this child
2626      * @return int
2627      */
2628     public function get_sort_order() {
2629         return $this->sort;
2630     }
2632     /**
2633      * Gets the parent this child belong to
2634      * @return custom_menu_item
2635      */
2636     public function get_parent() {
2637         return $this->parent;
2638     }
2640     /**
2641      * Sorts the children this item has
2642      */
2643     public function sort() {
2644         usort($this->children, array('custom_menu','sort_custom_menu_items'));
2645     }
2647     /**
2648      * Returns true if this item has any children
2649      * @return bool
2650      */
2651     public function has_children() {
2652         return (count($this->children) > 0);
2653     }
2655     /**
2656      * Sets the text for the node
2657      * @param string $text
2658      */
2659     public function set_text($text) {
2660         $this->text = (string)$text;
2661     }
2663     /**
2664      * Sets the title for the node
2665      * @param string $title
2666      */
2667     public function set_title($title) {
2668         $this->title = (string)$title;
2669     }
2671     /**
2672      * Sets the url for the node
2673      * @param moodle_url $url
2674      */
2675     public function set_url(moodle_url $url) {
2676         $this->url = $url;
2677     }
2680 /**
2681  * Custom menu class
2682  *
2683  * This class is used to operate a custom menu that can be rendered for the page.
2684  * The custom menu is built using $CFG->custommenuitems and is a structured collection
2685  * of custom_menu_item nodes that can be rendered by the core renderer.
2686  *
2687  * To configure the custom menu:
2688  *     Settings: Administration > Appearance > Themes > Theme settings
2689  *
2690  * @copyright 2010 Sam Hemelryk
2691  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2692  * @since Moodle 2.0
2693  * @package core
2694  * @category output
2695  */
2696 class custom_menu extends custom_menu_item {
2698     /**
2699      * @var string The language we should render for, null disables multilang support.
2700      */
2701     protected $currentlanguage = null;
2703     /**
2704      * Creates the custom menu
2705      *
2706      * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2707      * @param string $currentlanguage the current language code, null disables multilang support
2708      */
2709     public function __construct($definition = '', $currentlanguage = null) {
2710         $this->currentlanguage = $currentlanguage;
2711         parent::__construct('root'); // create virtual root element of the menu
2712         if (!empty($definition)) {
2713             $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2714         }
2715     }
2717     /**
2718      * Overrides the children of this custom menu. Useful when getting children
2719      * from $CFG->custommenuitems
2720      *
2721      * @param array $children
2722      */
2723     public function override_children(array $children) {
2724         $this->children = array();
2725         foreach ($children as $child) {
2726             if ($child instanceof custom_menu_item) {
2727                 $this->children[] = $child;
2728             }
2729         }
2730     }
2732     /**
2733      * Converts a string into a structured array of custom_menu_items which can
2734      * then be added to a custom menu.
2735      *
2736      * Structure:
2737      *     text|url|title|langs
2738      * The number of hyphens at the start determines the depth of the item. The
2739      * languages are optional, comma separated list of languages the line is for.
2740      *
2741      * Example structure:
2742      *     First level first item|http://www.moodle.com/
2743      *     -Second level first item|http://www.moodle.com/partners/
2744      *     -Second level second item|http://www.moodle.com/hq/
2745      *     --Third level first item|http://www.moodle.com/jobs/
2746      *     -Second level third item|http://www.moodle.com/development/
2747      *     First level second item|http://www.moodle.com/feedback/
2748      *     First level third item
2749      *     English only|http://moodle.com|English only item|en
2750      *     German only|http://moodle.de|Deutsch|de,de_du,de_kids
2751      *
2752      *
2753      * @static
2754      * @param string $text the menu items definition
2755      * @param string $language the language code, null disables multilang support
2756      * @return array
2757      */
2758     public static function convert_text_to_menu_nodes($text, $language = null) {
2759         $lines = explode("\n", $text);
2760         $children = array();
2761         $lastchild = null;
2762         $lastdepth = null;
2763         $lastsort = 0;
2764         foreach ($lines as $line) {
2765             $line = trim($line);
2766             $bits = explode('|', $line, 4);    // name|url|title|langs
2767             if (!array_key_exists(0, $bits) or empty($bits[0])) {
2768                 // Every item must have a name to be valid
2769                 continue;
2770             } else {
2771                 $bits[0] = ltrim($bits[0],'-');
2772             }
2773             if (!array_key_exists(1, $bits) or empty($bits[1])) {
2774                 // Set the url to null
2775                 $bits[1] = null;
2776             } else {
2777                 // Make sure the url is a moodle url
2778                 $bits[1] = new moodle_url(trim($bits[1]));
2779             }
2780             if (!array_key_exists(2, $bits) or empty($bits[2])) {
2781                 // Set the title to null seeing as there isn't one
2782                 $bits[2] = $bits[0];
2783             }
2784             if (!array_key_exists(3, $bits) or empty($bits[3])) {
2785                 // The item is valid for all languages
2786                 $itemlangs = null;
2787             } else {
2788                 $itemlangs = array_map('trim', explode(',', $bits[3]));
2789             }
2790             if (!empty($language) and !empty($itemlangs)) {
2791                 // check that the item is intended for the current language
2792                 if (!in_array($language, $itemlangs)) {
2793                     continue;
2794                 }
2795             }
2796             // Set an incremental sort order to keep it simple.
2797             $lastsort++;
2798             if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2799                 $depth = strlen($match[1]);
2800                 if ($depth < $lastdepth) {
2801                     $difference = $lastdepth - $depth;
2802                     if ($lastdepth > 1 && $lastdepth != $difference) {
2803                         $tempchild = $lastchild->get_parent();
2804                         for ($i =0; $i < $difference; $i++) {
2805                             $tempchild = $tempchild->get_parent();
2806                         }
2807                         $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2808                     } else {
2809                         $depth = 0;
2810                         $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2811                         $children[] = $lastchild;
2812                     }
2813                 } else if ($depth > $lastdepth) {
2814                     $depth = $lastdepth + 1;
2815                     $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2816                 } else {
2817                     if ($depth == 0) {
2818                         $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2819                         $children[] = $lastchild;
2820                     } else {
2821                         $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2822                     }
2823                 }
2824             } else {
2825                 $depth = 0;
2826                 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2827                 $children[] = $lastchild;
2828             }
2829             $lastdepth = $depth;
2830         }
2831         return $children;
2832     }
2834     /**
2835      * Sorts two custom menu items
2836      *
2837      * This function is designed to be used with the usort method
2838      *     usort($this->children, array('custom_menu','sort_custom_menu_items'));
2839      *
2840      * @static
2841      * @param custom_menu_item $itema
2842      * @param custom_menu_item $itemb
2843      * @return int
2844      */
2845     public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2846         $itema = $itema->get_sort_order();
2847         $itemb = $itemb->get_sort_order();
2848         if ($itema == $itemb) {
2849             return 0;
2850         }
2851         return ($itema > $itemb) ? +1 : -1;
2852     }
2855 /**
2856  * Stores one tab
2857  *
2858  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2859  * @package core
2860  */
2861 class tabobject implements renderable {
2862     /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2863     var $id;
2864     /** @var moodle_url|string link */
2865     var $link;
2866     /** @var string text on the tab */
2867     var $text;
2868     /** @var string title under the link, by defaul equals to text */
2869     var $title;
2870     /** @var bool whether to display a link under the tab name when it's selected */
2871     var $linkedwhenselected = false;
2872     /** @var bool whether the tab is inactive */
2873     var $inactive = false;
2874     /** @var bool indicates that this tab's child is selected */
2875     var $activated = false;
2876     /** @var bool indicates that this tab is selected */
2877     var $selected = false;
2878     /** @var array stores children tabobjects */
2879     var $subtree = array();
2880     /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2881     var $level = 1;
2883     /**
2884      * Constructor
2885      *
2886      * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2887      * @param string|moodle_url $link
2888      * @param string $text text on the tab
2889      * @param string $title title under the link, by defaul equals to text
2890      * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2891      */
2892     public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2893         $this->id = $id;
2894         $this->link = $link;
2895         $this->text = $text;
2896         $this->title = $title ? $title : $text;
2897         $this->linkedwhenselected = $linkedwhenselected;
2898     }
2900     /**
2901      * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2902      *
2903      * @param string $selected the id of the selected tab (whatever row it's on),
2904      *    if null marks all tabs as unselected
2905      * @return bool whether this tab is selected or contains selected tab in its subtree
2906      */
2907     protected function set_selected($selected) {
2908         if ((string)$selected === (string)$this->id) {
2909             $this->selected = true;
2910             // This tab is selected. No need to travel through subtree.
2911             return true;
2912         }
2913         foreach ($this->subtree as $subitem) {
2914             if ($subitem->set_selected($selected)) {
2915                 // This tab has child that is selected. Mark it as activated. No need to check other children.
2916                 $this->activated = true;
2917                 return true;
2918             }
2919         }
2920         return false;
2921     }
2923     /**
2924      * Travels through tree and finds a tab with specified id
2925      *
2926      * @param string $id
2927      * @return tabtree|null
2928      */
2929     public function find($id) {
2930         if ((string)$this->id === (string)$id) {
2931             return $this;
2932         }
2933         foreach ($this->subtree as $tab) {
2934             if ($obj = $tab->find($id)) {
2935                 return $obj;
2936             }
2937         }
2938         return null;
2939     }
2941     /**
2942      * Allows to mark each tab's level in the tree before rendering.
2943      *
2944      * @param int $level
2945      */
2946     protected function set_level($level) {
2947         $this->level = $level;
2948         foreach ($this->subtree as $tab) {
2949             $tab->set_level($level + 1);
2950         }
2951     }
2954 /**
2955  * Stores tabs list
2956  *
2957  * Example how to print a single line tabs:
2958  * $rows = array(
2959  *    new tabobject(...),
2960  *    new tabobject(...)
2961  * );
2962  * echo $OUTPUT->tabtree($rows, $selectedid);
2963  *
2964  * Multiple row tabs may not look good on some devices but if you want to use them
2965  * you can specify ->subtree for the active tabobject.
2966  *
2967  * @copyright 2013 Marina Glancy
2968  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2969  * @since Moodle 2.5
2970  * @package core
2971  * @category output
2972  */
2973 class tabtree extends tabobject {
2974     /**
2975      * Constuctor
2976      *
2977      * It is highly recommended to call constructor when list of tabs is already
2978      * populated, this way you ensure that selected and inactive tabs are located
2979      * and attribute level is set correctly.
2980      *
2981      * @param array $tabs array of tabs, each of them may have it's own ->subtree
2982      * @param string|null $selected which tab to mark as selected, all parent tabs will
2983      *     automatically be marked as activated
2984      * @param array|string|null $inactive list of ids of inactive tabs, regardless of
2985      *     their level. Note that you can as weel specify tabobject::$inactive for separate instances
2986      */
2987     public function __construct($tabs, $selected = null, $inactive = null) {
2988         $this->subtree = $tabs;
2989         if ($selected !== null) {
2990             $this->set_selected($selected);
2991         }
2992         if ($inactive !== null) {
2993             if (is_array($inactive)) {
2994                 foreach ($inactive as $id) {
2995                     if ($tab = $this->find($id)) {
2996                         $tab->inactive = true;
2997                     }
2998                 }
2999             } else if ($tab = $this->find($inactive)) {
3000                 $tab->inactive = true;
3001             }
3002         }
3003         $this->set_level(0);
3004     }