Merge pull request 'feat: full-screen backup screen for pre-update + Backup Now (Akeeba-style), fixes white screen' (#238) from feat/fullscreen-backup-screen into dev
Universal: Auto Version Bump / Version Bump (push) Has been skipped
Universal: Pre-Release / Build Pre-Release (${{ inputs.stability || github.ref_name }}) (push) Successful in 17s

This commit was merged in pull request #238.
This commit is contained in:
2026-07-06 03:58:05 +00:00
10 changed files with 455 additions and 448 deletions
@@ -151,18 +151,6 @@
<option value="1">JYES</option>
<option value="0">JNO</option>
</field>
<field
name="preupdate_auto_intercept"
type="radio"
label="COM_MOKOJOOMBACKUP_CONFIG_PREUPDATE_AUTO_INTERCEPT"
description="COM_MOKOJOOMBACKUP_CONFIG_PREUPDATE_AUTO_INTERCEPT_DESC"
default="0"
class="btn-group"
showon="backup_before_update:1"
>
<option value="1">JYES</option>
<option value="0">JNO</option>
</field>
<field
name="backup_before_uninstall"
type="radio"
@@ -336,6 +336,19 @@ COM_MOKOJOOMBACKUP_CONFIG_PREUPDATE_AUTO_INTERCEPT_DESC="When enabled, clicking
COM_MOKOJOOMBACKUP_CONFIG_BACKUP_BEFORE_UNINSTALL="Backup Before Extension Uninstall"
COM_MOKOJOOMBACKUP_CONFIG_BACKUP_BEFORE_UNINSTALL_DESC="Automatically run a full backup before any extension is uninstalled. Uses the default profile. Throttled to once per 10 minutes."
; Full-screen backup progress view (runbackup)
COM_MOKOJOOMBACKUP_RUNBACKUP_TITLE="Backing Up"
COM_MOKOJOOMBACKUP_RUNBACKUP_PROFILE="Profile: %s"
COM_MOKOJOOMBACKUP_RUNBACKUP_STARTING="Starting backup…"
COM_MOKOJOOMBACKUP_RUNBACKUP_RUNNING="Backing up…"
COM_MOKOJOOMBACKUP_RUNBACKUP_COMPLETE="Backup complete"
COM_MOKOJOOMBACKUP_RUNBACKUP_CONTINUING="Backup complete — continuing…"
COM_MOKOJOOMBACKUP_RUNBACKUP_FAILED="Backup failed"
COM_MOKOJOOMBACKUP_RUNBACKUP_RETRY="Retry backup"
COM_MOKOJOOMBACKUP_RUNBACKUP_CONTINUE_ANYWAY="Continue without backup"
COM_MOKOJOOMBACKUP_RUNBACKUP_BACK_TO_DASHBOARD="Back to dashboard"
COM_MOKOJOOMBACKUP_RUNBACKUP_LEAVE_WARNING="A backup is in progress. Leaving now will cancel it."
COM_MOKOJOOMBACKUP_CONFIG_CLEANUP="Cleanup Defaults"
COM_MOKOJOOMBACKUP_CONFIG_MAX_AGE="Max Backup Age (days)"
COM_MOKOJOOMBACKUP_CONFIG_MAX_AGE_DESC="Default maximum age for backup records. Used by the system plugin and CLI cleanup command."
@@ -384,6 +397,8 @@ COM_MOKOJOOMBACKUP_FIELD_NOTIFY_USER_GROUPS_DESC="Select Joomla user groups whos
; Dashboard warnings
COM_MOKOJOOMBACKUP_DASHBOARD_DEFAULT_DIR_WARNING_TITLE="Backup directory is inside the web root"
COM_MOKOJOOMBACKUP_DASHBOARD_DEFAULT_DIR_WARNING="One or more profiles store backups in the default directory inside the web root. This may expose backup archives if .htaccess is not supported. Move backups to a directory outside the web root for better security."
COM_MOKOJOOMBACKUP_DASHBOARD_LIVESITE_WARNING_TITLE="Site URL (live_site) is not set"
COM_MOKOJOOMBACKUP_DASHBOARD_LIVESITE_WARNING="Your Global Configuration has no Site URL (live_site). CLI and scheduled backups can't reliably determine the site's domain (archive names fall back to the server hostname), and some URLs may be generated incorrectly. Set Site URL in System → Global Configuration to your full site address including https://."
COM_MOKOJOOMBACKUP_WEB_ACCESSIBLE_WARNING="This backup is stored inside the web root and may be directly downloadable if .htaccess is not supported."
@@ -58,6 +58,19 @@ COM_MOKOJOOMBACKUP_CONFIG_PREUPDATE_AUTO_INTERCEPT_DESC="When enabled, clicking
COM_MOKOJOOMBACKUP_CONFIG_BACKUP_BEFORE_UNINSTALL="Backup Before Extension Uninstall"
COM_MOKOJOOMBACKUP_CONFIG_BACKUP_BEFORE_UNINSTALL_DESC="Automatically run a full backup before any extension is uninstalled. Uses the default profile. Throttled to once per 10 minutes."
; Full-screen backup progress view (runbackup)
COM_MOKOJOOMBACKUP_RUNBACKUP_TITLE="Backing Up"
COM_MOKOJOOMBACKUP_RUNBACKUP_PROFILE="Profile: %s"
COM_MOKOJOOMBACKUP_RUNBACKUP_STARTING="Starting backup…"
COM_MOKOJOOMBACKUP_RUNBACKUP_RUNNING="Backing up…"
COM_MOKOJOOMBACKUP_RUNBACKUP_COMPLETE="Backup complete"
COM_MOKOJOOMBACKUP_RUNBACKUP_CONTINUING="Backup complete — continuing…"
COM_MOKOJOOMBACKUP_RUNBACKUP_FAILED="Backup failed"
COM_MOKOJOOMBACKUP_RUNBACKUP_RETRY="Retry backup"
COM_MOKOJOOMBACKUP_RUNBACKUP_CONTINUE_ANYWAY="Continue without backup"
COM_MOKOJOOMBACKUP_RUNBACKUP_BACK_TO_DASHBOARD="Back to dashboard"
COM_MOKOJOOMBACKUP_RUNBACKUP_LEAVE_WARNING="A backup is in progress. Leaving now will cancel it."
COM_MOKOJOOMBACKUP_CONFIG_CLEANUP="Cleanup Defaults"
COM_MOKOJOOMBACKUP_CONFIG_MAX_AGE="Max Backup Age (days)"
COM_MOKOJOOMBACKUP_CONFIG_MAX_AGE_DESC="Default maximum age for backup records. Used by the system plugin and CLI cleanup command."
@@ -75,6 +88,8 @@ COM_MOKOJOOMBACKUP_FOLDER_NOT_FOUND="Directory not found"
COM_MOKOJOOMBACKUP_BACKUP_DIR_DEFAULT="Default (inside web root)"
COM_MOKOJOOMBACKUP_DASHBOARD_DEFAULT_DIR_WARNING_TITLE="Backup directory is inside the web root"
COM_MOKOJOOMBACKUP_DASHBOARD_DEFAULT_DIR_WARNING="One or more profiles store backups in the default directory inside the web root. This may expose backup archives if .htaccess is not supported. Move backups to a directory outside the web root for better security."
COM_MOKOJOOMBACKUP_DASHBOARD_LIVESITE_WARNING_TITLE="Site URL (live_site) is not set"
COM_MOKOJOOMBACKUP_DASHBOARD_LIVESITE_WARNING="Your Global Configuration has no Site URL (live_site). CLI and scheduled backups can't reliably determine the site's domain (archive names fall back to the server hostname), and some URLs may be generated incorrectly. Set Site URL in System → Global Configuration to your full site address including https://."
COM_MOKOJOOMBACKUP_WEB_ACCESSIBLE_WARNING="This backup is stored inside the web root and may be directly downloadable if .htaccess is not supported."
COM_MOKOJOOMBACKUP_FOLDER_EXISTS="Directory exists"
COM_MOKOJOOMBACKUP_FOLDER_NOT_FOUND="Directory not found"
@@ -0,0 +1,89 @@
<?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
*/
namespace Joomla\Component\MokoSuiteBackup\Administrator\View\Runbackup;
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\ToolbarHelper;
/**
* Full-screen "run a backup" progress view.
*
* Auto-starts the stepped backup (ajax.init → loop ajax.step) and shows a
* full-page progress screen. Used both by the dashboard "Backup Now" action
* and — via the system plugin's pre-update redirect — as the interstitial
* between clicking Joomla's Update and the update actually running. When a
* `returnurl` is supplied the page redirects there once the backup completes
* (e.g. back to `com_joomlaupdate&task=update.install&is_backed_up=1`).
*/
class HtmlView extends BaseHtmlView
{
public int $profileId = 1;
public string $profileTitle = '';
public string $description = '';
/** Raw (possibly base64) return URL from the request; validated in the layout. */
public string $returnUrl = '';
public bool $autostart = true;
public function display($tpl = null): void
{
$input = Factory::getApplication()->getInput();
$this->profileId = (int) $input->getInt('profile_id', $input->getInt('profileid', 1));
$this->description = $input->getString('description', '');
$this->returnUrl = $input->getRaw('returnurl', '');
$this->autostart = (bool) $input->getInt('autostart', 1);
if ($this->profileId <= 0) {
$this->profileId = 1;
}
$this->profileTitle = $this->loadProfileTitle($this->profileId);
$this->addToolbar();
parent::display($tpl);
}
/**
* Look up the target profile's title for display (best-effort).
*/
private function loadProfileTitle(int $profileId): string
{
try {
$db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class);
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__mokosuitebackup_profiles'))
->where($db->quoteName('id') . ' = ' . (int) $profileId);
$db->setQuery($query);
return (string) ($db->loadResult() ?? '');
} catch (\Throwable $e) {
return '';
}
}
protected function addToolbar(): void
{
ToolbarHelper::title(
Text::_('COM_MOKOJOOMBACKUP_SHORT') . ': ' . Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_TITLE'),
'archive'
);
}
}
@@ -17,6 +17,9 @@ use Joomla\CMS\Session\Session;
$ajaxToken = Session::getFormToken();
$ajaxUrl = Route::_('index.php?option=com_mokosuitebackup&format=json', false);
$runbackupUrl = Route::_('index.php?option=com_mokosuitebackup&view=runbackup&autostart=1', false);
$liveSite = trim((string) \Joomla\CMS\Factory::getApplication()->get('live_site', ''));
?>
<?php if ($this->defaultDirWarning) : ?>
<div class="alert alert-warning d-flex align-items-center mb-3" role="alert">
@@ -31,6 +34,16 @@ $ajaxUrl = Route::_('index.php?option=com_mokosuitebackup&format=json', false)
</div>
<?php endif; ?>
<?php if ($liveSite === '') : ?>
<div class="alert alert-warning d-flex align-items-center mb-3" role="alert">
<span class="icon-warning-circle fs-4 me-3" aria-hidden="true"></span>
<div>
<strong><?php echo Text::_('COM_MOKOJOOMBACKUP_DASHBOARD_LIVESITE_WARNING_TITLE'); ?></strong><br>
<?php echo Text::_('COM_MOKOJOOMBACKUP_DASHBOARD_LIVESITE_WARNING'); ?>
</div>
</div>
<?php endif; ?>
<div class="row">
<!-- Row 1: Status Cards (clickable) -->
<div class="col-md-3 mb-3">
@@ -244,7 +257,7 @@ document.querySelectorAll('.mb-tile').forEach(function(tile) {
</option>
<?php endforeach; ?>
</select>
<button type="button" class="btn btn-primary w-100" onclick="window.mokosuitebackupStart()">
<button type="button" class="btn btn-primary w-100" onclick="mokosuitebackupGo()">
<span class="icon-download" aria-hidden="true"></span>
<?php echo Text::_('COM_MOKOJOOMBACKUP_TOOLBAR_BACKUP_NOW'); ?>
</button>
@@ -302,123 +315,18 @@ document.querySelectorAll('.mb-tile').forEach(function(tile) {
</div>
</div>
<!-- Stepped Backup Modal (reused from backups view) -->
<div id="mokosuitebackup-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:10000;">
<div style="max-width:500px; margin:10% auto; background:#fff; border-radius:8px; padding:2rem; box-shadow:0 4px 20px rgba(0,0,0,0.3);">
<h3 id="mb-modal-title" style="margin:0 0 1rem;">Backup in Progress</h3>
<div class="alert alert-warning py-1 px-2 mb-2" style="font-size:0.85rem;">
<span class="icon-warning-circle" aria-hidden="true"></span>
<strong>Do not navigate away or close this window</strong> while the backup is running.
</div>
<div style="background:#e9ecef; border-radius:4px; overflow:hidden; height:24px; margin-bottom:0.5rem;">
<div id="mb-progress-bar" style="height:100%; background:#0d6efd; transition:width 0.3s; width:0%; display:flex; align-items:center; justify-content:center; color:#fff; font-size:0.8rem; font-weight:bold;">0%</div>
</div>
<p id="mb-status" style="color:#666; font-size:0.9rem; margin:0.5rem 0;">Initializing...</p>
<p id="mb-phase" style="color:#999; font-size:0.8rem; margin:0;">Phase: init</p>
</div>
</div>
<script>
(function() {
const AJAX_URL = <?php echo json_encode($ajaxUrl); ?>;
const TOKEN_NAME = <?php echo json_encode($ajaxToken); ?>;
/* "Backup Now" navigates to the full-screen backup progress page (view=runbackup)
for the selected profile — the same screen used for the pre-update backup. */
(function () {
'use strict';
var backupRunning = false;
var RUNBACKUP_URL = <?php echo json_encode($runbackupUrl); ?>;
window.addEventListener('beforeunload', function(e) {
if (backupRunning) { e.preventDefault(); e.returnValue = ''; }
});
function showModal() {
backupRunning = true;
document.getElementById('mokosuitebackup-modal').style.display = 'block';
}
function hideModal() {
backupRunning = false;
document.getElementById('mokosuitebackup-modal').style.display = 'none';
}
function updateProgress(progress, message, phase) {
const bar = document.getElementById('mb-progress-bar');
bar.style.width = progress + '%';
bar.textContent = progress + '%';
document.getElementById('mb-status').textContent = message;
document.getElementById('mb-phase').textContent = 'Phase: ' + phase;
}
async function postAjax(params) {
const form = new URLSearchParams();
form.append(TOKEN_NAME, '1');
for (const [k, v] of Object.entries(params)) {
form.append(k, v);
}
const res = await fetch(AJAX_URL, {
method: 'POST',
body: form,
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
return res.json();
}
async function startSteppedBackup() {
const profileSelect = document.getElementById('mb-profile-select');
const profileId = profileSelect ? profileSelect.value : '1';
showModal();
updateProgress(0, 'Initializing backup...', 'init');
try {
const initResult = await postAjax({
task: 'ajax.init',
profile_id: profileId
});
if (initResult.error) {
updateProgress(0, 'ERROR: ' + initResult.message, 'failed');
setTimeout(hideModal, 5000);
return;
}
// Show preflight warnings if any
if (initResult.warnings && initResult.warnings.length > 0) {
var warningEl = document.getElementById('mb-phase');
warningEl.textContent = 'Warnings: ' + initResult.warnings.join('; ');
warningEl.style.color = '#856404';
}
const sessionId = initResult.session_id;
updateProgress(initResult.progress, initResult.message, initResult.phase);
let done = false;
while (!done) {
const stepResult = await postAjax({
task: 'ajax.step',
session_id: sessionId
});
if (stepResult.error) {
updateProgress(0, 'ERROR: ' + stepResult.message, 'failed');
setTimeout(hideModal, 5000);
return;
}
updateProgress(stepResult.progress, stepResult.message, stepResult.phase);
done = stepResult.done || false;
}
document.getElementById('mb-modal-title').textContent = 'Backup Complete';
setTimeout(function() {
hideModal();
location.reload();
}, 2000);
} catch (err) {
updateProgress(0, 'ERROR: ' + err.message, 'failed');
setTimeout(hideModal, 5000);
}
}
window.mokosuitebackupStart = startSteppedBackup;
window.mokosuitebackupGo = function () {
var sel = document.getElementById('mb-profile-select');
var pid = sel ? sel.value : '1';
window.location.href = RUNBACKUP_URL + '&profile_id=' + encodeURIComponent(pid);
};
})();
</script>
@@ -0,0 +1,253 @@
<?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
*
* Full-screen backup progress screen. Reuses the stepped-backup AJAX
* (ajax.init → loop ajax.step). On completion, redirects to a validated
* return URL (pre-update flow) or shows a completion panel (Backup Now).
*/
defined('_JEXEC') or die;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
$ajaxToken = Session::getFormToken();
$ajaxUrl = Route::_('index.php?option=com_mokosuitebackup&format=json', false);
/* Validate the return URL to prevent an open redirect / javascript: XSS
(the value ends up in window.location.href). Accept ONLY:
- an absolute http(s) URL whose host matches this site, or
- a root-relative path starting with a single "/" (not "//").
This rejects javascript:, data:, vbscript: (empty host) and
protocol-relative //evil.com. Falls back to '' (no redirect). */
$safeReturnUrl = '';
if ($this->returnUrl !== '') {
$decoded = base64_decode($this->returnUrl, true);
$raw = ($decoded !== false && $decoded !== '') ? $decoded : $this->returnUrl;
$isAbsoluteHttp = (bool) preg_match('#^https?://#i', $raw);
$isRootRelative = isset($raw[0]) && $raw[0] === '/' && (!isset($raw[1]) || $raw[1] !== '/');
if ($isAbsoluteHttp || $isRootRelative) {
try {
$rootHost = Uri::getInstance(Uri::root())->getHost();
$target = new Uri($raw);
$scheme = strtolower((string) $target->getScheme());
$schemeOk = $scheme === '' || $scheme === 'http' || $scheme === 'https';
$hostOk = $target->getHost() === '' || strcasecmp($target->getHost(), $rootHost) === 0;
if ($schemeOk && $hostOk) {
$safeReturnUrl = $raw;
}
} catch (\Throwable $e) {
$safeReturnUrl = '';
}
}
}
$dashboardUrl = Route::_('index.php?option=com_mokosuitebackup&view=dashboard', false);
$config = [
'ajaxUrl' => $ajaxUrl,
'token' => $ajaxToken,
'profileId' => $this->profileId,
'description' => $this->description,
'returnUrl' => $safeReturnUrl,
'dashboardUrl' => $dashboardUrl,
'autostart' => $this->autostart,
'labels' => [
'starting' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_STARTING'),
'running' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_RUNNING'),
'complete' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_COMPLETE'),
'continuing' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_CONTINUING'),
'failed' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_FAILED'),
'retry' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_RETRY'),
'continue' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_CONTINUE_ANYWAY'),
'dashboard' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_BACK_TO_DASHBOARD'),
'leaveWarn' => Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_LEAVE_WARNING'),
],
];
?>
<div class="msb-runbackup" style="max-width:640px;margin:3rem auto;padding:0 1rem;">
<div class="card shadow-sm">
<div class="card-body p-4">
<h1 class="h4 mb-1" id="msb-rb-title">
<span class="icon-archive" aria-hidden="true"></span>
<?php echo Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_TITLE'); ?>
</h1>
<p class="text-muted mb-4" id="msb-rb-subtitle">
<?php echo htmlspecialchars(
$this->profileTitle !== ''
? Text::sprintf('COM_MOKOJOOMBACKUP_RUNBACKUP_PROFILE', $this->profileTitle)
: Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_STARTING'),
ENT_QUOTES,
'UTF-8'
); ?>
</p>
<div class="progress mb-3" style="height:1.75rem;">
<div id="msb-rb-bar" class="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar" style="width:0;" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">0%</div>
</div>
<div id="msb-rb-phase" class="fw-bold mb-1"></div>
<div id="msb-rb-status" class="text-muted small mb-3"><?php echo htmlspecialchars(Text::_('COM_MOKOJOOMBACKUP_RUNBACKUP_STARTING'), ENT_QUOTES, 'UTF-8'); ?></div>
<div id="msb-rb-actions" class="d-none">
<button type="button" id="msb-rb-retry" class="btn btn-primary d-none"></button>
<a href="#" id="msb-rb-continue" class="btn btn-warning d-none"></a>
<a href="<?php echo $dashboardUrl; ?>" id="msb-rb-dashboard" class="btn btn-secondary d-none"></a>
</div>
</div>
</div>
</div>
<script>
(function () {
'use strict';
var CFG = <?php echo json_encode($config); ?>;
var L = CFG.labels || {};
var running = false;
var el = {
bar: document.getElementById('msb-rb-bar'),
phase: document.getElementById('msb-rb-phase'),
status: document.getElementById('msb-rb-status'),
title: document.getElementById('msb-rb-title'),
actions: document.getElementById('msb-rb-actions'),
retry: document.getElementById('msb-rb-retry'),
continue: document.getElementById('msb-rb-continue'),
dashboard: document.getElementById('msb-rb-dashboard')
};
function setBar(pct, striped) {
pct = Math.max(0, Math.min(100, parseInt(pct, 10) || 0));
el.bar.style.width = pct + '%';
el.bar.textContent = pct + '%';
el.bar.setAttribute('aria-valuenow', pct);
if (!striped) {
el.bar.classList.remove('progress-bar-striped', 'progress-bar-animated');
}
}
function setPhase(t) { el.phase.textContent = t || ''; }
function setStatus(t) { if (t) { el.status.textContent = t; } }
function post(params) {
var body = new URLSearchParams();
body.append(CFG.token, '1');
Object.keys(params).forEach(function (k) { body.append(k, params[k]); });
return fetch(CFG.ajaxUrl, {
method: 'POST',
body: body,
headers: { 'X-Requested-With': 'XMLHttpRequest' }
}).then(function (r) { return r.json(); });
}
function showActions() { el.actions.classList.remove('d-none'); }
function showBtn(node, label, href) {
node.textContent = label;
if (href) { node.setAttribute('href', href); }
node.classList.remove('d-none');
}
function onComplete() {
el.bar.classList.remove('progress-bar-striped', 'progress-bar-animated');
el.bar.classList.add('bg-success');
setBar(100, false);
el.title.textContent = L.complete || 'Backup complete';
if (CFG.returnUrl) {
setStatus(L.continuing || 'Continuing…');
window.setTimeout(function () { window.location.href = CFG.returnUrl; }, 1200);
} else {
setStatus(L.complete || 'Backup complete');
showActions();
showBtn(el.dashboard, L.dashboard || 'Back to dashboard', CFG.dashboardUrl);
}
}
function onError(message) {
running = false;
el.bar.classList.remove('progress-bar-striped', 'progress-bar-animated');
el.bar.classList.add('bg-danger');
el.title.textContent = L.failed || 'Backup failed';
setStatus(message || 'Backup failed');
showActions();
el.retry.textContent = L.retry || 'Retry';
el.retry.classList.remove('d-none');
el.retry.onclick = function () {
el.retry.classList.add('d-none');
el.continue.classList.add('d-none');
el.bar.classList.remove('bg-danger');
el.bar.classList.add('progress-bar-striped', 'progress-bar-animated');
run();
};
if (CFG.returnUrl) {
showBtn(el.continue, L.continue || 'Continue without backup', CFG.returnUrl);
}
showBtn(el.dashboard, L.dashboard || 'Back to dashboard', CFG.dashboardUrl);
}
async function run() {
if (running) { return; }
running = true;
el.actions.classList.add('d-none');
setBar(0, true);
setPhase('');
setStatus(L.starting || 'Starting backup…');
try {
var init = await post({ task: 'ajax.init', profile_id: CFG.profileId, description: CFG.description });
if (!init || init.error || !init.session_id) {
throw new Error((init && init.message) || 'Could not start backup');
}
setBar(init.progress, true);
setPhase(init.phase || '');
setStatus(init.message || (L.running || 'Backing up…'));
var done = false;
while (!done) {
var step = await post({ task: 'ajax.step', session_id: init.session_id });
if (!step || step.error) {
throw new Error((step && step.message) || 'Backup step failed');
}
setBar(step.progress, true);
setPhase(step.phase || '');
setStatus(step.message || '');
done = step.done || false;
}
running = false;
onComplete();
} catch (err) {
onError(err && err.message ? err.message : String(err));
}
}
/* Warn before leaving while a backup is mid-flight. */
window.addEventListener('beforeunload', function (e) {
if (running) { e.preventDefault(); e.returnValue = L.leaveWarn || ''; }
});
if (CFG.autostart) {
document.addEventListener('DOMContentLoaded', run);
}
})();
</script>
@@ -1,261 +0,0 @@
/**
* MokoSuiteBackup — pre-update backup notice + live-progress modal.
*
* Injected by plg_system_mokosuitebackup on the Joomla core-update
* (com_joomlaupdate) and extensions-update (com_installer&view=update) pages.
*
* Why a client-side modal: the server-side onExtensionBeforeUpdate backup runs
* synchronously mid-request and cannot drive a browser modal. This offers an
* on-demand "Back up now" button that runs the same stepped backup the
* dashboard uses (ajax.init then a loop of ajax.step) and shows live progress.
* On success it pings ajax.preupdateAck so the imminent server-side pre-update
* backup is skipped (no duplicate backup) when the admin clicks Update.
*
* Config comes from Joomla.getOptions('plg_system_mokosuitebackup.preupdate').
*/
(function () {
'use strict';
var cfg = (window.Joomla && Joomla.getOptions)
? Joomla.getOptions('plg_system_mokosuitebackup.preupdate', null)
: null;
if (!cfg || !cfg.ajaxUrl || !cfg.token) {
return;
}
var L = cfg.labels || {};
var running = false;
var backedUp = false;
document.addEventListener('DOMContentLoaded', function () {
injectNotice();
});
if (cfg.autoIntercept) {
setupInterception();
}
/* ── Phase 2: auto-run on the Update click ──────────────────────────────
* Wrap window.Joomla.submitbutton so clicking the toolbar Update button
* first runs the backup modal, then continues the original update once the
* backup succeeds. submitbutton is synchronous, so we can't pause it — we
* swallow the update task, run the async backup, and re-issue the original
* task ourselves on success. The notice's "Back up now" button remains a
* fallback for any flow that doesn't route through submitbutton. */
function setupInterception() {
if (!wrapSubmit()) {
document.addEventListener('DOMContentLoaded', wrapSubmit);
}
}
function wrapSubmit() {
var J = window.Joomla;
if (!J || typeof J.submitbutton !== 'function' || J.submitbutton.__msbWrapped) {
return !!(J && J.submitbutton && J.submitbutton.__msbWrapped);
}
var original = J.submitbutton;
var wrapped = function (task) {
if (!backedUp && !running && isUpdateTask(task)) {
var args = arguments;
runBackup().then(function (ok) {
if (ok) {
original.apply(window.Joomla, args);
}
});
return;
}
return original.apply(window.Joomla, arguments);
};
wrapped.__msbWrapped = true;
J.submitbutton = wrapped;
return true;
}
/* Only the actual "apply the update" tasks — never Find Updates / Clear
* Cache (update.find / update.purge) which also start with "update". */
function isUpdateTask(task) {
return task === 'update.update' || task === 'update.install';
}
function injectNotice() {
var host = document.querySelector('main') || document.querySelector('#content') || document.body;
if (!host || document.getElementById('msb-preupdate-notice')) {
return;
}
var bar = document.createElement('div');
bar.id = 'msb-preupdate-notice';
bar.setAttribute('role', 'status');
bar.style.cssText = 'display:flex;align-items:center;gap:1rem;flex-wrap:wrap;'
+ 'margin:0 0 1rem 0;padding:.75rem 1rem;border:1px solid #f0c36d;'
+ 'background:#fcf8e3;border-radius:.35rem;color:#8a6d3b;font-size:.95rem;';
var text = document.createElement('span');
text.style.cssText = 'flex:1 1 auto;';
text.textContent = L.notice || 'A full-site backup is recommended before you update.';
var btn = document.createElement('button');
btn.type = 'button';
btn.id = 'msb-preupdate-run';
btn.className = 'btn btn-warning btn-sm';
btn.textContent = L.backupNow || 'Back up now';
btn.addEventListener('click', runBackup);
var dismiss = document.createElement('button');
dismiss.type = 'button';
dismiss.className = 'btn btn-link btn-sm';
dismiss.style.cssText = 'color:#8a6d3b;';
dismiss.textContent = L.dismiss || 'Dismiss';
dismiss.addEventListener('click', function () { bar.remove(); });
bar.appendChild(text);
bar.appendChild(btn);
bar.appendChild(dismiss);
host.insertBefore(bar, host.firstChild);
}
/* ── The live-progress overlay (dependency-free, mirrors the dashboard) ── */
function buildOverlay() {
var overlay = document.createElement('div');
overlay.id = 'msb-preupdate-overlay';
overlay.style.cssText = 'position:fixed;inset:0;z-index:10000;display:flex;'
+ 'align-items:center;justify-content:center;background:rgba(0,0,0,.5);';
var box = document.createElement('div');
box.style.cssText = 'width:min(480px,92vw);background:#fff;border-radius:.5rem;'
+ 'padding:1.5rem;box-shadow:0 10px 40px rgba(0,0,0,.3);';
var title = document.createElement('h3');
title.id = 'msb-pu-title';
title.style.cssText = 'margin:0 0 1rem 0;font-size:1.15rem;';
title.textContent = L.backingUp || 'Backing up…';
var track = document.createElement('div');
track.style.cssText = 'height:1.25rem;background:#e9ecef;border-radius:.35rem;overflow:hidden;';
var barfill = document.createElement('div');
barfill.id = 'msb-pu-bar';
barfill.style.cssText = 'height:100%;width:0;background:#198754;transition:width .3s ease;';
track.appendChild(barfill);
var status = document.createElement('div');
status.id = 'msb-pu-status';
status.style.cssText = 'margin-top:.75rem;font-size:.9rem;color:#555;';
status.textContent = L.starting || 'Starting backup…';
box.appendChild(title);
box.appendChild(track);
box.appendChild(status);
overlay.appendChild(box);
document.body.appendChild(overlay);
return { overlay: overlay, title: title, bar: barfill, status: status };
}
function setProgress(ui, progress, message) {
var pct = Math.max(0, Math.min(100, parseInt(progress, 10) || 0));
ui.bar.style.width = pct + '%';
if (message) {
ui.status.textContent = message;
}
}
function post(params) {
var body = new URLSearchParams();
body.append(cfg.token, '1');
Object.keys(params).forEach(function (k) {
body.append(k, params[k]);
});
return fetch(cfg.ajaxUrl, {
method: 'POST',
body: body,
headers: { 'X-Requested-With': 'XMLHttpRequest' }
}).then(function (r) { return r.json(); });
}
async function runBackup() {
if (running) {
return;
}
running = true;
var runBtn = document.getElementById('msb-preupdate-run');
if (runBtn) {
runBtn.disabled = true;
}
var ui = buildOverlay();
var guard = function (e) { e.preventDefault(); e.returnValue = ''; };
window.addEventListener('beforeunload', guard);
try {
var init = await post({ task: 'ajax.init', profile_id: cfg.profileId });
if (!init || init.error || !init.session_id) {
throw new Error((init && init.message) || 'Could not start backup');
}
setProgress(ui, init.progress, init.message);
var done = false;
while (!done) {
var step = await post({ task: 'ajax.step', session_id: init.session_id });
if (!step || step.error) {
throw new Error((step && step.message) || 'Backup step failed');
}
setProgress(ui, step.progress, step.message);
done = step.done || false;
}
/* Tell the server the pre-update backup is satisfied so the
synchronous onExtensionBeforeUpdate backup is skipped. */
try { await post({ task: 'ajax.preupdateAck' }); } catch (ignore) {}
backedUp = true;
ui.title.textContent = L.complete || 'Backup complete — safe to update.';
setProgress(ui, 100, '');
var notice = document.getElementById('msb-preupdate-notice');
if (notice) {
notice.style.background = '#d1e7dd';
notice.style.borderColor = '#badbcc';
notice.style.color = '#0f5132';
}
setTimeout(function () { ui.overlay.remove(); }, 1500);
return true;
} catch (err) {
ui.title.textContent = (L.failed || 'Backup failed') + ': ' + err.message;
ui.bar.style.background = '#dc3545';
if (runBtn) {
runBtn.disabled = false;
}
return false;
} finally {
running = false;
window.removeEventListener('beforeunload', guard);
}
}
})();
@@ -29,10 +29,6 @@
<language tag="en-GB">language/en-GB/plg_system_mokosuitebackup.sys.ini</language>
</languages>
<media destination="plg_system_mokosuitebackup" folder="media">
<folder>js</folder>
</media>
<config>
<fields name="params">
<fieldset name="basic">
@@ -13,11 +13,8 @@ namespace Joomla\Plugin\System\MokoSuiteBackup\Extension;
defined('_JEXEC') or die;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Document\HtmlDocument;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\RetentionManager;
@@ -34,7 +31,6 @@ final class MokoSuiteBackup extends CMSPlugin implements SubscriberInterface
return [
'onAfterInitialise' => 'onAfterInitialise',
'onAfterRoute' => 'onAfterRoute',
'onBeforeCompileHead' => 'onBeforeCompileHead',
'onExtensionBeforeUpdate' => 'onExtensionBeforeUpdate',
'onExtensionBeforeUninstall' => 'onExtensionBeforeUninstall',
];
@@ -127,6 +123,10 @@ final class MokoSuiteBackup extends CMSPlugin implements SubscriberInterface
return;
}
// Pre-update: send Joomla core-update installs through the full-screen
// backup page BEFORE the update runs (may not return from here).
$this->maybeRedirectForUpdate();
if (!(int) $this->params->get('auto_cleanup', 1)) {
return;
}
@@ -146,74 +146,79 @@ final class MokoSuiteBackup extends CMSPlugin implements SubscriberInterface
}
/**
* Inject the pre-update backup notice + live-progress modal on the admin
* update pages (com_joomlaupdate and com_installer's update view).
* Send a Joomla core-update install through the full-screen backup page
* BEFORE the update runs (Akeeba-style), so no backup runs synchronously
* inside the update request (which is what white-screened large sites).
*
* The server-side onExtensionBeforeUpdate backup runs synchronously and
* cannot drive a browser modal, so this offers an on-demand "Back up now"
* button that runs the same stepped backup as the dashboard and shows live
* progress. On success the client pings ajax.preupdateAck, which arms the
* same throttle key runPreActionBackup() checks — so the subsequent server
* update does not run a duplicate backup.
* Flow: user clicks "Install the update" (com_joomlaupdate&task=update.install)
* → we redirect to com_mokosuitebackup&view=runbackup (full screen) with a
* returnurl back to update.install&is_backed_up=1 → the backup runs on its
* own page with real progress → on completion the browser returns to
* update.install, we arm the throttle so onExtensionBeforeUpdate doesn't
* duplicate the backup, and the update proceeds.
*/
public function onBeforeCompileHead(Event $event): void
private function maybeRedirectForUpdate(): void
{
$app = $this->getApplication();
if (!$app->isClient('administrator')) {
return;
}
$input = $app->getInput();
$option = $input->getCmd('option', '');
$view = $input->getCmd('view', '');
$onUpdatePage = $option === 'com_joomlaupdate'
|| ($option === 'com_installer' && $view === 'update');
if (!$onUpdatePage) {
return;
}
$params = ComponentHelper::getParams('com_mokosuitebackup');
// Respect the notice toggle and the pre-update backup feature flag.
if (!(int) $params->get('show_update_notice', 1) || !(int) $params->get('backup_before_update', 0)) {
if (!(int) $params->get('backup_before_update', 0)) {
return;
}
// Already backed up this session (within the throttle window)? Stay quiet.
$lastRun = (int) Factory::getSession()->get('mokosuitebackup.preaction_backup_before_update', 0);
$app = $this->getApplication();
$input = $app->getInput();
if ($input->getCmd('option', '') !== 'com_joomlaupdate'
|| $input->getCmd('task', '') !== 'update.install') {
return;
}
$session = Factory::getSession();
// Returned from the backup screen: arm the throttle so the synchronous
// onExtensionBeforeUpdate backup doesn't run again, then let it proceed.
if ((int) $input->getInt('is_backed_up', 0) === 1) {
$session->set('mokosuitebackup.preaction_backup_before_update', time());
return;
}
// Backed up recently already — let the update proceed.
$lastRun = (int) $session->get('mokosuitebackup.preaction_backup_before_update', 0);
if ($lastRun > 0 && (time() - $lastRun) < 600) {
return;
}
$doc = $app->getDocument();
// Super Users only.
$user = $app->getIdentity();
if (!$doc instanceof HtmlDocument) {
if (!$user || $user->guest || !$user->authorise('core.admin')) {
return;
}
$doc->getWebAssetManager()->useScript('core');
$token = Session::getFormToken();
$profileId = (int) $params->get('default_profile', 1);
$doc->addScriptOptions('plg_system_mokosuitebackup.preupdate', [
'ajaxUrl' => Route::_('index.php?option=com_mokosuitebackup&format=json', false),
'token' => Session::getFormToken(),
'profileId' => (int) $params->get('default_profile', 1),
'autoIntercept' => (bool) (int) $params->get('preupdate_auto_intercept', 0),
'labels' => [
'notice' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_UPDATE_NOTICE'),
'backupNow' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_BACKUP_NOW'),
'dismiss' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_DISMISS'),
'backingUp' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_BACKING_UP'),
'starting' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_BACKUP_STARTING'),
'complete' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_BACKUP_COMPLETE'),
'failed' => Text::_('PLG_SYSTEM_MOKOJOOMBACKUP_BACKUP_FAILED'),
],
]);
// Where to send the browser after the backup: back to the update install.
$returnUri = new Uri(Uri::base() . 'index.php');
$returnUri->setVar('option', 'com_joomlaupdate');
$returnUri->setVar('task', 'update.install');
$returnUri->setVar('is_backed_up', '1');
$returnUri->setVar($token, '1');
$doc->addScript(Uri::root(true) . '/media/plg_system_mokosuitebackup/js/update-backup.js', [], ['defer' => true]);
// The full-screen backup page (chromeless via tmpl=component).
$redirect = new Uri(Uri::base() . 'index.php');
$redirect->setVar('option', 'com_mokosuitebackup');
$redirect->setVar('view', 'runbackup');
$redirect->setVar('tmpl', 'component');
$redirect->setVar('autostart', '1');
$redirect->setVar('profile_id', (string) $profileId);
$redirect->setVar('description', 'Pre-update backup');
$redirect->setVar('returnurl', base64_encode($returnUri->toString()));
$redirect->setVar($token, '1');
$app->redirect($redirect->toString());
}
/**