.
/**
* Classes representing HTML elements, used by $OUTPUT methods
*
* Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
* for an overview.
*
* @package moodlecore
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* This constant is used for html attributes which need to have an empty
* value and still be output by the renderers (e.g. alt="");
*
* @constant @EMPTY@
*/
define('HTML_ATTR_EMPTY', '@EMPTY@');
/**
* Interface marking other classes as suitable for renderer_base::render()
* @author 2010 Petr Skoda (skodak) info@skodak.org
*/
interface renderable {
// intentionally empty
}
/**
* Data structure representing a user picture.
*
* @copyright 2009 Nicolas Connault, 2010 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class user_picture implements renderable {
/**
* List of mandatory fields in user record here.
* @var string
*/
const FIELDS = 'id,picture,firstname,lastname,imagealt';
/**
* @var object $user A user object with at least fields id, picture, imagealt, firstname and lastname set.
*/
public $user;
/**
* @var int $courseid The course id. Used when constructing the link to the user's profile,
* page course id used if not specified.
*/
public $courseid;
/**
* @var bool $link add course profile link to image
*/
public $link = true;
/**
* @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
*/
public $size = 35;
/**
* @var boolean $alttext add non-blank alt-text to the image.
* Default true, set to false when image alt just duplicates text in screenreaders.
*/
public $alttext = true;
/**
* @var boolean $popup Whether or not to open the link in a popup window.
*/
public $popup = false;
/**
* @var string Image class attribute
*/
public $class = 'userpicture';
/**
* User picture constructor.
*
* @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
* @param array $options such as link, size, link, ...
*/
public function __construct(stdClass $user) {
global $DB;
static $fields = null;
if (is_null($fields)) {
$fields = explode(',', self::FIELDS);
}
if (empty($user->id)) {
throw new coding_exception('User id is required when printing user avatar image.');
}
// only touch the DB if we are missing data and complain loudly...
$needrec = false;
foreach ($fields as $field) {
if (!array_key_exists($field, $user)) {
$needrec = true;
debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
.'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
break;
}
}
if ($needrec) {
$this->user = $DB->get_record('user', array('id'=>$user->id), self::FIELDS, MUST_EXIST);
} else {
$this->user = clone($user);
}
}
/**
* Returns a list of required user fields, usefull when fetching required user info from db.
* @param string $tableprefix name of database table prefix in query
* @return string
*/
public static function fields($tableprefix = '') {
if ($tableprefix === '') {
return self::FIELDS;
} else {
return "$tableprefix." . str_replace(',', ",$tableprefix.", self::FIELDS);
}
}
}
/**
* Data structure representing a help icon.
*
* @copyright 2009 Nicolas Connault, 2010 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class help_icon implements renderable {
/**
* @var string $page name of help page
*/
public $helppage;
/**
* @var string $title A descriptive text for title tooltip
*/
public $title = '';
/**
* @var string $component Component name, the same as in get_string()
*/
public $component = 'moodle';
/**
* @var string $linktext Extra descriptive text next to the icon
*/
public $linktext = '';
/**
* Constructor: sets up the other components in case they are needed
* @param string $page The keyword that defines a help page
* @param string $title A descriptive text for accesibility only
* @param string $component
* @param bool $linktext add extra text to icon
* @return void
*/
public function __construct($helppage, $title, $component = 'moodle') {
if (empty($title)) {
throw new coding_exception('A help_icon object requires a $text parameter');
}
if (empty($helppage)) {
throw new coding_exception('A help_icon object requires a $helppage parameter');
}
$this->helppage = $helppage;
$this->title = $title;
$this->component = $component;
}
}
/**
* Data structure representing a simple form with only one button.
*
* @copyright 2009 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class single_button implements renderable {
/**
* Target url
* @var moodle_url
*/
var $url;
/**
* Button label
* @var string
*/
var $label;
/**
* Form submit method
* @var string post or get
*/
var $method = 'post';
/**
* Wrapping div class
* @var string
* */
var $class = 'singlebutton';
/**
* True if button disabled, false if normal
* @var boolean
*/
var $disabled = false;
/**
* Button tooltip
* @var string
*/
var $tooltip = '';
/**
* Form id
* @var string
*/
var $formid;
/**
* List of attached actions
* @var array of component_action
*/
var $actions = array();
/**
* Constructor
* @param string|moodle_url $url
* @param string $label button text
* @param string $method get or post submit method
*/
public function __construct(moodle_url $url, $label, $method='post') {
$this->url = clone($url);
$this->label = $label;
$this->method = $method;
}
/**
* Shortcut for adding a JS confirm dialog when the button is clicked.
* The message must be a yes/no question.
* @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
* @return void
*/
public function add_confirm_action($confirmmessage) {
$this->add_action(new component_action('click', 'confirm_dialog', array('message' => $confirmmessage)));
}
/**
* Add action to the button.
* @param component_action $action
* @return void
*/
public function add_action(component_action $action) {
$this->actions[] = $action;
}
}
/**
* Data structure describing html link with special action attached.
* @copyright 2010 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class action_link implements renderable {
/**
* Href url
* @var moodle_url
*/
var $url;
/**
* Link text
* @var string HTML fragment
*/
var $text;
/**
* HTML attributes
* @var array
*/
var $attributes;
/**
* List of actions attached to link
* @var array of component_action
*/
var $actions;
/**
* Constructor
* @param string|moodle_url $url
* @param string $text HTML fragment
* @param component_action $action
* @param array $attributes associative array of html link attributes + disabled
*/
public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
$this->url = clone($url);
$this->text = $text;
if ($action) {
$this->add_action($action);
}
}
/**
* Add action to the link.
* @param component_action $action
* @return void
*/
public function add_action(component_action $action) {
$this->actions[] = $action;
}
}
// ==== HTML writer and helper classes, will be probably moved elsewhere ======
/**
* Simple html output class
* @copyright 2009 Tim Hunt, 2010 Petr Skoda
*/
class html_writer {
/**
* Outputs a tag with attributes and contents
* @param string $tagname The name of tag ('a', 'img', 'span' etc.)
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @param string $contents What goes between the opening and closing tags
* @return string HTML fragment
*/
public static function tag($tagname, array $attributes = null, $contents) {
return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
}
/**
* Outputs an opening tag with attributes
* @param string $tagname The name of tag ('a', 'img', 'span' etc.)
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function start_tag($tagname, array $attributes = null) {
return '<' . $tagname . self::attributes($attributes) . '>';
}
/**
* Outputs a closing tag
* @param string $tagname The name of tag ('a', 'img', 'span' etc.)
* @return string HTML fragment
*/
public static function end_tag($tagname) {
return '' . $tagname . '>';
}
/**
* Outputs an empty tag with attributes
* @param string $tagname The name of tag ('input', 'img', 'br' etc.)
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* @return string HTML fragment
*/
public static function empty_tag($tagname, array $attributes = null) {
return '<' . $tagname . self::attributes($attributes) . ' />';
}
/**
* Outputs a HTML attribute and value
* @param string $name The name of the attribute ('src', 'href', 'class' etc.)
* @param string $value The value of the attribute. The value will be escaped with {@link s()}
* @return string HTML fragment
*/
public static function attribute($name, $value) {
if (is_array($value)) {
debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
}
if ($value instanceof moodle_url) {
return ' ' . $name . '="' . $value->out() . '"';
}
$value = trim($value);
if ($value == HTML_ATTR_EMPTY) {
return ' ' . $name . '=""';
} else if ($value || is_numeric($value)) { // We want 0 to be output.
return ' ' . $name . '="' . s($value) . '"';
}
}
/**
* Outputs a list of HTML attributes and values
* @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
* The values will be escaped with {@link s()}
* @return string HTML fragment
*/
public static function attributes(array $attributes = null) {
$attributes = (array)$attributes;
$output = '';
foreach ($attributes as $name => $value) {
$output .= self::attribute($name, $value);
}
return $output;
}
/**
* Generates random html element id.
* @param string $base
* @return string
*/
public static function random_id($base='random') {
return uniqid($base);
}
/**
* Generates a simple html link
* @param string|moodle_url $url
* @param string $text link txt
* @param array $attributes extra html attributes
* @return string HTML fragment
*/
public static function link($url, $text, array $attributes = null) {
$attributes = (array)$attributes;
$attributes['href'] = $url;
return self::tag('a', $attributes, $text);
}
/**
* Generates a simple select form field
* @param array $options associative array value=>label ex.:
* array(1=>'One, 2=>Two)
* it is also possible to specify optgroup as complex label array ex.:
* array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
* array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
* @param string $name name of select element
* @param string|array $selected value or arary of values depending on multiple attribute
* @param array|bool $nothing, add nothing selected option, or false of not added
* @param array $attributes - html select element attributes
* @return string HRML fragment
*/
public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choose'), array $attributes = null) {
$attributes = (array)$attributes;
if (is_array($nothing)) {
foreach ($nothing as $k=>$v) {
if ($v === 'choose' or $v === 'choosedots') {
$nothing[$k] = get_string('choosedots');
}
}
$options = $nothing + $options; // keep keys, do not override
} else if (is_string($nothing) and $nothing !== '') {
// BC
$options = array(''=>$nothing) + $options;
}
// we may accept more values if multiple attribute specified
$selected = (array)$selected;
foreach ($selected as $k=>$v) {
$selected[$k] = (string)$v;
}
if (!isset($attributes['id'])) {
$id = 'menu'.$name;
// name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
$id = str_replace('[', '', $id);
$id = str_replace(']', '', $id);
$attributes['id'] = $id;
}
if (!isset($attributes['class'])) {
$class = 'menu'.$name;
// name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
$class = str_replace('[', '', $class);
$class = str_replace(']', '', $class);
$attributes['class'] = $class;
}
$attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
$attributes['name'] = $name;
$output = '';
foreach ($options as $value=>$label) {
if (is_array($label)) {
// ignore key, it just has to be unique
$output .= self::select_optgroup(key($label), current($label), $selected);
} else {
$output .= self::select_option($label, $value, $selected);
}
}
return self::tag('select', $attributes, $output);
}
private static function select_option($label, $value, array $selected) {
$attributes = array();
$value = (string)$value;
if (in_array($value, $selected, true)) {
$attributes['selected'] = 'selected';
}
$attributes['value'] = $value;
return self::tag('option', $attributes, $label);
}
private static function select_optgroup($groupname, $options, array $selected) {
if (empty($options)) {
return '';
}
$attributes = array('label'=>$groupname);
$output = '';
foreach ($options as $value=>$label) {
$output .= self::select_option($label, $value, $selected);
}
return self::tag('optgroup', $attributes, $output);
}
/**
* Returns hidden input fields created from url parameters.
* @param moodle_url $url
* @param array $exclude list of excluded parameters
* @return string HTML fragment
*/
public static function input_hidden_params(moodle_url $url, array $exclude = null) {
$exclude = (array)$exclude;
$params = $url->params();
foreach ($exclude as $key) {
unset($params[$key]);
}
$output = '';
foreach ($params as $key => $value) {
$attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
$output .= self::empty_tag('input', $attributes)."\n";
}
return $output;
}
/**
* Generate a script tag containing the the specified code.
*
* @param string $js the JavaScript code
* @return string HTML, the code wrapped in \n";
} else {
return '';
}
}
}
// ===============================================================================================
// TODO: Following components will be refactored soon
/**
* Base class for classes representing HTML elements, like html_select.
*
* Handles the id and class attributes.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class html_component {
/**
* @var string value to use for the id attribute of this HTML tag.
*/
public $id = '';
/**
* @var string $alt value to use for the alt attribute of this HTML tag.
*/
public $alt = '';
/**
* @var string $style value to use for the style attribute of this HTML tag.
*/
public $style = '';
/**
* @var array class names to add to this HTML element.
*/
public $classes = array();
/**
* @var string $title The title attributes applicable to any XHTML element
*/
public $title = '';
/**
* An optional array of component_action objects handling the action part of this component.
* @var array $actions
*/
protected $actions = array();
/**
* Compoment constructor.
* @param array $options image attributes such as title, id, alt, style, class
*/
public function __construct(array $options = null) {
// not implemented in this class because we want to set only public properties of this component
renderer_base::apply_component_options($this, $options);
}
/**
* Ensure some class names are an array.
* @param mixed $classes either an array of class names or a space-separated
* string containing class names.
* @return array the class names as an array.
*/
public static function clean_classes($classes) {
if (empty($classes)) {
return array();
} else if (is_array($classes)) {
return $classes;
} else {
return explode(' ', trim($classes));
}
}
/**
* Set the class name array.
* @param mixed $classes either an array of class names or a space-separated
* string containing class names.
* @return void
*/
public function set_classes($classes) {
$this->classes = self::clean_classes($classes);
}
/**
* Add a class name to the class names array.
* @param string $class the new class name to add.
* @return void
*/
public function add_class($class) {
$this->classes[] = $class;
}
/**
* Add a whole lot of class names to the class names array.
* @param mixed $classes either an array of class names or a space-separated
* string containing class names.
* @return void
*/
public function add_classes($classes) {
$this->classes = array_merge($this->classes, self::clean_classes($classes));
}
/**
* Get the class names as a string.
* @return string the class names as a space-separated string. Ready to be put in the class="" attribute.
*/
public function get_classes_string() {
return implode(' ', $this->classes);
}
/**
* Perform any cleanup or final processing that should be done before an
* instance of this class is output. This method is supposed to be called
* only from renderers.
*
* @param renderer_base $output output renderer
* @param moodle_page $page
* @param string $target rendering target
* @return void
*/
public function prepare(renderer_base $output, moodle_page $page, $target) {
$this->classes = array_unique(self::clean_classes($this->classes));
}
/**
* This checks developer do not try to assign a property directly
* if we have a setter for it. Otherwise, the property is set as expected.
* @param string $name The name of the variable to set
* @param mixed $value The value to assign to the variable
* @return void
*/
public function __set($name, $value) {
if ($name == 'class') {
debugging('this way of setting css class has been deprecated. use set_classes() method instead.');
$this->set_classes($value);
} else {
$this->{$name} = $value;
}
}
/**
* Adds a JS action to this component.
* Note: the JS function you write must have only two arguments: (string)event and (object|array)args
* If you want to add an instantiated component_action (or one of its subclasses), give the object as the only parameter
*
* @param mixed $event a DOM event (click, mouseover etc.) or a component_action object
* @param string $jsfunction The name of the JS function to call. required if argument 1 is a string (event)
* @param array $jsfunctionargs An optional array of JS arguments to pass to the function
*/
public function add_action($event, $jsfunction=null, $jsfunctionargs=array()) {
if (empty($this->id)) {
$this->generate_id();
}
if ($event instanceof component_action) {
$this->actions[] = $event;
} else {
if (empty($jsfunction)) {
throw new coding_exception('html_component::add_action requires a JS function argument if the first argument is a string event');
}
$this->actions[] = new component_action($event, $jsfunction, $jsfunctionargs);
}
}
/**
* Internal method for generating a unique ID for the purpose of event handlers.
*/
protected function generate_id() {
$this->id = uniqid(get_class($this));
}
/**
* Returns the array of component_actions.
* @return array Component actions
*/
public function get_actions() {
return $this->actions;
}
/**
* Shortcut for adding a JS confirm dialog when the component is clicked.
* The message must be a yes/no question.
* @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
* @param string $callback The name of a JS function whose scope will be set to the simpleDialog object and have this
* function's arguments set as this.args.
* @return void
*/
public function add_confirm_action($message, $callback=null) {
$this->add_action(new component_action('click', 'confirm_dialog', array('message' => $message, 'callback' => $callback)));
}
/**
* Returns true if this component has an action of the requested type (component_action by default).
* @param string $class The class of the action we are looking for
* @return boolean True if action is found
*/
public function has_action($class='component_action') {
foreach ($this->actions as $action) {
if (get_class($action) == $class) {
return true;
}
}
return false;
}
}
class labelled_html_component extends html_component {
/**
* @var mixed $label The label for that component. String or html_label object
*/
public $label;
/**
* Compoment constructor.
* @param array $options image attributes such as title, id, alt, style, class
*/
public function __construct(array $options = null) {
parent::__construct($options);
}
/**
* Adds a descriptive label to the component.
*
* This can be used in two ways:
*
*
*
* Use the second form when you need to add additional HTML attributes
* to the label and/or JS actions.
*
* @param mixed $text Either the text of the label or a html_label object
* @param text $for The value of the "for" attribute (the associated element's id)
* @return void
*/
public function set_label($text, $for=null) {
if ($text instanceof html_label) {
$this->label = $text;
} else if (!empty($text)) {
$this->label = new html_label();
$this->label->for = $for;
if (empty($for)) {
if (empty($this->id)) {
$this->generate_id();
}
$this->label->for = $this->id;
}
$this->label->text = $text;
}
}
}
/// Components representing HTML elements
/**
* This class represents a label element
*
* @copyright 2009 Nicolas Connault
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class html_label extends html_component {
/**
* @var string $text The text to display in the label
*/
public $text;
/**
* @var string $for The name of the form field this label is associated with
*/
public $for;
/**
* @see html_component::prepare()
* @return void
*/
public function prepare(renderer_base $output, moodle_page $page, $target) {
if (empty($this->text)) {
throw new coding_exception('html_label must have a $text value.');
}
parent::prepare($output, $page, $target);
}
}
/**
* This class hold all the information required to describe a