diff --git a/blocks/classes/output/block_contents.php b/blocks/classes/output/block_contents.php index aeb12971102..6d8f7850e4c 100644 --- a/blocks/classes/output/block_contents.php +++ b/blocks/classes/output/block_contents.php @@ -30,7 +30,7 @@ namespace core_block\output; * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 - * @package core + * @package core_block * @category output */ class block_contents { @@ -51,7 +51,7 @@ class block_contents { /** * @var int All the blocks (or things that look like blocks) printed on * a page are given a unique number that can be used to construct id="" attributes. - * This is set automatically be the {@link prepare()} method. + * This is set automatically be the {@see prepare()} method. * Do not try to set it manually. */ public $skipid; @@ -71,7 +71,7 @@ class block_contents { /** * @var array An array of attribute => value pairs that are put on the outer div of this - * block. {@link $id} and {@link $classes} attributes should be set separately. + * block. {@see $id} and {@see $classes} attributes should be set separately. */ public $attributes; @@ -122,23 +122,24 @@ class block_contents { * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption). * $icon is the icon name. Fed to $OUTPUT->image_url. */ - public $controls = array(); + public $controls = []; /** - * Create new instance of block content - * @param array $attributes + * Create new instance of block content. + * + * @param null|array $attributes */ - public function __construct(array $attributes = null) { + public function __construct(?array $attributes = null) { $this->skipid = self::$idcounter; self::$idcounter += 1; if ($attributes) { - // standard block + // Standard block. $this->attributes = $attributes; } else { - // simple "fake" blocks used in some modules and "Add new block" block - $this->attributes = array('class'=>'block'); + // Simple "fake" blocks used in some modules and "Add new block" block. + $this->attributes = ['class' => 'block']; } } @@ -148,7 +149,7 @@ class block_contents { * @param string $class */ public function add_class($class) { - $this->attributes['class'] .= ' '.$class; + $this->attributes['class'] .= ' ' . $class; } /** diff --git a/blocks/classes/output/block_move_target.php b/blocks/classes/output/block_move_target.php index d698ac21c7d..d305a901daa 100644 --- a/blocks/classes/output/block_move_target.php +++ b/blocks/classes/output/block_move_target.php @@ -28,7 +28,7 @@ use moodle_url; * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 - * @package core + * @package core_block * @category output */ class block_move_target { diff --git a/lib/classes/output/action_link.php b/lib/classes/output/action_link.php index bb094108d05..c34d69ef17a 100644 --- a/lib/classes/output/action_link.php +++ b/lib/classes/output/action_link.php @@ -59,15 +59,17 @@ class action_link implements renderable { * Constructor * @param moodle_url $url * @param string $text HTML fragment - * @param component_action $action - * @param array $attributes associative array of html link attributes + disabled - * @param pix_icon $icon optional pix_icon to render with the link text + * @param null|component_action $action + * @param null|array $attributes associative array of html link attributes + disabled + * @param null|pix_icon $icon optional pix_icon to render with the link text */ - public function __construct(moodle_url $url, + public function __construct( + moodle_url $url, $text, - component_action $action=null, - array $attributes=null, - pix_icon $icon=null) { + ?component_action $action = null, + ?array $attributes = null, + ?pix_icon $icon = null + ) { $this->url = clone($url); $this->text = $text; if (empty($attributes['id'])) { @@ -144,14 +146,14 @@ class action_link implements renderable { $data->classes = isset($attributes['class']) ? $attributes['class'] : ''; unset($attributes['class']); - $data->attributes = array_map(function($key, $value) { + $data->attributes = array_map(function ($key, $value) { return [ 'name' => $key, - 'value' => $value + 'value' => $value, ]; }, array_keys($attributes), $attributes); - $data->actions = array_map(function($action) use ($output) { + $data->actions = array_map(function ($action) use ($output) { return $action->export_for_template($output); }, !empty($this->actions) ? $this->actions : []); $data->hasactions = !empty($this->actions); diff --git a/lib/classes/output/action_menu.php b/lib/classes/output/action_menu.php index 1bbdeb22cc2..588753e652e 100644 --- a/lib/classes/output/action_menu.php +++ b/lib/classes/output/action_menu.php @@ -64,35 +64,35 @@ class action_menu implements renderable, templatable { protected $instance = 0; /** - * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions. + * An array of primary actions. Please use {@see action_menu::add_primary_action()} to add actions. * @var array */ - protected $primaryactions = array(); + protected $primaryactions = []; /** - * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions. + * An array of secondary actions. Please use {@see action_menu::add_secondary_action()} to add actions. * @var array */ - protected $secondaryactions = array(); + protected $secondaryactions = []; /** * An array of attributes added to the container of the action menu. * Initialised with defaults during construction. * @var array */ - public $attributes = array(); + public $attributes = []; /** * An array of attributes added to the container of the primary actions. * Initialised with defaults during construction. * @var array */ - public $attributesprimary = array(); + public $attributesprimary = []; /** * An array of attributes added to the container of the secondary actions. * Initialised with defaults during construction. * @var array */ - public $attributessecondary = array(); + public $attributessecondary = []; /** * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu. @@ -147,27 +147,27 @@ class action_menu implements renderable, templatable { * * @param array $actions An array of actions (action_menu_link|pix_icon|string). */ - public function __construct(array $actions = array()) { + public function __construct(array $actions = []) { static $initialised = 0; $this->instance = $initialised; $initialised++; - $this->attributes = array( - 'id' => 'action-menu-'.$this->instance, + $this->attributes = [ + 'id' => 'action-menu-' . $this->instance, 'class' => 'moodle-actionmenu', - 'data-enhance' => 'moodle-core-actionmenu' - ); - $this->attributesprimary = array( - 'id' => 'action-menu-'.$this->instance.'-menubar', + 'data-enhance' => 'moodle-core-actionmenu', + ]; + $this->attributesprimary = [ + 'id' => 'action-menu-' . $this->instance . '-menubar', 'class' => 'menubar', - ); - $this->attributessecondary = array( - 'id' => 'action-menu-'.$this->instance.'-menu', + ]; + $this->attributessecondary = [ + 'id' => 'action-menu-' . $this->instance . '-menu', 'class' => 'menu', 'data-rel' => 'menu-content', - 'aria-labelledby' => 'action-menu-toggle-'.$this->instance, - 'role' => 'menu' - ); + 'aria-labelledby' => 'action-menu-toggle-' . $this->instance, + 'role' => 'menu', + ]; $this->dropdownalignment = 'dropdown-menu-right'; foreach ($actions as $action) { $this->add($action); @@ -207,8 +207,11 @@ class action_menu implements renderable, templatable { * @param string|null $extraclasses extra classes for the trigger {@see self::set_menu_trigger()} * @throws coding_exception */ - public function set_kebab_trigger(?string $triggername = null, ?core_renderer $output = null, - ?string $extraclasses = '') { + public function set_kebab_trigger( + ?string $triggername = null, + ?core_renderer $output = null, + ?string $extraclasses = '' + ) { global $OUTPUT; if (empty($output)) { $output = $OUTPUT; @@ -307,16 +310,16 @@ class action_menu implements renderable, templatable { /** * Returns the primary actions ready to be rendered. * - * @param core_renderer $output The renderer to use for getting icons. + * @param null|core_renderer $output The renderer to use for getting icons. * @return array */ - public function get_primary_actions(core_renderer $output = null) { + public function get_primary_actions(?core_renderer $output = null) { global $OUTPUT; if ($output === null) { $output = $OUTPUT; } $pixicon = $this->actionicon; - $linkclasses = array('toggle-display'); + $linkclasses = ['toggle-display']; $title = ''; if (!empty($this->menutrigger)) { @@ -328,7 +331,7 @@ class action_menu implements renderable, templatable { 't/edit_menu', '', 'moodle', - array('class' => 'iconsmall actionmenu', 'title' => '') + ['class' => 'iconsmall actionmenu', 'title' => ''] ); $pixicon = $this->actionicon; } @@ -349,14 +352,14 @@ class action_menu implements renderable, templatable { $label = $title; } $actions = $this->primaryactions; - $attributes = array( + $attributes = [ 'class' => implode(' ', $linkclasses), 'title' => $title, 'aria-label' => $label, - 'id' => 'action-menu-toggle-'.$this->instance, + 'id' => 'action-menu-toggle-' . $this->instance, 'role' => 'menuitem', 'tabindex' => '-1', - ); + ]; $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes); if ($this->prioritise) { array_unshift($actions, $link); @@ -395,12 +398,12 @@ class action_menu implements renderable, templatable { if (isset($this->attributessecondary['data-align'])) { // We've already got one set, lets remove the old class so as to avoid troubles. $class = $this->attributessecondary['class']; - $search = 'align-'.$this->attributessecondary['data-align']; + $search = 'align-' . $this->attributessecondary['data-align']; $this->attributessecondary['class'] = str_replace($search, '', $class); } $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button); $this->attributessecondary['data-align'] = $align; - $this->attributessecondary['class'] .= ' align-'.$align; + $this->attributessecondary['class'] .= ' align-' . $align; } /** @@ -411,15 +414,15 @@ class action_menu implements renderable, templatable { */ protected function get_align_string($align) { switch ($align) { - case self::TL : + case self::TL: return 'tl'; - case self::TR : + case self::TR: return 'tr'; - case self::BL : + case self::BL: return 'bl'; - case self::BR : + case self::BR: return 'br'; - default : + default: return 'tl'; } } @@ -502,7 +505,7 @@ class action_menu implements renderable, templatable { $pos = strpos($this->attributes['class'], $class); if ($value === true && $pos === false) { // The value is true and the class has not been set yet. Add it. - $this->attributes['class'] .= ' '.$class; + $this->attributes['class'] .= ' ' . $class; } else if ($value === false && $pos !== false) { // The value is false and the class has been set. Remove it. $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class)); @@ -520,7 +523,7 @@ class action_menu implements renderable, templatable { */ public function set_additional_classes(string $class = '') { if (!empty($this->attributes['class'])) { - $this->attributes['class'] .= " ".$class; + $this->attributes['class'] .= " " . $class; } else { $this->attributes['class'] = $class; } @@ -547,7 +550,7 @@ class action_menu implements renderable, templatable { $data->classes = isset($attributes['class']) ? $attributes['class'] : ''; unset($attributes['class']); - $data->attributes = array_map(function($key, $value) { + $data->attributes = array_map(function ($key, $value) { return [ 'name' => $key, 'value' => $value ]; }, array_keys($attributes), $attributes); diff --git a/lib/classes/output/action_menu/link.php b/lib/classes/output/action_menu/link.php index af440be5ec3..ea6b2da25f2 100644 --- a/lib/classes/output/action_menu/link.php +++ b/lib/classes/output/action_menu/link.php @@ -33,7 +33,6 @@ use stdClass; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class link extends action_link implements renderable { - /** * True if this is a primary action. False if not. * @var bool @@ -49,8 +48,8 @@ class link extends action_link implements renderable { /** * The number of instances of this action menu link (and its subclasses). * - * @deprecated since Moodle 4.4. * @var int + * @deprecated since Moodle 4.4. */ protected static $instance = 1; @@ -63,7 +62,7 @@ class link extends action_link implements renderable { * @param bool $primary Whether this is a primary action or not. * @param array $attributes Any attribtues associated with the action. */ - public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) { + public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = []) { parent::__construct($url, $text, null, $attributes, $icon); $this->primary = (bool)$primary; $this->add_class('menu-action'); @@ -104,10 +103,10 @@ class link extends action_link implements renderable { $data->disabled = !empty($attributes['disabled']); unset($attributes['disabled']); - $data->attributes = array_map(function($key, $value) { + $data->attributes = array_map(function ($key, $value) { return [ 'name' => $key, - 'value' => $value + 'value' => $value, ]; }, array_keys($attributes), $attributes); diff --git a/lib/classes/output/action_menu/link_primary.php b/lib/classes/output/action_menu/link_primary.php index 3a251d93023..c7d314b98ce 100644 --- a/lib/classes/output/action_menu/link_primary.php +++ b/lib/classes/output/action_menu/link_primary.php @@ -36,7 +36,7 @@ class link_primary extends link { * @param string $text * @param array $attributes */ - public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) { + public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = []) { parent::__construct($url, $icon, $text, true, $attributes); } } diff --git a/lib/classes/output/action_menu/link_secondary.php b/lib/classes/output/action_menu/link_secondary.php index 5f71598ac15..dac7767f2ef 100644 --- a/lib/classes/output/action_menu/link_secondary.php +++ b/lib/classes/output/action_menu/link_secondary.php @@ -36,7 +36,7 @@ class link_secondary extends link { * @param string $text * @param array $attributes */ - public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) { + public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = []) { parent::__construct($url, $icon, $text, false, $attributes); } } diff --git a/lib/classes/output/actions/component_action.php b/lib/classes/output/actions/component_action.php index 39b73c218f6..e8af7e60dbf 100644 --- a/lib/classes/output/actions/component_action.php +++ b/lib/classes/output/actions/component_action.php @@ -31,7 +31,6 @@ use stdClass; * @category output */ class component_action implements templatable { - /** * @var string $event The DOM event that will trigger this action when caught */ @@ -48,7 +47,7 @@ class component_action implements templatable { /** * @var array An array of arguments to pass to the JS function */ - public $jsfunctionargs = array(); + public $jsfunctionargs = []; /** * Constructor @@ -56,7 +55,7 @@ class component_action implements templatable { * @param string $jsfunction An optional JS function. Required if jsfunctionargs is given * @param array $jsfunctionargs An array of arguments to pass to the jsfunction */ - public function __construct($event, $jsfunction, $jsfunctionargs=array()) { + public function __construct($event, $jsfunction, $jsfunctionargs = []) { $this->event = $event; $this->jsfunction = $jsfunction; diff --git a/lib/classes/output/actions/confirm_action.php b/lib/classes/output/actions/confirm_action.php index e49d80b3963..f18ce1c1fbd 100644 --- a/lib/classes/output/actions/confirm_action.php +++ b/lib/classes/output/actions/confirm_action.php @@ -37,14 +37,18 @@ class confirm_action extends component_action { */ public function __construct($message, $callback = null, $continuelabel = null, $cancellabel = null) { if ($callback !== null) { - debugging('The callback argument to new confirm_action() has been deprecated.' . + debugging( + 'The callback argument to new confirm_action() has been deprecated.' . ' If you need to use a callback, please write Javascript to use moodle-core-notification-confirmation ' . 'and attach to the provided events.', - DEBUG_DEVELOPER); + DEBUG_DEVELOPER, + ); } - parent::__construct('click', 'M.util.show_confirm_dialog', array( - 'message' => $message, - 'continuelabel' => $continuelabel, 'cancellabel' => $cancellabel)); + parent::__construct('click', 'M.util.show_confirm_dialog', [ + 'message' => $message, + 'continuelabel' => $continuelabel, + 'cancellabel' => $cancellabel, + ]); } } diff --git a/lib/classes/output/actions/popup_action.php b/lib/classes/output/actions/popup_action.php index bf1d20af3a6..9dcd3291f0a 100644 --- a/lib/classes/output/actions/popup_action.php +++ b/lib/classes/output/actions/popup_action.php @@ -37,20 +37,21 @@ class popup_action extends component_action { /** * @var array An array of parameters that will be passed to the openpopup JS function */ - public $params = array( - 'height' => 400, - 'width' => 500, - 'top' => 0, - 'left' => 0, - 'menubar' => false, - 'location' => false, - 'scrollbars' => true, - 'resizable' => true, - 'toolbar' => true, - 'status' => true, - 'directories' => false, - 'fullscreen' => false, - 'dependent' => true); + public $params = [ + 'height' => 400, + 'width' => 500, + 'top' => 0, + 'left' => 0, + 'menubar' => false, + 'location' => false, + 'scrollbars' => true, + 'resizable' => true, + 'toolbar' => true, + 'status' => true, + 'directories' => false, + 'fullscreen' => false, + 'dependent' => true, + ]; /** * Constructor @@ -60,18 +61,18 @@ class popup_action extends component_action { * @param string $name The JS function to call for the popup (default 'popup') * @param array $params An array of popup parameters */ - public function __construct($event, $url, $name='popup', $params=array()) { + public function __construct($event, $url, $name = 'popup', $params = []) { global $CFG; $url = new moodle_url($url); if ($name) { - $_name = $name; - if (($_name = preg_replace("/\s/", '_', $_name)) != $name) { + $checkname = $name; + if (($checkname = preg_replace("/\s/", '_', $checkname)) != $name) { throw new coding_exception( - 'The $name of a popup window shouldn\'t contain spaces - string modified. ' . $name . ' changed to ' . $_name, + "The {$name} of a popup window shouldn't contain spaces - string modified. {$name} changed to {$checkname}", ); - $name = $_name; + $name = $checkname; } } else { $name = 'popup'; @@ -83,7 +84,7 @@ class popup_action extends component_action { } } - $attributes = array('url' => $url->out(false), 'name' => $name, 'options' => $this->get_js_options($params)); + $attributes = ['url' => $url->out(false), 'name' => $name, 'options' => $this->get_js_options($params)]; if (!empty($params['fullscreen'])) { $attributes['fullscreen'] = 1; } @@ -102,7 +103,7 @@ class popup_action extends component_action { foreach ($this->params as $var => $val) { if (is_string($val) || is_int($val)) { $jsoptions .= "$var=$val,"; - } elseif (is_bool($val)) { + } else if (is_bool($val)) { $jsoptions .= ($val) ? "$var," : "$var=0,"; } } diff --git a/lib/classes/output/activity_header.php b/lib/classes/output/activity_header.php index 10c4b7f0c24..01bfd470931 100644 --- a/lib/classes/output/activity_header.php +++ b/lib/classes/output/activity_header.php @@ -64,8 +64,10 @@ class activity_header implements renderable, templatable { $this->title = format_string($page->activityrecord->name); } - if (empty($layoutoptions['nodescription']) && !empty($page->activityrecord->intro) && - trim($page->activityrecord->intro)) { + if ( + empty($layoutoptions['nodescription']) && !empty($page->activityrecord->intro) && + trim($page->activityrecord->intro) + ) { $this->description = format_module_intro($this->page->activityname, $page->activityrecord, $page->cm->id); } } diff --git a/lib/classes/output/choicelist.php b/lib/classes/output/choicelist.php index 57d9bdc71ee..65a47919a54 100644 --- a/lib/classes/output/choicelist.php +++ b/lib/classes/output/choicelist.php @@ -97,13 +97,13 @@ class choicelist implements named_templatable, renderable { * @return \stdClass[] */ public function get_selectable_options(): array { - $selectableOptions = []; + $selectableoptions = []; foreach ($this->options as $option) { if ($option['value'] !== $this->selected && !$option['disabled']) { - $selectableOptions[] = (object) $option; + $selectableoptions[] = (object) $option; } } - return $selectableOptions; + return $selectableoptions; } /** diff --git a/lib/classes/output/chooser.php b/lib/classes/output/chooser.php index 268e4285c43..0f7c86df65a 100644 --- a/lib/classes/output/chooser.php +++ b/lib/classes/output/chooser.php @@ -36,7 +36,6 @@ use stdClass; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class chooser implements renderable, templatable { - /** @var moodle_url The form action URL. */ public $actionurl; /** @var lang_string The instructions to display. */ @@ -81,7 +80,7 @@ class chooser implements renderable, templatable { $this->params[] = [ 'name' => $name, 'value' => $value, - 'id' => $id + 'id' => $id, ]; } @@ -120,11 +119,10 @@ class chooser implements renderable, templatable { $data->sesskey = sesskey(); $data->title = (string) $this->title; - $data->sections = array_map(function($section) use ($output) { + $data->sections = array_map(function ($section) use ($output) { return $section->export_for_template($output); }, $this->sections); return $data; } - } diff --git a/lib/classes/output/chooser_item.php b/lib/classes/output/chooser_item.php index e1a7e99281a..c90d6f115b8 100644 --- a/lib/classes/output/chooser_item.php +++ b/lib/classes/output/chooser_item.php @@ -36,7 +36,6 @@ use stdClass; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class chooser_item implements renderable, templatable { - /** @var string An identifier for the item. */ public $id; /** @var string The label of this item. */ @@ -89,11 +88,17 @@ class chooser_item implements renderable, templatable { $data->description = ''; if (!empty($this->description)) { - list($data->description) = \core_external\util::format_text((string) $this->description, FORMAT_MARKDOWN, - $this->context->id, null, null, null, $options); + [$data->description] = \core_external\util::format_text( + (string) $this->description, + FORMAT_MARKDOWN, + $this->context->id, + null, + null, + null, + $options + ); } return $data; } - } diff --git a/lib/classes/output/chooser_section.php b/lib/classes/output/chooser_section.php index ed071058cc0..b4e85d24581 100644 --- a/lib/classes/output/chooser_section.php +++ b/lib/classes/output/chooser_section.php @@ -35,7 +35,6 @@ use stdClass; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class chooser_section implements renderable, templatable { - /** @var string $id An identifier for the section. */ public $id; /** @var lang_string $label The label of the section. */ @@ -66,10 +65,9 @@ class chooser_section implements renderable, templatable { $data = new stdClass(); $data->id = $this->id; $data->label = (string) $this->label; - $data->items = array_map(function($item) use ($output) { + $data->items = array_map(function ($item) use ($output) { return $item->export_for_template($output); }, array_values($this->items)); return $data; } - } diff --git a/lib/classes/output/comboboxsearch.php b/lib/classes/output/comboboxsearch.php index b8ec7ea8b79..f0120c8874a 100644 --- a/lib/classes/output/comboboxsearch.php +++ b/lib/classes/output/comboboxsearch.php @@ -21,12 +21,11 @@ use core\exception\moodle_exception; /** * Renderable class for the comboboxsearch. * - * @package core_output + * @package core * @copyright 2022 Mathew May * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class comboboxsearch implements renderable, templatable { - /** @var bool $renderlater Should the dropdown render straightaway? We sometimes need to output the component without all of the * data and leave the rendering of any defaults and actual data to the caller. We will give you a basic placeholder that can * then be easily replaced.*/ @@ -50,7 +49,7 @@ class comboboxsearch implements renderable, templatable { /** @var null|string $buttonheader If the button item in the tertiary nav needs an extra top header for context. */ protected $buttonheader; - /** @var boolean $usesbutton Whether to provide a A11y button. */ + /** @var bool $usesbutton Whether to provide a A11y button. */ protected $usesbutton; /** @var null|string $label The label of the combobox. */ @@ -96,15 +95,16 @@ class comboboxsearch implements renderable, templatable { throw new moodle_exception( 'incorrectdropdownvars', 'core', - '', null, + '', + null, 'Dropdown content must be set to render later.' ); } if ($usebutton && !$label) { debugging( - 'You have requested to use the button but have not provided a label for the combobox.', - DEBUG_DEVELOPER + 'You have requested to use the button but have not provided a label for the combobox.', + DEBUG_DEVELOPER ); } @@ -137,7 +137,7 @@ class comboboxsearch implements renderable, templatable { public function export_for_template(renderer_base $output): array { return [ 'renderlater' => $this->renderlater, - 'buttoncontent' => $this->buttoncontent , + 'buttoncontent' => $this->buttoncontent, 'dropdowncontent' => $this->dropdowncontent, 'parentclasses' => $this->parentclasses, 'buttonclasses' => $this->buttonclasses, diff --git a/lib/classes/output/context_header.php b/lib/classes/output/context_header.php index fc6a056118f..b3030ced3af 100644 --- a/lib/classes/output/context_header.php +++ b/lib/classes/output/context_header.php @@ -26,18 +26,15 @@ namespace core\output; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class context_header implements renderable, templatable { -/** - * @var string $heading Main heading. - */ + /** @var string $heading Main heading */ public $heading; - /** - * @var int $headinglevel Main heading 'h' tag level. - */ + + /** @var int $headinglevel Main heading 'h' tag level */ public $headinglevel; - /** - * @var string|null $imagedata HTML code for the picture in the page header. - */ + + /** @var string|null $imagedata HTML code for the picture in the page header */ public $imagedata; + /** * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header. * array elements - title => alternate text for the image, or if no image is available the button text. @@ -47,9 +44,8 @@ class context_header implements renderable, templatable { * page => page object. Don't include if the image is an external image. */ public $additionalbuttons; - /** - * @var string $prefix A string that is before the title. - */ + + /** @var string $prefix A string that is before the title */ public $prefix; /** @@ -62,7 +58,6 @@ class context_header implements renderable, templatable { * @param string $prefix Text that precedes the heading. */ public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) { - $this->heading = $heading; $this->headinglevel = $headinglevel; $this->imagedata = $imagedata; @@ -101,8 +96,10 @@ class context_header implements renderable, templatable { $class = 'btn'; } // Add the bootstrap 'btn' class for formatting. - $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'], - array('class' => $class)); + $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge( + $button['linkattributes'], + ['class' => $class] + ); } } diff --git a/lib/classes/output/core_renderer.php b/lib/classes/output/core_renderer.php index 038ef4a7c5d..e56a8dbeeea 100644 --- a/lib/classes/output/core_renderer.php +++ b/lib/classes/output/core_renderer.php @@ -69,36 +69,36 @@ class core_renderer extends renderer_base { * Do NOT use, please use main_content() ?> * in layout files instead. * @deprecated - * @var string used in {@link core_renderer::header()}. + * @var string used in {@see core_renderer::header()}. */ const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]'; /** - * @var string Used to pass information from {@link core_renderer::doctype()} to - * {@link core_renderer::standard_head_html()}. + * @var string Used to pass information from {@see core_renderer::doctype()} to + * @see core_renderer::standard_head_html() */ protected $contenttype; /** - * @var string Used by {@link core_renderer::redirect_message()} method to communicate - * with {@link core_renderer::header()}. + * @var string Used by {@see core_renderer::redirect_message()} method to communicate + * with {@see core_renderer::header()}. */ protected $metarefreshtag = ''; /** * @var string Unique token for the closing HTML */ - protected $unique_end_html_token; + protected $unique_end_html_token; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore /** * @var string Unique token for performance information */ - protected $unique_performance_info_token; + protected $unique_performance_info_token; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore /** * @var string Unique token for the main content. */ - protected $unique_main_content_token; + protected $unique_main_content_token; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore /** @var custom_menu_item language The language menu if created */ protected $language = null; @@ -120,9 +120,9 @@ class core_renderer extends renderer_base { $this->page = $page; $this->target = $target; - $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%'; - $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%'; - $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']'; + $this->unique_end_html_token = '%%ENDHTML-' . sesskey() . '%%'; + $this->unique_performance_info_token = '%%PERFORMANCEINFO-' . sesskey() . '%%'; + $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - ' . sesskey() . ']'; } /** @@ -135,11 +135,9 @@ class core_renderer extends renderer_base { if ($this->page->theme->doctype === 'html5') { $this->contenttype = 'text/html; charset=utf-8'; return "\n"; - } else if ($this->page->theme->doctype === 'xhtml5') { $this->contenttype = 'application/xhtml+xml; charset=utf-8'; return "\n"; - } else { // legacy xhtml 1.0 $this->contenttype = 'text/html; charset=utf-8'; @@ -207,16 +205,16 @@ class core_renderer extends renderer_base { $hook->add_html('' . "\n"); $hook->add_html('' . "\n"); - // This is only set by the {@link redirect()} method + // This is only set by the {@see redirect()} method $hook->add_html($this->metarefreshtag); // Check if a periodic refresh delay has been set and make sure we arn't // already meta refreshing - if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) { + if ($this->metarefreshtag == '' && $this->page->periodicrefreshdelay !== null) { $hook->add_html( html_writer::empty_tag('meta', [ 'http-equiv' => 'refresh', - 'content' => $this->page->periodicrefreshdelay . ';url='.$this->page->url->out(), + 'content' => $this->page->periodicrefreshdelay . ';url=' . $this->page->url->out(), ]), ); } @@ -231,14 +229,14 @@ class core_renderer extends renderer_base { if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) { // This is a horrifically bad way to handle focus but it is passed in // through messy formslib::moodleform - $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2])); - } else if (strpos($focus, '.')!==false) { + $this->page->requires->js_function_call('old_onload_focus', [$matches[1], $matches[2]]); + } else if (strpos($focus, '.') !== false) { // Old style of focus, bad way to do it debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER); $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2)); } else { // Focus element with given id - $this->page->requires->js_function_call('focuscontrol', array($focus)); + $this->page->requires->js_function_call('focuscontrol', [$focus]); } } @@ -262,13 +260,17 @@ class core_renderer extends renderer_base { // List alternate versions. foreach ($this->page->alternateversions as $type => $alt) { - $output .= html_writer::empty_tag('link', array('rel' => 'alternate', - 'type' => $type, 'title' => $alt->title, 'href' => $alt->url)); + $output .= html_writer::empty_tag('link', [ + 'rel' => 'alternate', + 'type' => $type, + 'title' => $alt->title, + 'href' => $alt->url, + ]); } // Add noindex tag if relevant page and setting applied. $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0; - $loginpages = array('login-index', 'login-signup'); + $loginpages = ['login-index', 'login-signup']; if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) { if (!isset($CFG->additionalhtmlhead)) { $CFG->additionalhtmlhead = ''; @@ -277,7 +279,7 @@ class core_renderer extends renderer_base { } if (!empty($CFG->additionalhtmlhead)) { - $output .= "\n".$CFG->additionalhtmlhead; + $output .= "\n" . $CFG->additionalhtmlhead; } if ($this->page->pagelayout == 'frontpage') { @@ -300,7 +302,7 @@ class core_renderer extends renderer_base { global $CFG; $output = $this->page->requires->get_top_of_body_code($this); if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) { - $output .= "\n".$CFG->additionalhtmltopofbody; + $output .= "\n" . $CFG->additionalhtmltopofbody; } // Allow components to add content to the top of the body. @@ -342,11 +344,15 @@ class core_renderer extends renderer_base { } $output .= $this->box_end(); - $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer', - array(array('timeleftinsec' => $timeleft))); + $this->page->requires->yui_module( + 'moodle-core-maintenancemodetimer', + 'M.core.maintenancemodetimer', + [['timeleftinsec' => $timeleft]] + ); $this->page->requires->strings_for_js( - array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'), - 'admin'); + ['maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'], + 'admin' + ); } return $output; } @@ -371,7 +377,7 @@ class core_renderer extends renderer_base { if ($this->page->devicetypeinuse == 'legacy') { // The legacy theme is in use print the notification - $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse')); + $output .= html_writer::tag('div', get_string('legacythemeinuse'), ['class' => 'legacythemeinuse']); } // Get links to switch device types (only shown for users not on a default device) @@ -400,21 +406,26 @@ class core_renderer extends renderer_base { $output .= $this->unique_performance_info_token; if (!empty($CFG->debugpageinfo)) { - $output .= '
' . get_string('pageinfodebugsummary', 'core_admin', - $this->page->debug_summary()) . '
'; + $output .= '
' . get_string( + 'pageinfodebugsummary', + 'core_admin', + $this->page->debug_summary() + ) . '
'; } if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode - // Add link to profiling report if necessary if (function_exists('profiling_is_running') && profiling_is_running()) { $txt = get_string('profiledscript', 'admin'); $title = get_string('profiledscriptview', 'admin'); $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT); - $link= '' . $txt . ''; + $link = '' . $txt . ''; $output .= '
' . $link . '
'; } - $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1, - 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false))); + $purgeurl = new moodle_url('/admin/purgecaches.php', [ + 'confirm' => 1, + 'sesskey' => sesskey(), + 'returnurl' => $this->page->url->out_as_local_url(false), + ]); $output .= '
' . html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '
'; @@ -427,7 +438,7 @@ class core_renderer extends renderer_base { $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl)); $validatorlinks = [ html_writer::link($nuurl, get_string('validatehtml')), - html_writer::link($waveurl, get_string('wcagcheck')) + html_writer::link($waveurl, get_string('wcagcheck')), ]; $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']); $output .= html_writer::div($validatorlinkslist, 'validators'); @@ -448,7 +459,7 @@ class core_renderer extends renderer_base { // This is an unfortunate hack. DO NO EVER add anything more here. // DO NOT add classes. // DO NOT add an id. - return '
'.$this->unique_main_content_token.'
'; + return '
' . $this->unique_main_content_token . '
'; } /** @@ -481,8 +492,10 @@ class core_renderer extends renderer_base { public function activity_navigation() { // First we should check if we want to add navigation. $context = $this->page->context; - if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop') - || $context->contextlevel != CONTEXT_MODULE) { + if ( + ($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop') + || $context->contextlevel != CONTEXT_MODULE + ) { return ''; } @@ -496,8 +509,10 @@ class core_renderer extends renderer_base { // If the theme implements course index and the current course format uses course index and the current // page layout is not 'frametop' (this layout does not support course index), show no links. - if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() && - $this->page->pagelayout !== 'frametop') { + if ( + $this->page->theme->usescourseindex && $courseformat->uses_course_index() && + $this->page->pagelayout !== 'frametop' + ) { return ''; } @@ -525,7 +540,7 @@ class core_renderer extends renderer_base { $modname .= ' ' . get_string('hiddenwithbrackets'); } // Module URL. - $linkurl = new moodle_url($module->url, array('forceview' => 1)); + $linkurl = new moodle_url($module->url, ['forceview' => 1]); // Add module URL (as key) and name (as value) to the activity list array. $activitylist[$linkurl->out(false)] = $modname; } @@ -570,12 +585,12 @@ class core_renderer extends renderer_base { public function standard_end_of_body_html() { global $CFG; - // This function is normally called from a layout.php file in {@link core_renderer::header()} + // This function is normally called from a layout.php file in {@see core_renderer::header()} // but some of the content won't be known until later, so we return a placeholder - // for now. This will be replaced with the real content in {@link core_renderer::footer()}. + // for now. This will be replaced with the real content in {@see core_renderer::footer()}. $output = ''; if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) { - $output .= "\n".$CFG->additionalhtmlfooter; + $output .= "\n" . $CFG->additionalhtmlfooter; } $output .= $this->unique_end_html_token; return $output; @@ -628,8 +643,8 @@ class core_renderer extends renderer_base { $fullname = fullname($realuser); if ($withlinks) { $loginastitle = get_string('loginas'); - $realuserinfo = " [wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\""; - $realuserinfo .= "title =\"".$loginastitle."\">$fullname] "; + $realuserinfo = " [wwwroot/course/loginas.php?id=$course->id&sesskey=" . sesskey() . "\""; + $realuserinfo .= "title =\"" . $loginastitle . "\">$fullname] "; } else { $realuserinfo = " [$fullname] "; } @@ -654,7 +669,7 @@ class core_renderer extends renderer_base { } else { $username = $fullname; } - if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) { + if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', ['id' => $USER->mnethostid])) { if ($withlinks) { $username .= " from wwwroot}\">{$idprovider->name}"; } else { @@ -662,34 +677,34 @@ class core_renderer extends renderer_base { } } if (isguestuser()) { - $loggedinas = $realuserinfo.get_string('loggedinasguest'); + $loggedinas = $realuserinfo . get_string('loggedinasguest'); if (!$loginpage && $withlinks) { - $loggedinas .= " (".get_string('login').')'; + $loggedinas .= " (" . get_string('login') . ')'; } } else if (is_role_switched($course->id)) { // Has switched roles $rolename = ''; - if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) { - $rolename = ': '.role_get_name($role, $context); + if ($role = $DB->get_record('role', ['id' => $USER->access['rsw'][$context->path]])) { + $rolename = ': ' . role_get_name($role, $context); } - $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename; + $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename; if ($withlinks) { - $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false))); - $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')'; + $url = new moodle_url('/course/switchrole.php', ['id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false)]); + $loggedinas .= ' (' . html_writer::tag('a', get_string('switchrolereturn'), ['href' => $url]) . ')'; } } else { - $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username); + $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username); if ($withlinks) { - $loggedinas .= " (wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').')'; + $loggedinas .= " (wwwroot/login/logout.php?sesskey=" . sesskey() . "\">" . get_string('logout') . ')'; } } } else { $loggedinas = get_string('loggedinnot', 'moodle'); if (!$loginpage && $withlinks) { - $loggedinas .= " (".get_string('login').')'; + $loggedinas .= " (" . get_string('login') . ')'; } } - $loggedinas = '
'.$loggedinas.'
'; + $loggedinas = '
' . $loggedinas . '
'; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); @@ -702,8 +717,11 @@ class core_renderer extends renderer_base { $a->attempts = $count; $loggedinas .= get_string('failedloginattempts', '', $a); if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) { - $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1, - 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')'; + $loggedinas .= ' (' . html_writer::link(new moodle_url('/report/log/index.php', [ + 'chooselog' => 1, + 'id' => 0, + 'modid' => 'site_errors', + ]), get_string('logs')) . ')'; } $loggedinas .= ''; } @@ -724,11 +742,11 @@ class core_renderer extends renderer_base { // In fact the login pages should be only these two pages and as exposing this as an option for all pages // could lead to abuse (or at least unneedingly complex code) the hack is the way to go. return in_array( - $this->page->url->out_as_local_url(false, array()), - array( + $this->page->url->out_as_local_url(false, []), + [ '/login/index.php', '/login/forgot_password.php', - ) + ] ); } @@ -744,21 +762,18 @@ class core_renderer extends renderer_base { // Special case for site home page - please do not remove return ''; - + '' . get_string('moodlelogo') . ''; } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) { // Special case for during install/upgrade. - return ''; } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) { return ''; - } else { return ''; + format_string($this->page->course->shortname, true, ['context' => $this->page->context]) . ''; } } @@ -783,7 +798,6 @@ class core_renderer extends renderer_base { * @return string The HTML to display to the user before dying, may contain * meta refresh, javascript refresh, and may have set header redirects */ - public function redirect_message( $encodedurl, $message, @@ -795,36 +809,36 @@ class core_renderer extends renderer_base { $url = str_replace('&', '&', $encodedurl); switch ($this->page->state) { - case moodle_page::STATE_BEFORE_HEADER : + case moodle_page::STATE_BEFORE_HEADER: // No output yet it is safe to delivery the full arsenal of redirect methods if (!$debugdisableredirect) { // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time. - $this->metarefreshtag = ''."\n"; - $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3)); + $this->metarefreshtag = '' . "\n"; + $this->page->requires->js_function_call('document.location.replace', [$url], false, ($delay + 3)); } $output = $this->header(); break; - case moodle_page::STATE_PRINTING_HEADER : + case moodle_page::STATE_PRINTING_HEADER: // We should hopefully never get here throw new coding_exception('You cannot redirect while printing the page header'); break; - case moodle_page::STATE_IN_BODY : + case moodle_page::STATE_IN_BODY: // We really shouldn't be here but we can deal with this debugging("You should really redirect before you start page output"); if (!$debugdisableredirect) { - $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay); + $this->page->requires->js_function_call('document.location.replace', [$url], false, $delay); } $output = $this->opencontainers->pop_all_but_last(); break; - case moodle_page::STATE_DONE : + case moodle_page::STATE_DONE: // Too late to be calling redirect now throw new coding_exception('You cannot redirect after the entire page has been generated'); break; } $output .= $this->notification($message, $messagetype); - $output .= '
('. get_string('continue') .')
'; + $output .= '
(' . get_string('continue') . ')
'; if ($debugdisableredirect) { - $output .= '

'.get_string('erroroutput', 'error').'

'; + $output .= '

' . get_string('erroroutput', 'error') . '

'; } $output .= $this->footer(); return $output; @@ -896,8 +910,10 @@ class core_renderer extends renderer_base { } // If this theme version is below 2.4 release and this is a course view page - if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) && - $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) { + if ( + (!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) && + $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE) + ) { // check if course content header/footer have not been output during render of theme layout $coursecontentheader = $this->course_content_header(true); $coursecontentfooter = $this->course_content_footer(true); @@ -908,7 +924,7 @@ class core_renderer extends renderer_base { // Besides the content header and footer are not displayed on any other course page debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER); $header .= $coursecontentheader; - $footer = $coursecontentfooter. $footer; + $footer = $coursecontentfooter . $footer; } } @@ -981,12 +997,14 @@ class core_renderer extends renderer_base { // If the output buffer was off then we render a placeholder and stream the // performance debugging into it at the very end in the shutdown handler. $PERF->perfdebugdeferred = true; - $performanceinfo .= html_writer::tag('div', + $performanceinfo .= html_writer::tag( + 'div', get_string('perfdebugdeferred', 'admin'), [ 'id' => 'perfdebugfooter', 'style' => 'min-height: 30em', - ]); + ] + ); } else { $perf = get_performance_info(); $performanceinfo = $perf['html']; @@ -1002,10 +1020,10 @@ class core_renderer extends renderer_base { // Only show notifications when the current page has a context id. if (!empty($this->page->context->id)) { - $this->page->requires->js_call_amd('core/notification', 'init', array( + $this->page->requires->js_call_amd('core/notification', 'init', [ $this->page->context->id, - \core\notification::fetch_as_array($this) - )); + \core\notification::fetch_as_array($this), + ]); } $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer); @@ -1062,19 +1080,19 @@ class core_renderer extends renderer_base { $bodynotifications = ''; foreach ($notifications as $notification) { $bodynotifications .= $this->render_from_template( - $notification->get_template_name(), - $notification->export_for_template($this) - ); + $notification->get_template_name(), + $notification->export_for_template($this) + ); } - $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications')); + $output = html_writer::span($bodynotifications, 'notifications', ['id' => 'user-notifications']); if ($this->page->course->id == SITEID) { // return immediately and do not include /course/lib.php if not necessary return $output; } - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); $functioncalled = true; $courseformat = course_get_format($this->page->course); if (($obj = $courseformat->course_content_header()) !== null) { @@ -1102,7 +1120,7 @@ class core_renderer extends renderer_base { return ''; } $functioncalled = true; - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); $courseformat = course_get_format($this->page->course); if (($obj = $courseformat->course_content_footer()) !== null) { return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer'); @@ -1122,7 +1140,7 @@ class core_renderer extends renderer_base { // return immediately and do not include /course/lib.php if not necessary return ''; } - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); $courseformat = course_get_format($this->page->course); if (($obj = $courseformat->course_header()) !== null) { return $courseformat->get_renderer($this->page)->render($obj); @@ -1142,7 +1160,7 @@ class core_renderer extends renderer_base { // return immediately and do not include /course/lib.php if not necessary return ''; } - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); $courseformat = course_get_format($this->page->course); if (($obj = $courseformat->course_footer()) !== null) { return $courseformat->get_renderer($this->page)->render($obj); @@ -1209,7 +1227,7 @@ class core_renderer extends renderer_base { /** * Returns lang menu or '', this method also checks forcing of languages in courses. * - * This function calls {@link core_renderer::render_single_select()} to actually display the language menu. + * This function calls {@see core_renderer::render_single_select()} to actually display the language menu. * * @return string The lang menu HTML or empty string */ @@ -1225,8 +1243,8 @@ class core_renderer extends renderer_base { /** * Output the row of editing icons for a block, as defined by the controls array. * - * @param array $controls an array like {@link block_contents::$controls}. - * @param string $blockid The ID given to the block. + * @param array $actions an array like {@see block_contents::$controls}. + * @param null|string $blockid The ID given to the block. * @return string HTML fragment. */ public function block_controls($actions, $blockid = null) { @@ -1235,7 +1253,7 @@ class core_renderer extends renderer_base { } $menu = new action_menu($actions); if ($blockid !== null) { - $menu->set_owner_selector('#'.$blockid); + $menu->set_owner_selector('#' . $blockid); } $menu->attributes['class'] .= ' block-control-actions commands'; return $this->render($menu); @@ -1262,7 +1280,7 @@ class core_renderer extends renderer_base { 'name' => $name, 'value' => $value, 'rows' => $rows, - 'cols' => $cols + 'cols' => $cols, ]; return $this->render_from_template('core_form/editor_textarea', $context); @@ -1451,18 +1469,18 @@ class core_renderer extends renderer_base { */ public function list_block_contents($icons, $items) { $row = 0; - $lis = array(); + $lis = []; foreach ($items as $key => $string) { - $item = html_writer::start_tag('li', array('class' => 'r' . $row)); - if (!empty($icons[$key])) { //test if the content has an assigned icon - $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0')); + $item = html_writer::start_tag('li', ['class' => 'r' . $row]); + if (!empty($icons[$key])) { // test if the content has an assigned icon + $item .= html_writer::tag('div', $icons[$key], ['class' => 'icon column c0']); } - $item .= html_writer::tag('div', $string, array('class' => 'column c1')); + $item .= html_writer::tag('div', $string, ['class' => 'column c1']); $item .= html_writer::end_tag('li'); $lis[] = $item; $row = 1 - $row; // Flip even/odd. } - return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist')); + return html_writer::tag('ul', implode("\n", $lis), ['class' => 'unlist']); } /** @@ -1475,7 +1493,7 @@ class core_renderer extends renderer_base { public function blocks_for_region($region, $fakeblocksonly = false) { $blockcontents = $this->page->blocks->get_content_for_region($region, $this); $lastblock = null; - $zones = array(); + $zones = []; foreach ($blockcontents as $bc) { if ($bc instanceof block_contents) { $zones[] = $bc->title; @@ -1523,23 +1541,23 @@ class core_renderer extends renderer_base { } else { $position = get_string('moveblockafter', 'block', $previous); } - return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget')); + return html_writer::tag('a', html_writer::tag('span', $position, ['class' => 'accesshide']), ['href' => $target->url, 'class' => 'blockmovetarget']); } /** * Renders a special html link with attached action * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_action_link()} instead. + * {@see core_renderer::render_action_link()} instead. * * @param string|moodle_url $url * @param string $text HTML fragment - * @param component_action $action - * @param array $attributes associative array of html link attributes + disabled - * @param pix_icon optional pix icon to render with the link + * @param null|component_action $action + * @param null|array $attributes associative array of html link attributes + disabled + * @param null|pix_icon optional pix icon to render with the link * @return string HTML fragment */ - public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) { + public function action_link($url, $text, ?component_action $action = null, ?array $attributes = null, $icon = null) { if (!($url instanceof moodle_url)) { $url = new moodle_url($url); } @@ -1552,7 +1570,7 @@ class core_renderer extends renderer_base { * Renders an action_link object. * * The provided link is renderer and the HTML returned. At the same time the - * associated actions are setup in JS by {@link core_renderer::add_action_handler()} + * associated actions are setup in JS by {@see core_renderer::add_action_handler()} * * @param action_link $link * @return string HTML fragment @@ -1564,22 +1582,28 @@ class core_renderer extends renderer_base { /** * Renders an action_icon. * - * This function uses the {@link core_renderer::action_link()} method for the + * This function uses the {@see core_renderer::action_link()} method for the * most part. What it does different is prepare the icon as HTML and use it * as the link text. * * Theme developers: If you want to change how action links and/or icons are rendered, - * consider overriding function {@link core_renderer::render_action_link()} and - * {@link core_renderer::render_pix_icon()}. + * consider overriding function {@see core_renderer::render_action_link()} and + * {@see core_renderer::render_pix_icon()}. * * @param string|moodle_url $url A string URL or moodel_url * @param pix_icon $pixicon - * @param component_action $action - * @param array $attributes associative array of html link attributes + disabled + * @param null|component_action $action + * @param null|array $attributes associative array of html link attributes + disabled * @param bool $linktext show title next to image in link * @return string HTML fragment */ - public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) { + public function action_icon( + $url, + pix_icon $pixicon, + ?component_action $action = null, + ?array $attributes = null, + $linktext = false, + ) { if (!($url instanceof moodle_url)) { $url = new moodle_url($url); } @@ -1603,7 +1627,7 @@ class core_renderer extends renderer_base { $icon = $this->render($pixicon); - return $this->action_link($url, $text.$icon, $action, $attributes); + return $this->action_link($url, $text . $icon, $action, $attributes); } /** @@ -1630,11 +1654,19 @@ class core_renderer extends renderer_base { $continue->type = single_button::BUTTON_PRIMARY; } } else if (is_string($continue)) { - $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post', - $displayoptions['type'] ?? single_button::BUTTON_PRIMARY); + $continue = new single_button( + new moodle_url($continue), + $displayoptions['continuestr'], + 'post', + $displayoptions['type'] ?? single_button::BUTTON_PRIMARY + ); } else if ($continue instanceof moodle_url) { - $continue = new single_button($continue, $displayoptions['continuestr'], 'post', - $displayoptions['type'] ?? single_button::BUTTON_PRIMARY); + $continue = new single_button( + $continue, + $displayoptions['continuestr'], + 'post', + $displayoptions['type'] ?? single_button::BUTTON_PRIMARY + ); } else { throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.'); } @@ -1650,10 +1682,10 @@ class core_renderer extends renderer_base { } $attributes = [ - 'role'=>'alertdialog', - 'aria-labelledby'=>'modal-header', - 'aria-describedby'=>'modal-body', - 'aria-modal'=>'true' + 'role' => 'alertdialog', + 'aria-labelledby' => 'modal-header', + 'aria-describedby' => 'modal-body', + 'aria-modal' => 'true', ]; $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes); @@ -1662,8 +1694,8 @@ class core_renderer extends renderer_base { $output .= html_writer::tag('h4', $displayoptions['confirmtitle']); $output .= $this->box_end(); $attributes = [ - 'role'=>'alert', - 'data-aria-autofocus'=>'true' + 'role' => 'alert', + 'data-aria-autofocus' => 'true', ]; $output .= $this->box_start('modal-body', 'modal-body', $attributes); $output .= html_writer::tag('p', $message); @@ -1680,21 +1712,21 @@ class core_renderer extends renderer_base { * Returns a form with a single button. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_single_button()} instead. + * {@see core_renderer::render_single_button()} instead. * * @param string|moodle_url $url * @param string $label button text * @param string $method get or post submit method - * @param array $options associative array {disabled, title, etc.} + * @param null|array $options associative array {disabled, title, etc.} * @return string HTML fragment */ - public function single_button($url, $label, $method='post', array $options=null) { + public function single_button($url, $label, $method = 'post', ?array $options = null) { if (!($url instanceof moodle_url)) { $url = new moodle_url($url); } $button = new single_button($url, $label, $method); - foreach ((array)$options as $key=>$value) { + foreach ((array)$options as $key => $value) { if (property_exists($button, $key)) { $button->$key = $value; } else { @@ -1721,7 +1753,7 @@ class core_renderer extends renderer_base { * Returns a form with a single select widget. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_single_select()} instead. + * {@see core_renderer::render_single_select()} instead. * * @param moodle_url $url form action target, includes hidden fields * @param string $name name of selection field - the changing parameter in url @@ -1732,8 +1764,15 @@ class core_renderer extends renderer_base { * @param array $attributes other attributes for the single select * @return string HTML fragment */ - public function single_select($url, $name, array $options, $selected = '', - $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) { + public function single_select( + $url, + $name, + array $options, + $selected = '', + $nothing = ['' => 'choosedots'], + $formid = null, + $attributes = [] + ) { if (!($url instanceof moodle_url)) { $url = new moodle_url($url); } @@ -1762,20 +1801,20 @@ class core_renderer extends renderer_base { $options = []; foreach ($formats as $format) { if ($format->is_enabled()) { - $options[] = array( + $options[] = [ 'value' => $format->name, 'label' => get_string('dataformat', $format->component), - ); + ]; } } - $hiddenparams = array(); + $hiddenparams = []; foreach ($params as $key => $value) { - $hiddenparams[] = array( + $hiddenparams[] = [ 'name' => $key, 'value' => $value, - ); + ]; } - $data = array( + $data = [ 'label' => $label, 'base' => $base, 'name' => $name, @@ -1783,7 +1822,7 @@ class core_renderer extends renderer_base { 'options' => $options, 'sesskey' => sesskey(), 'submit' => get_string('download'), - ); + ]; return $this->render_from_template('core/dataformat_selector', $data); } @@ -1803,7 +1842,7 @@ class core_renderer extends renderer_base { * Returns a form with a url select widget. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_url_select()} instead. + * {@see core_renderer::render_url_select()} instead. * * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....) * @param string $selected selected element @@ -1811,7 +1850,7 @@ class core_renderer extends renderer_base { * @param string $formid * @return string HTML fragment */ - public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) { + public function url_select(array $urls, $selected, $nothing = ['' => 'choosedots'], $formid = null) { $select = new url_select($urls, $selected, $nothing, $formid); return $this->render($select); } @@ -1839,14 +1878,18 @@ class core_renderer extends renderer_base { public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) { global $CFG; - $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre')); + $icon = $this->pix_icon('book', '', 'moodle', ['class' => 'iconhelp icon-pre']); $attributes['href'] = new moodle_url(get_docs_url($path)); $newwindowicon = ''; if (!empty($CFG->doctonewwindow) || $forcepopup) { $attributes['target'] = '_blank'; - $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', - ['class' => 'fa fa-externallink fa-fw']); + $newwindowicon = $this->pix_icon( + 'i/externallink', + get_string('opensinnewwindow'), + 'moodle', + ['class' => 'fa fa-externallink fa-fw'] + ); } return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes); @@ -1856,15 +1899,15 @@ class core_renderer extends renderer_base { * Return HTML for an image_icon. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_image_icon()} instead. + * {@see core_renderer::render_image_icon()} instead. * * @param string $pix short pix name * @param string $alt mandatory alt attribute * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc. - * @param array $attributes htm attributes + * @param null|array $attributes htm attributes * @return string HTML fragment */ - public function image_icon($pix, $alt, $component='moodle', array $attributes = null) { + public function image_icon($pix, $alt, $component = 'moodle', ?array $attributes = null) { $icon = new image_icon($pix, $alt, $component, $attributes); return $this->render($icon); } @@ -1884,15 +1927,15 @@ class core_renderer extends renderer_base { * Return HTML for a pix_icon. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_pix_icon()} instead. + * {@see core_renderer::render_pix_icon()} instead. * * @param string $pix short pix name * @param string $alt mandatory alt attribute * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc. - * @param array $attributes htm lattributes + * @param null|array $attributes htm lattributes * @return string HTML fragment */ - public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) { + public function pix_icon($pix, $alt, $component = 'moodle', ?array $attributes = null) { $icon = new pix_icon($pix, $alt, $component, $attributes); return $this->render($icon); } @@ -1929,7 +1972,7 @@ class core_renderer extends renderer_base { global $CFG, $USER; if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) { - return null;//ratings are turned off + return null;// ratings are turned off } $ratingmanager = new rating_manager(); @@ -1937,73 +1980,70 @@ class core_renderer extends renderer_base { $ratingmanager->initialise_rating_javascript($this->page); $strrate = get_string("rate", "rating"); - $ratinghtml = ''; //the string we'll return + $ratinghtml = ''; // the string we'll return // permissions check - can they view the aggregate? if ($rating->user_can_view_aggregate()) { - $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod); - $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label')); + $aggregatelabel = html_writer::tag('span', $aggregatelabel, ['class' => 'rating-aggregate-label']); $aggregatestr = $rating->get_aggregate_string(); - $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' '; + $aggregatehtml = html_writer::tag('span', $aggregatestr, ['id' => 'ratingaggregate' . $rating->itemid, 'class' => 'ratingaggregate']) . ' '; if ($rating->count > 0) { $countstr = "({$rating->count})"; } else { $countstr = '-'; } - $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' '; + $aggregatehtml .= html_writer::tag('span', $countstr, ['id' => "ratingcount{$rating->itemid}", 'class' => 'ratingcount']) . ' '; if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) { - $nonpopuplink = $rating->get_view_ratings_url(); $popuplink = $rating->get_view_ratings_url(true); - $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600)); + $action = new popup_action('click', $popuplink, 'ratings', ['height' => 400, 'width' => 600]); $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action); } - $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container')); + $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, ['class' => 'rating-aggregate-container']); } $formstart = null; // if the item doesn't belong to the current user, the user has permission to rate // and we're within the assessable period if ($rating->user_can_rate()) { - $rateurl = $rating->get_rate_url(); $inputs = $rateurl->params(); - //start the rating form - $formattrs = array( + // start the rating form + $formattrs = [ 'id' => "postrating{$rating->itemid}", 'class' => 'postratingform', 'method' => 'post', - 'action' => $rateurl->out_omit_querystring() - ); + 'action' => $rateurl->out_omit_querystring(), + ]; $formstart = html_writer::start_tag('form', $formattrs); - $formstart .= html_writer::start_tag('div', array('class' => 'ratingform')); + $formstart .= html_writer::start_tag('div', ['class' => 'ratingform']); // add the hidden inputs foreach ($inputs as $name => $value) { - $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value); + $attributes = ['type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value]; $formstart .= html_writer::empty_tag('input', $attributes); } if (empty($ratinghtml)) { - $ratinghtml .= $strrate.': '; + $ratinghtml .= $strrate . ': '; } - $ratinghtml = $formstart.$ratinghtml; + $ratinghtml = $formstart . $ratinghtml; - $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems; - $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid); - $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide')); + $scalearray = [RATING_UNSET_RATING => $strrate . '...'] + $rating->settings->scale->scaleitems; + $scaleattrs = ['class' => 'postratingmenu ratinginput', 'id' => 'menurating' . $rating->itemid]; + $ratinghtml .= html_writer::label($rating->rating, 'menurating' . $rating->itemid, false, ['class' => 'accesshide']); $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs); - //output submit button - $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit")); + // output submit button + $ratinghtml .= html_writer::start_tag('span', ['class' => "ratingsubmit"]); - $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating'))); + $attributes = ['type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit' . $rating->itemid, 'value' => s(get_string('rate', 'rating'))]; $ratinghtml .= html_writer::empty_tag('input', $attributes); if (!$rating->settings->scale->isnumeric) { @@ -2039,7 +2079,7 @@ class core_renderer extends renderer_base { public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) { $image = ''; if ($icon) { - $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge')); + $image = $this->pix_icon($icon, $iconalt, $component, ['class' => 'icon iconlarge']); } $help = ''; @@ -2047,7 +2087,7 @@ class core_renderer extends renderer_base { $help = $this->help_icon($helpidentifier, $component); } - return $this->heading($image.$text.$help, $level, $classnames); + return $this->heading($image . $text . $help, $level, $classnames); } /** @@ -2063,7 +2103,7 @@ class core_renderer extends renderer_base { * Returns HTML to display a help icon. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_help_icon()} instead. + * {@see core_renderer::render_help_icon()} instead. * * @param string $identifier The keyword that defines a help page * @param string $component component name @@ -2104,27 +2144,27 @@ class core_renderer extends renderer_base { public function help_icon_scale($courseid, stdClass $scale) { global $CFG; - $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')'; + $title = get_string('helpprefix2', '', $scale->name) . ' (' . get_string('newwindow') . ')'; - $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp')); + $icon = $this->pix_icon('help', get_string('scales'), 'moodle', ['class' => 'iconhelp']); $scaleid = abs($scale->id); - $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid)); + $link = new moodle_url('/course/scales.php', ['id' => $courseid, 'list' => true, 'scaleid' => $scaleid]); $action = new popup_action('click', $link, 'ratingscale'); - return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink')); + return html_writer::tag('span', $this->action_link($link, $icon, $action), ['class' => 'helplink']); } /** * Creates and returns a spacer image with optional line break. * - * @param array $attributes Any HTML attributes to add to the spaced. + * @param null|array $attributes Any HTML attributes to add to the spaced. * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be * laxy do it with CSS which is a much better solution. * @return string HTML fragment */ - public function spacer(array $attributes = null, $br = false) { + public function spacer(?array $attributes = null, $br = false) { $attributes = (array)$attributes; if (empty($attributes['width'])) { $attributes['width'] = 1; @@ -2160,12 +2200,12 @@ class core_renderer extends renderer_base { * * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_user_picture()} instead. + * {@see core_renderer::render_user_picture()} instead. * * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname * If any of these are missing, the database is queried. Avoid this * if at all possible, particularly for reports. It is very bad for performance. - * @param array $options associative array with user picture options, used only if not a user_picture object, + * @param null|array $options associative array with user picture options, used only if not a user_picture object, * options are: * - courseid=$this->page->course->id (course id of user profile in link) * - size=35 (size of image) @@ -2178,9 +2218,9 @@ class core_renderer extends renderer_base { * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id) * @return string HTML fragment */ - public function user_picture(stdClass $user, array $options = null) { + public function user_picture(stdClass $user, ?array $options = null) { $userpicture = new user_picture($user); - foreach ((array)$options as $key=>$value) { + foreach ((array)$options as $key => $value) { if (property_exists($userpicture, $key)) { $userpicture->$key = $value; } @@ -2231,7 +2271,7 @@ class core_renderer extends renderer_base { $src = $userpicture->get_url($this->page, $this); - $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size); + $attributes = ['src' => $src, 'class' => $class, 'width' => $size, 'height' => $size]; if (!$userpicture->visibletoscreenreaders) { $alt = ''; } @@ -2247,7 +2287,8 @@ class core_renderer extends renderer_base { $fullname = fullname($userpicture->user, $canviewfullnames); // Don't modify in corner cases where neither the firstname nor the lastname appears. $output = html_writer::tag( - 'span', $initials, + 'span', + $initials, [ 'class' => 'userinitials size-' . $size, 'title' => $fullname, @@ -2270,18 +2311,20 @@ class core_renderer extends renderer_base { $courseid = $userpicture->courseid; } if ($courseid == SITEID) { - $url = new moodle_url('/user/profile.php', array('id' => $user->id)); + $url = new moodle_url('/user/profile.php', ['id' => $user->id]); } else { - $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid)); + $url = new moodle_url('/user/view.php', ['id' => $user->id, 'course' => $courseid]); } // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself. - if (!$userpicture->link || - ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url. + if ( + !$userpicture->link || + ($this->page->has_set_url() && $this->page->url == $url) + ) { // Protect against unset page->url. return $output; } - $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn'); + $attributes = ['href' => $url, 'class' => 'd-inline-block aabtn']; if (!$userpicture->visibletoscreenreaders) { $attributes['tabindex'] = '-1'; $attributes['aria-hidden'] = 'true'; @@ -2311,7 +2354,7 @@ class core_renderer extends renderer_base { * * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_file_picker()} instead. + * {@see core_renderer::render_file_picker()} instead. * * @param stdClass $options file manager options * options are: @@ -2342,7 +2385,7 @@ class core_renderer extends renderer_base { $strloading = get_string('loading', 'repository'); $strdndenabled = get_string('dndenabled_inbox', 'moodle'); $strdroptoupload = get_string('droptoupload', 'moodle'); - $iconprogress = $this->pix_icon('i/loading_small', $strloading).''; + $iconprogress = $this->pix_icon('i/loading_small', $strloading) . ''; $currentfile = $options->currentfile; if (empty($currentfile)) { @@ -2438,7 +2481,6 @@ EOD; */ public function edit_switch() { if ($this->page->user_allowed_editing()) { - $temp = (object) [ 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false), 'pagecontextid' => $this->page->context->id, @@ -2458,7 +2500,7 @@ EOD; * @param string $text The lang string for the button's label (already output from get_string()) * @return string html fragment */ - public function close_window_button($text='') { + public function close_window_button($text = '') { if (empty($text)) { $text = get_string('closewindow'); } @@ -2479,8 +2521,8 @@ EOD; if (empty($message)) { return ''; } - $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message; - return html_writer::tag('span', $message, array('class' => 'error')); + $message = $this->pix_icon('i/warning', get_string('error'), '', ['class' => 'icon icon-pre', 'title' => '']) . $message; + return html_writer::tag('span', $message, ['class' => 'error']); } /** @@ -2493,7 +2535,8 @@ EOD; * @param string $moreinfourl URL where more info can be found about the error * @param string $link Link for the Continue button * @param array $backtrace The execution backtrace - * @param string $debuginfo Debugging information + * @param null|string $debuginfo Debugging information + * @param string $errorcode * @return string the HTML to output. */ public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") { @@ -2506,7 +2549,6 @@ EOD; // we can not always recover properly here, we have problems with output buffering, // html tables, etc. $output .= $this->opencontainers->pop_all_but_last(); - } else { // It is really bad if library code throws exception when output buffering is on, // because the buffered text would be printed before our start of page. @@ -2536,7 +2578,7 @@ EOD; $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here $this->page->set_url('/'); // no url - //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-( + // $this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-( $this->page->set_title(get_string('error')); $this->page->set_heading($this->page->course->fullname); // No need to display the activity header when encountering an error. @@ -2544,14 +2586,14 @@ EOD; $output .= $this->header(); } - $message = '

' . s($message) . '

'. + $message = '

' . s($message) . '

' . '

' . get_string('moreinformation') . '

'; if (empty($CFG->rolesactive)) { $message .= '

' . get_string('installproblem', 'error') . '

'; - //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation. + // It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation. } - $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror')); + $output .= $this->box($message, 'errorbox alert alert-danger', null, ['data-rel' => 'fatalerror']); if ($CFG->debugdeveloper) { $labelsep = get_string('labelsep', 'langconfig'); @@ -2565,7 +2607,7 @@ EOD; $label = get_string('stacktrace', 'debug') . $labelsep; $output .= $this->notification("$label " . format_backtrace($backtrace), 'notifytiny'); } - if ($obbuffer !== '' ) { + if ($obbuffer !== '') { $label = get_string('outputbuffer', 'debug') . $labelsep; $output .= $this->notification("$label " . s($obbuffer), 'notifytiny'); } @@ -2652,7 +2694,7 @@ EOD; * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more. */ public function notify_problem() { - throw new coding_exception('core_renderer::notify_problem() can not be used any more, '. + throw new coding_exception('core_renderer::notify_problem() can not be used any more, ' . 'please use \core\notification::add(), or \core\output\notification as required.'); } @@ -2660,7 +2702,7 @@ EOD; * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more. */ public function notify_success() { - throw new coding_exception('core_renderer::notify_success() can not be used any more, '. + throw new coding_exception('core_renderer::notify_success() can not be used any more, ' . 'please use \core\notification::add(), or \core\output\notification as required.'); } @@ -2668,7 +2710,7 @@ EOD; * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more. */ public function notify_message() { - throw new coding_exception('core_renderer::notify_message() can not be used any more, '. + throw new coding_exception('core_renderer::notify_message() can not be used any more, ' . 'please use \core\notification::add(), or \core\output\notification as required.'); } @@ -2676,7 +2718,7 @@ EOD; * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more. */ public function notify_redirect() { - throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '. + throw new coding_exception('core_renderer::notify_redirect() can not be used any more, ' . 'please use \core\notification::add(), or \core\output\notification as required.'); } @@ -2711,7 +2753,7 @@ EOD; * Returns HTML to display a single paging bar to provide access to other pages (usually in a search) * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_paging_bar()} instead. + * {@see core_renderer::render_paging_bar()} instead. * * @param int $totalcount The total number of entries available to be paged through * @param int $page The page you are currently viewing @@ -2771,7 +2813,7 @@ EOD; * @return string the HTML to output. */ public function skip_link_target($id = null) { - return html_writer::span('', '', array('id' => $id)); + return html_writer::span('', '', ['id' => $id]); } /** @@ -2784,11 +2826,11 @@ EOD; * @return string the HTML to output. */ public function heading($text, $level = 2, $classes = null, $id = null) { - $level = (integer) $level; + $level = (int) $level; if ($level < 1 or $level > 6) { throw new coding_exception('Heading level must be an integer between 1 and 6.'); } - return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes))); + return html_writer::tag('h' . $level, $text, ['id' => $id, 'class' => renderer_base::prepare_classes($classes)]); } /** @@ -2800,7 +2842,7 @@ EOD; * @param array $attributes An array of other attributes to give the box. * @return string the HTML to output. */ - public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) { + public function box($contents, $classes = 'generalbox', $id = null, $attributes = []) { return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end(); } @@ -2812,7 +2854,7 @@ EOD; * @param array $attributes An array of other attributes to give the box. * @return string the HTML to output. */ - public function box_start($classes = 'generalbox', $id = null, $attributes = array()) { + public function box_start($classes = 'generalbox', $id = null, $attributes = []) { $this->opencontainers->push('box', html_writer::end_tag('div')); $attributes['id'] = $id; $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes); @@ -2913,40 +2955,40 @@ EOD; * @param array $attrs html attributes passed to the top ofs the list * @return string HTML */ - public function tree_block_contents($items, $attrs = array()) { + public function tree_block_contents($items, $attrs = []) { // exit if empty, we don't want an empty ul element if (empty($items)) { return ''; } // array of nested li elements - $lis = array(); + $lis = []; foreach ($items as $item) { // this applies to the li item which contains all child lists too $content = $item->content($this); - $liclasses = array($item->get_css_type()); - if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) { + $liclasses = [$item->get_css_type()]; + if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count() == 0 && $item->nodetype == navigation_node::NODETYPE_BRANCH)) { $liclasses[] = 'collapsed'; } if ($item->isactive === true) { $liclasses[] = 'current_branch'; } - $liattr = array('class'=>join(' ',$liclasses)); + $liattr = ['class' => join(' ', $liclasses)]; // class attribute on the div item which only contains the item content - $divclasses = array('tree_item'); - if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) { + $divclasses = ['tree_item']; + if ($item->children->count() > 0 || $item->nodetype == navigation_node::NODETYPE_BRANCH) { $divclasses[] = 'branch'; } else { $divclasses[] = 'leaf'; } - if (!empty($item->classes) && count($item->classes)>0) { + if (!empty($item->classes) && count($item->classes) > 0) { $divclasses[] = join(' ', $item->classes); } - $divattr = array('class'=>join(' ', $divclasses)); + $divattr = ['class' => join(' ', $divclasses)]; if (!empty($item->id)) { $divattr['id'] = $item->id; } $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children); - if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) { + if (!empty($item->preceedwithhr) && $item->preceedwithhr === true) { $content = html_writer::empty_tag('hr') . $content; } $content = html_writer::tag('li', $content, $liattr); @@ -3088,7 +3130,7 @@ EOD; 'value' ) ), - array('class' => 'meta viewingas') + ['class' => 'meta viewingas'] ); } @@ -3139,7 +3181,6 @@ EOD; $navitemcount = count($opts->navitems); $idx = 0; foreach ($opts->navitems as $key => $value) { - switch ($value->itemtype) { case 'divider': // If the nav item is a divider, add one and skip link processing. @@ -3154,12 +3195,12 @@ EOD; // Process this as a link item. $pix = null; if (isset($value->pix) && !empty($value->pix)) { - $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall')); + $pix = new pix_icon($value->pix, '', null, ['class' => 'iconsmall']); } else if (isset($value->imgsrc) && !empty($value->imgsrc)) { $value->title = html_writer::img( $value->imgsrc, $value->title, - array('class' => 'iconsmall') + ['class' => 'iconsmall'] ) . $value->title; } @@ -3167,7 +3208,7 @@ EOD; $value->url, $pix, $value->title, - array('class' => 'icon') + ['class' => 'icon'] ); if (!empty($value->titleidentifier)) { $al->attributes['data-title'] = $value->titleidentifier; @@ -3239,7 +3280,7 @@ EOD; if ($item->action instanceof moodle_url) { $content = $item->get_content(); $title = $item->get_title(); - $attributes = array(); + $attributes = []; $attributes['itemprop'] = 'url'; if ($title !== '') { $attributes['title'] = $title; @@ -3250,14 +3291,13 @@ EOD; if ($item->is_last()) { $attributes['aria-current'] = 'page'; } - $content = html_writer::tag('span', $content, array('itemprop' => 'title')); + $content = html_writer::tag('span', $content, ['itemprop' => 'title']); $content = html_writer::link($item->action, $content, $attributes); - $attributes = array(); + $attributes = []; $attributes['itemscope'] = ''; $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb'; $content = html_writer::tag('span', $content, $attributes); - } else { $content = $this->render_navigation_node($item); } @@ -3275,10 +3315,10 @@ EOD; $title = $item->get_title(); if ($item->icon instanceof renderable && !$item->hideicon) { $icon = $this->render($item->icon); - $content = $icon.$content; // use CSS for spacing of icons + $content = $icon . $content; // use CSS for spacing of icons } if ($item->helpbutton !== null) { - $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0')); + $content = trim($item->helpbutton) . html_writer::tag('span', $content, ['class' => 'clearhelpbutton', 'tabindex' => '0']); } if ($content === '') { return ''; @@ -3294,7 +3334,7 @@ EOD; } $content = $this->render($link); } else if ($item->action instanceof moodle_url) { - $attributes = array(); + $attributes = []; if ($title !== '') { $attributes['title'] = $title; } @@ -3302,9 +3342,8 @@ EOD; $attributes['class'] = 'dimmed_text'; } $content = html_writer::link($item->action, $content, $attributes); - } else if (is_string($item->action) || empty($item->action)) { - $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence. + $attributes = ['tabindex' => '0']; // add tab support to span but still maintain character stream sequence. if ($title !== '') { $attributes['title'] = $title; } @@ -3375,7 +3414,7 @@ EOD; * and then configuring the custommenu config setting as described. * * Theme developers: DO NOT OVERRIDE! Please override function - * {@link core_renderer::render_custom_menu()} instead. + * {@see core_renderer::render_custom_menu()} instead. * * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings * @return string @@ -3415,7 +3454,7 @@ EOD; } $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000); foreach ($langs as $langtype => $langname) { - $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname); + $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), $langname); } } @@ -3495,11 +3534,11 @@ EOD; if ($menunode->get_url() !== null) { $url = $menunode->get_url(); } else { - $url = '#cm_submenu_'.$submenucount; + $url = '#cm_submenu_' . $submenucount; } - $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title())); - $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu')); - $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content')); + $content .= html_writer::link($url, $menunode->get_text(), ['class' => 'yui3-menu-label', 'title' => $menunode->get_title()]); + $content .= html_writer::start_tag('div', ['id' => 'cm_submenu_' . $submenucount, 'class' => 'yui3-menu custom_menu_submenu']); + $content .= html_writer::start_tag('div', ['class' => 'yui3-menu-content']); $content .= html_writer::start_tag('ul'); foreach ($menunode->get_children() as $menunode) { $content .= $this->render_custom_menu_item($menunode); @@ -3513,15 +3552,14 @@ EOD; // Also, if the node's text matches '####', add a class so we can treat it as a divider. $content = ''; if (preg_match("/^#+$/", $menunode->get_text())) { - // This is a divider. - $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider')); + $content = html_writer::start_tag('li', ['class' => 'yui3-menuitem divider']); } else { $content = html_writer::start_tag( 'li', - array( - 'class' => 'yui3-menuitem' - ) + [ + 'class' => 'yui3-menuitem', + ] ); if ($menunode->get_url() !== null) { $url = $menunode->get_url(); @@ -3531,7 +3569,7 @@ EOD; $content .= html_writer::link( $url, $menunode->get_text(), - array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title()) + ['class' => 'yui3-menuitem-content', 'title' => $menunode->get_title()] ); } $content .= html_writer::end_tag('li'); @@ -3564,10 +3602,10 @@ EOD; $linktext = get_string('switchdevicedefault'); $devicetype = 'default'; } - $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey())); + $linkurl = new moodle_url('/theme/switchdevice.php', ['url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()]); - $content = html_writer::start_tag('div', array('id' => 'theme_switch_link')); - $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow')); + $content = html_writer::start_tag('div', ['id' => 'theme_switch_link']); + $content .= html_writer::link($linkurl, $linktext, ['rel' => 'nofollow']); $content .= html_writer::end_tag('div'); return $content; @@ -3579,7 +3617,7 @@ EOD; * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments * * Theme developers: In order to change how tabs are displayed please override functions - * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()} + * {@see core_renderer::render_tabtree()} and/or {@see core_renderer::render_tabobject()} * * @param array $tabs array of tabs, each of them may have it's own ->subtree * @param string|null $selected which tab to mark as selected, all parent tabs will @@ -3609,7 +3647,7 @@ EOD; /** * Renders tabobject (part of tabtree) * - * This function is called from {@link core_renderer::render_tabtree()} + * This function is called from {@see core_renderer::render_tabtree()} * and also it calls itself when printing the $tabobject subtree recursively. * * Property $tabobject->level indicates the number of row of tabs. @@ -3625,27 +3663,27 @@ EOD; // No name for tabtree root. } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) { // Tab name without a link. The tag is used for styling. - $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex')); + $str .= html_writer::tag('a', html_writer::span($tabobject->text), ['class' => 'nolink moodle-has-zindex']); } else { // Tab name with a link. if (!($tabobject->link instanceof moodle_url)) { // backward compartibility when link was passed as quoted string $str .= "link\" title=\"$tabobject->title\">$tabobject->text"; } else { - $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title)); + $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), ['title' => $tabobject->title]); } } if (empty($tabobject->subtree)) { if ($tabobject->selected) { - $str .= html_writer::tag('div', ' ', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty')); + $str .= html_writer::tag('div', ' ', ['class' => 'tabrow' . ($tabobject->level + 1) . ' empty']); } return $str; } // Print subtree. if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) { - $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level)); + $str .= html_writer::start_tag('ul', ['class' => 'tabrow' . $tabobject->level]); $cnt = 0; foreach ($tabobject->subtree as $tab) { $liclass = ''; @@ -3666,7 +3704,7 @@ EOD; } // This will recursively call function render_tabobject() for each item in subtree. - $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass))); + $str .= html_writer::tag('li', $this->render($tab), ['class' => trim($liclass)]); $cnt++; } $str .= html_writer::end_tag('ul'); @@ -3685,16 +3723,16 @@ EOD; * @param boolean $fakeblocksonly Include fake blocks only. * @return string HTML. */ - public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) { + public function blocks($region, $classes = [], $tag = 'aside', $fakeblocksonly = false) { $displayregion = $this->page->apply_theme_region_manipulations($region); $classes = (array)$classes; $classes[] = 'block-region'; - $attributes = array( - 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion), + $attributes = [ + 'id' => 'block-region-' . preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion), 'class' => join(' ', $classes), 'data-blockregion' => $displayregion, - 'data-droptarget' => '1' - ); + 'data-droptarget' => '1', + ]; if ($this->page->blocks->region_has_content($displayregion, $this)) { $content = html_writer::tag('h2', get_string('blocks'), ['class' => 'sr-only']) . $this->blocks_for_region($displayregion, $fakeblocksonly); @@ -3733,7 +3771,7 @@ EOD; * @param array $additionalclasses Any additional classes to apply. * @return string */ - public function body_css_classes(array $additionalclasses = array()) { + public function body_css_classes(array $additionalclasses = []) { return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses); } @@ -3754,11 +3792,11 @@ EOD; * @param string|array $additionalclasses Any additional classes to give the body tag, * @return string */ - public function body_attributes($additionalclasses = array()) { + public function body_attributes($additionalclasses = []) { if (!is_array($additionalclasses)) { $additionalclasses = explode(' ', $additionalclasses); } - return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"'; + return ' id="' . $this->body_id() . '" class="' . $this->body_css_classes($additionalclasses) . '"'; } /** @@ -3812,9 +3850,11 @@ EOD; // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has // disabled support, or limited it to authenticated users and the current user is a guest or not logged in. - if (!isset($CFG->supportavailability) || + if ( + !isset($CFG->supportavailability) || $CFG->supportavailability == CONTACT_SUPPORT_DISABLED || - ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) { + ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser())) + ) { return ''; } @@ -3847,9 +3887,11 @@ EOD; public function services_support_link(): string { global $CFG; - if (during_initial_install() || + if ( + during_initial_install() || (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) || - !is_siteadmin()) { + !is_siteadmin() + ) { return ''; } @@ -3945,8 +3987,14 @@ EOD; } // Use $CFG->themerev to prevent browser caching when the file changes. - return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/', - theme_get_revision(), $logo); + return moodle_url::make_pluginfile_url( + context_system::instance()->id, + 'core_admin', + 'favicon', + '64x64/', + theme_get_revision(), + $logo + ); } /** @@ -3967,7 +4015,7 @@ EOD; */ public function render_preferences_group(preferences_group $renderable) { $html = ''; - $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group')); + $html .= html_writer::start_tag('div', ['class' => 'col-sm-4 preferences-group']); $html .= $this->heading($renderable->title, 3); $html .= html_writer::start_tag('ul'); foreach ($renderable->nodes as $node) { @@ -4003,7 +4051,7 @@ EOD; $user = $headerinfo['user']; } else { // Look up the user information if it is not supplied. - $user = $DB->get_record('user', array('id' => $context->instanceid)); + $user = $DB->get_record('user', ['id' => $context->instanceid]); } // If the user context is set, then use that for capability checks. @@ -4023,20 +4071,20 @@ EOD; $heading = fullname($user); } - $imagedata = $this->user_picture($user, array('size' => 100)); + $imagedata = $this->user_picture($user, ['size' => 100]); // Check to see if we should be displaying a message button. if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) { - $userbuttons = array( - 'messages' => array( + $userbuttons = [ + 'messages' => [ 'buttontype' => 'message', 'title' => get_string('message', 'message'), - 'url' => new moodle_url('/message/index.php', array('id' => $user->id)), + 'url' => new moodle_url('/message/index.php', ['id' => $user->id]), 'image' => 'message', 'linkattributes' => \core_message\helper::messageuser_link_params($user->id), - 'page' => $this->page - ) - ); + 'page' => $this->page, + ], + ]; if ($USER->id != $user->id) { $iscontact = \core_message\api::is_contact($USER->id, $user->id); @@ -4076,19 +4124,19 @@ EOD; $contacturlaction = 'removecontact'; $contactimage = 'removecontact'; } - $userbuttons['togglecontact'] = array( + $userbuttons['togglecontact'] = [ 'buttontype' => 'togglecontact', 'title' => get_string($contacttitle, 'message'), - 'url' => new moodle_url('/message/index.php', array( - 'user1' => $USER->id, - 'user2' => $user->id, - $contacturlaction => $user->id, - 'sesskey' => sesskey()) - ), + 'url' => new moodle_url('/message/index.php', [ + 'user1' => $USER->id, + 'user2' => $user->id, + $contacturlaction => $user->id, + 'sesskey' => sesskey(), + ]), 'image' => $contactimage, 'linkattributes' => $linkattributes, - 'page' => $this->page - ); + 'page' => $this->page, + ]; } } } else { @@ -4136,8 +4184,10 @@ EOD; } else if ($homepage == HOMEPAGE_SITE) { $homepagetype = 'site-index'; } - if ($this->page->include_region_main_settings_in_header_actions() && - !$this->page->blocks->is_block_present('settings')) { + if ( + $this->page->include_region_main_settings_in_header_actions() && + !$this->page->blocks->is_block_present('settings') + ) { // Only include the region main settings if the page has requested it and it doesn't already have // the settings block on it. The region main settings are included in the settings block and // duplicating the content causes behat failures. @@ -4180,25 +4230,29 @@ EOD; $showusermenu = false; // We are on the course home page. - if (($context->contextlevel == CONTEXT_COURSE) && + if ( + ($context->contextlevel == CONTEXT_COURSE) && !empty($currentnode) && - ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) { + ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION) + ) { $showcoursemenu = true; } $courseformat = course_get_format($this->page->course); // This is a single activity course format, always show the course menu on the activity main page. - if ($context->contextlevel == CONTEXT_MODULE && - !$courseformat->has_view_page()) { - + if ( + $context->contextlevel == CONTEXT_MODULE && + !$courseformat->has_view_page() + ) { $this->page->navigation->initialise(); $activenode = $this->page->navigation->find_active_node(); // If the settings menu has been forced then show the menu. if ($this->page->is_settings_menu_forced()) { $showcoursemenu = true; - } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY || - $activenode->type == navigation_node::TYPE_RESOURCE)) { - + } else if ( + !empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY || + $activenode->type == navigation_node::TYPE_RESOURCE) + ) { // We only want to show the menu on the first page of the activity. This means // the breadcrumb has no additional nodes. if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) { @@ -4208,16 +4262,20 @@ EOD; } // This is the site front page. - if ($context->contextlevel == CONTEXT_COURSE && + if ( + $context->contextlevel == CONTEXT_COURSE && !empty($currentnode) && - $currentnode->key === 'home') { + $currentnode->key === 'home' + ) { $showfrontpagemenu = true; } // This is the user profile page. - if ($context->contextlevel == CONTEXT_USER && + if ( + $context->contextlevel == CONTEXT_USER && !empty($currentnode) && - ($currentnode->key === 'myprofile')) { + ($currentnode->key === 'myprofile') + ) { $showusermenu = true; } @@ -4230,7 +4288,7 @@ EOD; // We only add a list to the full settings menu if we didn't include every node in the short menu. if ($skipped) { $text = get_string('morenavigationlinks'); - $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id)); + $url = new moodle_url('/course/admin.php', ['courseid' => $this->page->course->id]); $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text)); $menu->add_secondary_action($link); } @@ -4244,7 +4302,7 @@ EOD; // We only add a list to the full settings menu if we didn't include every node in the short menu. if ($skipped) { $text = get_string('morenavigationlinks'); - $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id)); + $url = new moodle_url('/course/admin.php', ['courseid' => $this->page->course->id]); $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text)); $menu->add_secondary_action($link); } @@ -4271,10 +4329,12 @@ EOD; * @param boolean $onlytopleafnodes * @return boolean nodesskipped - True if nodes were skipped in building the menu */ - protected function build_action_menu_from_navigation(action_menu $menu, - navigation_node $node, - $indent = false, - $onlytopleafnodes = false) { + protected function build_action_menu_from_navigation( + action_menu $menu, + navigation_node $node, + $indent = false, + $onlytopleafnodes = false + ) { $skipped = false; // Build an action menu based on the visible nodes from this navigation tree. foreach ($node->children as $menuitem) { @@ -4325,16 +4385,16 @@ EOD; $menu = new action_menu(); if ($context->contextlevel == CONTEXT_MODULE) { - $this->page->navigation->initialise(); $node = $this->page->navigation->find_active_node(); $buildmenu = false; // If the settings menu has been forced then show the menu. if ($this->page->is_settings_menu_forced()) { $buildmenu = true; - } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY || - $node->type == navigation_node::TYPE_RESOURCE)) { - + } else if ( + !empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY || + $node->type == navigation_node::TYPE_RESOURCE) + ) { $items = $this->page->navbar->get_items(); $navbarnode = end($items); // We only want to show the menu on the first page of the activity. This means @@ -4351,7 +4411,6 @@ EOD; $this->build_action_menu_from_navigation($menu, $node); } } - } else if ($context->contextlevel == CONTEXT_COURSECAT) { // For course category context, show category settings menu, if we're on the course category page. if ($this->page->pagetype === 'course-index-category') { @@ -4361,7 +4420,6 @@ EOD; $this->build_action_menu_from_navigation($menu, $node); } } - } else { $items = $this->page->navbar->get_items(); $navbarnode = end($items); @@ -4372,7 +4430,6 @@ EOD; // Build an action menu based on the visible nodes from this navigation tree. $this->build_action_menu_from_navigation($menu, $node); } - } } return $this->render($menu); @@ -4391,8 +4448,14 @@ EOD; * @param bool $accesshidelabel if true, the label should have class="accesshide" added. * @return string */ - public function tag_list($tags, $label = null, $classes = '', $limit = 10, - $pagecontext = null, $accesshidelabel = false) { + public function tag_list( + $tags, + $label = null, + $classes = '', + $limit = 10, + $pagecontext = null, + $accesshidelabel = false + ) { $list = new taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel); return $this->render_from_template('core_tag/taglist', $list->export_for_template($this)); } @@ -4448,7 +4511,7 @@ EOD; $chartdata = json_encode($chart); return $this->render_from_template('core/chart', (object) [ 'chartdata' => $chartdata, - 'withtable' => $withtable + 'withtable' => $withtable, ]); } @@ -4469,8 +4532,11 @@ EOD; $url = $url->out(false); } $context->logourl = $url; - $context->sitename = format_string($SITE->fullname, true, - ['context' => context_course::instance(SITEID), "escape" => false]); + $context->sitename = format_string( + $SITE->fullname, + true, + ['context' => context_course::instance(SITEID), "escape" => false] + ); return $this->render_from_template('core/loginform', $context); } @@ -4529,15 +4595,15 @@ EOD; $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id']; } - $context = array( + $context = [ 'element' => $elementcontext, 'label' => $label, 'text' => $text, 'required' => $required, 'advanced' => $advanced, 'helpbutton' => $helpbutton, - 'error' => $error - ); + 'error' => $error, + ]; return $this->render_from_template($templatename, $context); } } catch (\Exception $e) { @@ -4561,8 +4627,11 @@ EOD; $url = $url->out(false); } $context['logourl'] = $url; - $context['sitename'] = format_string($SITE->fullname, true, - ['context' => context_course::instance(SITEID), "escape" => false]); + $context['sitename'] = format_string( + $SITE->fullname, + true, + ['context' => context_course::instance(SITEID), "escape" => false] + ); return $this->render_from_template('core/signup_form_layout', $context); } @@ -4671,7 +4740,8 @@ EOD; if (count($regions) == 0) { return ''; } - if (isset($this->page->theme->addblockposition) && + if ( + isset($this->page->theme->addblockposition) && $this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->page->pagelayout !== 'mycourses' @@ -4681,7 +4751,8 @@ EOD; $params['bui_blockregion'] = $region; } $url = new moodle_url($this->page->url, $params); - $addblockbutton = $this->render_from_template('core/add_block_button', + $addblockbutton = $this->render_from_template( + 'core/add_block_button', [ 'link' => $url->out(false), 'escapedlink' => "?{$url->get_query_string(false)}", @@ -4730,8 +4801,10 @@ EOD; public function select_element_for_append(string $selector = '#region-main [role=main]', string $element = 'div') { if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) { - throw new coding_exception('select_element_for_append used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', - DEBUG_DEVELOPER); + throw new coding_exception( + 'select_element_for_append used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', + DEBUG_DEVELOPER + ); } // We are already streaming into this element so don't change anything. @@ -4786,8 +4859,10 @@ EOD; public function select_element_for_replace(string $selector, string $html, bool $outer = false) { if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) { - throw new coding_exception('select_element_for_replace used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', - DEBUG_DEVELOPER); + throw new coding_exception( + 'select_element_for_replace used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', + DEBUG_DEVELOPER + ); } // Escape html for use inside a javascript string. diff --git a/lib/classes/output/core_renderer_ajax.php b/lib/classes/output/core_renderer_ajax.php index a70a42b2ed1..41c9786c454 100644 --- a/lib/classes/output/core_renderer_ajax.php +++ b/lib/classes/output/core_renderer_ajax.php @@ -40,21 +40,23 @@ class core_renderer_ajax extends core_renderer { * @param string $moreinfourl URL where more info can be found about the error * @param string $link Link for the Continue button * @param array $backtrace The execution backtrace - * @param string $debuginfo Debugging information + * @param null|string $debuginfo Debugging information + * @param string $errorcode * @return string A template fragment for a fatal error */ public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") { global $CFG; - $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here + // Ugly hack - make sure page context is set to something, we do not want bogus warnings here. + $this->page->set_context(null); $e = new stdClass(); $e->error = $message; $e->errorcode = $errorcode; - $e->stacktrace = NULL; - $e->debuginfo = NULL; - $e->reproductionlink = NULL; - if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) { + $e->stacktrace = null; + $e->debuginfo = null; + $e->reproductionlink = null; + if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) { $link = (string) $link; if ($link) { $e->reproductionlink = $link; @@ -99,7 +101,8 @@ class core_renderer_ajax extends core_renderer { $delay, $debugdisableredirect, $messagetype = notification::NOTIFY_INFO, - ) {} + ) { + } /** * Prepares the start of an AJAX output. @@ -118,7 +121,7 @@ class core_renderer_ajax extends core_renderer { @header('Content-type: application/json; charset=utf-8'); } - // Headers to make it not cacheable and json + // Headers to make it not cacheable and json. @header('Cache-Control: no-store, no-cache, must-revalidate'); @header('Cache-Control: post-check=0, pre-check=0', false); @header('Pragma: no-cache'); @@ -131,7 +134,8 @@ class core_renderer_ajax extends core_renderer { * There is no footer for an AJAX request, however we must override the * footer method to prevent the default footer. */ - public function footer() {} + public function footer() { + } /** * No need for headers in an AJAX request... this should never happen. @@ -140,7 +144,8 @@ class core_renderer_ajax extends core_renderer { * @param string $classes * @param string $id */ - public function heading($text, $level = 2, $classes = 'main', $id = null) {} + public function heading($text, $level = 2, $classes = 'main', $id = null) { + } } // Alias this class to the old name. diff --git a/lib/classes/output/core_renderer_cli.php b/lib/classes/output/core_renderer_cli.php index 1de38c598a1..d277966bd2a 100644 --- a/lib/classes/output/core_renderer_cli.php +++ b/lib/classes/output/core_renderer_cli.php @@ -33,7 +33,6 @@ use core\check\result as check_result; class core_renderer_cli extends core_renderer { /** * @var array $progressmaximums stores the largest percentage for a progress bar. - * @return string ascii fragment */ private $progressmaximums = []; @@ -59,10 +58,10 @@ class core_renderer_cli extends core_renderer { $status = $result->get_status(); $labels = [ - check_result::NA => ' ' . cli_ansi_format('' ) . ' NA ', + check_result::NA => ' ' . cli_ansi_format('') . ' NA ', check_result::OK => ' ' . cli_ansi_format('') . ' OK ', - check_result::INFO => ' ' . cli_ansi_format('' ) . ' INFO ', - check_result::UNKNOWN => ' ' . cli_ansi_format('' ) . ' UNKNOWN ', + check_result::INFO => ' ' . cli_ansi_format('') . ' INFO ', + check_result::UNKNOWN => ' ' . cli_ansi_format('') . ' UNKNOWN ', check_result::WARNING => ' ' . cli_ansi_format('') . ' WARNING ', check_result::ERROR => ' ' . cli_ansi_format('') . ' ERROR ', check_result::CRITICAL => '' . cli_ansi_format('') . ' CRITICAL ', @@ -96,7 +95,7 @@ class core_renderer_cli extends core_renderer { $ascii = "\n"; if (stream_isatty(STDOUT)) { - require_once($CFG->libdir.'/clilib.php'); + require_once($CFG->libdir . '/clilib.php'); $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n"; return cli_ansi_format($ascii); @@ -199,7 +198,8 @@ class core_renderer_cli extends core_renderer { * @param string $moreinfourl URL where more info can be found about the error * @param string $link Link for the Continue button * @param array $backtrace The execution backtrace - * @param string $debuginfo Debugging information + * @param null|string $debuginfo Debugging information + * @param string $errorcode * @return string A template fragment for a fatal error */ public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") { diff --git a/lib/classes/output/core_renderer_maintenance.php b/lib/classes/output/core_renderer_maintenance.php index 1aee2863dc0..50b4153cb95 100644 --- a/lib/classes/output/core_renderer_maintenance.php +++ b/lib/classes/output/core_renderer_maintenance.php @@ -70,7 +70,7 @@ class core_renderer_maintenance extends core_renderer { * @param boolean $fakeblocksonly * @return string */ - public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) { + public function blocks($region, $classes = [], $tag = 'aside', $fakeblocksonly = false) { return ''; } @@ -158,11 +158,19 @@ class core_renderer_maintenance extends core_renderer { if ($continue instanceof single_button) { $continue->type = single_button::BUTTON_PRIMARY; } else if (is_string($continue)) { - $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', - $displayoptions['type'] ?? single_button::BUTTON_PRIMARY); + $continue = new single_button( + new moodle_url($continue), + get_string('continue'), + 'post', + $displayoptions['type'] ?? single_button::BUTTON_PRIMARY + ); } else if ($continue instanceof moodle_url) { - $continue = new single_button($continue, get_string('continue'), 'post', - $displayoptions['type'] ?? single_button::BUTTON_PRIMARY); + $continue = new single_button( + $continue, + get_string('continue'), + 'post', + $displayoptions['type'] ?? single_button::BUTTON_PRIMARY + ); } else { throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' . ' (string/moodle_url) or a single_button instance.'); @@ -228,10 +236,10 @@ class core_renderer_maintenance extends core_renderer { * Does nothing. The maintenance renderer cannot produce user pictures. * * @param stdClass $user - * @param array $options + * @param null|array $options * @return string */ - public function user_picture(stdClass $user, array $options = null) { + public function user_picture(stdClass $user, ?array $options = null) { return ''; } } diff --git a/lib/classes/output/custom_menu.php b/lib/classes/output/custom_menu.php index 67ab20ee60d..5357df2b78d 100644 --- a/lib/classes/output/custom_menu.php +++ b/lib/classes/output/custom_menu.php @@ -44,7 +44,7 @@ class custom_menu extends custom_menu_item { /** * Creates the custom menu * - * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()} + * @param string $definition the menu items definition in syntax required by {@see convert_text_to_menu_nodes()} * @param string $currentlanguage the current language code, null disables multilang support */ public function __construct($definition = '', $currentlanguage = null) { @@ -62,7 +62,7 @@ class custom_menu extends custom_menu_item { * @param array $children */ public function override_children(array $children) { - $this->children = array(); + $this->children = []; foreach ($children as $child) { if ($child instanceof custom_menu_item) { $this->children[] = $child; @@ -100,7 +100,7 @@ class custom_menu extends custom_menu_item { $root = new custom_menu(); $lastitem = $root; $lastdepth = 0; - $hiddenitems = array(); + $hiddenitems = []; $lines = explode("\n", $text); foreach ($lines as $linenumber => $line) { $line = trim($line); diff --git a/lib/classes/output/custom_menu_item.php b/lib/classes/output/custom_menu_item.php index 314cfeebeb8..c1e1a389530 100644 --- a/lib/classes/output/custom_menu_item.php +++ b/lib/classes/output/custom_menu_item.php @@ -33,17 +33,11 @@ use stdClass; * @category output */ class custom_menu_item implements renderable, templatable { - /** * @var string The text to show for the item */ protected $text; - /** - * @var moodle_url The link to give the icon if it has no children - */ - protected $url; - /** * @var string A title to apply to the item. By default the text */ @@ -55,60 +49,66 @@ class custom_menu_item implements renderable, templatable { */ protected $sort; - /** - * @var custom_menu_item A reference to the parent for this item or NULL if - * it is a top level item - */ - protected $parent; - /** * @var array A array in which to store children this item has. */ - protected $children = array(); + protected $children = []; /** * @var int A reference to the sort var of the last child that was added */ protected $lastsort = 0; - /** @var array Array of other HTML attributes for the custom menu item. */ - protected $attributes = []; - /** * Constructs the new custom menu item * * @param string $text - * @param moodle_url $url A moodle url to apply as the link for this item [Optional] + * @param null|moodle_url $url A moodle url to apply as the link for this item [Optional] * @param string $title A title to apply to this item [Optional] * @param int $sort A sort or to use if we need to sort differently [Optional] - * @param custom_menu_item $parent A reference to the parent custom_menu_item this child + * @param null|custom_menu_item $parent A reference to the parent custom_menu_item this child * belongs to, only if the child has a parent. [Optional] * @param array $attributes Array of other HTML attributes for the custom menu item. */ - public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null, - array $attributes = []) { + public function __construct( + $text, + /** @var moodle_url The link to give the icon if it has no children */ + protected ?moodle_url $url = null, + $title = null, + $sort = null, + /** + * @var custom_menu_item A reference to the parent for this item or NULL if + * it is a top level item + */ + protected ?custom_menu_item $parent = null, + /** @var array Array of other HTML attributes for the custom menu item. */ + protected array $attributes = [], + ) { // Use class setter method for text to ensure it's always a string type. $this->set_text($text); - $this->url = $url; $this->title = $title; $this->sort = (int)$sort; - $this->parent = $parent; - $this->attributes = $attributes; } /** * Adds a custom menu item as a child of this node given its properties. * * @param string $text - * @param moodle_url $url + * @param null|moodle_url $url * @param string $title * @param int $sort * @param array $attributes Array of other HTML attributes for the custom menu item. * @return custom_menu_item */ - public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) { + public function add( + $text, + ?moodle_url $url = null, + $title = null, + $sort = null, + $attributes = [], + ) { $key = count($this->children); if (empty($sort)) { $sort = $this->lastsort + 1; @@ -195,7 +195,7 @@ class custom_menu_item implements renderable, templatable { * Sorts the children this item has */ public function sort() { - usort($this->children, array('custom_menu','sort_custom_menu_items')); + usort($this->children, ['custom_menu', 'sort_custom_menu_items']); } /** @@ -252,7 +252,7 @@ class custom_menu_item implements renderable, templatable { if (!empty($this->attributes)) { $context->attributes = $this->attributes; } - $context->children = array(); + $context->children = []; if (preg_match("/^#+$/", $this->text)) { $context->divider = true; } diff --git a/lib/classes/output/datafilter.php b/lib/classes/output/datafilter.php index 04973ef3d93..e8cef3acf2d 100644 --- a/lib/classes/output/datafilter.php +++ b/lib/classes/output/datafilter.php @@ -28,7 +28,6 @@ use stdClass; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class datafilter implements renderable, templatable { - /** @var int None of the following match */ public const JOINTYPE_NONE = 0; @@ -108,7 +107,7 @@ abstract class datafilter implements renderable, templatable { 'values' => $values, 'filteroptions' => $filteroptions, 'required' => $required, - 'joinlist' => json_encode($joinlist) + 'joinlist' => json_encode($joinlist), ]; } } diff --git a/lib/classes/output/dynamic_tabs.php b/lib/classes/output/dynamic_tabs.php index 1dbb26df2e6..c739934b0d1 100644 --- a/lib/classes/output/dynamic_tabs.php +++ b/lib/classes/output/dynamic_tabs.php @@ -28,7 +28,6 @@ use core\output\dynamic_tabs\base; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class dynamic_tabs implements templatable { - /** @var base[] */ protected $tabs = []; @@ -60,7 +59,7 @@ class dynamic_tabs implements templatable { */ public function export_for_template(renderer_base $output): array { $data = [ - 'tabs' => [] + 'tabs' => [], ]; foreach ($this->tabs as $tab) { diff --git a/lib/classes/output/dynamic_tabs/base.php b/lib/classes/output/dynamic_tabs/base.php index 477b73587ec..213148be34b 100644 --- a/lib/classes/output/dynamic_tabs/base.php +++ b/lib/classes/output/dynamic_tabs/base.php @@ -29,7 +29,6 @@ use core\output\templatable; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class base implements templatable { - /** @var array */ protected $data; diff --git a/lib/classes/output/external.php b/lib/classes/output/external.php index b9c24e049c3..181faf9d6ca 100644 --- a/lib/classes/output/external.php +++ b/lib/classes/output/external.php @@ -39,13 +39,12 @@ class external extends external_api { * @return external_function_parameters */ public static function load_template_parameters() { - return new external_function_parameters( - array('component' => new external_value(PARAM_COMPONENT, 'component containing the template'), - 'template' => new external_value(PARAM_SAFEPATH, 'name of the template'), - 'themename' => new external_value(PARAM_ALPHANUMEXT, 'The current theme.'), - 'includecomments' => new external_value(PARAM_BOOL, 'Include comments or not', VALUE_DEFAULT, false) - ) - ); + return new external_function_parameters([ + 'component' => new external_value(PARAM_COMPONENT, 'component containing the template'), + 'template' => new external_value(PARAM_SAFEPATH, 'name of the template'), + 'themename' => new external_value(PARAM_ALPHANUMEXT, 'The current theme.'), + 'includecomments' => new external_value(PARAM_BOOL, 'Include comments or not', VALUE_DEFAULT, false), + ]); } /** @@ -60,11 +59,15 @@ class external extends external_api { global $DB, $CFG, $PAGE; $PAGE->set_context(context_system::instance()); - $params = self::validate_parameters(self::load_template_parameters(), - array('component' => $component, - 'template' => $template, - 'themename' => $themename, - 'includecomments' => $includecomments)); + $params = self::validate_parameters( + self::load_template_parameters(), + [ + 'component' => $component, + 'template' => $template, + 'themename' => $themename, + 'includecomments' => $includecomments, + ], + ); $loader = new mustache_template_source_loader(); // Will throw exceptions if the template does not exist. @@ -72,7 +75,7 @@ class external extends external_api { $params['component'], $params['template'], $params['themename'], - $params['includecomments'] + $params['includecomments'], ); } @@ -108,7 +111,7 @@ class external extends external_api { * @param string $themename The name of the current theme. * @param bool $includecomments Whether to strip comments from the template source. * @param string $lang moodle translation language, null means use current. - * @return string the template + * @return array the template */ public static function load_template_with_dependencies( string $component, @@ -126,7 +129,7 @@ class external extends external_api { 'template' => $template, 'themename' => $themename, 'includecomments' => $includecomments, - 'lang' => $lang + 'lang' => $lang, ] ); @@ -141,14 +144,14 @@ class external extends external_api { [], $params['lang'] ); - $formatdependencies = function($dependency) { + $formatdependencies = function ($dependency) { $results = []; foreach ($dependency as $dependencycomponent => $dependencyvalues) { foreach ($dependencyvalues as $dependencyname => $dependencyvalue) { array_push($results, [ 'component' => $dependencycomponent, 'name' => $dependencyname, - 'value' => $dependencyvalue + 'value' => $dependencyvalue, ]); } } @@ -159,7 +162,7 @@ class external extends external_api { // by external functions (because they don't support dynamic keys). return [ 'templates' => $formatdependencies($dependencies['templates']), - 'strings' => $formatdependencies($dependencies['strings']) + 'strings' => $formatdependencies($dependencies['strings']), ]; } @@ -172,12 +175,12 @@ class external extends external_api { $resourcestructure = new external_single_structure([ 'component' => new external_value(PARAM_COMPONENT, 'component containing the resource'), 'name' => new external_value(PARAM_TEXT, 'name of the resource'), - 'value' => new external_value(PARAM_RAW, 'resource value') + 'value' => new external_value(PARAM_RAW, 'resource value'), ]); return new external_single_structure([ 'templates' => new external_multiple_structure($resourcestructure), - 'strings' => new external_multiple_structure($resourcestructure) + 'strings' => new external_multiple_structure($resourcestructure), ]); } diff --git a/lib/classes/output/file_picker.php b/lib/classes/output/file_picker.php index 783e29fe71c..2a3bdd3e0d3 100644 --- a/lib/classes/output/file_picker.php +++ b/lib/classes/output/file_picker.php @@ -52,18 +52,18 @@ class file_picker implements renderable { */ public function __construct(stdClass $options) { global $CFG, $USER, $PAGE; - require_once($CFG->dirroot. '/repository/lib.php'); - $defaults = array( - 'accepted_types'=>'*', - 'return_types'=>FILE_INTERNAL, + require_once($CFG->dirroot . '/repository/lib.php'); + $defaults = [ + 'accepted_types' => '*', + 'return_types' => FILE_INTERNAL, 'env' => 'filepicker', 'client_id' => uniqid(), 'itemid' => 0, - 'maxbytes'=>-1, - 'maxfiles'=>1, - 'buttonname'=>false - ); - foreach ($defaults as $key=>$value) { + 'maxbytes' => -1, + 'maxfiles' => 1, + 'buttonname' => false, + ]; + foreach ($defaults as $key => $value) { if (empty($options->$key)) { $options->$key = $value; } @@ -81,15 +81,19 @@ class file_picker implements renderable { $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename); } if (!empty($file)) { - $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename()); + $options->currentfile = html_writer::link(moodle_url::make_draftfile_url( + $file->get_itemid(), + $file->get_filepath(), + $file->get_filename(), + ), $file->get_filename()); } } - // initilise options, getting files in root path + // Initialise options, getting files in root path. $this->options = initialise_filepicker($options); - // copying other options - foreach ($options as $name=>$value) { + // Copying other options. + foreach ($options as $name => $value) { if (!isset($this->options->$name)) { $this->options->$name = $value; } diff --git a/lib/classes/output/help_icon.php b/lib/classes/output/help_icon.php index 6c36b1cf918..4fd2beec17f 100644 --- a/lib/classes/output/help_icon.php +++ b/lib/classes/output/help_icon.php @@ -75,7 +75,7 @@ class help_icon implements renderable, templatable { if (!$sm->string_exists($this->identifier, $this->component)) { debugging("Help title string does not exist: [$this->identifier, $this->component]"); } - if (!$sm->string_exists($this->identifier.'_help', $this->component)) { + if (!$sm->string_exists($this->identifier . '_help', $this->component)) { debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]"); } } @@ -107,7 +107,7 @@ class help_icon implements renderable, templatable { $options = [ 'component' => $this->component, 'identifier' => $this->identifier, - 'lang' => current_language() + 'lang' => current_language(), ]; // Debugging feature lets you display string identifier and component. diff --git a/lib/classes/output/html_writer.php b/lib/classes/output/html_writer.php index 3f00022d876..f9331da6038 100644 --- a/lib/classes/output/html_writer.php +++ b/lib/classes/output/html_writer.php @@ -38,10 +38,10 @@ class html_writer { * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param string $contents What goes between the opening and closing tags - * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) + * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ - public static function tag($tagname, $contents, array $attributes = null) { + public static function tag($tagname, $contents, ?array $attributes = null) { return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname); } @@ -49,10 +49,10 @@ class html_writer { * 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.) + * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ - public static function start_tag($tagname, array $attributes = null) { + public static function start_tag($tagname, ?array $attributes = null) { return '<' . $tagname . self::attributes($attributes) . '>'; } @@ -70,10 +70,10 @@ class html_writer { * 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.) + * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ - public static function empty_tag($tagname, array $attributes = null) { + public static function empty_tag($tagname, ?array $attributes = null) { return '<' . $tagname . self::attributes($attributes) . ' />'; } @@ -82,10 +82,10 @@ class html_writer { * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param string $contents What goes between the opening and closing tags - * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) + * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ - public static function nonempty_tag($tagname, $contents, array $attributes = null) { + public static function nonempty_tag($tagname, $contents, ?array $attributes = null) { if ($contents === '' || is_null($contents)) { return ''; } @@ -96,7 +96,7 @@ class html_writer { * 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()} + * @param string $value The value of the attribute. The value will be escaped with {@see s()} * @return string HTML fragment */ public static function attribute($name, $value) { @@ -104,23 +104,23 @@ class html_writer { return ' ' . $name . '="' . $value->out() . '"'; } - // special case, we do not want these in output + // Special case, we do not want these in output. if ($value === null) { return ''; } - // no sloppy trimming here! + // No sloppy trimming here! 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()} + * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) + * The values will be escaped with {@see s()} * @return string HTML fragment */ - public static function attributes(array $attributes = null) { + public static function attributes(?array $attributes = null) { $attributes = (array)$attributes; $output = ''; foreach ($attributes as $name => $value) { @@ -134,10 +134,10 @@ class html_writer { * * @param string $src The source of image * @param string $alt The alternate text for image - * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.) + * @param null|array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.) * @return string HTML fragment */ - public static function img($src, $alt, array $attributes = null) { + public static function img($src, $alt, ?array $attributes = null) { $attributes = (array)$attributes; $attributes['src'] = $src; // In case a null alt text is provided, set it to an empty string. @@ -161,7 +161,7 @@ class html_writer { * @param string $base A string fragment that will be included in the random ID. * @return string A unique ID */ - public static function random_id($base='random') { + public static function random_id($base = 'random') { static $counter = 0; static $uniq; @@ -170,7 +170,7 @@ class html_writer { } $counter++; - return $base.$uniq.$counter; + return $base . $uniq . $counter; } /** @@ -178,10 +178,10 @@ class html_writer { * * @param string|moodle_url $url The URL * @param string $text The text - * @param array $attributes HTML attributes + * @param null|array $attributes HTML attributes * @return string HTML fragment */ - public static function link($url, $text, array $attributes = null) { + public static function link($url, $text, ?array $attributes = null) { $attributes = (array)$attributes; $attributes['href'] = $url; return self::tag('a', $text, $attributes); @@ -194,16 +194,22 @@ class html_writer { * @param string $value The value of the checkbox * @param bool $checked Whether the checkbox is checked * @param string $label The label for the checkbox - * @param array $attributes Any attributes to apply to the checkbox - * @param array $labelattributes Any attributes to apply to the label, if present + * @param null|array $attributes Any attributes to apply to the checkbox + * @param null|array $labelattributes Any attributes to apply to the label, if present * @return string html fragment */ - public static function checkbox($name, $value, $checked = true, $label = '', - array $attributes = null, array $labelattributes = null) { + public static function checkbox( + $name, + $value, + $checked = true, + $label = '', + ?array $attributes = null, + ?array $labelattributes = null, + ) { $attributes = (array) $attributes; $output = ''; - if ($label !== '' and !is_null($label)) { + if ($label !== '' && !is_null($label)) { if (empty($attributes['id'])) { $attributes['id'] = self::random_id('checkbox_'); } @@ -215,7 +221,7 @@ class html_writer { $output .= self::empty_tag('input', $attributes); - if ($label !== '' and !is_null($label)) { + if ($label !== '' && !is_null($label)) { $labelattributes = (array) $labelattributes; $labelattributes['for'] = $attributes['id']; $output .= self::tag('label', $label, $labelattributes); @@ -229,11 +235,11 @@ class html_writer { * * @param string $name name of select element * @param bool $selected - * @param array $attributes - html select element attributes + * @param null|array $attributes - html select element attributes * @return string HTML fragment */ - public static function select_yes_no($name, $selected=true, array $attributes = null) { - $options = array('1'=>get_string('yes'), '0'=>get_string('no')); + public static function select_yes_no($name, $selected = true, ?array $attributes = null) { + $options = ['1' => get_string('yes'), '0' => get_string('no')]; return self::select($options, $name, $selected, null, $attributes); } @@ -250,41 +256,46 @@ class html_writer { * @param string $name name of select element * @param string|array $selected value or array of values depending on multiple attribute * @param array|bool|null $nothing add nothing selected option, or false of not added - * @param array $attributes html select element attributes + * @param null|array $attributes html select element attributes * @return string HTML fragment */ - public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) { + public static function select( + array $options, + $name, + $selected = '', + $nothing = ['' => 'choosedots'], + ?array $attributes = null, + ) { $attributes = (array)$attributes; if (is_array($nothing)) { - foreach ($nothing as $k=>$v) { - if ($v === 'choose' or $v === 'choosedots') { + foreach ($nothing as $k => $v) { + if ($v === 'choose' || $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; + $options = $nothing + $options; // Keep keys, do not override. + } else if (is_string($nothing) && $nothing !== '') { + // BC. + $options = ['' => $nothing] + $options; } - // we may accept more values if multiple attribute specified + // We may accept more values if multiple attribute specified. $selected = (array)$selected; - foreach ($selected as $k=>$v) { + 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 = 'menu' . $name; + // Name may contain [], 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 = 'menu' . $name; + // Name may contain [], 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; @@ -300,9 +311,9 @@ class html_writer { } $output = ''; - foreach ($options as $value=>$label) { + foreach ($options as $value => $label) { if (is_array($label)) { - // ignore key, it just has to be unique + // 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); @@ -320,7 +331,7 @@ class html_writer { * @return string HTML fragment */ private static function select_option($label, $value, array $selected) { - $attributes = array(); + $attributes = []; $value = (string)$value; if (in_array($value, $selected, true)) { $attributes['selected'] = 'selected'; @@ -341,9 +352,9 @@ class html_writer { if (empty($options)) { return ''; } - $attributes = array('label'=>$groupname); + $attributes = ['label' => $groupname]; $output = ''; - foreach ($options as $value=>$label) { + foreach ($options as $value => $label) { $output .= self::select_option($label, $value, $selected); } return self::tag('optgroup', $output, $attributes); @@ -356,12 +367,12 @@ class html_writer { * @param string $name fieldname * @param int $currenttime A default timestamp in GMT * @param int $step minute spacing - * @param array $attributes - html select element attributes + * @param null|array $attributes - html select element attributes * @param float|int|string $timezone the timezone to use to calculate the time * {@link https://moodledev.io/docs/apis/subsystems/time#timezone} * @return string HTML fragment */ - public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null, $timezone = 99) { + public static function select_time($type, $name, $currenttime = 0, $step = 5, ?array $attributes = null, $timezone = 99) { global $OUTPUT; if (!$currenttime) { @@ -371,7 +382,7 @@ class html_writer { $currentdate = $calendartype->timestamp_to_date_array($currenttime, $timezone); $userdatetype = $type; - $timeunits = array(); + $timeunits = []; switch ($type) { case 'years': @@ -388,17 +399,17 @@ class html_writer { $userdatetype = 'mday'; break; case 'hours': - for ($i=0; $i<=23; $i++) { - $timeunits[$i] = sprintf("%02d",$i); + for ($i = 0; $i <= 23; $i++) { + $timeunits[$i] = sprintf("%02d", $i); } break; case 'minutes': if ($step != 1) { - $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step; + $currentdate['minutes'] = ceil($currentdate['minutes'] / $step) * $step; } - for ($i=0; $i<=59; $i+=$step) { - $timeunits[$i] = sprintf("%02d",$i); + for ($i = 0; $i <= 59; $i += $step) { + $timeunits[$i] = sprintf("%02d", $i); } break; default: @@ -410,21 +421,21 @@ class html_writer { 'name' => $name, 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'), 'label' => get_string(substr($type, 0, -1), 'form'), - 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) { + 'options' => array_map(function ($value) use ($timeunits, $currentdate, $userdatetype) { return [ 'name' => $timeunits[$value], 'value' => $value, - 'selected' => $currentdate[$userdatetype] == $value + 'selected' => $currentdate[$userdatetype] == $value, ]; }, array_keys($timeunits)), ]; unset($attributes['id']); unset($attributes['name']); - $data->attributes = array_map(function($name) use ($attributes) { + $data->attributes = array_map(function ($name) use ($attributes) { return [ 'name' => $name, - 'value' => $attributes[$name] + 'value' => $attributes[$name], ]; }, array_keys($attributes)); @@ -437,14 +448,14 @@ class html_writer { * Note: 'list' is a reserved keyword ;-) * * @param array $items - * @param array $attributes + * @param null|array $attributes * @param string $tag ul or ol * @return string */ - public static function alist(array $items, array $attributes = null, $tag = 'ul') { - $output = self::start_tag($tag, $attributes)."\n"; + public static function alist(array $items, ?array $attributes = null, $tag = 'ul') { + $output = self::start_tag($tag, $attributes) . "\n"; foreach ($items as $item) { - $output .= self::tag('li', $item)."\n"; + $output .= self::tag('li', $item) . "\n"; } $output .= self::end_tag($tag); return $output; @@ -454,10 +465,10 @@ class html_writer { * Returns hidden input fields created from url parameters. * * @param moodle_url $url - * @param array $exclude list of excluded parameters + * @param null|array $exclude list of excluded parameters * @return string HTML fragment */ - public static function input_hidden_params(moodle_url $url, array $exclude = null) { + public static function input_hidden_params(moodle_url $url, ?array $exclude = null) { $exclude = (array)$exclude; $params = $url->params(); foreach ($exclude as $key) { @@ -466,8 +477,8 @@ class html_writer { $output = ''; foreach ($params as $key => $value) { - $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value); - $output .= self::empty_tag('input', $attributes)."\n"; + $attributes = ['type' => 'hidden', 'name' => $key, 'value' => $value]; + $output .= self::empty_tag('input', $attributes) . "\n"; } return $output; } @@ -479,13 +490,11 @@ class html_writer { * @param moodle_url|string $url optional url of the external script, $code ignored if specified * @return string HTML, the code wrapped in '; + $code .= ''; } return $code; } - } /** @@ -1518,7 +1591,7 @@ EOF; // Please note custom CSS is strongly discouraged, // because it can not be overridden by themes! // It is suitable only for things like mod/data which accepts CSS from teachers. - $attributes = array('rel'=>'stylesheet', 'type'=>'text/css'); + $attributes = ['rel' => 'stylesheet', 'type' => 'text/css']; // Add the YUI code first. We want this to be overridden by any Moodle CSS. $code = $this->get_yui3lib_headcss(); @@ -1528,7 +1601,11 @@ EOF; // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets // ignored whenever another resource is added until such time as a redraw // is forced, usually by moving the mouse over the affected element. - $code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css')); + $code .= html_writer::tag( + 'script', + '/** Required in order to fix style inclusion problems in IE with YUI **/', + ['id' => 'firstthemesheet', 'type' => 'text/css'], + ); $urls = $this->cssthemeurls + $this->cssurls; foreach ($urls as $url) { @@ -1550,7 +1627,7 @@ EOF; if (empty($this->extramodules)) { return ''; } - return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules))); + return html_writer::script(js_writer::function_call('M.yui.add_module', [$this->extramodules])); } /** @@ -1588,7 +1665,7 @@ EOF; // Set up global YUI3 loader object - this should contain all code needed by plugins. // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });", - // this needs to be done before including any other script. + // this needs to be done before including any other script. $js .= $this->YUI_config->get_config_functions(); $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n"; $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more. @@ -1600,7 +1677,7 @@ EOF; if ($this->jsinitvariables['head']) { $js = ''; foreach ($this->jsinitvariables['head'] as $data) { - list($var, $value) = $data; + [$var, $value] = $data; $js .= js_writer::set_variable($var, $value, true); } $output .= html_writer::script($js); @@ -1670,7 +1747,7 @@ EOF; if ($CFG->debugdeveloper) { $logconfig->level = 'trace'; } - $this->js_call_amd('core/log', 'setConfig', array($logconfig)); + $this->js_call_amd('core/log', 'setConfig', [$logconfig]); // Add any global JS that needs to run on all pages. $this->js_call_amd('core/page_global', 'init'); $this->js_call_amd('core/utility'); @@ -1692,7 +1769,7 @@ EOF; // Add all needed strings. // First add core strings required for some dialogues. - $this->strings_for_js(array( + $this->strings_for_js([ 'confirm', 'yes', 'no', @@ -1705,17 +1782,17 @@ EOF; // TODO MDL-70830 shortforms should preload the collapseall/expandall strings properly. 'collapseall', 'expandall', - ), 'moodle'); - $this->strings_for_js(array( + ], 'moodle'); + $this->strings_for_js([ 'debuginfo', 'line', 'stacktrace', - ), 'debug'); + ], 'debug'); $this->string_for_js('labelsep', 'langconfig'); if (!empty($this->stringsforjs)) { - $strings = array(); - foreach ($this->stringsforjs as $component=>$v) { - foreach($v as $indentifier => $langstring) { + $strings = []; + foreach ($this->stringsforjs as $component => $v) { + foreach ($v as $indentifier => $langstring) { $strings[$component][$indentifier] = $langstring->out(); } } @@ -1726,7 +1803,7 @@ EOF; if ($this->jsinitvariables['footer']) { $js = ''; foreach ($this->jsinitvariables['footer'] as $data) { - list($var, $value) = $data; + [$var, $value] = $data; $js .= js_writer::set_variable($var, $value, true); } $output .= html_writer::script($js); @@ -1766,9 +1843,9 @@ EOF; /** * Should we generate a bit of content HTML that is only required once on * this page (e.g. the contents of the modchooser), now? Basically, we call - * {@link has_one_time_item_been_created()}, and if the thing has not already + * {@see has_one_time_item_been_created()}, and if the thing has not already * been output, we return true to tell the caller to generate it, and also - * call {@link set_one_time_item_created()} to record the fact that it is + * call {@see set_one_time_item_created()} to record the fact that it is * about to be generated. * * That is, a typical usage pattern (in a renderer method) is: @@ -1796,7 +1873,7 @@ EOF; * Has a particular bit of HTML that is only required once on this page * (e.g. the contents of the modchooser) already been generated? * - * Normally, you can use the {@link should_create_one_time_item_now()} helper + * Normally, you can use the {@see should_create_one_time_item_now()} helper * method rather than calling this method directly. * * @param string $thing identifier for the bit of content. Should be of the form @@ -1811,7 +1888,7 @@ EOF; * Indicate that a particular bit of HTML that is only required once on this * page (e.g. the contents of the modchooser) has been generated (or is about to be)? * - * Normally, you can use the {@link should_create_one_time_item_now()} helper + * Normally, you can use the {@see should_create_one_time_item_now()} helper * method rather than calling this method directly. * * @param string $thing identifier for the bit of content. Should be of the form diff --git a/lib/classes/output/requirements/yui.php b/lib/classes/output/requirements/yui.php index 367177fc80b..58a695191c2 100644 --- a/lib/classes/output/requirements/yui.php +++ b/lib/classes/output/requirements/yui.php @@ -46,8 +46,8 @@ class yui { public $combine; public $filter = null; public $insertBefore = 'firstthemesheet'; - public $groups = array(); - public $modules = array(); + public $groups = []; + public $modules = []; /** @var array The log sources that should be not be logged. */ public $logInclude = []; /** @var array Tog sources that should be logged. */ @@ -58,7 +58,7 @@ class yui { /** * @var array List of functions used by the YUI Loader group pattern recognition. */ - protected $jsconfigfunctions = array(); + protected $jsconfigfunctions = []; /** * Create a new group within the YUI_config system. @@ -70,7 +70,10 @@ class yui { */ public function add_group($name, $config) { if (isset($this->groups[$name])) { - throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group()."); + throw new coding_exception( + "A YUI configuration group for '{$name}' already exists. " . + 'To make changes to this group use YUI_config->update_group().', + ); } $this->groups[$name] = $config; } @@ -88,7 +91,10 @@ class yui { */ public function update_group($name, $config) { if (!isset($this->groups[$name])) { - throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.'); + throw new coding_exception( + 'The Moodle YUI module does not exist. ' . + 'You must define the moodle module config using YUI_config->add_module_config first.', + ); } $this->groups[$name] = $config; } @@ -101,13 +107,15 @@ class yui { * The JS function your write will be passed a single argument 'name' containing the * name of the module being loaded. * - * @param $function String the body of the JavaScript function. This should be used i + * @param string $function String the body of the JavaScript function. This should be used i * @return string the name of the function to use in the group pattern configuration. */ public function set_config_function($function) { $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn'; if (isset($this->jsconfigfunctions[$configname])) { - throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique."); + throw new coding_exception( + "A YUI config function with this name already exists. Config function names must be unique.", + ); } $this->jsconfigfunctions[$configname] = $function; return '@' . $configname . '@'; @@ -119,7 +127,7 @@ class yui { * * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses. * - * @param $file The path to the JavaScript function used for YUI configuration. + * @param string $file The path to the JavaScript function used for YUI configuration. * @return string the name of the function to use in the group pattern configuration. */ public function set_config_source($file) { @@ -136,7 +144,7 @@ class yui { $configfn = $cache->get($keyname); if ($configfn === false) { require_once($CFG->libdir . '/jslib.php'); - $configfn = core_minify::js_files(array($fullpath)); + $configfn = core_minify::js_files([$fullpath]); $cache->set($keyname, $configfn); } } @@ -161,7 +169,7 @@ class yui { /** * Update the header JavaScript with any required modification for the YUI Loader. * - * @param $js String The JavaScript to manipulate. + * @param string $js String The JavaScript to manipulate. * @return string the modified JS string. */ public function update_header_js($js) { @@ -187,10 +195,13 @@ class yui { public function add_module_config($name, $config, $group = null) { if ($group) { if (!isset($this->groups[$name])) { - throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.'); + throw new coding_exception( + 'The Moodle YUI module does not exist. ' . + 'You must define the moodle module config using YUI_config->add_module_config first.', + ); } if (!isset($this->groups[$group]['modules'])) { - $this->groups[$group]['modules'] = array(); + $this->groups[$group]['modules'] = []; } $modules = &$this->groups[$group]['modules']; } else { @@ -212,16 +223,19 @@ class yui { public function add_moodle_metadata() { global $CFG; if (!isset($this->groups['moodle'])) { - throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.'); + throw new coding_exception( + 'The Moodle YUI module does not exist. ' . + 'You must define the moodle module config using YUI_config->add_module_config first.', + ); } if (!isset($this->groups['moodle']['modules'])) { - $this->groups['moodle']['modules'] = array(); + $this->groups['moodle']['modules'] = []; } $cache = cache::make('core', 'yuimodules'); if (!isset($CFG->jsrev) || $CFG->jsrev == -1) { - $metadata = array(); + $metadata = []; $metadata = $this->get_moodle_metadata(); $cache->delete('metadata'); } else { @@ -233,8 +247,10 @@ class yui { } // Merge with any metadata added specific to this page which was added manually. - $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'], - $metadata); + $this->groups['moodle']['modules'] = array_merge( + $this->groups['moodle']['modules'], + $metadata + ); } /** @@ -246,7 +262,7 @@ class yui { * @return array of module metadata */ private function get_moodle_metadata() { - $moodlemodules = array(); + $moodlemodules = []; // Core isn't a plugin type or subsystem - handle it seperately. if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) { $moodlemodules = array_merge($moodlemodules, $module); @@ -286,11 +302,11 @@ class yui { private function get_moodle_path_metadata($path) { // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json. $baseyui = $path . '/yui/src'; - $modules = array(); + $modules = []; if (is_dir($baseyui)) { $items = new DirectoryIterator($baseyui); foreach ($items as $item) { - if ($item->isDot() or !$item->isDir()) { + if ($item->isDot() || !$item->isDir()) { continue; } $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json'); @@ -324,35 +340,34 @@ class yui { // If we are using the local combobase in the loader, we can add a group and still make use of the combo // loader. We just need to specify a different root which includes a slightly different YUI version number // to include our patchlevel. - $patterns = array(); - $modules = array(); + $patterns = []; + $modules = []; foreach ($patchedmodules as $modulename) { // We must define the pattern and module here so that the loader uses our group configuration instead of // the standard module definition. We may lose some metadata provided by upstream but this will be // loaded when the module is loaded anyway. - $patterns[$modulename] = array( + $patterns[$modulename] = [ 'group' => 'yui-patched', - ); - $modules[$modulename] = array(); + ]; + $modules[$modulename] = []; } // Actually add the patch group here. - $this->add_group('yui-patched', array( + $this->add_group('yui-patched', [ 'combine' => true, 'root' => $subversion . '/', 'patterns' => $patterns, 'modules' => $modules, - )); - + ]); } else { // The CDN is in use - we need to instead use the local combobase for this module and override the modules // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the // local base in browser caches. $fullpathbase = $combobase . $subversion . '/'; foreach ($patchedmodules as $modulename) { - $this->modules[$modulename] = array( - 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js' - ); + $this->modules[$modulename] = [ + 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js', + ]; } } } diff --git a/lib/classes/output/select_menu.php b/lib/classes/output/select_menu.php index ee512815299..e642c70b6c6 100644 --- a/lib/classes/output/select_menu.php +++ b/lib/classes/output/select_menu.php @@ -83,7 +83,7 @@ class select_menu implements renderable, templatable { 'name' => $groupname, 'isgroup' => true, 'id' => \html_writer::random_id('select-menu-group'), - 'options' => [] + 'options' => [], ]; } foreach ($optoptions as $optvalue => $optoption) { diff --git a/lib/classes/output/single_button.php b/lib/classes/output/single_button.php index c2dbfb607de..853f8d83f08 100644 --- a/lib/classes/output/single_button.php +++ b/lib/classes/output/single_button.php @@ -40,7 +40,7 @@ class single_button implements renderable { self::BUTTON_SUCCESS, self::BUTTON_DANGER, self::BUTTON_WARNING, - self::BUTTON_INFO + self::BUTTON_INFO, ]; /** @@ -117,7 +117,7 @@ class single_button implements renderable { /** * @var array List of attached actions */ - public $actions = array(); + public $actions = []; /** * @var array $params URL Params @@ -143,8 +143,13 @@ class single_button implements renderable { * @param string $type whether this is a primary button or another type, used for styling * @param array $attributes Attributes for the HTML button tag */ - public function __construct(moodle_url $url, $label, $method = 'post', $type = self::BUTTON_SECONDARY, - $attributes = []) { + public function __construct( + moodle_url $url, + $label, + $method = 'post', + $type = self::BUTTON_SECONDARY, + $attributes = [] + ) { if (is_bool($type)) { debugging('The boolean $primary is deprecated and replaced by $type, use single_button::BUTTON_PRIMARY or self::BUTTON_SECONDARY instead'); @@ -262,7 +267,7 @@ class single_button implements renderable { // Button actions. $actions = $this->actions; - $data->actions = array_map(function($action) use ($output) { + $data->actions = array_map(function ($action) use ($output) { return $action->export_for_template($output); }, $actions); $data->hasactions = !empty($data->actions); diff --git a/lib/classes/output/single_select.php b/lib/classes/output/single_select.php index 6e7954eab42..d4bfa8cc084 100644 --- a/lib/classes/output/single_select.php +++ b/lib/classes/output/single_select.php @@ -33,16 +33,15 @@ use stdClass; * @category output */ class single_select implements renderable, templatable { - /** * @var moodle_url Target url - includes hidden fields */ - var $url; + public $url; /** * @var string Name of the select element. */ - var $name; + public $name; /** * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two) @@ -50,62 +49,62 @@ class single_select implements renderable, templatable { * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) */ - var $options; + public $options; /** * @var string Selected option */ - var $selected; + public $selected; /** * @var array Nothing selected */ - var $nothing; + public $nothing; /** * @var array Extra select field attributes */ - var $attributes = array(); + public $attributes = []; /** * @var string Button label */ - var $label = ''; + public $label = ''; /** * @var array Button label's attributes */ - var $labelattributes = array(); + public $labelattributes = []; /** * @var string Form submit method post or get */ - var $method = 'get'; + public $method = 'get'; /** * @var string Wrapping div class */ - var $class = 'singleselect'; + public $class = 'singleselect'; /** * @var bool True if button disabled, false if normal */ - var $disabled = false; + public $disabled = false; /** * @var string Button tooltip */ - var $tooltip = null; + public $tooltip = null; /** * @var string Form id */ - var $formid = null; + public $formid = null; /** * @var help_icon The help icon for this element. */ - var $helpicon = null; + public $helpicon = null; /** @var component_action[] component action. */ public $actions = []; @@ -119,7 +118,14 @@ class single_select implements renderable, templatable { * @param ?array $nothing * @param string $formid */ - public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) { + public function __construct( + moodle_url $url, + $name, + array $options, + $selected = '', + $nothing = ['' => 'choosedots'], + $formid = null, + ) { $this->url = $url; $this->name = $name; $this->options = $options; @@ -135,7 +141,7 @@ class single_select implements renderable, templatable { * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur. */ public function add_confirm_action($confirmmessage) { - $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage))); + $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', ['message' => $confirmmessage])); } /** @@ -172,10 +178,9 @@ class single_select implements renderable, templatable { * @param string $label * @param array $attributes (optional) */ - public function set_label($label, $attributes = array()) { + public function set_label($label, $attributes = []) { $this->label = $label; $this->labelattributes = $attributes; - } /** @@ -207,7 +212,7 @@ class single_select implements renderable, templatable { unset($attributes['disabled']); // Map the attributes. - $data->attributes = array_map(function($key) use ($attributes) { + $data->attributes = array_map(function ($key) use ($attributes) { return ['name' => $key, 'value' => $attributes[$key]]; }, array_keys($attributes)); @@ -260,7 +265,7 @@ class single_select implements renderable, templatable { $data->options[] = [ 'name' => $optgroupname, 'optgroup' => true, - 'options' => $sublist + 'options' => $sublist, ]; } } else { @@ -268,7 +273,7 @@ class single_select implements renderable, templatable { 'value' => $value, 'name' => $options[$value], 'selected' => strval($this->selected) === strval($value), - 'optgroup' => false + 'optgroup' => false, ]; if ($hasnothing && $nothingkey === $value) { diff --git a/lib/classes/output/sticky_footer.php b/lib/classes/output/sticky_footer.php index fdb88d57251..06e7e3723da 100644 --- a/lib/classes/output/sticky_footer.php +++ b/lib/classes/output/sticky_footer.php @@ -33,7 +33,6 @@ namespace core\output; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class sticky_footer implements named_templatable, renderable { - /** * @var string content of the sticky footer. */ diff --git a/lib/classes/output/tabobject.php b/lib/classes/output/tabobject.php index 7d7fa865833..d0943e6b166 100644 --- a/lib/classes/output/tabobject.php +++ b/lib/classes/output/tabobject.php @@ -23,28 +23,29 @@ use moodle_url; * * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @package core + * @copyright Marina Glancy */ class tabobject implements renderable, templatable { /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */ - var $id; + public $id; /** @var moodle_url|string link */ - var $link; + public $link; /** @var string text on the tab */ - var $text; + public $text; /** @var string title under the link, by defaul equals to text */ - var $title; + public $title; /** @var bool whether to display a link under the tab name when it's selected */ - var $linkedwhenselected = false; + public $linkedwhenselected = false; /** @var bool whether the tab is inactive */ - var $inactive = false; + public $inactive = false; /** @var bool indicates that this tab's child is selected */ - var $activated = false; + public $activated = false; /** @var bool indicates that this tab is selected */ - var $selected = false; + public $selected = false; /** @var array stores children tabobjects */ - var $subtree = array(); + public $subtree = []; /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */ - var $level = 1; + public $level = 1; /** * Constructor @@ -140,7 +141,6 @@ class tabobject implements renderable, templatable { 'level' => $this->level, ]; } - } // Alias this class to the old name. diff --git a/lib/classes/output/tabtree.php b/lib/classes/output/tabtree.php index 62a58a25694..0c47b4cb69b 100644 --- a/lib/classes/output/tabtree.php +++ b/lib/classes/output/tabtree.php @@ -87,7 +87,7 @@ class tabtree extends tabobject { return (object) [ 'tabs' => $tabs, - 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false + 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false, ]; } } diff --git a/lib/classes/output/theme_config.php b/lib/classes/output/theme_config.php index 4edc1b65697..3a056592ac0 100644 --- a/lib/classes/output/theme_config.php +++ b/lib/classes/output/theme_config.php @@ -33,6 +33,9 @@ use moodle_page; use moodle_url; use stdClass; +// phpcs:disable moodle.NamingConventions.ValidVariableName.VariableNameUnderscore +// phpcs:disable moodle.NamingConventions.ValidVariableName.MemberNameUnderscore + /** * This class represents the configuration variables of a Moodle theme. * @@ -44,7 +47,7 @@ use stdClass; * file, you can just ignore those, and the following information for developers. * * Normally, to create an instance of this class, you should use the - * {@link theme_config::load()} factory method to load a themes config.php file. + * {@see theme_config::load()} factory method to load a themes config.php file. * However, normally you don't need to bother, because moodle_page (that is, $PAGE) * will create one for you, accessible as $PAGE->theme. * @@ -54,7 +57,6 @@ use stdClass; * @category output */ class theme_config { - /** * @var string Default theme, used when requested theme not found. */ @@ -66,7 +68,7 @@ class theme_config { /** * @var array You can base your theme on other themes by linking to the other theme as * parents. This lets you use the CSS and layouts from the other themes - * (see {@link theme_config::$layouts}). + * (see {@see theme_config::$layouts}). * That makes it easy to create a new theme that is similar to another one * but with a few changes. In this themes CSS you only need to override * those rules you want to change. @@ -77,7 +79,7 @@ class theme_config { * @var array The names of all the stylesheets from this theme that you would * like included, in order. Give the names of the files without .css. */ - public $sheets = array(); + public $sheets = []; /** * @var array The names of all the stylesheets from parents that should be excluded. @@ -96,7 +98,7 @@ class theme_config { * @var array List of style sheets that are included in the text editor bodies. * Sheets from parent themes are used automatically and can not be excluded. */ - public $editor_sheets = array(); + public $editor_sheets = []; /** * @var bool Whether a fallback version of the stylesheet will be used @@ -108,13 +110,13 @@ class theme_config { * @var array The names of all the javascript files this theme that you would * like included from head, in order. Give the names of the files without .js. */ - public $javascripts = array(); + public $javascripts = []; /** * @var array The names of all the javascript files this theme that you would * like included from footer, in order. Give the names of the files without .js. */ - public $javascripts_footer = array(); + public $javascripts_footer = []; /** * @var array The names of all the javascript files from parents that should @@ -172,11 +174,11 @@ class theme_config { * that someone added blocks using a different theme that used different region * names, and then switched to this theme.) */ - public $layouts = array(); + public $layouts = []; /** * @var string Name of the renderer factory class to use. Must implement the - * {@link renderer_factory} interface. + * {@see renderer_factory} interface. * * This is an advanced feature. Moodle output is generated by 'renderers', * you can customise the HTML that is output by writing custom renderers, @@ -186,8 +188,8 @@ class theme_config { * There are some renderer factories supplied with Moodle. Please follow these * links to see what they do. *
    - *
  • {@link standard_renderer_factory} - the default.
  • - *
  • {@link theme_overridden_renderer_factory} - use this if you want to write + *
  • {@see standard_renderer_factory} - the default.
  • + *
  • {@see theme_overridden_renderer_factory} - use this if you want to write * your own custom renderers in a lib.php file in this theme (or the parent theme).
  • *
*/ @@ -268,7 +270,7 @@ class theme_config { */ public $requiredblocks = false; - //==Following properties are not configurable from theme config.php== + // The Following properties are not configurable from theme config.php. /** * @var string The name of this theme. Set automatically when this theme is @@ -304,7 +306,7 @@ class theme_config { * @var array list of YUI CSS modules to be included on each page. This may be used * to remove cssreset and use cssnormalise module instead. */ - public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase'); + public $yuicssmodules = ['cssreset', 'cssfonts', 'cssgrids', 'cssbase']; /** * An associative array of block manipulations that should be made if the user is using an rtl language. @@ -312,7 +314,7 @@ class theme_config { * This is used when displaying blocks for regions only. * @var array */ - public $blockrtlmanipulations = array(); + public $blockrtlmanipulations = []; /** * @var renderer_factory Instance of the renderer_factory implementation @@ -323,7 +325,7 @@ class theme_config { /** * @var array List of parent config objects. **/ - protected $parent_configs = array(); + protected $parent_configs = []; /** * Used to determine whether we can serve SVG images or not. @@ -365,7 +367,7 @@ class theme_config { /** * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php - * Defaults to {@link core_renderer::blocks_for_region()} + * Defaults to {@see core_renderer::blocks_for_region()} * @var string */ public $blockrendermethod = null; @@ -435,27 +437,24 @@ class theme_config { public static function load($themename) { global $CFG; - // load theme settings from db + // Load theme settings from db. try { - $settings = get_config('theme_'.$themename); + $settings = get_config('theme_' . $themename); } catch (dml_exception $e) { - // most probably moodle tables not created yet + // Most probably moodle tables not created yet. $settings = new stdClass(); } if ($config = self::find_theme_config($themename, $settings)) { return new self($config); - } else if ($themename == self::DEFAULT_THEME) { - throw new coding_exception('Default theme '.self::DEFAULT_THEME.' not available or broken!'); - + throw new coding_exception('Default theme ' . self::DEFAULT_THEME . ' not available or broken!'); } else if ($config = self::find_theme_config($CFG->theme, $settings)) { debugging('This page should be using theme ' . $themename . ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL); return new self($config); - } else { - // bad luck, the requested theme has some problems - admin see details in theme config + // Bad luck, the requested theme has some problems - admin see details in theme config. debugging('This page should be using theme ' . $themename . ' which cannot be initialised. Nor can the site theme ' . $CFG->theme . '. Falling back to ' . self::DEFAULT_THEME, DEBUG_NORMAL); @@ -474,8 +473,8 @@ class theme_config { * @return array description of problems */ public static function diagnose($themename) { - //TODO: MDL-21108 - return array(); + // TODO: MDL-21108. + return []; } /** @@ -483,7 +482,7 @@ class theme_config { * @param stdClass $config */ private function __construct($config) { - global $CFG; //needed for included lib.php files + global $CFG; // Needed for included lib.php files. $this->settings = $config->settings; $this->name = $config->name; @@ -507,49 +506,49 @@ class theme_config { 'removedprimarynavitems', ]; - foreach ($config as $key=>$value) { + foreach ($config as $key => $value) { if (in_array($key, $configurable)) { $this->$key = $value; } } - // verify all parents and load configs and renderers + // Verify all parents and load configs and renderers. foreach ($this->parents as $parent) { if (!$parent_config = self::find_theme_config($parent, $this->settings)) { - // this is not good - better exclude faulty parents + // This is not good - better exclude faulty parents. continue; } - $libfile = $parent_config->dir.'/lib.php'; + $libfile = $parent_config->dir . '/lib.php'; if (is_readable($libfile)) { - // theme may store various function here + // Theme may store various function here. include_once($libfile); } - $renderersfile = $parent_config->dir.'/renderers.php'; + $renderersfile = $parent_config->dir . '/renderers.php'; if (is_readable($renderersfile)) { - // may contain core and plugin renderers and renderer factory + // May contain core and plugin renderers and renderer factory. include_once($renderersfile); } $this->parent_configs[$parent] = $parent_config; } - $libfile = $this->dir.'/lib.php'; + $libfile = $this->dir . '/lib.php'; if (is_readable($libfile)) { - // theme may store various function here + // Theme may store various function here. include_once($libfile); } - $rendererfile = $this->dir.'/renderers.php'; + $rendererfile = $this->dir . '/renderers.php'; if (is_readable($rendererfile)) { - // may contain core and plugin renderers and renderer factory + // May contain core and plugin renderers and renderer factory. include_once($rendererfile); } else { - // check if renderers.php file is missnamed renderer.php - if (is_readable($this->dir.'/renderer.php')) { - debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php. + // Check if renderers.php file is missnamed renderer.php. + if (is_readable($this->dir . '/renderer.php')) { + debugging('Developer hint: ' . $this->dir . '/renderer.php should be renamed to ' . $this->dir . "/renderers.php. See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER); } } - // cascade all layouts properly - foreach ($baseconfig->layouts as $layout=>$value) { + // Cascade all layouts properly. + foreach ($baseconfig->layouts as $layout => $value) { if (!isset($this->layouts[$layout])) { foreach ($this->parent_configs as $parent_config) { if (isset($parent_config->layouts[$layout])) { @@ -561,7 +560,7 @@ class theme_config { } } - //fix arrows if needed + // Fix arrows if needed. $this->check_theme_arrows(); } @@ -573,7 +572,7 @@ class theme_config { * @param moodle_page $page */ public function init_page(moodle_page $page) { - $themeinitfunction = 'theme_'.$this->name.'_page_init'; + $themeinitfunction = 'theme_' . $this->name . '_page_init'; if (function_exists($themeinitfunction)) { $themeinitfunction($page); } @@ -588,9 +587,9 @@ class theme_config { * (unlike > »), and must be accompanied by text. */ private function check_theme_arrows() { - if (!isset($this->rarrow) and !isset($this->larrow)) { + if (!isset($this->rarrow) && !isset($this->larrow)) { // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8... - // Also OK in Win 9x/2K/IE 5.x + // Also OK in Win 9x/2K/IE 5.x. $this->rarrow = '►'; $this->larrow = '◄'; $this->uarrow = '▲'; @@ -600,25 +599,29 @@ class theme_config { } else { $uagent = $_SERVER['HTTP_USER_AGENT']; } - if (false !== strpos($uagent, 'Opera') - || false !== strpos($uagent, 'Mac')) { + if ( + false !== strpos($uagent, 'Opera') + || false !== strpos($uagent, 'Mac') + ) { // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari. // Not broken in Mac/IE 5, Mac/Netscape 7 (?). $this->rarrow = '▶︎'; $this->larrow = '◀︎'; - } - elseif ((false !== strpos($uagent, 'Konqueror')) - || (false !== strpos($uagent, 'Android'))) { + } else if ( + (false !== strpos($uagent, 'Konqueror')) + || (false !== strpos($uagent, 'Android')) + ) { // The fonts on Android don't include the characters required for this to work as expected. // So we use the same ones Konqueror uses. $this->rarrow = '→'; $this->larrow = '←'; $this->uarrow = '↑'; $this->darrow = '↓'; - } - elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET']) - && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) { - // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.) + } else if ( + isset($_SERVER['HTTP_ACCEPT_CHARSET']) + && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8') + ) { + // Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode. // To be safe, non-Unicode browsers! $this->rarrow = '>'; $this->larrow = '<'; @@ -626,7 +629,7 @@ class theme_config { $this->darrow = 'v'; } - // RTL support - in RTL languages, swap r and l arrows + // RTL support - in RTL languages, swap r and l arrows. if (right_to_left()) { $t = $this->rarrow; $this->rarrow = $this->larrow; @@ -642,12 +645,12 @@ class theme_config { * @return array */ public function renderer_prefixes() { - global $CFG; // just in case the included files need it + global $CFG; // Just in case the included files need it. - $prefixes = array('theme_'.$this->name); + $prefixes = ['theme_' . $this->name]; foreach ($this->parent_configs as $parent) { - $prefixes[] = 'theme_'.$parent->name; + $prefixes[] = 'theme_' . $parent->name; } return $prefixes; @@ -659,7 +662,7 @@ class theme_config { * @param bool $encoded false means use & and true use & in URLs * @return moodle_url */ - public function editor_css_url($encoded=true) { + public function editor_css_url($encoded = true) { global $CFG; $rev = theme_get_revision(); $type = 'editor'; @@ -701,14 +704,14 @@ class theme_config { * @return array */ public function editor_css_files() { - $files = array(); + $files = []; // First editor plugins. $plugins = core_component::get_plugin_list('editor'); foreach ($plugins as $plugin => $fulldir) { $sheetfile = "$fulldir/editor_styles.css"; if (is_readable($sheetfile)) { - $files['plugin_'.$plugin] = $sheetfile; + $files['plugin_' . $plugin] = $sheetfile; } $subplugintypes = core_component::get_subplugins("editor_{$plugin}") ?? []; @@ -732,7 +735,7 @@ class theme_config { foreach ($parent_config->editor_sheets as $sheet) { $sheetfile = "$parent_config->dir/style/$sheet.css"; if (is_readable($sheetfile)) { - $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile; + $files['parent_' . $parent_config->name . '_' . $sheet] = $sheetfile; } } } @@ -741,7 +744,7 @@ class theme_config { foreach ($this->editor_sheets as $sheet) { $sheetfile = "$this->dir/style/$sheet.css"; if (is_readable($sheetfile)) { - $files['theme_'.$sheet] = $sheetfile; + $files['theme_' . $sheet] = $sheetfile; } } } @@ -804,7 +807,7 @@ class theme_config { $rev = theme_get_revision(); - $urls = array(); + $urls = []; $svg = $this->use_svg_icons(); $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10')); @@ -825,15 +828,15 @@ class theme_config { if (!$svg) { // We add a simple /_s to the start of the path. // The underscore is used to ensure that it isn't a valid theme name. - $slashargs .= '/_s'.$slashargs; + $slashargs .= '/_s' . $slashargs; } - $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename; + $slashargs .= '/' . $this->name . '/' . $rev . '/' . $filename; if ($separate) { $slashargs .= '/chunk0'; } $url->set_slashargument($slashargs, 'noparam', true); } else { - $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename); + $params = ['theme' => $this->name, 'rev' => $rev, 'type' => $filename]; if (!$svg) { // We add an SVG param so that we know not to serve SVG images. // We do this because all modern browsers support SVG and this param will one day be removed. @@ -845,7 +848,6 @@ class theme_config { $url->params($params); } $urls[] = $url; - } else { $baseurl = new moodle_url('/theme/styles_debug.php'); @@ -864,33 +866,42 @@ class theme_config { } if (core_useragent::is_ie()) { // Lalala, IE does not allow more than 31 linked CSS files from main document. - $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins')); - foreach ($css['parents'] as $parent=>$sheets) { + $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'ie', 'subtype' => 'plugins']); + foreach ($css['parents'] as $parent => $sheets) { // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096). - $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent)); + $urls[] = new moodle_url($baseurl, [ + 'theme' => $this->name, + 'type' => 'ie', + 'subtype' => 'parents', + 'sheet' => $parent, + ]); } if ($this->get_scss_property()) { // No need to define the type as IE here. - $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss')); + $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'scss']); } - $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme')); - + $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'ie', 'subtype' => 'theme']); } else { - foreach ($css['plugins'] as $plugin=>$unused) { - $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin)); + foreach ($css['plugins'] as $plugin => $unused) { + $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'plugin', 'subtype' => $plugin]); } - foreach ($css['parents'] as $parent=>$sheets) { - foreach ($sheets as $sheet=>$unused2) { - $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet)); + foreach ($css['parents'] as $parent => $sheets) { + foreach ($sheets as $sheet => $unused2) { + $urls[] = new moodle_url($baseurl, [ + 'theme' => $this->name, + 'type' => 'parent', + 'subtype' => $parent, + 'sheet' => $sheet, + ]); } } foreach ($css['theme'] as $sheet => $filename) { if ($sheet === self::SCSS_KEY) { // This is the theme SCSS file. - $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss')); + $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'scss']); } else { // Sheet first in order to make long urls easier to read. - $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); + $urls[] = new moodle_url($baseurl, ['sheet' => $sheet, 'theme' => $this->name, 'type' => 'theme']); } } } @@ -1011,16 +1022,15 @@ class theme_config { return ''; } - $cssfiles = array(); + $cssfiles = []; $css = $this->get_css_files(true); if ($type === 'ie') { // IE is a sloppy browser with weird limits, sorry. if ($subtype === 'plugins') { $cssfiles = $css['plugins']; - } else if ($subtype === 'parents') { - if (empty($sheet)) { + if (empty($sheet)) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf // Do not bother with the empty parent here. } else { // Build up the CSS for that parent so we can serve it as one file. @@ -1038,17 +1048,14 @@ class theme_config { } } } - } else if ($type === 'plugin') { if (isset($css['plugins'][$subtype])) { $cssfiles[] = $css['plugins'][$subtype]; } - } else if ($type === 'parent') { if (isset($css['parents'][$subtype][$sheet])) { $cssfiles[] = $css['parents'][$subtype][$sheet]; } - } else if ($type === 'theme') { if (isset($css['theme'][$sheet])) { $cssfiles[] = $css['theme'][$sheet]; @@ -1061,7 +1068,7 @@ class theme_config { $contents = $this->post_process($contents); $comment = "/** Path: $type $subtype $sheet.' **/\n"; $stats = ''; - $csscontent .= $comment.$stats.$contents."\n\n"; + $csscontent .= $comment . $stats . $contents . "\n\n"; } return $csscontent; @@ -1080,7 +1087,7 @@ class theme_config { // If editor has static CSS, include it. foreach ($cssfiles as $file) { - $css .= file_get_contents($file)."\n"; + $css .= file_get_contents($file) . "\n"; } // If editor has SCSS, compile and include it. @@ -1105,10 +1112,10 @@ class theme_config { $cache = null; $cachekey = 'cssfiles'; if ($themedesigner) { - require_once($CFG->dirroot.'/lib/csslib.php'); + require_once($CFG->dirroot . '/lib/csslib.php'); // We need some kind of caching here because otherwise the page navigation becomes // way too slow in theme designer mode. Feel free to create full cache definition later... - $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name)); + $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', ['theme' => $this->name]); if ($files = $cache->get($cachekey)) { if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) { unset($files['created']); @@ -1117,30 +1124,33 @@ class theme_config { } } - $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array()); + $cssfiles = ['plugins' => [], 'parents' => [], 'theme' => []]; // Get all plugin sheets. $excludes = $this->resolve_excludes('plugins_exclude_sheets'); if ($excludes !== true) { - foreach (core_component::get_plugin_types() as $type=>$unused) { - if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) { + foreach (core_component::get_plugin_types() as $type => $unused) { + if ($type === 'theme' || (!empty($excludes[$type]) && $excludes[$type] === true)) { continue; } $plugins = core_component::get_plugin_list($type); - foreach ($plugins as $plugin=>$fulldir) { - if (!empty($excludes[$type]) and is_array($excludes[$type]) - and in_array($plugin, $excludes[$type])) { + foreach ($plugins as $plugin => $fulldir) { + if ( + !empty($excludes[$type]) + && is_array($excludes[$type]) + && in_array($plugin, $excludes[$type]) + ) { continue; } // Get the CSS from the plugin. $sheetfile = "$fulldir/styles.css"; if (is_readable($sheetfile)) { - $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile; + $cssfiles['plugins'][$type . '_' . $plugin] = $sheetfile; } // Create a list of candidate sheets from parents (direct parent last) and current theme. - $candidates = array(); + $candidates = []; foreach (array_reverse($this->parent_configs) as $parent_config) { $candidates[] = $parent_config->name; } @@ -1150,7 +1160,7 @@ class theme_config { foreach ($candidates as $candidate) { $sheetthemefile = "$fulldir/styles_{$candidate}.css"; if (is_readable($sheetthemefile)) { - $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile; + $cssfiles['plugins'][$type . '_' . $plugin . '_' . $candidate] = $sheetthemefile; } } } @@ -1162,12 +1172,14 @@ class theme_config { if ($excludes !== true) { foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. $parent = $parent_config->name; - if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) { + if (empty($parent_config->sheets) || (!empty($excludes[$parent]) && $excludes[$parent] === true)) { continue; } foreach ($parent_config->sheets as $sheet) { - if (!empty($excludes[$parent]) && is_array($excludes[$parent]) - && in_array($sheet, $excludes[$parent])) { + if ( + !empty($excludes[$parent]) && is_array($excludes[$parent]) + && in_array($sheet, $excludes[$parent]) + ) { continue; } @@ -1180,7 +1192,6 @@ class theme_config { } } - // Current theme sheets. // We first add the SCSS file because we want the CSS ones to // be included after the SCSS code. @@ -1213,7 +1224,7 @@ class theme_config { protected function get_css_content_from_scss($themedesigner) { global $CFG; - list($paths, $scss) = $this->get_scss_property(); + [$paths, $scss] = $this->get_scss_property(); if (!$scss) { throw new coding_exception('The theme did not define a SCSS file, or it is not readable.'); } @@ -1228,11 +1239,11 @@ class theme_config { $cachedir = make_localcache_directory('scsscache-' . $this->name, false); $cacheoptions = []; if ($themedesigner) { - $cacheoptions = array( + $cacheoptions = [ 'cacheDir' => $cachedir, 'prefix' => 'scssphp_', 'forceRefresh' => false, - ); + ]; } else { if (file_exists($cachedir)) { remove_dir($cachedir); @@ -1246,7 +1257,7 @@ class theme_config { // Enable source maps. $compiler->setSourceMapOptions([ 'sourceMapBasepath' => str_replace('\\', '/', $CFG->dirroot), - 'sourceMapRootpath' => $CFG->wwwroot . '/' + 'sourceMapRootpath' => $CFG->wwwroot . '/', ]); $compiler->setSourceMap($compiler::SOURCE_MAP_INLINE); } @@ -1263,7 +1274,6 @@ class theme_config { try { // Compile! $compiled = $compiler->to_css(); - } catch (\Exception $e) { $compiled = false; debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER); @@ -1321,7 +1331,7 @@ class theme_config { * * This is intended to be used by themes to inject some SCSS code * before it gets compiled. If you want to inject variables you - * should use {@link self::get_scss_variables()}. + * should use {@see self::get_scss_variables()}. * * @return string The SCSS code to inject. */ @@ -1329,7 +1339,7 @@ class theme_config { $content = ''; // Getting all the candidate functions. - $candidates = array(); + $candidates = []; foreach (array_reverse($this->parent_configs) as $parent_config) { if (!isset($parent_config->extrascsscallback)) { continue; @@ -1362,7 +1372,7 @@ class theme_config { $content = ''; // Getting all the candidate functions. - $candidates = array(); + $candidates = []; foreach (array_reverse($this->parent_configs) as $parent_config) { if (!isset($parent_config->prescsscallback)) { continue; @@ -1416,7 +1426,6 @@ class theme_config { if ($scss && is_dir($path)) { $paths[] = $path; } - } $this->scsscache = $scss !== null ? [$paths, $scss] : false; @@ -1438,17 +1447,17 @@ class theme_config { global $CFG; $rev = theme_get_revision(); - $params = array('theme'=>$this->name,'rev'=>$rev); + $params = ['theme' => $this->name, 'rev' => $rev]; $params['type'] = $inhead ? 'head' : 'footer'; - // Return early if there are no files to serve + // Return early if there are no files to serve. if (count($this->javascript_files($params['type'])) === 0) { return null; } - if (!empty($CFG->slasharguments) and $rev > 0) { + if (!empty($CFG->slasharguments) && $rev > 0) { $url = new moodle_url("/theme/javascript.php"); - $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true); + $url->set_slashargument('/' . $this->name . '/' . $rev . '/' . $params['type'], 'noparam', true); return $url; } else { return new moodle_url('/theme/javascript.php', $params); @@ -1470,21 +1479,24 @@ class theme_config { $type = 'javascripts'; } - $js = array(); - // find out wanted parent javascripts + $js = []; + // Find out wanted parent javascripts. $excludes = $this->resolve_excludes('parents_exclude_javascripts'); if ($excludes !== true) { - foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last + foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. $parent = $parent_config->name; if (empty($parent_config->$type)) { continue; } - if (!empty($excludes[$parent]) and $excludes[$parent] === true) { + if (!empty($excludes[$parent]) && $excludes[$parent] === true) { continue; } foreach ($parent_config->$type as $javascript) { - if (!empty($excludes[$parent]) and is_array($excludes[$parent]) - and in_array($javascript, $excludes[$parent])) { + if ( + !empty($excludes[$parent]) + && is_array($excludes[$parent]) + && in_array($javascript, $excludes[$parent]) + ) { continue; } $javascriptfile = "$parent_config->dir/javascript/$javascript.js"; @@ -1495,7 +1507,7 @@ class theme_config { } } - // current theme javascripts + // Current theme javascripts. if (is_array($this->$type)) { foreach ($this->$type as $javascript) { $javascriptfile = "$this->dir/javascript/$javascript.js"; @@ -1517,14 +1529,14 @@ class theme_config { */ protected function resolve_excludes($variable, $default = null) { $setting = $default; - if (is_array($this->{$variable}) or $this->{$variable} === true) { + if (is_array($this->{$variable}) || $this->{$variable} === true) { $setting = $this->{$variable}; } else { - foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last + foreach ($this->parent_configs as $parent_config) { // The immediate parent first, base last. if (!isset($parent_config->{$variable})) { continue; } - if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) { + if (is_array($parent_config->{$variable}) || $parent_config->{$variable} === true) { $setting = $parent_config->{$variable}; break; } @@ -1543,7 +1555,7 @@ class theme_config { $jsfiles = $this->javascript_files($type); $js = ''; foreach ($jsfiles as $jsfile) { - $js .= file_get_contents($jsfile)."\n"; + $js .= file_get_contents($jsfile) . "\n"; } return $js; } @@ -1560,9 +1572,9 @@ class theme_config { * @return string The processed CSS. */ public function post_process($css) { - // now resolve all image locations + // Now resolve all image locations. if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) { - $replaced = array(); + $replaced = []; foreach ($matches as $match) { if (isset($replaced[$match[0]])) { continue; @@ -1571,7 +1583,7 @@ class theme_config { $imagename = $match[2]; $component = rtrim($match[1], '|'); $imageurl = $this->image_url($imagename, $component)->out(false); - // we do not need full url because the image.php is always in the same dir + // We do not need full url because the image.php is always in the same dir. $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl); $css = str_replace($match[0], $imageurl, $css); } @@ -1579,7 +1591,7 @@ class theme_config { // Now resolve all font locations. if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) { - $replaced = array(); + $replaced = []; foreach ($matches as $match) { if (isset($replaced[$match[0]])) { continue; @@ -1605,7 +1617,6 @@ class theme_config { $treeprocessor = $this->get_css_tree_post_processor(); $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode); if ($needsparsing) { - // We might need more memory/time to do this, so let's play safe. raise_memory_limit(MEMORY_EXTRA); core_php_time_limit::raise(300); @@ -1667,10 +1678,10 @@ class theme_config { public function image_url($imagename, $component) { global $CFG; - $params = array('theme'=>$this->name); + $params = ['theme' => $this->name]; $svg = $this->use_svg_icons(); - if (empty($component) or $component === 'moodle' or $component === 'core') { + if (empty($component) || $component === 'moodle' || $component === 'core') { $params['component'] = 'core'; } else { $params['component'] = $component; @@ -1684,12 +1695,12 @@ class theme_config { $params['image'] = $imagename; $url = new moodle_url("/theme/image.php"); - if (!empty($CFG->slasharguments) and $rev > 0) { - $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image']; + if (!empty($CFG->slasharguments) && $rev > 0) { + $path = '/' . $params['theme'] . '/' . $params['component'] . '/' . $params['rev'] . '/' . $params['image']; if (!$svg) { // We add a simple /_s to the start of the path. // The underscore is used to ensure that it isn't a valid theme name. - $path = '/_s'.$path; + $path = '/_s' . $path; } $url->set_slashargument($path, 'noparam', true); } else { @@ -1714,9 +1725,9 @@ class theme_config { public function font_url($font, $component) { global $CFG; - $params = array('theme'=>$this->name); + $params = ['theme' => $this->name]; - if (empty($component) or $component === 'moodle' or $component === 'core') { + if (empty($component) || $component === 'moodle' || $component === 'core') { $params['component'] = 'core'; } else { $params['component'] = $component; @@ -1730,8 +1741,8 @@ class theme_config { $params['font'] = $font; $url = new moodle_url("/theme/font.php"); - if (!empty($CFG->slasharguments) and $rev > 0) { - $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font']; + if (!empty($CFG->slasharguments) && $rev > 0) { + $path = '/' . $params['theme'] . '/' . $params['component'] . '/' . $params['rev'] . '/' . $params['font']; $url->set_slashargument($path, 'noparam', true); } else { $url->params($params); @@ -1757,12 +1768,15 @@ class theme_config { return null; } - $component = 'theme_'.$this->name; + $component = 'theme_' . $this->name; $itemid = theme_get_revision(); $filepath = $this->settings->$setting; $syscontext = context_system::instance(); - $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath); + $url = moodle_url::make_file_url( + "$CFG->wwwroot/pluginfile.php", + "/$syscontext->id/$component/$filearea/$itemid" . $filepath, + ); // Now this is tricky because the we can not hardcode http or https here, lets use the relative link. // Note: unfortunately moodle_url does not support //urls yet. @@ -1786,13 +1800,13 @@ class theme_config { require_once("$CFG->libdir/filelib.php"); $syscontext = context_system::instance(); - $component = 'theme_'.$this->name; + $component = 'theme_' . $this->name; $revision = array_shift($args); if ($revision < 0) { $lifetime = 0; } else { - $lifetime = 60*60*24*60; + $lifetime = 60 * 60 * 24 * 60; // By default, theme files must be cache-able by both browsers and proxies. if (!array_key_exists('cacheability', $options)) { $options['cacheability'] = 'public'; @@ -1836,11 +1850,11 @@ class theme_config { $svg = $this->use_svg_icons(); } - if ($component === 'moodle' or $component === 'core' or empty($component)) { + if ($component === 'moodle' || $component === 'core' || empty($component)) { if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) { return $imagefile; } - foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last + foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) { return $imagefile; } @@ -1852,26 +1866,24 @@ class theme_config { return $imagefile; } return null; - - } else if ($component === 'theme') { //exception + } else if ($component === 'theme') { // Exception. if ($image === 'favicon') { return "$this->dir/pix/favicon.ico"; } if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) { return $imagefile; } - foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last + foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) { return $imagefile; } } return null; - } else { if (strpos($component, '_') === false) { $component = "mod_{$component}"; } - list($type, $plugin) = explode('_', $component, 2); + [$type, $plugin] = explode('_', $component, 2); // In Moodle 4.0 we introduced a new image format. // Support that image format here. @@ -1923,7 +1935,7 @@ class theme_config { public function resolve_font_location($font, $component) { global $CFG; - if ($component === 'moodle' or $component === 'core' or empty($component)) { + if ($component === 'moodle' || $component === 'core' || empty($component)) { if (file_exists("$this->dir/fonts_core/$font")) { return "$this->dir/fonts_core/$font"; } @@ -1939,7 +1951,6 @@ class theme_config { return "$CFG->dirroot/lib/fonts/$font"; } return null; - } else if ($component === 'theme') { // Exception. if (file_exists("$this->dir/fonts/$font")) { return "$this->dir/fonts/$font"; @@ -1950,12 +1961,11 @@ class theme_config { } } return null; - } else { if (strpos($component, '_') === false) { - $component = 'mod_'.$component; + $component = 'mod_' . $component; } - list($type, $plugin) = explode('_', $component, 2); + [$type, $plugin] = explode('_', $component, 2); if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) { return "$this->dir/fonts_plugins/$type/$plugin/$font"; @@ -2054,13 +2064,13 @@ class theme_config { private static function image_exists($filepath, $svg = false) { if ($svg && file_exists("$filepath.svg")) { return "$filepath.svg"; - } else if (file_exists("$filepath.png")) { + } else if (file_exists("$filepath.png")) { return "$filepath.png"; } else if (file_exists("$filepath.gif")) { return "$filepath.gif"; - } else if (file_exists("$filepath.jpg")) { + } else if (file_exists("$filepath.jpg")) { return "$filepath.jpg"; - } else if (file_exists("$filepath.jpeg")) { + } else if (file_exists("$filepath.jpeg")) { return "$filepath.jpeg"; } else { return false; @@ -2088,12 +2098,12 @@ class theme_config { $THEME->dir = $dir; $THEME->settings = $settings; - global $CFG; // just in case somebody tries to use $CFG in theme config + global $CFG; // Just in case somebody tries to use $CFG in theme config. include("$THEME->dir/config.php"); - // verify the theme configuration is OK + // Verify the theme configuration is OK. if (!is_array($THEME->parents)) { - // parents option is mandatory now + // Parents option is mandatory now. return null; } else { // We use $parentscheck to only check the direct parents (avoid infinite loop). @@ -2123,16 +2133,14 @@ class theme_config { if (file_exists("$CFG->dirroot/theme/$themename/config.php")) { $dir = "$CFG->dirroot/theme/$themename"; - - } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) { + } else if (!empty($CFG->themedir) && file_exists("$CFG->themedir/$themename/config.php")) { $dir = "$CFG->themedir/$themename"; - } else { return null; } if (file_exists("$dir/styles.php")) { - //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page + // Legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page. return null; } @@ -2158,10 +2166,10 @@ class theme_config { } /** - * Get the information from {@link $layouts} for this type of page. + * Get the information from {@see $layouts} for this type of page. * * @param string $pagelayout the the page layout name. - * @return array the appropriate part of {@link $layouts}. + * @return array the appropriate part of {@see $layouts}. */ protected function layout_info_for_page($pagelayout) { if (array_key_exists($pagelayout, $this->layouts)) { @@ -2176,7 +2184,7 @@ class theme_config { * Given the settings of this theme, and the page pagelayout, return the * full path of the page layout file to use. * - * Used by {@link core_renderer::header()}. + * Used by {@see core_renderer::header()}. * * @param string $pagelayout the the page layout name. * @return string Full path to the lyout file to use @@ -2188,9 +2196,9 @@ class theme_config { $layoutfile = $layoutinfo['file']; if (array_key_exists('theme', $layoutinfo)) { - $themes = array($layoutinfo['theme']); + $themes = [$layoutinfo['theme']]; } else { - $themes = array_merge(array($this->name),$this->parents); + $themes = array_merge([$this->name], $this->parents); } foreach ($themes as $theme) { @@ -2218,7 +2226,7 @@ class theme_config { if (!empty($info['options'])) { return $info['options']; } - return array(); + return []; } /** @@ -2269,7 +2277,7 @@ class theme_config { * @return array internal region name => human readable name. */ public function get_all_block_regions() { - $regions = array(); + $regions = []; foreach ($this->layouts as $layoutinfo) { foreach ($layoutinfo['regions'] as $region) { $regions[$region] = $this->get_region_name($region, $this->name); @@ -2284,7 +2292,7 @@ class theme_config { * @return string */ public function get_theme_name() { - return get_string('pluginname', 'theme_'.$this->name); + return get_string('pluginname', 'theme_' . $this->name); } /** @@ -2327,7 +2335,6 @@ class theme_config { } return null; } - } // Alias this class to the old name. // This file will be autoloaded by the legacyclasses autoload system. diff --git a/lib/classes/output/theme_usage.php b/lib/classes/output/theme_usage.php index 21d33dda046..19633dc8642 100644 --- a/lib/classes/output/theme_usage.php +++ b/lib/classes/output/theme_usage.php @@ -25,7 +25,6 @@ namespace core\output; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class theme_usage { - /** @var string The theme usage type for users. */ public const THEME_USAGE_TYPE_USER = 'user'; @@ -61,7 +60,6 @@ class theme_usage { $isused = $cache->get($themename); if ($isused === false) { - $sqlunions = []; // For each context, check if the config is enabled and there is at least one use. @@ -119,7 +117,6 @@ class theme_usage { // Cache the result so we don't have to keep checking for this theme. $cache->set($themename, $isused); return $isused; - } else { return $isused; } diff --git a/lib/classes/output/url_rewriter.php b/lib/classes/output/url_rewriter.php index eacd434ed2f..5cc5270d6a2 100644 --- a/lib/classes/output/url_rewriter.php +++ b/lib/classes/output/url_rewriter.php @@ -25,8 +25,6 @@ namespace core\output; -defined('MOODLE_INTERNAL') || die(); - /** * URL rewriter interface * @@ -36,7 +34,6 @@ defined('MOODLE_INTERNAL') || die(); * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ interface url_rewriter { - /** * Rewrite moodle_urls into another form. * @@ -52,7 +49,4 @@ interface url_rewriter { * @return void */ public static function html_head_setup(); - - } - diff --git a/lib/classes/output/url_select.php b/lib/classes/output/url_select.php index 0f043fa0815..3068f443ae9 100644 --- a/lib/classes/output/url_select.php +++ b/lib/classes/output/url_select.php @@ -36,62 +36,62 @@ class url_select implements renderable, templatable { * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) */ - var $urls; + public $urls; /** * @var string Selected option */ - var $selected; + public $selected; /** * @var array Nothing selected */ - var $nothing; + public $nothing; /** * @var array Extra select field attributes */ - var $attributes = array(); + public $attributes = []; /** * @var string Button label */ - var $label = ''; + public $label = ''; /** * @var array Button label's attributes */ - var $labelattributes = array(); + public $labelattributes = []; /** * @var string Wrapping div class */ - var $class = 'urlselect'; + public $class = 'urlselect'; /** * @var bool True if button disabled, false if normal */ - var $disabled = false; + public $disabled = false; /** * @var string Button tooltip */ - var $tooltip = null; + public $tooltip = null; /** * @var string Form id */ - var $formid = null; + public $formid = null; /** * @var help_icon The help icon for this element. */ - var $helpicon = null; + public $helpicon = null; /** * @var string If set, makes button visible with given name for button */ - var $showbutton = null; + public $showbutton = null; /** * Constructor @@ -102,7 +102,7 @@ class url_select implements renderable, templatable { * @param string $showbutton Set to text of button if it should be visible * or null if it should be hidden (hidden version always has text 'go') */ - public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) { + public function __construct(array $urls, $selected = '', $nothing = ['' => 'choosedots'], $formid = null, $showbutton = null) { $this->urls = $urls; $this->selected = $selected; $this->nothing = $nothing; @@ -135,7 +135,7 @@ class url_select implements renderable, templatable { * @param string $label * @param array $attributes (optional) */ - public function set_label($label, $attributes = array()) { + public function set_label($label, $attributes = []) { $this->label = $label; $this->labelattributes = $attributes; } @@ -149,12 +149,11 @@ class url_select implements renderable, templatable { protected function clean_url($value) { global $CFG; + // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf if (empty($value)) { // Nothing. - } else if (strpos($value, $CFG->wwwroot . '/') === 0) { $value = str_replace($CFG->wwwroot, '', $value); - } else if (strpos($value, '/') !== 0) { debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER); } @@ -181,7 +180,7 @@ class url_select implements renderable, templatable { $flattened[$groupname] = [ 'name' => $groupname, 'isgroup' => true, - 'options' => [] + 'options' => [], ]; } foreach ($optoptions as $optvalue => $optoption) { @@ -193,7 +192,6 @@ class url_select implements renderable, templatable { ]; } } - } else { $cleanedvalue = $this->clean_url($value); $flattened[$cleanedvalue] = [ @@ -208,7 +206,7 @@ class url_select implements renderable, templatable { $value = key($nothing); $name = reset($nothing); $flattened = [ - $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value] + $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value], ] + $flattened; } diff --git a/lib/classes/output/user_picture.php b/lib/classes/output/user_picture.php index a7947b6430c..8da6537c581 100644 --- a/lib/classes/output/user_picture.php +++ b/lib/classes/output/user_picture.php @@ -17,6 +17,7 @@ namespace core\output; use core\context\user as context_user; +use core\exception\coding_exception; use moodle_page; use moodle_url; use stdClass; @@ -40,7 +41,7 @@ class user_picture implements renderable { /** * @var int The course id. Used when constructing the link to the user's * profile, page course id used if not specified. - */ + */ public $courseid; /** @@ -99,20 +100,28 @@ class user_picture implements renderable { 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... + // Only touch the DB if we are missing data and complain loudly... $needrec = false; foreach (\core_user\fields::get_picture_fields() as $field) { if (!property_exists($user, $field)) { $needrec = true; - debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. ' - .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER); + debugging( + "Missing {$field} property in {$user} object, " + . "this is a performance problem that needs to be fixed by a developer. " + . 'Please use the \core_user\fields API to get the full list of required fields.', + DEBUG_DEVELOPER, + ); break; } } if ($needrec) { - $this->user = $DB->get_record('user', array('id' => $user->id), - implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST); + $this->user = $DB->get_record( + 'user', + ['id' => $user->id], + implode(',', \core_user\fields::get_picture_fields()), + MUST_EXIST + ); } else { $this->user = clone($user); } @@ -126,14 +135,20 @@ class user_picture implements renderable { * id of the result record. Please note it has to be converted back to id before rendering. * * @param string $tableprefix name of database table prefix in query - * @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) + * @param null|array $extrafields extra fields to be included in result + * Do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE. * @param string $idalias alias of id field * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id' * @return string * @deprecated since Moodle 3.11 MDL-45242 * @see \core_user\fields */ - public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') { + public static function fields( + $tableprefix = '', + ?array $extrafields = null, + $idalias = 'id', + $fieldprefix = '', + ) { debugging('user_picture::fields() is deprecated. Please use the \core_user\fields API instead.', DEBUG_DEVELOPER); $userfields = \core_user\fields::for_userpic(); if ($extrafields) { @@ -152,17 +167,21 @@ class user_picture implements renderable { /** * Extract the aliased user fields from a given record * - * Given a record that was previously obtained using {@link self::fields()} with aliases, + * Given a record that was previously obtained using {@see self::fields()} with aliases, * this method extracts user related unaliased fields. * * @param stdClass $record containing user picture fields - * @param array $extrafields extra fields included in the $record + * @param null|array $extrafields extra fields included in the $record * @param string $idalias alias of the id field * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id' * @return stdClass object with unaliased user fields */ - public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') { - + public static function unalias( + stdClass $record, + ?array $extrafields = null, + $idalias = 'id', + $fieldprefix = '', + ) { if (empty($idalias)) { $idalias = 'id'; } @@ -175,18 +194,18 @@ class user_picture implements renderable { $return->id = $record->{$idalias}; } } else { - if (property_exists($record, $fieldprefix.$field)) { - $return->{$field} = $record->{$fieldprefix.$field}; + if (property_exists($record, $fieldprefix . $field)) { + $return->{$field} = $record->{$fieldprefix . $field}; } } } - // add extra fields if not already there + // Add extra fields if not already there. if ($extrafields) { foreach ($extrafields as $e) { - if ($e === 'id' or property_exists($return, $e)) { + if ($e === 'id' || property_exists($return, $e)) { continue; } - $return->{$e} = $record->{$fieldprefix.$e}; + $return->{$e} = $record->{$fieldprefix . $e}; } } @@ -200,10 +219,13 @@ class user_picture implements renderable { * if requests are made for non-existent files etc. * * @param moodle_page $page - * @param renderer_base $renderer + * @param null|renderer_base $renderer * @return moodle_url */ - public function get_url(moodle_page $page, renderer_base $renderer = null) { + public function get_url( + moodle_page $page, + ?renderer_base $renderer = null, + ) { global $CFG; if (is_null($renderer)) { @@ -215,7 +237,7 @@ class user_picture implements renderable { if (empty($this->size)) { $filename = 'f2'; $size = 35; - } else if ($this->size === true or $this->size == 1) { + } else if ($this->size === true || $this->size == 1) { $filename = 'f1'; $size = 100; } else if ($this->size > 100) { @@ -229,10 +251,12 @@ class user_picture implements renderable { $size = (int)$this->size; } - $defaulturl = $renderer->image_url('u/'.$filename); // default image + $defaulturl = $renderer->image_url('u/' . $filename); // Default image. - if ((!empty($CFG->forcelogin) and !isloggedin()) || - (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) { + if ( + (!empty($CFG->forcelogin) && !isloggedin()) || + (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser())) + ) { // Protect images if login required and not logged in; // also if login is required for profile images and is not logged in or guest // do not use require_login() because it is expensive and not suitable here anyway. @@ -240,7 +264,7 @@ class user_picture implements renderable { } // First try to detect deleted users - but do not read from database for performance reasons! - if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) { + if (!empty($this->user->deleted) || !str_contains($this->user->email, '@')) { // All deleted users should have email replaced by md5 hash, // all active users are expected to have valid email. return $defaulturl; @@ -265,27 +289,35 @@ class user_picture implements renderable { // in the circumstance that the profile picture is not available // when the user actually requests it they still get the profile // picture for the correct theme. - $path .= $page->theme->name.'/'; + $path .= $page->theme->name . '/'; } // Set the image URL to the URL for the uploaded file and return. $url = moodle_url::make_pluginfile_url( - $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken); + $contextid, + 'user', + 'icon', + null, + $path, + $filename, + false, + $this->includetoken + ); $url->param('rev', $this->user->picture); return $url; } - if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) { - // Normalise the size variable to acceptable bounds + if ($this->user->picture == 0 && !empty($CFG->enablegravatar)) { + // Normalise the size variable to acceptable bounds. if ($size < 1 || $size > 512) { $size = 35; } - // Hash the users email address + // Hash the users email address. $md5 = md5(strtolower(trim($this->user->email))); // Build a gravatar URL with what we know. - // Find the best default image URL we can (MDL-35669) + // Find the best default image URL we can (MDL-35669). if (empty($CFG->gravatardefaulturl)) { - $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core'); + $absoluteimagepath = $page->theme->resolve_image_location('u/' . $filename, 'core'); if (strpos($absoluteimagepath, $CFG->dirroot) === 0) { $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot)); } else { @@ -298,9 +330,9 @@ class user_picture implements renderable { // If the currently requested page is https then we'll return an // https gravatar page. if (is_https()) { - return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault)); + return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", ['s' => $size, 'd' => $gravatardefault]); } else { - return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault)); + return new moodle_url("http://www.gravatar.com/avatar/{$md5}", ['s' => $size, 'd' => $gravatardefault]); } } diff --git a/lib/classes/output/xhtml_container_stack.php b/lib/classes/output/xhtml_container_stack.php index 64e7192397b..ccb52ac5511 100644 --- a/lib/classes/output/xhtml_container_stack.php +++ b/lib/classes/output/xhtml_container_stack.php @@ -36,16 +36,16 @@ class xhtml_container_stack { /** * @var array Stores the list of open containers. */ - protected $opencontainers = array(); + protected $opencontainers = []; /** * @var array In developer debug mode, stores a stack trace of all opens and * closes, so we can output helpful error messages when there is a mismatch. */ - protected $log = array(); + protected $log = []; /** - * @var boolean Store whether we are developer debug mode. We need this in + * @var bool Store whether we are developer debug mode. We need this in * several places including in the destructor where we may not have access to $CFG. */ protected $isdebugging; @@ -61,7 +61,7 @@ class xhtml_container_stack { /** * Push the close HTML for a recently opened container onto the stack. * - * @param string $type The type of container. This is checked when {@link pop()} + * @param string $type The type of container. This is checked when {@see pop()} * is called and must match, otherwise a developer debug warning is output. * @param string $closehtml The HTML required to close the container. */ diff --git a/lib/outputactions.php b/lib/outputactions.php index 0fdca282e68..b7c551871da 100644 --- a/lib/outputactions.php +++ b/lib/outputactions.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +defined('MOODLE_INTERNAL') || die(); + // This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php. // Throwing an exception here should be fine because removing the manual inclusion should have no impact. throw new \core\exception\coding_exception( diff --git a/lib/outputcomponents.php b/lib/outputcomponents.php index 0fdca282e68..b7c551871da 100644 --- a/lib/outputcomponents.php +++ b/lib/outputcomponents.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +defined('MOODLE_INTERNAL') || die(); + // This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php. // Throwing an exception here should be fine because removing the manual inclusion should have no impact. throw new \core\exception\coding_exception( diff --git a/lib/outputfactories.php b/lib/outputfactories.php index 0fdca282e68..b7c551871da 100644 --- a/lib/outputfactories.php +++ b/lib/outputfactories.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +defined('MOODLE_INTERNAL') || die(); + // This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php. // Throwing an exception here should be fine because removing the manual inclusion should have no impact. throw new \core\exception\coding_exception( diff --git a/lib/outputfragmentrequirementslib.php b/lib/outputfragmentrequirementslib.php index 2b6fa039198..b7c551871da 100644 --- a/lib/outputfragmentrequirementslib.php +++ b/lib/outputfragmentrequirementslib.php @@ -14,7 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . -// This file is deprecated, but it should never have been manually included by anything outside of lib/pagelib.php. +defined('MOODLE_INTERNAL') || die(); + +// This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php. // Throwing an exception here should be fine because removing the manual inclusion should have no impact. throw new \core\exception\coding_exception( 'This file should not be manually included by any component.', diff --git a/lib/outputlib.php b/lib/outputlib.php index 4dbf86e0b3b..ef3dd636d88 100644 --- a/lib/outputlib.php +++ b/lib/outputlib.php @@ -59,7 +59,6 @@ function theme_get_revision() { } else { return $CFG->themerev; } - } else { return -1; } @@ -99,11 +98,11 @@ function theme_get_next_revision() { global $CFG; $next = time(); - if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) { + if (isset($CFG->themerev) && ($next <= $CFG->themerev) && (($CFG->themerev - $next) < 60 * 60)) { // This resolves problems when reset is requested repeatedly within 1s, // the < 1h condition prevents accidental switching to future dates // because we might not recover from it. - $next = $CFG->themerev+1; + $next = $CFG->themerev + 1; } return $next; @@ -120,7 +119,7 @@ function theme_get_next_sub_revision_for_theme($themename) { $next = time(); $current = theme_get_sub_revision_for_theme($themename); - if ($next <= $current and $current - $next < 60 * 60) { + if ($next <= $current && $current - $next < 60 * 60) { // This resolves problems when reset is requested repeatedly within 1s, // the < 1h condition prevents accidental switching to future dates // because we might not recover from it. @@ -160,7 +159,7 @@ function theme_get_config_file_path($themename) { if (file_exists("{$CFG->dirroot}/theme/{$themename}/config.php")) { return "{$CFG->dirroot}/theme/{$themename}/config.php"; - } else if (!empty($CFG->themedir) and file_exists("{$CFG->themedir}/{$themename}/config.php")) { + } else if (!empty($CFG->themedir) && file_exists("{$CFG->themedir}/{$themename}/config.php")) { return "{$CFG->themedir}/{$themename}/config.php"; } else { return null; @@ -191,8 +190,12 @@ function theme_get_css_filename($themename, $globalrevision, $themerevision, $di * @param bool $cache Should the generated files be stored in local cache. * @return array The built theme content in a multi-dimensional array of name => direction => content */ -function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'], - $cache = true, $mtraceprogress = false): array { +function theme_build_css_for_themes( + $themeconfigs = [], + $directions = ['rtl', 'ltr'], + $cache = true, + $mtraceprogress = false +): array { global $CFG; if (empty($themeconfigs)) { @@ -344,7 +347,7 @@ function template_reset_all_caches() { global $CFG; $next = time(); - if (isset($CFG->templaterev) and $next <= $CFG->templaterev and $CFG->templaterev - $next < 60 * 60) { + if (isset($CFG->templaterev) && $next <= $CFG->templaterev && $CFG->templaterev - $next < 60 * 60) { // This resolves problems when reset is requested repeatedly within 1s, // the < 1h condition prevents accidental switching to future dates // because we might not recover from it. @@ -361,11 +364,11 @@ function js_reset_all_caches() { global $CFG; $next = time(); - if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) { + if (isset($CFG->jsrev) && $next <= $CFG->jsrev && $CFG->jsrev - $next < 60 * 60) { // This resolves problems when reset is requested repeatedly within 1s, // the < 1h condition prevents accidental switching to future dates // because we might not recover from it. - $next = $CFG->jsrev+1; + $next = $CFG->jsrev + 1; } set_config('jsrev', $next); diff --git a/lib/outputrenderers.php b/lib/outputrenderers.php index 0fdca282e68..b7c551871da 100644 --- a/lib/outputrenderers.php +++ b/lib/outputrenderers.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +defined('MOODLE_INTERNAL') || die(); + // This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php. // Throwing an exception here should be fine because removing the manual inclusion should have no impact. throw new \core\exception\coding_exception( diff --git a/lib/outputrequirementslib.php b/lib/outputrequirementslib.php index 0fdca282e68..b7c551871da 100644 --- a/lib/outputrequirementslib.php +++ b/lib/outputrequirementslib.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +defined('MOODLE_INTERNAL') || die(); + // This file is deprecated, but it should never have been manually included by anything outside of lib/outputlib.php. // Throwing an exception here should be fine because removing the manual inclusion should have no impact. throw new \core\exception\coding_exception( diff --git a/lib/table/classes/base_export_format.php b/lib/table/classes/base_export_format.php index 22b29fd89db..35653e4c444 100644 --- a/lib/table/classes/base_export_format.php +++ b/lib/table/classes/base_export_format.php @@ -27,25 +27,23 @@ require_once("{$CFG->libdir}/tablelib.php"); /** * The table base export format. * - * @package moodlecore + * @package core_table * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class base_export_format { /** - * @var flexible_table or child class reference pointing to table class - * object from which to export data. + * @var flexible_table or child class reference pointing to table class object from which to export data. */ - var $table; + public $table; /** - * @var bool output started. Keeps track of whether any output has been - * started yet. + * @var bool output started. Keeps track of whether any output has been started yet. */ - var $documentstarted = false; + public $documentstarted = false; /** - * Constructor + * Constructor. * * @param flexible_table $table */ @@ -53,39 +51,37 @@ class base_export_format { $this->table =& $table; } - /** - * Old syntax of class constructor. Deprecated in PHP7. - * - * @deprecated since Moodle 3.1 - */ - public function table_default_export_format_parent(&$table) { - debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER); - self::__construct($table); - } - - function set_table(&$table) { + public function set_table(&$table) { $this->table =& $table; } - function add_data($row) { + public function add_data($row) { return false; } - function add_seperator() { + public function add_seperator() { return false; } - function document_started() { + public function document_started() { return $this->documentstarted; } + /** + * Format the text. + * * Given text in a variety of format codings, this function returns * the text as safe HTML or as plain text dependent on what is appropriate * for the download format. The default removes all tags. + * + * @param string $text + * @param int $format + * @param null|array $options + * @param null|int $courseid */ - function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) { - //use some whitespace to indicate where there was some line spacing. - $text = str_replace(array('

', "\n", "\r"), ' ', $text); + public function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseid = null) { + // Use some whitespace to indicate where there was some line spacing. + $text = str_replace(['

', "\n", "\r"], ' ', $text); return html_entity_decode(strip_tags($text), ENT_COMPAT); } diff --git a/lib/table/classes/dataformat_export_format.php b/lib/table/classes/dataformat_export_format.php index 4d2922728cf..fcc84a4a8b5 100644 --- a/lib/table/classes/dataformat_export_format.php +++ b/lib/table/classes/dataformat_export_format.php @@ -29,7 +29,7 @@ use core\dataformat; /** * Dataformat exporter * - * @package core + * @package core_table * @subpackage tablelib * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later diff --git a/lib/table/classes/flexible_table.php b/lib/table/classes/flexible_table.php index 3950b5770ce..65ba85b5013 100644 --- a/lib/table/classes/flexible_table.php +++ b/lib/table/classes/flexible_table.php @@ -31,6 +31,8 @@ global $CFG; require_once("{$CFG->libdir}/tablelib.php"); +// phpcs:disable moodle.NamingConventions.ValidVariableName.MemberNameUnderscore + /** * Flexible table implementation. * @@ -39,10 +41,9 @@ require_once("{$CFG->libdir}/tablelib.php"); * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class flexible_table { - - var $uniqueid = NULL; - var $attributes = array(); - var $headers = array(); + public $uniqueid = null; + public $attributes = []; + public $headers = []; /** * @var string A column which should be considered as a header column. @@ -52,23 +53,23 @@ class flexible_table { /** * @var string For create header with help icon. */ - private $helpforheaders = array(); - var $columns = array(); - var $column_style = array(); - var $column_class = array(); - var $column_suppress = array(); - var $column_nosort = array('userpic'); - private $column_textsort = array(); + private $helpforheaders = []; + public $columns = []; + public $column_style = []; + public $column_class = []; + public $column_suppress = []; + public $column_nosort = ['userpic']; + private $column_textsort = []; /** * @var array The sticky attribute of each table column. */ protected $columnsticky = []; - /** @var boolean Stores if setup has already been called on this flixible table. */ - var $setup = false; - var $baseurl = NULL; - var $request = array(); + /** @var bool Stores if setup has already been called on this flixible table. */ + public $setup = false; + public $baseurl = null; + public $request = []; /** @var string[] Columns that are expected to contain a users fullname. */ protected $userfullnamecolumns = ['fullname']; @@ -80,8 +81,8 @@ class flexible_table { * @var bool Whether or not to store table properties in the user_preferences table. */ private $persistent = false; - var $is_collapsible = false; - var $is_sortable = false; + public $is_collapsible = false; + public $is_sortable = false; /** * @var array The fields to sort. @@ -94,24 +95,24 @@ class flexible_table { /** @var string The manually set last name initial preference */ protected $ilast; - var $use_pages = false; - var $use_initials = false; + public $use_pages = false; + public $use_initials = false; - var $maxsortkeys = 2; - var $pagesize = 30; - var $currpage = 0; - var $totalrows = 0; - var $currentrow = 0; - var $sort_default_column = NULL; - var $sort_default_order = SORT_ASC; + public $maxsortkeys = 2; + public $pagesize = 30; + public $currpage = 0; + public $totalrows = 0; + public $currentrow = 0; + public $sort_default_column = null; + public $sort_default_order = SORT_ASC; - /** @var integer The defeult per page size for the table. */ + /** @var int The defeult per page size for the table. */ private $defaultperpage = 30; /** - * Array of positions in which to display download controls. + * @var array Array of positions in which to display download controls. */ - var $showdownloadbuttonsat= array(TABLE_P_TOP); + public $showdownloadbuttonsat = [TABLE_P_TOP]; /** * @var string Key of field returned by db query that is the id field of the @@ -124,26 +125,26 @@ class flexible_table { * html table with paging. Property set by is_downloading which typically * passes in cleaned data from $ */ - var $download = ''; + public $download = ''; /** * @var bool whether data is downloadable from table. Determines whether * to display download buttons. Set by method downloadable(). */ - var $downloadable = false; + public $downloadable = false; /** * @var bool Has start output been called yet? */ - var $started_output = false; + public $started_output = false; /** @var dataformat_export_format */ - var $exportclass = null; + public $exportclass = null; /** * @var array For storing user-customised table properties in the user_preferences db table. */ - private $prefs = array(); + private $prefs = []; /** @var string $sheettitle */ protected $sheettitle; @@ -178,9 +179,9 @@ class flexible_table { * @param string $uniqueid all tables have to have a unique id, this is used * as a key when storing table properties like sort order in the session. */ - function __construct($uniqueid) { + public function __construct($uniqueid) { $this->uniqueid = $uniqueid; - $this->request = array( + $this->request = [ TABLE_VAR_SORT => 'tsort', TABLE_VAR_HIDE => 'thide', TABLE_VAR_SHOW => 'tshow', @@ -189,7 +190,7 @@ class flexible_table { TABLE_VAR_PAGE => 'page', TABLE_VAR_RESET => 'treset', TABLE_VAR_DIR => 'tdir', - ); + ]; } /** @@ -205,8 +206,8 @@ class flexible_table { * @param string $sheettitle title for downloaded data. * @return string download dataformat type. */ - function is_downloading($download = null, $filename='', $sheettitle='') { - if ($download!==null) { + public function is_downloading($download = null, $filename = '', $sheettitle = '') { + if ($download !== null) { $this->sheettitle = $sheettitle; $this->is_downloadable(true); $this->download = $download; @@ -221,7 +222,7 @@ class flexible_table { * @param dataformat_export_format $exportclass (optional) if passed, set the table to use this export class. * @return dataformat_export_format the export class in use (after any set). */ - function export_class_instance($exportclass = null) { + public function export_class_instance($exportclass = null) { if (!is_null($exportclass)) { $this->started_output = true; $this->exportclass = $exportclass; @@ -244,7 +245,7 @@ class flexible_table { * current state of table. * @return bool whether table data is set to be downloadable. */ - function is_downloadable($downloadable = null) { + public function is_downloadable($downloadable = null) { if ($downloadable !== null) { $this->downloadable = $downloadable; } @@ -271,7 +272,7 @@ class flexible_table { * @param array $showat array of postions in which to show download buttons. * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM */ - function show_download_buttons_at($showat) { + public function show_download_buttons_at($showat) { $this->showdownloadbuttonsat = $showat; } @@ -283,7 +284,7 @@ class flexible_table { * @param int $defaultorder * @return void */ - function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) { + public function sortable($bool, $defaultcolumn = null, $defaultorder = SORT_ASC) { $this->is_sortable = $bool; $this->sort_default_column = $defaultcolumn; $this->sort_default_order = $defaultorder; @@ -295,7 +296,7 @@ class flexible_table { * with real columns. See MDL-40481 for an example. * @param string column name */ - function text_sorting($column) { + public function text_sorting($column) { $this->column_textsort[] = $column; } @@ -303,7 +304,7 @@ class flexible_table { * Do not sort using this column * @param string column name */ - function no_sorting($column) { + public function no_sorting($column) { $this->column_nosort[] = $column; } @@ -312,7 +313,7 @@ class flexible_table { * @param string column name, null means table * @return bool */ - function is_sortable($column = null) { + public function is_sortable($column = null) { if (empty($column)) { return $this->is_sortable; } @@ -327,7 +328,7 @@ class flexible_table { * @param bool $bool * @return void */ - function collapsible($bool) { + public function collapsible($bool) { $this->is_collapsible = $bool; } @@ -336,7 +337,7 @@ class flexible_table { * @param bool $bool * @return void */ - function pageable($bool) { + public function pageable($bool) { $this->use_pages = $bool; } @@ -345,7 +346,7 @@ class flexible_table { * @param bool $bool * @return void */ - function initialbars($bool) { + public function initialbars($bool) { $this->use_initials = $bool; } @@ -356,7 +357,7 @@ class flexible_table { * @param int $total * @return void */ - function pagesize($perpage, $total) { + public function pagesize($perpage, $total) { $this->pagesize = $perpage; $this->totalrows = $total; $this->use_pages = true; @@ -368,7 +369,7 @@ class flexible_table { * @param array $variables * @return void */ - function set_control_variables($variables) { + public function set_control_variables($variables) { foreach ($variables as $what => $variable) { if (isset($this->request[$what])) { $this->request[$what] = $variable; @@ -382,7 +383,7 @@ class flexible_table { * @param mixed $value * @return void */ - function set_attribute($attribute, $value) { + public function set_attribute($attribute, $value) { $this->attributes[$attribute] = $value; } @@ -395,7 +396,7 @@ class flexible_table { * for their first attempt. * @param int $column the index of a column. */ - function column_suppress($column) { + public function column_suppress($column) { if (isset($this->column_suppress[$column])) { $this->column_suppress[$column] = true; } @@ -407,9 +408,9 @@ class flexible_table { * @param string $classname * @return void */ - function column_class($column, $classname) { + public function column_class($column, $classname) { if (isset($this->column_class[$column])) { - $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML + $this->column_class[$column] = ' ' . $classname; // This space needed so that classnames don't run together in the HTML. } } @@ -420,7 +421,7 @@ class flexible_table { * @param mixed $value * @return void */ - function column_style($column, $property, $value) { + public function column_style($column, $property, $value) { if (isset($this->column_style[$column])) { $this->column_style[$column][$property] = $value; } @@ -453,7 +454,7 @@ class flexible_table { * @param string $value * @return void */ - function column_style_all($property, $value) { + public function column_style_all($property, $value) { foreach (array_keys($this->columns) as $column) { $this->column_style[$column][$property] = $value; } @@ -463,25 +464,27 @@ class flexible_table { * Sets $this->baseurl. * @param moodle_url|string $url the url with params needed to call up this page */ - function define_baseurl($url) { + public function define_baseurl($url) { $this->baseurl = new moodle_url($url); } /** + * Define the columns for the table. + * * @param array $columns an array of identifying names for columns. If * columns are sorted then column names must correspond to a field in sql. */ - function define_columns($columns) { - $this->columns = array(); - $this->column_style = array(); - $this->column_class = array(); + public function define_columns($columns) { + $this->columns = []; + $this->column_style = []; + $this->column_class = []; $this->columnsticky = []; $this->columnsattributes = []; $colnum = 0; foreach ($columns as $column) { $this->columns[$column] = $colnum++; - $this->column_style[$column] = array(); + $this->column_style[$column] = []; $this->column_class[$column] = ''; $this->columnsticky[$column] = ''; $this->columnsattributes[$column] = []; @@ -490,10 +493,12 @@ class flexible_table { } /** + * Define the headers for the table, replacing any existing header configuration. + * * @param array $headers numerical keyed array of displayed string titles * for each column. */ - function define_headers($headers) { + public function define_headers($headers) { $this->headers = $headers; } @@ -537,14 +542,13 @@ class flexible_table { } return $this->resetting; -} + } /** * Must be called after table is defined. Use methods above first. Cannot * use functions below till after calling this method. */ - function setup() { - + public function setup() { if (empty($this->columns) || empty($this->uniqueid)) { return false; } @@ -563,7 +567,7 @@ class flexible_table { $this->setup = true; - // Always introduce the "flexible" class for the table if not specified + // Always introduce the "flexible" class for the table if not specified. if (empty($this->attributes)) { $this->attributes['class'] = 'flexible table table-striped table-hover'; } else if (!isset($this->attributes['class'])) { @@ -590,7 +594,7 @@ class flexible_table { return ''; } if (empty($prefs['textsort'])) { - $prefs['textsort'] = array(); + $prefs['textsort'] = []; } return self::construct_order_by($prefs['sortby'], $prefs['textsort']); @@ -598,12 +602,13 @@ class flexible_table { /** * Prepare an an order by clause from the list of columns to be sorted. + * * @param array $cols column name => SORT_ASC or SORT_DESC * @return string SQL fragment that can be used in an ORDER BY clause. */ - public static function construct_order_by($cols, $textsortcols=array()) { + public static function construct_order_by($cols, $textsortcols = []) { global $DB; - $bits = array(); + $bits = []; foreach ($cols as $column => $order) { if (in_array($column, $textsortcols)) { @@ -620,6 +625,8 @@ class flexible_table { } /** + * Get the SQL Sort clause for the table. + * * @return string SQL fragment that can be used in an ORDER BY clause. */ public function get_sql_sort() { @@ -638,7 +645,7 @@ class flexible_table { } /** - * Get the columns to sort by, in the form required by {@link construct_order_by()}. + * Get the columns to sort by, in the form required by {@see construct_order_by()}. * @return array column name => SORT_... constant. */ public function get_sort_columns() { @@ -647,7 +654,7 @@ class flexible_table { } if (empty($this->prefs['sortby'])) { - return array(); + return []; } foreach ($this->prefs['sortby'] as $column => $notused) { if (isset($this->columns[$column])) { @@ -664,9 +671,11 @@ class flexible_table { } /** + * Get the starting row number for this page. + * * @return int the offset for LIMIT clause of SQL */ - function get_page_start() { + public function get_page_start() { if (!$this->use_pages) { return ''; } @@ -676,7 +685,7 @@ class flexible_table { /** * @return int the pagesize for LIMIT clause of SQL */ - function get_page_size() { + public function get_page_size() { if (!$this->use_pages) { return ''; } @@ -686,27 +695,27 @@ class flexible_table { /** * @return array sql to add to where statement. */ - function get_sql_where() { + public function get_sql_where() { global $DB; - $conditions = array(); - $params = array(); + $conditions = []; + $params = []; if ($this->contains_fullname_columns()) { static $i = 0; $i++; if (!empty($this->prefs['i_first'])) { - $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false); - $params['ifirstc'.$i] = $this->prefs['i_first'].'%'; + $conditions[] = $DB->sql_like('firstname', ':ifirstc' . $i, false, false); + $params['ifirstc' . $i] = $this->prefs['i_first'] . '%'; } if (!empty($this->prefs['i_last'])) { - $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false); - $params['ilastc'.$i] = $this->prefs['i_last'].'%'; + $conditions[] = $DB->sql_like('lastname', ':ilastc' . $i, false, false); + $params['ilastc' . $i] = $this->prefs['i_last'] . '%'; } } - return array(implode(" AND ", $conditions), $params); + return [implode(" AND ", $conditions), $params]; } /** @@ -723,7 +732,7 @@ class flexible_table { * as defined in call to define_columns. * @param string $classname CSS class name to add to this row's tr tag. */ - function add_data_keyed($rowwithkeys, $classname = '') { + public function add_data_keyed($rowwithkeys, $classname = '') { $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname); } @@ -751,11 +760,11 @@ class flexible_table { /** * Add a seperator line to table. */ - function add_separator() { + public function add_separator() { if (!$this->setup) { return false; } - $this->add_data(NULL); + $this->add_data(null); } /** @@ -769,14 +778,14 @@ class flexible_table { * @param string $classname CSS class name to add to this row's tr tag. * @return bool success. */ - function add_data($row, $classname = '') { + public function add_data($row, $classname = '') { if (!$this->setup) { return false; } if (!$this->started_output) { $this->start_output(); } - if ($this->exportclass!==null) { + if ($this->exportclass !== null) { if ($row === null) { $this->exportclass->add_seperator(); } else { @@ -793,8 +802,8 @@ class flexible_table { * data to the table with add_data or add_data_keyed. * */ - function finish_output($closeexportclassdoc = true) { - if ($this->exportclass!==null) { + public function finish_output($closeexportclassdoc = true) { + if ($this->exportclass !== null) { $this->exportclass->finish_table(); if ($closeexportclassdoc) { $this->exportclass->finish_document(); @@ -809,7 +818,7 @@ class flexible_table { * for example. Called only when there is data to display and not * downloading. */ - function wrap_html_start() { + public function wrap_html_start() { } /** @@ -817,7 +826,7 @@ class flexible_table { * for example. Called only when there is data to display and not * downloading. */ - function wrap_html_finish() { + public function wrap_html_finish() { } /** @@ -830,18 +839,18 @@ class flexible_table { * @param array|object $row row of data from db used to make one row of the table. * @return array one row for the table, added using add_data_keyed method. */ - function format_row($row) { + public function format_row($row) { if (is_array($row)) { $row = (object)$row; } - $formattedrow = array(); + $formattedrow = []; foreach (array_keys($this->columns) as $column) { - $colmethodname = 'col_'.$column; + $colmethodname = 'col_' . $column; if (method_exists($this, $colmethodname)) { $formattedcolumn = $this->$colmethodname($row); } else { $formattedcolumn = $this->other_cols($column, $row); - if ($formattedcolumn===NULL) { + if ($formattedcolumn === null) { $formattedcolumn = $row->$column; } } @@ -862,7 +871,7 @@ class flexible_table { * current language. * @return string contents of cell in column 'fullname', for this row. */ - function col_fullname($row) { + public function col_fullname($row) { global $COURSE; $name = fullname($row, has_capability('moodle/site:viewfullnames', $this->get_context())); @@ -872,10 +881,12 @@ class flexible_table { $userid = $row->{$this->useridfield}; if ($COURSE->id == SITEID) { - $profileurl = new moodle_url('/user/profile.php', array('id' => $userid)); + $profileurl = new moodle_url('/user/profile.php', ['id' => $userid]); } else { - $profileurl = new moodle_url('/user/view.php', - array('id' => $userid, 'course' => $COURSE->id)); + $profileurl = new moodle_url( + '/user/view.php', + ['id' => $userid, 'course' => $COURSE->id] + ); } return html_writer::link($profileurl, $name); } @@ -884,14 +895,16 @@ class flexible_table { * You can override this method in a child class. See the description of * build_table which calls this method. */ - function other_cols($column, $row) { - if (isset($row->$column) && ($column === 'email' || $column === 'idnumber') && - (!$this->is_downloading() || $this->export_class_instance()->supports_html())) { + public function other_cols($column, $row) { + if ( + isset($row->$column) && ($column === 'email' || $column === 'idnumber') && + (!$this->is_downloading() || $this->export_class_instance()->supports_html()) + ) { // Columns email and idnumber may potentially contain malicious characters, escape them by default. // This function will not be executed if the child class implements col_email() or col_idnumber(). return s($row->$column); } - return NULL; + return null; } /** @@ -901,12 +914,12 @@ class flexible_table { * are the same as format_text function in weblib.php but some default * options are changed. */ - function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) { + public function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseid = null) { if (!$this->is_downloading()) { if (is_null($options)) { - $options = new stdClass; + $options = new stdClass(); } - //some sensible defaults + // Some sensible defaults. if (!isset($options->para)) { $options->para = false; } @@ -926,7 +939,7 @@ class flexible_table { * This method is deprecated although the old api is still supported. * @deprecated 1.9.2 - Jun 2, 2008 */ - function print_html() { + public function print_html() { if (!$this->setup) { return false; } @@ -937,9 +950,9 @@ class flexible_table { * This function is not part of the public api. * @return string initial of first name we are currently filtering by */ - function get_initial_first() { + public function get_initial_first() { if (!$this->use_initials) { - return NULL; + return null; } return $this->prefs['i_first']; @@ -949,16 +962,16 @@ class flexible_table { * This function is not part of the public api. * @return string initial of last name we are currently filtering by */ - function get_initial_last() { + public function get_initial_last() { if (!$this->use_initials) { - return NULL; + return null; } return $this->prefs['i_last']; } /** - * Helper function, used by {@link print_initials_bar()} to output one initial bar. + * Helper function, used by {@see print_initials_bar()} to output one initial bar. * @param array $alpha of letters in the alphabet. * @param string $current the currently selected letter. * @param string $class class name to add to this initial bar. @@ -972,10 +985,10 @@ class flexible_table { debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' . 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER); - echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) . + echo html_writer::start_tag('div', ['class' => 'initialbar ' . $class]) . $title . ' : '; if ($current) { - echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all')); + echo html_writer::link($this->baseurl->out(false, [$urlvar => '']), get_string('all')); } else { echo html_writer::tag('strong', get_string('all')); } @@ -984,7 +997,7 @@ class flexible_table { if ($letter === $current) { echo html_writer::tag('strong', $letter); } else { - echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter); + echo html_writer::link($this->baseurl->out(false, [$urlvar => $letter]), $letter); } } @@ -994,7 +1007,7 @@ class flexible_table { /** * This function is not part of the public api. */ - function print_initials_bar() { + public function print_initials_bar() { global $OUTPUT; $ifirst = $this->get_initial_first(); @@ -1012,13 +1025,12 @@ class flexible_table { echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl); echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl); } - } /** * This function is not part of the public api. */ - function print_nothing_to_display() { + public function print_nothing_to_display() { global $OUTPUT; // Render the dynamic table header. @@ -1038,16 +1050,16 @@ class flexible_table { /** * This function is not part of the public api. */ - function get_row_from_keyed($rowwithkeys) { + public function get_row_from_keyed($rowwithkeys) { if (is_object($rowwithkeys)) { $rowwithkeys = (array)$rowwithkeys; } - $row = array(); + $row = []; foreach (array_keys($this->columns) as $column) { if (isset($rowwithkeys[$column])) { - $row [] = $rowwithkeys[$column]; + $row[] = $rowwithkeys[$column]; } else { - $row[] =''; + $row[] = ''; } } return $row; @@ -1062,8 +1074,12 @@ class flexible_table { global $OUTPUT; if ($this->is_downloadable() && !$this->is_downloading()) { - return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'), - $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params()); + return $OUTPUT->download_dataformat_selector( + get_string('downloadas', 'table'), + $this->baseurl->out_omit_querystring(), + 'download', + $this->baseurl->params() + ); } else { return ''; } @@ -1075,9 +1091,9 @@ class flexible_table { * needed when you start adding data to the table. * */ - function start_output() { + public function start_output() { $this->started_output = true; - if ($this->exportclass!==null) { + if ($this->exportclass !== null) { $this->exportclass->start_table($this->sheettitle); $this->exportclass->output_headers($this->headers); } else { @@ -1090,7 +1106,7 @@ class flexible_table { /** * This function is not part of the public api. */ - function print_row($row, $classname = '') { + public function print_row($row, $classname = '') { echo $this->get_row_html($row, $classname); } @@ -1103,8 +1119,8 @@ class flexible_table { * @return string $html html code for the row passed. */ public function get_row_html($row, $classname = '') { - static $suppress_lastrow = NULL; - $rowclasses = array(); + static $suppresslastrow = null; + $rowclasses = []; if ($classname) { $rowclasses[] = $classname; @@ -1113,23 +1129,25 @@ class flexible_table { $rowid = $this->uniqueid . '_r' . $this->currentrow; $html = ''; - $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid)); + $html .= html_writer::start_tag('tr', ['class' => implode(' ', $rowclasses), 'id' => $rowid]); - // If we have a separator, print it - if ($row === NULL) { + // If we have a separator, print it. + if ($row === null) { $colcount = count($this->columns); - $html .= html_writer::tag('td', html_writer::tag('div', '', - array('class' => 'tabledivider')), array('colspan' => $colcount)); - + $html .= html_writer::tag('td', html_writer::tag( + 'div', + '', + ['class' => 'tabledivider'] + ), ['colspan' => $colcount]); } else { - $html .= $this->get_row_cells_html($rowid, $row, $suppress_lastrow); + $html .= $this->get_row_cells_html($rowid, $row, $suppresslastrow); } $html .= html_writer::end_tag('tr'); - $suppress_enabled = array_sum($this->column_suppress); - if ($suppress_enabled) { - $suppress_lastrow = $row; + $suppressenabled = array_sum($this->column_suppress); + if ($suppressenabled) { + $suppresslastrow = $row; } $this->currentrow++; return $html; @@ -1187,13 +1205,12 @@ class flexible_table { /** * This function is not part of the public api. */ - function finish_html() { + public function finish_html() { global $OUTPUT, $PAGE; if (!$this->started_output) { - //no data has been added to the table. + // No data has been added to the table. $this->print_nothing_to_display(); - } else { // Print empty rows to fill the table to the current pagesize. // This is done so the header aria-controls attributes do not point to @@ -1208,12 +1225,12 @@ class flexible_table { echo html_writer::end_tag('div'); $this->wrap_html_finish(); - // Paging bar - if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) { + // Paging bar. + if (in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) { echo $this->download_buttons(); } - if($this->use_pages) { + if ($this->use_pages) { $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl); $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE]; echo $OUTPUT->render($pagingbar); @@ -1226,7 +1243,7 @@ class flexible_table { /** * Generate the HTML for the collapse/uncollapse icon. This is a helper method - * used by {@link print_headers()}. + * used by {@see print_headers()}. * @param string $column the column name, index into various names. * @param int $index numerical index of the column. * @return string HTML fragment. @@ -1252,10 +1269,12 @@ class flexible_table { 'data-column' => $column, 'role' => 'button', ]; - return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)), - $OUTPUT->pix_icon('t/switch_plus', null), $linkattributes); - - } else if ($this->headers[$index] !== NULL) { + return html_writer::link( + $this->baseurl->out(false, [$this->request[TABLE_VAR_SHOW] => $column]), + $OUTPUT->pix_icon('t/switch_plus', null), + $linkattributes + ); + } else if ($this->headers[$index] !== null) { $linkattributes = [ 'title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]), 'aria-expanded' => 'true', @@ -1264,15 +1283,18 @@ class flexible_table { 'data-column' => $column, 'role' => 'button', ]; - return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)), - $OUTPUT->pix_icon('t/switch_minus', null), $linkattributes); + return html_writer::link( + $this->baseurl->out(false, [$this->request[TABLE_VAR_HIDE] => $column]), + $OUTPUT->pix_icon('t/switch_minus', null), + $linkattributes + ); } } /** * This function is not part of the public api. */ - function print_headers() { + public function print_headers() { global $CFG, $OUTPUT; // Set the primary sort column/order where possible, so that sort links/icons are correct. @@ -1284,19 +1306,16 @@ class flexible_table { echo html_writer::start_tag('thead'); echo html_writer::start_tag('tr'); foreach ($this->columns as $column => $index) { - - $icon_hide = ''; + $iconhide = ''; if ($this->is_collapsible) { - $icon_hide = $this->show_hide_link($column, $index); + $iconhide = $this->show_hide_link($column, $index); } switch ($column) { - case 'userpic': - // do nothing, do not display sortable links + // Do nothing, do not display sortable links. break; default: - if (array_search($column, $this->userfullnamecolumns) !== false) { // Check the full name display for sortable fields. if (has_capability('moodle/site:viewfullnames', $this->get_context())) { @@ -1316,8 +1335,12 @@ class flexible_table { // Done this way for the possibility of more than two sortable full name display fields. $this->headers[$index] = ''; foreach ($requirednames as $name) { - $sortname = $this->sort_link(get_string($name), - $name, $primarysortcolumn === $name, $primarysortorder); + $sortname = $this->sort_link( + get_string($name), + $name, + $primarysortcolumn === $name, + $primarysortorder + ); $this->headers[$index] .= $sortname . ' / '; } $helpicon = ''; @@ -1332,19 +1355,23 @@ class flexible_table { if (isset($this->helpforheaders[$index])) { $helpicon = $OUTPUT->render($this->helpforheaders[$index]); } - $this->headers[$index] = $this->sort_link($this->headers[$index], - $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon; + $this->headers[$index] = $this->sort_link( + $this->headers[$index], + $column, + $primarysortcolumn == $column, + $primarysortorder + ) . $helpicon; } } - $attributes = array( + $attributes = [ 'class' => 'header c' . $index . $this->column_class[$column] . $this->columnsticky[$column], 'scope' => 'col', - ); - if ($this->headers[$index] === NULL) { + ]; + if ($this->headers[$index] === null) { $content = ' '; } else if (!empty($this->prefs['collapse'][$column])) { - $content = $icon_hide; + $content = $iconhide; } else { if (is_array($this->column_style[$column])) { $attributes['style'] = $this->make_styles_string($this->column_style[$column]); @@ -1353,8 +1380,11 @@ class flexible_table { if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) { $helpicon = $OUTPUT->render($this->helpforheaders[$index]); } - $content = $this->headers[$index] . $helpicon . html_writer::tag('div', - $icon_hide, array('class' => 'commands')); + $content = $this->headers[$index] . $helpicon . html_writer::tag( + 'div', + $iconhide, + ['class' => 'commands'] + ); } echo html_writer::tag('th', $content, $attributes); } @@ -1383,7 +1413,7 @@ class flexible_table { } $usernamefields = \core_user\fields::get_name_fields(); - $sortdata = array_filter($sortdata, function($sortby) use ($usernamefields) { + $sortdata = array_filter($sortdata, function ($sortby) use ($usernamefields) { $isvalidsort = $sortby && $this->is_sortable($sortby); $isvalidsort = $isvalidsort && empty($this->prefs['collapse'][$sortby]); $isrealcolumn = isset($this->columns[$sortby]); @@ -1427,7 +1457,6 @@ class flexible_table { if (!is_null($ilast) && ($ilast === '' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) { $this->prefs['i_last'] = $ilast; } - } /** @@ -1436,7 +1465,7 @@ class flexible_table { protected function set_hide_show_preferences(): void { if ($this->hiddencolumns !== null) { - $this->prefs['collapse'] = array_fill_keys(array_filter($this->hiddencolumns, function($column) { + $this->prefs['collapse'] = array_fill_keys(array_filter($this->hiddencolumns, function ($column) { return array_key_exists($column, $this->columns); }), true); } else { @@ -1504,11 +1533,15 @@ class flexible_table { $this->ilast = null; } - if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) && - isset($this->columns[$showcol])) { + if ( + ($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) && + isset($this->columns[$showcol]) + ) { $this->prefs['collapse'][$showcol] = false; - } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) && - isset($this->columns[$hidecol])) { + } else if ( + ($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) && + isset($this->columns[$hidecol]) + ) { $this->prefs['collapse'][$hidecol] = true; if (array_key_exists($hidecol, $this->prefs['sortby'])) { unset($this->prefs['sortby'][$hidecol]); @@ -1620,7 +1653,7 @@ class flexible_table { } /** - * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}. + * Generate the HTML for the sort icon. This is a helper method used by {@see sort_link()}. * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.) * @param int $order SORT_ASC or SORT_DESC * @return string HTML fragment. @@ -1641,7 +1674,7 @@ class flexible_table { /** * Generate the correct tool tip for changing the sort order. This is a - * helper method used by {@link sort_link()}. + * helper method used by {@see sort_link()}. * @param bool $isprimary whether the is column is the current primary sort column. * @param int $order SORT_ASC or SORT_DESC * @return string the correct title. @@ -1655,7 +1688,7 @@ class flexible_table { } /** - * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}. + * Generate the HTML for the sort link. This is a helper method used by {@see print_headers()}. * @param string $text the text for the link. * @param string $column the column name, may be a fake column like 'firstname' or a real one. * @param bool $isprimary whether the is column is the current primary sort column. @@ -1675,15 +1708,17 @@ class flexible_table { $this->request[TABLE_VAR_DIR] => $sortorder, ]; - return html_writer::link($this->baseurl->out(false, $params), - $text . get_accesshide(get_string('sortby') . ' ' . + return html_writer::link( + $this->baseurl->out(false, $params), + $text . get_accesshide(get_string('sortby') . ' ' . $text . ' ' . $this->sort_order_name($isprimary, $order)), - [ + [ 'data-sortable' => $this->is_sortable($column), 'data-sortby' => $column, 'data-sortorder' => $sortorder, 'role' => 'button', - ]) . ' ' . $this->sort_icon($isprimary, $order); + ] + ) . ' ' . $this->sort_icon($isprimary, $order); } /** @@ -1745,12 +1780,13 @@ class flexible_table { */ protected function get_dynamic_table_html_start(): string { if (is_a($this, dynamic::class)) { - $sortdata = array_map(function($sortby, $sortorder) { + $sortdata = array_map(function ($sortby, $sortorder) { return [ 'sortby' => $sortby, 'sortorder' => $sortorder, ]; - }, array_keys($this->prefs['sortby']), array_values($this->prefs['sortby']));; + }, array_keys($this->prefs['sortby']), array_values($this->prefs['sortby'])); + ; return html_writer::start_tag('div', [ 'class' => 'table-dynamic position-relative', @@ -1818,7 +1854,7 @@ class flexible_table { /** * This function is not part of the public api. */ - function start_html() { + public function start_html() { global $OUTPUT; // Render the dynamic table header. @@ -1830,7 +1866,7 @@ class flexible_table { // Do we need to print initial bars? $this->print_initials_bar(); - // Paging bar + // Paging bar. if ($this->use_pages) { $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl); $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE]; @@ -1842,9 +1878,9 @@ class flexible_table { } $this->wrap_html_start(); - // Start of main data table + // Start of main data table. - echo html_writer::start_tag('div', array('class' => 'no-overflow')); + echo html_writer::start_tag('div', ['class' => 'no-overflow']); echo html_writer::start_tag('table', $this->attributes) . $this->render_caption(); } @@ -1881,13 +1917,13 @@ class flexible_table { * @param array $styles CSS-property => value * @return string values suitably to go in a style="" attribute in HTML. */ - function make_styles_string($styles) { + public function make_styles_string($styles) { if (empty($styles)) { return null; } $string = ''; - foreach($styles as $property => $value) { + foreach ($styles as $property => $value) { $string .= $property . ':' . $value . ';'; } return $string; @@ -1904,7 +1940,7 @@ class flexible_table { return ''; } - $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1)); + $url = $this->baseurl->out(false, [$this->request[TABLE_VAR_RESET] => 1]); $html = html_writer::start_div('resettable mdl-right'); $html .= html_writer::link($url, get_string('resettable'), ['role' => 'button']); @@ -1923,20 +1959,18 @@ class flexible_table { protected function can_be_reset() { // Loop through preferences and make sure they are empty or set to the default value. foreach ($this->prefs as $prefname => $prefval) { - if ($prefname === 'sortby' and !empty($this->sort_default_column)) { + if ($prefname === 'sortby' && !empty($this->sort_default_column)) { // Check if the actual sorting differs from the default one. - if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) { + if (empty($prefval) || ($prefval !== [$this->sort_default_column => $this->sort_default_order])) { return true; } - - } else if ($prefname === 'collapse' and !empty($prefval)) { + } else if ($prefname === 'collapse' && !empty($prefval)) { // Check if there are some collapsed columns (all are expanded by default). foreach ($prefval as $columnname => $iscollapsed) { if ($iscollapsed) { return true; } } - } else if (!empty($prefval)) { // For all other cases, we just check if some preference is set. return true; diff --git a/lib/table/classes/output/html_table.php b/lib/table/classes/output/html_table.php index c04ef01bc7e..8ec95880ca0 100644 --- a/lib/table/classes/output/html_table.php +++ b/lib/table/classes/output/html_table.php @@ -17,7 +17,7 @@ namespace core_table\output; /** - * Holds all the information required to render a by {@link core_renderer::table()} + * Holds all the information required to render a
by {@see core_renderer::table()} * * Example of usage: * $t = new html_table(); @@ -27,11 +27,10 @@ namespace core_table\output; * @copyright 2009 David Mudrak * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 - * @package core + * @package core_table * @category output */ class html_table { - /** * @var string Value to use for the id attribute of the table */ @@ -40,7 +39,7 @@ class html_table { /** * @var array Attributes of HTML attributes for the
element */ - public $attributes = array(); + public $attributes = []; /** * @var array An array of headings. The n-th array item is used as a heading of the n-th column. @@ -54,8 +53,8 @@ class html_table { /** * @var array An array that can be used to make a heading span multiple columns. - * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns, - * the same heading is used. Therefore, {@link html_table::$head} should consist of two items. + * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns, + * the same heading is used. Therefore, {@see html_table::$head} should consist of two items. * * Example of usage: * $t->headspan = array(2,1); @@ -122,20 +121,20 @@ class html_table { public $data = []; /** - * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var string Width of the table, percentage of the page preferred. + * @deprecated since Moodle 2.0. Styling should be in the CSS. */ public $width = null; /** - * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default). + * @deprecated since Moodle 2.0. Styling should be in the CSS. */ public $tablealign = null; /** - * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var int Padding on each cell, in pixels + * @deprecated since Moodle 2.0. Styling should be in the CSS. */ public $cellpadding = null; diff --git a/lib/table/classes/output/html_table_cell.php b/lib/table/classes/output/html_table_cell.php index 038fb27ad50..7f44cd96a52 100644 --- a/lib/table/classes/output/html_table_cell.php +++ b/lib/table/classes/output/html_table_cell.php @@ -22,7 +22,7 @@ namespace core_table\output; * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 - * @package core + * @package core_table * @category output */ class html_table_cell { @@ -69,7 +69,7 @@ class html_table_cell { /** * @var array Attributes of additional HTML attributes for the element */ - public $attributes = array(); + public $attributes = []; /** * Constructor - * @param array $cells + * + * @param null|array $cells */ - public function __construct(array $cells=null) { + public function __construct(?array $cells = null) { $this->attributes['class'] = ''; $cells = (array)$cells; foreach ($cells as $cell) { diff --git a/lib/table/classes/sql_table.php b/lib/table/classes/sql_table.php index 00e26153535..815e81aef1f 100644 --- a/lib/table/classes/sql_table.php +++ b/lib/table/classes/sql_table.php @@ -29,38 +29,39 @@ require_once("{$CFG->libdir}/tablelib.php"); /** * A table whose data is provided by SQL queries. * - * @package moodlecore + * @package core_table * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class sql_table extends flexible_table { - public $countsql = NULL; - public $countparams = NULL; - /** - * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'. - */ - public $sql = NULL; - /** - * @var array|\Traversable Data fetched from the db. - */ - public $rawdata = NULL; + /** @var string The SQL query to count records */ + public $countsql = null; - /** - * @var bool Overriding default for this. - */ - public $is_sortable = true; - /** - * @var bool Overriding default for this. - */ - public $is_collapsible = true; + /** @var array The parameters for the Count SQL */ + public $countparams = null; + + /** @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params' */ + public $sql = null; + + /** @var array|\Traversable Data fetched from the db */ + public $rawdata = null; + + /** @var bool Overriding default for this */ + + public $is_sortable = true; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore + + /** @var bool Overriding default for this */ + public $is_collapsible = true; // phpcs:ignore moodle.NamingConventions.ValidVariableName.MemberNameUnderscore /** + * Create a new instance of the sql_table. + * * @param string $uniqueid a string identifying this table.Used as a key in * session vars. */ - function __construct($uniqueid) { + public function __construct($uniqueid) { parent::__construct($uniqueid); - // some sensible defaults + // Set some sensible defaults. $this->set_attribute('class', 'generaltable generalbox'); } @@ -89,8 +90,10 @@ class sql_table extends flexible_table { * Closes recordset (for use after building the table). */ public function close_recordset() { - if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk || - $this->rawdata instanceof moodle_recordset)) { + if ( + $this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk || + $this->rawdata instanceof moodle_recordset) + ) { $this->rawdata->close(); $this->rawdata = null; } @@ -98,14 +101,17 @@ class sql_table extends flexible_table { /** * Get any extra classes names to add to this row in the HTML. - * @param $row array the data for this row. + * + * @param array $row the data for this row. * @return string added to the class="" attribute of the tr. */ - function get_row_class($row) { + public function get_row_class($row) { return ''; } /** + * Set the SQL used to count records. + * * This is only needed if you want to use different sql to count rows. * Used for example when perhaps all db JOINS are not needed when counting * records. You don't need to call this function the count_sql @@ -113,8 +119,11 @@ class sql_table extends flexible_table { * * We need to count rows returned by the db seperately to the query itself * as we need to know how many pages of data we have to display. + * + * @param string $sql + * @param null|array $params */ - function set_count_sql($sql, array $params = NULL) { + public function set_count_sql($sql, ?array $params = null) { $this->countsql = $sql; $this->countparams = $params; } @@ -124,8 +133,13 @@ class sql_table extends flexible_table { * SELECT $fields FROM $from WHERE $where * Of course you can use sub-queries, JOINS etc. by putting them in the * appropriate clause of the query. + * + * @param string $fields + * @param string $from + * @param string $where + * @param array $params */ - function set_sql($fields, $from, $where, array $params = array()) { + public function set_sql($fields, $from, $where, array $params = []) { $this->sql = new stdClass(); $this->sql->fields = $fields; $this->sql->from = $from; @@ -140,11 +154,11 @@ class sql_table extends flexible_table { * @param bool $useinitialsbar do you want to use the initials bar. Bar * will only be used if there is a fullname column defined for the table. */ - function query_db($pagesize, $useinitialsbar=true) { + public function query_db($pagesize, $useinitialsbar = true) { global $DB; if (!$this->is_downloading()) { - if ($this->countsql === NULL) { - $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where; + if ($this->countsql === null) { + $this->countsql = 'SELECT COUNT(1) FROM ' . $this->sql->from . ' WHERE ' . $this->sql->where; $this->countparams = $this->sql->params; } $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams); @@ -152,12 +166,12 @@ class sql_table extends flexible_table { $this->initialbars(true); } - list($wsql, $wparams) = $this->get_sql_where(); + [$wsql, $wparams] = $this->get_sql_where(); if ($wsql) { - $this->countsql .= ' AND '.$wsql; + $this->countsql .= ' AND ' . $wsql; $this->countparams = array_merge($this->countparams, $wparams); - $this->sql->where .= ' AND '.$wsql; + $this->sql->where .= ' AND ' . $wsql; $this->sql->params = array_merge($this->sql->params, $wparams); $total = $DB->count_records_sql($this->countsql, $this->countparams); @@ -168,7 +182,7 @@ class sql_table extends flexible_table { $this->pagesize($pagesize, $total); } - // Fetch the attempts + // Fetch the attempts. $sort = $this->get_sql_sort(); if ($sort) { $sort = "ORDER BY $sort"; @@ -189,14 +203,21 @@ class sql_table extends flexible_table { /** * Convenience method to call a number of methods for you to display the * table. + * + * @param int $pagesize + * @param bool $useinitialsbar + * @param string $downloadhelpbutton */ - function out($pagesize, $useinitialsbar, $downloadhelpbutton='') { + public function out($pagesize, $useinitialsbar, $downloadhelpbutton = '') { global $DB; if (!$this->columns) { - $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", - $this->sql->params, IGNORE_MULTIPLE); - //if columns is not set then define columns as the keys of the rows returned - //from the db. + $onerow = $DB->get_record_sql( + "SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", + $this->sql->params, + IGNORE_MULTIPLE + ); + // If columns is not set then define columns as the keys of the rows returned + // from the db. $this->define_columns(array_keys((array)$onerow)); $this->define_headers(array_keys((array)$onerow)); } diff --git a/lib/tests/html_writer_test.php b/lib/tests/output/html_writer_test.php similarity index 56% rename from lib/tests/html_writer_test.php rename to lib/tests/output/html_writer_test.php index 7823a0def9d..afb88b4915e 100644 --- a/lib/tests/html_writer_test.php +++ b/lib/tests/output/html_writer_test.php @@ -14,15 +14,24 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\output; + +use core_table\output\html_table; +use core_table\output\html_table_cell; +use core_table\output\html_table_row; + +// phpcs:disable moodle.Commenting.DocblockDescription.Missing + /** * Unit tests for the html_writer class. * + * @package core * @copyright 2010 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - * @covers \html_writer - * @coversDefaultClass \html_writer + * @covers \core\output\html_writer + * @coversDefaultClass \\core\output\html_writer */ -final class html_writer_test extends basic_testcase { +final class html_writer_test extends \basic_testcase { /** * @covers ::start_tag */ @@ -34,16 +43,20 @@ final class html_writer_test extends basic_testcase { * @covers ::start_tag */ public function test_start_tag_with_attr(): void { - $this->assertSame('
', - html_writer::start_tag('div', array('class' => 'frog'))); + $this->assertSame( + '
', + html_writer::start_tag('div', ['class' => 'frog']) + ); } /** * @covers ::start_tag */ public function test_start_tag_with_attrs(): void { - $this->assertSame('
', - html_writer::start_tag('div', array('class' => 'frog', 'id' => 'mydiv'))); + $this->assertSame( + '
', + html_writer::start_tag('div', ['class' => 'frog', 'id' => 'mydiv']), + ); } /** @@ -64,48 +77,60 @@ final class html_writer_test extends basic_testcase { * @covers ::empty_Tag */ public function test_empty_tag_with_attrs(): void { - $this->assertSame('', - html_writer::empty_tag('input', array('type' => 'submit', 'value' => 'frog'))); + $this->assertSame( + '', + html_writer::empty_tag('input', ['type' => 'submit', 'value' => 'frog']), + ); } /** * @covers ::nonempty_tag */ public function test_nonempty_tag_with_content(): void { - $this->assertSame('
Hello world!
', - html_writer::nonempty_tag('div', 'Hello world!')); + $this->assertSame( + '
Hello world!
', + html_writer::nonempty_tag('div', 'Hello world!'), + ); } /** * @covers ::nonempty_tag */ public function test_nonempty_tag_empty(): void { - $this->assertSame('', - html_writer::nonempty_tag('div', '')); + $this->assertSame( + '', + html_writer::nonempty_tag('div', ''), + ); } /** * @covers ::nonempty_tag */ public function test_nonempty_tag_null(): void { - $this->assertSame('', - html_writer::nonempty_tag('div', null)); + $this->assertSame( + '', + html_writer::nonempty_tag('div', null), + ); } /** * @covers ::nonempty_tag */ public function test_nonempty_tag_zero(): void { - $this->assertSame('
0
', - html_writer::nonempty_tag('div', 0, array('class' => 'score'))); + $this->assertSame( + '
0
', + html_writer::nonempty_tag('div', 0, ['class' => 'score']) + ); } /** * @covers ::nonempty_tag */ public function test_nonempty_tag_zero_string(): void { - $this->assertSame('
0
', - html_writer::nonempty_tag('div', '0', array('class' => 'score'))); + $this->assertSame( + '
0
', + html_writer::nonempty_tag('div', '0', ['class' => 'score']) + ); } /** @@ -113,20 +138,30 @@ final class html_writer_test extends basic_testcase { */ public function test_div(): void { // All options. - $this->assertSame('
ribbit
', - html_writer::div('ribbit', 'frog', array('id' => 'kermit'))); + $this->assertSame( + '
ribbit
', + html_writer::div('ribbit', 'frog', ['id' => 'kermit']) + ); // Combine class from attributes and $class. - $this->assertSame('
ribbit
', - html_writer::div('ribbit', 'frog', array('class' => 'amphibian'))); + $this->assertSame( + '
ribbit
', + html_writer::div('ribbit', 'frog', ['class' => 'amphibian']) + ); // Class only. - $this->assertSame('
ribbit
', - html_writer::div('ribbit', 'frog')); + $this->assertSame( + '
ribbit
', + html_writer::div('ribbit', 'frog') + ); // Attributes only. - $this->assertSame('
ribbit
', - html_writer::div('ribbit', '', array('id' => 'kermit'))); + $this->assertSame( + '
ribbit
', + html_writer::div('ribbit', '', ['id' => 'kermit']) + ); // No options. - $this->assertSame('
ribbit
', - html_writer::div('ribbit')); + $this->assertSame( + '
ribbit
', + html_writer::div('ribbit') + ); } /** @@ -134,20 +169,30 @@ final class html_writer_test extends basic_testcase { */ public function test_start_div(): void { // All options. - $this->assertSame('
', - html_writer::start_div('frog', array('id' => 'kermit'))); + $this->assertSame( + '
', + html_writer::start_div('frog', ['id' => 'kermit']) + ); // Combine class from attributes and $class. - $this->assertSame('
', - html_writer::start_div('frog', array('class' => 'amphibian'))); + $this->assertSame( + '
', + html_writer::start_div('frog', ['class' => 'amphibian']) + ); // Class only. - $this->assertSame('
', - html_writer::start_div('frog')); + $this->assertSame( + '
', + html_writer::start_div('frog') + ); // Attributes only. - $this->assertSame('
', - html_writer::start_div('', array('id' => 'kermit'))); + $this->assertSame( + '
', + html_writer::start_div('', ['id' => 'kermit']) + ); // No options. - $this->assertSame('
', - html_writer::start_div()); + $this->assertSame( + '
', + html_writer::start_div() + ); } /** @@ -162,20 +207,30 @@ final class html_writer_test extends basic_testcase { */ public function test_span(): void { // All options. - $this->assertSame('ribbit', - html_writer::span('ribbit', 'frog', array('id' => 'kermit'))); + $this->assertSame( + 'ribbit', + html_writer::span('ribbit', 'frog', ['id' => 'kermit']) + ); // Combine class from attributes and $class. - $this->assertSame('ribbit', - html_writer::span('ribbit', 'frog', array('class' => 'amphibian'))); + $this->assertSame( + 'ribbit', + html_writer::span('ribbit', 'frog', ['class' => 'amphibian']) + ); // Class only. - $this->assertSame('ribbit', - html_writer::span('ribbit', 'frog')); + $this->assertSame( + 'ribbit', + html_writer::span('ribbit', 'frog') + ); // Attributes only. - $this->assertSame('ribbit', - html_writer::span('ribbit', '', array('id' => 'kermit'))); + $this->assertSame( + 'ribbit', + html_writer::span('ribbit', '', ['id' => 'kermit']) + ); // No options. - $this->assertSame('ribbit', - html_writer::span('ribbit')); + $this->assertSame( + 'ribbit', + html_writer::span('ribbit') + ); } /** @@ -183,20 +238,30 @@ final class html_writer_test extends basic_testcase { */ public function test_start_span(): void { // All options. - $this->assertSame('', - html_writer::start_span('frog', array('id' => 'kermit'))); + $this->assertSame( + '', + html_writer::start_span('frog', ['id' => 'kermit']) + ); // Combine class from attributes and $class. - $this->assertSame('', - html_writer::start_span('frog', array('class' => 'amphibian'))); + $this->assertSame( + '', + html_writer::start_span('frog', ['class' => 'amphibian']) + ); // Class only. - $this->assertSame('', - html_writer::start_span('frog')); + $this->assertSame( + '', + html_writer::start_span('frog') + ); // Attributes only. - $this->assertSame('', - html_writer::start_span('', array('id' => 'kermit'))); + $this->assertSame( + '', + html_writer::start_span('', ['id' => 'kermit']) + ); // No options. - $this->assertSame('', - html_writer::start_span()); + $this->assertSame( + '', + html_writer::start_span() + ); } /** @@ -208,9 +273,9 @@ final class html_writer_test extends basic_testcase { /** * @covers ::table - * @covers \html_table_row - * @covers \html_table_cell - * @covers \html_table + * @covers \core_table\output\html_table_row + * @covers \core_table\output\html_table_cell + * @covers \core_table\output\html_table */ public function test_table(): void { $row = new html_table_row(); @@ -268,11 +333,11 @@ EOF; $table = new html_table(); $table->id = "whodat"; - $table->data = array( - array('fred', 'MDK'), - array('bob', 'Burgers'), - array('dave', 'Competitiveness') - ); + $table->data = [ + ['fred', 'MDK'], + ['bob', 'Burgers'], + ['dave', 'Competitiveness'], + ]; $table->caption = "Who even knows?"; $table->captionhide = true; $table->responsive = false;
element */ - public $attributes = array(); + public $attributes = []; /** * Constructs a table cell diff --git a/lib/table/classes/output/html_table_row.php b/lib/table/classes/output/html_table_row.php index 6b92c0a5486..b70a7dcd400 100644 --- a/lib/table/classes/output/html_table_row.php +++ b/lib/table/classes/output/html_table_row.php @@ -22,7 +22,7 @@ namespace core_table\output; * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 - * @package core + * @package core_table * @category output */ class html_table_row { @@ -34,7 +34,7 @@ class html_table_row { /** * @var array Array of html_table_cell objects */ - public $cells = array(); + public $cells = []; /** * @var string Value to use for the style attribute of the table row @@ -44,13 +44,14 @@ class html_table_row { /** * @var array Attributes of additional HTML attributes for the