Joomla CMS  4.2.2
Documentation des API du CMS Joomla en version 4.2.2
C:/laragon/www/_install/Joomla_422-Stable-Full_Package_French_v1/libraries/src/HTML/HTMLHelper.php

Gets a URL, cleans the Joomla specific params and returns an object

Paramètres
string$urlThe relative or absolute URL to use for the src attribute.
Renvoie
object
        url: 'string',
        attributes: [
          width:  integer,
          height: integer,
        ]
      }
Depuis
4.0.0
<?php
namespace Joomla\CMS\HTML;
// phpcs:disable PSR1.Files.SideEffects
\defined('JPATH_PLATFORM') or die;
// phpcs:enable PSR1.Files.SideEffects
abstract class HTMLHelper
{
public static $formatOptions = array('format.depth' => 0, 'format.eol' => "\n", 'format.indent' => "\t");
protected static $includePaths = array();
protected static $registry = array();
protected static $serviceRegistry;
protected static function extract($key)
{
$key = preg_replace('#[^A-Z0-9_\.]#i', '', $key);
// Check to see whether we need to load a helper file
$parts = explode('.', $key);
if (\count($parts) === 3) {
'Support for a three segment service key is deprecated and will be removed in Joomla 5.0, use the service registry instead',
);
}
$prefix = \count($parts) === 3 ? array_shift($parts) : 'JHtml';
$file = \count($parts) === 2 ? array_shift($parts) : '';
$func = array_shift($parts);
return array(strtolower($prefix . '.' . $file . '.' . $func), $prefix, $file, $func);
}
final public static function _(string $key, ...$methodArgs)
{
list($key, $prefix, $file, $func) = static::extract($key);
if (\array_key_exists($key, static::$registry)) {
$function = static::$registry[$key];
return static::call($function, $methodArgs);
}
/*
* Support fetching services from the registry if a custom class prefix was not given (a three segment key),
* the service comes from a class other than this one, and a service has been registered for the file.
*/
if ($prefix === 'JHtml' && $file !== '' && static::getServiceRegistry()->hasService($file)) {
$service = static::getServiceRegistry()->getService($file);
$toCall = array($service, $func);
if (!\is_callable($toCall)) {
throw new \InvalidArgumentException(sprintf('%s::%s not found.', $file, $func), 500);
}
static::register($key, $toCall);
return static::call($toCall, $methodArgs);
}
$className = $prefix . ucfirst($file);
$path = Path::find(static::$includePaths, strtolower($file) . '.php');
if (!$path) {
throw new \InvalidArgumentException(sprintf('%s %s not found.', $prefix, $file), 500);
}
throw new \InvalidArgumentException(sprintf('%s not found.', $className), 500);
}
}
// If calling a method from this class, do not allow access to internal methods
if ($className === __CLASS__) {
if (!((new \ReflectionMethod($className, $func))->isPublic())) {
throw new \InvalidArgumentException('Access to internal class methods is not allowed.');
}
}
$toCall = array($className, $func);
if (!\is_callable($toCall)) {
throw new \InvalidArgumentException(sprintf('%s::%s not found.', $className, $func), 500);
}
static::register($key, $toCall);
return static::call($toCall, $methodArgs);
}
public static function register($key, callable $function)
{
'Support for registering functions is deprecated and will be removed in Joomla 5.0, use the service registry instead',
);
list($key) = static::extract($key);
static::$registry[$key] = $function;
return true;
}
public static function unregister($key)
{
'Support for registering functions is deprecated and will be removed in Joomla 5.0, use the service registry instead',
);
list($key) = static::extract($key);
if (isset(static::$registry[$key])) {
unset(static::$registry[$key]);
return true;
}
return false;
}
public static function isRegistered($key)
{
list($key) = static::extract($key);
return isset(static::$registry[$key]);
}
public static function getServiceRegistry(): Registry
{
if (!static::$serviceRegistry) {
static::$serviceRegistry = Factory::getContainer()->get(Registry::class);
}
return static::$serviceRegistry;
}
protected static function call(callable $function, $args)
{
// Workaround to allow calling helper methods have arguments passed by reference
$temp = [];
foreach ($args as &$arg) {
$temp[] = &$arg;
}
return \call_user_func_array($function, $temp);
}
public static function link($url, $text, $attribs = null)
{
if (\is_array($attribs)) {
}
return '<a href="' . $url . '" ' . $attribs . '>' . $text . '</a>';
}
public static function iframe($url, $name, $attribs = null, $noFrames = '')
{
if (\is_array($attribs)) {
}
return '<iframe src="' . $url . '" ' . $attribs . ' name="' . $name . '">' . $noFrames . '</iframe>';
}
protected static function includeRelativeFiles($folder, $file, $relative, $detectBrowser, $detectDebug)
{
// Set debug flag
$debugMode = false;
// Detect debug mode
if ($detectDebug && JDEBUG) {
$debugMode = true;
}
// If http is present in filename
if (strpos($file, 'http') === 0 || strpos($file, '//') === 0) {
$includes = [$file];
} else {
// Extract extension and strip the file
$strip = File::stripExt($file);
$ext = File::getExt($file);
// Prepare array of files
$includes = [];
// Detect browser and compute potential files
if ($detectBrowser) {
$navigator = Browser::getInstance();
$browser = $navigator->getBrowser();
$major = $navigator->getMajor();
$minor = $navigator->getMinor();
$minExt = '';
if (\strlen($strip) > 4 && preg_match('#\.min$#', $strip)) {
$minExt = '.min';
$strip = preg_replace('#\.min$#', '', $strip);
}
// Try to include files named filename.ext, filename_browser.ext, filename_browser_major.ext, filename_browser_major_minor.ext
// where major and minor are the browser version names
$potential = [
$strip . $minExt,
$strip . '_' . $browser . $minExt,
$strip . '_' . $browser . '_' . $major . $minExt,
$strip . '_' . $browser . '_' . $major . '_' . $minor . $minExt,
];
} else {
$potential = [$strip];
}
// If relative search in template directory or media directory
if ($relative) {
$template = $app->getTemplate(true);
$templaPath = JPATH_THEMES;
if ($template->inheritable || !empty($template->parent)) {
$client = $app->isClient('administrator') === true ? 'administrator' : 'site';
$templaPath = JPATH_ROOT . "/media/templates/$client";
}
// For each potential files
foreach ($potential as $strip) {
$files = [];
$files[] = $strip . '.' . $ext;
foreach ($files as $file) {
if (!empty($template->parent)) {
$found = static::addFileToBuffer("$templaPath/$template->template/$folder/$file", $ext, $debugMode);
if (empty($found)) {
$found = static::addFileToBuffer("$templaPath/$template->parent/$folder/$file", $ext, $debugMode);
}
} else {
$found = static::addFileToBuffer("$templaPath/$template->template/$folder/$file", $ext, $debugMode);
}
if (!empty($found)) {
$includes[] = $found;
break;
} else {
// If the file contains any /: it can be in a media extension subfolder
if (strpos($file, '/')) {
// Divide the file extracting the extension as the first part before /
list($extension, $file) = explode('/', $file, 2);
// If the file yet contains any /: it can be a plugin
if (strpos($file, '/')) {
// Divide the file extracting the element as the first part before /
list($element, $file) = explode('/', $file, 2);
// Try to deal with plugins group in the media folder
$found = static::addFileToBuffer(JPATH_ROOT . "/media/$extension/$element/$folder/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
// Try to deal with classical file in a media subfolder called element
$found = static::addFileToBuffer(JPATH_ROOT . "/media/$extension/$folder/$element/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
// Try to deal with system files in the template folder
if (!empty($template->parent)) {
$found = static::addFileToBuffer("$templaPath/$template->template/$folder/system/$element/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
$found = static::addFileToBuffer("$templaPath/$template->parent/$folder/system/$element/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
} else {
// Try to deal with system files in the media folder
$found = static::addFileToBuffer(JPATH_ROOT . "/media/system/$folder/$element/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
}
} else {
// Try to deal with files in the extension's media folder
$found = static::addFileToBuffer(JPATH_ROOT . "/media/$extension/$folder/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
// Try to deal with system files in the template folder
if (!empty($template->parent)) {
$found = static::addFileToBuffer("$templaPath/$template->template/$folder/system/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
$found = static::addFileToBuffer("$templaPath/$template->parent/$folder/system/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
} else {
// Try to deal with system files in the template folder
$found = static::addFileToBuffer("$templaPath/$template->template/$folder/system/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
}
// Try to deal with system files in the media folder
$found = static::addFileToBuffer(JPATH_ROOT . "/media/system/$folder/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
}
} else {
// Try to deal with system files in the media folder
$found = static::addFileToBuffer(JPATH_ROOT . "/media/system/$folder/$file", $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
}
}
}
}
} else {
// If not relative and http is not present in filename
foreach ($potential as $strip) {
$files = [];
$files[] = $strip . '.' . $ext;
foreach ($files as $file) {
$path = JPATH_ROOT . "/$file";
$found = static::addFileToBuffer($path, $ext, $debugMode);
if (!empty($found)) {
$includes[] = $found;
break;
}
}
}
}
}
return $includes;
}
public static function cleanImageURL($url)
{
$obj = new \stdClass();
$obj->attributes = [
'width' => 0,
'height' => 0,
];
if ($url === null) {
$url = '';
}
if (!strpos($url, '?')) {
$obj->url = $url;
return $obj;
}
$mediaUri = new Uri($url);
// Old image URL format
if ($mediaUri->hasVar('joomla_image_height')) {
$height = (int) $mediaUri->getVar('joomla_image_height');
$width = (int) $mediaUri->getVar('joomla_image_width');
$mediaUri->delVar('joomla_image_height');
$mediaUri->delVar('joomla_image_width');
} else {
// New Image URL format
$fragmentUri = new Uri($mediaUri->getFragment());
$width = (int) $fragmentUri->getVar('width', 0);
$height = (int) $fragmentUri->getVar('height', 0);
}
if ($width > 0) {
$obj->attributes['width'] = $width;
}
if ($height > 0) {
$obj->attributes['height'] = $height;
}
$mediaUri->setFragment('');
$obj->url = $mediaUri->toString();
return $obj;
}
public static function image($file, $alt, $attribs = null, $relative = false, $returnPath = 0)
{
// Ensure is an integer
$returnPath = (int) $returnPath;
// The path of the file
$path = $file;
// The arguments of the file path
$arguments = '';
// Get the arguments positions
$pos1 = strpos($file, '?');
$pos2 = strpos($file, '#');
// Check if there are arguments
if ($pos1 !== false || $pos2 !== false) {
// Get the path only
$path = substr($file, 0, min($pos1, $pos2));
// Determine the arguments is mostly the part behind the #
$arguments = str_replace($path, '', $file);
}
// Get the relative file name when requested
if ($returnPath !== -1) {
// Search for relative file names
$includes = static::includeRelativeFiles('images', $path, $relative, false, false);
// Grab the first found path and if none exists default to null
$path = \count($includes) ? $includes[0] : null;
}
// Compile the file name
$file = ($path === null ? null : $path . $arguments);
// If only the file is required, return here
if ($returnPath === 1) {
return $file;
}
// Ensure we have a valid default for concatenating
if ($attribs === null || $attribs === false) {
$attribs = [];
}
// When it is a string, we need convert it to an array
// Go through each argument
foreach (explode(' ', $attribs) as $attribute) {
// When an argument without a value, default to an empty string
if (strpos($attribute, '=') === false) {
$attributes[$attribute] = '';
continue;
}
// Set the attribute
list($key, $value) = explode('=', $attribute);
}
// Add the attributes from the string to the original attributes
}
// Fill the attributes with the file and alt text
$attribs['src'] = $file;
$attribs['alt'] = $alt;
// Render the layout with the attributes
return LayoutHelper::render('joomla.html.image', $attribs);
}
public static function stylesheet($file, $options = array(), $attribs = array())
{
$options['relative'] = $options['relative'] ?? false;
$options['pathOnly'] = $options['pathOnly'] ?? false;
$options['detectBrowser'] = $options['detectBrowser'] ?? false;
$options['detectDebug'] = $options['detectDebug'] ?? true;
$includes = static::includeRelativeFiles('css', $file, $options['relative'], $options['detectBrowser'], $options['detectDebug']);
// If only path is required
if ($options['pathOnly']) {
if (\count($includes) === 0) {
return;
}
if (\count($includes) === 1) {
return $includes[0];
}
return $includes;
}
// If inclusion is required
$document = Factory::getApplication()->getDocument();
foreach ($includes as $include) {
// If there is already a version hash in the script reference (by using deprecated MD5SUM).
if ($pos = strpos($include, '?') !== false) {
$options['version'] = substr($include, $pos + 1);
}
$document->addStyleSheet($include, $options, $attribs);
}
}
public static function script($file, $options = array(), $attribs = array())
{
$options['relative'] = $options['relative'] ?? false;
$options['pathOnly'] = $options['pathOnly'] ?? false;
$options['detectBrowser'] = $options['detectBrowser'] ?? false;
$options['detectDebug'] = $options['detectDebug'] ?? true;
$includes = static::includeRelativeFiles('js', $file, $options['relative'], $options['detectBrowser'], $options['detectDebug']);
// If only path is required
if ($options['pathOnly']) {
if (\count($includes) === 0) {
return;
}
if (\count($includes) === 1) {
return $includes[0];
}
return $includes;
}
// If inclusion is required
$document = Factory::getApplication()->getDocument();
foreach ($includes as $include) {
// If there is already a version hash in the script reference (by using deprecated MD5SUM).
if ($pos = strpos($include, '?') !== false) {
$options['version'] = substr($include, $pos + 1);
}
$document->addScript($include, $options, $attribs);
}
}
public static function setFormatOptions($options)
{
foreach ($options as $key => $val) {
if (isset(static::$formatOptions[$key])) {
static::$formatOptions[$key] = $val;
}
}
}
public static function date($input = 'now', $format = null, $tz = true, $gregorian = false)
{
// UTC date converted to user time zone.
if ($tz === true) {
// Get a date object based on UTC.
// Set the correct time zone based on the user configuration.
$date->setTimezone($app->getIdentity()->getTimezone());
} elseif ($tz === false) {
// UTC date converted to server time zone.
// Get a date object based on UTC.
// Set the correct time zone based on the server configuration.
$date->setTimezone(new \DateTimeZone($app->get('offset')));
} elseif ($tz === null) {
// No date conversion.
} else {
// UTC date converted to given time zone.
// Get a date object based on UTC.
// Set the correct time zone based on the server configuration.
$date->setTimezone(new \DateTimeZone($tz));
}
// If no format is given use the default locale based format.
if (!$format) {
$format = Text::_('DATE_FORMAT_LC1');
// $format is an existing language key
}
if ($gregorian) {
return $date->format($format, true);
}
return $date->calendar($format, true);
}
public static function tooltip($tooltip, $title = '', $image = 'tooltip.png', $text = '', $href = '', $alt = 'Tooltip', $class = 'hasTooltip')
{
if (\is_array($title)) {
foreach (array('image', 'text', 'href', 'alt', 'class') as $param) {
if (isset($title[$param])) {
$$param = $title[$param];
}
}
if (isset($title['title'])) {
$title = $title['title'];
} else {
$title = '';
}
}
if (!$text) {
$alt = htmlspecialchars($alt, ENT_COMPAT, 'UTF-8');
}
if ($href) {
$tip = '<a href="' . $href . '">' . $text . '</a>';
} else {
$tip = $text;
}
if ($class === 'hasTip') {
// Still using MooTools tooltips!
$tooltip = htmlspecialchars($tooltip, ENT_COMPAT, 'UTF-8');
if ($title) {
$title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
$tooltip = $title . '::' . $tooltip;
}
} else {
$tooltip = self::tooltipText($title, $tooltip, 0);
}
return '<span class="' . $class . '" title="' . $tooltip . '">' . $tip . '</span>';
}
public static function tooltipText($title = '', $content = '', $translate = true, $escape = true)
{
// Initialise return value.
$result = '';
// Don't process empty strings
if ($content !== '' || $title !== '') {
// Split title into title and content if the title contains '::' (old Mootools format).
if ($content === '' && !(strpos($title, '::') === false)) {
list($title, $content) = explode('::', $title, 2);
}
// Pass texts through Text if required.
if ($translate) {
}
// Use only the content if no title is given.
if ($title === '') {
// Use only the title, if title and text are the same.
$result = '<strong>' . $title . '</strong>';
} elseif ($content !== '') {
// Use a formatted string combining the title and content.
$result = '<strong>' . $title . '</strong><br>' . $content;
} else {
}
// Escape everything, if required.
if ($escape) {
$result = htmlspecialchars($result);
}
}
return $result;
}
public static function calendar($value, $name, $id, $format = '%Y-%m-%d', $attribs = array())
{
$lang = $app->getLanguage();
$tag = $lang->getTag();
$calendar = $lang->getCalendar();
$direction = strtolower($app->getDocument()->getDirection());
// Get the appropriate file for the current language date helper
$helperPath = 'system/fields/calendar-locales/date/gregorian/date-helper.min.js';
if ($calendar && is_dir(JPATH_ROOT . '/media/system/js/fields/calendar-locales/date/' . strtolower($calendar))) {
$helperPath = 'system/fields/calendar-locales/date/' . strtolower($calendar) . '/date-helper.min.js';
}
$readonly = isset($attribs['readonly']) && $attribs['readonly'] === 'readonly';
$disabled = isset($attribs['disabled']) && $attribs['disabled'] === 'disabled';
$autocomplete = isset($attribs['autocomplete']) && $attribs['autocomplete'] === '';
$autofocus = isset($attribs['autofocus']) && $attribs['autofocus'] === '';
$required = isset($attribs['required']) && $attribs['required'] === '';
$filter = isset($attribs['filter']) && $attribs['filter'] === '';
$todayBtn = $attribs['todayBtn'] ?? true;
$weekNumbers = $attribs['weekNumbers'] ?? true;
$showTime = $attribs['showTime'] ?? false;
$fillTable = $attribs['fillTable'] ?? true;
$timeFormat = $attribs['timeFormat'] ?? 24;
$singleHeader = $attribs['singleHeader'] ?? false;
$hint = $attribs['placeholder'] ?? '';
$class = $attribs['class'] ?? '';
$onchange = $attribs['onChange'] ?? '';
$minYear = $attribs['minYear'] ?? null;
$maxYear = $attribs['maxYear'] ?? null;
$showTime = ($showTime) ? "1" : "0";
$todayBtn = ($todayBtn) ? "1" : "0";
$weekNumbers = ($weekNumbers) ? "1" : "0";
$fillTable = ($fillTable) ? "1" : "0";
$singleHeader = ($singleHeader) ? "1" : "0";
// Format value when not nulldate ('0000-00-00 00:00:00'), otherwise blank it as it would result in 1970-01-01.
if ($value && $value !== Factory::getDbo()->getNullDate() && strtotime($value) !== false) {
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$inputvalue = strftime($format, strtotime($value));
date_default_timezone_set($tz);
} else {
}
$data = array(
'id' => $id,
'name' => $name,
'class' => $class,
'value' => $inputvalue,
'format' => $format,
'filter' => $filter,
'required' => $required,
'readonly' => $readonly,
'disabled' => $disabled,
'hint' => $hint,
'autofocus' => $autofocus,
'autocomplete' => $autocomplete,
'todaybutton' => $todayBtn,
'weeknumbers' => $weekNumbers,
'showtime' => $showTime,
'filltable' => $fillTable,
'timeformat' => $timeFormat,
'singleheader' => $singleHeader,
'tag' => $tag,
'helperPath' => $helperPath,
'direction' => $direction,
'onchange' => $onchange,
'minYear' => $minYear,
'maxYear' => $maxYear,
'dataAttribute' => '',
'dataAttributes' => '',
'calendar' => $calendar,
'firstday' => $lang->getFirstDay(),
'weekend' => explode(',', $lang->getWeekEnd()),
);
return LayoutHelper::render('joomla.form.field.calendar', $data, null, null);
}
public static function addIncludePath($path = '')
{
'Support for registering lookup paths is deprecated and will be removed in Joomla 5.0, use the service registry instead',
);
// Loop through the path directories
foreach ((array) $path as $dir) {
if (!empty($dir) && !\in_array($dir, static::$includePaths)) {
array_unshift(static::$includePaths, Path::clean($dir));
}
}
return static::$includePaths;
}
protected static function addFileToBuffer($path = '', $ext = '', $debugMode = false)
{
$position = strrpos($path, '.min.');
// We are handling a name.min.ext file:
if ($position !== false) {
$minifiedPath = $path;
$nonMinifiedPath = substr_replace($path, '', $position, 4);
if ($debugMode) {
return self::checkFileOrder($minifiedPath, $nonMinifiedPath);
}
return self::checkFileOrder($nonMinifiedPath, $minifiedPath);
}
$minifiedPath = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME) . '.min.' . $ext;
if ($debugMode) {
return self::checkFileOrder($minifiedPath, $path);
}
return self::checkFileOrder($path, $minifiedPath);
}
protected static function convertToRelativePath($path)
{
$relativeFilePath = Uri::root(true) . str_replace(JPATH_ROOT, '', $path);
// On windows devices we need to replace "\" with "/" otherwise some browsers will not load the asset
return str_replace(DIRECTORY_SEPARATOR, '/', $relativeFilePath);
}
private static function checkFileOrder($first, $second)
{
if (is_file($second)) {
return static::convertToRelativePath($second);
}
if (is_file($first)) {
return static::convertToRelativePath($first);
}
return '';
}
}