Files
MokoSuiteBackup/source/packages/com_mokosuitebackup/src/Engine/PlaceholderResolver.php
T
jmiller 5ffcbcc2f1
Universal: PR Check / Require Docs Update (pull_request) Has been skipped
Universal: PR Check / Wiki Update Reminder (pull_request) Has been skipped
Universal: PR Check / Branch Policy (pull_request) Successful in 2s
Universal: Pre-Release / Build Pre-Release (${{ inputs.stability || github.ref_name }}) (push) Successful in 40s
Universal: PR Check / Secret Scan (pull_request) Successful in 9s
Generic: Project CI / Lint & Validate (pull_request) Successful in 17s
Joomla: Metadata Validation / Validate Joomla Metadata (pull_request) Successful in 16s
Universal: PR Check / Validate PR (pull_request) Failing after 50s
Generic: Project CI / Tests (pull_request) Has been cancelled
Universal: PR Check / Build RC Package (pull_request) Has been cancelled
Universal: PR Check / Report Issues (pull_request) Has been cancelled
fix: CLI backups no longer named joomla.invalid (host placeholder)
Joomla's console fills $_SERVER['HTTP_HOST'] with the reserved sentinel
'joomla.invalid', which the [HOST] placeholder resolver used verbatim
because its unusable-host check only knew about empty/localhost. Treat
'joomla.invalid' as unusable too, falling back to live_site then the
system hostname, so CLI/console/scheduled backups get a real name.

Claude-Session: https://claude.ai/code/session_01WbGBN9VyRK61zczYWcCQ2i
2026-07-05 22:02:46 -05:00

164 lines
4.8 KiB
PHP

<?php
/**
* @package MokoSuiteBackup
* @subpackage com_mokosuitebackup
* @author Moko Consulting <hello@mokoconsulting.tech>
* @copyright Copyright (C) 2026 Moko Consulting. All rights reserved.
* @license GNU General Public License version 3 or later; see LICENSE
*
* Resolves placeholders like [HOST], [DATE], [PROFILE_NAME] in backup
* directory paths and archive filename formats.
*/
namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\Component\MokoSuiteBackup\Administrator\Utility\BackupDirectory;
class PlaceholderResolver
{
/**
* Supported placeholders and their descriptions (for documentation).
*/
public const PLACEHOLDERS = [
'[HOST]' => 'Server hostname',
'[DATE]' => 'Date as Ymd (e.g. 20260604)',
'[TIME]' => 'Time as His (e.g. 143025)',
'[DATETIME]' => 'Date and time as Ymd_His',
'[YEAR]' => 'Four-digit year',
'[MONTH]' => 'Two-digit month',
'[DAY]' => 'Two-digit day',
'[HOUR]' => 'Two-digit hour (24h)',
'[MINUTE]' => 'Two-digit minute',
'[SECOND]' => 'Two-digit second',
'[PROFILE_ID]' => 'Backup profile ID',
'[PROFILE_NAME]' => 'Profile title (sanitized)',
'[SITE_NAME]' => 'Joomla site name (sanitized)',
'[TYPE]' => 'Backup type (full, database, files, differential)',
'[RANDOM]' => 'Random 6-character hex string',
'[DEFAULT_DIR]' => 'Default backup directory',
'[HOME]' => 'Home directory of the PHP process owner',
];
private array $replacements;
/**
* @param object $profile The backup profile object
*/
public function __construct(object $profile)
{
$now = new \DateTimeImmutable('now');
/* Resolve hostname: prefer the real request host (web), then the
configured live_site (CLI), then the system hostname. Joomla's console
fills the request host with the placeholder 'joomla.invalid' (an
RFC 6761 reserved TLD used as a CLI sentinel), so treat that — along
with empty/localhost — as unusable and fall through; otherwise every
CLI-triggered backup would be named 'joomla.invalid_…'. */
$unusable = static function (string $h): bool {
$h = strtolower(trim($h));
return $h === '' || $h === 'localhost' || $h === 'joomla.invalid';
};
$rawHost = (string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '');
if ($unusable($rawHost)) {
try {
$liveSite = (string) Factory::getApplication()->get('live_site', '');
if ($liveSite !== '') {
$parsed = parse_url($liveSite, PHP_URL_HOST);
if (!empty($parsed)) {
$rawHost = $parsed;
}
}
} catch (\Throwable $e) {
/* fall through to system hostname */
}
}
if ($unusable($rawHost)) {
$sysHost = php_uname('n');
$rawHost = $sysHost !== '' ? $sysHost : 'site';
}
$hostname = preg_replace('/[^a-zA-Z0-9._-]/', '', $rawHost);
$siteName = '';
try {
$siteName = Factory::getApplication()->get('sitename', '');
} catch (\Throwable $e) {
// Fallback: not critical
}
$this->replacements = [
'[HOST]' => $hostname,
'[DATE]' => $now->format('Ymd'),
'[TIME]' => $now->format('His'),
'[DATETIME]' => $now->format('Ymd_His'),
'[YEAR]' => $now->format('Y'),
'[MONTH]' => $now->format('m'),
'[DAY]' => $now->format('d'),
'[HOUR]' => $now->format('H'),
'[MINUTE]' => $now->format('i'),
'[SECOND]' => $now->format('s'),
'[PROFILE_ID]' => (string) ($profile->id ?? '0'),
'[PROFILE_NAME]' => $this->sanitize($profile->title ?? 'default'),
'[SITE_NAME]' => $this->sanitize($siteName ?: 'joomla'),
'[TYPE]' => $profile->backup_type ?? 'full',
'[RANDOM]' => bin2hex(random_bytes(3)),
'[DEFAULT_DIR]' => BackupDirectory::getDefaultAbsolute(),
'[HOME]' => BackupDirectory::getHomeDirectory(),
];
}
/**
* Replace all placeholders in a string.
*
* @param string $template String containing [placeholder] tokens
*
* @return string Resolved string
*/
public function resolve(string $template): string
{
return str_replace(
array_keys($this->replacements),
array_values($this->replacements),
$template
);
}
/**
* Get the raw hostname value (for backward compatibility).
*/
public function getHostname(): string
{
return $this->replacements['[HOST]'];
}
/**
* Get the datetime tag value (for backward compatibility).
*/
public function getTag(): string
{
return $this->replacements['[DATETIME]'];
}
/**
* Sanitize a string for use in filenames/paths.
* Keeps alphanumerics, dots, hyphens, underscores. Replaces spaces with hyphens.
*/
private function sanitize(string $value): string
{
$value = str_replace(' ', '-', trim($value));
return preg_replace('/[^a-zA-Z0-9._-]/', '', $value);
}
}