Merge pull request 'feat(#237): snapshot transfer + master→slave injection (all conflict modes)' (#241) from feature/237-snapshot-transfer 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 49s

This commit was merged in pull request #241.
This commit is contained in:
2026-07-10 21:07:31 +00:00
23 changed files with 909 additions and 16 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
# FILE INFORMATION
# DEFGROUP: MokoGitea.Workflow
# INGROUP: mokocli.Automation
# VERSION: 02.58.21
# VERSION: 02.58.23
# BRIEF: Auto-create feature branch when an issue is opened
name: "Universal: Issue Branch"
+1
View File
@@ -3,6 +3,7 @@
## [Unreleased]
### Added
- **Snapshot transfer + master→slave injection (#237):** download a content snapshot as a portable **`.msbsnap`** file (zip of `manifest.json` + `snapshot.json` + a sha256 integrity check); **import** one on another site via a new Import button on the Snapshots page (materialises a local snapshot record you can then restore); and a **direct injection API**`POST /api/index.php/v1/mokosuitebackup/snapshot/inject` — so a **master** site can push a snapshot straight into a **slave**'s Web Services API. Two conflict modes ship now: **overwrite** (replace matching items by ID — master wins) and **create** (skip existing, add only new), selectable per inject call or defaulted in **Options → Snapshot Transfer**. A receiving site must opt in via the new *Allow Snapshot Injection* setting. A third **duplicate** mode inserts everything as brand-new records with **remapped IDs** (articles, categories, modules — plus their tags, custom-field values and featured flags) using Joomla's Table API so assets/UCM/nested-sets stay valid; each item is inserted defensively (a bad item is skipped and logged, never fatal).
- Full-screen backup now also fronts **extension updates and uninstalls** (Extensions → Update / Manage), not just core Joomla updates. Because `com_installer`'s `update.update` / `manage.remove` are POST actions (CSRF token + a checked `cid[]` list) that a server-side redirect can't cleanly resume, this is done client-side: the toolbar Update/Uninstall click is intercepted, the selection is captured, the full-screen backup runs, and on return the original selection is restored and the real POST form is re-submitted. Gated by `backup_before_update` / `backup_before_uninstall`, super-user only, and skipped if a backup already ran this session.
- Manual **"Backup Now"** completion now offers a **View backup record** button (links straight to the record that was just created). It appears only for manual backups — the pre-update / pre-uninstall flow hands control back to Joomla instead.
- **Full-screen backup screen** (`view=runbackup`) for both pre-update and manual backups, modelled on Akeeba's Backup-on-Update — replaces the earlier popup-modal approach. Clicking Joomla's **Install the update** now redirects (server-side, Akeeba-style) to a dedicated full-page backup screen that runs the stepped backup with a real progress bar and then **automatically continues the update** via a validated `returnurl` (flagged `is_backed_up=1` so the backup isn't repeated). Crucially, **no backup runs synchronously inside the update request** — which is what white-screened large sites. The dashboard **Backup Now** now opens the same full-screen screen instead of an inline modal. (#196)
+1 -1
View File
@@ -23,7 +23,7 @@ DEFGROUP: Template-Joomla
INGROUP: Template-Joomla.Documentation
REPO: https://git.mokoconsulting.tech/MokoConsulting/Template-Joomla
PATH: /SECURITY.md
VERSION: 02.58.21
VERSION: 02.58.23
BRIEF: Security vulnerability reporting and handling policy
-->
@@ -21,9 +21,11 @@ namespace Joomla\Component\MokoSuiteBackup\Api\Controller;
defined('_JEXEC') or die;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Controller\ApiController;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotEngine;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotPortable;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotRestoreEngine;
class SnapshotsController extends ApiController
@@ -159,11 +161,11 @@ class SnapshotsController extends ApiController
$data = json_decode($this->input->json->getRaw(), true) ?: [];
$mode = $data['mode'] ?? 'replace';
$mode = (string) ($data['mode'] ?? 'replace');
$contentTypes = $data['content_types'] ?? [];
// Enforce valid restore mode
if (!in_array($mode, ['replace', 'merge'], true)) {
// Accept the external mode names too; the engine normalises + validates.
if (!in_array($mode, ['replace', 'merge', 'overwrite', 'create', 'duplicate'], true)) {
$mode = 'replace';
}
@@ -183,6 +185,86 @@ class SnapshotsController extends ApiController
return $this;
}
/**
* Inject a snapshot payload directly into this site (master → slave).
* POST /api/index.php/v1/mokosuitebackup/snapshot/inject
*
* Body: {
* "snapshot": { version, content_types, tables }, // the payload (required)
* "mode": "overwrite" | "create" | "duplicate", // optional; defaults to the site's snapshot_inject_mode
* "content_types": [ ... ], // optional filter
* "description": "..." // optional
* }
*/
public function inject(): static
{
if (!$this->app->getIdentity()->authorise('mokosuitebackup.snapshot.manage', 'com_mokosuitebackup')) {
$this->app->setHeader('status', 403);
echo json_encode(['errors' => [['title' => 'Access denied']]]);
$this->app->close();
return $this;
}
$params = ComponentHelper::getParams('com_mokosuitebackup');
// The receiving (slave) site must explicitly allow injection.
if (!(int) $params->get('snapshot_allow_inject', 0)) {
$this->app->setHeader('status', 403);
echo json_encode(['errors' => [['title' => 'Snapshot injection is disabled on this site']]]);
$this->app->close();
return $this;
}
$body = json_decode($this->input->json->getRaw(), true) ?: [];
$snapshot = $body['snapshot'] ?? null;
if (!is_array($snapshot)) {
$this->app->setHeader('status', 400);
echo json_encode(['errors' => [['title' => 'Missing "snapshot" payload']]]);
$this->app->close();
return $this;
}
// Explicit mode wins; otherwise the site default from Options.
$mode = (string) ($body['mode'] ?? $params->get('snapshot_inject_mode', 'overwrite'));
$contentTypes = $body['content_types'] ?? [];
$description = (string) ($body['description'] ?? 'Injected snapshot');
// Materialise a local record from the payload, then restore it.
$ingest = SnapshotPortable::ingestData($snapshot, $description);
if (empty($ingest['success'])) {
$this->app->setHeader('status', 422);
echo json_encode(['errors' => [['title' => $ingest['message']]]]);
$this->app->close();
return $this;
}
$engine = new SnapshotRestoreEngine();
$result = $engine->restore((int) $ingest['id'], $mode, $contentTypes);
$result['snapshot_id'] = (int) $ingest['id'];
if (!empty($ingest['warnings'])) {
$result['warnings'] = array_merge($result['warnings'] ?? [], $ingest['warnings']);
}
if ($result['success']) {
$this->app->setHeader('status', 200);
echo json_encode(['data' => $result]);
} else {
$this->app->setHeader('status', 500);
echo json_encode(['errors' => [['title' => $result['message']]], 'data' => $result]);
}
$this->app->close();
return $this;
}
/**
* Delete a snapshot record and its data file (DELETE /api/index.php/v1/mokosuitebackup/snapshot/:id)
*/
@@ -206,6 +206,31 @@
/>
</fieldset>
<fieldset name="snapshot_transfer" label="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_TRANSFER">
<field
name="snapshot_inject_mode"
type="list"
label="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_INJECT_MODE"
description="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_INJECT_MODE_DESC"
default="overwrite"
>
<option value="overwrite">COM_MOKOJOOMBACKUP_SNAPSHOT_MODE_OVERWRITE</option>
<option value="create">COM_MOKOJOOMBACKUP_SNAPSHOT_MODE_CREATE</option>
<option value="duplicate">COM_MOKOJOOMBACKUP_SNAPSHOT_MODE_DUPLICATE</option>
</field>
<field
name="snapshot_allow_inject"
type="radio"
label="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_ALLOW_INJECT"
description="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_ALLOW_INJECT_DESC"
default="0"
class="btn-group"
>
<option value="1">JYES</option>
<option value="0">JNO</option>
</field>
</fieldset>
<fieldset name="notifications" label="COM_MOKOJOOMBACKUP_CONFIG_NOTIFICATIONS">
<field
name="notify_email"
@@ -495,6 +495,22 @@ COM_MOKOJOOMBACKUP_WEBCRON_IP_NONE="No IP restrictions — any IP can trigger we
COM_MOKOJOOMBACKUP_WEBCRON_IP_PLACEHOLDER="Enter IP address"
COM_MOKOJOOMBACKUP_WEBCRON_IP_ADD="Add"
; Snapshot transfer / injection (#237)
COM_MOKOJOOMBACKUP_SNAPSHOT_DOWNLOAD="Download portable snapshot (.msbsnap)"
COM_MOKOJOOMBACKUP_SNAPSHOT_NOT_FOUND="Snapshot not found."
COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT="Import Snapshot"
COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT_DESC="Upload a .msbsnap file exported from another site. It is added as a snapshot here, which you can then restore."
COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT_FILE="Snapshot file (.msbsnap)"
COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT_NO_FILE="No snapshot file was uploaded, or the upload failed."
COM_MOKOJOOMBACKUP_SNAPSHOT_MODE_OVERWRITE="Overwrite — replace matching items (master wins)"
COM_MOKOJOOMBACKUP_SNAPSHOT_MODE_CREATE="Create — skip existing, add only new items"
COM_MOKOJOOMBACKUP_SNAPSHOT_MODE_DUPLICATE="Duplicate — add as new copies (remapped IDs)"
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_TRANSFER="Snapshot Transfer / Injection"
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_INJECT_MODE="Default Conflict Mode"
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_INJECT_MODE_DESC="Default mode used when a snapshot is injected via the API without an explicit mode."
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_ALLOW_INJECT="Allow Snapshot Injection (API)"
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_ALLOW_INJECT_DESC="Allow a remote master site to inject snapshots directly into this site via the Web Services API (POST /snapshot/inject). Off by default; requires an API token with snapshot-manage permission."
; Snapshot browse / detail view
COM_MOKOJOOMBACKUP_SNAPSHOT_BROWSE="Browse Snapshot"
COM_MOKOJOOMBACKUP_SNAPSHOT_TAB_ARTICLES="Articles"
@@ -17,7 +17,7 @@
display label there.
-->
<name>MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-02</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -0,0 +1 @@
/* 02.58.22 — no schema changes */
@@ -0,0 +1 @@
/* 02.58.23 — no schema changes */
@@ -18,6 +18,7 @@ use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotEngine;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotPortable;
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotRestoreEngine;
class SnapshotsController extends AdminController
@@ -29,6 +30,95 @@ class SnapshotsController extends AdminController
return parent::getModel($name, $prefix, $config);
}
/**
* Download a snapshot as a portable .msbsnap file (manifest + payload + checksum).
*/
public function downloadPortable(): void
{
$this->checkToken('get');
if (!$this->app->getIdentity()->authorise('mokosuitebackup.snapshot.manage', 'com_mokosuitebackup')) {
$this->setMessage(Text::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 'error');
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
return;
}
$id = $this->input->getInt('id', 0);
$item = $id ? $this->getModel('Snapshot')->getItem($id) : null;
if (!$item || empty($item->id)) {
$this->setMessage(Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_NOT_FOUND'), 'error');
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
return;
}
try {
$file = SnapshotPortable::package($item);
} catch (\Throwable $e) {
$this->setMessage($e->getMessage(), 'error');
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
return;
}
$name = SnapshotPortable::filename($item);
while (@ob_end_clean()) {
// flush buffers
}
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($name));
header('Content-Length: ' . filesize($file));
header('Cache-Control: no-cache, must-revalidate');
readfile($file);
@unlink($file);
$this->app->close();
}
/**
* Import an uploaded .msbsnap file — materialise a local snapshot record.
*/
public function import(): void
{
$this->checkToken();
if (!$this->app->getIdentity()->authorise('mokosuitebackup.snapshot.manage', 'com_mokosuitebackup')) {
$this->setMessage(Text::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 'error');
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
return;
}
$file = $this->input->files->get('msbsnap_file', null, 'raw');
if (!is_array($file) || empty($file['tmp_name']) || (int) ($file['error'] ?? 1) !== 0
|| !is_uploaded_file($file['tmp_name'])) {
$this->setMessage(Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT_NO_FILE'), 'error');
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
return;
}
$result = SnapshotPortable::ingestZip($file['tmp_name']);
if (!empty($result['success'])) {
foreach ($result['warnings'] ?? [] as $warning) {
$this->app->enqueueMessage($warning, 'warning');
}
$this->setMessage($result['message']);
} else {
$this->setMessage($result['message'], 'error');
}
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
}
/**
* Create a new content snapshot.
*/
@@ -0,0 +1,285 @@
<?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
*
* Portable snapshot transfer format (.msbsnap).
*
* A .msbsnap is a zip containing:
* - manifest.json — format/version, generator, source (host/Joomla/prefix),
* content summary, and a sha256 of the payload.
* - snapshot.json — the snapshot's content data (verbatim, same shape the
* snapshot engine writes: {version, content_types, tables}).
*
* package() builds a .msbsnap for an existing snapshot record (for download).
* ingestZip() validates an uploaded .msbsnap and materialises a local snapshot
* record from it (so the normal restore UX can act on it).
* ingestData() materialises a record from an already-parsed data array (used by
* the master→slave injection API, which receives the payload inline).
*/
namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\Component\MokoSuiteBackup\Administrator\Utility\BackupDirectory;
final class SnapshotPortable
{
public const FORMAT = 'msbsnap';
public const FORMAT_VERSION = 1;
public const MANIFEST_NAME = 'manifest.json';
public const PAYLOAD_NAME = 'snapshot.json';
/**
* Build a portable .msbsnap zip for a snapshot record.
*
* @param object $snapshot Row from #__mokosuitebackup_snapshots (needs
* data_file, description, content_types, *_count)
*
* @return string Absolute path to a temp .msbsnap file (caller unlinks it)
*
* @throws \RuntimeException
*/
public static function package(object $snapshot): string
{
$dataFile = (string) ($snapshot->data_file ?? '');
if ($dataFile === '' || !is_file($dataFile) || !is_readable($dataFile)) {
throw new \RuntimeException('Snapshot data file is missing or unreadable.');
}
$payload = file_get_contents($dataFile);
if ($payload === false) {
throw new \RuntimeException('Could not read snapshot data file.');
}
$manifest = [
'format' => self::FORMAT,
'format_version' => self::FORMAT_VERSION,
'generator' => 'MokoSuiteBackup',
'created' => Factory::getDate()->toISO8601(),
'source' => [
'host' => self::siteHost(),
'joomla_version' => JVERSION,
'db_prefix' => Factory::getDbo()->getPrefix(),
],
'snapshot' => [
'description' => (string) ($snapshot->description ?? ''),
'content_types' => json_decode((string) ($snapshot->content_types ?? '[]'), true) ?: [],
'articles_count' => (int) ($snapshot->articles_count ?? 0),
'categories_count' => (int) ($snapshot->categories_count ?? 0),
'modules_count' => (int) ($snapshot->modules_count ?? 0),
'created' => (string) ($snapshot->created ?? ''),
],
'payload' => [
'file' => self::PAYLOAD_NAME,
'sha256' => hash('sha256', $payload),
'size' => strlen($payload),
],
];
$tmp = tempnam(sys_get_temp_dir(), 'msbsnap_');
if ($tmp === false) {
throw new \RuntimeException('Could not create a temporary file.');
}
$zip = new \ZipArchive();
if ($zip->open($tmp, \ZipArchive::OVERWRITE) !== true) {
@unlink($tmp);
throw new \RuntimeException('Could not create the .msbsnap archive.');
}
$zip->addFromString(self::MANIFEST_NAME, json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
$zip->addFromString(self::PAYLOAD_NAME, $payload);
$zip->close();
return $tmp;
}
/**
* A friendly download filename for a snapshot's portable file.
*/
public static function filename(object $snapshot): string
{
$id = (int) ($snapshot->id ?? 0);
$date = date('Ymd_His');
return 'snapshot-' . $id . '-' . $date . '.msbsnap';
}
/**
* Ingest an uploaded .msbsnap file: validate it and materialise a local
* snapshot record so the normal restore UX can act on it.
*
* @return array{success:bool,message:string,id?:int,warnings?:array}
*/
public static function ingestZip(string $zipPath, string $descriptionPrefix = 'Imported'): array
{
if (!is_file($zipPath) || !is_readable($zipPath)) {
return ['success' => false, 'message' => 'Uploaded file is missing or unreadable.'];
}
$zip = new \ZipArchive();
if ($zip->open($zipPath) !== true) {
return ['success' => false, 'message' => 'Not a valid .msbsnap archive.'];
}
try {
$manifestRaw = $zip->getFromName(self::MANIFEST_NAME);
$payloadRaw = $zip->getFromName(self::PAYLOAD_NAME);
} finally {
$zip->close();
}
if ($manifestRaw === false || $payloadRaw === false) {
return ['success' => false, 'message' => 'Archive is missing its manifest or payload.'];
}
$manifest = json_decode($manifestRaw, true);
if (!is_array($manifest) || ($manifest['format'] ?? '') !== self::FORMAT) {
return ['success' => false, 'message' => 'Unrecognised snapshot file format.'];
}
if ((int) ($manifest['format_version'] ?? 0) > self::FORMAT_VERSION) {
return ['success' => false, 'message' => 'This snapshot file was made by a newer version of MokoSuiteBackup.'];
}
$expected = (string) ($manifest['payload']['sha256'] ?? '');
if ($expected !== '' && !hash_equals($expected, hash('sha256', $payloadRaw))) {
return ['success' => false, 'message' => 'Snapshot payload failed its integrity (checksum) check.'];
}
$data = json_decode($payloadRaw, true);
if (!self::isValidData($data)) {
return ['success' => false, 'message' => 'Snapshot payload is not valid content data.'];
}
$warnings = self::compatWarnings($manifest);
$srcHost = (string) ($manifest['source']['host'] ?? '');
$srcDesc = (string) ($manifest['snapshot']['description'] ?? '');
$descr = trim($descriptionPrefix . ': ' . ($srcDesc !== '' ? $srcDesc : 'snapshot')
. ($srcHost !== '' ? ' (from ' . $srcHost . ')' : ''));
$result = self::ingestData($data, $descr);
if (!empty($warnings) && !empty($result['success'])) {
$result['warnings'] = array_merge($result['warnings'] ?? [], $warnings);
}
return $result;
}
/**
* Materialise a snapshot record from an already-parsed data array.
* Used by the injection API (payload arrives inline, not as a zip).
*
* @return array{success:bool,message:string,id?:int,warnings?:array}
*/
public static function ingestData(array $data, string $description): array
{
if (!self::isValidData($data)) {
return ['success' => false, 'message' => 'Snapshot data is invalid or empty.'];
}
try {
$backupDir = BackupDirectory::getDefaultAbsolute();
BackupDirectory::ensureReady($backupDir);
$filename = 'snapshot_' . date('Ymd_His') . '_imported.json';
$filePath = $backupDir . '/' . $filename;
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if ($json === false || file_put_contents($filePath, $json) === false) {
return ['success' => false, 'message' => 'Could not write the imported snapshot file.'];
}
$tables = $data['tables'] ?? [];
$db = Factory::getDbo();
$record = (object) [
'description' => $description !== '' ? $description : 'Imported snapshot',
'content_types' => json_encode(array_values($data['content_types'] ?? [])),
'status' => 'complete',
'articles_count' => count($tables['#__content'] ?? []),
'categories_count' => count($tables['#__categories'] ?? []),
'modules_count' => count($tables['#__modules'] ?? []),
'data_file' => $filePath,
'data_size' => strlen($json),
'log' => 'Imported ' . Factory::getDate()->toSql(),
'created' => Factory::getDate()->toSql(),
'created_by' => (int) (Factory::getApplication()->getIdentity()->id ?? 0),
];
$db->insertObject('#__mokosuitebackup_snapshots', $record, 'id');
return [
'success' => true,
'message' => 'Snapshot imported (record #' . (int) $record->id . ').',
'id' => (int) $record->id,
'warnings' => [],
];
} catch (\Throwable $e) {
return ['success' => false, 'message' => 'Import failed: ' . $e->getMessage()];
}
}
/**
* Structural check for a snapshot data payload.
*/
private static function isValidData($data): bool
{
return is_array($data)
&& isset($data['tables']) && is_array($data['tables'])
&& isset($data['content_types']) && is_array($data['content_types']);
}
/**
* Best-effort compatibility warnings (non-blocking).
*
* @return string[]
*/
private static function compatWarnings(array $manifest): array
{
$warnings = [];
$srcJoomla = (string) ($manifest['source']['joomla_version'] ?? '');
$srcMajor = $srcJoomla !== '' ? (int) explode('.', $srcJoomla)[0] : 0;
$thisMajor = (int) explode('.', JVERSION)[0];
if ($srcMajor > 0 && $srcMajor !== $thisMajor) {
$warnings[] = 'Snapshot was created on Joomla ' . $srcJoomla . ' but this site is Joomla ' . JVERSION
. ' — content tables may differ; review after restoring.';
}
return $warnings;
}
/**
* The current site's host, for the manifest (best-effort, informational).
*/
private static function siteHost(): string
{
try {
$host = Uri::getInstance(Uri::root())->getHost();
} catch (\Throwable $e) {
$host = '';
}
return $host !== '' ? $host : (string) (Factory::getApplication()->get('sitename', 'site'));
}
}
@@ -59,7 +59,9 @@ class SnapshotRestoreEngine
$this->log('WARNING: Could not increase memory limit to 512M');
}
if (!in_array($mode, ['replace', 'merge'])) {
$mode = $this->normaliseMode($mode);
if (!in_array($mode, ['replace', 'merge', 'create', 'duplicate'], true)) {
return ['success' => false, 'message' => 'Invalid restore mode: ' . $mode];
}
@@ -129,6 +131,9 @@ class SnapshotRestoreEngine
// Build list of tables to restore based on selected types
$tablesToRestore = $this->getTablesToRestore($restoreTypes);
if ($mode === 'duplicate') {
$totalRows = $this->restoreDuplicate($data, $restoreTypes);
} else {
foreach ($tablesToRestore as $abstractTable) {
if (!isset($data['tables'][$abstractTable])) {
$this->log(' Skipping ' . $abstractTable . ' (not in snapshot)');
@@ -140,6 +145,8 @@ class SnapshotRestoreEngine
if ($mode === 'replace') {
$rowCount = $this->restoreReplace($db, $realTable, $abstractTable, $rows);
} elseif ($mode === 'create') {
$rowCount = $this->restoreCreate($db, $realTable, $abstractTable, $rows);
} else {
$rowCount = $this->restoreMerge($db, $realTable, $abstractTable, $rows);
}
@@ -147,6 +154,7 @@ class SnapshotRestoreEngine
$totalRows += $rowCount;
$this->log(' ' . $abstractTable . ': ' . $rowCount . ' rows restored');
}
}
$db->transactionCommit();
@@ -264,6 +272,340 @@ class SnapshotRestoreEngine
return $count;
}
/**
* Create mode: insert only rows that don't already exist; never overwrite.
* Non-destructive — existing content on the target is left untouched. Used
* by master→slave injection when the master must not clobber local edits.
*/
private function restoreCreate(object $db, string $realTable, string $abstractTable, array $rows): int
{
$pk = self::PRIMARY_KEYS[$abstractTable] ?? null;
$count = 0;
foreach ($rows as $row) {
$obj = (object) $row;
if ($pk !== null && isset($row[$pk])) {
$exists = $db->setQuery(
$db->getQuery(true)
->select('COUNT(*)')
->from($db->quoteName($realTable))
->where($db->quoteName($pk) . ' = ' . $db->quote($row[$pk]))
)->loadResult();
if ($exists) {
continue;
}
$db->insertObject($realTable, $obj);
} else {
// Composite-key tables: insert, skip genuine duplicates.
try {
$db->insertObject($realTable, $obj);
} catch (\Exception $e) {
if (str_contains($e->getMessage(), 'Duplicate entry') || $e->getCode() === 1062) {
continue;
}
throw $e;
}
}
$count++;
}
return $count;
}
/**
* Normalise external mode names to the engine's internal modes.
* overwrite→replace, skip/new→create, copy→duplicate; passthrough otherwise.
*/
private function normaliseMode(string $mode): string
{
$map = [
'overwrite' => 'replace',
'replace' => 'replace',
'update' => 'merge',
'merge' => 'merge',
'skip' => 'create',
'new' => 'create',
'create' => 'create',
'copy' => 'duplicate',
'duplicate' => 'duplicate',
];
return $map[strtolower(trim($mode))] ?? strtolower(trim($mode));
}
/**
* Duplicate mode: insert snapshot content as BRAND-NEW records (new IDs),
* leaving existing content untouched. Uses Joomla's Table API so assets,
* UCM entries, category/tag nested-sets and alias uniqueness are handled by
* core. Every item is wrapped in try/catch — a bad item is skipped + logged,
* never fatal — so a partial import degrades gracefully rather than corrupting.
*
* Known limits: workflow stage is left to the article table's default;
* references to content NOT included in the snapshot keep their original IDs.
*
* @return int Number of new records created
*/
private function restoreDuplicate(array $data, array $types): int
{
$app = Factory::getApplication();
$db = Factory::getDbo();
$tables = $data['tables'] ?? [];
$count = 0;
$catMap = [];
$articleMap = [];
$moduleMap = [];
// --- Categories (parents before children so the remap resolves) ---
if (in_array('categories', $types, true) && !empty($tables['#__categories'])) {
$factory = $app->bootComponent('com_categories')->getMVCFactory();
$cats = $tables['#__categories'];
usort($cats, static fn ($a, $b) => ((int) ($a['level'] ?? 0)) <=> ((int) ($b['level'] ?? 0)));
foreach ($cats as $row) {
$oldId = (int) ($row['id'] ?? 0);
$oldParent = (int) ($row['parent_id'] ?? 1);
$newParent = $catMap[$oldParent] ?? ($oldParent > 1 ? $oldParent : 1);
unset($row['id'], $row['asset_id'], $row['lft'], $row['rgt'], $row['level'], $row['path']);
$row['extension'] = 'com_content';
$row['parent_id'] = $newParent;
$row['alias'] = $this->uniqueAlias($db, '#__categories', (string) ($row['alias'] ?? ''), ['extension' => 'com_content']);
try {
$table = $factory->createTable('Category', 'Administrator');
$table->setLocation($newParent, 'last-child');
if ($table->bind($row) && $table->check() && $table->store()) {
$catMap[$oldId] = (int) $table->id;
$count++;
} else {
$this->log(' Category skipped: ' . $table->getError());
}
} catch (\Throwable $e) {
$this->log(' Category "' . ($row['title'] ?? '?') . '" skipped: ' . $e->getMessage());
}
}
}
// --- Articles ---
if (in_array('articles', $types, true) && !empty($tables['#__content'])) {
$factory = $app->bootComponent('com_content')->getMVCFactory();
$featured = [];
foreach ($tables['#__content_frontpage'] ?? [] as $fp) {
$featured[(int) ($fp['content_id'] ?? 0)] = true;
}
$tagTitles = $this->buildArticleTagTitles($tables);
foreach ($tables['#__content'] as $row) {
$oldId = (int) ($row['id'] ?? 0);
$oldCat = (int) ($row['catid'] ?? 0);
unset($row['id'], $row['asset_id']);
if (isset($catMap[$oldCat])) {
$row['catid'] = $catMap[$oldCat];
}
$row['alias'] = $this->uniqueAlias($db, '#__content', (string) ($row['alias'] ?? ''), ['catid' => (int) ($row['catid'] ?? 0)]);
try {
$table = $factory->createTable('Article', 'Administrator');
$tagIds = $this->resolveTagIds($db, $app, $tagTitles[$oldId] ?? []);
if ($tagIds) {
$table->newTags = $tagIds;
}
if ($table->bind($row) && $table->check() && $table->store()) {
$newId = (int) $table->id;
$articleMap[$oldId] = $newId;
$count++;
if (!empty($featured[$oldId])) {
try {
$db->insertObject($db->getPrefix() . 'content_frontpage', (object) ['content_id' => $newId, 'ordering' => 0]);
} catch (\Throwable $e) {
// featured-ordering row is non-critical
}
}
} else {
$this->log(' Article skipped: ' . $table->getError());
}
} catch (\Throwable $e) {
$this->log(' Article "' . ($row['title'] ?? '?') . '" skipped: ' . $e->getMessage());
}
}
// Custom-field values for the duplicated articles.
foreach ($tables['#__fields_values'] ?? [] as $fv) {
$oldItem = (int) ($fv['item_id'] ?? 0);
if (!isset($articleMap[$oldItem])) {
continue;
}
$fv['item_id'] = (string) $articleMap[$oldItem];
try {
$db->insertObject($db->getPrefix() . 'fields_values', (object) $fv);
} catch (\Throwable $e) {
// duplicate/invalid field value — skip
}
}
}
// --- Modules ---
if (in_array('modules', $types, true) && !empty($tables['#__modules'])) {
$factory = $app->bootComponent('com_modules')->getMVCFactory();
foreach ($tables['#__modules'] as $row) {
$oldId = (int) ($row['id'] ?? 0);
unset($row['id'], $row['asset_id']);
try {
$table = $factory->createTable('Module', 'Administrator');
if ($table->bind($row) && $table->check() && $table->store()) {
$moduleMap[$oldId] = (int) $table->id;
$count++;
} else {
$this->log(' Module skipped: ' . $table->getError());
}
} catch (\Throwable $e) {
$this->log(' Module "' . ($row['title'] ?? '?') . '" skipped: ' . $e->getMessage());
}
}
foreach ($tables['#__modules_menu'] ?? [] as $mm) {
$oldMod = (int) ($mm['moduleid'] ?? 0);
if (!isset($moduleMap[$oldMod])) {
continue;
}
try {
$db->insertObject($db->getPrefix() . 'modules_menu', (object) ['moduleid' => $moduleMap[$oldMod], 'menuid' => (int) ($mm['menuid'] ?? 0)]);
} catch (\Throwable $e) {
// duplicate assignment — skip
}
}
}
$this->log('Duplicated ' . $count . ' new records (categories: ' . count($catMap) . ', articles: ' . count($articleMap) . ', modules: ' . count($moduleMap) . ')');
return $count;
}
/**
* Make an alias unique within a scope by appending -2, -3, … if needed.
*/
private function uniqueAlias(object $db, string $abstractTable, string $alias, array $scope): string
{
$alias = $alias !== '' ? $alias : 'item';
$table = str_replace('#__', $db->getPrefix(), $abstractTable);
$base = $alias;
$n = 1;
while (true) {
$query = $db->getQuery(true)
->select('COUNT(*)')
->from($db->quoteName($table))
->where($db->quoteName('alias') . ' = ' . $db->quote($alias));
foreach ($scope as $col => $val) {
$query->where($db->quoteName($col) . ' = ' . $db->quote($val));
}
if ((int) $db->setQuery($query)->loadResult() === 0) {
return $alias;
}
$n++;
$alias = $base . '-' . $n;
if ($n > 100) {
return $base . '-' . substr(md5((string) mt_rand()), 0, 6);
}
}
}
/**
* Map old article id → its tag titles, from the snapshot's tag map + tags.
*
* @return array<int,string[]>
*/
private function buildArticleTagTitles(array $tables): array
{
$tagTitle = [];
foreach ($tables['#__tags'] ?? [] as $tag) {
$tagTitle[(int) ($tag['id'] ?? 0)] = (string) ($tag['title'] ?? '');
}
$byArticle = [];
foreach ($tables['#__contentitem_tag_map'] ?? [] as $map) {
if (strpos((string) ($map['type_alias'] ?? ''), 'com_content.article') !== 0) {
continue;
}
$articleId = (int) ($map['content_item_id'] ?? 0);
$title = $tagTitle[(int) ($map['tag_id'] ?? 0)] ?? '';
if ($articleId && $title !== '') {
$byArticle[$articleId][] = $title;
}
}
return $byArticle;
}
/**
* Resolve tag titles to target tag IDs, creating any that don't exist.
*
* @return int[]
*/
private function resolveTagIds(object $db, object $app, array $titles): array
{
$ids = [];
foreach (array_unique($titles) as $title) {
try {
$existing = $db->setQuery(
$db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__tags'))
->where($db->quoteName('title') . ' = ' . $db->quote($title))
)->loadResult();
if ($existing) {
$ids[] = (int) $existing;
continue;
}
$table = $app->bootComponent('com_tags')->getMVCFactory()->createTable('Tag', 'Administrator');
$table->setLocation(1, 'last-child');
if ($table->bind(['title' => $title, 'alias' => '', 'published' => 1, 'parent_id' => 1])
&& $table->check() && $table->store()) {
$ids[] = (int) $table->id;
}
} catch (\Throwable $e) {
// tag resolution is best-effort
}
}
return $ids;
}
/**
* Delete rows from a table, scoping to relevant content only.
*
@@ -27,6 +27,14 @@ $listDirn = $this->escape($this->state->get('list.direction'));
<div class="row">
<div class="col-md-12">
<div id="j-main-container" class="j-main-container">
<?php if ($canManage) : ?>
<div class="mb-3">
<button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#mb-snapshot-import-modal">
<span class="icon-upload" aria-hidden="true"></span>
<?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT'); ?>
</button>
</div>
<?php endif; ?>
<?php if (empty($this->items)) : ?>
<div class="alert alert-info">
@@ -112,6 +120,11 @@ $listDirn = $this->escape($this->state->get('list.direction'));
title="<?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_RESTORE'); ?>">
<span class="icon-upload"></span>
</button>
<a class="btn btn-sm btn-outline-secondary"
href="<?php echo Route::_('index.php?option=com_mokosuitebackup&task=snapshots.downloadPortable&id=' . (int) $item->id . '&' . Session::getFormToken() . '=1'); ?>"
title="<?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_DOWNLOAD'); ?>">
<span class="icon-download"></span>
</a>
<?php endif; ?>
</td>
<td><?php echo (int) $item->id; ?></td>
@@ -131,6 +144,32 @@ $listDirn = $this->escape($this->state->get('list.direction'));
</div>
</form>
<!-- Import Snapshot Modal -->
<div class="modal fade" id="mb-snapshot-import-modal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="<?php echo Route::_('index.php?option=com_mokosuitebackup&task=snapshots.import'); ?>" method="post" enctype="multipart/form-data">
<div class="modal-header">
<h5 class="modal-title"><?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT'); ?></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo Text::_('JCLOSE'); ?>"></button>
</div>
<div class="modal-body">
<p class="text-muted"><?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT_DESC'); ?></p>
<div class="mb-3">
<label for="msbsnap_file" class="form-label"><?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT_FILE'); ?></label>
<input type="file" class="form-control" id="msbsnap_file" name="msbsnap_file" accept=".msbsnap,application/zip,application/octet-stream" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo Text::_('JCANCEL'); ?></button>
<button type="submit" class="btn btn-primary"><?php echo Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_IMPORT'); ?></button>
</div>
<?php echo HTMLHelper::_('form.token'); ?>
</form>
</div>
</div>
</div>
<!-- Create Snapshot Modal -->
<div class="modal fade" id="mb-snapshot-create-modal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
@@ -8,7 +8,7 @@
-->
<extension type="module" client="administrator" method="upgrade">
<name>Module - MokoSuiteBackup - cPanel</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-23</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -7,7 +7,7 @@
-->
<extension type="plugin" group="actionlog" method="upgrade">
<name>Action Log - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-04</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -7,7 +7,7 @@
-->
<extension type="plugin" group="console" method="upgrade">
<name>Console - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-04</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -7,7 +7,7 @@
-->
<extension type="plugin" group="content" method="upgrade">
<name>Content - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-04</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<extension type="plugin" group="quickicon" method="upgrade">
<name>Quick Icon - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-02</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -7,7 +7,7 @@
-->
<extension type="plugin" group="system" method="upgrade">
<name>System - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-02</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -7,7 +7,7 @@
-->
<extension type="plugin" group="task" method="upgrade">
<name>Task - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-02</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -7,7 +7,7 @@
-->
<extension type="plugin" group="webservices" method="upgrade">
<name>Web Services - MokoSuiteBackup</name>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-02</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>
@@ -137,6 +137,17 @@ final class MokoSuiteBackupWebServices extends CMSPlugin implements SubscriberIn
)
);
// Inject a snapshot payload directly — master → slave (POST)
$router->addRoute(
new Route(
['POST'],
'v1/mokosuitebackup/snapshot/inject',
'snapshots.inject',
[],
$defaults
)
);
// Delete a snapshot (DELETE)
$router->addRoute(
new Route(
+1 -1
View File
@@ -8,7 +8,7 @@
<extension type="package" method="upgrade">
<name>Package - MokoSuiteBackup</name>
<packagename>mokosuitebackup</packagename>
<version>02.58.21</version>
<version>02.58.23</version>
<creationDate>2026-06-02</creationDate>
<author>Moko Consulting</author>
<authorEmail>hello@mokoconsulting.tech</authorEmail>