Compare commits
311 Commits
version/01.26.00
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 438a2fdaec | |||
| 27a2008675 | |||
| cd1d3241bd | |||
| e2d88313cf | |||
| 256d79a270 | |||
| d8d5a1e48e | |||
| 330cfa9dc5 | |||
| 8485f24342 | |||
| 51c4db5115 | |||
| fd33c86157 | |||
| ac7673805e | |||
| 428e217b56 | |||
| c0ba29aca8 | |||
| 81a72d466b | |||
| 942b33f9ce | |||
| 60e04cfd0a | |||
| 672b953ef5 | |||
| 1b481f2e2c | |||
| 4a027d6245 | |||
| 8af19f875c | |||
| b56e4060bf | |||
| 9b5d0475f5 | |||
| 53e11fe9ad | |||
| 9757658c34 | |||
| c82378128a | |||
| f95505704a | |||
| 6cdc9b04d0 | |||
| bad73529ae | |||
| 288baf41d3 | |||
| 7d1dcf3e1c | |||
| 2002c1fcad | |||
| 4abe81f916 | |||
| 571b03743f | |||
| 7fc1cad305 | |||
| 03a1dd75c9 | |||
| 02d8312d1b | |||
| c508fcc8d5 | |||
| 3af3708020 | |||
| 3098b7ad40 | |||
| d10bda3321 | |||
| 12214bade1 | |||
| d104b7b936 | |||
| 80110ac111 | |||
| 3bd1f63833 | |||
| 93f0fa0a47 | |||
| ee1de178b1 | |||
| 014d659908 | |||
| 113febad3f | |||
| 18a3a524f2 | |||
| 659fc6e274 | |||
| 89af9fa14c | |||
| d60535ae64 | |||
| b9ef947feb | |||
| e7ab83c5fb | |||
| dc81cd7cc8 | |||
| 268b3d54d7 | |||
| 1cfe7c6c6e | |||
| f0da0c02b4 | |||
| 2f8a65388c | |||
| 9978622960 | |||
| 35e5fc1503 | |||
| 2338ba5197 | |||
| e67eedbc93 | |||
| d812aca832 | |||
| 4315f36c6a | |||
| 10467835ac | |||
| f26d58504e | |||
| 07fb4dcc24 | |||
| 21a4352b3b | |||
| 9d26f59f98 | |||
| 3488434f28 | |||
| f97cd30c95 | |||
| 836d1bc8b7 | |||
| 79b3caa35a | |||
| 6102c8f590 | |||
| 88e53c5698 | |||
| ec1c3486c5 | |||
| 3742477aef | |||
| 1c256bba7a | |||
| cd4dc6efd2 | |||
| 2e6b71ac97 | |||
| 5b4f84bad7 | |||
| 847bb9bd0f | |||
| ebcaf44b63 | |||
| 17b05f9a13 | |||
| bb8e4a258a | |||
| e6d646011a | |||
| 726291995c | |||
| 2ac4923d74 | |||
| adc4935587 | |||
| 8f7b747c59 | |||
| 42b7503d7b | |||
| 9ac8757a8c | |||
| ef3fde1c39 | |||
| 5750e71d15 | |||
| c8e022d46b | |||
| 21f2ba0eff | |||
| 821c4bae11 | |||
| e86c104276 | |||
| af2a1a2dae | |||
| c88b163de0 | |||
| 358a7eb68a | |||
| 898520d1db | |||
| e633d0cc0a | |||
| ff7418721d | |||
| 0b2b885163 | |||
| 6c47838b30 | |||
| 0f95cb6e9f | |||
| 1da2fdb856 | |||
| 4bafaa519a | |||
| 3c32bd93e9 | |||
| ef17873448 | |||
| dae30161ae | |||
| 8e70bfb723 | |||
| dcd772018e | |||
| 26d765b74e | |||
| 78b68d2647 | |||
| 50a879155d | |||
| b4fb674566 | |||
| 1b93d2ac21 | |||
| 8e5913d706 | |||
| 1f7def05c1 | |||
| 95317fb707 | |||
| cb5ff2843d | |||
| 4e6369094b | |||
| 0fbcc861d9 | |||
| 8cea58d1f6 | |||
| 4df70531e2 | |||
| 845b856cda | |||
| 84511b08d2 | |||
| 899a33bc58 | |||
| 633e9b7f1e | |||
| ec0b7eb8a4 | |||
| 7d119565da | |||
| 7970597fb8 | |||
| 13f1c1db5e | |||
| 7ea30aa146 | |||
| d96f3e7760 | |||
| 10b31fea84 | |||
| 997924a107 | |||
| 9319abec41 | |||
| 7e404b0246 | |||
| 6638577cf5 | |||
| 114995242d | |||
| 3d6c0974fa | |||
| 8aefc1d702 | |||
| da52a9d2f9 | |||
| 0dc0eb1bef | |||
| 1def73df19 | |||
| 48f132ecf9 | |||
| c17349277d | |||
| 5a6ad02b53 | |||
| 29da9776cd | |||
| 09bac755a9 | |||
| f830dc2ddf | |||
| 5698c074da | |||
| aaf189b87a | |||
| 61023821e6 | |||
| 02a6e30db1 | |||
| 5a0cd51df6 | |||
| 12c832d7fe | |||
| 65c8820db4 | |||
| 0f914c3061 | |||
| 4191f44c1b | |||
| fb99afbeba | |||
| de632e9c5c | |||
| 53ff99148c | |||
| c2ff3b272a | |||
| 747b68c179 | |||
| cbff40d04c | |||
| e415e701cd | |||
| d184ed9de0 | |||
| 297f27c807 | |||
| 30e8d7baa9 | |||
| efc5754bef | |||
| e3e422d29e | |||
| 9f5c8c0b5e | |||
| 044e57adf3 | |||
| e7f165ac96 | |||
| fc41e1801a | |||
| 1aa35dd041 | |||
| 6a1f4a8797 | |||
| 6f6a6c705b | |||
| e8d7d1d421 | |||
| cd31617e21 | |||
| 6d9d96d7cd | |||
| df7c07bec4 | |||
| 5b4717bf6f | |||
| 65d30613b2 | |||
| d5bbab7e72 | |||
| 18b65d30ac | |||
| f55b032cc9 | |||
| e62dba8f40 | |||
| 0619825f38 | |||
| 70d7da34b3 | |||
| 13c251196b | |||
| 4841f24eab | |||
| 64ffbb9d61 | |||
| 83e91c6fa6 | |||
| b1833825e7 | |||
| bde20e82ad | |||
| 8348d23fe4 | |||
| d9557489d5 | |||
| 089ec69595 | |||
| 7427cbb043 | |||
| 456e744d81 | |||
| 6d5ef50727 | |||
| 00e7963988 | |||
| bc06657317 | |||
| bda4b0a23d | |||
| e327f9cf5c | |||
| 5b9351e5f0 | |||
| 5785e9fd1e | |||
| 1e9c8d54f4 | |||
| 7515274712 | |||
| 0be459fe34 | |||
| 11ccdbfde4 | |||
| fd517c16f3 | |||
| fe76f81b47 | |||
| 18127454b5 | |||
| 7826c315b1 | |||
| e329dbd99b | |||
| d6b3e8cff0 | |||
| 80c97620a5 | |||
| 33d852bacf | |||
| 8be0500913 | |||
| 27dded6c62 | |||
| e465dfa6ee | |||
| 3ac0318ba3 | |||
| 17e4625448 | |||
| eb748323f7 | |||
| bc3085f74b | |||
| f66100f74f | |||
| be8b1f73bf | |||
| 0f2c4fc238 | |||
| d0fe641d5c | |||
| 4a2520a43b | |||
| 54c3a6e2e9 | |||
| a27ec0f0b9 | |||
| a7c30ad67c | |||
| ee21f7a373 | |||
| 5c0ff72d27 | |||
| 50c016d707 | |||
| e4de103a00 | |||
| 8c66fd3260 | |||
| 4213def0ad | |||
| 8a4ebe1bde | |||
| 8ea09ee0d1 | |||
| d562e0dc10 | |||
| 29c7e974b5 | |||
| 6d47b70aaf | |||
| 01bed8942c | |||
| 391047d8e5 | |||
| 5a672454ad | |||
| ed799217bf | |||
| 5f0f958aca | |||
| 7bf42f1a89 | |||
| a919d52cf7 | |||
| a7e94467ee | |||
| 01335ac70f | |||
| 35b7e2a0b8 | |||
| c72e950a25 | |||
| 5dcba6d8cb | |||
| 0638c2cef6 | |||
| fc0c1b05a6 | |||
| 3547667158 | |||
| b882e8ba90 | |||
| db2beef189 | |||
| b0629f9f30 | |||
| b3d955e1a8 | |||
| f5e8d0fe03 | |||
| 5815a65a39 | |||
| ad1c0cf349 | |||
| 8b6e260b28 | |||
| eb7f48d3a2 | |||
| 974b971340 | |||
| 9db7331a72 | |||
| 32931c1e37 | |||
| c299798542 | |||
| 612dc4acd5 | |||
| cdb54f6a3e | |||
| 6fbc91527e | |||
| 57bfb37be1 | |||
| 3328d7cf19 | |||
| c410c02487 | |||
| 93879c8118 | |||
| e4329c9fc6 | |||
| 0fa58daa12 | |||
| f8591ed15c | |||
| cbc7004d18 | |||
| a33a585b98 | |||
| 2573ba8599 | |||
| f0d506bbb1 | |||
| a26343a76e | |||
| 9990240d2d | |||
| 418db394a4 | |||
| d939d8c9d7 | |||
| 6383e9b111 | |||
| 2395a4eabc | |||
| 1ec8ec8f6d | |||
| 8df630c529 | |||
| 5c8503e79e | |||
| 3a087d7859 | |||
| 58d3b812a7 | |||
| ac3727f22f | |||
| 43a4e552ce | |||
| a532e639ea | |||
| f099ad8fe9 | |||
| dbed0d0da7 | |||
| 617c103055 | |||
| edb202071c |
@@ -0,0 +1,3 @@
|
||||
[submodule "source/packages/MokoSuiteClient"]
|
||||
path = source/packages/MokoSuiteClient
|
||||
url = https://git.mokoconsulting.tech/MokoConsulting/MokoSuiteClient.git
|
||||
@@ -22,7 +22,7 @@ on:
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
MOKOGITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -27,9 +27,18 @@ name: "Universal: Build & Release"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, closed]
|
||||
types: [opened, synchronize, closed]
|
||||
branches:
|
||||
- main
|
||||
paths-ignore:
|
||||
- '.mokogitea/workflows/**'
|
||||
- '*.md'
|
||||
- 'wiki/**'
|
||||
- '.editorconfig'
|
||||
- '.gitignore'
|
||||
- '.gitattributes'
|
||||
- '.gitmessage'
|
||||
- 'LICENSE'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
action:
|
||||
@@ -43,7 +52,7 @@ on:
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
MOKOGITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
GITEA_ORG: ${{ vars.GITEA_ORG || github.repository_owner }}
|
||||
GITEA_REPO: ${{ vars.GITEA_REPO || github.event.repository.name }}
|
||||
|
||||
@@ -57,6 +66,7 @@ jobs:
|
||||
runs-on: release
|
||||
if: >-
|
||||
(github.event.action == 'opened' && github.event.pull_request.merged != true) ||
|
||||
(github.event.action == 'synchronize' && github.event.pull_request.merged != true) ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.action == 'promote-rc')
|
||||
|
||||
steps:
|
||||
@@ -92,7 +102,7 @@ jobs:
|
||||
php ${MOKO_CLI}/branch_rename.php \
|
||||
--from "${{ github.event.pull_request.head.ref || 'dev' }}" --to rc \
|
||||
--token "${{ secrets.MOKOGITEA_TOKEN }}" \
|
||||
--api-base "${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}" \
|
||||
--api-base "${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}" \
|
||||
--pr "${{ github.event.pull_request.number }}"
|
||||
|
||||
- name: Checkout rc and configure git
|
||||
@@ -111,7 +121,7 @@ jobs:
|
||||
|
||||
- name: Update RC release notes from CHANGELOG.md
|
||||
run: |
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
|
||||
# Extract [Unreleased] section from changelog
|
||||
@@ -259,7 +269,7 @@ jobs:
|
||||
!startsWith(steps.platform.outputs.platform, 'joomla')
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
SEMVER_TAG="v${VERSION}"
|
||||
|
||||
@@ -284,7 +294,7 @@ jobs:
|
||||
|
||||
- name: Update release notes and promote changelog
|
||||
run: |
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
|
||||
# Get the stable release info (version and ID)
|
||||
@@ -353,7 +363,7 @@ jobs:
|
||||
VERSION="${{ steps.bump.outputs.version || steps.version.outputs.version }}"
|
||||
RELEASE_TAG="${{ steps.version.outputs.release_tag }}"
|
||||
GH_REPO="${{ vars.GH_MIRROR_REPO || github.repository }}"
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
php ${MOKO_CLI}/release_mirror.php \
|
||||
--version "$VERSION" --tag "$RELEASE_TAG" \
|
||||
--token "${{ secrets.MOKOGITEA_TOKEN }}" --api-base "$API_BASE" \
|
||||
@@ -382,7 +392,7 @@ jobs:
|
||||
if: steps.version.outputs.skip != 'true'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
|
||||
# Delete rc branch (ephemeral — created by promote-rc)
|
||||
@@ -406,7 +416,7 @@ jobs:
|
||||
if: steps.version.outputs.skip != 'true'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
VERSION="${{ steps.bump.outputs.version || steps.version.outputs.version }}"
|
||||
BRANCH_NAME="version/${VERSION}"
|
||||
@@ -427,7 +437,7 @@ jobs:
|
||||
if: steps.version.outputs.skip != 'true'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
API_BASE="${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
API_BASE="${MOKOGITEA_URL}/api/v1/repos/${GITEA_ORG}/${GITEA_REPO}"
|
||||
php ${MOKO_CLI}/version_reset_dev.php \
|
||||
--token "${{ secrets.MOKOGITEA_TOKEN }}" --api-base "${API_BASE}" \
|
||||
--branch dev --path . 2>&1 || true
|
||||
@@ -453,5 +463,5 @@ jobs:
|
||||
echo "| Version | \`${VERSION}\` |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Branch | \`${{ steps.version.outputs.branch }}\` |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Tag | \`${{ steps.version.outputs.tag }}\` |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Release | [View](${GITEA_URL}/${GITEA_ORG}/${GITEA_REPO}/releases/tag/${{ steps.version.outputs.tag }}) |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Release | [View](${MOKOGITEA_URL}/${GITEA_ORG}/${GITEA_REPO}/releases/tag/${{ steps.version.outputs.tag }}) |" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
@@ -13,6 +13,12 @@
|
||||
name: "Generic: Project CI"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
- dev/**
|
||||
- rc/**
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# FILE INFORMATION
|
||||
# DEFGROUP: Gitea.Workflow
|
||||
# INGROUP: mokocli.Universal
|
||||
# REPO: https://git.mokoconsulting.tech/MokoConsulting/mokocli
|
||||
# PATH: /.mokogitea/workflows/ci-issue-reporter.yml
|
||||
# VERSION: 01.00.00
|
||||
# BRIEF: Reusable workflow — creates/updates a Gitea issue when a CI gate fails.
|
||||
# Clones MokoCLI and runs cli/ci_issue_reporter.sh.
|
||||
|
||||
name: "Universal: CI Issue Reporter"
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
gate:
|
||||
description: "CI gate name (e.g. PR Validation, Repository Health)"
|
||||
required: true
|
||||
type: string
|
||||
details:
|
||||
description: "Human-readable failure description"
|
||||
required: true
|
||||
type: string
|
||||
severity:
|
||||
description: "error or warning"
|
||||
required: false
|
||||
type: string
|
||||
default: "error"
|
||||
workflow:
|
||||
description: "Workflow name for the issue title"
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
secrets:
|
||||
MOKOGITEA_TOKEN:
|
||||
required: true
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
|
||||
|
||||
jobs:
|
||||
report:
|
||||
name: "Report: ${{ inputs.gate }}"
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Clone MokoCLI
|
||||
env:
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
run: |
|
||||
MOKOGITEA_URL="${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}"
|
||||
git clone --depth 1 --filter=blob:none --sparse "${MOKOGITEA_URL}/MokoConsulting/MokoCLI.git" /tmp/mokocli
|
||||
cd /tmp/mokocli && git sparse-checkout set cli/ci_issue_reporter.sh
|
||||
|
||||
- name: Report CI failure
|
||||
env:
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
MOKOGITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
run: |
|
||||
chmod +x /tmp/mokocli/cli/ci_issue_reporter.sh
|
||||
/tmp/mokocli/cli/ci_issue_reporter.sh \
|
||||
--gate "${{ inputs.gate }}" \
|
||||
--details "${{ inputs.details }}" \
|
||||
--severity "${{ inputs.severity }}" \
|
||||
--workflow "${{ inputs.workflow }}"
|
||||
@@ -21,7 +21,7 @@ permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
MOKOGITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
@@ -33,17 +33,17 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GA_TOKEN }}
|
||||
token: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
|
||||
- name: Delete merged branches
|
||||
env:
|
||||
GA_TOKEN: ${{ secrets.GA_TOKEN }}
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
run: |
|
||||
echo "=== Merged Branch Cleanup ==="
|
||||
API="${GITEA_URL}/api/v1/repos/${{ github.repository }}"
|
||||
API="${MOKOGITEA_URL}/api/v1/repos/${{ github.repository }}"
|
||||
|
||||
# List branches via API
|
||||
BRANCHES=$(curl -sS -H "Authorization: token ${GA_TOKEN}" \
|
||||
BRANCHES=$(curl -sS -H "Authorization: token ${MOKOGITEA_TOKEN}" \
|
||||
"${API}/branches?limit=50" | jq -r '.[].name')
|
||||
|
||||
DELETED=0
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
# Check if branch is merged into main
|
||||
if git merge-base --is-ancestor "origin/${BRANCH}" origin/main 2>/dev/null; then
|
||||
echo " Deleting merged branch: ${BRANCH}"
|
||||
curl -sS -X DELETE -H "Authorization: token ${GA_TOKEN}" \
|
||||
curl -sS -X DELETE -H "Authorization: token ${MOKOGITEA_TOKEN}" \
|
||||
"${API}/branches/${BRANCH}" 2>/dev/null || true
|
||||
DELETED=$((DELETED + 1))
|
||||
fi
|
||||
@@ -66,20 +66,20 @@ jobs:
|
||||
|
||||
- name: Clean old workflow runs
|
||||
env:
|
||||
GA_TOKEN: ${{ secrets.GA_TOKEN }}
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
run: |
|
||||
echo "=== Workflow Run Cleanup ==="
|
||||
API="${GITEA_URL}/api/v1/repos/${{ github.repository }}"
|
||||
API="${MOKOGITEA_URL}/api/v1/repos/${{ github.repository }}"
|
||||
CUTOFF=$(date -d "30 days ago" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -v-30d +%Y-%m-%dT%H:%M:%SZ)
|
||||
|
||||
# Get old completed runs
|
||||
RUNS=$(curl -sS -H "Authorization: token ${GA_TOKEN}" \
|
||||
RUNS=$(curl -sS -H "Authorization: token ${MOKOGITEA_TOKEN}" \
|
||||
"${API}/actions/runs?status=completed&limit=50" | \
|
||||
jq -r ".workflow_runs[] | select(.created_at < \"${CUTOFF}\") | .id" 2>/dev/null)
|
||||
|
||||
DELETED=0
|
||||
for RUN_ID in $RUNS; do
|
||||
curl -sS -X DELETE -H "Authorization: token ${GA_TOKEN}" \
|
||||
curl -sS -X DELETE -H "Authorization: token ${MOKOGITEA_TOKEN}" \
|
||||
"${API}/actions/runs/${RUN_ID}" 2>/dev/null || true
|
||||
DELETED=$((DELETED + 1))
|
||||
done
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: "Publish to Composer"
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
- '[0-9]*.[0-9]*.[0-9]*'
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish Package
|
||||
runs-on: ubuntu-latest
|
||||
if: >-
|
||||
!contains(github.event.head_commit.message, '[skip ci]') &&
|
||||
!contains(github.event.head_commit.message, '[skip publish]')
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
run: |
|
||||
if ! command -v php &> /dev/null; then
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq php-cli php-mbstring php-xml php-zip php-curl composer >/dev/null 2>&1
|
||||
fi
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --no-dev --no-interaction --prefer-dist --quiet
|
||||
|
||||
- name: Determine version
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(php -r "echo json_decode(file_get_contents('composer.json'))->version;")
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "Package version: ${VERSION}"
|
||||
|
||||
# Gitea Composer Registry — auto-publishes from tags
|
||||
# The tag push itself registers the package at:
|
||||
# https://git.mokoconsulting.tech/api/packages/MokoConsulting/composer
|
||||
- name: Verify Gitea registry
|
||||
run: |
|
||||
echo "Gitea Composer registry auto-publishes from tags."
|
||||
echo "Package available at: ${GITEA_URL}/api/packages/MokoConsulting/composer"
|
||||
echo "Install: composer require mokoconsulting/mokocli"
|
||||
|
||||
# Packagist — notify of new version
|
||||
- name: Notify Packagist
|
||||
if: secrets.PACKAGIST_TOKEN != ''
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
echo "Notifying Packagist of version ${VERSION}..."
|
||||
curl -sf -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"repository":{"url":"https://git.mokoconsulting.tech/MokoConsulting/mokocli"}}' \
|
||||
"https://packagist.org/api/update-package?username=mokoconsulting&apiToken=${{ secrets.PACKAGIST_TOKEN }}" \
|
||||
&& echo "Packagist notified" \
|
||||
|| echo "::warning::Packagist notification failed (package may not be registered yet)"
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
echo "## Composer Package Published" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Registry | Status |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|----------|--------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Gitea | \`composer require mokoconsulting/mokocli:${VERSION}\` |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Packagist | \`composer require mokoconsulting/mokocli\` |" >> $GITHUB_STEP_SUMMARY
|
||||
@@ -42,10 +42,10 @@ jobs:
|
||||
|
||||
- name: Setup MokoStandards tools
|
||||
env:
|
||||
GA_TOKEN: ${{ secrets.GA_TOKEN || secrets.GA_TOKEN || github.token }}
|
||||
MOKO_CLONE_TOKEN: ${{ secrets.GA_TOKEN || secrets.GA_TOKEN || github.token }}
|
||||
MOKO_CLONE_HOST: ${{ secrets.GA_TOKEN && 'git.mokoconsulting.tech/MokoConsulting' || 'github.com/mokoconsulting-tech' }}
|
||||
COMPOSER_AUTH: '{"github-oauth":{"github.com":"${{ secrets.GA_TOKEN || github.token }}"}}'
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN || github.token }}
|
||||
MOKO_CLONE_TOKEN: ${{ secrets.MOKOGITEA_TOKEN || github.token }}
|
||||
MOKO_CLONE_HOST: ${{ secrets.MOKOGITEA_TOKEN && 'git.mokoconsulting.tech/MokoConsulting' || 'github.com/mokoconsulting-tech' }}
|
||||
COMPOSER_AUTH: '{"github-oauth":{"github.com":"${{ secrets.MOKOGITEA_TOKEN || github.token }}"}}'
|
||||
run: |
|
||||
git clone --depth 1 --branch main --quiet \
|
||||
"https://x-access-token:${MOKO_CLONE_TOKEN}@${MOKO_CLONE_HOST}/MokoStandards-API.git" \
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
#
|
||||
# FILE INFORMATION
|
||||
# DEFGROUP: Gitea.Workflow
|
||||
# INGROUP: moko-platform.Automation
|
||||
# VERSION: 01.26.00
|
||||
# INGROUP: mokocli.Automation
|
||||
# VERSION: 01.44.03
|
||||
# BRIEF: Auto-create feature branch when an issue is opened
|
||||
|
||||
name: "Universal: Issue Branch"
|
||||
@@ -19,7 +19,7 @@ permissions:
|
||||
issues: write
|
||||
|
||||
env:
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
MOKOGITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
|
||||
jobs:
|
||||
create-branch:
|
||||
@@ -28,8 +28,8 @@ jobs:
|
||||
steps:
|
||||
- name: Create branch and comment
|
||||
run: |
|
||||
TOKEN="${{ secrets.GA_TOKEN }}"
|
||||
API="${GITEA_URL}/api/v1/repos/${{ github.repository }}"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
API="${MOKOGITEA_URL}/api/v1/repos/${{ github.repository }}"
|
||||
ISSUE_NUM="${{ github.event.issue.number }}"
|
||||
ISSUE_TITLE="${{ github.event.issue.title }}"
|
||||
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
echo "Created branch: ${BRANCH}"
|
||||
|
||||
# Comment on issue with branch link
|
||||
REPO_URL="${GITEA_URL}/${{ github.repository }}"
|
||||
REPO_URL="${MOKOGITEA_URL}/${{ github.repository }}"
|
||||
BODY="Branch created: [\`${BRANCH}\`](${REPO_URL}/src/branch/${BRANCH})\n\n\`\`\`bash\ngit fetch origin\ngit checkout ${BRANCH}\n\`\`\`"
|
||||
|
||||
curl -sf -X POST \
|
||||
|
||||
@@ -496,39 +496,26 @@ jobs:
|
||||
steps:
|
||||
- name: Trigger RC pre-release
|
||||
env:
|
||||
GA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
REPO: ${{ github.repository }}
|
||||
BRANCH: ${{ github.head_ref }}
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
MOKOGITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
run: |
|
||||
curl -s -X POST "${GITEA_URL}/api/v1/repos/${REPO}/actions/workflows/pre-release.yml/dispatches" -H "Authorization: token ${GITEA_TOKEN}" -H "Content-Type: application/json" -d "{\"ref\":\"${BRANCH}\",\"inputs\":{\"stability\":\"release-candidate\"}}"
|
||||
curl -s -X POST "${MOKOGITEA_URL}/api/v1/repos/${REPO}/actions/workflows/pre-release.yml/dispatches" -H "Authorization: token ${MOKOGITEA_TOKEN}" -H "Content-Type: application/json" -d "{\"ref\":\"${BRANCH}\",\"inputs\":{\"stability\":\"release-candidate\"}}"
|
||||
echo "### Pre-Release" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Triggered RC build on branch \`${BRANCH}\`" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
# ── Issue Reporter ──────────────────────────────────────────────────────
|
||||
report-issues:
|
||||
name: Report Issues
|
||||
runs-on: ubuntu-latest
|
||||
needs: [branch-policy, validate]
|
||||
if: >-
|
||||
always() &&
|
||||
needs.validate.result == 'failure'
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: automation/ci-issue-reporter.sh
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: "File issue for PR validation failure"
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
run: |
|
||||
chmod +x automation/ci-issue-reporter.sh
|
||||
./automation/ci-issue-reporter.sh \
|
||||
--gate "PR Validation" \
|
||||
--workflow "PR Check" \
|
||||
--severity error \
|
||||
--details "PR validation failed (syntax, manifest, changelog, or source checks). See the CI run for the specific check that failed."
|
||||
uses: ./.mokogitea/workflows/ci-issue-reporter.yml
|
||||
with:
|
||||
gate: "PR Validation"
|
||||
workflow: "PR Check"
|
||||
severity: error
|
||||
details: "PR validation failed (syntax, manifest, changelog, or source checks). See the CI run for the specific check that failed."
|
||||
secrets: inherit
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# INGROUP: mokocli.Release
|
||||
# REPO: https://git.mokoconsulting.tech/MokoConsulting/mokocli
|
||||
# PATH: /templates/workflows/universal/pre-release.yml.template
|
||||
# VERSION: 05.01.00
|
||||
# VERSION: 05.02.00
|
||||
# BRIEF: Auto pre-release on push to dev/alpha/beta/rc branches
|
||||
|
||||
name: "Universal: Pre-Release"
|
||||
@@ -59,6 +59,11 @@ jobs:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
ref: ${{ github.ref_name }}
|
||||
submodules: recursive
|
||||
|
||||
- name: Update submodules to main
|
||||
run: |
|
||||
git submodule foreach --quiet 'git checkout main && git pull --quiet origin main' 2>/dev/null || true
|
||||
|
||||
- name: Setup mokocli tools
|
||||
env:
|
||||
|
||||
@@ -29,12 +29,20 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Rename branch
|
||||
env:
|
||||
BRANCH: ${{ github.event.pull_request.head.ref }}
|
||||
REPO: ${{ github.repository }}
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
run: |
|
||||
BRANCH="${{ github.event.pull_request.head.ref }}"
|
||||
set -euo pipefail
|
||||
# BRANCH is attacker-controlled (PR head ref). Strict allowlist before ANY use.
|
||||
if ! printf '%s' "$BRANCH" | grep -Eq '^rc/[A-Za-z0-9._/-]+$'; then
|
||||
echo "::error::Refusing unsafe branch name: $BRANCH"; exit 1
|
||||
fi
|
||||
SUFFIX="${BRANCH#rc/}"
|
||||
DEV_BRANCH="dev/${SUFFIX}"
|
||||
API="${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}/api/v1/repos/${{ github.repository }}/branches"
|
||||
TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
|
||||
API="${GITEA_URL}/api/v1/repos/${REPO}/branches"
|
||||
|
||||
# Create dev/ branch from rc/ branch
|
||||
STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X POST \
|
||||
@@ -42,25 +50,22 @@ jobs:
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"new_branch_name\": \"${DEV_BRANCH}\", \"old_branch_name\": \"${BRANCH}\"}" \
|
||||
"${API}" 2>/dev/null || true)
|
||||
|
||||
if [ "$STATUS" = "201" ]; then
|
||||
echo "Created branch: ${DEV_BRANCH}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Created branch: ${DEV_BRANCH}" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "::error::Failed to create ${DEV_BRANCH} from ${BRANCH} (HTTP ${STATUS})"
|
||||
exit 1
|
||||
echo "::error::Failed to create ${DEV_BRANCH} from ${BRANCH} (HTTP ${STATUS})"; exit 1
|
||||
fi
|
||||
|
||||
# Delete rc/ branch
|
||||
ENCODED=$(php -r "echo rawurlencode('${BRANCH}');")
|
||||
# Read BRANCH from the environment inside PHP (getenv, no string interpolation -> no PHP injection)
|
||||
ENCODED=$(php -r 'echo rawurlencode(getenv("BRANCH"));')
|
||||
STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X DELETE \
|
||||
-H "Authorization: token ${TOKEN}" \
|
||||
"${API}/${ENCODED}" 2>/dev/null || true)
|
||||
|
||||
if [ "$STATUS" = "204" ]; then
|
||||
echo "Deleted branch: ${BRANCH}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Deleted branch: ${BRANCH}" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "::warning::Failed to delete ${BRANCH} (HTTP ${STATUS})"
|
||||
fi
|
||||
|
||||
echo "### RC Reverted" >> $GITHUB_STEP_SUMMARY
|
||||
echo "${BRANCH} → ${DEV_BRANCH}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### RC Reverted" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "${BRANCH} → ${DEV_BRANCH}" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
@@ -77,7 +77,7 @@ jobs:
|
||||
- name: Check actor permission (admin only)
|
||||
id: perm
|
||||
env:
|
||||
TOKEN: ${{ secrets.MOKOGITEA_TOKEN || secrets.MOKOGITEA_TOKEN || github.token }}
|
||||
TOKEN: ${{ secrets.MOKOGITEA_TOKEN || github.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
run: |
|
||||
@@ -671,42 +671,30 @@ jobs:
|
||||
# ═══════════════════════════════════════════════════════════════════════
|
||||
# Issue Reporter — file issues for failed gates
|
||||
# ═══════════════════════════════════════════════════════════════════════
|
||||
report-issues:
|
||||
name: "Report Issues"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [access_check, scripts_governance, repo_health]
|
||||
report-scripts:
|
||||
name: "Report: Scripts Governance"
|
||||
needs: [access_check, scripts_governance]
|
||||
if: >-
|
||||
always() &&
|
||||
(needs.scripts_governance.result == 'failure' ||
|
||||
needs.repo_health.result == 'failure')
|
||||
needs.scripts_governance.result == 'failure'
|
||||
uses: ./.mokogitea/workflows/ci-issue-reporter.yml
|
||||
with:
|
||||
gate: "Scripts Governance"
|
||||
workflow: "Repo Health"
|
||||
severity: error
|
||||
details: "Scripts directory policy violations detected. Review required and allowed directories."
|
||||
secrets: inherit
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: automation/ci-issue-reporter.sh
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: "File issues for failed gates"
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}
|
||||
run: |
|
||||
chmod +x automation/ci-issue-reporter.sh
|
||||
REPORTER="./automation/ci-issue-reporter.sh"
|
||||
WF="Repo Health"
|
||||
|
||||
report_gate() {
|
||||
local gate="$1" result="$2" details="$3"
|
||||
if [ "$result" = "failure" ]; then
|
||||
"$REPORTER" --gate "$gate" --details "$details" --workflow "$WF" --severity error
|
||||
fi
|
||||
}
|
||||
|
||||
report_gate "Scripts Governance" \
|
||||
"${{ needs.scripts_governance.result }}" \
|
||||
"Scripts directory policy violations detected. Review required and allowed directories."
|
||||
|
||||
report_gate "Repository Health" \
|
||||
"${{ needs.repo_health.result }}" \
|
||||
"Repository health checks failed — missing required artifacts, disallowed files, or content warnings. Check the CI run summary."
|
||||
report-health:
|
||||
name: "Report: Repository Health"
|
||||
needs: [access_check, repo_health]
|
||||
if: >-
|
||||
always() &&
|
||||
needs.repo_health.result == 'failure'
|
||||
uses: ./.mokogitea/workflows/ci-issue-reporter.yml
|
||||
with:
|
||||
gate: "Repository Health"
|
||||
workflow: "Repo Health"
|
||||
severity: error
|
||||
details: "Repository health checks failed — missing required artifacts, disallowed files, or content warnings. Check the CI run summary."
|
||||
secrets: inherit
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# FILE INFORMATION
|
||||
# DEFGROUP: Gitea.Workflow
|
||||
# INGROUP: MokoStandards.Security
|
||||
# REPO: https://git.mokoconsulting.tech/MokoConsulting/MokoStandards
|
||||
# PATH: /.gitea/workflows/security-audit.yml
|
||||
# VERSION: 01.00.00
|
||||
# BRIEF: Dependency vulnerability scanning for composer and npm packages
|
||||
|
||||
name: "Universal: Security Audit"
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * 1' # Weekly on Monday at 06:00 UTC
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'composer.json'
|
||||
- 'composer.lock'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
NTFY_URL: ${{ vars.NTFY_URL || 'https://ntfy.mokoconsulting.tech' }}
|
||||
NTFY_TOPIC: ${{ vars.NTFY_TOPIC || 'gitea-security' }}
|
||||
|
||||
jobs:
|
||||
audit:
|
||||
name: Dependency Audit
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Composer audit
|
||||
if: hashFiles('composer.lock') != ''
|
||||
run: |
|
||||
echo "=== Composer Security Audit ==="
|
||||
if ! command -v composer &> /dev/null; then
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq php-cli composer >/dev/null 2>&1
|
||||
fi
|
||||
composer audit --format=plain 2>&1 | tee /tmp/composer-audit.txt
|
||||
RESULT=$?
|
||||
if [ $RESULT -ne 0 ]; then
|
||||
echo "::warning::Composer vulnerabilities found"
|
||||
echo "composer_vulnerable=true" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "No known vulnerabilities in composer dependencies"
|
||||
fi
|
||||
|
||||
- name: NPM audit
|
||||
if: hashFiles('package-lock.json') != ''
|
||||
run: |
|
||||
echo "=== NPM Security Audit ==="
|
||||
npm audit --production 2>&1 | tee /tmp/npm-audit.txt || true
|
||||
if npm audit --production 2>&1 | grep -q "found 0 vulnerabilities"; then
|
||||
echo "No known vulnerabilities in npm dependencies"
|
||||
else
|
||||
echo "::warning::NPM vulnerabilities found"
|
||||
echo "npm_vulnerable=true" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Notify on vulnerabilities
|
||||
if: env.composer_vulnerable == 'true' || env.npm_vulnerable == 'true'
|
||||
run: |
|
||||
REPO="${{ github.event.repository.name }}"
|
||||
curl -sS \
|
||||
-H "Title: ${REPO} has vulnerable dependencies" \
|
||||
-H "Tags: lock,warning" \
|
||||
-H "Priority: high" \
|
||||
-d "Security audit found vulnerabilities. Review dependency updates." \
|
||||
"${NTFY_URL}/${NTFY_TOPIC}" || true
|
||||
@@ -0,0 +1,130 @@
|
||||
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# FILE INFORMATION
|
||||
# DEFGROUP: Gitea.Workflow.Template
|
||||
# INGROUP: MokoStandards.CI
|
||||
# REPO: https://git.mokoconsulting.tech/MokoConsulting/Template-Joomla
|
||||
# PATH: /.mokogitea/workflows/version-set.yml
|
||||
# VERSION: 01.00.00
|
||||
# BRIEF: Set or reset the extension version across all version-bearing files
|
||||
|
||||
name: "Joomla: Set Version"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version number (e.g. 01.00.00)"
|
||||
required: true
|
||||
type: string
|
||||
branch:
|
||||
description: "Branch to update (default: current)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
|
||||
|
||||
jobs:
|
||||
set-version:
|
||||
name: Set Version to ${{ inputs.version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Validate version format
|
||||
run: |
|
||||
VERSION="${{ inputs.version }}"
|
||||
if ! echo "$VERSION" | grep -qP '^\d{2}\.\d{2}\.\d{2}$'; then
|
||||
echo "::error::Invalid version format '${VERSION}' — expected XX.YY.ZZ (e.g. 01.00.00)"
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=${VERSION}" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.MOKOGITEA_TOKEN || github.token }}
|
||||
ref: ${{ inputs.branch || github.ref }}
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Update manifest version
|
||||
run: |
|
||||
MANIFEST=""
|
||||
for XML_FILE in $(find . -maxdepth 3 -name "*.xml" -not -path "./.git/*" -not -path "./vendor/*"); do
|
||||
if grep -q "<extension" "$XML_FILE" 2>/dev/null; then
|
||||
MANIFEST="$XML_FILE"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$MANIFEST" ]; then
|
||||
echo "::warning::No Joomla extension manifest found — skipping manifest update"
|
||||
else
|
||||
OLD_VER=$(grep -oP '<version>\K[^<]+' "$MANIFEST" | head -1)
|
||||
sed -i "s|<version>${OLD_VER}</version>|<version>${VERSION}</version>|" "$MANIFEST"
|
||||
echo "Manifest: ${OLD_VER} → ${VERSION} (${MANIFEST})"
|
||||
fi
|
||||
|
||||
- name: Update README.md version
|
||||
run: |
|
||||
if [ -f "README.md" ]; then
|
||||
if grep -qP '^\s*VERSION:\s*\d' README.md; then
|
||||
sed -i -E "s/(VERSION:\s*)[0-9]{2}\.[0-9]{2}\.[0-9]{2}/\1${VERSION}/" README.md
|
||||
echo "README.md version updated to ${VERSION}"
|
||||
else
|
||||
echo "::warning::No VERSION line found in README.md — skipping"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Update CHANGELOG.md
|
||||
run: |
|
||||
if [ -f "CHANGELOG.md" ]; then
|
||||
DATE=$(date +%Y-%m-%d)
|
||||
# Check if this version already has an entry
|
||||
if grep -q "^\#\# \[${VERSION}\]" CHANGELOG.md; then
|
||||
echo "CHANGELOG.md already has entry for ${VERSION} — skipping"
|
||||
else
|
||||
# Insert new version entry after [Unreleased] or at the top after header
|
||||
if grep -q '^\#\# \[Unreleased\]' CHANGELOG.md; then
|
||||
sed -i "/^\#\# \[Unreleased\]/a\\\\n## [${VERSION}] --- ${DATE}" CHANGELOG.md
|
||||
else
|
||||
sed -i "/^\# Changelog/a\\\\n## [Unreleased]\n\n## [${VERSION}] --- ${DATE}" CHANGELOG.md
|
||||
fi
|
||||
echo "CHANGELOG.md: added entry for ${VERSION}"
|
||||
fi
|
||||
else
|
||||
echo "::warning::No CHANGELOG.md found — skipping"
|
||||
fi
|
||||
|
||||
- name: Update FILE INFORMATION blocks
|
||||
run: |
|
||||
# Update VERSION in file header blocks (# VERSION: XX.YY.ZZ)
|
||||
find . -maxdepth 1 -type f \( -name "*.yml" -o -name "*.yaml" -o -name "*.php" -o -name "*.md" \) \
|
||||
-not -path "./.git/*" -not -path "./vendor/*" -print0 2>/dev/null | \
|
||||
while IFS= read -r -d '' FILE; do
|
||||
if head -20 "$FILE" | grep -qP '^\s*#?\s*VERSION:\s*\d{2}\.\d{2}\.\d{2}'; then
|
||||
sed -i -E "s/(#?\s*VERSION:\s*)[0-9]{2}\.[0-9]{2}\.[0-9]{2}/\1${VERSION}/" "$FILE"
|
||||
echo "Updated FILE INFORMATION VERSION in ${FILE}"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Commit and push
|
||||
run: |
|
||||
git config user.name "Moko Consulting [bot]"
|
||||
git config user.email "hello@mokoconsulting.tech"
|
||||
git add -A
|
||||
if git diff --cached --quiet; then
|
||||
echo "No version changes detected — nothing to commit"
|
||||
else
|
||||
git commit -m "chore: set version to ${VERSION} [skip bump]
|
||||
|
||||
Authored-by: Moko Consulting"
|
||||
git push
|
||||
echo "### Version Set" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Version updated to \`${VERSION}\` on branch \`${GITHUB_REF_NAME}\`" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
@@ -13,6 +13,7 @@
|
||||
name: "Universal: Workflow Sync Trigger"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches:
|
||||
@@ -26,8 +27,9 @@ jobs:
|
||||
name: Sync workflows to live repos
|
||||
runs-on: ubuntu-latest
|
||||
if: >-
|
||||
github.event.pull_request.merged == true &&
|
||||
!contains(github.event.pull_request.title, '[skip sync]')
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event.pull_request.merged == true &&
|
||||
!contains(github.event.pull_request.title, '[skip sync]'))
|
||||
|
||||
steps:
|
||||
- name: Determine platform from repo name
|
||||
@@ -49,8 +51,14 @@ jobs:
|
||||
env:
|
||||
MOKOGITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
|
||||
run: |
|
||||
GITEA_URL="${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}"
|
||||
git clone --depth 1 "${GITEA_URL}/MokoConsulting/mokocli.git" /tmp/mokocli
|
||||
MOKOGITEA_URL="${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}"
|
||||
git clone --depth 1 "${MOKOGITEA_URL}/MokoConsulting/mokocli.git" /tmp/mokocli
|
||||
|
||||
- name: Install PHP
|
||||
run: |
|
||||
if ! command -v php &> /dev/null; then
|
||||
apt-get update -qq && apt-get install -y -qq php-cli php-json php-curl > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
|
||||
+150
-6
@@ -1,14 +1,158 @@
|
||||
# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [01.26.00] --- 2026-06-21
|
||||
## [01.43.35] --- 2026-06-28
|
||||
|
||||
## [01.26.00] --- 2026-06-21
|
||||
### Added
|
||||
- Customizable restore script filename per backup profile (reduces discoverability on remote servers)
|
||||
- MokoRestore standalone mode: multi-ZIP selector when multiple backup archives are present
|
||||
- MokoRestore preflight: Joomla installation detection warning before overwriting an existing site
|
||||
- MokoRestore error handling: try/catch on fetch calls, HTTP status checks, JSON parse recovery
|
||||
- Download button on individual backup record detail toolbar
|
||||
- Profile column in backup records list links to the profile edit view
|
||||
|
||||
## [01.25.00] --- 2026-06-20
|
||||
### Changed
|
||||
- Moved download, browse archive, and view log actions from backup list rows into the individual backup record view
|
||||
- Removed "Run Backup" / "Backup Now" buttons from profiles list, profile edit toolbar, and backup records view (backups are triggered from the dashboard only)
|
||||
- Removed ordering field from profiles; default sort is now by ID ascending
|
||||
- MokoRestore cleanup and security messages now reference the actual script filename instead of hardcoded "restore.php"
|
||||
|
||||
## [01.25.00] --- 2026-06-20
|
||||
### Fixed
|
||||
- SSH key indicator detection and missing delete language key
|
||||
- Bootstrap 5 modal conversion for snapshots view (data-bs-dismiss, modal-footer, getOrCreateInstance)
|
||||
- ntfy default URL changed from ntfy.sh to ntfy.mokoconsulting.tech
|
||||
- Untranslated JFIELD_ORDERING_ASC / JFIELD_ORDERING_LABEL language keys replaced with component-specific keys
|
||||
- Options page title now shows "MokoSuiteBackup Options" instead of raw language key
|
||||
- Profile dropdown IDs in backup records and dashboard show "#ID — Title (type)" format
|
||||
- MokoRestore stalling: unhandled promise rejections from network errors or non-JSON responses left UI in loading state
|
||||
|
||||
## [01.24.00] --- 2026-06-20
|
||||
## [01.43.00] --- 2026-06-24
|
||||
|
||||
## [01.24.00] --- 2026-06-19
|
||||
## [01.42.00] --- 2026-06-23
|
||||
|
||||
|
||||
## [01.42.00] --- 2026-06-23
|
||||
|
||||
## [01.41.00] — 2026-06-23
|
||||
|
||||
### Added — Multi-Remote Storage
|
||||
- New `#__mokosuitebackup_remotes` table for multiple destinations per profile
|
||||
- Remote destinations UI: AJAX-driven add/edit/delete/toggle modal on profile edit
|
||||
- Engine uploads to ALL enabled destinations (BackupEngine + SteppedBackupEngine)
|
||||
- Migration auto-converts existing SFTP/S3/GDrive/FTP profile columns to new table
|
||||
- Backward compatibility: falls back to legacy single-remote columns if table empty
|
||||
- Secrets masked in API responses, merged from DB on save
|
||||
|
||||
### Added — Content Snapshots
|
||||
- Lightweight JSON snapshots of articles, categories, and modules
|
||||
- Includes tags, custom fields, workflow associations, field values
|
||||
- Restore modes: Replace (clean slate), Merge (upsert), Selective (per-article)
|
||||
- Snapshot retention: max count + max age with automatic cleanup
|
||||
- Scheduled snapshot task via com_scheduler
|
||||
- CLI: `mokosuitebackup:snapshot create|restore|list|delete`
|
||||
- REST API: create, list, restore, delete, download snapshots
|
||||
- Tabbed browse modal: Articles / Categories / Modules with item counts
|
||||
|
||||
### Added — SFTP Remote Storage
|
||||
- SFTP support with SSH key file authentication (key stored base64 in database)
|
||||
- Auth type dropdown: Password / Key File / Key File + Passphrase
|
||||
- SshKeyField: file upload via FileReader, key never exposed in HTML
|
||||
- SFTP remote directory browser for path selection
|
||||
- `__KEEP_EXISTING__` sentinel preserves key on profile re-save
|
||||
|
||||
### Added — MokoRestore Wizard (9 steps)
|
||||
- Per-table conflict resolution: Replace / Skip / Merge / Data Only
|
||||
- Preset buttons: "All Replace", "All Skip", "Everything except users"
|
||||
- Post-restore actions: reset passwords, hits, versions, sessions, cache
|
||||
- Auto-detect sanitized passwords and prompt for reset (random temp password)
|
||||
- Standalone mode: restore.php scans directory for ZIP files
|
||||
- Wrapped mode: restore.php bundled inside backup ZIP
|
||||
- Security gate with filesystem verification + path traversal protection
|
||||
|
||||
### Added — Data Sanitization
|
||||
- Sanitize user passwords: replace hashes with invalid sentinel
|
||||
- Sanitize user emails: replace with dummy values
|
||||
- Clear session data: exclude `#__session` table
|
||||
- Preserve super admin credentials (optional)
|
||||
- GDPR-friendly backup sharing for demos and staging sites
|
||||
|
||||
### Added — Backup Engine
|
||||
- Pre-flight validation: directory, disk space, extensions, credentials, running backups
|
||||
- Auto-verify archive integrity after creation (ZIP, tar.gz, 7z)
|
||||
- 7z archive format via system 7za/7z CLI binary with native encryption
|
||||
- Streaming database dump to temp file (prevents OOM on large sites)
|
||||
- S3 streaming upload via CURLOPT_PUT (prevents OOM)
|
||||
- Graceful remote degradation: local backup preserved if upload fails
|
||||
- DatabaseDumper::dumpToFile() for memory-efficient operation
|
||||
|
||||
### Added — Admin UI
|
||||
- Dashboard: snapshot widget, 30-day backup trend chart, per-profile storage breakdown
|
||||
- CPanel admin dashboard module (mod_mokosuitebackup_cpanel) with quick actions
|
||||
- Backup type filter dropdown in backups list
|
||||
- Backup comparison: select two backups for side-by-side diff
|
||||
- Archive browser: view files inside backup without extracting
|
||||
- Manual purge: delete backups older than a date with count preview
|
||||
- Backup count badges on profile list
|
||||
- "Do not navigate away" warning in backup/restore progress modals
|
||||
- Clickable placeholder pills for backup directory and archive name fields
|
||||
- Comprehensive help modal with absolute/relative/placeholder path documentation
|
||||
- Placeholder resolution display with EXAMPLE prefix
|
||||
- All placeholders UPPERCASE: [HOST], [SITE_NAME], [DATE], [DATETIME], etc.
|
||||
|
||||
### Added — CLI & API
|
||||
- `mokosuitebackup:restore` with --files-only, --db-only, --password options
|
||||
- `mokosuitebackup:snapshot` with create, restore, list, delete actions
|
||||
- REST API for snapshots: create, list, restore, delete, download
|
||||
- Profile credentials masked in API responses
|
||||
|
||||
### Added — Notifications & Logging
|
||||
- Email/ntfy notifications for site restore, snapshot create/restore
|
||||
- Joomla Action Logs for restore, snapshot, and snapshot restore events
|
||||
- Global ntfy server/topic/token settings (fallback for profiles)
|
||||
|
||||
### Added — Security & Configuration
|
||||
- Webcron secret field with CSPRNG generator + strength meter
|
||||
- IP whitelist field with current IP detection + one-click "Add my IP"
|
||||
- 10 ACL permissions with full enforcement audit across all controllers
|
||||
- Config defaults: archive format, MokoRestore mode, sanitization settings
|
||||
- Path traversal protection on all archive extraction (ZIP, tar.gz, JPA)
|
||||
|
||||
### Fixed
|
||||
- CLI RestoreCommand passed wrong arguments (filepath instead of record ID)
|
||||
- JPA path traversal: reject `../` in archive entry paths
|
||||
- S3Uploader OOM: streaming upload instead of file_get_contents
|
||||
- DatabaseDumper OOM: streaming to file instead of in-memory string
|
||||
- AkeebaImporter: removed unserialize() (PHP object injection risk)
|
||||
- BackupTable: delete DB row before file (prevents data loss)
|
||||
- RestoreEngine: staging path sanitized with preg_replace
|
||||
- API profiles: sensitive fields masked with `***`
|
||||
- Webcron: missing return after sendJsonResponse on auth failure
|
||||
- loadFormData(): cast array to object (PHP 8.x TypeError fix)
|
||||
- MokoRestore data-only mode: uses REPLACE INTO for existing rows
|
||||
- Plaintext archive deleted on encryption failure
|
||||
- TarGzArchiver: intermediate .tar cleaned in finally block
|
||||
- Install script: single-line comments converted to block comments
|
||||
- Orphaned root-level webservices plugin files removed
|
||||
- include_mokorestore column: TINYINT changed to VARCHAR(20)
|
||||
- Snapshot fields_values: scoped dump and restore to com_content.article (previously destroyed values for contacts, users, etc.)
|
||||
- Run Backup button: accept CSRF token from GET (fixes "token did not match" on profile edit)
|
||||
- SFTP fields: moved into remote fieldset for showon visibility; removed required attr that blocked non-SFTP saves
|
||||
- Script.php merge conflict markers resolved
|
||||
|
||||
## [01.24.00] — 2026-06-02
|
||||
|
||||
### Added
|
||||
- Initial release: full-site backup and restore for Joomla 6
|
||||
- Database, files, and configuration backup
|
||||
- ZIP and tar.gz archive formats with AES-256 encryption
|
||||
- Differential backups based on file manifests
|
||||
- FTP/FTPS, S3, Google Drive remote storage
|
||||
- MokoRestore standalone restore wizard
|
||||
- CLI backup and restore commands
|
||||
- REST API for remote management
|
||||
- Scheduled tasks via com_scheduler
|
||||
- Email and ntfy push notifications
|
||||
- Per-profile retention, exclusions, and notifications
|
||||
- Akeeba Backup migration tool
|
||||
- Admin dashboard with system health checks
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
# Makefile for Joomla Extensions
|
||||
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# MokoSuiteBackup — Full-site backup and restore for Joomla
|
||||
#
|
||||
# Builds and releases are handled by CI workflows (pre-release.yml,
|
||||
# auto-release.yml). This Makefile provides local validation helpers
|
||||
# and workflow dispatch shortcuts.
|
||||
|
||||
# ==============================================================================
|
||||
# CONFIGURATION
|
||||
# ==============================================================================
|
||||
|
||||
EXTENSION_NAME := mokosuitebackup
|
||||
EXTENSION_TYPE := package
|
||||
|
||||
SRC_DIR := source
|
||||
|
||||
# Gitea
|
||||
GITEA_URL := https://git.mokoconsulting.tech
|
||||
GITEA_ORG := MokoConsulting
|
||||
GITEA_REPO := MokoSuiteBackup
|
||||
|
||||
# Tools
|
||||
PHP := php
|
||||
COMPOSER := composer
|
||||
PHPCS := vendor/bin/phpcs
|
||||
|
||||
# Coding Standards
|
||||
PHPCS_STANDARD := Joomla
|
||||
|
||||
# Colors for output
|
||||
COLOR_RESET := \033[0m
|
||||
COLOR_GREEN := \033[32m
|
||||
COLOR_YELLOW := \033[33m
|
||||
COLOR_BLUE := \033[34m
|
||||
COLOR_RED := \033[31m
|
||||
|
||||
# ==============================================================================
|
||||
# TARGETS
|
||||
# ==============================================================================
|
||||
|
||||
.PHONY: help
|
||||
help: ## Show this help message
|
||||
@echo "$(COLOR_BLUE)╔════════════════════════════════════════════════════════════╗$(COLOR_RESET)"
|
||||
@echo "$(COLOR_BLUE)║ MokoSuiteBackup Makefile ║$(COLOR_RESET)"
|
||||
@echo "$(COLOR_BLUE)╚════════════════════════════════════════════════════════════╝$(COLOR_RESET)"
|
||||
@echo ""
|
||||
@echo "$(COLOR_GREEN)Available targets:$(COLOR_RESET)"
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " $(COLOR_BLUE)%-20s$(COLOR_RESET) %s\n", $$1, $$2}'
|
||||
@echo ""
|
||||
|
||||
# -- Validation ----------------------------------------------------------------
|
||||
|
||||
.PHONY: lint
|
||||
lint: ## Run PHP syntax check on all source files
|
||||
@echo "$(COLOR_BLUE)Running PHP linter...$(COLOR_RESET)"
|
||||
@ERROR=0; \
|
||||
find $(SRC_DIR) -name "*.php" -exec $(PHP) -l {} \; 2>&1 | grep -v "No syntax errors" || true; \
|
||||
if find $(SRC_DIR) -name "*.php" -exec $(PHP) -l {} \; 2>&1 | grep -q "Parse error"; then \
|
||||
echo "$(COLOR_RED)✗ Syntax errors found$(COLOR_RESET)"; exit 1; \
|
||||
fi
|
||||
@echo "$(COLOR_GREEN)✓ PHP linting complete$(COLOR_RESET)"
|
||||
|
||||
.PHONY: phpcs
|
||||
phpcs: ## Run PHP CodeSniffer (Joomla standards)
|
||||
@echo "$(COLOR_BLUE)Running PHP CodeSniffer...$(COLOR_RESET)"
|
||||
@if [ -f "$(PHPCS)" ]; then \
|
||||
$(PHPCS) --standard=$(PHPCS_STANDARD) --extensions=php $(SRC_DIR); \
|
||||
else \
|
||||
echo "$(COLOR_YELLOW)⚠ PHP CodeSniffer not installed. Run: composer install$(COLOR_RESET)"; \
|
||||
fi
|
||||
|
||||
.PHONY: validate
|
||||
validate: lint ## Run all local validation checks
|
||||
@echo "$(COLOR_GREEN)✓ Validation passed$(COLOR_RESET)"
|
||||
|
||||
.PHONY: validate-xml
|
||||
validate-xml: ## Validate all XML manifests are well-formed
|
||||
@echo "$(COLOR_BLUE)Validating XML manifests...$(COLOR_RESET)"
|
||||
@ERROR=0; \
|
||||
for f in $$(find $(SRC_DIR) -name "*.xml"); do \
|
||||
$(PHP) -r "new SimpleXMLElement(file_get_contents('$$f'));" 2>/dev/null \
|
||||
|| { echo "$(COLOR_RED)✗ Invalid XML: $$f$(COLOR_RESET)"; ERROR=1; }; \
|
||||
done; \
|
||||
[ $$ERROR -eq 0 ] && echo "$(COLOR_GREEN)✓ All XML manifests valid$(COLOR_RESET)" || exit 1
|
||||
|
||||
# -- Dependencies --------------------------------------------------------------
|
||||
|
||||
.PHONY: install-deps
|
||||
install-deps: ## Install PHP dependencies via Composer
|
||||
@echo "$(COLOR_BLUE)Installing dependencies...$(COLOR_RESET)"
|
||||
@if [ -f "composer.json" ]; then \
|
||||
$(COMPOSER) install; \
|
||||
echo "$(COLOR_GREEN)✓ Composer dependencies installed$(COLOR_RESET)"; \
|
||||
fi
|
||||
|
||||
.PHONY: security-check
|
||||
security-check: ## Run security audit on dependencies
|
||||
@echo "$(COLOR_BLUE)Running security checks...$(COLOR_RESET)"
|
||||
@if [ -f "composer.json" ]; then \
|
||||
$(COMPOSER) audit || echo "$(COLOR_YELLOW)⚠ Vulnerabilities found$(COLOR_RESET)"; \
|
||||
fi
|
||||
|
||||
# -- Minify --------------------------------------------------------------------
|
||||
|
||||
MOKO_PLATFORM ?= $(or $(wildcard ../moko-platform),$(wildcard $(HOME)/moko-platform),$(wildcard /opt/moko-platform))
|
||||
MINIFY_SCRIPT := $(MOKO_PLATFORM)/build/minify.js
|
||||
|
||||
.PHONY: minify
|
||||
minify: ## Minify CSS/JS assets
|
||||
@echo "$(COLOR_BLUE)Minifying assets...$(COLOR_RESET)"
|
||||
@if [ -f "$(MINIFY_SCRIPT)" ]; then \
|
||||
node "$(MINIFY_SCRIPT)" $(SRC_DIR); \
|
||||
elif [ -f "scripts/minify.js" ]; then \
|
||||
node scripts/minify.js; \
|
||||
else \
|
||||
echo "$(COLOR_YELLOW)⚠ No minify script found$(COLOR_RESET)"; \
|
||||
fi
|
||||
|
||||
# -- Release (CI workflow dispatch) --------------------------------------------
|
||||
|
||||
.PHONY: release
|
||||
release: validate validate-xml ## Trigger pre-release build via CI workflow
|
||||
@echo "$(COLOR_BLUE)Triggering pre-release workflow...$(COLOR_RESET)"
|
||||
@if ! command -v curl >/dev/null 2>&1; then \
|
||||
echo "$(COLOR_RED)✗ curl required$(COLOR_RESET)"; exit 1; \
|
||||
fi
|
||||
@if [ -z "$$MOKOGITEA_TOKEN" ]; then \
|
||||
echo "$(COLOR_RED)✗ MOKOGITEA_TOKEN not set$(COLOR_RESET)"; exit 1; \
|
||||
fi
|
||||
@BRANCH=$$(git rev-parse --abbrev-ref HEAD); \
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token $$MOKOGITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
"$(GITEA_URL)/api/v1/repos/$(GITEA_ORG)/$(GITEA_REPO)/actions/workflows/pre-release.yml/dispatches" \
|
||||
-d "{\"ref\":\"$$BRANCH\",\"inputs\":{\"stability\":\"development\"}}" \
|
||||
&& echo "$(COLOR_GREEN)✓ Pre-release dispatched on $$BRANCH (development channel)$(COLOR_RESET)" \
|
||||
|| { echo "$(COLOR_RED)✗ Dispatch failed$(COLOR_RESET)"; exit 1; }
|
||||
|
||||
.PHONY: release-rc
|
||||
release-rc: validate validate-xml ## Trigger release-candidate build via CI workflow
|
||||
@echo "$(COLOR_BLUE)Triggering RC pre-release workflow...$(COLOR_RESET)"
|
||||
@if [ -z "$$MOKOGITEA_TOKEN" ]; then \
|
||||
echo "$(COLOR_RED)✗ MOKOGITEA_TOKEN not set$(COLOR_RESET)"; exit 1; \
|
||||
fi
|
||||
@BRANCH=$$(git rev-parse --abbrev-ref HEAD); \
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token $$MOKOGITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
"$(GITEA_URL)/api/v1/repos/$(GITEA_ORG)/$(GITEA_REPO)/actions/workflows/pre-release.yml/dispatches" \
|
||||
-d "{\"ref\":\"$$BRANCH\",\"inputs\":{\"stability\":\"release-candidate\"}}" \
|
||||
&& echo "$(COLOR_GREEN)✓ Pre-release dispatched on $$BRANCH (release-candidate channel)$(COLOR_RESET)" \
|
||||
|| { echo "$(COLOR_RED)✗ Dispatch failed$(COLOR_RESET)"; exit 1; }
|
||||
|
||||
# -- Info ----------------------------------------------------------------------
|
||||
|
||||
.PHONY: version
|
||||
version: ## Display version from package manifest
|
||||
@VERSION=$$(grep '<version>' $(SRC_DIR)/pkg_mokosuitebackup.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/'); \
|
||||
echo "$(COLOR_BLUE)$(EXTENSION_NAME)$(COLOR_RESET) v$$VERSION ($(EXTENSION_TYPE))"
|
||||
|
||||
# Default target
|
||||
.DEFAULT_GOAL := help
|
||||
@@ -1,50 +1,86 @@
|
||||
# MokoSuiteBackup
|
||||
|
||||
<!-- VERSION: 01.26.00 -->
|
||||
|
||||
Full-site backup and restore for Joomla — database, files, and configuration.
|
||||
|
||||
## Overview
|
||||
|
||||
MokoSuiteBackup is a comprehensive backup solution for Joomla 4/5/6 sites. It creates complete site backups including the database, files, and configuration, packaged into downloadable ZIP archives. Supports multiple backup profiles, scheduled backups via CLI/cron, and a REST API for remote management.
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| **Package** | `pkg_mokosuitebackup` |
|
||||
| **Type** | Joomla Package (9 sub-extensions + MokoSuiteClient) |
|
||||
| **Joomla** | 6.x+ |
|
||||
| **PHP** | 8.1+ |
|
||||
| **License** | GPL-3.0-or-later |
|
||||
|
||||
## Features
|
||||
|
||||
- Full site backup (database + files + configuration)
|
||||
- Database-only backup mode
|
||||
- Files-only backup mode
|
||||
- Multiple backup profiles with independent configurations
|
||||
- File and directory exclusion filters
|
||||
- Table exclusion filters for database backups
|
||||
- Step-based backup engine (avoids PHP timeout on large sites)
|
||||
- CLI script for cron/scheduled backups
|
||||
- REST API (Joomla Web Services) for remote management
|
||||
- Backup record management (list, download, delete)
|
||||
- Automatic old backup cleanup (configurable retention)
|
||||
- Admin dashboard with backup history and storage usage
|
||||
### Backup
|
||||
- Full site, database-only, files-only, and differential backup modes
|
||||
- Pre-flight validation — checks directory, disk space, extensions, credentials before starting
|
||||
- Auto-verify archive integrity after creation
|
||||
- Stepped AJAX engine prevents timeout on shared hosting
|
||||
- AES-256 ZIP encryption with configurable password
|
||||
- Configurable archive naming with placeholders ([HOST], [DATE], [SITE_NAME], etc.)
|
||||
- Per-profile retention — configure max backup count and max age (days) per profile, with global defaults
|
||||
- Data sanitization — optionally clear user passwords, emails, and sessions in backup
|
||||
|
||||
### Content Snapshots
|
||||
- Lightweight JSON snapshots of articles, categories, and modules
|
||||
- Includes tags, custom fields, workflow associations
|
||||
- Restore modes: Replace (clean slate) or Merge (upsert)
|
||||
- Selective article restore — browse and pick individual items
|
||||
- Automatic retention (max count + max age)
|
||||
- Scheduled snapshot task via com_scheduler
|
||||
|
||||
### Remote Storage
|
||||
- Multi-remote — upload to multiple destinations per profile simultaneously
|
||||
- SFTP with SSH key file auth + remote directory browser
|
||||
- Amazon S3 and S3-compatible (DigitalOcean Spaces, Wasabi, MinIO)
|
||||
- Google Drive with OAuth2 and resumable uploads
|
||||
- Graceful degradation — local backup preserved if upload fails
|
||||
|
||||
### MokoRestore Standalone Wizard
|
||||
- 9-step restore wizard that works without Joomla installed
|
||||
- Per-table conflict resolution: Replace / Skip / Merge / Data Only
|
||||
- Post-restore actions: reset passwords, hits, versions, sessions, cache
|
||||
- Auto-detect sanitized passwords and prompt for reset
|
||||
- Standalone mode: restore.php scans directory for ZIP files
|
||||
- Wrapped mode: restore.php bundled inside backup ZIP
|
||||
- Security gate with filesystem verification
|
||||
|
||||
### Notifications
|
||||
- Email on success/failure per profile
|
||||
- ntfy push notifications
|
||||
- Notifications for restore and snapshot operations
|
||||
|
||||
### Admin Dashboard
|
||||
- Last backup status, next scheduled, total count, storage used
|
||||
- Snapshot widget with latest info and type badges
|
||||
- 30-day backup trend chart
|
||||
- Per-profile storage breakdown
|
||||
- System health checks
|
||||
|
||||
### CLI
|
||||
- `mokosuitebackup:run --profile=1` — run backup
|
||||
- `mokosuitebackup:restore 1 --files-only --db-only --password=xxx`
|
||||
- `mokosuitebackup:snapshot create|restore|list|delete`
|
||||
|
||||
### REST API
|
||||
- Backup: start, list, download, delete, profiles
|
||||
- Snapshots: create, list, restore, delete, download
|
||||
- Profile credentials masked in API responses
|
||||
|
||||
### Bundled: MokoSuiteClient
|
||||
- Full MokoSuiteClient package installed automatically alongside MokoSuiteBackup
|
||||
- Provides admin dashboard, security firewall, tenant management, and developer tools
|
||||
|
||||
## Installation
|
||||
|
||||
1. Download `pkg_mokobackup-*.zip` from [Releases](https://git.mokoconsulting.tech/MokoConsulting/MokoSuiteBackup/releases)
|
||||
1. Download from [Releases](https://git.mokoconsulting.tech/MokoConsulting/MokoSuiteBackup/releases)
|
||||
2. Joomla Administrator > Extensions > Install
|
||||
3. System plugin enabled automatically on install
|
||||
3. Components > MokoSuiteBackup > Dashboard
|
||||
|
||||
## Configuration
|
||||
## Documentation
|
||||
|
||||
- **Component**: Administrator > Components > MokoSuiteBackup
|
||||
- **Profiles**: Create backup profiles with different file/database filters
|
||||
- **System Plugin**: Configure scheduled backup triggers and notifications
|
||||
- **CLI**: `php cli/mokobackup.php --profile=1` for cron-based backups
|
||||
|
||||
## REST API
|
||||
|
||||
The webservices plugin exposes endpoints compatible with the MokoBackup MCP server:
|
||||
|
||||
- `POST /api/index.php/v1/mokobackup/backup` — Start a backup
|
||||
- `GET /api/index.php/v1/mokobackup/backups` — List backup records
|
||||
- `GET /api/index.php/v1/mokobackup/backup/:id/download` — Download archive
|
||||
- `DELETE /api/index.php/v1/mokobackup/backup/:id` — Delete backup record
|
||||
- `GET /api/index.php/v1/mokobackup/profiles` — List backup profiles
|
||||
See the [Wiki](https://git.mokoconsulting.tech/MokoConsulting/MokoSuiteBackup/wiki) for guides and reference.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
<!--
|
||||
Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
|
||||
This file is part of a Moko Consulting project.
|
||||
|
||||
SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# FILE INFORMATION
|
||||
DEFGROUP: Template-Joomla
|
||||
INGROUP: Template-Joomla.Documentation
|
||||
REPO: https://git.mokoconsulting.tech/MokoConsulting/Template-Joomla
|
||||
PATH: /SECURITY.md
|
||||
VERSION: 01.44.03
|
||||
BRIEF: Security vulnerability reporting and handling policy
|
||||
-->
|
||||
|
||||
# Security Policy
|
||||
|
||||
## Purpose and Scope
|
||||
|
||||
This document defines the security vulnerability reporting, response, and disclosure policy for this Joomla Plugin template repository. It establishes the authoritative process for responsible disclosure, assessment, remediation, and communication of security issues.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Security updates are provided for the following versions:
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 01.x.x | :white_check_mark: |
|
||||
| < 01.0 | :x: |
|
||||
|
||||
Only the current major version receives security updates. Users should upgrade to the latest supported version to receive security patches.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
### Where to Report
|
||||
|
||||
**DO NOT** create public GitHub issues for security vulnerabilities.
|
||||
|
||||
Report security vulnerabilities privately to:
|
||||
|
||||
**Email**: `security@mokoconsulting.tech`
|
||||
|
||||
**Subject Line**: `[SECURITY] Template-Joomla - Brief Description`
|
||||
|
||||
### What to Include
|
||||
|
||||
A complete vulnerability report should include:
|
||||
|
||||
1. **Description**: Clear explanation of the vulnerability
|
||||
2. **Impact**: Potential security impact and severity assessment
|
||||
3. **Affected Versions**: Which versions are vulnerable
|
||||
4. **Reproduction Steps**: Detailed steps to reproduce the issue
|
||||
5. **Proof of Concept**: Code, configuration, or demonstration (if applicable)
|
||||
6. **Suggested Fix**: Proposed remediation (if known)
|
||||
7. **Disclosure Timeline**: Your expectations for public disclosure
|
||||
|
||||
### Response Timeline
|
||||
|
||||
* **Initial Response**: Within 3 business days
|
||||
* **Assessment Complete**: Within 7 business days
|
||||
* **Fix Timeline**: Depends on severity (see below)
|
||||
* **Disclosure**: Coordinated with reporter
|
||||
|
||||
## Severity Classification
|
||||
|
||||
Vulnerabilities are classified using the following severity levels:
|
||||
|
||||
### Critical
|
||||
* Remote code execution
|
||||
* Authentication bypass
|
||||
* Data breach or exposure of sensitive information
|
||||
* **Fix Timeline**: 7 days
|
||||
|
||||
### High
|
||||
* Privilege escalation
|
||||
* SQL injection or command injection
|
||||
* Cross-site scripting (XSS) with significant impact
|
||||
* **Fix Timeline**: 14 days
|
||||
|
||||
### Medium
|
||||
* Information disclosure (limited scope)
|
||||
* Denial of service
|
||||
* Security misconfigurations with moderate impact
|
||||
* **Fix Timeline**: 30 days
|
||||
|
||||
### Low
|
||||
* Security best practice violations
|
||||
* Minor information leaks
|
||||
* Issues requiring user interaction or complex preconditions
|
||||
* **Fix Timeline**: 60 days or next release
|
||||
|
||||
## Remediation Process
|
||||
|
||||
1. **Acknowledgment**: Security team confirms receipt and begins investigation
|
||||
2. **Assessment**: Vulnerability is validated, severity assigned, and impact analyzed
|
||||
3. **Development**: Security patch is developed and tested
|
||||
4. **Review**: Patch undergoes security review and validation
|
||||
5. **Release**: Fixed version is released with security advisory
|
||||
6. **Disclosure**: Public disclosure follows coordinated timeline
|
||||
|
||||
## Security Advisories
|
||||
|
||||
Security advisories are published via:
|
||||
|
||||
* GitHub Security Advisories
|
||||
* Release notes and CHANGELOG.md
|
||||
* Email notification to project users (if mailing list is established)
|
||||
|
||||
Advisories include:
|
||||
|
||||
* CVE identifier (if applicable)
|
||||
* Severity rating
|
||||
* Affected versions
|
||||
* Fixed versions
|
||||
* Mitigation steps
|
||||
* Attribution (with reporter consent)
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
For projects using this template:
|
||||
|
||||
### Required Controls
|
||||
|
||||
* Enable GitHub security features (Dependabot, code scanning)
|
||||
* Implement branch protection on `main`
|
||||
* Require code review for all changes
|
||||
* Enforce signed commits (recommended)
|
||||
* Use secrets management (never commit credentials)
|
||||
* Maintain security documentation
|
||||
* Follow secure coding standards defined in MokoStandards
|
||||
|
||||
### Joomla Plugin Security
|
||||
|
||||
* Follow Joomla security best practices
|
||||
* Validate and sanitize all user input
|
||||
* Use Joomla's database API to prevent SQL injection
|
||||
* Properly escape output to prevent XSS
|
||||
* Implement proper access control checks
|
||||
* Use Joomla's session and authentication APIs
|
||||
* Keep Joomla and dependencies up to date
|
||||
|
||||
### CI/CD Security
|
||||
|
||||
* Validate all inputs
|
||||
* Sanitize outputs
|
||||
* Use least privilege access
|
||||
* Pin dependencies with hash verification
|
||||
* Scan for vulnerabilities in dependencies
|
||||
* Audit third-party actions and tools
|
||||
|
||||
#### Automated Security Scanning
|
||||
|
||||
All repositories SHOULD implement:
|
||||
|
||||
**CodeQL Analysis**:
|
||||
* Enabled for PHP and other supported languages
|
||||
* Runs on: push to main, pull requests, weekly schedule
|
||||
* Query sets: `security-extended` and `security-and-quality`
|
||||
* Configuration: `.github/workflows/codeql-analysis.yml`
|
||||
|
||||
**Dependabot Security Updates**:
|
||||
* Weekly scans for vulnerable dependencies
|
||||
* Automated pull requests for security patches
|
||||
* Configuration: `.github/dependabot.yml`
|
||||
|
||||
**Secret Scanning**:
|
||||
* Enabled by default with push protection
|
||||
* Prevents accidental credential commits
|
||||
|
||||
### Dependency Management
|
||||
|
||||
* Keep dependencies up to date
|
||||
* Monitor security advisories for dependencies
|
||||
* Remove unused dependencies
|
||||
* Audit new dependencies before adoption
|
||||
* Document security-critical dependencies
|
||||
|
||||
## Compliance and Governance
|
||||
|
||||
This security policy is aligned with MokoStandards. Deviations require documented justification.
|
||||
|
||||
Security policies are reviewed and updated at least annually or following significant security incidents.
|
||||
|
||||
## Attribution and Recognition
|
||||
|
||||
We acknowledge and appreciate responsible disclosure. With your permission, we will:
|
||||
|
||||
* Credit you in security advisories
|
||||
* List you in CHANGELOG.md for the fix release
|
||||
* Recognize your contribution publicly (if desired)
|
||||
|
||||
## Contact and Escalation
|
||||
|
||||
* **Security Team**: security@mokoconsulting.tech
|
||||
* **Primary Contact**: hello@mokoconsulting.tech
|
||||
* **Escalation**: For urgent matters requiring immediate attention, contact the maintainer directly via GitHub
|
||||
|
||||
## Out of Scope
|
||||
|
||||
The following are explicitly out of scope:
|
||||
|
||||
* Issues in third-party dependencies (report directly to maintainers)
|
||||
* Social engineering attacks
|
||||
* Physical security issues
|
||||
* Denial of service via resource exhaustion without amplification
|
||||
* Issues requiring physical access to systems
|
||||
* Theoretical vulnerabilities without proof of exploitability
|
||||
|
||||
---
|
||||
|
||||
## Metadata
|
||||
|
||||
| Field | Value |
|
||||
| ------------ | ------------------------------------------------------------------------------------------------------------ |
|
||||
| Document | Security Policy |
|
||||
| Path | /SECURITY.md |
|
||||
| Repository | [https://github.com/mokoconsulting-tech/Template-Joomla](https://github.com/mokoconsulting-tech/Template-Joomla) |
|
||||
| Owner | Moko Consulting |
|
||||
| Scope | Security vulnerability handling |
|
||||
| Status | Active |
|
||||
| Effective | 2026-01-16 |
|
||||
|
||||
## Revision History
|
||||
|
||||
| Date | Change Description | Author |
|
||||
| ---------- | ------------------------------------------------- | --------------- |
|
||||
| 2026-01-16 | Initial creation for template repository | Moko Consulting |
|
||||
@@ -1,237 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
||||
#
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# FILE INFORMATION
|
||||
# DEFGROUP: Automation.CI
|
||||
# INGROUP: moko-platform.Automation
|
||||
# REPO: https://git.mokoconsulting.tech/MokoConsulting/moko-platform
|
||||
# PATH: /automation/ci-issue-reporter.sh
|
||||
# VERSION: 09.23.00
|
||||
# BRIEF: Creates or updates a Gitea issue when a CI gate fails.
|
||||
# Deduplicates by searching open issues with the "ci-auto" label
|
||||
# whose title matches the gate. If a matching issue exists, a comment
|
||||
# is appended instead of opening a duplicate.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# ── Defaults ────────────────────────────────────────────────────────────────
|
||||
GITEA_URL="${GITEA_URL:-https://git.mokoconsulting.tech}"
|
||||
GITEA_TOKEN="${GITEA_TOKEN:-}"
|
||||
REPO="${GITHUB_REPOSITORY:-}"
|
||||
RUN_URL="${GITHUB_SERVER_URL:-${GITEA_URL}}/${REPO}/actions/runs/${GITHUB_RUN_ID:-0}"
|
||||
LABEL_NAME="ci-auto"
|
||||
LABEL_COLOR="#e11d48"
|
||||
|
||||
GATE=""
|
||||
DETAILS=""
|
||||
SEVERITY="error"
|
||||
WORKFLOW=""
|
||||
|
||||
# ── Parse arguments ─────────────────────────────────────────────────────────
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: ci-issue-reporter.sh --gate NAME --details TEXT [OPTIONS]
|
||||
|
||||
Required:
|
||||
--gate CI gate name (e.g. "Code Quality", "Self-Health")
|
||||
--details Human-readable failure description
|
||||
|
||||
Optional:
|
||||
--severity "error" (default) or "warning"
|
||||
--workflow Workflow name for the issue title
|
||||
--repo owner/repo (default: \$GITHUB_REPOSITORY)
|
||||
--run-url URL to the CI run (auto-detected from env)
|
||||
--token Gitea API token (default: \$GITEA_TOKEN)
|
||||
--url Gitea base URL (default: \$GITEA_URL)
|
||||
EOF
|
||||
exit 1
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--gate) GATE="$2"; shift 2 ;;
|
||||
--details) DETAILS="$2"; shift 2 ;;
|
||||
--severity) SEVERITY="$2"; shift 2 ;;
|
||||
--workflow) WORKFLOW="$2"; shift 2 ;;
|
||||
--repo) REPO="$2"; shift 2 ;;
|
||||
--run-url) RUN_URL="$2"; shift 2 ;;
|
||||
--token) GITEA_TOKEN="$2"; shift 2 ;;
|
||||
--url) GITEA_URL="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "Unknown option: $1"; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -z "$GATE" ]] && { echo "ERROR: --gate is required"; usage; }
|
||||
[[ -z "$DETAILS" ]] && { echo "ERROR: --details is required"; usage; }
|
||||
[[ -z "$GITEA_TOKEN" ]] && { echo "ERROR: GITEA_TOKEN not set"; exit 1; }
|
||||
[[ -z "$REPO" ]] && { echo "ERROR: GITHUB_REPOSITORY not set"; exit 1; }
|
||||
|
||||
API="${GITEA_URL}/api/v1/repos/${REPO}"
|
||||
|
||||
# ── Build title ─────────────────────────────────────────────────────────────
|
||||
if [[ -n "$WORKFLOW" ]]; then
|
||||
TITLE="[CI] ${WORKFLOW}: ${GATE} failed"
|
||||
else
|
||||
TITLE="[CI] ${GATE} failed"
|
||||
fi
|
||||
|
||||
# ── Ensure label exists ─────────────────────────────────────────────────────
|
||||
ensure_label() {
|
||||
local exists
|
||||
exists=$(curl -sf -o /dev/null -w '%{http_code}' \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
"${API}/labels" 2>/dev/null || echo "000")
|
||||
|
||||
if [[ "$exists" == "200" ]]; then
|
||||
# Check if label already exists
|
||||
local found
|
||||
found=$(curl -sf \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
"${API}/labels" 2>/dev/null \
|
||||
| grep -o "\"name\":\"${LABEL_NAME}\"" || true)
|
||||
|
||||
if [[ -z "$found" ]]; then
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${API}/labels" \
|
||||
-d "{\"name\":\"${LABEL_NAME}\",\"color\":\"${LABEL_COLOR}\",\"description\":\"Auto-created by CI issue reporter\"}" \
|
||||
> /dev/null 2>&1 || true
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# ── Search for existing open issue ──────────────────────────────────────────
|
||||
find_existing_issue() {
|
||||
# URL-encode the gate name for the query
|
||||
local query
|
||||
query=$(printf '%s' "[CI] ${GATE}" | sed 's/ /%20/g; s/\[/%5B/g; s/\]/%5D/g')
|
||||
|
||||
local response
|
||||
response=$(curl -sf \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
"${API}/issues?type=issues&state=open&labels=${LABEL_NAME}&q=${query}&limit=5" \
|
||||
2>/dev/null || echo "[]")
|
||||
|
||||
# Extract the first matching issue number
|
||||
echo "$response" \
|
||||
| grep -oP '"number":\s*\K[0-9]+' \
|
||||
| head -1
|
||||
}
|
||||
|
||||
# ── Build issue body ────────────────────────────────────────────────────────
|
||||
build_body() {
|
||||
local severity_badge
|
||||
if [[ "$SEVERITY" == "error" ]]; then
|
||||
severity_badge="**Severity:** Error"
|
||||
else
|
||||
severity_badge="**Severity:** Warning"
|
||||
fi
|
||||
|
||||
cat <<BODY
|
||||
## CI Gate Failure: ${GATE}
|
||||
|
||||
${severity_badge}
|
||||
**Workflow:** ${WORKFLOW:-unknown}
|
||||
**Branch:** ${GITHUB_REF_NAME:-unknown}
|
||||
**Commit:** \`${GITHUB_SHA:0:8}\`
|
||||
**Run:** [View CI run](${RUN_URL})
|
||||
|
||||
### Details
|
||||
|
||||
${DETAILS}
|
||||
|
||||
### Resolution
|
||||
|
||||
Fix the issue described above and push a new commit. This issue will be closed automatically when the gate passes, or can be closed manually.
|
||||
|
||||
---
|
||||
*Auto-created by [ci-issue-reporter](${GITEA_URL}/${REPO}/src/branch/main/automation/ci-issue-reporter.sh)*
|
||||
BODY
|
||||
}
|
||||
|
||||
# ── Build comment body (for existing issues) ────────────────────────────────
|
||||
build_comment() {
|
||||
cat <<COMMENT
|
||||
### CI failure recurrence
|
||||
|
||||
**Branch:** ${GITHUB_REF_NAME:-unknown}
|
||||
**Commit:** \`${GITHUB_SHA:0:8}\`
|
||||
**Run:** [View CI run](${RUN_URL})
|
||||
|
||||
${DETAILS}
|
||||
COMMENT
|
||||
}
|
||||
|
||||
# ── Main ────────────────────────────────────────────────────────────────────
|
||||
ensure_label
|
||||
|
||||
EXISTING=$(find_existing_issue)
|
||||
|
||||
if [[ -n "$EXISTING" ]]; then
|
||||
# Append comment to existing issue
|
||||
COMMENT_BODY=$(build_comment)
|
||||
COMMENT_JSON=$(printf '%s' "$COMMENT_BODY" | python3 -c "
|
||||
import sys, json
|
||||
print(json.dumps({'body': sys.stdin.read()}))" 2>/dev/null)
|
||||
|
||||
HTTP=$(curl -sf -o /dev/null -w '%{http_code}' -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${API}/issues/${EXISTING}/comments" \
|
||||
-d "${COMMENT_JSON}" 2>/dev/null || echo "000")
|
||||
|
||||
if [[ "$HTTP" == "201" ]]; then
|
||||
echo "Commented on existing issue #${EXISTING}"
|
||||
else
|
||||
echo "WARNING: Failed to comment on issue #${EXISTING} (HTTP ${HTTP})"
|
||||
fi
|
||||
else
|
||||
# Create new issue
|
||||
ISSUE_BODY=$(build_body)
|
||||
ISSUE_JSON=$(python3 -c "
|
||||
import sys, json
|
||||
body = sys.stdin.read()
|
||||
print(json.dumps({
|
||||
'title': sys.argv[1],
|
||||
'body': body,
|
||||
'labels': []
|
||||
}))" "$TITLE" <<< "$ISSUE_BODY" 2>/dev/null)
|
||||
|
||||
# Create the issue
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${API}/issues" \
|
||||
-d "${ISSUE_JSON}" 2>/dev/null || echo "{}")
|
||||
|
||||
ISSUE_NUM=$(echo "$RESPONSE" | grep -oP '"number":\s*\K[0-9]+' | head -1)
|
||||
|
||||
if [[ -n "$ISSUE_NUM" ]]; then
|
||||
# Apply label (separate call — more reliable across Gitea versions)
|
||||
LABEL_ID=$(curl -sf \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
"${API}/labels" 2>/dev/null \
|
||||
| grep -oP "\"id\":\s*\K[0-9]+(?=[^}]*\"name\":\s*\"${LABEL_NAME}\")" \
|
||||
| head -1 || true)
|
||||
|
||||
if [[ -n "$LABEL_ID" ]]; then
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${API}/issues/${ISSUE_NUM}/labels" \
|
||||
-d "{\"labels\":[${LABEL_ID}]}" \
|
||||
> /dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
echo "Created issue #${ISSUE_NUM}: ${TITLE}"
|
||||
else
|
||||
echo "WARNING: Failed to create issue"
|
||||
echo "Response: ${RESPONSE}"
|
||||
fi
|
||||
fi
|
||||
@@ -1,31 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
* @package 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
|
||||
-->
|
||||
<extension type="plugin" group="webservices" method="upgrade">
|
||||
<name>Web Services - MokoSuiteBackup</name>
|
||||
<version>01.26.00</version>
|
||||
<creationDate>2026-06-02</creationDate>
|
||||
<author>Moko Consulting</author>
|
||||
<authorEmail>hello@mokoconsulting.tech</authorEmail>
|
||||
<authorUrl>https://mokoconsulting.tech</authorUrl>
|
||||
<copyright>Copyright (C) 2026 Moko Consulting. All rights reserved.</copyright>
|
||||
<license>GPL-3.0-or-later</license>
|
||||
<description>PLG_WEBSERVICES_MOKOJOOMBACKUP_DESCRIPTION</description>
|
||||
|
||||
<namespace path="src">Joomla\Plugin\WebServices\MokoSuiteBackup</namespace>
|
||||
|
||||
<files>
|
||||
<filename plugin="mokosuitebackup">mokosuitebackup.php</filename>
|
||||
<folder>services</folder>
|
||||
<folder>src</folder>
|
||||
</files>
|
||||
|
||||
<languages>
|
||||
<language tag="en-GB">language/en-GB/plg_webservices_mokosuitebackup.ini</language>
|
||||
<language tag="en-GB">language/en-GB/plg_webservices_mokosuitebackup.sys.ini</language>
|
||||
</languages>
|
||||
</extension>
|
||||
@@ -1 +0,0 @@
|
||||
<!DOCTYPE html><title></title>
|
||||
Submodule
+1
Submodule source/packages/MokoSuiteClient added at f0a8ad6c39
@@ -12,5 +12,8 @@
|
||||
<action name="mokosuitebackup.backup.download" title="COM_MOKOSUITEBACKUP_ACTION_BACKUP_DOWNLOAD" />
|
||||
<action name="mokosuitebackup.backup.restore" title="COM_MOKOSUITEBACKUP_ACTION_BACKUP_RESTORE" />
|
||||
<action name="mokosuitebackup.snapshot.manage" title="COM_MOKOSUITEBACKUP_ACTION_SNAPSHOT_MANAGE" />
|
||||
<action name="mokosuitebackup.backup.purge" title="COM_MOKOSUITEBACKUP_ACTION_BACKUP_PURGE" />
|
||||
<action name="mokosuitebackup.backup.compare" title="COM_MOKOSUITEBACKUP_ACTION_BACKUP_COMPARE" />
|
||||
<action name="mokosuitebackup.backup.browse" title="COM_MOKOSUITEBACKUP_ACTION_BACKUP_BROWSE" />
|
||||
</section>
|
||||
</access>
|
||||
|
||||
@@ -121,11 +121,28 @@ class BackupsController extends ApiController
|
||||
|
||||
$data = [];
|
||||
|
||||
// Strip sensitive credentials before serialization
|
||||
$sensitiveFields = [
|
||||
'ftp_password', 'ftp_username',
|
||||
'sftp_password', 'sftp_key_data', 'sftp_passphrase',
|
||||
's3_access_key', 's3_secret_key',
|
||||
'gdrive_client_secret', 'gdrive_refresh_token',
|
||||
'encryption_password', 'ntfy_token',
|
||||
];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$safe = clone $item;
|
||||
|
||||
foreach ($sensitiveFields as $field) {
|
||||
if (isset($safe->$field) && $safe->$field !== '') {
|
||||
$safe->$field = '***';
|
||||
}
|
||||
}
|
||||
|
||||
$data[] = [
|
||||
'type' => 'profiles',
|
||||
'id' => $item->id,
|
||||
'attributes' => $item,
|
||||
'id' => $safe->id,
|
||||
'attributes' => $safe,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
<?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
|
||||
*
|
||||
* REST API controller for content snapshot operations.
|
||||
*
|
||||
* Endpoints:
|
||||
* GET /api/index.php/v1/mokosuitebackup/snapshots — List snapshots
|
||||
* POST /api/index.php/v1/mokosuitebackup/snapshot — Create snapshot
|
||||
* POST /api/index.php/v1/mokosuitebackup/snapshot/:id/restore — Restore snapshot
|
||||
* DELETE /api/index.php/v1/mokosuitebackup/snapshot/:id — Delete snapshot
|
||||
* GET /api/index.php/v1/mokosuitebackup/snapshot/:id/download — Download snapshot JSON
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Api\Controller;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
use Joomla\CMS\MVC\Controller\ApiController;
|
||||
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotEngine;
|
||||
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\SnapshotRestoreEngine;
|
||||
|
||||
class SnapshotsController extends ApiController
|
||||
{
|
||||
protected $contentType = 'snapshots';
|
||||
protected $default_view = 'snapshots';
|
||||
|
||||
/**
|
||||
* List all snapshots with pagination (GET /api/index.php/v1/mokosuitebackup/snapshots)
|
||||
*/
|
||||
public function displayList(): 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;
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
$limit = $this->input->getInt('limit', 20);
|
||||
$offset = $this->input->getInt('offset', 0);
|
||||
|
||||
// Clamp limits
|
||||
$limit = max(1, min($limit, 100));
|
||||
$offset = max(0, $offset);
|
||||
|
||||
// Get total count
|
||||
$countQuery = $db->getQuery(true)
|
||||
->select('COUNT(*)')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'));
|
||||
$db->setQuery($countQuery);
|
||||
$total = (int) $db->loadResult();
|
||||
|
||||
// Get paginated results
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->order($db->quoteName('created') . ' DESC');
|
||||
$db->setQuery($query, $offset, $limit);
|
||||
$items = $db->loadObjectList() ?: [];
|
||||
|
||||
$data = [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$data[] = [
|
||||
'type' => 'snapshots',
|
||||
'id' => $item->id,
|
||||
'attributes' => $item,
|
||||
];
|
||||
}
|
||||
|
||||
$this->app->setHeader('status', 200);
|
||||
echo json_encode([
|
||||
'data' => $data,
|
||||
'meta' => [
|
||||
'total' => $total,
|
||||
'limit' => $limit,
|
||||
'offset' => $offset,
|
||||
],
|
||||
]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new content snapshot (POST /api/index.php/v1/mokosuitebackup/snapshot)
|
||||
*/
|
||||
public function create(): 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;
|
||||
}
|
||||
|
||||
$data = json_decode($this->input->json->getRaw(), true) ?: [];
|
||||
|
||||
$contentTypes = $data['content_types'] ?? [];
|
||||
$description = $data['description'] ?? '';
|
||||
|
||||
if (empty($contentTypes) || !is_array($contentTypes)) {
|
||||
$this->app->setHeader('status', 400);
|
||||
echo json_encode(['errors' => [['title' => 'content_types array is required']]]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$engine = new SnapshotEngine();
|
||||
$result = $engine->create($contentTypes, $description);
|
||||
|
||||
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']]]]);
|
||||
}
|
||||
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore from a snapshot (POST /api/index.php/v1/mokosuitebackup/snapshot/:id/restore)
|
||||
*/
|
||||
public function restore(): 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;
|
||||
}
|
||||
|
||||
$id = $this->input->getInt('id', 0);
|
||||
|
||||
if (!$id) {
|
||||
$this->app->setHeader('status', 400);
|
||||
echo json_encode(['errors' => [['title' => 'Snapshot ID is required']]]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$data = json_decode($this->input->json->getRaw(), true) ?: [];
|
||||
|
||||
$mode = $data['mode'] ?? 'replace';
|
||||
$contentTypes = $data['content_types'] ?? [];
|
||||
|
||||
// Enforce valid restore mode
|
||||
if (!in_array($mode, ['replace', 'merge'], true)) {
|
||||
$mode = 'replace';
|
||||
}
|
||||
|
||||
$engine = new SnapshotRestoreEngine();
|
||||
$result = $engine->restore($id, $mode, $contentTypes);
|
||||
|
||||
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']]]]);
|
||||
}
|
||||
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a snapshot record and its data file (DELETE /api/index.php/v1/mokosuitebackup/snapshot/:id)
|
||||
*/
|
||||
public function delete(): 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;
|
||||
}
|
||||
|
||||
$id = $this->input->getInt('id', 0);
|
||||
|
||||
if (!$id) {
|
||||
$this->app->setHeader('status', 400);
|
||||
echo json_encode(['errors' => [['title' => 'Snapshot ID is required']]]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
// Load record to get file path
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->where($db->quoteName('id') . ' = ' . $id);
|
||||
$db->setQuery($query);
|
||||
$record = $db->loadObject();
|
||||
|
||||
if (!$record) {
|
||||
$this->app->setHeader('status', 404);
|
||||
echo json_encode(['errors' => [['title' => 'Snapshot not found']]]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
// Delete data file
|
||||
if ($record->data_file && is_file($record->data_file)) {
|
||||
if (!unlink($record->data_file)) {
|
||||
error_log('MokoSuiteBackup: Failed to delete snapshot file: ' . $record->data_file);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete record
|
||||
$query = $db->getQuery(true)
|
||||
->delete($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->where($db->quoteName('id') . ' = ' . $id);
|
||||
$db->setQuery($query);
|
||||
$db->execute();
|
||||
|
||||
$this->app->setHeader('status', 200);
|
||||
echo json_encode(['data' => ['success' => true, 'message' => 'Snapshot deleted']]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream the JSON snapshot file (GET /api/index.php/v1/mokosuitebackup/snapshot/:id/download)
|
||||
*/
|
||||
public function download(): 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;
|
||||
}
|
||||
|
||||
$id = $this->input->getInt('id', 0);
|
||||
|
||||
if (!$id) {
|
||||
$this->app->setHeader('status', 400);
|
||||
echo json_encode(['errors' => [['title' => 'Snapshot ID is required']]]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->where($db->quoteName('id') . ' = ' . $id);
|
||||
$db->setQuery($query);
|
||||
$record = $db->loadObject();
|
||||
|
||||
if (!$record || !is_file($record->data_file) || !is_readable($record->data_file)) {
|
||||
$this->app->setHeader('status', 404);
|
||||
echo json_encode(['errors' => [['title' => 'Snapshot file not found']]]);
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
// Stream as download
|
||||
while (@ob_end_clean()) {
|
||||
// clear all buffers
|
||||
}
|
||||
|
||||
$filename = basename($record->data_file);
|
||||
$filesize = filesize($record->data_file);
|
||||
|
||||
header('Content-Type: application/json');
|
||||
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename));
|
||||
header('Content-Length: ' . $filesize);
|
||||
header('Cache-Control: no-cache, must-revalidate');
|
||||
|
||||
readfile($record->data_file);
|
||||
|
||||
$this->app->close();
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@
|
||||
type="sql"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_PROFILE"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_PROFILE_DESC"
|
||||
query="SELECT id AS value, CONCAT(title, ' (#', id, ')') AS text FROM #__mokosuitebackup_profiles WHERE published = 1 ORDER BY ordering ASC"
|
||||
query="SELECT id AS value, CONCAT(title, ' (#', id, ')') AS text FROM #__mokosuitebackup_profiles WHERE published = 1 ORDER BY id ASC"
|
||||
default="1"
|
||||
>
|
||||
<option value="1">Default Backup Profile (#1)</option>
|
||||
@@ -39,6 +39,73 @@
|
||||
</field>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="defaults" label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULTS">
|
||||
<field
|
||||
name="default_archive_format"
|
||||
type="list"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_FORMAT"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_FORMAT_DESC"
|
||||
default="zip"
|
||||
>
|
||||
<option value="zip">ZIP</option>
|
||||
<option value="tar.gz">tar.gz</option>
|
||||
<option value="7z">7z</option>
|
||||
</field>
|
||||
<field
|
||||
name="default_mokorestore"
|
||||
type="list"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_MOKORESTORE"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_MOKORESTORE_DESC"
|
||||
default="0"
|
||||
>
|
||||
<option value="0">COM_MOKOJOOMBACKUP_MOKORESTORE_NONE</option>
|
||||
<option value="1">COM_MOKOJOOMBACKUP_MOKORESTORE_WRAPPED</option>
|
||||
<option value="standalone">COM_MOKOJOOMBACKUP_MOKORESTORE_STANDALONE</option>
|
||||
</field>
|
||||
<field
|
||||
name="default_sanitize_passwords"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_PW"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_PW_DESC"
|
||||
default="0"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
<field
|
||||
name="default_sanitize_emails"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_EMAIL"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_EMAIL_DESC"
|
||||
default="0"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
<field
|
||||
name="default_sanitize_sessions"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_SESS"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_SESS_DESC"
|
||||
default="1"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
<field
|
||||
name="log_retention_days"
|
||||
type="number"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_LOG_RETENTION"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_LOG_RETENTION_DESC"
|
||||
default="90"
|
||||
min="0"
|
||||
max="365"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="webcron" label="COM_MOKOJOOMBACKUP_CONFIG_WEBCRON">
|
||||
<field
|
||||
name="webcron_secret"
|
||||
@@ -118,6 +185,27 @@
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="snapshot_cleanup" label="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_RETENTION">
|
||||
<field
|
||||
name="snapshot_retention_count"
|
||||
type="number"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_COUNT"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_COUNT_DESC"
|
||||
default="20"
|
||||
min="0"
|
||||
max="100"
|
||||
/>
|
||||
<field
|
||||
name="snapshot_retention_days"
|
||||
type="number"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_AGE"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_AGE_DESC"
|
||||
default="30"
|
||||
min="0"
|
||||
max="365"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="notifications" label="COM_MOKOJOOMBACKUP_CONFIG_NOTIFICATIONS">
|
||||
<field
|
||||
name="notify_email"
|
||||
@@ -151,6 +239,32 @@
|
||||
</field>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="ntfy" label="COM_MOKOJOOMBACKUP_CONFIG_NTFY">
|
||||
<field
|
||||
name="ntfy_server"
|
||||
type="text"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_NTFY_SERVER"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_NTFY_SERVER_DESC"
|
||||
default="https://ntfy.mokoconsulting.tech"
|
||||
filter="url"
|
||||
/>
|
||||
<field
|
||||
name="ntfy_topic"
|
||||
type="text"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOPIC"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOPIC_DESC"
|
||||
default=""
|
||||
filter="string"
|
||||
/>
|
||||
<field
|
||||
name="ntfy_token"
|
||||
type="password"
|
||||
label="COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOKEN"
|
||||
description="COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOKEN_DESC"
|
||||
default=""
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="permissions" label="JCONFIG_PERMISSIONS_LABEL"
|
||||
description="JCONFIG_PERMISSIONS_DESC">
|
||||
<field
|
||||
|
||||
@@ -19,6 +19,18 @@
|
||||
<option value="fail">COM_MOKOJOOMBACKUP_STATUS_FAIL</option>
|
||||
<option value="pending">COM_MOKOJOOMBACKUP_STATUS_PENDING</option>
|
||||
</field>
|
||||
<field
|
||||
name="backup_type"
|
||||
type="list"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_BACKUP_TYPE"
|
||||
onchange="this.form.submit();"
|
||||
>
|
||||
<option value="">COM_MOKOJOOMBACKUP_FILTER_TYPE_ALL</option>
|
||||
<option value="full">COM_MOKOJOOMBACKUP_TYPE_FULL</option>
|
||||
<option value="database">COM_MOKOJOOMBACKUP_TYPE_DATABASE</option>
|
||||
<option value="files">COM_MOKOJOOMBACKUP_TYPE_FILES</option>
|
||||
<option value="differential">COM_MOKOJOOMBACKUP_TYPE_DIFFERENTIAL</option>
|
||||
</field>
|
||||
</fields>
|
||||
|
||||
<fields name="list">
|
||||
|
||||
@@ -24,10 +24,9 @@
|
||||
name="fullordering"
|
||||
type="list"
|
||||
label="JGLOBAL_SORT_BY"
|
||||
default="a.ordering ASC"
|
||||
default="a.id ASC"
|
||||
onchange="this.form.submit();"
|
||||
>
|
||||
<option value="a.ordering ASC">JFIELD_ORDERING_LABEL_ASC</option>
|
||||
<option value="a.title ASC">COM_MOKOJOOMBACKUP_HEADING_TITLE_ASC</option>
|
||||
<option value="a.title DESC">COM_MOKOJOOMBACKUP_HEADING_TITLE_DESC</option>
|
||||
<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
>
|
||||
<option value="zip">ZIP</option>
|
||||
<option value="tar.gz">tar.gz</option>
|
||||
<option value="7z">COM_MOKOJOOMBACKUP_FORMAT_7Z</option>
|
||||
</field>
|
||||
<field
|
||||
name="compression_level"
|
||||
@@ -72,24 +73,36 @@
|
||||
/>
|
||||
<field
|
||||
name="archive_name_format"
|
||||
type="text"
|
||||
type="PlaceholderText"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_NAME_FORMAT"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_NAME_FORMAT_DESC"
|
||||
default="[host]_[datetime]_profile[profile_id]"
|
||||
default="[HOST]_[DATETIME]_profile[PROFILE_ID]"
|
||||
maxlength="512"
|
||||
hint="[host]_[datetime]_profile[profile_id]"
|
||||
hint="[HOST]_[DATETIME]_profile[PROFILE_ID]"
|
||||
placeholders="[HOST],[DATETIME],[DATE],[TIME],[YEAR],[MONTH],[DAY],[HOUR],[MINUTE],[SECOND],[PROFILE_ID],[PROFILE_NAME],[SITE_NAME],[TYPE],[RANDOM]"
|
||||
addfieldprefix="Joomla\Component\MokoSuiteBackup\Administrator\Field"
|
||||
/>
|
||||
<field
|
||||
name="include_mokorestore"
|
||||
type="radio"
|
||||
type="list"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_INCLUDE_MOKORESTORE"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_INCLUDE_MOKORESTORE_DESC"
|
||||
default="0"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
<option value="0">COM_MOKOJOOMBACKUP_MOKORESTORE_NONE</option>
|
||||
<option value="1">COM_MOKOJOOMBACKUP_MOKORESTORE_WRAPPED</option>
|
||||
<option value="standalone">COM_MOKOJOOMBACKUP_MOKORESTORE_STANDALONE</option>
|
||||
</field>
|
||||
<field
|
||||
name="restore_script_name"
|
||||
type="text"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_RESTORE_SCRIPT_NAME"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_RESTORE_SCRIPT_NAME_DESC"
|
||||
default="restore.php"
|
||||
maxlength="128"
|
||||
filter="string"
|
||||
showon="include_mokorestore!:0"
|
||||
/>
|
||||
<field
|
||||
name="encryption_password"
|
||||
type="password"
|
||||
@@ -99,6 +112,54 @@
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="sanitization" label="COM_MOKOJOOMBACKUP_FIELDSET_SANITIZATION">
|
||||
<field
|
||||
name="sanitize_passwords"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SANITIZE_PASSWORDS"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SANITIZE_PASSWORDS_DESC"
|
||||
default="0"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
<field
|
||||
name="preserve_super_admin"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_PRESERVE_SUPER_ADMIN"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_PRESERVE_SUPER_ADMIN_DESC"
|
||||
default="1"
|
||||
class="btn-group"
|
||||
showon="sanitize_passwords:1"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
<field
|
||||
name="sanitize_emails"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SANITIZE_EMAILS"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SANITIZE_EMAILS_DESC"
|
||||
default="0"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
<field
|
||||
name="sanitize_sessions"
|
||||
type="radio"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SANITIZE_SESSIONS"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SANITIZE_SESSIONS_DESC"
|
||||
default="1"
|
||||
class="btn-group"
|
||||
>
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="sidebar" label="COM_MOKOJOOMBACKUP_FIELDSET_STATUS">
|
||||
<field
|
||||
name="id"
|
||||
@@ -113,12 +174,6 @@
|
||||
<option value="1">JPUBLISHED</option>
|
||||
<option value="0">JUNPUBLISHED</option>
|
||||
</field>
|
||||
<field
|
||||
name="ordering"
|
||||
type="number"
|
||||
label="JFIELD_ORDERING_LABEL"
|
||||
default="0"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="filters" label="COM_MOKOJOOMBACKUP_FIELDSET_FILTERS">
|
||||
@@ -151,6 +206,13 @@
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="remote" label="COM_MOKOJOOMBACKUP_FIELDSET_REMOTE">
|
||||
<field
|
||||
name="remote_legacy_note"
|
||||
type="note"
|
||||
label=""
|
||||
description="COM_MOKOJOOMBACKUP_REMOTE_LEGACY_NOTE"
|
||||
class="alert alert-info small"
|
||||
/>
|
||||
<field
|
||||
name="remote_storage"
|
||||
type="list"
|
||||
@@ -159,7 +221,7 @@
|
||||
default="none"
|
||||
>
|
||||
<option value="none">COM_MOKOJOOMBACKUP_REMOTE_NONE</option>
|
||||
<option value="ftp">COM_MOKOJOOMBACKUP_REMOTE_FTP</option>
|
||||
<option value="sftp">COM_MOKOJOOMBACKUP_REMOTE_SFTP</option>
|
||||
<option value="google_drive">COM_MOKOJOOMBACKUP_REMOTE_GDRIVE</option>
|
||||
<option value="s3">COM_MOKOJOOMBACKUP_REMOTE_S3</option>
|
||||
</field>
|
||||
@@ -174,6 +236,81 @@
|
||||
<option value="1">JYES</option>
|
||||
<option value="0">JNO</option>
|
||||
</field>
|
||||
|
||||
<!-- SFTP fields (shown when remote_storage = sftp) -->
|
||||
<field
|
||||
name="sftp_host"
|
||||
type="text"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_HOST"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_HOST_DESC"
|
||||
maxlength="255"
|
||||
showon="remote_storage:sftp"
|
||||
/>
|
||||
<field
|
||||
name="sftp_port"
|
||||
type="number"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_PORT"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_PORT_DESC"
|
||||
default="22"
|
||||
min="1"
|
||||
max="65535"
|
||||
showon="remote_storage:sftp"
|
||||
/>
|
||||
<field
|
||||
name="sftp_username"
|
||||
type="text"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_USERNAME"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_USERNAME_DESC"
|
||||
maxlength="255"
|
||||
showon="remote_storage:sftp"
|
||||
/>
|
||||
<field
|
||||
name="sftp_auth_type"
|
||||
type="list"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_AUTH_TYPE"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_AUTH_TYPE_DESC"
|
||||
default="key"
|
||||
showon="remote_storage:sftp"
|
||||
>
|
||||
<option value="password">COM_MOKOJOOMBACKUP_SFTP_AUTH_PASSWORD</option>
|
||||
<option value="key">COM_MOKOJOOMBACKUP_SFTP_AUTH_KEY</option>
|
||||
<option value="key_passphrase">COM_MOKOJOOMBACKUP_SFTP_AUTH_KEY_PASSPHRASE</option>
|
||||
</field>
|
||||
<field
|
||||
name="sftp_password"
|
||||
type="password"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSWORD"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSWORD_DESC"
|
||||
maxlength="255"
|
||||
showon="remote_storage:sftp[AND]sftp_auth_type:password"
|
||||
/>
|
||||
<field
|
||||
name="sftp_key_data"
|
||||
type="SshKey"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_DESC"
|
||||
filter="raw"
|
||||
showon="remote_storage:sftp[AND]sftp_auth_type:key,key_passphrase"
|
||||
addfieldprefix="Joomla\Component\MokoSuiteBackup\Administrator\Field"
|
||||
/>
|
||||
<field
|
||||
name="sftp_passphrase"
|
||||
type="password"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSPHRASE"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSPHRASE_DESC"
|
||||
maxlength="255"
|
||||
showon="remote_storage:sftp[AND]sftp_auth_type:key_passphrase"
|
||||
/>
|
||||
<field
|
||||
name="sftp_path"
|
||||
type="SftpPath"
|
||||
label="COM_MOKOJOOMBACKUP_FIELD_SFTP_PATH"
|
||||
description="COM_MOKOJOOMBACKUP_FIELD_SFTP_PATH_DESC"
|
||||
default="/backups"
|
||||
maxlength="512"
|
||||
showon="remote_storage:sftp"
|
||||
addfieldprefix="Joomla\Component\MokoSuiteBackup\Administrator\Field"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
<fieldset name="retention" label="COM_MOKOJOOMBACKUP_FIELDSET_RETENTION">
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
; @license GPL-3.0-or-later
|
||||
|
||||
COM_MOKOJOOMBACKUP="MokoSuiteBackup"
|
||||
COM_MOKOJOOMBACKUP_CONFIGURATION="MokoSuiteBackup Options"
|
||||
COM_MOKOJOOMBACKUP_DESCRIPTION="Full-site backup and restore for Joomla"
|
||||
|
||||
; Submenu
|
||||
@@ -33,8 +34,16 @@ COM_MOKOJOOMBACKUP_DASHBOARD_QUICK_ACTIONS="Quick Actions"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_SCHEDULED_TASKS="Scheduled Tasks"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_UPDATE_SITE="Update Site"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_SYSTEM_HEALTH="System Health"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_SNAPSHOTS="Content Snapshots"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_VIEW_ALL="View All"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_LATEST_SNAPSHOT="Latest"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_NO_SNAPSHOTS="No snapshots yet. Create one from the Content Snapshots view."
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_STORAGE_BREAKDOWN="Storage by Profile"
|
||||
COM_MOKOJOOMBACKUP_DASHBOARD_BACKUP_TREND="Backup Trend (30 days)"
|
||||
|
||||
; Backups view
|
||||
COM_MOKOJOOMBACKUP_BACKUPS_N_ITEMS_DELETED="%d backup records deleted."
|
||||
COM_MOKOJOOMBACKUP_BACKUPS_N_ITEMS_DELETED_1="%d backup record deleted."
|
||||
COM_MOKOJOOMBACKUP_BACKUPS_TITLE="Backup Records"
|
||||
COM_MOKOJOOMBACKUP_BACKUPS_TABLE_CAPTION="Table of backup records"
|
||||
COM_MOKOJOOMBACKUP_NO_BACKUPS="No backups found. Click 'Backup Now' to create your first backup."
|
||||
@@ -44,6 +53,22 @@ COM_MOKOJOOMBACKUP_DOWNLOAD="Download"
|
||||
; Backup detail view
|
||||
COM_MOKOJOOMBACKUP_BACKUP_DETAIL="Backup Detail"
|
||||
COM_MOKOJOOMBACKUP_VIEW_LOG="Backup Log"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_ARCHIVE="Browse Archive Contents"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_COL_NAME="Name"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_COL_SIZE="Size"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_COL_COMPRESSED="Compressed"
|
||||
; Backup comparison
|
||||
COM_MOKOJOOMBACKUP_TOOLBAR_COMPARE="Compare"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_TITLE="Backup Comparison"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_LOADING="Loading comparison..."
|
||||
COM_MOKOJOOMBACKUP_COMPARE_FIELD="Field"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_BACKUP="Backup"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_DELTA="Delta"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_DB_SIZE="DB Size"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_FILES_COUNT="Files Count"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_TABLES_COUNT="Tables Count"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_DURATION="Duration"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_SELECT_TWO="Please select exactly two backup records to compare."
|
||||
COM_MOKOJOOMBACKUP_FIELD_CHECKSUM="SHA-256 Checksum"
|
||||
COM_MOKOJOOMBACKUP_FIELD_PATH="File Path"
|
||||
COM_MOKOJOOMBACKUP_FIELD_DB_SIZE="DB Size"
|
||||
@@ -56,6 +81,12 @@ COM_MOKOJOOMBACKUP_NO_PROFILES="No backup profiles found."
|
||||
COM_MOKOJOOMBACKUP_PROFILE_NEW="New Profile"
|
||||
COM_MOKOJOOMBACKUP_PROFILE_EDIT="Edit Profile"
|
||||
|
||||
; Profile actions
|
||||
COM_MOKOJOOMBACKUP_RUN_BACKUP="Run"
|
||||
COM_MOKOJOOMBACKUP_RUN_BACKUP_NOW="Run Backup Now"
|
||||
COM_MOKOJOOMBACKUP_VIEW_BACKUPS="View Backups"
|
||||
COM_MOKOJOOMBACKUP_HEADING_BACKUPS="Backups"
|
||||
|
||||
; Table headings
|
||||
COM_MOKOJOOMBACKUP_HEADING_DESCRIPTION="Description"
|
||||
COM_MOKOJOOMBACKUP_HEADING_PROFILE="Profile"
|
||||
@@ -91,6 +122,7 @@ COM_MOKOJOOMBACKUP_FIELD_TABLES_COUNT="Tables Count"
|
||||
; Archive settings
|
||||
COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_FORMAT="Archive Format"
|
||||
COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_FORMAT_DESC="Format for the backup archive file"
|
||||
COM_MOKOJOOMBACKUP_FORMAT_7Z="7z (requires 7za CLI)"
|
||||
COM_MOKOJOOMBACKUP_FIELD_COMPRESSION="Compression Level"
|
||||
COM_MOKOJOOMBACKUP_FIELD_COMPRESSION_DESC="Higher compression = smaller file but slower"
|
||||
COM_MOKOJOOMBACKUP_COMPRESSION_NONE="None (fastest)"
|
||||
@@ -98,15 +130,31 @@ COM_MOKOJOOMBACKUP_COMPRESSION_FASTEST="Low (fast)"
|
||||
COM_MOKOJOOMBACKUP_COMPRESSION_NORMAL="Normal (balanced)"
|
||||
COM_MOKOJOOMBACKUP_COMPRESSION_BEST="Maximum (smallest)"
|
||||
COM_MOKOJOOMBACKUP_FIELD_ENCRYPTION_PASSWORD="Encryption Password"
|
||||
COM_MOKOJOOMBACKUP_FIELD_ENCRYPTION_PASSWORD_DESC="Set a password to encrypt the backup archive with AES-256. Leave blank for no encryption. Required to restore encrypted backups."
|
||||
COM_MOKOJOOMBACKUP_FIELD_ENCRYPTION_PASSWORD_DESC="AES-256 encryption password. Leave blank for no encryption. Required to restore."
|
||||
COM_MOKOJOOMBACKUP_FIELD_SPLIT_SIZE="Split Size (MB)"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SPLIT_SIZE_DESC="Split archive into parts of this size in MB. 0 = no splitting."
|
||||
COM_MOKOJOOMBACKUP_FIELD_BACKUP_DIR="Backup Directory"
|
||||
COM_MOKOJOOMBACKUP_FIELD_BACKUP_DIR_DESC="Directory where backup archives are stored. Supports placeholders: [HOME] (user home directory), [host], [date], [year], [month], [day], [profile_name], [site_name], [type]. Use [HOME]/backups to store outside the web root. Absolute paths (starting with /) are used as-is; relative paths resolve from the Joomla root."
|
||||
COM_MOKOJOOMBACKUP_FIELD_BACKUP_DIR_DESC="Where backups are stored. Use placeholders like [HOME]/backups for portability. Click the ? icon for full documentation."
|
||||
COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_NAME_FORMAT="Archive Name Format"
|
||||
COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_NAME_FORMAT_DESC="Filename template for backup archives (without extension). Placeholders: [host] hostname, [date] Ymd, [time] His, [datetime] Ymd_His, [year] [month] [day] [hour] [minute] [second], [profile_id], [profile_name], [site_name], [type], [random]."
|
||||
COM_MOKOJOOMBACKUP_FIELD_INCLUDE_MOKORESTORE="Include Restore Script"
|
||||
COM_MOKOJOOMBACKUP_FIELD_INCLUDE_MOKORESTORE_DESC="Include MokoRestore (standalone restore.php) inside the backup archive. Creates a self-contained package that can restore the site on a blank server without Joomla installed."
|
||||
COM_MOKOJOOMBACKUP_FIELD_ARCHIVE_NAME_FORMAT_DESC="Filename template (without extension). Click the placeholder buttons below to insert tokens."
|
||||
COM_MOKOJOOMBACKUP_FIELD_INCLUDE_MOKORESTORE="MokoRestore Script"
|
||||
COM_MOKOJOOMBACKUP_FIELD_INCLUDE_MOKORESTORE_DESC="None: no restore script. Wrapped: bundled inside the ZIP. Standalone: separate restore.php file (ideal for remote servers)."
|
||||
COM_MOKOJOOMBACKUP_MOKORESTORE_NONE="None"
|
||||
COM_MOKOJOOMBACKUP_MOKORESTORE_WRAPPED="Wrapped (inside backup ZIP)"
|
||||
COM_MOKOJOOMBACKUP_MOKORESTORE_STANDALONE="Standalone (separate restore.php)"
|
||||
COM_MOKOJOOMBACKUP_FIELD_RESTORE_SCRIPT_NAME="Restore Script Filename"
|
||||
COM_MOKOJOOMBACKUP_FIELD_RESTORE_SCRIPT_NAME_DESC="Custom filename for the restore script. Must end in .php. Use a non-obvious name to reduce discoverability on remote servers (e.g. moko-install-xyz.php)."
|
||||
|
||||
; Data Sanitization
|
||||
COM_MOKOJOOMBACKUP_FIELDSET_SANITIZATION="Data Sanitization"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SANITIZE_PASSWORDS="Sanitize User Passwords"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SANITIZE_PASSWORDS_DESC="Replace password hashes with invalid values. Users must reset passwords after restore. For demos, staging, or GDPR."
|
||||
COM_MOKOJOOMBACKUP_FIELD_PRESERVE_SUPER_ADMIN="Preserve Super Admin Password"
|
||||
COM_MOKOJOOMBACKUP_FIELD_PRESERVE_SUPER_ADMIN_DESC="Keep the password for Super Users (group ID 8) intact. You will still be able to log in as a Super Admin after restoring."
|
||||
COM_MOKOJOOMBACKUP_FIELD_SANITIZE_EMAILS="Sanitize User Emails"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SANITIZE_EMAILS_DESC="Replace emails with dummy values. Prevents accidental emails from cloned sites. Super admin preserved if enabled above."
|
||||
COM_MOKOJOOMBACKUP_FIELD_SANITIZE_SESSIONS="Clear Session Data"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SANITIZE_SESSIONS_DESC="Exclude session data. Logs out all users on restore, prevents session hijacking. Enabled by default."
|
||||
|
||||
; Exclusion filter fields
|
||||
COM_MOKOJOOMBACKUP_FIELD_EXCLUDE_DIRS="Exclude Directories"
|
||||
@@ -167,6 +215,7 @@ COM_MOKOJOOMBACKUP_STATUS_PENDING="Pending"
|
||||
COM_MOKOJOOMBACKUP_FILTER_SEARCH="Search"
|
||||
COM_MOKOJOOMBACKUP_FILTER_STATUS="Status"
|
||||
COM_MOKOJOOMBACKUP_FILTER_STATUS_ALL="- Select Status -"
|
||||
COM_MOKOJOOMBACKUP_FILTER_TYPE_ALL="- Select Type -"
|
||||
|
||||
; Tabs and fieldsets
|
||||
COM_MOKOJOOMBACKUP_TAB_GENERAL="General"
|
||||
@@ -219,7 +268,35 @@ COM_MOKOJOOMBACKUP_VERIFY_FAILED="INTEGRITY CHECK FAILED — archive has been mo
|
||||
COM_MOKOJOOMBACKUP_VERIFY_NO_CHECKSUM="No checksum stored for this backup. Only backups created after this update can be verified."
|
||||
|
||||
; S3 storage
|
||||
COM_MOKOJOOMBACKUP_REMOTE_SFTP="SFTP (SSH File Transfer)"
|
||||
COM_MOKOJOOMBACKUP_REMOTE_S3="Amazon S3 / S3-Compatible"
|
||||
|
||||
; SFTP fields
|
||||
COM_MOKOJOOMBACKUP_FIELDSET_SFTP="SFTP Settings"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_HOST="SFTP Host"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_HOST_DESC="SFTP server hostname or IP address"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PORT="SFTP Port"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PORT_DESC="SSH port (default: 22)"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_USERNAME="SSH Username"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_USERNAME_DESC="Username for SSH authentication"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSWORD="SSH Password"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSWORD_DESC="Password for SSH authentication."
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY="SSH Private Key"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_DESC="Upload your SSH private key (id_rsa, id_ed25519). Stored base64-encoded in DB, written to temp file during upload only."
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_UPLOAD="Upload Key File"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_REPLACE="Replace Key"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_LOADED="Key loaded"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_NONE="No key file"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_CLEAR="Remove Key"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_AUTH_TYPE="Authentication Type"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_AUTH_TYPE_DESC="Choose how to authenticate with the SFTP server."
|
||||
COM_MOKOJOOMBACKUP_SFTP_AUTH_PASSWORD="Password"
|
||||
COM_MOKOJOOMBACKUP_SFTP_AUTH_KEY="Key File"
|
||||
COM_MOKOJOOMBACKUP_SFTP_AUTH_KEY_PASSPHRASE="Key File + Passphrase"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSPHRASE="Key Passphrase"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PASSPHRASE_DESC="Passphrase for the private key, if encrypted. Leave blank for unencrypted keys."
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PATH="Remote Path"
|
||||
COM_MOKOJOOMBACKUP_FIELD_SFTP_PATH_DESC="Directory on the remote server to upload backups to"
|
||||
COM_MOKOJOOMBACKUP_FIELDSET_S3="S3 Storage Settings"
|
||||
COM_MOKOJOOMBACKUP_FIELD_S3_ENDPOINT="S3 Endpoint"
|
||||
COM_MOKOJOOMBACKUP_FIELD_S3_ENDPOINT_DESC="S3 API endpoint URL. Leave blank for AWS S3. For Wasabi, MinIO, Backblaze B2, enter their endpoint URL."
|
||||
@@ -268,6 +345,13 @@ COM_MOKOJOOMBACKUP_CONFIG_NOTIFY_SUCCESS_DESC="Send email when any backup comple
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NOTIFY_FAILURE="Notify on Failure"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NOTIFY_FAILURE_DESC="Send email when any backup fails (unless overridden by profile)."
|
||||
|
||||
; Snapshot Retention
|
||||
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_RETENTION="Snapshot Retention"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_COUNT="Max Snapshot Count"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_COUNT_DESC="Maximum number of content snapshots to keep. Oldest are removed first. Set to 0 for unlimited."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_AGE="Max Snapshot Age (days)"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_SNAPSHOT_MAX_AGE_DESC="Delete snapshots older than this many days. Set to 0 for unlimited."
|
||||
|
||||
; Web Cron
|
||||
COM_MOKOJOOMBACKUP_CONFIG_WEBCRON="Web Cron"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_WEBCRON_ENABLED="Enable Web Cron"
|
||||
@@ -335,6 +419,38 @@ COM_MOKOJOOMBACKUP_SNAPSHOTS_N_DELETED="%d snapshot(s) deleted."
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOTS_1_DELETED="1 snapshot deleted."
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOTS_DELETE_ERRORS="Failed to delete snapshot(s): %s"
|
||||
|
||||
; Component Options — Defaults
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULTS="Profile Defaults"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_FORMAT="Default Archive Format"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_FORMAT_DESC="Archive format used when creating new profiles. Can be overridden per profile."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_MOKORESTORE="Default MokoRestore Mode"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_MOKORESTORE_DESC="MokoRestore mode for new profiles. None, Wrapped (inside ZIP), or Standalone (separate file)."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_PW="Default: Sanitize Passwords"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_PW_DESC="Whether new profiles should sanitize user passwords by default."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_EMAIL="Default: Sanitize Emails"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_EMAIL_DESC="Whether new profiles should sanitize user emails by default."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_SESS="Default: Clear Sessions"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_DEFAULT_SANITIZE_SESS_DESC="Whether new profiles should clear session data by default."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_LOG_RETENTION="Log Retention (days)"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_LOG_RETENTION_DESC="Days to keep .log files alongside backup archives. Set to 0 for unlimited."
|
||||
|
||||
; Component Options — ntfy
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY="Push Notifications (ntfy)"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY_SERVER="Global ntfy Server"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY_SERVER_DESC="Default ntfy server URL. Per-profile settings override this."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOPIC="Global ntfy Topic"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOPIC_DESC="Default ntfy topic for backup notifications. Per-profile settings override this."
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOKEN="Global ntfy Token"
|
||||
COM_MOKOJOOMBACKUP_CONFIG_NTFY_TOKEN_DESC="Default access token for private ntfy topics. Per-profile settings override this."
|
||||
|
||||
; ACL — additional actions
|
||||
COM_MOKOSUITEBACKUP_ACTION_BACKUP_PURGE="Purge Old Backups"
|
||||
COM_MOKOSUITEBACKUP_ACTION_BACKUP_PURGE_DESC="Allows users to bulk-delete backups older than a specific date."
|
||||
COM_MOKOSUITEBACKUP_ACTION_BACKUP_COMPARE="Compare Backups"
|
||||
COM_MOKOSUITEBACKUP_ACTION_BACKUP_COMPARE_DESC="Allows users to compare two backup records side-by-side."
|
||||
COM_MOKOSUITEBACKUP_ACTION_BACKUP_BROWSE="Browse Archives"
|
||||
COM_MOKOSUITEBACKUP_ACTION_BACKUP_BROWSE_DESC="Allows users to view file listings inside backup archives without extracting."
|
||||
|
||||
; Snapshot ACL
|
||||
COM_MOKOSUITEBACKUP_ACTION_SNAPSHOT_MANAGE="Manage Snapshots"
|
||||
COM_MOKOSUITEBACKUP_ACTION_SNAPSHOT_MANAGE_DESC="Allows users in this group to create and restore content snapshots. Snapshots only affect articles, categories, and modules — not the full site."
|
||||
@@ -357,6 +473,42 @@ 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 browse / detail view
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOT_BROWSE="Browse Snapshot"
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOT_TAB_ARTICLES="Articles"
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOT_TAB_CATEGORIES="Categories"
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOT_TAB_MODULES="Modules"
|
||||
COM_MOKOJOOMBACKUP_HEADING_STATE="State"
|
||||
COM_MOKOJOOMBACKUP_HEADING_POSITION="Position"
|
||||
COM_MOKOJOOMBACKUP_HEADING_MODULE_TYPE="Module Type"
|
||||
COM_MOKOJOOMBACKUP_HEADING_LEVEL="Level"
|
||||
COM_MOKOJOOMBACKUP_LOADING="Loading..."
|
||||
COM_MOKOJOOMBACKUP_SELECT_ALL="Select All"
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOT_RESTORE_SELECTED="Restore Selected"
|
||||
COM_MOKOJOOMBACKUP_SNAPSHOT_NO_ARTICLES_SELECTED="No articles selected for restore."
|
||||
|
||||
; Purge
|
||||
COM_MOKOJOOMBACKUP_TOOLBAR_PURGE="Purge Old Backups"
|
||||
COM_MOKOJOOMBACKUP_PURGE_TITLE="Purge Old Backups"
|
||||
COM_MOKOJOOMBACKUP_PURGE_DESC="Delete all completed backup records older than the selected date. This permanently removes archive files, log files, and database records."
|
||||
COM_MOKOJOOMBACKUP_PURGE_DATE_LABEL="Delete all backups before this date"
|
||||
COM_MOKOJOOMBACKUP_PURGE_SUBMIT="Purge Backups"
|
||||
COM_MOKOJOOMBACKUP_PURGE_CONFIRM="Are you sure? This action cannot be undone."
|
||||
COM_MOKOJOOMBACKUP_PURGE_COUNT_MSG="This will permanently delete %d backup(s) and their archive files."
|
||||
COM_MOKOJOOMBACKUP_PURGE_NONE_FOUND="No completed backups found before the selected date."
|
||||
COM_MOKOJOOMBACKUP_PURGE_INVALID_DATE="Invalid date. Please select a valid date."
|
||||
COM_MOKOJOOMBACKUP_PURGE_SUCCESS="%d backup(s) purged successfully."
|
||||
COM_MOKOJOOMBACKUP_PURGE_PARTIAL="%d backup(s) purged, but %d could not be deleted."
|
||||
|
||||
; Remote Destinations (multi-remote)
|
||||
COM_MOKOJOOMBACKUP_REMOTE_DESTINATIONS="Remote Destinations"
|
||||
COM_MOKOJOOMBACKUP_REMOTE_ADD="Add Destination"
|
||||
COM_MOKOJOOMBACKUP_REMOTE_EDIT="Edit Destination"
|
||||
COM_MOKOJOOMBACKUP_REMOTE_ENABLED="Enabled"
|
||||
COM_MOKOJOOMBACKUP_REMOTE_NONE_CONFIGURED="No remote destinations configured. Use 'Add Destination' to send backups to SFTP, S3, or Google Drive."
|
||||
COM_MOKOJOOMBACKUP_REMOTE_LEGACY_NOTE="Legacy single-remote fields below are hidden when remote destinations are configured above. Existing legacy settings continue to work as a fallback."
|
||||
COM_MOKOJOOMBACKUP_REMOTE_DELETE_CONFIRM="Are you sure you want to delete this remote destination?"
|
||||
|
||||
; Errors
|
||||
COM_MOKOJOOMBACKUP_ERROR_FILE_NOT_FOUND="Backup archive file not found or has been deleted."
|
||||
COM_MOKOJOOMBACKUP_ERROR_NO_RECORD_SELECTED="No backup record selected for restore."
|
||||
|
||||
@@ -35,6 +35,10 @@ COM_MOKOJOOMBACKUP_PROFILES_TITLE="Backup Profiles"
|
||||
COM_MOKOJOOMBACKUP_TOOLBAR_BACKUP_NOW="Backup Now"
|
||||
COM_MOKOJOOMBACKUP_NO_BACKUPS="No backups found. Click 'Backup Now' to create your first backup."
|
||||
COM_MOKOJOOMBACKUP_NO_PROFILES="No backup profiles found."
|
||||
COM_MOKOJOOMBACKUP_RUN_BACKUP="Run"
|
||||
COM_MOKOJOOMBACKUP_RUN_BACKUP_NOW="Run Backup Now"
|
||||
COM_MOKOJOOMBACKUP_VIEW_BACKUPS="View Backups"
|
||||
COM_MOKOJOOMBACKUP_HEADING_BACKUPS="Backups"
|
||||
COM_MOKOJOOMBACKUP_UPDATE_SITE_NOTICE="To receive automatic updates, configure your <a href=\"%s\">Update Site</a> with your download key."
|
||||
COM_MOKOJOOMBACKUP_UPDATE_SITE_MISSING="MokoSuiteBackup update site not found. Reinstall the package to register the update server."
|
||||
COM_MOKOJOOMBACKUP_POSTINSTALL_UPDATE_SITE="MokoSuiteBackup installed successfully. Configure your <a href=\"%s\">Update Site</a> to receive automatic updates."
|
||||
@@ -77,9 +81,38 @@ COM_MOKOJOOMBACKUP_FIELD_EXCLUDE_DATA="Data"
|
||||
COM_MOKOJOOMBACKUP_FIELD_EXCLUDE_STRUCTURE="Structure"
|
||||
COM_MOKOJOOMBACKUP_FIELD_TABLE_NAME="Table Name"
|
||||
COM_MOKOJOOMBACKUP_VIEW_LOG="Backup Log"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_ARCHIVE="Browse Archive Contents"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_COL_NAME="Name"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_COL_SIZE="Size"
|
||||
COM_MOKOJOOMBACKUP_BROWSE_COL_COMPRESSED="Compressed"
|
||||
; Backup comparison
|
||||
COM_MOKOJOOMBACKUP_TOOLBAR_COMPARE="Compare"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_TITLE="Backup Comparison"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_LOADING="Loading comparison..."
|
||||
COM_MOKOJOOMBACKUP_COMPARE_FIELD="Field"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_BACKUP="Backup"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_DELTA="Delta"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_DB_SIZE="DB Size"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_FILES_COUNT="Files Count"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_TABLES_COUNT="Tables Count"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_DURATION="Duration"
|
||||
COM_MOKOJOOMBACKUP_COMPARE_SELECT_TWO="Please select exactly two backup records to compare."
|
||||
COM_MOKOJOOMBACKUP_FIELD_CHECKSUM="SHA-256 Checksum"
|
||||
COM_MOKOJOOMBACKUP_FIELD_PATH="File Path"
|
||||
COM_MOKOJOOMBACKUP_FIELD_DB_SIZE="DB Size"
|
||||
COM_MOKOJOOMBACKUP_FIELD_REMOTE="Remote Path"
|
||||
COM_MOKOJOOMBACKUP_FIELD_NOTIFY_USER_GROUPS="Notify User Groups"
|
||||
COM_MOKOJOOMBACKUP_FIELD_NOTIFY_USER_GROUPS_DESC="Select Joomla user groups whose members will receive backup notifications. Combined with email addresses above."
|
||||
|
||||
; Purge
|
||||
COM_MOKOJOOMBACKUP_TOOLBAR_PURGE="Purge Old Backups"
|
||||
COM_MOKOJOOMBACKUP_PURGE_TITLE="Purge Old Backups"
|
||||
COM_MOKOJOOMBACKUP_PURGE_DESC="Delete all completed backup records older than the selected date. This permanently removes archive files, log files, and database records."
|
||||
COM_MOKOJOOMBACKUP_PURGE_DATE_LABEL="Delete all backups before this date"
|
||||
COM_MOKOJOOMBACKUP_PURGE_SUBMIT="Purge Backups"
|
||||
COM_MOKOJOOMBACKUP_PURGE_CONFIRM="Are you sure? This action cannot be undone."
|
||||
COM_MOKOJOOMBACKUP_PURGE_COUNT_MSG="This will permanently delete %d backup(s) and their archive files."
|
||||
COM_MOKOJOOMBACKUP_PURGE_NONE_FOUND="No completed backups found before the selected date."
|
||||
COM_MOKOJOOMBACKUP_PURGE_INVALID_DATE="Invalid date. Please select a valid date."
|
||||
COM_MOKOJOOMBACKUP_PURGE_SUCCESS="%d backup(s) purged successfully."
|
||||
COM_MOKOJOOMBACKUP_PURGE_PARTIAL="%d backup(s) purged, but %d could not be deleted."
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
-->
|
||||
<extension type="component" method="upgrade">
|
||||
<name>MokoSuiteBackup</name>
|
||||
<version>01.26.00</version>
|
||||
<version>01.44.03</version>
|
||||
<creationDate>2026-06-02</creationDate>
|
||||
<author>Moko Consulting</author>
|
||||
<authorEmail>hello@mokoconsulting.tech</authorEmail>
|
||||
|
||||
@@ -7,7 +7,7 @@ CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_profiles` (
|
||||
`compression_level` TINYINT(1) UNSIGNED NOT NULL DEFAULT 5 COMMENT '0=none, 9=max',
|
||||
`split_size` INT(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '0=no split, otherwise MB per part',
|
||||
`backup_dir` VARCHAR(512) NOT NULL DEFAULT '[DEFAULT_DIR]',
|
||||
`archive_name_format` VARCHAR(512) NOT NULL DEFAULT '[host]_[datetime]_profile[profile_id]' COMMENT 'Filename format with placeholders',
|
||||
`archive_name_format` VARCHAR(512) NOT NULL DEFAULT '[HOST]_[DATETIME]_profile[PROFILE_ID]' COMMENT 'Filename format with placeholders',
|
||||
`exclude_dirs` TEXT NOT NULL COMMENT 'Newline-separated directory paths to exclude',
|
||||
`exclude_files` TEXT NOT NULL COMMENT 'Newline-separated filename patterns to exclude',
|
||||
`exclude_tables` TEXT NOT NULL COMMENT 'Newline-separated table names to exclude',
|
||||
@@ -19,6 +19,14 @@ CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_profiles` (
|
||||
`ftp_path` VARCHAR(512) NOT NULL DEFAULT '/backups',
|
||||
`ftp_passive` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
`ftp_ssl` TINYINT(1) NOT NULL DEFAULT 0,
|
||||
`sftp_host` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`sftp_port` INT(5) UNSIGNED NOT NULL DEFAULT 22,
|
||||
`sftp_username` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`sftp_auth_type` VARCHAR(20) NOT NULL DEFAULT 'key',
|
||||
`sftp_password` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`sftp_key_data` MEDIUMTEXT,
|
||||
`sftp_passphrase` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`sftp_path` VARCHAR(512) NOT NULL DEFAULT '/backups',
|
||||
`gdrive_client_id` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`gdrive_client_secret` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`gdrive_refresh_token` VARCHAR(512) NOT NULL DEFAULT '',
|
||||
@@ -31,7 +39,12 @@ CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_profiles` (
|
||||
`s3_path` VARCHAR(512) NOT NULL DEFAULT '/backups',
|
||||
`remote_keep_local` TINYINT(1) NOT NULL DEFAULT 1 COMMENT 'Keep local copy after upload',
|
||||
`encryption_password` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'AES-256 archive encryption password (blank = no encryption)',
|
||||
`include_mokorestore` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Include MokoRestore standalone restore script in archive',
|
||||
`include_mokorestore` VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'MokoRestore mode: 0=none, 1=wrapped, standalone',
|
||||
`restore_script_name` VARCHAR(100) NOT NULL DEFAULT 'restore.php' COMMENT 'Custom restore script filename',
|
||||
`sanitize_passwords` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Replace user password hashes with invalid value',
|
||||
`preserve_super_admin` TINYINT(1) NOT NULL DEFAULT 1 COMMENT 'Keep super admin password when sanitizing',
|
||||
`sanitize_emails` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Replace user emails with dummy values',
|
||||
`sanitize_sessions` TINYINT(1) NOT NULL DEFAULT 1 COMMENT 'Skip session table data',
|
||||
`notify_email` VARCHAR(512) NOT NULL DEFAULT '' COMMENT 'Comma-separated notification emails',
|
||||
`notify_user_groups` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Comma-separated Joomla user group IDs',
|
||||
`notify_on_success` TINYINT(1) NOT NULL DEFAULT 0,
|
||||
@@ -42,7 +55,6 @@ CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_profiles` (
|
||||
`ntfy_server` VARCHAR(512) NOT NULL DEFAULT 'https://ntfy.sh' COMMENT 'ntfy server URL',
|
||||
`ntfy_token` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'ntfy access token (optional)',
|
||||
`published` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
`ordering` INT(11) NOT NULL DEFAULT 0,
|
||||
`created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
|
||||
`modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
|
||||
PRIMARY KEY (`id`),
|
||||
@@ -95,17 +107,32 @@ CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_snapshots` (
|
||||
KEY `idx_created` (`created`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_remotes` (
|
||||
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`profile_id` INT(11) UNSIGNED NOT NULL,
|
||||
`title` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`type` VARCHAR(20) NOT NULL DEFAULT 'sftp' COMMENT 'sftp, s3, google_drive',
|
||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
`params` MEDIUMTEXT COMMENT 'JSON: type-specific settings',
|
||||
`ordering` INT(11) NOT NULL DEFAULT 0,
|
||||
`created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
|
||||
`modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_profile` (`profile_id`),
|
||||
KEY `idx_enabled` (`profile_id`, `enabled`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Insert default backup profile (IGNORE prevents duplicate key error on update)
|
||||
INSERT IGNORE INTO `#__mokosuitebackup_profiles` (
|
||||
`id`, `title`, `description`, `backup_type`,
|
||||
`archive_format`, `compression_level`, `split_size`, `backup_dir`,
|
||||
`exclude_dirs`, `exclude_files`, `exclude_tables`,
|
||||
`published`, `ordering`, `created`, `modified`
|
||||
`published`, `created`, `modified`
|
||||
) VALUES (
|
||||
1, 'Default Backup Profile', 'Full site backup with default settings', 'full',
|
||||
'zip', 5, 0, '[DEFAULT_DIR]',
|
||||
'administrator/components/com_mokosuitebackup/backups\ntmp\ncache\nlogs\nadministrator/logs',
|
||||
'.gitignore\n.htaccess.bak',
|
||||
'#__session',
|
||||
1, 1, NOW(), NOW()
|
||||
1, NOW(), NOW()
|
||||
);
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
DROP TABLE IF EXISTS `#__mokosuitebackup_remotes`;
|
||||
DROP TABLE IF EXISTS `#__mokosuitebackup_records`;
|
||||
DROP TABLE IF EXISTS `#__mokosuitebackup_profiles`;
|
||||
|
||||
@@ -9,4 +9,4 @@ ALTER TABLE `#__mokosuitebackup_records` MODIFY `log` MEDIUMTEXT DEFAULT NULL;
|
||||
ALTER TABLE `#__mokosuitebackup_profiles` ADD COLUMN `notify_user_groups` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Comma-separated Joomla user group IDs' AFTER `notify_email`;
|
||||
|
||||
-- Add archive_name_format column with placeholder support
|
||||
ALTER TABLE `#__mokosuitebackup_profiles` ADD COLUMN `archive_name_format` VARCHAR(512) NOT NULL DEFAULT '[host]_[datetime]_profile[profile_id]' COMMENT 'Filename format with placeholders' AFTER `backup_dir`;
|
||||
ALTER TABLE `#__mokosuitebackup_profiles` ADD COLUMN `archive_name_format` VARCHAR(512) NOT NULL DEFAULT '[HOST]_[DATETIME]_profile[PROFILE_ID]' COMMENT 'Filename format with placeholders' AFTER `backup_dir`;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
-- MokoSuiteBackup 01.35.00 — SFTP support with key file storage
|
||||
|
||||
ALTER TABLE `#__mokosuitebackup_profiles`
|
||||
ADD COLUMN `sftp_host` VARCHAR(255) NOT NULL DEFAULT '' AFTER `ftp_ssl`,
|
||||
ADD COLUMN `sftp_port` INT(5) UNSIGNED NOT NULL DEFAULT 22 AFTER `sftp_host`,
|
||||
ADD COLUMN `sftp_username` VARCHAR(255) NOT NULL DEFAULT '' AFTER `sftp_port`,
|
||||
ADD COLUMN `sftp_password` VARCHAR(255) NOT NULL DEFAULT '' AFTER `sftp_username`,
|
||||
ADD COLUMN `sftp_key_data` MEDIUMTEXT AFTER `sftp_password`,
|
||||
ADD COLUMN `sftp_passphrase` VARCHAR(255) NOT NULL DEFAULT '' AFTER `sftp_key_data`,
|
||||
ADD COLUMN `sftp_path` VARCHAR(512) NOT NULL DEFAULT '/backups' AFTER `sftp_passphrase`;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- MokoSuiteBackup 01.36.00 — SFTP auth type column
|
||||
|
||||
ALTER TABLE `#__mokosuitebackup_profiles`
|
||||
ADD COLUMN `sftp_auth_type` VARCHAR(20) NOT NULL DEFAULT 'key' AFTER `sftp_username`;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- MokoSuiteBackup 01.39.00 — Change include_mokorestore from TINYINT to VARCHAR
|
||||
-- Needed to support 'standalone' value alongside 0/1
|
||||
|
||||
ALTER TABLE `#__mokosuitebackup_profiles`
|
||||
MODIFY COLUMN `include_mokorestore` VARCHAR(20) NOT NULL DEFAULT '0';
|
||||
@@ -0,0 +1,34 @@
|
||||
-- MokoSuiteBackup 01.39.01 — Uppercase all placeholders in profile data
|
||||
|
||||
UPDATE `#__mokosuitebackup_profiles` SET
|
||||
`archive_name_format` = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
|
||||
`archive_name_format`,
|
||||
'[host]', '[HOST]'),
|
||||
'[site_name]', '[SITE_NAME]'),
|
||||
'[datetime]', '[DATETIME]'),
|
||||
'[date]', '[DATE]'),
|
||||
'[time]', '[TIME]'),
|
||||
'[year]', '[YEAR]'),
|
||||
'[month]', '[MONTH]'),
|
||||
'[day]', '[DAY]'),
|
||||
'[hour]', '[HOUR]'),
|
||||
'[minute]', '[MINUTE]'),
|
||||
'[second]', '[SECOND]'),
|
||||
'[profile_id]', '[PROFILE_ID]'),
|
||||
'[profile_name]', '[PROFILE_NAME]'),
|
||||
'[type]', '[TYPE]'),
|
||||
'[random]', '[RANDOM]')
|
||||
WHERE `archive_name_format` REGEXP '\\[[a-z]';
|
||||
|
||||
UPDATE `#__mokosuitebackup_profiles` SET
|
||||
`backup_dir` = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
|
||||
`backup_dir`,
|
||||
'[host]', '[HOST]'),
|
||||
'[site_name]', '[SITE_NAME]'),
|
||||
'[date]', '[DATE]'),
|
||||
'[year]', '[YEAR]'),
|
||||
'[month]', '[MONTH]'),
|
||||
'[day]', '[DAY]'),
|
||||
'[profile_id]', '[PROFILE_ID]'),
|
||||
'[profile_name]', '[PROFILE_NAME]')
|
||||
WHERE `backup_dir` REGEXP '\\[[a-z]';
|
||||
@@ -0,0 +1,7 @@
|
||||
-- MokoSuiteBackup 01.39.02 — Data sanitization columns
|
||||
|
||||
ALTER TABLE `#__mokosuitebackup_profiles`
|
||||
ADD COLUMN `sanitize_passwords` TINYINT(1) NOT NULL DEFAULT 0 AFTER `include_mokorestore`,
|
||||
ADD COLUMN `preserve_super_admin` TINYINT(1) NOT NULL DEFAULT 1 AFTER `sanitize_passwords`,
|
||||
ADD COLUMN `sanitize_emails` TINYINT(1) NOT NULL DEFAULT 0 AFTER `preserve_super_admin`,
|
||||
ADD COLUMN `sanitize_sessions` TINYINT(1) NOT NULL DEFAULT 1 AFTER `sanitize_emails`;
|
||||
@@ -0,0 +1,97 @@
|
||||
-- MokoSuiteBackup 01.41.00 — Multi-remote storage destinations (#97)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `#__mokosuitebackup_remotes` (
|
||||
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`profile_id` INT(11) UNSIGNED NOT NULL,
|
||||
`title` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`type` VARCHAR(20) NOT NULL DEFAULT 'sftp' COMMENT 'sftp, s3, google_drive',
|
||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
`params` MEDIUMTEXT COMMENT 'JSON: type-specific settings',
|
||||
`ordering` INT(11) NOT NULL DEFAULT 0,
|
||||
`created` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
|
||||
`modified` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_profile` (`profile_id`),
|
||||
KEY `idx_enabled` (`profile_id`, `enabled`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Migrate existing SFTP remote configs into new table
|
||||
INSERT INTO `#__mokosuitebackup_remotes` (`profile_id`, `title`, `type`, `enabled`, `params`, `ordering`, `created`)
|
||||
SELECT
|
||||
`id`,
|
||||
CONCAT(`title`, ' - SFTP'),
|
||||
'sftp',
|
||||
1,
|
||||
JSON_OBJECT(
|
||||
'host', `sftp_host`,
|
||||
'port', `sftp_port`,
|
||||
'username', `sftp_username`,
|
||||
'auth_type', `sftp_auth_type`,
|
||||
'password', `sftp_password`,
|
||||
'key_data', COALESCE(`sftp_key_data`, ''),
|
||||
'passphrase', `sftp_passphrase`,
|
||||
'path', `sftp_path`
|
||||
),
|
||||
1,
|
||||
NOW()
|
||||
FROM `#__mokosuitebackup_profiles`
|
||||
WHERE `remote_storage` = 'sftp' AND `sftp_host` != '';
|
||||
|
||||
-- Migrate existing S3 remote configs into new table
|
||||
INSERT INTO `#__mokosuitebackup_remotes` (`profile_id`, `title`, `type`, `enabled`, `params`, `ordering`, `created`)
|
||||
SELECT
|
||||
`id`,
|
||||
CONCAT(`title`, ' - S3'),
|
||||
's3',
|
||||
1,
|
||||
JSON_OBJECT(
|
||||
'endpoint', `s3_endpoint`,
|
||||
'region', `s3_region`,
|
||||
'access_key', `s3_access_key`,
|
||||
'secret_key', `s3_secret_key`,
|
||||
'bucket', `s3_bucket`,
|
||||
'path', `s3_path`
|
||||
),
|
||||
1,
|
||||
NOW()
|
||||
FROM `#__mokosuitebackup_profiles`
|
||||
WHERE `remote_storage` = 's3' AND `s3_bucket` != '';
|
||||
|
||||
-- Migrate existing Google Drive remote configs into new table
|
||||
INSERT INTO `#__mokosuitebackup_remotes` (`profile_id`, `title`, `type`, `enabled`, `params`, `ordering`, `created`)
|
||||
SELECT
|
||||
`id`,
|
||||
CONCAT(`title`, ' - Google Drive'),
|
||||
'google_drive',
|
||||
1,
|
||||
JSON_OBJECT(
|
||||
'client_id', `gdrive_client_id`,
|
||||
'client_secret', `gdrive_client_secret`,
|
||||
'refresh_token', `gdrive_refresh_token`,
|
||||
'folder_id', `gdrive_folder_id`
|
||||
),
|
||||
1,
|
||||
NOW()
|
||||
FROM `#__mokosuitebackup_profiles`
|
||||
WHERE `remote_storage` = 'google_drive' AND `gdrive_client_id` != '';
|
||||
|
||||
-- Migrate existing FTP remote configs into new table
|
||||
INSERT INTO `#__mokosuitebackup_remotes` (`profile_id`, `title`, `type`, `enabled`, `params`, `ordering`, `created`)
|
||||
SELECT
|
||||
`id`,
|
||||
CONCAT(`title`, ' - FTP'),
|
||||
'ftp',
|
||||
1,
|
||||
JSON_OBJECT(
|
||||
'host', `ftp_host`,
|
||||
'port', `ftp_port`,
|
||||
'username', `ftp_username`,
|
||||
'password', `ftp_password`,
|
||||
'path', `ftp_path`,
|
||||
'passive', `ftp_passive`,
|
||||
'ssl', `ftp_ssl`
|
||||
),
|
||||
1,
|
||||
NOW()
|
||||
FROM `#__mokosuitebackup_profiles`
|
||||
WHERE `remote_storage` = 'ftp' AND `ftp_host` != '';
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.11 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.19 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.20 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.21 — no schema changes */
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 01.43.22 — Add restore_script_name to profiles, align remotes schema
|
||||
|
||||
ALTER TABLE `#__mokosuitebackup_profiles`
|
||||
ADD COLUMN `restore_script_name` VARCHAR(100) NOT NULL DEFAULT 'restore.php' COMMENT 'Custom restore script filename'
|
||||
AFTER `include_mokorestore`;
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.23 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.24 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.25 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.26 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.29 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.30 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.31 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.32 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `#__mokosuitebackup_profiles` DROP COLUMN `ordering`;
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.34 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.35 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.36 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.37 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.43.38 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.44.00 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.44.01 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.44.02 — no schema changes */
|
||||
@@ -0,0 +1 @@
|
||||
/* 01.44.03 — no schema changes */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,7 @@ defined('_JEXEC') or die;
|
||||
use Joomla\CMS\Language\Text;
|
||||
use Joomla\CMS\MVC\Controller\AdminController;
|
||||
use Joomla\CMS\Router\Route;
|
||||
use Joomla\CMS\Session\Session;
|
||||
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\BackupEngine;
|
||||
use Joomla\Component\MokoSuiteBackup\Administrator\Engine\RestoreEngine;
|
||||
|
||||
@@ -34,7 +35,14 @@ class BackupsController extends AdminController
|
||||
*/
|
||||
public function start(): void
|
||||
{
|
||||
$this->checkToken();
|
||||
/* Accept token from both GET (profile Run button) and POST (backup form).
|
||||
Joomla's checkToken() throws on failure, so try GET first. */
|
||||
if (!Session::checkToken('get') && !Session::checkToken('post')) {
|
||||
$this->setMessage(Text::_('JINVALID_TOKEN_NOTICE'), 'error');
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$this->app->getIdentity()->authorise('mokosuitebackup.backup.run', 'com_mokosuitebackup')) {
|
||||
$this->setMessage(Text::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 'error');
|
||||
@@ -49,6 +57,13 @@ class BackupsController extends AdminController
|
||||
$engine = new BackupEngine();
|
||||
$result = $engine->run($profileId, $description, 'backend');
|
||||
|
||||
// Surface preflight warnings as Joomla messages
|
||||
if (!empty($result['warnings'])) {
|
||||
foreach ($result['warnings'] as $warning) {
|
||||
$this->app->enqueueMessage($warning, 'warning');
|
||||
}
|
||||
}
|
||||
|
||||
if ($result['success']) {
|
||||
$this->setMessage($result['message']);
|
||||
} else {
|
||||
@@ -150,6 +165,88 @@ class BackupsController extends AdminController
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge (delete) all completed backup records older than a given date.
|
||||
*
|
||||
* Deletes archive files, log files, and database records.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function purge(): void
|
||||
{
|
||||
$this->checkToken();
|
||||
|
||||
if (!$this->app->getIdentity()->authorise('mokosuitebackup.backup.purge', 'com_mokosuitebackup')) {
|
||||
$this->setMessage(Text::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 'error');
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$cutoffDate = $this->input->getString('purge_date', '');
|
||||
|
||||
if (empty($cutoffDate) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $cutoffDate)) {
|
||||
$this->setMessage(Text::_('COM_MOKOJOOMBACKUP_PURGE_INVALID_DATE'), 'error');
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$cutoff = $cutoffDate . ' 00:00:00';
|
||||
|
||||
$db = $this->app->getContainer()->get('DatabaseDriver');
|
||||
$query = $db->getQuery(true)
|
||||
->select($db->quoteName('id'))
|
||||
->from($db->quoteName('#__mokosuitebackup_records'))
|
||||
->where($db->quoteName('backupstart') . ' < ' . $db->quote($cutoff))
|
||||
->where($db->quoteName('status') . ' = ' . $db->quote('complete'));
|
||||
$db->setQuery($query);
|
||||
$ids = $db->loadColumn();
|
||||
|
||||
if (empty($ids)) {
|
||||
$this->setMessage(Text::_('COM_MOKOJOOMBACKUP_PURGE_NONE_FOUND'), 'warning');
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$table = $this->getModel('Backup')->getTable();
|
||||
$deleted = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($ids as $id) {
|
||||
if ($table->load((int) $id)) {
|
||||
if ($table->delete()) {
|
||||
$deleted++;
|
||||
} else {
|
||||
$errors++;
|
||||
}
|
||||
}
|
||||
|
||||
$table->reset();
|
||||
}
|
||||
|
||||
if ($errors > 0) {
|
||||
$this->setMessage(Text::sprintf('COM_MOKOJOOMBACKUP_PURGE_PARTIAL', $deleted, $errors), 'warning');
|
||||
} else {
|
||||
$this->setMessage(Text::sprintf('COM_MOKOJOOMBACKUP_PURGE_SUCCESS', $deleted));
|
||||
}
|
||||
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op target for the purge toolbar button.
|
||||
*
|
||||
* The toolbar button needs a task so Joomla does not complain,
|
||||
* but the actual purge is triggered via the modal form which
|
||||
* submits to backups.purge. This method simply redirects back.
|
||||
*/
|
||||
public function purgeModal(): void
|
||||
{
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=backups', false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify integrity of a backup archive by re-computing SHA-256.
|
||||
*/
|
||||
|
||||
@@ -16,6 +16,7 @@ use Joomla\CMS\Factory;
|
||||
use Joomla\CMS\Language\Text;
|
||||
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\SnapshotRestoreEngine;
|
||||
|
||||
@@ -106,6 +107,151 @@ class SnapshotsController extends AdminController
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Browse articles inside a snapshot — returns JSON for AJAX modal.
|
||||
*/
|
||||
public function browse(): void
|
||||
{
|
||||
if (!Session::checkToken('get') && !Session::checkToken('post')) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Invalid token'], 403);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$this->app->getIdentity()->authorise('mokosuitebackup.snapshot.manage', 'com_mokosuitebackup')) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Access denied'], 403);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$id = $this->input->getInt('id', 0);
|
||||
|
||||
if (!$id) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Missing snapshot ID']);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->where($db->quoteName('id') . ' = ' . $id);
|
||||
$db->setQuery($query);
|
||||
$record = $db->loadObject();
|
||||
|
||||
if (!$record) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Snapshot not found'], 404);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($record->status !== 'complete') {
|
||||
$this->sendJson(['error' => true, 'message' => 'Cannot browse a failed snapshot']);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_file($record->data_file) || !is_readable($record->data_file)) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Snapshot data file not found']);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$json = file_get_contents($record->data_file);
|
||||
|
||||
if ($json === false) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Cannot read snapshot file']);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$data = json_decode($json, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE || empty($data['tables']['#__content'])) {
|
||||
$this->sendJson(['error' => true, 'message' => 'Snapshot does not contain articles']);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$articles = [];
|
||||
|
||||
foreach ($data['tables']['#__content'] as $row) {
|
||||
$articles[] = [
|
||||
'id' => (int) ($row['id'] ?? 0),
|
||||
'title' => $row['title'] ?? '',
|
||||
'catid' => (int) ($row['catid'] ?? 0),
|
||||
'state' => (int) ($row['state'] ?? 0),
|
||||
'created' => $row['created'] ?? '',
|
||||
];
|
||||
}
|
||||
|
||||
$this->sendJson([
|
||||
'error' => false,
|
||||
'articles' => $articles,
|
||||
'total' => count($articles),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore selected articles from a snapshot.
|
||||
*/
|
||||
public function restoreSelected(): 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;
|
||||
}
|
||||
|
||||
$id = $this->input->getInt('id', 0);
|
||||
$articleIds = $this->input->get('article_ids', [], 'array');
|
||||
|
||||
if (!$id) {
|
||||
$this->setMessage(Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_NO_RECORD'), 'error');
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (empty($articleIds)) {
|
||||
$this->setMessage(Text::_('COM_MOKOJOOMBACKUP_SNAPSHOT_NO_ARTICLES_SELECTED'), 'error');
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$engine = new SnapshotRestoreEngine();
|
||||
$result = $engine->restoreSelectedArticles($id, $articleIds);
|
||||
|
||||
if ($result['success']) {
|
||||
$this->setMessage($result['message']);
|
||||
} else {
|
||||
$this->setMessage($result['message'], 'error');
|
||||
}
|
||||
|
||||
$this->setRedirect(Route::_('index.php?option=com_mokosuitebackup&view=snapshots', false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a JSON response and close the application.
|
||||
*/
|
||||
private function sendJson(array $data, int $status = 200): void
|
||||
{
|
||||
$app = $this->app;
|
||||
$app->setHeader('status', $status);
|
||||
$app->setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
$app->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||||
$app->sendHeaders();
|
||||
|
||||
echo json_encode($data);
|
||||
|
||||
$app->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete snapshot records and their data files.
|
||||
*/
|
||||
@@ -113,7 +259,7 @@ class SnapshotsController extends AdminController
|
||||
{
|
||||
$this->checkToken();
|
||||
|
||||
if (!$this->app->getIdentity()->authorise('core.delete', 'com_mokosuitebackup')) {
|
||||
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));
|
||||
|
||||
|
||||
@@ -249,7 +249,6 @@ class AkeebaImporter
|
||||
'remote_keep_local' => 1,
|
||||
'include_mokorestore' => (int) (($config['akeeba.advanced.embedded_installer'] ?? 'none') !== 'none'),
|
||||
'published' => 1,
|
||||
'ordering' => (int) $akProfile->id,
|
||||
'created' => $now,
|
||||
'modified' => $now,
|
||||
];
|
||||
@@ -360,16 +359,12 @@ class AkeebaImporter
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Try JSON
|
||||
// Parse as JSON only — unserialize is an object injection risk
|
||||
$data = json_decode($raw, true);
|
||||
|
||||
if (!is_array($data)) {
|
||||
// Try unserialize (older Akeeba versions)
|
||||
$data = @unserialize($raw);
|
||||
|
||||
if (!is_array($data)) {
|
||||
return $result;
|
||||
}
|
||||
// Older Akeeba versions used serialized PHP — skip rather than risk object injection
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Extract directory exclusions
|
||||
|
||||
@@ -32,16 +32,21 @@ class BackupEngine
|
||||
*/
|
||||
public function run(int $profileId, string $description, string $origin = 'backend'): array
|
||||
{
|
||||
// Run pre-flight checks before creating any backup record
|
||||
$preflight = new PreflightCheck();
|
||||
$preflightResult = $preflight->run($profileId);
|
||||
|
||||
if (!$preflightResult['pass']) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Pre-flight failed: ' . implode('; ', $preflightResult['errors']),
|
||||
'warnings' => $preflightResult['warnings'],
|
||||
];
|
||||
}
|
||||
|
||||
// Override PHP limits for long-running backup operations
|
||||
$this->overridePhpLimits();
|
||||
|
||||
// Verify required extensions
|
||||
$extCheck = $this->checkRequiredExtensions();
|
||||
|
||||
if ($extCheck !== true) {
|
||||
return ['success' => false, 'message' => $extCheck];
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
// Load profile
|
||||
@@ -53,7 +58,12 @@ class BackupEngine
|
||||
$profile = $db->loadObject();
|
||||
|
||||
if (!$profile) {
|
||||
return ['success' => false, 'message' => 'Profile not found: ' . $profileId];
|
||||
return ['success' => false, 'message' => 'Profile not found: ' . $profileId, 'warnings' => []];
|
||||
}
|
||||
|
||||
// Log any preflight warnings
|
||||
foreach ($preflightResult['warnings'] as $warning) {
|
||||
$this->log('PREFLIGHT WARNING: ' . $warning);
|
||||
}
|
||||
|
||||
// Read settings directly from profile columns
|
||||
@@ -68,16 +78,23 @@ class BackupEngine
|
||||
$this->backupDir = BackupDirectory::resolve($resolver->resolve($configuredDir));
|
||||
|
||||
if (!BackupDirectory::ensureReady($this->backupDir)) {
|
||||
return ['success' => false, 'message' => 'Cannot create backup directory: ' . $this->backupDir, 'record_id' => 0];
|
||||
return ['success' => false, 'message' => 'Cannot create backup directory: ' . $this->backupDir, 'record_id' => 0, 'warnings' => $preflightResult['warnings']];
|
||||
}
|
||||
|
||||
// Create backup record
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$tag = $resolver->getTag();
|
||||
$archiveFormat = $profile->archive_format ?? 'zip';
|
||||
$archiveName = '';
|
||||
$archiver = $this->createArchiver($archiveFormat);
|
||||
|
||||
// Pass encryption password to 7z archiver (handles it natively via -p flag)
|
||||
if ($archiver instanceof SevenZipArchiver && !empty($profile->encryption_password)) {
|
||||
$archiver->setEncryptionPassword($profile->encryption_password);
|
||||
}
|
||||
|
||||
$archiveExt = $archiver->getExtension();
|
||||
$nameFormat = $profile->archive_name_format ?? '[host]_[datetime]_profile[profile_id]';
|
||||
$nameFormat = $profile->archive_name_format ?? '[HOST]_[DATETIME]_profile[PROFILE_ID]';
|
||||
$archiveName = $resolver->resolve($nameFormat) . '.' . $archiveExt;
|
||||
|
||||
if (empty($description)) {
|
||||
@@ -120,12 +137,27 @@ class BackupEngine
|
||||
$tablesCount = 0;
|
||||
|
||||
// Step 1: Database dump (unless files-only)
|
||||
// Streams to a temp file to avoid loading the entire dump into RAM
|
||||
$sqlTempFile = '';
|
||||
|
||||
if ($profile->backup_type !== 'files') {
|
||||
$this->log('Starting database dump...');
|
||||
$dumper = new DatabaseDumper($excludeTables);
|
||||
$sqlDump = $dumper->dump();
|
||||
$archiver->addFromString('database.sql', $sqlDump);
|
||||
$dbSize = strlen($sqlDump);
|
||||
$sqlTempFile = $this->backupDir . '/.database-' . $tag . '.sql';
|
||||
$sanitizePasswords = (bool) ($profile->sanitize_passwords ?? false);
|
||||
$preserveSuperAdmin = (bool) ($profile->preserve_super_admin ?? false);
|
||||
$sanitizeEmails = (bool) ($profile->sanitize_emails ?? false);
|
||||
$sanitizeSessions = (bool) ($profile->sanitize_sessions ?? true);
|
||||
$dumper = new DatabaseDumper($excludeTables, $sanitizePasswords, $preserveSuperAdmin, $sanitizeEmails, $sanitizeSessions);
|
||||
|
||||
if ($sanitizePasswords) {
|
||||
$this->log('User passwords will be sanitized' . ($preserveSuperAdmin ? ' (super admin preserved)' : ''));
|
||||
}
|
||||
|
||||
if ($sanitizeEmails) {
|
||||
$this->log('User emails will be sanitized');
|
||||
}
|
||||
$dbSize = $dumper->dumpToFile($sqlTempFile);
|
||||
$archiver->addFile($sqlTempFile, 'database.sql');
|
||||
$tablesCount = $dumper->getTablesCount();
|
||||
$this->log('Database dump complete: ' . $tablesCount . ' tables, ' . number_format($dbSize) . ' bytes');
|
||||
}
|
||||
@@ -193,16 +225,23 @@ class BackupEngine
|
||||
|
||||
$archiver->close();
|
||||
|
||||
// Clean up temp SQL file (no longer needed after archive is closed)
|
||||
if (!empty($sqlTempFile) && is_file($sqlTempFile)) {
|
||||
@unlink($sqlTempFile);
|
||||
}
|
||||
|
||||
// Step 1.5: Apply AES-256 encryption (if configured)
|
||||
$encryptionPassword = $profile->encryption_password ?? '';
|
||||
|
||||
if (!empty($encryptionPassword)) {
|
||||
if ($archiveFormat !== 'zip') {
|
||||
$this->log('WARNING: AES-256 encryption only supported for ZIP archives — skipping encryption');
|
||||
} else {
|
||||
if ($archiveFormat === 'zip') {
|
||||
$this->log('Encrypting archive with AES-256...');
|
||||
$this->encryptArchive($archivePath, $encryptionPassword);
|
||||
$this->log('Archive encrypted');
|
||||
} elseif ($archiveFormat === '7z') {
|
||||
$this->log('Archive encrypted with AES-256 (7z native encryption)');
|
||||
} else {
|
||||
$this->log('WARNING: AES-256 encryption only supported for ZIP and 7z archives — skipping encryption');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,56 +252,122 @@ class BackupEngine
|
||||
$this->log('Archive created: ' . $sizeHuman);
|
||||
$this->log('SHA-256: ' . ($checksum ?: 'N/A'));
|
||||
|
||||
// Step 2.5: Wrap with MokoRestore script (if enabled)
|
||||
$includeMokoRestore = (bool) ($profile->include_mokorestore ?? false);
|
||||
// Verify archive integrity
|
||||
$this->log('Verifying archive integrity...');
|
||||
$this->verifyArchive($archivePath, $profile->backup_type);
|
||||
$this->log('Archive integrity verified');
|
||||
|
||||
if ($includeMokoRestore) {
|
||||
// Step 2.5: MokoRestore script (if enabled)
|
||||
$mokoRestoreMode = $profile->include_mokorestore ?? '0';
|
||||
$restoreScriptName = $profile->restore_script_name ?? 'restore.php';
|
||||
$restoreScriptPath = '';
|
||||
|
||||
if ($mokoRestoreMode === '1') {
|
||||
$this->log('Wrapping with MokoRestore script...');
|
||||
$mokoRestoreName = str_replace('.zip', '-mokorestore.zip', $archiveName);
|
||||
$mokoRestorePath = $this->backupDir . '/' . $mokoRestoreName;
|
||||
MokoRestore::wrap($archivePath, $mokoRestorePath);
|
||||
MokoRestore::wrap($archivePath, $mokoRestorePath, $restoreScriptName);
|
||||
|
||||
// Replace the original archive with the wrapped one
|
||||
if (is_file($archivePath) && !unlink($archivePath)) {
|
||||
$this->log('WARNING: Could not remove pre-wrap archive');
|
||||
}
|
||||
rename($mokoRestorePath, $archivePath);
|
||||
$totalSize = filesize($archivePath);
|
||||
$sizeHuman = number_format($totalSize / 1048576, 2) . ' MB';
|
||||
// Recompute checksum for the final wrapped archive
|
||||
$checksum = hash_file('sha256', $archivePath);
|
||||
$this->log('MokoRestore archive created: ' . $sizeHuman);
|
||||
$this->log('SHA-256 (wrapped): ' . $checksum);
|
||||
} elseif ($mokoRestoreMode === 'standalone') {
|
||||
$restoreScriptName = MokoRestore::sanitizeScriptName($restoreScriptName);
|
||||
$this->log('Generating standalone ' . $restoreScriptName . '...');
|
||||
$restoreScriptPath = $this->backupDir . '/' . $restoreScriptName;
|
||||
MokoRestore::generateStandalone($restoreScriptPath);
|
||||
$this->log('Standalone ' . $restoreScriptName . ' generated (' . number_format(filesize($restoreScriptPath)) . ' bytes)');
|
||||
}
|
||||
|
||||
$remoteFilename = '';
|
||||
$uploadFailed = false;
|
||||
|
||||
// Step 3: Remote upload (if configured)
|
||||
$remoteStorage = $profile->remote_storage ?? 'none';
|
||||
/* Step 3: Remote upload — iterate all enabled destinations */
|
||||
$remotes = $this->loadRemoteDestinations($db, $profileId);
|
||||
|
||||
if ($remoteStorage !== 'none') {
|
||||
$this->log('Starting remote upload (' . $remoteStorage . ')...');
|
||||
$uploader = $this->createUploader($remoteStorage, $profile);
|
||||
$uploadResult = $uploader->upload($archivePath, $archiveName);
|
||||
if (!empty($remotes)) {
|
||||
foreach ($remotes as $remote) {
|
||||
try {
|
||||
$this->log('Uploading to: ' . $remote->title . ' (' . $remote->type . ')...');
|
||||
$params = json_decode($remote->params, true) ?: [];
|
||||
$uploader = $this->createUploaderFromParams($remote->type, $params);
|
||||
$result = $uploader->upload($archivePath, $archiveName);
|
||||
|
||||
if ($uploadResult['success']) {
|
||||
$remoteFilename = $uploadResult['remote_path'] ?? $archiveName;
|
||||
$this->log('Remote upload complete: ' . $uploadResult['message']);
|
||||
if ($result['success']) {
|
||||
$remoteFilename = $result['remote_path'] ?? $archiveName;
|
||||
$this->log(' Upload complete: ' . $result['message']);
|
||||
|
||||
// Delete local copy if configured
|
||||
if (empty($profile->remote_keep_local) && is_file($archivePath)) {
|
||||
@unlink($archivePath);
|
||||
$this->log('Local copy removed (remote_keep_local = off)');
|
||||
if (!empty($restoreScriptPath) && is_file($restoreScriptPath)) {
|
||||
$uploader->upload($restoreScriptPath, basename($restoreScriptPath));
|
||||
}
|
||||
} else {
|
||||
$uploadFailed = true;
|
||||
$this->log(' WARNING: Upload failed: ' . $result['message']);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$uploadFailed = true;
|
||||
$this->log(' WARNING: Upload exception: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/* Delete local copy only when ALL remotes succeeded and profile says so */
|
||||
if (!$uploadFailed && empty($profile->remote_keep_local) && is_file($archivePath)) {
|
||||
@unlink($archivePath);
|
||||
$this->log('Local copy removed (remote_keep_local = off)');
|
||||
}
|
||||
} else {
|
||||
/* Backward-compat: fall back to legacy single-remote column */
|
||||
$remoteStorage = $profile->remote_storage ?? 'none';
|
||||
|
||||
if ($remoteStorage !== 'none') {
|
||||
try {
|
||||
$this->log('Starting remote upload (' . $remoteStorage . ')...');
|
||||
$uploader = $this->createUploader($remoteStorage, $profile);
|
||||
$uploadResult = $uploader->upload($archivePath, $archiveName);
|
||||
|
||||
if ($uploadResult['success']) {
|
||||
$remoteFilename = $uploadResult['remote_path'] ?? $archiveName;
|
||||
$this->log('Remote upload complete: ' . $uploadResult['message']);
|
||||
|
||||
if (!empty($restoreScriptPath) && is_file($restoreScriptPath)) {
|
||||
$restoreBasename = basename($restoreScriptPath);
|
||||
$this->log('Uploading standalone ' . $restoreBasename . '...');
|
||||
$restoreUpload = $uploader->upload($restoreScriptPath, $restoreBasename);
|
||||
|
||||
if ($restoreUpload['success']) {
|
||||
$this->log('Standalone ' . $restoreBasename . ' uploaded');
|
||||
} else {
|
||||
$this->log('WARNING: ' . $restoreBasename . ' upload failed: ' . $restoreUpload['message']);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete local copy if configured
|
||||
if (empty($profile->remote_keep_local) && is_file($archivePath)) {
|
||||
@unlink($archivePath);
|
||||
$this->log('Local copy removed (remote_keep_local = off)');
|
||||
}
|
||||
} else {
|
||||
$uploadFailed = true;
|
||||
$this->log('WARNING: Remote upload failed: ' . $uploadResult['message']);
|
||||
$this->log('Local backup is preserved.');
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$uploadFailed = true;
|
||||
$this->log('WARNING: Remote upload threw an exception: ' . $e->getMessage());
|
||||
$this->log('Local backup is preserved.');
|
||||
}
|
||||
} else {
|
||||
$this->log('WARNING: Remote upload failed: ' . $uploadResult['message']);
|
||||
$this->log('Local backup is preserved.');
|
||||
}
|
||||
}
|
||||
|
||||
// Write log file alongside the archive
|
||||
$logContent = implode("\n", $this->log);
|
||||
$logPath = preg_replace('/\.(zip|tar\.gz)$/i', '.log', $archivePath);
|
||||
$logPath = preg_replace('/\.(zip|tar\.gz|7z)$/i', '.log', $archivePath);
|
||||
if (@file_put_contents($logPath, $logContent) === false) {
|
||||
error_log('MokoSuiteBackup: Could not write log file: ' . $logPath);
|
||||
}
|
||||
@@ -290,9 +395,14 @@ class BackupEngine
|
||||
|
||||
$db->updateObject('#__mokosuitebackup_records', $update, 'id');
|
||||
|
||||
// Send success notification
|
||||
// Send success notification (backup completed, even if upload failed)
|
||||
NotificationSender::send($profile, $update, true, implode("\n", $this->log));
|
||||
|
||||
// If remote upload failed, also send a failure notification for the upload
|
||||
if ($uploadFailed) {
|
||||
NotificationSender::send($profile, $update, false, "Remote upload failed — see backup log for details.\n\n" . implode("\n", $this->log));
|
||||
}
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterRun(true, $recordId, $description, $profileId, $origin);
|
||||
|
||||
@@ -300,10 +410,22 @@ class BackupEngine
|
||||
'success' => true,
|
||||
'message' => 'Backup complete: ' . $archiveName . ' (' . $sizeHuman . ')',
|
||||
'record_id' => $recordId,
|
||||
'warnings' => $preflightResult['warnings'],
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
$this->log('FATAL: ' . $e->getMessage());
|
||||
|
||||
// Clean up temp SQL file on failure
|
||||
if (!empty($sqlTempFile) && is_file($sqlTempFile)) {
|
||||
@unlink($sqlTempFile);
|
||||
}
|
||||
|
||||
// If encryption was intended and failed, remove the plaintext archive
|
||||
if (!empty($encryptionPassword) && !empty($archivePath) && is_file($archivePath)) {
|
||||
@unlink($archivePath);
|
||||
$this->log('Plaintext archive removed after encryption failure');
|
||||
}
|
||||
|
||||
$update = (object) [
|
||||
'id' => $recordId,
|
||||
'status' => 'fail',
|
||||
@@ -328,7 +450,7 @@ class BackupEngine
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterRun(false, $recordId, $description, $profileId, $origin);
|
||||
|
||||
return ['success' => false, 'message' => 'Backup failed: ' . $e->getMessage(), 'record_id' => $recordId];
|
||||
return ['success' => false, 'message' => 'Backup failed: ' . $e->getMessage(), 'record_id' => $recordId, 'warnings' => $preflightResult['warnings'] ?? []];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,35 +505,6 @@ class BackupEngine
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify required PHP extensions are loaded.
|
||||
*
|
||||
* @return true|string True if all ok, or error message string
|
||||
*/
|
||||
private function checkRequiredExtensions(): true|string
|
||||
{
|
||||
$required = [
|
||||
'zip' => 'ext-zip (required for archive creation)',
|
||||
'pdo' => 'ext-pdo (required for database operations)',
|
||||
'pdo_mysql' => 'ext-pdo_mysql (required for MySQL database dumps)',
|
||||
'mbstring' => 'ext-mbstring (required for binary-safe operations)',
|
||||
];
|
||||
|
||||
$missing = [];
|
||||
|
||||
foreach ($required as $ext => $label) {
|
||||
if (!extension_loaded($ext)) {
|
||||
$missing[] = $label;
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($missing)) {
|
||||
return 'Missing PHP extensions: ' . implode(', ', $missing);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the appropriate archiver based on the archive format.
|
||||
*/
|
||||
@@ -420,23 +513,80 @@ class BackupEngine
|
||||
return match ($format) {
|
||||
'zip' => new ZipArchiver(),
|
||||
'tar.gz' => new TarGzArchiver(),
|
||||
default => new ZipArchiver(),
|
||||
'7z' => new SevenZipArchiver(),
|
||||
default => throw new \InvalidArgumentException('Unknown archive format: ' . $format),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the appropriate remote uploader based on the storage type.
|
||||
* Legacy method — used by backward-compat fallback when remotes table
|
||||
* does not exist.
|
||||
*/
|
||||
private function createUploader(string $type, object $profile): RemoteUploaderInterface
|
||||
{
|
||||
return match ($type) {
|
||||
'ftp' => new FtpUploader($profile),
|
||||
'sftp' => new SftpUploader($profile),
|
||||
'google_drive' => new GoogleDriveUploader($profile),
|
||||
's3' => new S3Uploader($profile),
|
||||
default => throw new \InvalidArgumentException('Unknown remote storage type: ' . $type),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a remote uploader from JSON params (multi-remote destinations).
|
||||
*
|
||||
* Builds a fake profile-like object from the params array so the existing
|
||||
* uploader constructors work without modification.
|
||||
*
|
||||
* @param string $type Remote type: ftp, sftp, s3, google_drive
|
||||
* @param array $params Key-value params decoded from the remote's JSON
|
||||
*
|
||||
* @return RemoteUploaderInterface
|
||||
*/
|
||||
private function createUploaderFromParams(string $type, array $params): RemoteUploaderInterface
|
||||
{
|
||||
$fake = (object) $params;
|
||||
|
||||
return match ($type) {
|
||||
'ftp' => new FtpUploader($fake),
|
||||
'sftp' => new SftpUploader($fake),
|
||||
'google_drive' => new GoogleDriveUploader($fake),
|
||||
's3' => new S3Uploader($fake),
|
||||
default => throw new \InvalidArgumentException('Unknown remote storage type: ' . $type),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load enabled remote destinations for a profile from the remotes table.
|
||||
*
|
||||
* Returns an empty array when the table does not exist (pre-migration)
|
||||
* so the caller can fall back to the legacy single-remote column.
|
||||
*
|
||||
* @param object $db Database driver
|
||||
* @param int $profileId Profile ID
|
||||
*
|
||||
* @return object[] Array of remote destination rows
|
||||
*/
|
||||
private function loadRemoteDestinations(object $db, int $profileId): array
|
||||
{
|
||||
try {
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_remotes'))
|
||||
->where($db->quoteName('profile_id') . ' = ' . (int) $profileId)
|
||||
->where($db->quoteName('enabled') . ' = 1')
|
||||
->order($db->quoteName('ordering') . ' ASC');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadObjectList() ?: [];
|
||||
} catch (\Throwable $e) {
|
||||
// Table does not exist yet (pre-migration) — fall back to legacy
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the file manifest from the most recent full backup for this profile.
|
||||
* Used by differential backups to determine which files changed.
|
||||
@@ -501,6 +651,155 @@ class BackupEngine
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that a backup archive can be opened and contains expected entries.
|
||||
*
|
||||
* @param string $archivePath Absolute path to the archive file
|
||||
* @param string $backupType Backup type: full, database, files, differential
|
||||
*
|
||||
* @throws \RuntimeException If the archive fails verification
|
||||
*/
|
||||
private function verifyArchive(string $archivePath, string $backupType): void
|
||||
{
|
||||
if (!is_file($archivePath)) {
|
||||
throw new \RuntimeException('Archive file does not exist: ' . $archivePath);
|
||||
}
|
||||
|
||||
$extension = strtolower(pathinfo($archivePath, PATHINFO_EXTENSION));
|
||||
|
||||
// Detect tar.gz (pathinfo only returns 'gz')
|
||||
if ($extension === 'gz' && str_ends_with(strtolower($archivePath), '.tar.gz')) {
|
||||
$this->verifyTarGzArchive($archivePath);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 7z verification via CLI
|
||||
if ($extension === '7z') {
|
||||
$this->verify7zArchive($archivePath);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// ZIP verification
|
||||
$zip = new \ZipArchive();
|
||||
|
||||
if ($zip->open($archivePath, \ZipArchive::RDONLY) !== true) {
|
||||
throw new \RuntimeException('Archive integrity check failed: cannot open ZIP file');
|
||||
}
|
||||
|
||||
if ($zip->numFiles < 1) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive integrity check failed: archive contains no files');
|
||||
}
|
||||
|
||||
// Verify database.sql exists when backup includes database
|
||||
if ($backupType !== 'files') {
|
||||
if ($zip->locateName('database.sql') === false) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive integrity check failed: database.sql missing from archive');
|
||||
}
|
||||
}
|
||||
|
||||
// Spot-check: verify the first entry is readable
|
||||
$firstName = $zip->getNameIndex(0);
|
||||
|
||||
if ($firstName === false) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive integrity check failed: cannot read first entry');
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a tar.gz archive can be opened and iterated.
|
||||
*
|
||||
* @param string $archivePath Absolute path to the .tar.gz file
|
||||
*
|
||||
* @throws \RuntimeException If the archive fails verification
|
||||
*/
|
||||
private function verifyTarGzArchive(string $archivePath): void
|
||||
{
|
||||
try {
|
||||
$phar = new \PharData($archivePath);
|
||||
$count = 0;
|
||||
|
||||
foreach ($phar as $entry) {
|
||||
// Spot-check: verify at least the first entry is accessible
|
||||
$entry->getFilename();
|
||||
$count++;
|
||||
break;
|
||||
}
|
||||
|
||||
if ($count === 0) {
|
||||
throw new \RuntimeException('Archive integrity check failed: tar.gz archive contains no entries');
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
throw $e;
|
||||
} catch (\Throwable $e) {
|
||||
throw new \RuntimeException('Archive integrity check failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a 7z archive using the CLI binary.
|
||||
*
|
||||
* @param string $archivePath Absolute path to the .7z file
|
||||
*
|
||||
* @throws \RuntimeException If the archive fails verification
|
||||
*/
|
||||
private function verify7zArchive(string $archivePath): void
|
||||
{
|
||||
// Test the archive with 7z t (test integrity)
|
||||
$candidates = PHP_OS_FAMILY === 'Windows'
|
||||
? ['7z', '7za', 'C:\\Program Files\\7-Zip\\7z.exe', 'C:\\Program Files (x86)\\7-Zip\\7z.exe']
|
||||
: ['7za', '7z', '/usr/bin/7za', '/usr/bin/7z', '/usr/local/bin/7za', '/usr/local/bin/7z'];
|
||||
|
||||
$binary = null;
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if (str_contains($candidate, DIRECTORY_SEPARATOR) || str_contains($candidate, '/')) {
|
||||
if (is_file($candidate) && is_executable($candidate)) {
|
||||
$binary = $candidate;
|
||||
break;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$whichCmd = PHP_OS_FAMILY === 'Windows'
|
||||
? 'where ' . escapeshellarg($candidate) . ' 2>NUL'
|
||||
: 'which ' . escapeshellarg($candidate) . ' 2>/dev/null';
|
||||
|
||||
$result = trim((string) shell_exec($whichCmd));
|
||||
|
||||
if ($result !== '' && is_executable($result)) {
|
||||
$binary = $result;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($binary === null) {
|
||||
// Cannot verify without the binary — log warning but don't fail
|
||||
$this->log('WARNING: Cannot verify 7z archive (7z binary not found for test)');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$cmd = escapeshellarg($binary) . ' t ' . escapeshellarg($archivePath) . ' -y 2>&1';
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec($cmd, $output, $exitCode);
|
||||
|
||||
if ($exitCode !== 0) {
|
||||
throw new \RuntimeException(
|
||||
'Archive integrity check failed: 7z test exited with code ' . $exitCode
|
||||
. ': ' . implode("\n", array_slice($output, -5))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch the onMokoSuiteBackupAfterRun event so plugins (actionlog, etc.) can react.
|
||||
*/
|
||||
|
||||
@@ -27,12 +27,35 @@ class DatabaseDumper
|
||||
|
||||
private int $tablesCount = 0;
|
||||
|
||||
/** @var bool Whether to sanitize user passwords */
|
||||
private bool $sanitizePasswords = false;
|
||||
|
||||
/** @var bool Whether to preserve super admin password when sanitizing */
|
||||
private bool $preserveSuperAdmin = false;
|
||||
|
||||
/** @var bool Whether to sanitize user emails */
|
||||
private bool $sanitizeEmails = false;
|
||||
|
||||
/** @var bool Whether to clear session data */
|
||||
private bool $sanitizeSessions = false;
|
||||
|
||||
/** Known invalid bcrypt hash used for sanitized passwords */
|
||||
private const SANITIZED_HASH = '$2y$10$SANITIZED.MOKOSUITEBACKUP.INVALID.HASH.DO.NOT.USE.000000';
|
||||
|
||||
/**
|
||||
* @param array $excludeTables Table names to exclude (with #__ prefix).
|
||||
* Supports suffixes: :data-only, :structure-only.
|
||||
* No suffix = exclude both (backward compatible).
|
||||
* @param array $excludeTables Table names to exclude (with #__ prefix).
|
||||
* @param bool $sanitizePasswords Replace user password hashes with invalid value
|
||||
* @param bool $preserveSuperAdmin Keep super admin password when sanitizing
|
||||
* @param bool $sanitizeEmails Replace user emails with sanitized placeholders
|
||||
* @param bool $sanitizeSessions Skip session table data entirely
|
||||
*/
|
||||
public function __construct(array $excludeTables = [])
|
||||
public function __construct(
|
||||
array $excludeTables = [],
|
||||
bool $sanitizePasswords = false,
|
||||
bool $preserveSuperAdmin = false,
|
||||
bool $sanitizeEmails = false,
|
||||
bool $sanitizeSessions = false
|
||||
)
|
||||
{
|
||||
foreach ($excludeTables as $entry) {
|
||||
if (str_ends_with($entry, ':data-only')) {
|
||||
@@ -43,6 +66,16 @@ class DatabaseDumper
|
||||
$this->excludeBoth[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
$this->sanitizePasswords = $sanitizePasswords;
|
||||
$this->preserveSuperAdmin = $preserveSuperAdmin;
|
||||
$this->sanitizeEmails = $sanitizeEmails;
|
||||
$this->sanitizeSessions = $sanitizeSessions;
|
||||
|
||||
/* If session sanitization is on, auto-exclude session table data */
|
||||
if ($sanitizeSessions) {
|
||||
$this->excludeDataOnly[] = '#__session';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -154,6 +187,7 @@ class DatabaseDumper
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$this->sanitizeRow($row, $abstractName, $db);
|
||||
$values = [];
|
||||
|
||||
foreach ($row as $value) {
|
||||
@@ -219,6 +253,219 @@ class DatabaseDumper
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dump all database tables directly to a file, streaming row by row.
|
||||
* Avoids loading the entire dump into RAM.
|
||||
*
|
||||
* @param string $filePath Absolute path to write the SQL file
|
||||
*
|
||||
* @return int Size of the dump file in bytes
|
||||
*/
|
||||
public function dumpToFile(string $filePath): int
|
||||
{
|
||||
$db = Factory::getDbo();
|
||||
$prefix = $db->getPrefix();
|
||||
|
||||
$fp = fopen($filePath, 'w');
|
||||
|
||||
if ($fp === false) {
|
||||
throw new \RuntimeException('Cannot open dump file for writing: ' . $filePath);
|
||||
}
|
||||
|
||||
fwrite($fp, "-- MokoSuiteBackup Database Dump\n");
|
||||
fwrite($fp, "-- Generated: " . date('Y-m-d H:i:s') . "\n");
|
||||
fwrite($fp, "-- Server: " . $db->getServerType() . "\n");
|
||||
fwrite($fp, "-- Database: " . $db->getName() . "\n");
|
||||
fwrite($fp, "-- Original Prefix: " . $prefix . "\n");
|
||||
fwrite($fp, "-- Abstract Prefix: #__\n");
|
||||
fwrite($fp, "-- Note: Table names use #__ placeholder. Replace with your prefix on restore.\n\n");
|
||||
fwrite($fp, "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n");
|
||||
fwrite($fp, "SET time_zone = \"+00:00\";\n\n");
|
||||
|
||||
// Get all tables with the site prefix
|
||||
$tables = $db->getTableList();
|
||||
$siteTables = [];
|
||||
|
||||
foreach ($tables as $table) {
|
||||
if (str_starts_with($table, $prefix)) {
|
||||
$siteTables[] = $table;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($siteTables as $table) {
|
||||
$abstractName = '#__' . substr($table, strlen($prefix));
|
||||
|
||||
if ($this->isExcludedBoth($abstractName, $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$skipData = $this->isExcludedDataOnly($abstractName, $table);
|
||||
$skipStructure = $this->isExcludedStructureOnly($abstractName, $table);
|
||||
|
||||
$this->tablesCount++;
|
||||
|
||||
fwrite($fp, "-- --------------------------------------------------------\n");
|
||||
fwrite($fp, "-- Table: " . $abstractName . "\n");
|
||||
|
||||
if ($skipData) {
|
||||
fwrite($fp, "-- (data excluded)\n");
|
||||
}
|
||||
|
||||
if ($skipStructure) {
|
||||
fwrite($fp, "-- (structure excluded)\n");
|
||||
}
|
||||
|
||||
fwrite($fp, "-- --------------------------------------------------------\n\n");
|
||||
|
||||
if (!$skipStructure) {
|
||||
$db->setQuery('SHOW CREATE TABLE ' . $db->quoteName($table));
|
||||
$createRow = $db->loadRow();
|
||||
|
||||
if (!$createRow || empty($createRow[1])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$createSql = str_replace('`' . $prefix, '`#__', $createRow[1]);
|
||||
fwrite($fp, 'DROP TABLE IF EXISTS `' . $abstractName . "`;\\n");
|
||||
fwrite($fp, $createSql . ";\n\n");
|
||||
}
|
||||
|
||||
if ($skipData) {
|
||||
fwrite($fp, "\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
$db->setQuery('SELECT COUNT(*) FROM ' . $db->quoteName($table));
|
||||
$rowCount = (int) $db->loadResult();
|
||||
|
||||
if ($rowCount === 0) {
|
||||
fwrite($fp, "-- (empty table)\n\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
$chunkSize = 500;
|
||||
|
||||
for ($offset = 0; $offset < $rowCount; $offset += $chunkSize) {
|
||||
$db->setQuery(
|
||||
$db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName($table)),
|
||||
$offset,
|
||||
$chunkSize
|
||||
);
|
||||
$rows = $db->loadAssocList();
|
||||
|
||||
if (empty($rows)) {
|
||||
break;
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$this->sanitizeRow($row, $abstractName, $db);
|
||||
$values = [];
|
||||
|
||||
foreach ($row as $value) {
|
||||
if ($value === null) {
|
||||
$values[] = 'NULL';
|
||||
} else {
|
||||
$values[] = $db->quote($value);
|
||||
}
|
||||
}
|
||||
|
||||
$columns = array_map([$db, 'quoteName'], array_keys($row));
|
||||
fwrite($fp, 'INSERT INTO `' . $abstractName . '`'
|
||||
. ' (' . implode(', ', $columns) . ')'
|
||||
. ' VALUES (' . implode(', ', $values) . ");\n");
|
||||
}
|
||||
}
|
||||
|
||||
fwrite($fp, "\n");
|
||||
}
|
||||
|
||||
fclose($fp);
|
||||
|
||||
return filesize($filePath) ?: 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a row if it belongs to the users table and sanitization is enabled.
|
||||
*
|
||||
* Replaces the password column with an invalid hash so the backup
|
||||
* cannot be used to extract user credentials.
|
||||
*/
|
||||
private function sanitizeRow(array &$row, string $abstractTable, object $db): void
|
||||
{
|
||||
if ($abstractTable !== '#__users') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$this->sanitizePasswords && !$this->sanitizeEmails) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->sanitizeEmails && isset($row['email']) && isset($row['id'])) {
|
||||
$userId = (int) $row['id'];
|
||||
|
||||
/* Preserve super admin emails if preserving super admin */
|
||||
if (!$this->preserveSuperAdmin || !$this->isSuperAdmin($userId, $db)) {
|
||||
$row['email'] = 'user' . $userId . '@sanitized.example.com';
|
||||
}
|
||||
}
|
||||
|
||||
if (!$this->sanitizePasswords || !isset($row['password'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->preserveSuperAdmin && isset($row['id'])) {
|
||||
if ($this->isSuperAdmin((int) $row['id'], $db)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$row['password'] = self::SANITIZED_HASH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user ID belongs to the Super Users group (group_id = 8).
|
||||
*/
|
||||
private function isSuperAdmin(int $userId, object $db): bool
|
||||
{
|
||||
static $superAdminIds = null;
|
||||
|
||||
if ($superAdminIds === null) {
|
||||
$prefix = $db->getPrefix();
|
||||
|
||||
try {
|
||||
$db->setQuery(
|
||||
$db->getQuery(true)
|
||||
->select('DISTINCT ' . $db->quoteName('user_id'))
|
||||
->from($db->quoteName($prefix . 'user_usergroup_map'))
|
||||
->where($db->quoteName('group_id') . ' = 8')
|
||||
);
|
||||
$superAdminIds = array_map('intval', $db->loadColumn() ?: []);
|
||||
} catch (\Throwable $e) {
|
||||
$superAdminIds = [];
|
||||
}
|
||||
}
|
||||
|
||||
return in_array($userId, $superAdminIds, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if passwords were sanitized (for use by callers to log the action).
|
||||
*/
|
||||
public function isPasswordSanitizationEnabled(): bool
|
||||
{
|
||||
return $this->sanitizePasswords;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the sentinel hash used for sanitized passwords.
|
||||
*/
|
||||
public static function getSanitizedHash(): string
|
||||
{
|
||||
return self::SANITIZED_HASH;
|
||||
}
|
||||
|
||||
public function getTablesCount(): int
|
||||
{
|
||||
return $this->tablesCount;
|
||||
|
||||
@@ -206,6 +206,11 @@ class JpaUnarchiver
|
||||
}
|
||||
}
|
||||
|
||||
// Path traversal protection: reject absolute paths and directory traversal
|
||||
if (str_starts_with($path, '/') || str_starts_with($path, '\\') || str_contains($path, '..')) {
|
||||
return; // skip malicious entry
|
||||
}
|
||||
|
||||
// Is this a directory?
|
||||
if (substr($path, -1) === '/' || $uncompSize === 0 && $compSize === 0) {
|
||||
$dirPath = $this->outputDir . '/' . $path;
|
||||
@@ -228,6 +233,24 @@ class JpaUnarchiver
|
||||
|
||||
// Write file
|
||||
$fullPath = $this->outputDir . '/' . $path;
|
||||
|
||||
// Verify resolved path stays within output directory
|
||||
$realOutput = realpath($this->outputDir);
|
||||
|
||||
if ($realOutput !== false) {
|
||||
$parentDir = dirname($fullPath);
|
||||
|
||||
if (!is_dir($parentDir)) {
|
||||
mkdir($parentDir, 0755, true);
|
||||
}
|
||||
|
||||
$realDest = realpath($parentDir);
|
||||
|
||||
if ($realDest === false || !str_starts_with($realDest, $realOutput)) {
|
||||
return; // path escapes staging directory
|
||||
}
|
||||
}
|
||||
|
||||
$parentDir = dirname($fullPath);
|
||||
|
||||
if (!is_dir($parentDir)) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -236,6 +236,297 @@ class NotificationSender
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a restore/snapshot notification via email and ntfy.
|
||||
*
|
||||
* @param object $profile Profile object with notification settings
|
||||
* @param string $type One of: site_restore, snapshot_create, snapshot_restore
|
||||
* @param array $details Context: record_id, content_types, row_count, mode, user, etc.
|
||||
* @param string $log Operation log text
|
||||
*
|
||||
* @return bool True if at least one notification was sent
|
||||
*/
|
||||
public static function sendRestoreNotification(object $profile, string $type, array $details, string $log = ''): bool
|
||||
{
|
||||
$emailSent = self::sendRestoreEmail($profile, $type, $details, $log);
|
||||
$ntfySent = self::sendRestoreNtfy($profile, $type, $details);
|
||||
|
||||
return $emailSent || $ntfySent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the default profile (ID 1) for notification settings.
|
||||
*
|
||||
* @return object|null Profile object or null if not found
|
||||
*/
|
||||
public static function getDefaultProfile(): ?object
|
||||
{
|
||||
try {
|
||||
$db = Factory::getDbo();
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_profiles'))
|
||||
->where($db->quoteName('id') . ' = 1');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadObject() ?: null;
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: Cannot load default profile: ' . $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build subject and body for a restore/snapshot notification email.
|
||||
*/
|
||||
private static function buildRestoreMessage(string $type, array $details, string $siteName, string $siteUrl): array
|
||||
{
|
||||
$user = $details['user'] ?? 'Unknown';
|
||||
|
||||
switch ($type) {
|
||||
case 'site_restore':
|
||||
$subject = "[MokoSuiteBackup] RESTORE: Site restored — {$siteName}";
|
||||
$options = [];
|
||||
|
||||
if (!empty($details['restore_files'])) {
|
||||
$options[] = 'Files';
|
||||
}
|
||||
|
||||
if (!empty($details['restore_db'])) {
|
||||
$options[] = 'Database';
|
||||
}
|
||||
|
||||
if (!empty($details['preserve_config'])) {
|
||||
$options[] = 'Config preserved';
|
||||
}
|
||||
|
||||
$body = "MokoSuiteBackup — Site Restore Notification\n"
|
||||
. "=============================================\n\n"
|
||||
. "Site: {$siteName}\n"
|
||||
. "URL: {$siteUrl}\n"
|
||||
. "Action: Full site restore\n"
|
||||
. "Record ID: " . ($details['record_id'] ?? 'N/A') . "\n"
|
||||
. "Options: " . (empty($options) ? 'N/A' : implode(', ', $options)) . "\n"
|
||||
. "Triggered by: {$user}\n";
|
||||
break;
|
||||
|
||||
case 'snapshot_create':
|
||||
$types = $details['content_types'] ?? [];
|
||||
$typesStr = !empty($types) ? implode(', ', $types) : 'N/A';
|
||||
|
||||
$subject = "[MokoSuiteBackup] SNAPSHOT: Content snapshot created — {$siteName}";
|
||||
$body = "MokoSuiteBackup — Snapshot Created\n"
|
||||
. "===================================\n\n"
|
||||
. "Site: {$siteName}\n"
|
||||
. "URL: {$siteUrl}\n"
|
||||
. "Action: Snapshot created\n"
|
||||
. "Content types: {$typesStr}\n"
|
||||
. "Articles: " . ($details['articles_count'] ?? 0) . "\n"
|
||||
. "Categories: " . ($details['categories_count'] ?? 0) . "\n"
|
||||
. "Modules: " . ($details['modules_count'] ?? 0) . "\n"
|
||||
. "Triggered by: {$user}\n";
|
||||
break;
|
||||
|
||||
case 'snapshot_restore':
|
||||
$types = $details['content_types'] ?? [];
|
||||
$typesStr = !empty($types) ? implode(', ', $types) : 'N/A';
|
||||
|
||||
$subject = "[MokoSuiteBackup] RESTORE: Snapshot restored — {$siteName}";
|
||||
$body = "MokoSuiteBackup — Snapshot Restore Notification\n"
|
||||
. "================================================\n\n"
|
||||
. "Site: {$siteName}\n"
|
||||
. "URL: {$siteUrl}\n"
|
||||
. "Action: Snapshot restore\n"
|
||||
. "Mode: " . ($details['mode'] ?? 'N/A') . "\n"
|
||||
. "Content types: {$typesStr}\n"
|
||||
. "Rows restored: " . ($details['row_count'] ?? 0) . "\n"
|
||||
. "Triggered by: {$user}\n";
|
||||
break;
|
||||
|
||||
default:
|
||||
$subject = "[MokoSuiteBackup] NOTIFICATION: {$type} — {$siteName}";
|
||||
$body = "MokoSuiteBackup Notification\n"
|
||||
. "============================\n\n"
|
||||
. "Site: {$siteName}\n"
|
||||
. "URL: {$siteUrl}\n"
|
||||
. "Type: {$type}\n"
|
||||
. "Details: " . json_encode($details) . "\n";
|
||||
break;
|
||||
}
|
||||
|
||||
$body .= "\n--\n"
|
||||
. "MokoSuiteBackup — https://mokoconsulting.tech\n";
|
||||
|
||||
return ['subject' => $subject, 'body' => $body];
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a restore/snapshot notification email.
|
||||
*/
|
||||
private static function sendRestoreEmail(object $profile, string $type, array $details, string $log = ''): bool
|
||||
{
|
||||
$notifyEmail = trim($profile->notify_email ?? '');
|
||||
$notifyUserGroups = $profile->notify_user_groups ?? '';
|
||||
|
||||
$groupEmails = self::resolveUserGroupEmails($notifyUserGroups);
|
||||
|
||||
if (empty($notifyEmail) && empty($groupEmails)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Restore notifications are always "success" events — use notify_on_success preference
|
||||
if (empty($profile->notify_on_success)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$mailer = Factory::getMailer();
|
||||
$config = Factory::getApplication()->getConfig();
|
||||
$siteName = $config->get('sitename', 'Joomla Site');
|
||||
$siteUrl = Uri::root();
|
||||
|
||||
$recipients = array_map('trim', explode(',', $notifyEmail));
|
||||
$recipients = array_merge($recipients, $groupEmails);
|
||||
$recipients = array_unique(array_filter($recipients, fn($e) => filter_var($e, FILTER_VALIDATE_EMAIL)));
|
||||
|
||||
if (empty($recipients)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($recipients as $recipient) {
|
||||
$mailer->addRecipient($recipient);
|
||||
}
|
||||
|
||||
$message = self::buildRestoreMessage($type, $details, $siteName, $siteUrl);
|
||||
$mailer->setSubject($message['subject']);
|
||||
|
||||
$body = $message['body'];
|
||||
|
||||
// Append log excerpt if provided (last 30 lines)
|
||||
if (!empty($log)) {
|
||||
$logLines = explode("\n", $log);
|
||||
$excerpt = array_slice($logLines, -30);
|
||||
$body .= "\n--- Log (last 30 lines) ---\n"
|
||||
. implode("\n", $excerpt) . "\n";
|
||||
}
|
||||
|
||||
$mailer->setBody($body);
|
||||
$mailer->isHtml(false);
|
||||
|
||||
return $mailer->Send();
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup restore notification error: ' . $e->getMessage());
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a restore/snapshot push notification via ntfy.
|
||||
*/
|
||||
private static function sendRestoreNtfy(object $profile, string $type, array $details): bool
|
||||
{
|
||||
$topic = trim($profile->ntfy_topic ?? '');
|
||||
$server = trim($profile->ntfy_server ?? 'https://ntfy.sh');
|
||||
$token = trim($profile->ntfy_token ?? '');
|
||||
|
||||
if ($topic === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Restore notifications are always "success" events — use notify_on_success preference
|
||||
if (empty($profile->notify_on_success)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!function_exists('curl_init')) {
|
||||
error_log('MokoSuiteBackup: ntfy notifications require ext-curl');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$config = Factory::getApplication()->getConfig();
|
||||
$siteName = $config->get('sitename', 'Joomla Site');
|
||||
|
||||
switch ($type) {
|
||||
case 'site_restore':
|
||||
$emoji = "\xF0\x9F\x94\x84"; // 🔄
|
||||
$title = "{$emoji} Site Restored: {$siteName}";
|
||||
$body = "Record ID: " . ($details['record_id'] ?? 'N/A') . "\n"
|
||||
. "Triggered by: " . ($details['user'] ?? 'Unknown');
|
||||
break;
|
||||
|
||||
case 'snapshot_create':
|
||||
$emoji = "\xF0\x9F\x93\xB8"; // 📸
|
||||
$types = $details['content_types'] ?? [];
|
||||
$title = "{$emoji} Snapshot Created: {$siteName}";
|
||||
$body = "Types: " . implode(', ', $types) . "\n"
|
||||
. "Articles: " . ($details['articles_count'] ?? 0) . "\n"
|
||||
. "Categories: " . ($details['categories_count'] ?? 0) . "\n"
|
||||
. "Modules: " . ($details['modules_count'] ?? 0);
|
||||
break;
|
||||
|
||||
case 'snapshot_restore':
|
||||
$emoji = "\xF0\x9F\x94\x84"; // 🔄
|
||||
$types = $details['content_types'] ?? [];
|
||||
$title = "{$emoji} Snapshot Restored: {$siteName}";
|
||||
$body = "Mode: " . ($details['mode'] ?? 'N/A') . "\n"
|
||||
. "Types: " . implode(', ', $types) . "\n"
|
||||
. "Rows: " . ($details['row_count'] ?? 0);
|
||||
break;
|
||||
|
||||
default:
|
||||
$title = "MokoSuiteBackup: {$type} — {$siteName}";
|
||||
$body = json_encode($details);
|
||||
break;
|
||||
}
|
||||
|
||||
$url = rtrim($server, '/') . '/' . rawurlencode($topic);
|
||||
|
||||
$headers = [
|
||||
'Title: ' . $title,
|
||||
'Priority: 3',
|
||||
'Tags: arrows_counterclockwise',
|
||||
];
|
||||
|
||||
if ($token !== '') {
|
||||
$headers[] = 'Authorization: Bearer ' . $token;
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => $body,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_CONNECTTIMEOUT => 5,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$error = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($error !== '') {
|
||||
error_log('MokoSuiteBackup: ntfy error: ' . $error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($httpCode < 200 || $httpCode >= 300) {
|
||||
error_log('MokoSuiteBackup: ntfy returned HTTP ' . $httpCode . ': ' . substr((string) $response, 0, 200));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: ntfy restore notification error: ' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve user group IDs to email addresses of group members.
|
||||
*
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @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
|
||||
* Resolves placeholders like [HOST], [DATE], [PROFILE_NAME] in backup
|
||||
* directory paths and archive filename formats.
|
||||
*/
|
||||
|
||||
@@ -24,21 +24,21 @@ 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',
|
||||
'[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',
|
||||
];
|
||||
@@ -51,7 +51,32 @@ class PlaceholderResolver
|
||||
public function __construct(object $profile)
|
||||
{
|
||||
$now = new \DateTimeImmutable('now');
|
||||
$hostname = preg_replace('/[^a-zA-Z0-9._-]/', '', $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? php_uname('n'));
|
||||
|
||||
/* Resolve hostname: prefer HTTP_HOST (web), then try Joomla config (CLI), then system hostname */
|
||||
$rawHost = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '';
|
||||
|
||||
if (empty($rawHost) || $rawHost === 'localhost') {
|
||||
try {
|
||||
$app = Factory::getApplication();
|
||||
$liveSite = $app->get('live_site', '');
|
||||
|
||||
if (!empty($liveSite)) {
|
||||
$parsed = parse_url($liveSite, PHP_URL_HOST);
|
||||
|
||||
if (!empty($parsed)) {
|
||||
$rawHost = $parsed;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
/* fallback */
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($rawHost)) {
|
||||
$rawHost = php_uname('n');
|
||||
}
|
||||
|
||||
$hostname = preg_replace('/[^a-zA-Z0-9._-]/', '', $rawHost);
|
||||
|
||||
$siteName = '';
|
||||
|
||||
@@ -62,21 +87,21 @@ class PlaceholderResolver
|
||||
}
|
||||
|
||||
$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)),
|
||||
'[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(),
|
||||
];
|
||||
@@ -103,7 +128,7 @@ class PlaceholderResolver
|
||||
*/
|
||||
public function getHostname(): string
|
||||
{
|
||||
return $this->replacements['[host]'];
|
||||
return $this->replacements['[HOST]'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,7 +136,7 @@ class PlaceholderResolver
|
||||
*/
|
||||
public function getTag(): string
|
||||
{
|
||||
return $this->replacements['[datetime]'];
|
||||
return $this->replacements['[DATETIME]'];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
<?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
|
||||
*
|
||||
* Pre-flight validation for backup operations.
|
||||
*
|
||||
* Runs before any backup record is created, catching problems early
|
||||
* with clear messages instead of failing mid-backup. Returns a result
|
||||
* with errors (blockers) and warnings (informational).
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
use Joomla\Component\MokoSuiteBackup\Administrator\Utility\BackupDirectory;
|
||||
|
||||
class PreflightCheck
|
||||
{
|
||||
/** @var string[] Fatal issues that prevent backup from starting */
|
||||
private array $errors = [];
|
||||
|
||||
/** @var string[] Non-fatal issues the user should know about */
|
||||
private array $warnings = [];
|
||||
|
||||
/**
|
||||
* Run all pre-flight checks for a backup profile.
|
||||
*
|
||||
* @param int $profileId Profile to validate
|
||||
*
|
||||
* @return array{pass: bool, errors: string[], warnings: string[]}
|
||||
*/
|
||||
public function run(int $profileId): array
|
||||
{
|
||||
try {
|
||||
$db = Factory::getDbo();
|
||||
} catch (\Exception $e) {
|
||||
$this->errors[] = 'Cannot connect to database: ' . $e->getMessage();
|
||||
|
||||
return $this->result();
|
||||
}
|
||||
|
||||
// Load profile
|
||||
try {
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_profiles'))
|
||||
->where($db->quoteName('id') . ' = ' . (int) $profileId);
|
||||
$db->setQuery($query);
|
||||
$profile = $db->loadObject();
|
||||
} catch (\Exception $e) {
|
||||
$this->errors[] = 'Cannot load profile: ' . $e->getMessage();
|
||||
|
||||
return $this->result();
|
||||
}
|
||||
|
||||
if (!$profile) {
|
||||
$this->errors[] = 'Profile not found: #' . $profileId;
|
||||
|
||||
return $this->result();
|
||||
}
|
||||
|
||||
if (!$profile->published) {
|
||||
$this->errors[] = 'Profile is unpublished: ' . $profile->title;
|
||||
|
||||
return $this->result();
|
||||
}
|
||||
|
||||
$this->checkPhpExtensions($profile);
|
||||
$this->checkBackupDirectory($profile);
|
||||
$this->checkDiskSpace($profile, $db);
|
||||
$this->checkRunningBackup($profile, $db);
|
||||
$this->checkExcludedTables($profile, $db);
|
||||
$this->checkRemoteCredentials($profile);
|
||||
|
||||
return $this->result();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that required PHP extensions are loaded.
|
||||
*/
|
||||
private function checkPhpExtensions(object $profile): void
|
||||
{
|
||||
$required = ['pdo', 'pdo_mysql', 'mbstring'];
|
||||
|
||||
// ZIP is required unless using tar.gz
|
||||
$format = $profile->archive_format ?? 'zip';
|
||||
|
||||
if ($format === 'zip') {
|
||||
$required[] = 'zip';
|
||||
}
|
||||
|
||||
foreach ($required as $ext) {
|
||||
if (!extension_loaded($ext)) {
|
||||
$this->errors[] = 'Missing required PHP extension: ext-' . $ext;
|
||||
}
|
||||
}
|
||||
|
||||
// curl is only needed for remote upload and ntfy notifications
|
||||
$needsCurl = ($profile->remote_storage ?? 'none') !== 'none'
|
||||
|| !empty($profile->ntfy_topic);
|
||||
|
||||
if ($needsCurl && !extension_loaded('curl')) {
|
||||
$this->warnings[] = 'ext-curl is not loaded — remote upload and ntfy notifications will not work';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the backup directory exists and is writable.
|
||||
*/
|
||||
private function checkBackupDirectory(object $profile): void
|
||||
{
|
||||
$configuredDir = $profile->backup_dir ?: BackupDirectory::PLACEHOLDER;
|
||||
|
||||
// Resolve placeholders using a temporary resolver
|
||||
$resolver = new PlaceholderResolver($profile);
|
||||
$resolvedDir = BackupDirectory::resolve($resolver->resolve($configuredDir));
|
||||
|
||||
if (BackupDirectory::hasPlaceholders($resolvedDir)) {
|
||||
$this->warnings[] = 'Backup directory contains unresolved placeholders: ' . $resolvedDir
|
||||
. ' — directory cannot be validated until backup runs';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_dir($resolvedDir)) {
|
||||
// Try to create it
|
||||
if (!@mkdir($resolvedDir, 0755, true)) {
|
||||
$lastError = error_get_last();
|
||||
$reason = $lastError['message'] ?? 'unknown reason';
|
||||
$this->errors[] = 'Backup directory does not exist and cannot be created: ' . $resolvedDir
|
||||
. ' (' . $reason . ')';
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_writable($resolvedDir)) {
|
||||
$this->errors[] = 'Backup directory is not writable: ' . $resolvedDir;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check available disk space against the last backup size + 20% buffer.
|
||||
* Skipped if no previous backup exists for this profile.
|
||||
*/
|
||||
private function checkDiskSpace(object $profile, object $db): void
|
||||
{
|
||||
$configuredDir = $profile->backup_dir ?: BackupDirectory::PLACEHOLDER;
|
||||
$resolver = new PlaceholderResolver($profile);
|
||||
$resolvedDir = BackupDirectory::resolve($resolver->resolve($configuredDir));
|
||||
|
||||
if (BackupDirectory::hasPlaceholders($resolvedDir) || !is_dir($resolvedDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find last successful backup size for this profile
|
||||
$query = $db->getQuery(true)
|
||||
->select($db->quoteName('total_size'))
|
||||
->from($db->quoteName('#__mokosuitebackup_records'))
|
||||
->where($db->quoteName('profile_id') . ' = ' . (int) $profile->id)
|
||||
->where($db->quoteName('status') . ' = ' . $db->quote('complete'))
|
||||
->where($db->quoteName('total_size') . ' > 0')
|
||||
->order($db->quoteName('backupstart') . ' DESC');
|
||||
$db->setQuery($query, 0, 1);
|
||||
$lastSize = (int) $db->loadResult();
|
||||
|
||||
if ($lastSize === 0) {
|
||||
// No previous backup — skip disk space check
|
||||
return;
|
||||
}
|
||||
|
||||
$requiredBytes = (int) ($lastSize * 1.2); // 20% buffer
|
||||
$freeBytes = @disk_free_space($resolvedDir);
|
||||
|
||||
if ($freeBytes === false) {
|
||||
$this->warnings[] = 'Could not determine free disk space for: ' . $resolvedDir;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($freeBytes < $requiredBytes) {
|
||||
$freeMB = number_format($freeBytes / 1048576, 1);
|
||||
$neededMB = number_format($requiredBytes / 1048576, 1);
|
||||
|
||||
$this->warnings[] = 'Low disk space: ' . $freeMB . ' MB free, estimated ' . $neededMB . ' MB needed'
|
||||
. ' (based on last backup + 20% buffer)';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if another backup is already running for this profile.
|
||||
*/
|
||||
private function checkRunningBackup(object $profile, object $db): void
|
||||
{
|
||||
$query = $db->getQuery(true)
|
||||
->select('COUNT(*)')
|
||||
->from($db->quoteName('#__mokosuitebackup_records'))
|
||||
->where($db->quoteName('profile_id') . ' = ' . (int) $profile->id)
|
||||
->where($db->quoteName('status') . ' = ' . $db->quote('running'));
|
||||
$db->setQuery($query);
|
||||
$running = (int) $db->loadResult();
|
||||
|
||||
if ($running > 0) {
|
||||
$this->errors[] = 'Another backup is already running for profile: ' . $profile->title
|
||||
. ' — wait for it to finish or delete the stale record';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that excluded tables actually exist in the database.
|
||||
* Missing tables are warnings, not errors — the profile may have
|
||||
* been copied from another site or a table may have been removed.
|
||||
*/
|
||||
private function checkExcludedTables(object $profile, object $db): void
|
||||
{
|
||||
$excludeRaw = BackupDirectory::parseNewlineList($profile->exclude_tables ?? '');
|
||||
|
||||
if (empty($excludeRaw)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$prefix = $db->getPrefix();
|
||||
$allTables = array_flip($db->getTableList());
|
||||
|
||||
foreach ($excludeRaw as $entry) {
|
||||
// Strip :data-only / :structure-only suffixes
|
||||
$tableName = preg_replace('/:(?:data-only|structure-only)$/', '', $entry);
|
||||
|
||||
// Resolve #__ prefix to real prefix
|
||||
$realName = str_replace('#__', $prefix, $tableName);
|
||||
|
||||
if (!isset($allTables[$realName])) {
|
||||
$this->warnings[] = 'Excluded table does not exist: ' . $tableName
|
||||
. ' — it will be silently skipped during backup';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that remote storage credentials are minimally configured.
|
||||
* Does not test the actual connection (too slow for preflight).
|
||||
*/
|
||||
private function checkRemoteCredentials(object $profile): void
|
||||
{
|
||||
$remote = $profile->remote_storage ?? 'none';
|
||||
|
||||
if ($remote === 'none') {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($remote) {
|
||||
case 'ftp':
|
||||
if (empty($profile->ftp_host)) {
|
||||
$this->warnings[] = 'FTP host is not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
if (empty($profile->ftp_username)) {
|
||||
$this->warnings[] = 'FTP username is not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 's3':
|
||||
if (empty($profile->s3_bucket)) {
|
||||
$this->warnings[] = 'S3 bucket is not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
if (empty($profile->s3_access_key) || empty($profile->s3_secret_key)) {
|
||||
$this->warnings[] = 'S3 credentials are not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'sftp':
|
||||
if (empty($profile->sftp_host)) {
|
||||
$this->warnings[] = 'SFTP host is not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
if (empty($profile->sftp_username)) {
|
||||
$this->warnings[] = 'SFTP username is not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
if (empty($profile->sftp_key_data) && empty($profile->sftp_password)) {
|
||||
$this->warnings[] = 'SFTP requires either a private key or password — remote upload will fail';
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'google_drive':
|
||||
if (empty($profile->gdrive_client_id) || empty($profile->gdrive_client_secret)) {
|
||||
$this->warnings[] = 'Google Drive OAuth credentials are not configured — remote upload will fail';
|
||||
}
|
||||
|
||||
if (empty($profile->gdrive_refresh_token)) {
|
||||
$this->warnings[] = 'Google Drive refresh token is missing — remote upload will fail';
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the result array.
|
||||
*/
|
||||
private function result(): array
|
||||
{
|
||||
return [
|
||||
'pass' => empty($this->errors),
|
||||
'errors' => $this->errors,
|
||||
'warnings' => $this->warnings,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
use Joomla\Event\Event;
|
||||
|
||||
class RestoreEngine
|
||||
{
|
||||
@@ -76,8 +77,9 @@ class RestoreEngine
|
||||
return ['success' => false, 'message' => 'Backup archive not found: ' . $archivePath];
|
||||
}
|
||||
|
||||
// Create staging directory
|
||||
$this->stagingDir = JPATH_ROOT . '/tmp/mokosuitebackup-restore-' . $record->tag;
|
||||
// Create staging directory (sanitize tag to prevent path traversal)
|
||||
$safeTag = preg_replace('/[^a-zA-Z0-9_-]/', '', $record->tag ?: 'restore');
|
||||
$this->stagingDir = JPATH_ROOT . '/tmp/mokosuitebackup-restore-' . $safeTag;
|
||||
|
||||
if (is_dir($this->stagingDir)) {
|
||||
$this->recursiveDelete($this->stagingDir);
|
||||
@@ -145,6 +147,29 @@ class RestoreEngine
|
||||
|
||||
$this->log('Restore complete');
|
||||
|
||||
// Send restore notification
|
||||
try {
|
||||
$profile = NotificationSender::getDefaultProfile();
|
||||
|
||||
if ($profile) {
|
||||
$userId = Factory::getApplication()->getIdentity()->id ?? 0;
|
||||
$userName = Factory::getApplication()->getIdentity()->username ?? 'Unknown';
|
||||
|
||||
NotificationSender::sendRestoreNotification($profile, 'site_restore', [
|
||||
'record_id' => $recordId,
|
||||
'restore_files' => $restoreFiles,
|
||||
'restore_db' => $restoreDb,
|
||||
'preserve_config' => $preserveConfig,
|
||||
'user' => $userName . ' (ID: ' . $userId . ')',
|
||||
], implode("\n", $this->log));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: Restore notification failed: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterRestore(true, $recordId);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => 'Restore complete from: ' . basename($archivePath),
|
||||
@@ -164,6 +189,9 @@ class RestoreEngine
|
||||
$this->recursiveDelete($this->stagingDir);
|
||||
}
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterRestore(false, $recordId);
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Restore failed: ' . $e->getMessage(),
|
||||
@@ -190,6 +218,20 @@ class RestoreEngine
|
||||
$this->log('Decryption password set');
|
||||
}
|
||||
|
||||
// Validate all entries before extraction (path traversal protection)
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$entryName = $zip->getNameIndex($i);
|
||||
|
||||
if ($entryName === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_contains($entryName, '../') || str_contains($entryName, '..\\') || str_starts_with($entryName, '/') || str_starts_with($entryName, '\\')) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive contains unsafe path: ' . $entryName);
|
||||
}
|
||||
}
|
||||
|
||||
if (!$zip->extractTo($this->stagingDir)) {
|
||||
$zip->close();
|
||||
|
||||
@@ -209,6 +251,18 @@ class RestoreEngine
|
||||
private function extractTarGz(string $archivePath): void
|
||||
{
|
||||
$phar = new \PharData($archivePath);
|
||||
|
||||
// Validate all entries before extraction (path traversal protection)
|
||||
foreach (new \RecursiveIteratorIterator($phar) as $entry) {
|
||||
$entryName = $entry->getPathname();
|
||||
// PharData paths are prefixed with phar:// — extract the relative part
|
||||
$relative = substr($entryName, strlen('phar://' . $archivePath) + 1);
|
||||
|
||||
if (str_contains($relative, '../') || str_contains($relative, '..\\') || str_starts_with($relative, '/') || str_starts_with($relative, '\\')) {
|
||||
throw new \RuntimeException('Archive contains unsafe path: ' . $relative);
|
||||
}
|
||||
}
|
||||
|
||||
$phar->extractTo($this->stagingDir, null, true);
|
||||
$this->log('Extracted tar.gz archive');
|
||||
}
|
||||
@@ -238,6 +292,26 @@ class RestoreEngine
|
||||
@rmdir($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch the onMokoSuiteBackupAfterRestore event so plugins (actionlog, etc.) can react.
|
||||
*/
|
||||
private function dispatchAfterRestore(bool $success, int $recordId): void
|
||||
{
|
||||
try {
|
||||
$app = Factory::getApplication();
|
||||
|
||||
$event = new Event('onMokoSuiteBackupAfterRestore', [
|
||||
'success' => $success,
|
||||
'record_id' => $recordId,
|
||||
]);
|
||||
|
||||
$app->getDispatcher()->dispatch('onMokoSuiteBackupAfterRestore', $event);
|
||||
} catch (\Throwable $e) {
|
||||
// Never let a listener failure break the restore result, but log it
|
||||
error_log('MokoSuiteBackup: onAfterRestore listener error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function log(string $message): void
|
||||
{
|
||||
$this->log[] = '[' . date('H:i:s') . '] ' . $message;
|
||||
|
||||
@@ -114,19 +114,28 @@ class S3Uploader implements RemoteUploaderInterface
|
||||
*/
|
||||
private function singleUpload(string $localPath, string $objectKey): void
|
||||
{
|
||||
$url = $this->getObjectUrl($objectKey);
|
||||
$fileContent = file_get_contents($localPath);
|
||||
$contentHash = hash('sha256', $fileContent);
|
||||
$url = $this->getObjectUrl($objectKey);
|
||||
$fileSize = filesize($localPath);
|
||||
|
||||
// Stream file to compute SHA-256 without loading into RAM
|
||||
$contentHash = hash_file('sha256', $localPath);
|
||||
$headers = $this->signRequest('PUT', $url, $contentHash, [
|
||||
'Content-Type' => 'application/zip',
|
||||
'Content-Length' => (string) strlen($fileContent),
|
||||
'Content-Length' => (string) $fileSize,
|
||||
]);
|
||||
|
||||
$fp = fopen($localPath, 'rb');
|
||||
|
||||
if ($fp === false) {
|
||||
throw new \RuntimeException('Cannot open file for upload: ' . $localPath);
|
||||
}
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_URL => $url,
|
||||
CURLOPT_CUSTOMREQUEST => 'PUT',
|
||||
CURLOPT_POSTFIELDS => $fileContent,
|
||||
CURLOPT_PUT => true,
|
||||
CURLOPT_INFILE => $fp,
|
||||
CURLOPT_INFILESIZE => $fileSize,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_TIMEOUT => 600,
|
||||
@@ -135,6 +144,8 @@ class S3Uploader implements RemoteUploaderInterface
|
||||
$response = curl_exec($ch);
|
||||
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
|
||||
fclose($fp);
|
||||
|
||||
if (curl_errno($ch)) {
|
||||
$error = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
<?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\Engine;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
/**
|
||||
* 7z archiver using the 7za/7z CLI binary.
|
||||
*
|
||||
* Requires p7zip-full (Linux) or 7-Zip (Windows) to be installed on the server.
|
||||
* Supports native AES-256 encryption via the -p flag.
|
||||
*/
|
||||
class SevenZipArchiver implements ArchiverInterface
|
||||
{
|
||||
/** @var string Absolute path to the target archive */
|
||||
private string $archivePath = '';
|
||||
|
||||
/** @var string[] Absolute paths of files to add */
|
||||
private array $filePaths = [];
|
||||
|
||||
/** @var string[] Corresponding local names inside the archive */
|
||||
private array $localNames = [];
|
||||
|
||||
/** @var string[] Temp files created by addFromString() that must be cleaned up */
|
||||
private array $tempFiles = [];
|
||||
|
||||
/** @var string Optional encryption password */
|
||||
private string $encryptionPassword = '';
|
||||
|
||||
/**
|
||||
* Set the encryption password for the archive.
|
||||
*
|
||||
* @param string $password Password for AES-256 encryption
|
||||
*/
|
||||
public function setEncryptionPassword(string $password): void
|
||||
{
|
||||
$this->encryptionPassword = $password;
|
||||
}
|
||||
|
||||
public function open(string $path): void
|
||||
{
|
||||
$this->archivePath = $path;
|
||||
$this->filePaths = [];
|
||||
$this->localNames = [];
|
||||
$this->tempFiles = [];
|
||||
|
||||
// Remove existing archive to avoid appending to stale data
|
||||
if (is_file($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function addFromString(string $localName, string $contents): void
|
||||
{
|
||||
// Write to a temp file so 7z can read it from disk
|
||||
$tempDir = \dirname($this->archivePath);
|
||||
$tempFile = $tempDir . '/.7z-tmp-' . md5($localName . microtime(true)) . '-' . basename($localName);
|
||||
|
||||
if (file_put_contents($tempFile, $contents) === false) {
|
||||
throw new \RuntimeException('SevenZipArchiver: cannot write temp file: ' . $tempFile);
|
||||
}
|
||||
|
||||
$this->tempFiles[] = $tempFile;
|
||||
$this->filePaths[] = $tempFile;
|
||||
$this->localNames[] = $localName;
|
||||
}
|
||||
|
||||
public function addFile(string $filePath, string $localName): void
|
||||
{
|
||||
$this->filePaths[] = $filePath;
|
||||
$this->localNames[] = $localName;
|
||||
}
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
try {
|
||||
$this->buildArchive();
|
||||
} finally {
|
||||
// Always clean up temp files
|
||||
foreach ($this->tempFiles as $tempFile) {
|
||||
if (is_file($tempFile)) {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
$this->tempFiles = [];
|
||||
}
|
||||
}
|
||||
|
||||
public function getExtension(): string
|
||||
{
|
||||
return '7z';
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the 7z archive using the CLI binary.
|
||||
*
|
||||
* Writes a list file mapping local names to absolute paths, then invokes
|
||||
* 7za/7z to create the archive. Uses stdin rename pairs for correct
|
||||
* internal paths.
|
||||
*/
|
||||
private function buildArchive(): void
|
||||
{
|
||||
$binary = $this->findBinary();
|
||||
|
||||
if ($binary === null) {
|
||||
throw new \RuntimeException(
|
||||
'SevenZipArchiver: 7z/7za binary not found. '
|
||||
. 'Install p7zip-full (Linux) or 7-Zip (Windows).'
|
||||
);
|
||||
}
|
||||
|
||||
if (empty($this->filePaths)) {
|
||||
throw new \RuntimeException('SevenZipArchiver: no files to archive');
|
||||
}
|
||||
|
||||
// Strategy: create a temporary staging directory with the correct
|
||||
// directory structure, symlink or copy files, then archive the
|
||||
// staging directory. This gives us correct internal paths.
|
||||
$stagingDir = \dirname($this->archivePath) . '/.7z-staging-' . md5($this->archivePath . microtime(true));
|
||||
|
||||
if (!mkdir($stagingDir, 0755, true)) {
|
||||
throw new \RuntimeException('SevenZipArchiver: cannot create staging directory: ' . $stagingDir);
|
||||
}
|
||||
|
||||
try {
|
||||
// Create the directory structure and link/copy files
|
||||
foreach ($this->filePaths as $i => $sourcePath) {
|
||||
$localName = $this->localNames[$i];
|
||||
$targetPath = $stagingDir . '/' . $localName;
|
||||
$targetDir = \dirname($targetPath);
|
||||
|
||||
if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true)) {
|
||||
throw new \RuntimeException('SevenZipArchiver: cannot create directory: ' . $targetDir);
|
||||
}
|
||||
|
||||
// Use symlink where possible (faster, no disk usage), fall back to copy
|
||||
if (@symlink($sourcePath, $targetPath) === false) {
|
||||
if (!copy($sourcePath, $targetPath)) {
|
||||
throw new \RuntimeException('SevenZipArchiver: cannot copy file: ' . $sourcePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build command
|
||||
$cmd = escapeshellarg($binary)
|
||||
. ' a'
|
||||
. ' -t7z'
|
||||
. ' -mx=5'
|
||||
. ' -mhe=on'
|
||||
. ' ' . escapeshellarg($this->archivePath)
|
||||
. ' ' . escapeshellarg($stagingDir . '/*');
|
||||
|
||||
// Add encryption if password is set
|
||||
if ($this->encryptionPassword !== '') {
|
||||
$cmd .= ' -p' . escapeshellarg($this->encryptionPassword);
|
||||
}
|
||||
|
||||
// Suppress interactive prompts
|
||||
$cmd .= ' -y';
|
||||
|
||||
// Redirect stderr to stdout for capture
|
||||
$cmd .= ' 2>&1';
|
||||
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec($cmd, $output, $exitCode);
|
||||
|
||||
if ($exitCode !== 0) {
|
||||
$outputStr = implode("\n", $output);
|
||||
throw new \RuntimeException(
|
||||
'SevenZipArchiver: 7z exited with code ' . $exitCode . ': ' . $outputStr
|
||||
);
|
||||
}
|
||||
|
||||
if (!is_file($this->archivePath)) {
|
||||
throw new \RuntimeException('SevenZipArchiver: archive was not created: ' . $this->archivePath);
|
||||
}
|
||||
|
||||
// The archive contains paths relative to the staging dir.
|
||||
// We need to verify that the internal structure doesn't include
|
||||
// the staging dir name as a prefix. If 7z was given staging/*,
|
||||
// the paths inside should be correct (relative to staging).
|
||||
} finally {
|
||||
// Remove staging directory
|
||||
$this->removeDirectory($stagingDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the 7z or 7za binary.
|
||||
*
|
||||
* @return string|null Absolute path to binary, or null if not found
|
||||
*/
|
||||
private function findBinary(): ?string
|
||||
{
|
||||
// Check common binary names
|
||||
$candidates = PHP_OS_FAMILY === 'Windows'
|
||||
? ['7z', '7za', 'C:\\Program Files\\7-Zip\\7z.exe', 'C:\\Program Files (x86)\\7-Zip\\7z.exe']
|
||||
: ['7za', '7z', '/usr/bin/7za', '/usr/bin/7z', '/usr/local/bin/7za', '/usr/local/bin/7z'];
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
// If it's an absolute path, check file existence
|
||||
if (str_contains($candidate, DIRECTORY_SEPARATOR) || str_contains($candidate, '/')) {
|
||||
if (is_file($candidate) && is_executable($candidate)) {
|
||||
return $candidate;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Use 'which' / 'where' to find in PATH
|
||||
$whichCmd = PHP_OS_FAMILY === 'Windows'
|
||||
? 'where ' . escapeshellarg($candidate) . ' 2>NUL'
|
||||
: 'which ' . escapeshellarg($candidate) . ' 2>/dev/null';
|
||||
|
||||
$result = trim((string) shell_exec($whichCmd));
|
||||
|
||||
if ($result !== '' && is_executable($result)) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively remove a directory and its contents.
|
||||
*/
|
||||
private function removeDirectory(string $dir): void
|
||||
{
|
||||
if (!is_dir($dir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
|
||||
foreach ($items as $item) {
|
||||
if ($item->isDir()) {
|
||||
@rmdir($item->getPathname());
|
||||
} else {
|
||||
// Remove symlinks and files
|
||||
@unlink($item->getPathname());
|
||||
}
|
||||
}
|
||||
|
||||
@rmdir($dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
<?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
|
||||
*
|
||||
* SFTP uploader using the system sftp/scp binary with SSH key authentication.
|
||||
*
|
||||
* The private key is stored in the database (profile column) and written
|
||||
* to a temp file with 0600 permissions at upload time, then deleted.
|
||||
* This avoids leaving key files on the filesystem permanently.
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
class SftpUploader implements RemoteUploaderInterface
|
||||
{
|
||||
private string $host;
|
||||
private int $port;
|
||||
private string $username;
|
||||
private string $keyData;
|
||||
private string $passphrase;
|
||||
private string $password;
|
||||
private string $remotePath;
|
||||
|
||||
public function __construct(object $profile)
|
||||
{
|
||||
$this->host = $profile->sftp_host ?? '';
|
||||
$this->port = (int) ($profile->sftp_port ?? 22);
|
||||
$this->username = $profile->sftp_username ?? '';
|
||||
$this->keyData = $profile->sftp_key_data ?? '';
|
||||
$this->passphrase = $profile->sftp_passphrase ?? '';
|
||||
$this->password = $profile->sftp_password ?? '';
|
||||
$this->remotePath = rtrim($profile->sftp_path ?? '/backups', '/');
|
||||
}
|
||||
|
||||
public function upload(string $localPath, string $remoteName): array
|
||||
{
|
||||
if (empty($this->host)) {
|
||||
return ['success' => false, 'message' => 'SFTP host is not configured'];
|
||||
}
|
||||
|
||||
if (empty($this->username)) {
|
||||
return ['success' => false, 'message' => 'SFTP username is not configured'];
|
||||
}
|
||||
|
||||
if (empty($this->keyData) && empty($this->password)) {
|
||||
return ['success' => false, 'message' => 'SFTP requires either a private key or password'];
|
||||
}
|
||||
|
||||
$keyFile = null;
|
||||
|
||||
try {
|
||||
/* Write key to temp file if using key auth */
|
||||
if (!empty($this->keyData)) {
|
||||
$keyFile = $this->writeTempKey();
|
||||
}
|
||||
|
||||
/* Ensure remote directory exists */
|
||||
$this->ensureRemoteDir($keyFile);
|
||||
|
||||
/* Upload via scp */
|
||||
$remoteTarget = $this->username . '@' . $this->host . ':' . $this->remotePath . '/' . $remoteName;
|
||||
$cmd = $this->buildScpCommand($localPath, $remoteTarget, $keyFile);
|
||||
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec($cmd . ' 2>&1', $output, $exitCode);
|
||||
|
||||
if ($exitCode !== 0) {
|
||||
$errorMsg = implode("\n", $output);
|
||||
throw new \RuntimeException('scp failed (exit ' . $exitCode . '): ' . $errorMsg);
|
||||
}
|
||||
|
||||
/* Verify upload by checking remote file size */
|
||||
$remoteFile = $this->remotePath . '/' . $remoteName;
|
||||
$remoteSize = $this->getRemoteFileSize($remoteFile, $keyFile);
|
||||
$localSize = filesize($localPath);
|
||||
|
||||
if ($remoteSize > 0 && $remoteSize !== $localSize) {
|
||||
throw new \RuntimeException(
|
||||
'Size mismatch after upload: local=' . $localSize . ' remote=' . $remoteSize
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => 'Uploaded via SFTP: ' . $remoteFile,
|
||||
'remote_path' => $remoteFile,
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
return ['success' => false, 'message' => 'SFTP upload failed: ' . $e->getMessage()];
|
||||
} finally {
|
||||
$this->cleanupTempKey($keyFile);
|
||||
}
|
||||
}
|
||||
|
||||
public function testConnection(): array
|
||||
{
|
||||
if (empty($this->host)) {
|
||||
return ['success' => false, 'message' => 'SFTP host is not configured'];
|
||||
}
|
||||
|
||||
$keyFile = null;
|
||||
|
||||
try {
|
||||
if (!empty($this->keyData)) {
|
||||
$keyFile = $this->writeTempKey();
|
||||
}
|
||||
|
||||
$cmd = $this->buildSshCommand('echo "MokoSuiteBackup connection test OK" && hostname', $keyFile);
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec($cmd . ' 2>&1', $output, $exitCode);
|
||||
|
||||
if ($exitCode !== 0) {
|
||||
return ['success' => false, 'message' => 'SSH connection failed: ' . implode(' ', $output)];
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => 'Connected to ' . $this->host . ' — ' . implode(' ', $output),
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
return ['success' => false, 'message' => 'Connection test failed: ' . $e->getMessage()];
|
||||
} finally {
|
||||
$this->cleanupTempKey($keyFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the private key from the database to a temp file with 0600 permissions.
|
||||
*/
|
||||
private function writeTempKey(): string
|
||||
{
|
||||
$tmpDir = sys_get_temp_dir();
|
||||
$keyFile = $tmpDir . '/mokobackup-sftp-' . bin2hex(random_bytes(8)) . '.key';
|
||||
|
||||
/* Key is stored base64-encoded in the database — decode before writing */
|
||||
$keyContent = base64_decode($this->keyData, true);
|
||||
|
||||
if ($keyContent === false) {
|
||||
/* Fallback: might be raw PEM (legacy or paste) */
|
||||
$keyContent = $this->keyData;
|
||||
}
|
||||
|
||||
if (file_put_contents($keyFile, $keyContent) === false) {
|
||||
throw new \RuntimeException('Cannot write temporary SSH key file');
|
||||
}
|
||||
|
||||
chmod($keyFile, 0600);
|
||||
|
||||
return $keyFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the temp key file.
|
||||
*/
|
||||
private function cleanupTempKey(?string $keyFile): void
|
||||
{
|
||||
if ($keyFile !== null && is_file($keyFile)) {
|
||||
unlink($keyFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the remote directory exists via ssh mkdir -p.
|
||||
*/
|
||||
private function ensureRemoteDir(?string $keyFile): void
|
||||
{
|
||||
$escapedPath = escapeshellarg($this->remotePath);
|
||||
$cmd = $this->buildSshCommand('mkdir -p ' . $escapedPath, $keyFile);
|
||||
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec($cmd . ' 2>&1', $output, $exitCode);
|
||||
|
||||
/* mkdir -p exits 0 even if dir already exists, so only fail on non-zero */
|
||||
if ($exitCode !== 0) {
|
||||
throw new \RuntimeException('Cannot create remote directory: ' . implode(' ', $output));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get remote file size via ssh stat.
|
||||
*/
|
||||
private function getRemoteFileSize(string $remotePath, ?string $keyFile): int
|
||||
{
|
||||
$escapedPath = escapeshellarg($remotePath);
|
||||
$cmd = $this->buildSshCommand('stat -c %s ' . $escapedPath . ' 2>/dev/null || echo -1', $keyFile);
|
||||
|
||||
$output = [];
|
||||
exec($cmd . ' 2>&1', $output);
|
||||
|
||||
$size = (int) trim(implode('', $output));
|
||||
|
||||
return $size > 0 ? $size : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an scp command string with proper SSH options.
|
||||
*/
|
||||
private function buildScpCommand(string $localPath, string $remoteTarget, ?string $keyFile): string
|
||||
{
|
||||
$parts = ['scp', '-o', 'StrictHostKeyChecking=no', '-o', 'BatchMode=yes'];
|
||||
|
||||
if ($this->port !== 22) {
|
||||
$parts[] = '-P';
|
||||
$parts[] = (string) $this->port;
|
||||
}
|
||||
|
||||
if ($keyFile !== null) {
|
||||
$parts[] = '-i';
|
||||
$parts[] = escapeshellarg($keyFile);
|
||||
}
|
||||
|
||||
if (!empty($this->passphrase)) {
|
||||
/* scp doesn't natively support passphrase via CLI — requires ssh-agent or expect.
|
||||
For now, key files should be unencrypted or use ssh-agent. */
|
||||
}
|
||||
|
||||
$parts[] = escapeshellarg($localPath);
|
||||
$parts[] = escapeshellarg($remoteTarget);
|
||||
|
||||
return implode(' ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an ssh command string for remote commands.
|
||||
*/
|
||||
private function buildSshCommand(string $remoteCmd, ?string $keyFile): string
|
||||
{
|
||||
$parts = ['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'BatchMode=yes'];
|
||||
|
||||
if ($this->port !== 22) {
|
||||
$parts[] = '-p';
|
||||
$parts[] = (string) $this->port;
|
||||
}
|
||||
|
||||
if ($keyFile !== null) {
|
||||
$parts[] = '-i';
|
||||
$parts[] = escapeshellarg($keyFile);
|
||||
}
|
||||
|
||||
$parts[] = escapeshellarg($this->username . '@' . $this->host);
|
||||
$parts[] = escapeshellarg($remoteCmd);
|
||||
|
||||
return implode(' ', $parts);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
use Joomla\Component\MokoSuiteBackup\Administrator\Utility\BackupDirectory;
|
||||
use Joomla\Event\Event;
|
||||
|
||||
class SnapshotEngine
|
||||
{
|
||||
@@ -41,6 +42,10 @@ class SnapshotEngine
|
||||
private const ARTICLE_RELATED = [
|
||||
'#__workflow_associations',
|
||||
'#__contentitem_tag_map',
|
||||
'#__tags',
|
||||
'#__fields',
|
||||
'#__fields_values',
|
||||
'#__fields_categories',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -107,6 +112,32 @@ class SnapshotEngine
|
||||
$rows = $this->dumpTagMap($db, $prefix);
|
||||
$data['tables']['#__contentitem_tag_map'] = $rows;
|
||||
$this->log(' #__contentitem_tag_map: ' . count($rows) . ' rows');
|
||||
|
||||
// Tags — dump all (shared, small table)
|
||||
$rows = $this->dumpTable($db, str_replace('#__', $prefix, '#__tags'), '#__tags', 'articles');
|
||||
$data['tables']['#__tags'] = $rows;
|
||||
$this->log(' #__tags: ' . count($rows) . ' rows');
|
||||
|
||||
// Custom fields — only com_content.article context
|
||||
$rows = $this->dumpFilteredTable(
|
||||
$db,
|
||||
str_replace('#__', $prefix, '#__fields'),
|
||||
'#__fields',
|
||||
'context',
|
||||
'com_content.article'
|
||||
);
|
||||
$data['tables']['#__fields'] = $rows;
|
||||
$this->log(' #__fields: ' . count($rows) . ' rows');
|
||||
|
||||
// Field values — only for com_content.article fields (table is shared across extensions)
|
||||
$rows = $this->dumpFieldValues($db, $prefix);
|
||||
$data['tables']['#__fields_values'] = $rows;
|
||||
$this->log(' #__fields_values: ' . count($rows) . ' rows');
|
||||
|
||||
// Field-category mappings — only for com_content.article fields
|
||||
$rows = $this->dumpFieldCategories($db, $prefix);
|
||||
$data['tables']['#__fields_categories'] = $rows;
|
||||
$this->log(' #__fields_categories: ' . count($rows) . ' rows');
|
||||
}
|
||||
|
||||
// Count items
|
||||
@@ -164,6 +195,29 @@ class SnapshotEngine
|
||||
|
||||
$this->log('Snapshot record created: ID ' . $record->id);
|
||||
|
||||
// Send snapshot creation notification
|
||||
try {
|
||||
$profile = NotificationSender::getDefaultProfile();
|
||||
|
||||
if ($profile) {
|
||||
$userName = Factory::getApplication()->getIdentity()->username ?? 'Unknown';
|
||||
$userIdVal = Factory::getApplication()->getIdentity()->id ?? 0;
|
||||
|
||||
NotificationSender::sendRestoreNotification($profile, 'snapshot_create', [
|
||||
'content_types' => array_values($validTypes),
|
||||
'articles_count' => $counts['articles'],
|
||||
'categories_count' => $counts['categories'],
|
||||
'modules_count' => $counts['modules'],
|
||||
'user' => $userName . ' (ID: ' . $userIdVal . ')',
|
||||
], implode("\n", $this->log));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: Snapshot creation notification failed: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterSnapshot(true, $record->id, array_values($validTypes));
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => sprintf(
|
||||
@@ -177,6 +231,9 @@ class SnapshotEngine
|
||||
} catch (\Exception $e) {
|
||||
$this->log('FATAL: ' . $e->getMessage());
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterSnapshot(false, 0, $contentTypes);
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Snapshot failed: ' . $e->getMessage(),
|
||||
@@ -231,6 +288,73 @@ class SnapshotEngine
|
||||
return $db->loadAssocList() ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dump field-category mappings for com_content.article fields.
|
||||
*
|
||||
* Uses a subquery: field_id IN (SELECT id FROM #__fields WHERE context = 'com_content.article')
|
||||
*/
|
||||
/**
|
||||
* Dump field values only for com_content.article fields.
|
||||
*/
|
||||
private function dumpFieldValues(object $db, string $prefix): array
|
||||
{
|
||||
$fvTable = $prefix . 'fields_values';
|
||||
$fTable = $prefix . 'fields';
|
||||
|
||||
$subQuery = $db->getQuery(true)
|
||||
->select($db->quoteName('id'))
|
||||
->from($db->quoteName($fTable))
|
||||
->where($db->quoteName('context') . ' = ' . $db->quote('com_content.article'));
|
||||
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName($fvTable))
|
||||
->where($db->quoteName('field_id') . ' IN (' . $subQuery . ')');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadAssocList() ?: [];
|
||||
}
|
||||
|
||||
private function dumpFieldCategories(object $db, string $prefix): array
|
||||
{
|
||||
$fcTable = $prefix . 'fields_categories';
|
||||
$fTable = $prefix . 'fields';
|
||||
|
||||
$subQuery = $db->getQuery(true)
|
||||
->select($db->quoteName('id'))
|
||||
->from($db->quoteName($fTable))
|
||||
->where($db->quoteName('context') . ' = ' . $db->quote('com_content.article'));
|
||||
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName($fcTable))
|
||||
->where($db->quoteName('field_id') . ' IN (' . $subQuery . ')');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadAssocList() ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch the onMokoSuiteBackupAfterSnapshot event so plugins (actionlog, etc.) can react.
|
||||
*/
|
||||
private function dispatchAfterSnapshot(bool $success, int $snapshotId, array $contentTypes): void
|
||||
{
|
||||
try {
|
||||
$app = Factory::getApplication();
|
||||
|
||||
$event = new Event('onMokoSuiteBackupAfterSnapshot', [
|
||||
'success' => $success,
|
||||
'snapshot_id' => $snapshotId,
|
||||
'content_types' => $contentTypes,
|
||||
]);
|
||||
|
||||
$app->getDispatcher()->dispatch('onMokoSuiteBackupAfterSnapshot', $event);
|
||||
} catch (\Throwable $e) {
|
||||
// Never let a listener failure break the snapshot result, but log it
|
||||
error_log('MokoSuiteBackup: onAfterSnapshot listener error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function log(string $message): void
|
||||
{
|
||||
$this->log[] = '[' . date('H:i:s') . '] ' . $message;
|
||||
|
||||
@@ -19,6 +19,7 @@ namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
use Joomla\Event\Event;
|
||||
|
||||
class SnapshotRestoreEngine
|
||||
{
|
||||
@@ -33,6 +34,10 @@ class SnapshotRestoreEngine
|
||||
'#__contentitem_tag_map' => null, // composite key, handled specially
|
||||
'#__modules' => 'id',
|
||||
'#__modules_menu' => null, // composite key, handled specially
|
||||
'#__tags' => 'id',
|
||||
'#__fields' => 'id',
|
||||
'#__fields_values' => null, // composite key, handled specially
|
||||
'#__fields_categories' => null, // composite key, handled specially
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -147,6 +152,28 @@ class SnapshotRestoreEngine
|
||||
|
||||
$this->log('Restore complete: ' . $totalRows . ' total rows');
|
||||
|
||||
// Send snapshot restore notification
|
||||
try {
|
||||
$profile = NotificationSender::getDefaultProfile();
|
||||
|
||||
if ($profile) {
|
||||
$userName = Factory::getApplication()->getIdentity()->username ?? 'Unknown';
|
||||
$userIdVal = Factory::getApplication()->getIdentity()->id ?? 0;
|
||||
|
||||
NotificationSender::sendRestoreNotification($profile, 'snapshot_restore', [
|
||||
'mode' => $mode,
|
||||
'content_types' => $restoreTypes,
|
||||
'row_count' => $totalRows,
|
||||
'user' => $userName . ' (ID: ' . $userIdVal . ')',
|
||||
], implode("\n", $this->log));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: Snapshot restore notification failed: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterSnapshotRestore(true, $snapshotId, $mode);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => sprintf('Snapshot restored (%s mode): %d rows across %d tables', $mode, $totalRows, count($tablesToRestore)),
|
||||
@@ -162,6 +189,9 @@ class SnapshotRestoreEngine
|
||||
|
||||
$this->log('FATAL: ' . $e->getMessage());
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterSnapshotRestore(false, $snapshotId, $mode);
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Restore failed: ' . $e->getMessage(),
|
||||
@@ -282,6 +312,48 @@ class SnapshotRestoreEngine
|
||||
$query->where($db->quoteName('moduleid') . ' IN (' . implode(',', $moduleIds) . ')');
|
||||
break;
|
||||
|
||||
case '#__tags':
|
||||
// Only delete tags that exist in the snapshot — never wipe all tags
|
||||
$ids = array_filter(array_column($rows, 'id'));
|
||||
|
||||
if (empty($ids)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$ids = array_map('intval', $ids);
|
||||
$query->where($db->quoteName('id') . ' IN (' . implode(',', $ids) . ')');
|
||||
break;
|
||||
|
||||
case '#__fields':
|
||||
// Only delete custom fields scoped to com_content.article
|
||||
$query->where($db->quoteName('context') . ' = ' . $db->quote('com_content.article'));
|
||||
break;
|
||||
|
||||
case '#__fields_values':
|
||||
// Only delete field values for com_content.article fields
|
||||
$prefix = $db->getPrefix();
|
||||
$fTable = $prefix . 'fields';
|
||||
|
||||
$subQuery = $db->getQuery(true)
|
||||
->select($db->quoteName('id'))
|
||||
->from($db->quoteName($fTable))
|
||||
->where($db->quoteName('context') . ' = ' . $db->quote('com_content.article'));
|
||||
$query->where($db->quoteName('field_id') . ' IN (' . $subQuery . ')');
|
||||
break;
|
||||
|
||||
case '#__fields_categories':
|
||||
// Delete field-category mappings for com_content.article fields only
|
||||
$prefix = $db->getPrefix();
|
||||
$fTable = $prefix . 'fields';
|
||||
|
||||
$subQuery = $db->getQuery(true)
|
||||
->select($db->quoteName('id'))
|
||||
->from($db->quoteName($fTable))
|
||||
->where($db->quoteName('context') . ' = ' . $db->quote('com_content.article'));
|
||||
|
||||
$query->where($db->quoteName('field_id') . ' IN (' . $subQuery . ')');
|
||||
break;
|
||||
|
||||
// #__content and #__content_frontpage are fully owned by com_content
|
||||
default:
|
||||
break;
|
||||
@@ -303,6 +375,10 @@ class SnapshotRestoreEngine
|
||||
$tables[] = '#__content_frontpage';
|
||||
$tables[] = '#__workflow_associations';
|
||||
$tables[] = '#__contentitem_tag_map';
|
||||
$tables[] = '#__tags';
|
||||
$tables[] = '#__fields';
|
||||
$tables[] = '#__fields_values';
|
||||
$tables[] = '#__fields_categories';
|
||||
}
|
||||
|
||||
if (in_array('categories', $types)) {
|
||||
@@ -317,6 +393,208 @@ class SnapshotRestoreEngine
|
||||
return array_unique($tables);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore only selected articles (and their related rows) from a snapshot.
|
||||
*
|
||||
* Uses merge/upsert mode: updates existing rows by ID, inserts missing ones.
|
||||
*
|
||||
* @param int $snapshotId Snapshot record ID
|
||||
* @param array $articleIds Article IDs to restore
|
||||
*
|
||||
* @return array{success: bool, message: string, restored?: int, log?: string}
|
||||
*/
|
||||
public function restoreSelectedArticles(int $snapshotId, array $articleIds): array
|
||||
{
|
||||
if (empty($articleIds)) {
|
||||
return ['success' => false, 'message' => 'No article IDs provided'];
|
||||
}
|
||||
|
||||
$articleIds = array_map('intval', $articleIds);
|
||||
$articleIds = array_filter($articleIds, fn($id) => $id > 0);
|
||||
|
||||
if (empty($articleIds)) {
|
||||
return ['success' => false, 'message' => 'No valid article IDs provided'];
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
// Load snapshot record
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->where($db->quoteName('id') . ' = ' . $snapshotId);
|
||||
$db->setQuery($query);
|
||||
$record = $db->loadObject();
|
||||
|
||||
if (!$record) {
|
||||
return ['success' => false, 'message' => 'Snapshot not found: ' . $snapshotId];
|
||||
}
|
||||
|
||||
if ($record->status !== 'complete') {
|
||||
return ['success' => false, 'message' => 'Cannot restore from failed snapshot'];
|
||||
}
|
||||
|
||||
if (!is_file($record->data_file) || !is_readable($record->data_file)) {
|
||||
return ['success' => false, 'message' => 'Snapshot file not found: ' . $record->data_file];
|
||||
}
|
||||
|
||||
$this->log('Loading snapshot file: ' . basename($record->data_file));
|
||||
|
||||
$json = file_get_contents($record->data_file);
|
||||
|
||||
if ($json === false) {
|
||||
return ['success' => false, 'message' => 'Cannot read snapshot file'];
|
||||
}
|
||||
|
||||
$data = json_decode($json, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return ['success' => false, 'message' => 'Snapshot file contains invalid JSON: ' . json_last_error_msg()];
|
||||
}
|
||||
|
||||
if (!is_array($data) || empty($data['tables'])) {
|
||||
return ['success' => false, 'message' => 'Invalid snapshot data format: missing tables key'];
|
||||
}
|
||||
|
||||
$contentTable = $data['tables']['#__content'] ?? [];
|
||||
|
||||
if (empty($contentTable)) {
|
||||
return ['success' => false, 'message' => 'Snapshot does not contain articles'];
|
||||
}
|
||||
|
||||
// Filter #__content rows to only selected article IDs
|
||||
$selectedRows = array_filter($contentTable, fn($row) => in_array((int) ($row['id'] ?? 0), $articleIds, true));
|
||||
|
||||
if (empty($selectedRows)) {
|
||||
return ['success' => false, 'message' => 'None of the selected article IDs exist in this snapshot'];
|
||||
}
|
||||
|
||||
$foundIds = array_map(fn($row) => (int) $row['id'], $selectedRows);
|
||||
$this->log('Restoring ' . count($selectedRows) . ' articles: IDs ' . implode(', ', $foundIds));
|
||||
|
||||
// Filter workflow_associations for selected articles
|
||||
$workflowRows = [];
|
||||
|
||||
if (!empty($data['tables']['#__workflow_associations'])) {
|
||||
$workflowRows = array_filter(
|
||||
$data['tables']['#__workflow_associations'],
|
||||
fn($row) => in_array((int) ($row['item_id'] ?? 0), $foundIds, true)
|
||||
);
|
||||
}
|
||||
|
||||
// Filter tag_map entries for selected articles
|
||||
$tagMapRows = [];
|
||||
|
||||
if (!empty($data['tables']['#__contentitem_tag_map'])) {
|
||||
$tagMapRows = array_filter(
|
||||
$data['tables']['#__contentitem_tag_map'],
|
||||
fn($row) => in_array((int) ($row['content_item_id'] ?? 0), $foundIds, true)
|
||||
&& str_starts_with($row['type_alias'] ?? '', 'com_content.')
|
||||
);
|
||||
}
|
||||
|
||||
$prefix = $db->getPrefix();
|
||||
$totalRows = 0;
|
||||
|
||||
try {
|
||||
$db->transactionStart();
|
||||
|
||||
// Restore articles using merge/upsert
|
||||
$realTable = str_replace('#__', $prefix, '#__content');
|
||||
$rowCount = $this->restoreMerge($db, $realTable, '#__content', array_values($selectedRows));
|
||||
$totalRows += $rowCount;
|
||||
$this->log(' #__content: ' . $rowCount . ' rows restored');
|
||||
|
||||
// Restore workflow associations
|
||||
if (!empty($workflowRows)) {
|
||||
$realTable = str_replace('#__', $prefix, '#__workflow_associations');
|
||||
$rowCount = $this->restoreMerge($db, $realTable, '#__workflow_associations', array_values($workflowRows));
|
||||
$totalRows += $rowCount;
|
||||
$this->log(' #__workflow_associations: ' . $rowCount . ' rows restored');
|
||||
}
|
||||
|
||||
// Restore tag map entries
|
||||
if (!empty($tagMapRows)) {
|
||||
$realTable = str_replace('#__', $prefix, '#__contentitem_tag_map');
|
||||
$rowCount = $this->restoreMerge($db, $realTable, '#__contentitem_tag_map', array_values($tagMapRows));
|
||||
$totalRows += $rowCount;
|
||||
$this->log(' #__contentitem_tag_map: ' . $rowCount . ' rows restored');
|
||||
}
|
||||
|
||||
$db->transactionCommit();
|
||||
|
||||
$this->log('Selective restore complete: ' . $totalRows . ' total rows');
|
||||
|
||||
// Send notification
|
||||
try {
|
||||
$profile = NotificationSender::getDefaultProfile();
|
||||
|
||||
if ($profile) {
|
||||
$userName = Factory::getApplication()->getIdentity()->username ?? 'Unknown';
|
||||
$userIdVal = Factory::getApplication()->getIdentity()->id ?? 0;
|
||||
|
||||
NotificationSender::sendRestoreNotification($profile, 'snapshot_selective_restore', [
|
||||
'mode' => 'selective',
|
||||
'article_ids' => $foundIds,
|
||||
'row_count' => $totalRows,
|
||||
'user' => $userName . ' (ID: ' . $userIdVal . ')',
|
||||
], implode("\n", $this->log));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: Selective restore notification failed: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterSnapshotRestore(true, $snapshotId, 'selective');
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => sprintf('Restored %d articles (%d total rows)', count($selectedRows), $totalRows),
|
||||
'restored' => count($selectedRows),
|
||||
'log' => implode("\n", $this->log),
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
try {
|
||||
$db->transactionRollback();
|
||||
$this->log('Transaction rolled back');
|
||||
} catch (\Exception $rollbackEx) {
|
||||
$this->log('Rollback failed: ' . $rollbackEx->getMessage());
|
||||
}
|
||||
|
||||
$this->log('FATAL: ' . $e->getMessage());
|
||||
|
||||
// Dispatch event for actionlog and other listeners
|
||||
$this->dispatchAfterSnapshotRestore(false, $snapshotId, 'selective');
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Selective restore failed: ' . $e->getMessage(),
|
||||
'log' => implode("\n", $this->log),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch the onMokoSuiteBackupAfterSnapshotRestore event so plugins (actionlog, etc.) can react.
|
||||
*/
|
||||
private function dispatchAfterSnapshotRestore(bool $success, int $snapshotId, string $mode): void
|
||||
{
|
||||
try {
|
||||
$app = Factory::getApplication();
|
||||
|
||||
$event = new Event('onMokoSuiteBackupAfterSnapshotRestore', [
|
||||
'success' => $success,
|
||||
'snapshot_id' => $snapshotId,
|
||||
'mode' => $mode,
|
||||
]);
|
||||
|
||||
$app->getDispatcher()->dispatch('onMokoSuiteBackupAfterSnapshotRestore', $event);
|
||||
} catch (\Throwable $e) {
|
||||
// Never let a listener failure break the restore result, but log it
|
||||
error_log('MokoSuiteBackup: onAfterSnapshotRestore listener error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function log(string $message): void
|
||||
{
|
||||
$this->log[] = '[' . date('H:i:s') . '] ' . $message;
|
||||
|
||||
@@ -32,6 +32,18 @@ class SteppedBackupEngine
|
||||
*/
|
||||
public function init(int $profileId, string $description = '', string $origin = 'backend'): array
|
||||
{
|
||||
// Run pre-flight checks before creating any backup record
|
||||
$preflight = new PreflightCheck();
|
||||
$preflightResult = $preflight->run($profileId);
|
||||
|
||||
if (!$preflightResult['pass']) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'Pre-flight failed: ' . implode('; ', $preflightResult['errors']),
|
||||
'warnings' => $preflightResult['warnings'],
|
||||
];
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
// Load profile
|
||||
@@ -43,7 +55,7 @@ class SteppedBackupEngine
|
||||
$profile = $db->loadObject();
|
||||
|
||||
if (!$profile) {
|
||||
return ['error' => true, 'message' => 'Profile not found: ' . $profileId];
|
||||
return ['error' => true, 'message' => 'Profile not found: ' . $profileId, 'warnings' => []];
|
||||
}
|
||||
|
||||
// Create session
|
||||
@@ -58,9 +70,14 @@ class SteppedBackupEngine
|
||||
$session->excludeTables = BackupDirectory::parseNewlineList($profile->exclude_tables ?? '');
|
||||
$session->backupDir = $profile->backup_dir ?: BackupDirectory::PLACEHOLDER;
|
||||
$session->remoteStorage = $profile->remote_storage ?? 'none';
|
||||
$session->includeMokoRestore = (bool) ($profile->include_mokorestore ?? false);
|
||||
$session->includeMokoRestore = $profile->include_mokorestore ?? '0';
|
||||
$session->restoreScriptName = $profile->restore_script_name ?? 'restore.php';
|
||||
$session->remoteKeepLocal = (bool) ($profile->remote_keep_local ?? true);
|
||||
|
||||
// Load multi-remote destinations from the remotes table
|
||||
$session->remoteDestinations = $this->loadRemoteDestinations($db, $profileId);
|
||||
$session->remoteIndex = 0;
|
||||
|
||||
// Resolve placeholders in directory and filename
|
||||
$resolver = new PlaceholderResolver($profile);
|
||||
$backupDir = BackupDirectory::resolve($resolver->resolve($session->backupDir));
|
||||
@@ -69,9 +86,21 @@ class SteppedBackupEngine
|
||||
return ['error' => true, 'message' => 'Cannot create backup directory: ' . $backupDir];
|
||||
}
|
||||
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$tag = $resolver->getTag();
|
||||
$nameFormat = $profile->archive_name_format ?? '[host]_[datetime]_profile[profile_id]';
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$tag = $resolver->getTag();
|
||||
$archiveFormat = $profile->archive_format ?? 'zip';
|
||||
$nameFormat = $profile->archive_name_format ?? '[HOST]_[DATETIME]_profile[PROFILE_ID]';
|
||||
|
||||
// The stepped engine uses ZipArchive batch-by-batch, so only ZIP is
|
||||
// supported. For 7z / tar.gz the non-stepped BackupEngine must be used.
|
||||
if ($archiveFormat !== 'zip') {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'The stepped backup engine only supports ZIP format. '
|
||||
. 'Please use the CLI or API backup for ' . $archiveFormat . ' archives.',
|
||||
];
|
||||
}
|
||||
|
||||
$archiveName = $resolver->resolve($nameFormat) . '.zip';
|
||||
|
||||
$session->archivePath = $backupDir . '/' . $archiveName;
|
||||
@@ -123,13 +152,27 @@ class SteppedBackupEngine
|
||||
}
|
||||
|
||||
$totalSteps += 1; // finalize step
|
||||
$totalSteps += ($session->remoteStorage !== 'none') ? 1 : 0; // upload step
|
||||
|
||||
// Determine upload step count: one step per remote destination,
|
||||
// or one step for legacy single-remote, or zero if no remotes.
|
||||
$remoteCount = count($session->remoteDestinations);
|
||||
|
||||
if ($remoteCount > 0) {
|
||||
$totalSteps += $remoteCount;
|
||||
} elseif ($session->remoteStorage !== 'none') {
|
||||
$totalSteps += 1;
|
||||
}
|
||||
|
||||
$session->totalSteps = $totalSteps;
|
||||
$session->currentStep = 1;
|
||||
$session->phase = ($profile->backup_type !== 'files') ? 'database' : 'files';
|
||||
$session->log('Backup initialized: ' . $session->description);
|
||||
$session->log('Total steps: ' . $totalSteps . ' (tables: ' . count($session->tables) . ', file batches: ' . count($session->fileBatches) . ')');
|
||||
$session->log('Total steps: ' . $totalSteps . ' (tables: ' . count($session->tables) . ', file batches: ' . count($session->fileBatches) . ', remotes: ' . $remoteCount . ')');
|
||||
// Log any preflight warnings into the session
|
||||
foreach ($preflightResult['warnings'] as $warning) {
|
||||
$session->log('PREFLIGHT WARNING: ' . $warning);
|
||||
}
|
||||
|
||||
$session->statusMessage = 'Initialized — starting backup...';
|
||||
$session->save();
|
||||
|
||||
@@ -138,6 +181,7 @@ class SteppedBackupEngine
|
||||
'phase' => $session->phase,
|
||||
'progress' => $session->getProgress(),
|
||||
'message' => $session->statusMessage,
|
||||
'warnings' => $preflightResult['warnings'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -329,15 +373,35 @@ class SteppedBackupEngine
|
||||
|
||||
$totalSize = file_exists($session->archivePath) ? filesize($session->archivePath) : 0;
|
||||
|
||||
// MokoRestore wrapper
|
||||
if ($session->includeMokoRestore) {
|
||||
// Verify archive integrity
|
||||
$session->log('Verifying archive integrity...');
|
||||
$this->verifyArchive($session->archivePath, $session->backupType);
|
||||
$session->log('Archive integrity verified');
|
||||
|
||||
// MokoRestore
|
||||
$mokoRestoreMode = $session->includeMokoRestore ?? '0';
|
||||
$restoreScriptName = $session->restoreScriptName ?? 'restore.php';
|
||||
|
||||
if ($mokoRestoreMode === '1') {
|
||||
$session->log('Wrapping with MokoRestore script...');
|
||||
$mokoRestorePath = $session->archivePath . '.mokorestore.zip';
|
||||
MokoRestore::wrap($session->archivePath, $mokoRestorePath);
|
||||
MokoRestore::wrap($session->archivePath, $mokoRestorePath, $restoreScriptName);
|
||||
@unlink($session->archivePath);
|
||||
rename($mokoRestorePath, $session->archivePath);
|
||||
$totalSize = filesize($session->archivePath);
|
||||
$session->log('MokoRestore archive created');
|
||||
} elseif ($mokoRestoreMode === 'standalone') {
|
||||
$restoreScriptName = MokoRestore::sanitizeScriptName($restoreScriptName);
|
||||
$restoreDir = dirname($session->archivePath);
|
||||
$session->restoreScriptPath = $restoreDir . '/' . $restoreScriptName;
|
||||
|
||||
try {
|
||||
MokoRestore::generateStandalone($session->restoreScriptPath);
|
||||
$session->log('Standalone ' . $restoreScriptName . ' generated');
|
||||
} catch (\Throwable $e) {
|
||||
$session->log('MokoRestore error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
|
||||
$session->log('Stack trace: ' . $e->getTraceAsString());
|
||||
}
|
||||
}
|
||||
|
||||
// Update record
|
||||
@@ -356,7 +420,17 @@ class SteppedBackupEngine
|
||||
$db->updateObject('#__mokosuitebackup_records', $update, 'id');
|
||||
|
||||
$session->currentStep++;
|
||||
$session->phase = ($session->remoteStorage !== 'none') ? 'upload' : 'complete';
|
||||
|
||||
// Determine next phase: multi-remote, legacy single-remote, or complete
|
||||
$hasMultiRemote = !empty($session->remoteDestinations);
|
||||
$hasLegacyRemote = $session->remoteStorage !== 'none';
|
||||
|
||||
if ($hasMultiRemote || $hasLegacyRemote) {
|
||||
$session->phase = 'upload';
|
||||
} else {
|
||||
$session->phase = 'complete';
|
||||
}
|
||||
|
||||
$session->statusMessage = 'Archive finalized: ' . $sizeHuman;
|
||||
$session->log('Archive finalized: ' . $sizeHuman);
|
||||
|
||||
@@ -367,62 +441,197 @@ class SteppedBackupEngine
|
||||
|
||||
/**
|
||||
* Upload phase: send archive to remote storage.
|
||||
*
|
||||
* When multi-remote destinations are configured, each call uploads to
|
||||
* one destination (one step per remote). When only the legacy
|
||||
* single-remote column is set, uploads in a single step.
|
||||
*/
|
||||
private function stepUpload(SteppedSession $session): void
|
||||
{
|
||||
$db = Factory::getDbo();
|
||||
|
||||
// Reload profile for remote settings
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_profiles'))
|
||||
->where($db->quoteName('id') . ' = ' . $session->profileId);
|
||||
$db->setQuery($query);
|
||||
$profile = $db->loadObject();
|
||||
|
||||
$uploader = match ($session->remoteStorage) {
|
||||
'ftp' => new FtpUploader($profile),
|
||||
'google_drive' => new GoogleDriveUploader($profile),
|
||||
's3' => new S3Uploader($profile),
|
||||
default => throw new \InvalidArgumentException('Unknown storage: ' . $session->remoteStorage),
|
||||
};
|
||||
|
||||
$session->log('Starting remote upload (' . $session->remoteStorage . ')...');
|
||||
$result = $uploader->upload($session->archivePath, $session->archiveName);
|
||||
|
||||
$remoteFilename = '';
|
||||
$uploadFailed = false;
|
||||
|
||||
if ($result['success']) {
|
||||
$remoteFilename = $result['remote_path'] ?? $session->archiveName;
|
||||
$session->log('Remote upload complete: ' . $result['message']);
|
||||
if (!empty($session->remoteDestinations)) {
|
||||
// ── Multi-remote path ──────────────────────────────────
|
||||
$index = $session->remoteIndex;
|
||||
|
||||
if (!$session->remoteKeepLocal && is_file($session->archivePath)) {
|
||||
@unlink($session->archivePath);
|
||||
$session->log('Local copy removed');
|
||||
if ($index >= count($session->remoteDestinations)) {
|
||||
// All remotes processed — move to complete
|
||||
$session->phase = 'complete';
|
||||
$session->statusMessage = 'All remote uploads finished';
|
||||
$this->completeRecord($session);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$remote = (object) $session->remoteDestinations[$index];
|
||||
|
||||
try {
|
||||
$title = $remote->title ?? ('Remote #' . ($index + 1));
|
||||
$type = $remote->type ?? 'unknown';
|
||||
$params = json_decode($remote->params ?? '{}', true) ?: [];
|
||||
|
||||
$session->log('Uploading to: ' . $title . ' (' . $type . ')...');
|
||||
$uploader = $this->createUploaderFromParams($type, $params);
|
||||
$result = $uploader->upload($session->archivePath, $session->archiveName);
|
||||
|
||||
if ($result['success']) {
|
||||
$remoteFilename = $result['remote_path'] ?? $session->archiveName;
|
||||
$session->log(' Upload complete: ' . $result['message']);
|
||||
|
||||
if (!empty($session->restoreScriptPath) && is_file($session->restoreScriptPath)) {
|
||||
$uploader->upload($session->restoreScriptPath, basename($session->restoreScriptPath));
|
||||
}
|
||||
} else {
|
||||
$uploadFailed = true;
|
||||
$session->log(' WARNING: Upload failed: ' . $result['message']);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$uploadFailed = true;
|
||||
$session->log(' WARNING: Upload exception: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$session->remoteIndex++;
|
||||
$session->currentStep++;
|
||||
|
||||
$remaining = count($session->remoteDestinations) - $session->remoteIndex;
|
||||
$session->statusMessage = 'Uploaded to ' . ($remote->title ?? 'remote') . ($remaining > 0 ? ' (' . $remaining . ' remaining)' : '');
|
||||
|
||||
if ($session->remoteIndex >= count($session->remoteDestinations)) {
|
||||
// All remotes done — delete local if configured and no failures
|
||||
if (!$uploadFailed && !$session->remoteKeepLocal && is_file($session->archivePath)) {
|
||||
@unlink($session->archivePath);
|
||||
$session->log('Local copy removed (remote_keep_local = off)');
|
||||
}
|
||||
|
||||
// Update record with remote filename
|
||||
$update = (object) [
|
||||
'id' => $session->recordId,
|
||||
'remote_filename' => $remoteFilename,
|
||||
'filesexist' => is_file($session->archivePath) ? 1 : 0,
|
||||
];
|
||||
$db->updateObject('#__mokosuitebackup_records', $update, 'id');
|
||||
|
||||
$session->phase = 'complete';
|
||||
$session->statusMessage = $uploadFailed
|
||||
? 'Backup complete (some remote uploads failed — local archive preserved)'
|
||||
: 'Backup complete';
|
||||
$this->completeRecord($session, $uploadFailed);
|
||||
}
|
||||
} else {
|
||||
$session->log('WARNING: Remote upload failed: ' . $result['message']);
|
||||
// ── Legacy single-remote fallback ──────────────────────
|
||||
try {
|
||||
// Reload profile for remote settings
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_profiles'))
|
||||
->where($db->quoteName('id') . ' = ' . $session->profileId);
|
||||
$db->setQuery($query);
|
||||
$profile = $db->loadObject();
|
||||
|
||||
$uploader = match ($session->remoteStorage) {
|
||||
'ftp' => new FtpUploader($profile),
|
||||
'sftp' => new SftpUploader($profile),
|
||||
'google_drive' => new GoogleDriveUploader($profile),
|
||||
's3' => new S3Uploader($profile),
|
||||
default => throw new \InvalidArgumentException('Unknown storage: ' . $session->remoteStorage),
|
||||
};
|
||||
|
||||
$session->log('Starting remote upload (' . $session->remoteStorage . ')...');
|
||||
$result = $uploader->upload($session->archivePath, $session->archiveName);
|
||||
|
||||
if ($result['success']) {
|
||||
$remoteFilename = $result['remote_path'] ?? $session->archiveName;
|
||||
$session->log('Remote upload complete: ' . $result['message']);
|
||||
|
||||
if (!empty($session->restoreScriptPath) && is_file($session->restoreScriptPath)) {
|
||||
$restoreBasename = basename($session->restoreScriptPath);
|
||||
$session->log('Uploading standalone ' . $restoreBasename . '...');
|
||||
$uploader->upload($session->restoreScriptPath, $restoreBasename);
|
||||
}
|
||||
|
||||
if (!$session->remoteKeepLocal && is_file($session->archivePath)) {
|
||||
@unlink($session->archivePath);
|
||||
$session->log('Local copy removed');
|
||||
}
|
||||
} else {
|
||||
$uploadFailed = true;
|
||||
$session->log('WARNING: Remote upload failed: ' . $result['message']);
|
||||
$session->log('Local backup is preserved.');
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$uploadFailed = true;
|
||||
$session->log('WARNING: Remote upload threw an exception: ' . $e->getMessage());
|
||||
$session->log('Local backup is preserved.');
|
||||
}
|
||||
|
||||
// Update record with remote filename
|
||||
$update = (object) [
|
||||
'id' => $session->recordId,
|
||||
'remote_filename' => $remoteFilename,
|
||||
'filesexist' => is_file($session->archivePath) ? 1 : 0,
|
||||
];
|
||||
|
||||
$db->updateObject('#__mokosuitebackup_records', $update, 'id');
|
||||
|
||||
$session->currentStep++;
|
||||
$session->phase = 'complete';
|
||||
$session->statusMessage = $uploadFailed
|
||||
? 'Backup complete (remote upload failed — local archive preserved)'
|
||||
: 'Backup complete';
|
||||
$this->completeRecord($session, $uploadFailed);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that a backup archive can be opened and contains expected entries.
|
||||
*
|
||||
* @param string $archivePath Absolute path to the archive file
|
||||
* @param string $backupType Backup type: full, database, files, differential
|
||||
*
|
||||
* @throws \RuntimeException If the archive fails verification
|
||||
*/
|
||||
private function verifyArchive(string $archivePath, string $backupType): void
|
||||
{
|
||||
if (!is_file($archivePath)) {
|
||||
throw new \RuntimeException('Archive file does not exist: ' . $archivePath);
|
||||
}
|
||||
|
||||
// Update record with remote filename
|
||||
$update = (object) [
|
||||
'id' => $session->recordId,
|
||||
'remote_filename' => $remoteFilename,
|
||||
'filesexist' => is_file($session->archivePath) ? 1 : 0,
|
||||
];
|
||||
$zip = new \ZipArchive();
|
||||
|
||||
$db->updateObject('#__mokosuitebackup_records', $update, 'id');
|
||||
if ($zip->open($archivePath, \ZipArchive::RDONLY) !== true) {
|
||||
throw new \RuntimeException('Archive integrity check failed: cannot open ZIP file');
|
||||
}
|
||||
|
||||
$session->currentStep++;
|
||||
$session->phase = 'complete';
|
||||
$session->statusMessage = 'Backup complete';
|
||||
$this->completeRecord($session);
|
||||
if ($zip->numFiles < 1) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive integrity check failed: archive contains no files');
|
||||
}
|
||||
|
||||
// Verify database.sql exists when backup includes database
|
||||
if ($backupType !== 'files') {
|
||||
if ($zip->locateName('database.sql') === false) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive integrity check failed: database.sql missing from archive');
|
||||
}
|
||||
}
|
||||
|
||||
// Spot-check: verify the first entry is readable
|
||||
$firstName = $zip->getNameIndex(0);
|
||||
|
||||
if ($firstName === false) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive integrity check failed: cannot read first entry');
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the backup record as complete.
|
||||
*/
|
||||
private function completeRecord(SteppedSession $session): void
|
||||
private function completeRecord(SteppedSession $session, bool $uploadFailed = false): void
|
||||
{
|
||||
$db = Factory::getDbo();
|
||||
$logContent = implode("\n", $session->log);
|
||||
@@ -472,6 +681,11 @@ class SteppedBackupEngine
|
||||
];
|
||||
|
||||
NotificationSender::send($profile, $record, true, $logContent);
|
||||
|
||||
// If remote upload failed, also send a failure notification for the upload
|
||||
if ($uploadFailed) {
|
||||
NotificationSender::send($profile, $record, false, "Remote upload failed — see backup log for details.\n\n" . $logContent);
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
error_log('MokoSuiteBackup: SteppedBackupEngine notification failed: ' . $e->getMessage());
|
||||
@@ -632,4 +846,58 @@ class SteppedBackupEngine
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load enabled remote destinations for a profile from the remotes table.
|
||||
*
|
||||
* Returns an empty array when the table does not exist (pre-migration)
|
||||
* so the caller can fall back to the legacy single-remote column.
|
||||
*
|
||||
* @param object $db Database driver
|
||||
* @param int $profileId Profile ID
|
||||
*
|
||||
* @return array Array of remote destination rows (as associative arrays for JSON serialization)
|
||||
*/
|
||||
private function loadRemoteDestinations(object $db, int $profileId): array
|
||||
{
|
||||
try {
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_remotes'))
|
||||
->where($db->quoteName('profile_id') . ' = ' . (int) $profileId)
|
||||
->where($db->quoteName('enabled') . ' = 1')
|
||||
->order($db->quoteName('ordering') . ' ASC');
|
||||
$db->setQuery($query);
|
||||
|
||||
// Use loadAssocList so the data survives JSON serialization in SteppedSession
|
||||
return $db->loadAssocList() ?: [];
|
||||
} catch (\Throwable $e) {
|
||||
// Table does not exist yet (pre-migration) — fall back to legacy
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a remote uploader from JSON params (multi-remote destinations).
|
||||
*
|
||||
* Builds a fake profile-like object from the params array so the existing
|
||||
* uploader constructors work without modification.
|
||||
*
|
||||
* @param string $type Remote type: ftp, sftp, s3, google_drive
|
||||
* @param array $params Key-value params decoded from the remote's JSON
|
||||
*
|
||||
* @return RemoteUploaderInterface
|
||||
*/
|
||||
private function createUploaderFromParams(string $type, array $params): RemoteUploaderInterface
|
||||
{
|
||||
$fake = (object) $params;
|
||||
|
||||
return match ($type) {
|
||||
'ftp' => new FtpUploader($fake),
|
||||
'sftp' => new SftpUploader($fake),
|
||||
'google_drive' => new GoogleDriveUploader($fake),
|
||||
's3' => new S3Uploader($fake),
|
||||
default => throw new \InvalidArgumentException('Unknown remote storage type: ' . $type),
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,753 @@
|
||||
<?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
|
||||
*
|
||||
* AJAX step-based restore engine for shared hosting.
|
||||
*
|
||||
* Each call to runStep() performs one unit of work within the PHP time
|
||||
* limit, saves state, and returns. The browser JS fires the next step.
|
||||
*
|
||||
* Phases: extract -> files -> database -> config -> cleanup -> complete
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Administrator\Engine;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
|
||||
class SteppedRestoreEngine
|
||||
{
|
||||
/**
|
||||
* Number of files to copy per step during the files phase.
|
||||
*/
|
||||
private const FILE_BATCH_SIZE = 200;
|
||||
|
||||
/**
|
||||
* Number of SQL statements to execute per step during the database phase.
|
||||
*/
|
||||
private const SQL_BATCH_SIZE = 500;
|
||||
|
||||
/**
|
||||
* Initialize a new stepped restore session.
|
||||
*
|
||||
* @param int $recordId Backup record ID to restore from
|
||||
* @param bool $restoreFiles Whether to restore files
|
||||
* @param bool $restoreDb Whether to restore the database
|
||||
* @param bool $preserveConfig Keep current configuration.php
|
||||
* @param string $password Decryption password (for encrypted archives)
|
||||
*
|
||||
* @return array{session_id: string, phase: string, progress: int, message: string}
|
||||
*/
|
||||
public function init(int $recordId, bool $restoreFiles = true, bool $restoreDb = true, bool $preserveConfig = true, string $password = ''): array
|
||||
{
|
||||
if (!extension_loaded('zip')) {
|
||||
return ['error' => true, 'message' => 'PHP ext-zip is required for restore operations'];
|
||||
}
|
||||
|
||||
$db = Factory::getDbo();
|
||||
|
||||
// Load backup record
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_records'))
|
||||
->where($db->quoteName('id') . ' = ' . $recordId);
|
||||
$db->setQuery($query);
|
||||
$record = $db->loadObject();
|
||||
|
||||
if (!$record) {
|
||||
return ['error' => true, 'message' => 'Backup record not found: ' . $recordId];
|
||||
}
|
||||
|
||||
if ($record->status !== 'complete') {
|
||||
return ['error' => true, 'message' => 'Cannot restore from incomplete backup (status: ' . $record->status . ')'];
|
||||
}
|
||||
|
||||
$archivePath = $record->absolute_path;
|
||||
|
||||
if (!is_file($archivePath) || !is_readable($archivePath)) {
|
||||
return ['error' => true, 'message' => 'Backup archive not found: ' . $archivePath];
|
||||
}
|
||||
|
||||
// Create session
|
||||
$session = SteppedSession::create();
|
||||
$session->recordId = $recordId;
|
||||
$session->archivePath = $archivePath;
|
||||
$session->archiveName = basename($archivePath);
|
||||
$session->description = 'Restore from: ' . ($record->description ?: basename($archivePath));
|
||||
|
||||
// Store restore-specific settings as dynamic properties via the session's
|
||||
// generic save/load (SteppedSession serialises all public properties).
|
||||
// We repurpose some existing fields and add restore-specific ones to the
|
||||
// session data stored on disk.
|
||||
$session->phase = 'extract';
|
||||
|
||||
// Build staging directory path
|
||||
$safeTag = preg_replace('/[^a-zA-Z0-9_-]/', '', $record->tag ?: 'restore');
|
||||
$stagingDir = JPATH_ROOT . '/tmp/mokosuitebackup-restore-' . $safeTag . '-' . substr($session->sessionId, 3);
|
||||
|
||||
// Estimate total steps
|
||||
$totalSteps = 1; // extract step
|
||||
|
||||
if ($restoreFiles) {
|
||||
$totalSteps += 1; // at least one files step (will adjust after extraction)
|
||||
}
|
||||
|
||||
if ($restoreDb) {
|
||||
$totalSteps += 1; // at least one database step (will adjust after extraction)
|
||||
}
|
||||
|
||||
$totalSteps += 1; // config step
|
||||
$totalSteps += 1; // cleanup step
|
||||
|
||||
$session->totalSteps = $totalSteps;
|
||||
$session->currentStep = 0;
|
||||
$session->statusMessage = 'Initializing restore...';
|
||||
|
||||
// Store restore-specific data in session log metadata
|
||||
// We'll use a JSON file alongside the session for restore state
|
||||
$restoreState = [
|
||||
'staging_dir' => $stagingDir,
|
||||
'restore_files' => $restoreFiles,
|
||||
'restore_db' => $restoreDb,
|
||||
'preserve_config' => $preserveConfig,
|
||||
'password' => $password,
|
||||
'config_backup' => '',
|
||||
'file_list' => [],
|
||||
'file_index' => 0,
|
||||
'sql_file' => '',
|
||||
'sql_offset' => 0,
|
||||
'sql_done' => false,
|
||||
'sql_executed' => 0,
|
||||
];
|
||||
|
||||
$this->saveRestoreState($session->sessionId, $restoreState);
|
||||
|
||||
$session->log('Restore initialized for record #' . $recordId . ': ' . $record->description);
|
||||
$session->log('Archive: ' . $archivePath);
|
||||
$session->log('Options: files=' . ($restoreFiles ? 'yes' : 'no')
|
||||
. ', database=' . ($restoreDb ? 'yes' : 'no')
|
||||
. ', preserve_config=' . ($preserveConfig ? 'yes' : 'no'));
|
||||
$session->save();
|
||||
|
||||
return [
|
||||
'session_id' => $session->sessionId,
|
||||
'phase' => $session->phase,
|
||||
'progress' => $session->getProgress(),
|
||||
'message' => $session->statusMessage,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the next step of a restore session.
|
||||
*
|
||||
* @return array{session_id: string, phase: string, progress: int, message: string, done?: bool}
|
||||
*/
|
||||
public function runStep(string $sessionId): array
|
||||
{
|
||||
$session = SteppedSession::load($sessionId);
|
||||
|
||||
if (!$session) {
|
||||
return ['error' => true, 'message' => 'Session not found: ' . $sessionId];
|
||||
}
|
||||
|
||||
$restoreState = $this->loadRestoreState($sessionId);
|
||||
|
||||
if (!$restoreState) {
|
||||
return ['error' => true, 'message' => 'Restore state not found for session: ' . $sessionId];
|
||||
}
|
||||
|
||||
try {
|
||||
switch ($session->phase) {
|
||||
case 'extract':
|
||||
$this->stepExtract($session, $restoreState);
|
||||
break;
|
||||
|
||||
case 'files':
|
||||
$this->stepFiles($session, $restoreState);
|
||||
break;
|
||||
|
||||
case 'database':
|
||||
$this->stepDatabase($session, $restoreState);
|
||||
break;
|
||||
|
||||
case 'config':
|
||||
$this->stepConfig($session, $restoreState);
|
||||
break;
|
||||
|
||||
case 'cleanup':
|
||||
$this->stepCleanup($session, $restoreState);
|
||||
break;
|
||||
|
||||
case 'complete':
|
||||
$this->destroyRestoreState($sessionId);
|
||||
$session->destroy();
|
||||
|
||||
return [
|
||||
'session_id' => $sessionId,
|
||||
'phase' => 'complete',
|
||||
'progress' => 100,
|
||||
'message' => 'Restore complete: ' . $session->archiveName,
|
||||
'done' => true,
|
||||
];
|
||||
}
|
||||
|
||||
$this->saveRestoreState($sessionId, $restoreState);
|
||||
$session->save();
|
||||
|
||||
return [
|
||||
'session_id' => $sessionId,
|
||||
'phase' => $session->phase,
|
||||
'progress' => $session->getProgress(),
|
||||
'message' => $session->statusMessage,
|
||||
'done' => $session->phase === 'complete',
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
$session->log('FATAL: ' . $e->getMessage());
|
||||
|
||||
// Restore config on failure if we preserved it
|
||||
if (!empty($restoreState['config_backup']) && $restoreState['preserve_config']) {
|
||||
@file_put_contents(JPATH_ROOT . '/configuration.php', $restoreState['config_backup']);
|
||||
$session->log('Configuration.php restored after failure');
|
||||
}
|
||||
|
||||
// Clean up staging on failure
|
||||
$stagingDir = $restoreState['staging_dir'] ?? '';
|
||||
|
||||
if (!empty($stagingDir) && is_dir($stagingDir)) {
|
||||
$this->recursiveDelete($stagingDir);
|
||||
}
|
||||
|
||||
$this->destroyRestoreState($sessionId);
|
||||
$session->destroy();
|
||||
|
||||
return ['error' => true, 'message' => 'Restore failed: ' . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract phase: extract archive to staging directory.
|
||||
*/
|
||||
private function stepExtract(SteppedSession $session, array &$state): void
|
||||
{
|
||||
$stagingDir = $state['staging_dir'];
|
||||
$archivePath = $session->archivePath;
|
||||
$password = $state['password'];
|
||||
|
||||
// Clean existing staging dir
|
||||
if (is_dir($stagingDir)) {
|
||||
$this->recursiveDelete($stagingDir);
|
||||
}
|
||||
|
||||
if (!mkdir($stagingDir, 0755, true)) {
|
||||
throw new \RuntimeException('Cannot create staging directory: ' . $stagingDir);
|
||||
}
|
||||
|
||||
$session->log('Extracting archive: ' . basename($archivePath));
|
||||
|
||||
// Detect format and extract
|
||||
if (JpaUnarchiver::isJpaFile($archivePath)) {
|
||||
$session->log('Detected JPA format (Akeeba Backup archive)');
|
||||
$jpa = new JpaUnarchiver($archivePath, $stagingDir);
|
||||
$count = $jpa->extract();
|
||||
$session->log('Extracted ' . $count . ' files from JPA');
|
||||
} elseif (str_ends_with($archivePath, '.tar.gz') || str_ends_with($archivePath, '.tgz')) {
|
||||
$session->log('Detected tar.gz format');
|
||||
$phar = new \PharData($archivePath);
|
||||
|
||||
// Validate entries for path traversal
|
||||
foreach (new \RecursiveIteratorIterator($phar) as $entry) {
|
||||
$entryName = $entry->getPathname();
|
||||
$relative = substr($entryName, strlen('phar://' . $archivePath) + 1);
|
||||
|
||||
if (str_contains($relative, '../') || str_contains($relative, '..\\')
|
||||
|| str_starts_with($relative, '/') || str_starts_with($relative, '\\')) {
|
||||
throw new \RuntimeException('Archive contains unsafe path: ' . $relative);
|
||||
}
|
||||
}
|
||||
|
||||
$phar->extractTo($stagingDir, null, true);
|
||||
$session->log('Extracted tar.gz archive');
|
||||
} else {
|
||||
$this->extractZipArchive($archivePath, $stagingDir, $password, $session);
|
||||
}
|
||||
|
||||
$session->log('Extraction complete');
|
||||
|
||||
// Preserve configuration.php before any files are copied
|
||||
if ($state['preserve_config'] && is_file(JPATH_ROOT . '/configuration.php')) {
|
||||
$state['config_backup'] = file_get_contents(JPATH_ROOT . '/configuration.php');
|
||||
$session->log('Current configuration.php preserved');
|
||||
}
|
||||
|
||||
// Build file list for the files phase
|
||||
if ($state['restore_files']) {
|
||||
$fileList = $this->scanStagingFiles($stagingDir);
|
||||
$state['file_list'] = $fileList;
|
||||
$state['file_index'] = 0;
|
||||
|
||||
$fileBatches = (int) ceil(count($fileList) / self::FILE_BATCH_SIZE);
|
||||
$session->log('Files to restore: ' . count($fileList) . ' (' . $fileBatches . ' batches)');
|
||||
}
|
||||
|
||||
// Check for SQL file
|
||||
$sqlFile = $stagingDir . '/database.sql';
|
||||
|
||||
if ($state['restore_db'] && is_file($sqlFile)) {
|
||||
$state['sql_file'] = $sqlFile;
|
||||
$state['sql_offset'] = 0;
|
||||
$state['sql_done'] = false;
|
||||
|
||||
// Estimate SQL batches by counting lines
|
||||
$lineCount = 0;
|
||||
$fh = fopen($sqlFile, 'r');
|
||||
|
||||
if ($fh) {
|
||||
while (fgets($fh) !== false) {
|
||||
$lineCount++;
|
||||
}
|
||||
|
||||
fclose($fh);
|
||||
}
|
||||
|
||||
// Rough estimate: each statement ~2 lines on average
|
||||
$estimatedStatements = max(1, (int) ($lineCount / 2));
|
||||
$sqlBatches = (int) ceil($estimatedStatements / self::SQL_BATCH_SIZE);
|
||||
$session->log('SQL file found: ~' . $estimatedStatements . ' statements (' . $sqlBatches . ' batches)');
|
||||
} elseif ($state['restore_db']) {
|
||||
$session->log('No database.sql found in archive — skipping database restore');
|
||||
$state['restore_db'] = false;
|
||||
}
|
||||
|
||||
// Recalculate total steps now that we know the actual counts
|
||||
$totalSteps = 1; // extract (done)
|
||||
|
||||
if ($state['restore_files']) {
|
||||
$totalSteps += max(1, (int) ceil(count($state['file_list']) / self::FILE_BATCH_SIZE));
|
||||
}
|
||||
|
||||
if ($state['restore_db'] && !empty($state['sql_file'])) {
|
||||
$totalSteps += max(1, $sqlBatches ?? 1);
|
||||
}
|
||||
|
||||
$totalSteps += 1; // config
|
||||
$totalSteps += 1; // cleanup
|
||||
|
||||
$session->totalSteps = $totalSteps;
|
||||
$session->currentStep = 1;
|
||||
|
||||
// Move to next phase
|
||||
if ($state['restore_files']) {
|
||||
$session->phase = 'files';
|
||||
} elseif ($state['restore_db'] && !empty($state['sql_file'])) {
|
||||
$session->phase = 'database';
|
||||
} else {
|
||||
$session->phase = 'config';
|
||||
}
|
||||
|
||||
$session->statusMessage = 'Archive extracted — starting restore...';
|
||||
}
|
||||
|
||||
/**
|
||||
* Files phase: copy a batch of files from staging to JPATH_ROOT.
|
||||
*/
|
||||
private function stepFiles(SteppedSession $session, array &$state): void
|
||||
{
|
||||
$fileList = $state['file_list'];
|
||||
$fileIndex = $state['file_index'];
|
||||
$stagingDir = $state['staging_dir'];
|
||||
$totalFiles = count($fileList);
|
||||
|
||||
if ($fileIndex >= $totalFiles) {
|
||||
// Files phase complete
|
||||
$session->log('Files phase complete: ' . $totalFiles . ' files restored');
|
||||
|
||||
if ($state['restore_db'] && !empty($state['sql_file'])) {
|
||||
$session->phase = 'database';
|
||||
} else {
|
||||
$session->phase = 'config';
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$batchEnd = min($fileIndex + self::FILE_BATCH_SIZE, $totalFiles);
|
||||
$copied = 0;
|
||||
$sourceBase = rtrim($stagingDir, '/\\');
|
||||
$targetBase = rtrim(JPATH_ROOT, '/\\');
|
||||
|
||||
// Files that should never be overwritten during restore
|
||||
$skipFiles = ['configuration.php', 'configuration.php.bak', '.htaccess', 'web.config'];
|
||||
$excludeFiles = ['database.sql'];
|
||||
|
||||
for ($i = $fileIndex; $i < $batchEnd; $i++) {
|
||||
$relativePath = $fileList[$i];
|
||||
$sourcePath = $sourceBase . '/' . $relativePath;
|
||||
$targetPath = $targetBase . '/' . $relativePath;
|
||||
$basename = basename($relativePath);
|
||||
$dirPart = dirname($relativePath);
|
||||
|
||||
// Skip excluded files
|
||||
if (in_array($basename, $excludeFiles, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip protected files at root level
|
||||
if (($dirPart === '' || $dirPart === '.') && in_array($basename, $skipFiles, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_file($sourcePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
$parentDir = dirname($targetPath);
|
||||
|
||||
if (!is_dir($parentDir)) {
|
||||
mkdir($parentDir, 0755, true);
|
||||
}
|
||||
|
||||
if (copy($sourcePath, $targetPath)) {
|
||||
$perms = fileperms($sourcePath);
|
||||
|
||||
if ($perms !== false) {
|
||||
@chmod($targetPath, $perms);
|
||||
}
|
||||
|
||||
$copied++;
|
||||
}
|
||||
}
|
||||
|
||||
$state['file_index'] = $batchEnd;
|
||||
|
||||
$session->currentStep++;
|
||||
$batchNum = (int) ceil($batchEnd / self::FILE_BATCH_SIZE);
|
||||
$totalBatch = (int) ceil($totalFiles / self::FILE_BATCH_SIZE);
|
||||
$session->statusMessage = "Restoring files batch {$batchNum}/{$totalBatch} ({$copied} files copied)";
|
||||
$session->log("Files batch {$batchNum}: {$copied} files copied ({$batchEnd}/{$totalFiles})");
|
||||
|
||||
// Check if we're done with files
|
||||
if ($batchEnd >= $totalFiles) {
|
||||
$session->log('Files phase complete: ' . $totalFiles . ' files processed');
|
||||
|
||||
if ($state['restore_db'] && !empty($state['sql_file'])) {
|
||||
$session->phase = 'database';
|
||||
} else {
|
||||
$session->phase = 'config';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Database phase: import SQL statements in batches.
|
||||
*/
|
||||
private function stepDatabase(SteppedSession $session, array &$state): void
|
||||
{
|
||||
if ($state['sql_done'] || empty($state['sql_file'])) {
|
||||
$session->log('Database phase complete: ' . $state['sql_executed'] . ' statements executed');
|
||||
$session->phase = 'config';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$sqlFile = $state['sql_file'];
|
||||
$offset = $state['sql_offset'];
|
||||
|
||||
$db = Factory::getDbo();
|
||||
$prefix = $db->getPrefix();
|
||||
|
||||
$handle = fopen($sqlFile, 'r');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new \RuntimeException('Cannot open SQL file: ' . $sqlFile);
|
||||
}
|
||||
|
||||
// Seek to the byte offset where we left off
|
||||
if ($offset > 0) {
|
||||
fseek($handle, $offset);
|
||||
}
|
||||
|
||||
$statementsExecuted = 0;
|
||||
$currentStatement = '';
|
||||
$inMultiLineComment = false;
|
||||
|
||||
while (($line = fgets($handle)) !== false) {
|
||||
$trimmed = trim($line);
|
||||
|
||||
// Skip empty lines
|
||||
if ($trimmed === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip single-line comments
|
||||
if (str_starts_with($trimmed, '--') || str_starts_with($trimmed, '#')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle multi-line comments
|
||||
if (str_starts_with($trimmed, '/*')) {
|
||||
$inMultiLineComment = true;
|
||||
}
|
||||
|
||||
if ($inMultiLineComment) {
|
||||
if (str_contains($trimmed, '*/')) {
|
||||
$inMultiLineComment = false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Accumulate the statement
|
||||
$currentStatement .= $line;
|
||||
|
||||
// Check if statement is complete (ends with semicolon)
|
||||
if (str_ends_with($trimmed, ';')) {
|
||||
$statement = trim($currentStatement);
|
||||
$currentStatement = '';
|
||||
|
||||
if (empty($statement)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace abstract #__ prefix with the current site's prefix
|
||||
$statement = str_replace('#__', $prefix, $statement);
|
||||
|
||||
try {
|
||||
$db->setQuery($statement);
|
||||
$db->execute();
|
||||
} catch (\Exception $e) {
|
||||
error_log('MokoSuiteBackup SQL import warning: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$statementsExecuted++;
|
||||
$state['sql_executed']++;
|
||||
|
||||
// Check if we've hit the batch limit
|
||||
if ($statementsExecuted >= self::SQL_BATCH_SIZE) {
|
||||
$state['sql_offset'] = ftell($handle);
|
||||
fclose($handle);
|
||||
|
||||
$session->currentStep++;
|
||||
$session->statusMessage = 'Importing database... (' . $state['sql_executed'] . ' statements executed)';
|
||||
$session->log('Database batch: ' . $statementsExecuted . ' statements (total: ' . $state['sql_executed'] . ')');
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle any remaining statement without trailing semicolon
|
||||
$remaining = trim($currentStatement);
|
||||
|
||||
if (!empty($remaining)) {
|
||||
$remaining = str_replace('#__', $prefix, $remaining);
|
||||
|
||||
try {
|
||||
$db->setQuery($remaining);
|
||||
$db->execute();
|
||||
$state['sql_executed']++;
|
||||
} catch (\Exception $e) {
|
||||
error_log('MokoSuiteBackup SQL import warning (final): ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
fclose($handle);
|
||||
|
||||
$state['sql_done'] = true;
|
||||
$session->currentStep++;
|
||||
$session->phase = 'config';
|
||||
$session->statusMessage = 'Database import complete: ' . $state['sql_executed'] . ' statements';
|
||||
$session->log('Database import complete: ' . $state['sql_executed'] . ' statements executed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Config phase: restore preserved configuration.php.
|
||||
*/
|
||||
private function stepConfig(SteppedSession $session, array &$state): void
|
||||
{
|
||||
if ($state['preserve_config'] && !empty($state['config_backup'])) {
|
||||
file_put_contents(JPATH_ROOT . '/configuration.php', $state['config_backup']);
|
||||
$session->log('Configuration.php restored to pre-restore state');
|
||||
}
|
||||
|
||||
$session->currentStep++;
|
||||
$session->phase = 'cleanup';
|
||||
$session->statusMessage = 'Configuration restored — cleaning up...';
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup phase: remove staging directory.
|
||||
*/
|
||||
private function stepCleanup(SteppedSession $session, array &$state): void
|
||||
{
|
||||
$stagingDir = $state['staging_dir'];
|
||||
|
||||
if (!empty($stagingDir) && is_dir($stagingDir)) {
|
||||
$this->recursiveDelete($stagingDir);
|
||||
$session->log('Staging directory cleaned up');
|
||||
}
|
||||
|
||||
$session->currentStep++;
|
||||
$session->phase = 'complete';
|
||||
$session->statusMessage = 'Restore complete: ' . $session->archiveName;
|
||||
$session->log('Restore complete');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a ZIP archive to the staging directory with path traversal protection.
|
||||
*/
|
||||
private function extractZipArchive(string $archivePath, string $stagingDir, string $password, SteppedSession $session): void
|
||||
{
|
||||
$zip = new \ZipArchive();
|
||||
$result = $zip->open($archivePath);
|
||||
|
||||
if ($result !== true) {
|
||||
throw new \RuntimeException('Cannot open archive (error code: ' . $result . ')');
|
||||
}
|
||||
|
||||
if (!empty($password)) {
|
||||
$zip->setPassword($password);
|
||||
$session->log('Decryption password set');
|
||||
}
|
||||
|
||||
// Validate all entries before extraction (path traversal protection)
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$entryName = $zip->getNameIndex($i);
|
||||
|
||||
if ($entryName === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_contains($entryName, '../') || str_contains($entryName, '..\\')
|
||||
|| str_starts_with($entryName, '/') || str_starts_with($entryName, '\\')) {
|
||||
$zip->close();
|
||||
throw new \RuntimeException('Archive contains unsafe path: ' . $entryName);
|
||||
}
|
||||
}
|
||||
|
||||
if (!$zip->extractTo($stagingDir)) {
|
||||
$zip->close();
|
||||
|
||||
throw new \RuntimeException(
|
||||
'Failed to extract archive. '
|
||||
. (!empty($password) ? 'Check that the decryption password is correct.' : 'The archive may be encrypted — provide a password.')
|
||||
);
|
||||
}
|
||||
|
||||
$session->log('Extracted ' . $zip->numFiles . ' entries');
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan the staging directory and return a flat list of relative file paths.
|
||||
*/
|
||||
private function scanStagingFiles(string $stagingDir): array
|
||||
{
|
||||
$files = [];
|
||||
$baseLen = strlen(rtrim($stagingDir, '/\\')) + 1;
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($stagingDir, \FilesystemIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
foreach ($iterator as $item) {
|
||||
if ($item->isFile()) {
|
||||
$relativePath = substr($item->getPathname(), $baseLen);
|
||||
// Normalise directory separators
|
||||
$relativePath = str_replace('\\', '/', $relativePath);
|
||||
$files[] = $relativePath;
|
||||
}
|
||||
}
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively delete a directory and all its contents.
|
||||
*/
|
||||
private function recursiveDelete(string $dir): void
|
||||
{
|
||||
if (!is_dir($dir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
|
||||
foreach ($items as $item) {
|
||||
if ($item->isDir()) {
|
||||
@rmdir($item->getPathname());
|
||||
} else {
|
||||
@unlink($item->getPathname());
|
||||
}
|
||||
}
|
||||
|
||||
@rmdir($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save restore-specific state to a JSON file alongside the session.
|
||||
*/
|
||||
private function saveRestoreState(string $sessionId, array $state): void
|
||||
{
|
||||
$path = $this->getRestoreStatePath($sessionId);
|
||||
|
||||
if (file_put_contents($path, json_encode($state, JSON_PRETTY_PRINT)) === false) {
|
||||
throw new \RuntimeException('Cannot save restore state: ' . $path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load restore-specific state from disk.
|
||||
*/
|
||||
private function loadRestoreState(string $sessionId): ?array
|
||||
{
|
||||
$path = $this->getRestoreStatePath($sessionId);
|
||||
|
||||
if (!is_file($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = json_decode(file_get_contents($path), true);
|
||||
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete restore state file.
|
||||
*/
|
||||
private function destroyRestoreState(string $sessionId): void
|
||||
{
|
||||
$path = $this->getRestoreStatePath($sessionId);
|
||||
|
||||
if (is_file($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file path for restore-specific state.
|
||||
*/
|
||||
private function getRestoreStatePath(string $sessionId): string
|
||||
{
|
||||
$safe = preg_replace('/[^a-zA-Z0-9_-]/', '', $sessionId);
|
||||
$dir = JPATH_ROOT . '/tmp/mokosuitebackup-sessions';
|
||||
|
||||
if (!is_dir($dir)) {
|
||||
if (!mkdir($dir, 0755, true)) {
|
||||
throw new \RuntimeException('Cannot create session directory: ' . $dir);
|
||||
}
|
||||
}
|
||||
|
||||
return $dir . '/' . $safe . '.restore.json';
|
||||
}
|
||||
}
|
||||
@@ -51,10 +51,16 @@ class SteppedSession
|
||||
public array $excludeFiles = [];
|
||||
public array $excludeTables = [];
|
||||
public string $remoteStorage = 'none';
|
||||
public bool $includeMokoRestore = false;
|
||||
public string $includeMokoRestore = '0';
|
||||
public string $restoreScriptName = 'restore.php';
|
||||
public string $restoreScriptPath = '';
|
||||
public bool $remoteKeepLocal = true;
|
||||
public string $encryptionPassword = '';
|
||||
|
||||
// Multi-remote destinations (loaded from #__mokosuitebackup_remotes)
|
||||
public array $remoteDestinations = [];
|
||||
public int $remoteIndex = 0;
|
||||
|
||||
// Progress
|
||||
public int $totalSteps = 0;
|
||||
public int $currentStep = 0;
|
||||
|
||||
@@ -47,12 +47,14 @@ class TarGzArchiver implements ArchiverInterface
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
// Compress the .tar to .tar.gz
|
||||
$this->tar->compress(\Phar::GZ);
|
||||
|
||||
// Remove the uncompressed .tar
|
||||
if (is_file($this->tarPath)) {
|
||||
@unlink($this->tarPath);
|
||||
try {
|
||||
// Compress the .tar to .tar.gz
|
||||
$this->tar->compress(\Phar::GZ);
|
||||
} finally {
|
||||
// Always remove the uncompressed .tar, even if compress() fails
|
||||
if (is_file($this->tarPath)) {
|
||||
@unlink($this->tarPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,30 @@ class FolderPickerField extends FormField
|
||||
}
|
||||
|
||||
// Build placeholder map for JS resolution
|
||||
$hostname = preg_replace('/[^a-zA-Z0-9._-]/', '', $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? php_uname('n'));
|
||||
/* Resolve hostname: prefer HTTP_HOST, then Joomla live_site config, then system hostname */
|
||||
$rawHost = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '';
|
||||
|
||||
if (empty($rawHost) || $rawHost === 'localhost') {
|
||||
try {
|
||||
$liveSite = Factory::getApplication()->get('live_site', '');
|
||||
|
||||
if (!empty($liveSite)) {
|
||||
$parsed = parse_url($liveSite, PHP_URL_HOST);
|
||||
|
||||
if (!empty($parsed)) {
|
||||
$rawHost = $parsed;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
/* fallback */
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($rawHost)) {
|
||||
$rawHost = php_uname('n');
|
||||
}
|
||||
|
||||
$hostname = preg_replace('/[^a-zA-Z0-9._-]/', '', $rawHost);
|
||||
$siteName = '';
|
||||
|
||||
try {
|
||||
@@ -52,15 +75,15 @@ class FolderPickerField extends FormField
|
||||
$placeholders = [
|
||||
'[DEFAULT_DIR]' => BackupDirectory::getDefaultAbsolute(),
|
||||
'[HOME]' => BackupDirectory::getHomeDirectory(),
|
||||
'[host]' => $hostname,
|
||||
'[site_name]' => $sanitizedSiteName ?: 'joomla',
|
||||
'[profile_id]' => '1',
|
||||
'[profile_name]' => 'default',
|
||||
'[type]' => 'full',
|
||||
'[year]' => date('Y'),
|
||||
'[month]' => date('m'),
|
||||
'[day]' => date('d'),
|
||||
'[date]' => date('Ymd'),
|
||||
'[HOST]' => $hostname,
|
||||
'[SITE_NAME]' => $sanitizedSiteName ?: 'joomla',
|
||||
'[PROFILE_ID]' => '1',
|
||||
'[PROFILE_NAME]' => 'default',
|
||||
'[TYPE]' => 'full',
|
||||
'[YEAR]' => date('Y'),
|
||||
'[MONTH]' => date('m'),
|
||||
'[DAY]' => date('d'),
|
||||
'[DATE]' => date('Ymd'),
|
||||
];
|
||||
|
||||
$placeholdersJson = json_encode($placeholders);
|
||||
@@ -96,51 +119,140 @@ class FolderPickerField extends FormField
|
||||
<span class="icon-folder-open" aria-hidden="true"></span>
|
||||
Browse
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-info" data-bs-toggle="modal" data-bs-target="#{$id}_helpModal" title="Available placeholders">
|
||||
<button type="button" class="btn btn-outline-info" id="{$id}_helpBtn" title="Help — placeholders, paths, and examples">
|
||||
<span class="icon-question-circle" aria-hidden="true"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-1 mb-1" id="{$id}_placeholders" style="display:flex; flex-wrap:wrap; gap:4px;">
|
||||
<span class="text-muted small me-1" style="line-height:24px;">Insert:</span>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[HOME]" title="Home directory">[HOME]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[DEFAULT_DIR]" title="Default backup dir">[DEFAULT_DIR]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[HOST]" title="Server hostname">[HOST]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[SITE_NAME]" title="Joomla site name">[SITE_NAME]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[DATE]" title="Date (Ymd)">[DATE]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[PROFILE_ID]" title="Profile ID">[PROFILE_ID]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[PROFILE_NAME]" title="Profile name">[PROFILE_NAME]</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert" data-field="{$id}" data-ph="[TYPE]" title="Backup type">[TYPE]</button>
|
||||
</div>
|
||||
<div class="mt-1" id="{$id}_status">
|
||||
<small class="{$statusClass}">
|
||||
<span class="{$statusIcon}" aria-hidden="true"></span>
|
||||
{$statusDetail}
|
||||
</small>
|
||||
</div>
|
||||
<div class="mt-1" id="{$id}_resolved" style="font-size:0.8rem; line-height:1.6;">
|
||||
</div>
|
||||
<div id="{$id}_defaultwarn" class="alert alert-warning alert-sm mt-1 py-1 px-2" style="display:none; font-size:0.85rem;">
|
||||
<span class="icon-warning-circle" aria-hidden="true"></span>
|
||||
The default backup directory is inside the web root. Backup archives may be directly downloadable if <code>.htaccess</code> is not supported. For better security, use a path outside the web root.
|
||||
</div>
|
||||
<div class="modal fade" id="{$id}_helpModal" tabindex="-1" aria-labelledby="{$id}_helpLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="{$id}_helpLabel">Backup Directory Placeholders</h5>
|
||||
<h5 class="modal-title" id="{$id}_helpLabel">Backup Directory — Help</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Use these placeholders in the backup directory path. They are resolved at backup time.</p>
|
||||
|
||||
<h6 class="text-primary">How Path Resolution Works</h6>
|
||||
<p>The backup directory path is resolved at backup time. You can use <strong>absolute paths</strong>, <strong>relative paths</strong>, or <strong>placeholder paths</strong>.</p>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header fw-bold">Absolute Paths</div>
|
||||
<div class="card-body py-2">
|
||||
<p class="mb-1">Start with <code>/</code> (Linux) or a drive letter (Windows). Used as-is.</p>
|
||||
<ul class="mb-0">
|
||||
<li><code>/home/user/backups</code> — Fixed path on the server</li>
|
||||
<li><code>/var/backups/joomla</code> — System backup directory</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header fw-bold">Relative Paths</div>
|
||||
<div class="card-body py-2">
|
||||
<p class="mb-1">Paths that do <strong>not</strong> start with <code>/</code> are resolved relative to the Joomla root directory, using the same conventions as URL paths:</p>
|
||||
<table class="table table-sm mb-2">
|
||||
<thead><tr><th>Path</th><th>Meaning</th><th>Resolves To</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>backups</code></td><td>Subdirectory of Joomla root</td><td><code>{$jRoot}/backups</code></td></tr>
|
||||
<tr><td><code>./backups</code></td><td>Same as above (explicit current dir)</td><td><code>{$jRoot}/backups</code></td></tr>
|
||||
<tr><td><code>../backups</code></td><td>One level <strong>above</strong> Joomla root</td><td>Parent of <code>{$jRoot}</code></td></tr>
|
||||
<tr><td><code>../../backups</code></td><td>Two levels above Joomla root</td><td>Grandparent of <code>{$jRoot}</code></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="alert alert-warning py-1 px-2 mb-0" style="font-size:0.85rem;">
|
||||
<strong>Warning:</strong> Relative paths that stay inside the web root may expose backup files to direct download if .htaccess is not supported. Use <code>../</code> or <code>[HOME]</code> to store backups outside the web root.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header fw-bold">Placeholder Paths (Recommended)</div>
|
||||
<div class="card-body py-2">
|
||||
<p class="mb-1">Use <code>[PLACEHOLDER]</code> tokens that are replaced with actual values at backup time. This makes paths <strong>portable</strong> across servers.</p>
|
||||
<ul class="mb-0">
|
||||
<li><code>[HOME]/backups</code> — User's home directory + /backups</li>
|
||||
<li><code>[HOME]/[HOST]/backups</code> — Per-site subdirectory under home</li>
|
||||
<li><code>[DEFAULT_DIR]</code> — Joomla's default backup directory</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h6 class="text-primary mt-3">Available Placeholders</h6>
|
||||
<table class="table table-sm table-striped">
|
||||
<thead><tr><th>Placeholder</th><th>Description</th><th>Example</th></tr></thead>
|
||||
<thead><tr><th>Placeholder</th><th>Description</th><th>Current Value</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>[HOME]</code></td><td>Home directory of the server user</td><td><code>{$placeholders['[HOME]']}</code></td></tr>
|
||||
<tr><td><code>[DEFAULT_DIR]</code></td><td>Default backup directory (inside web root)</td><td><code>{$placeholders['[DEFAULT_DIR]']}</code></td></tr>
|
||||
<tr><td><code>[host]</code></td><td>Server hostname</td><td><code>{$placeholders['[host]']}</code></td></tr>
|
||||
<tr><td><code>[site_name]</code></td><td>Joomla site name</td><td><code>{$placeholders['[site_name]']}</code></td></tr>
|
||||
<tr><td><code>[date]</code></td><td>Date (Ymd)</td><td><code>{$placeholders['[date]']}</code></td></tr>
|
||||
<tr><td><code>[year]</code></td><td>Four-digit year</td><td><code>{$placeholders['[year]']}</code></td></tr>
|
||||
<tr><td><code>[month]</code></td><td>Two-digit month</td><td><code>{$placeholders['[month]']}</code></td></tr>
|
||||
<tr><td><code>[day]</code></td><td>Two-digit day</td><td><code>{$placeholders['[day]']}</code></td></tr>
|
||||
<tr><td><code>[profile_id]</code></td><td>Backup profile ID</td><td><code>1</code></td></tr>
|
||||
<tr><td><code>[profile_name]</code></td><td>Profile title</td><td><code>default</code></td></tr>
|
||||
<tr><td><code>[type]</code></td><td>Backup type</td><td><code>full</code></td></tr>
|
||||
<tr><td><code>[HOME]</code></td><td>Home directory of the PHP process owner. Detected from environment, POSIX, or JPATH_ROOT.</td><td><code>{$placeholders['[HOME]']}</code></td></tr>
|
||||
<tr><td><code>[DEFAULT_DIR]</code></td><td>Default backup directory inside the Joomla web root. Protected by .htaccess but not recommended for production.</td><td><code>{$placeholders['[DEFAULT_DIR]']}</code></td></tr>
|
||||
<tr><td><code>[HOST]</code></td><td>Server hostname from HTTP_HOST. Sanitized to alphanumeric, dots, and hyphens.</td><td><code>{$placeholders['[HOST]']}</code></td></tr>
|
||||
<tr><td><code>[SITE_NAME]</code></td><td>Joomla site name from Global Configuration. Spaces become hyphens, special characters stripped.</td><td><code>{$placeholders['[SITE_NAME]']}</code></td></tr>
|
||||
<tr><td><code>[DATE]</code></td><td>Current date in Ymd format (e.g. 20260623).</td><td><code>{$placeholders['[DATE]']}</code></td></tr>
|
||||
<tr><td><code>[YEAR]</code></td><td>Four-digit year.</td><td><code>{$placeholders['[YEAR]']}</code></td></tr>
|
||||
<tr><td><code>[MONTH]</code></td><td>Two-digit month (01-12).</td><td><code>{$placeholders['[MONTH]']}</code></td></tr>
|
||||
<tr><td><code>[DAY]</code></td><td>Two-digit day (01-31).</td><td><code>{$placeholders['[DAY]']}</code></td></tr>
|
||||
<tr><td><code>[PROFILE_ID]</code></td><td>Numeric ID of the backup profile being used.</td><td><code>1</code></td></tr>
|
||||
<tr><td><code>[PROFILE_NAME]</code></td><td>Title of the backup profile, sanitized for filesystem use.</td><td><code>default</code></td></tr>
|
||||
<tr><td><code>[TYPE]</code></td><td>Backup type: full, database, files, or differential.</td><td><code>full</code></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h6>Recommended Paths</h6>
|
||||
<ul class="list-unstyled">
|
||||
<li><code>[HOME]/backups</code> — Outside web root (recommended)</li>
|
||||
<li><code>[HOME]/backups/[host]</code> — Per-site subdirectory</li>
|
||||
<li><code>[DEFAULT_DIR]</code> — Inside web root (protected by .htaccess)</li>
|
||||
</ul>
|
||||
|
||||
<h6 class="text-primary mt-3">Recommended Configurations</h6>
|
||||
<table class="table table-sm">
|
||||
<thead><tr><th>Use Case</th><th>Path</th><th>Notes</th></tr></thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>Single site, secure</strong></td>
|
||||
<td><code>[HOME]/backups</code></td>
|
||||
<td>Outside web root. Best for most sites.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Multiple sites on one server</strong></td>
|
||||
<td><code>[HOME]/backups/[HOST]</code></td>
|
||||
<td>Each site gets its own subdirectory.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Date-organized</strong></td>
|
||||
<td><code>[HOME]/backups/[YEAR]/[MONTH]</code></td>
|
||||
<td>Backups sorted by year and month.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Per-profile</strong></td>
|
||||
<td><code>[HOME]/backups/[PROFILE_NAME]</code></td>
|
||||
<td>Separate directory for each backup profile.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Shared hosting (default)</strong></td>
|
||||
<td><code>[DEFAULT_DIR]</code></td>
|
||||
<td>Inside web root, protected by .htaccess. Use only if you cannot write outside web root.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="alert alert-info py-2 mt-3 mb-0">
|
||||
<strong>Tip:</strong> The directory is created automatically if it doesn't exist. Placeholders are resolved fresh each time a backup runs, so date-based paths create new directories over time.
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
@@ -155,6 +267,56 @@ class FolderPickerField extends FormField
|
||||
</div>
|
||||
<script>
|
||||
(function() {
|
||||
/* Clickable placeholder insertion at cursor position */
|
||||
document.querySelectorAll('.moko-ph-insert[data-field="{$id}"]').forEach(function(btn) {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
var target = document.getElementById(this.getAttribute('data-field'));
|
||||
var ph = this.getAttribute('data-ph');
|
||||
if (!target) return;
|
||||
var start = target.selectionStart || 0;
|
||||
var end = target.selectionEnd || 0;
|
||||
var val = target.value;
|
||||
target.value = val.substring(0, start) + ph + val.substring(end);
|
||||
/* Move cursor to after the inserted placeholder */
|
||||
var newPos = start + ph.length;
|
||||
target.setSelectionRange(newPos, newPos);
|
||||
target.focus();
|
||||
/* Trigger input event so status updates */
|
||||
target.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
});
|
||||
});
|
||||
|
||||
/* Help button — open modal with Bootstrap 5 or fallback */
|
||||
var helpBtn = document.getElementById('{$id}_helpBtn');
|
||||
var helpModal = document.getElementById('{$id}_helpModal');
|
||||
if (helpBtn && helpModal) {
|
||||
helpBtn.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
||||
var modal = bootstrap.Modal.getOrCreateInstance(helpModal);
|
||||
modal.show();
|
||||
} else {
|
||||
helpModal.classList.add('show');
|
||||
helpModal.style.display = 'block';
|
||||
helpModal.setAttribute('aria-hidden', 'false');
|
||||
document.body.classList.add('modal-open');
|
||||
var backdrop = document.createElement('div');
|
||||
backdrop.className = 'modal-backdrop fade show';
|
||||
backdrop.id = '{$id}_backdrop';
|
||||
document.body.appendChild(backdrop);
|
||||
helpModal.querySelector('.btn-close, [data-bs-dismiss]').addEventListener('click', function() {
|
||||
helpModal.classList.remove('show');
|
||||
helpModal.style.display = 'none';
|
||||
helpModal.setAttribute('aria-hidden', 'true');
|
||||
document.body.classList.remove('modal-open');
|
||||
var bd = document.getElementById('{$id}_backdrop');
|
||||
if (bd) bd.remove();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var fieldId = '{$id}';
|
||||
var btn = document.getElementById(fieldId + '_btn');
|
||||
var browser = document.getElementById(fieldId + '_browser');
|
||||
@@ -162,7 +324,7 @@ class FolderPickerField extends FormField
|
||||
var input = document.getElementById(fieldId);
|
||||
var placeholders = {$placeholdersJson};
|
||||
|
||||
// Resolve placeholders in a path (forward: [site_name] -> actual value)
|
||||
// Resolve placeholders in a path (forward: [SITE_NAME] -> actual value)
|
||||
function resolve(path) {
|
||||
for (var key in placeholders) {
|
||||
path = path.split(key).join(placeholders[key]);
|
||||
@@ -253,8 +415,54 @@ class FolderPickerField extends FormField
|
||||
});
|
||||
}
|
||||
|
||||
/* Show which placeholders are in use and their resolved values */
|
||||
var resolvedDiv = document.getElementById(fieldId + '_resolved');
|
||||
|
||||
function updateResolvedDisplay() {
|
||||
while (resolvedDiv.firstChild) resolvedDiv.removeChild(resolvedDiv.firstChild);
|
||||
var val = input.value || '';
|
||||
var found = false;
|
||||
|
||||
for (var key in placeholders) {
|
||||
if (val.indexOf(key) !== -1 && placeholders[key]) {
|
||||
found = true;
|
||||
var badge = document.createElement('span');
|
||||
badge.className = 'badge bg-light text-dark border me-1 mb-1';
|
||||
badge.style.fontSize = '0.75rem';
|
||||
badge.style.fontFamily = 'monospace';
|
||||
|
||||
var keySpan = document.createElement('strong');
|
||||
keySpan.textContent = key;
|
||||
badge.appendChild(keySpan);
|
||||
|
||||
badge.appendChild(document.createTextNode(' = '));
|
||||
|
||||
var valSpan = document.createElement('span');
|
||||
valSpan.className = 'text-primary';
|
||||
valSpan.textContent = placeholders[key];
|
||||
badge.appendChild(valSpan);
|
||||
|
||||
resolvedDiv.appendChild(badge);
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
var fullResolved = document.createElement('div');
|
||||
fullResolved.className = 'mt-1';
|
||||
var arrow = document.createElement('span');
|
||||
arrow.className = 'text-muted';
|
||||
arrow.textContent = 'EXAMPLE: ';
|
||||
fullResolved.appendChild(arrow);
|
||||
var code = document.createElement('code');
|
||||
code.textContent = resolve(val);
|
||||
fullResolved.appendChild(code);
|
||||
resolvedDiv.appendChild(fullResolved);
|
||||
}
|
||||
}
|
||||
|
||||
input.addEventListener('input', function() {
|
||||
clearTimeout(checkTimer);
|
||||
updateResolvedDisplay();
|
||||
checkTimer = setTimeout(checkDirPermissions, 400);
|
||||
});
|
||||
|
||||
@@ -368,6 +576,7 @@ class FolderPickerField extends FormField
|
||||
|
||||
// Run initial check on page load
|
||||
setDefaultDirWarning();
|
||||
updateResolvedDisplay();
|
||||
checkDirPermissions();
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<?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
|
||||
*
|
||||
* Text field with clickable placeholder pills that insert at cursor position.
|
||||
* Used for backup directory and archive name format fields.
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Administrator\Field;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Form\FormField;
|
||||
|
||||
class PlaceholderTextField extends FormField
|
||||
{
|
||||
protected $type = 'PlaceholderText';
|
||||
|
||||
protected function getInput(): string
|
||||
{
|
||||
$value = htmlspecialchars($this->value ?? $this->default ?? '', ENT_QUOTES, 'UTF-8');
|
||||
$id = htmlspecialchars($this->id, ENT_QUOTES, 'UTF-8');
|
||||
$name = htmlspecialchars($this->name, ENT_QUOTES, 'UTF-8');
|
||||
$hint = htmlspecialchars($this->element['hint'] ?? '', ENT_QUOTES, 'UTF-8');
|
||||
$max = (int) ($this->element['maxlength'] ?? 512);
|
||||
|
||||
$placeholderAttr = (string) ($this->element['placeholders'] ?? '');
|
||||
$placeholders = array_filter(array_map('trim', explode(',', $placeholderAttr)));
|
||||
|
||||
if (empty($placeholders)) {
|
||||
$placeholders = ['[HOST]', '[DATE]', '[DATETIME]', '[TIME]', '[YEAR]', '[MONTH]', '[DAY]',
|
||||
'[HOUR]', '[MINUTE]', '[SECOND]', '[PROFILE_ID]', '[PROFILE_NAME]', '[SITE_NAME]', '[TYPE]', '[RANDOM]'];
|
||||
}
|
||||
|
||||
$html = '<input type="text" name="' . $name . '" id="' . $id . '" value="' . $value . '"'
|
||||
. ' class="form-control" maxlength="' . $max . '"'
|
||||
. ($hint ? ' placeholder="' . $hint . '"' : '') . '>';
|
||||
|
||||
$html .= '<div class="mt-1" style="display:flex; flex-wrap:wrap; gap:4px;">';
|
||||
$html .= '<span class="text-muted small me-1" style="line-height:24px;">Insert:</span>';
|
||||
|
||||
foreach ($placeholders as $ph) {
|
||||
$html .= '<button type="button" class="btn btn-outline-secondary btn-sm py-0 px-1 moko-ph-insert"'
|
||||
. ' data-field="' . $id . '" data-ph="' . htmlspecialchars($ph) . '">'
|
||||
. htmlspecialchars($ph) . '</button>';
|
||||
}
|
||||
|
||||
$html .= '</div>';
|
||||
|
||||
$html .= <<<JS
|
||||
<script>
|
||||
document.querySelectorAll('.moko-ph-insert[data-field="{$id}"]').forEach(function(btn) {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
var target = document.getElementById(this.getAttribute('data-field'));
|
||||
var ph = this.getAttribute('data-ph');
|
||||
if (!target) return;
|
||||
var start = target.selectionStart || 0;
|
||||
var end = target.selectionEnd || 0;
|
||||
var val = target.value;
|
||||
target.value = val.substring(0, start) + ph + val.substring(end);
|
||||
var newPos = start + ph.length;
|
||||
target.setSelectionRange(newPos, newPos);
|
||||
target.focus();
|
||||
target.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
});
|
||||
});
|
||||
</script>
|
||||
JS;
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
*
|
||||
* SFTP remote path field with Browse Remote button and modal directory browser.
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Administrator\Field;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Form\FormField;
|
||||
|
||||
class SftpPathField extends FormField
|
||||
{
|
||||
protected $type = 'SftpPath';
|
||||
|
||||
protected function getInput(): string
|
||||
{
|
||||
$value = htmlspecialchars($this->value ?: $this->default, ENT_QUOTES, 'UTF-8');
|
||||
$id = htmlspecialchars($this->id, ENT_QUOTES, 'UTF-8');
|
||||
$name = htmlspecialchars($this->name, ENT_QUOTES, 'UTF-8');
|
||||
|
||||
return <<<HTML
|
||||
<div class="input-group">
|
||||
<input type="text" name="{$name}" id="{$id}" value="{$value}"
|
||||
class="form-control" maxlength="512"
|
||||
placeholder="/backups" />
|
||||
<button type="button" class="btn btn-outline-secondary" id="{$id}_browseBtn"
|
||||
title="Browse directories on the remote SFTP server">
|
||||
<span class="icon-folder-open" aria-hidden="true"></span>
|
||||
Browse Remote
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal fade" id="{$id}_sftpModal" tabindex="-1" aria-labelledby="{$id}_sftpModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="{$id}_sftpModalLabel">
|
||||
<span class="icon-folder-open" aria-hidden="true"></span>
|
||||
Browse Remote SFTP Directory
|
||||
</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="{$id}_sftpStatus" class="mb-2">
|
||||
<small class="text-muted">Click "Browse Remote" to connect...</small>
|
||||
</div>
|
||||
<div id="{$id}_sftpCurrent" class="mb-2 p-2 bg-light border rounded" style="font-family:monospace; font-size:0.85rem;">
|
||||
/
|
||||
</div>
|
||||
<div id="{$id}_sftpTree" class="border rounded" style="max-height:350px; overflow-y:auto;">
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<small class="text-muted">
|
||||
Click a directory to navigate into it. Click "Select This Directory" to use the current path.
|
||||
<br>SFTP credentials must be saved in the profile before browsing.
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="button" class="btn btn-primary" id="{$id}_sftpSelect">
|
||||
<span class="icon-checkmark" aria-hidden="true"></span>
|
||||
Select This Directory
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function() {
|
||||
var fieldId = '{$id}';
|
||||
var input = document.getElementById(fieldId);
|
||||
var browseBtn = document.getElementById(fieldId + '_browseBtn');
|
||||
var modalEl = document.getElementById(fieldId + '_sftpModal');
|
||||
var treeEl = document.getElementById(fieldId + '_sftpTree');
|
||||
var statusEl = document.getElementById(fieldId + '_sftpStatus');
|
||||
var currentEl = document.getElementById(fieldId + '_sftpCurrent');
|
||||
var selectBtn = document.getElementById(fieldId + '_sftpSelect');
|
||||
var currentPath = '/';
|
||||
|
||||
function getProfileId() {
|
||||
var el = document.getElementById('jform_id');
|
||||
return el ? parseInt(el.value, 10) || 0 : 0;
|
||||
}
|
||||
|
||||
function showModal() {
|
||||
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
||||
var modal = bootstrap.Modal.getOrCreateInstance(modalEl);
|
||||
modal.show();
|
||||
}
|
||||
}
|
||||
|
||||
function hideModal() {
|
||||
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
||||
var modal = bootstrap.Modal.getInstance(modalEl);
|
||||
if (modal) modal.hide();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the status message using safe DOM methods (no innerHTML).
|
||||
* @param {string} cssClass - CSS class for the small element
|
||||
* @param {string} iconClass - Icon CSS class (e.g. 'icon-spinner icon-spin'), or empty
|
||||
* @param {string} text - Plain text message
|
||||
*/
|
||||
function setStatus(cssClass, iconClass, text) {
|
||||
while (statusEl.firstChild) statusEl.removeChild(statusEl.firstChild);
|
||||
var small = document.createElement('small');
|
||||
small.className = cssClass;
|
||||
if (iconClass) {
|
||||
var icon = document.createElement('span');
|
||||
icon.className = iconClass;
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
small.appendChild(icon);
|
||||
small.appendChild(document.createTextNode(' '));
|
||||
}
|
||||
small.appendChild(document.createTextNode(text));
|
||||
statusEl.appendChild(small);
|
||||
}
|
||||
|
||||
function loadSftpDir(path) {
|
||||
currentPath = path;
|
||||
currentEl.textContent = path;
|
||||
while (treeEl.firstChild) treeEl.removeChild(treeEl.firstChild);
|
||||
setStatus('text-muted', 'icon-spinner icon-spin', 'Connecting to remote server...');
|
||||
|
||||
var profileId = getProfileId();
|
||||
if (!profileId) {
|
||||
setStatus('text-danger', '', 'Please save the profile first so SFTP credentials are available.');
|
||||
return;
|
||||
}
|
||||
|
||||
var form = new URLSearchParams();
|
||||
form.append('task', 'ajax.browseSftpDir');
|
||||
form.append('profile_id', profileId);
|
||||
form.append('path', path);
|
||||
|
||||
var tokenName = Joomla.getOptions('csrf.token') || '';
|
||||
if (tokenName) form.append(tokenName, '1');
|
||||
|
||||
fetch('index.php?option=com_mokosuitebackup&format=json', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' }
|
||||
})
|
||||
.then(function(r) {
|
||||
if (!r.ok) throw new Error('Server error (HTTP ' + r.status + ')');
|
||||
return r.json();
|
||||
})
|
||||
.then(function(data) {
|
||||
if (data.error) {
|
||||
setStatus('text-danger', 'icon-warning', data.message || 'Error');
|
||||
return;
|
||||
}
|
||||
var count = data.dirs ? data.dirs.length : 0;
|
||||
setStatus('text-success', 'icon-publish', 'Connected \u2014 ' + count + ' subdirectories');
|
||||
currentPath = data.current || path;
|
||||
currentEl.textContent = currentPath;
|
||||
renderSftpTree(data);
|
||||
})
|
||||
.catch(function(err) {
|
||||
setStatus('text-danger', 'icon-warning', err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function renderSftpTree(data) {
|
||||
while (treeEl.firstChild) treeEl.removeChild(treeEl.firstChild);
|
||||
var list = document.createElement('div');
|
||||
list.className = 'list-group list-group-flush';
|
||||
|
||||
/* Parent / back button */
|
||||
if (data.parent !== null && data.parent !== undefined) {
|
||||
var up = document.createElement('a');
|
||||
up.href = '#';
|
||||
up.className = 'list-group-item list-group-item-action py-1';
|
||||
var upIcon = document.createElement('span');
|
||||
upIcon.className = 'icon-arrow-up-4';
|
||||
upIcon.setAttribute('aria-hidden', 'true');
|
||||
up.appendChild(upIcon);
|
||||
up.appendChild(document.createTextNode(' .. (parent directory)'));
|
||||
up.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
loadSftpDir(data.parent);
|
||||
});
|
||||
list.appendChild(up);
|
||||
}
|
||||
|
||||
/* Directory entries */
|
||||
var dirs = data.dirs || [];
|
||||
|
||||
dirs.forEach(function(dir) {
|
||||
var item = document.createElement('a');
|
||||
item.href = '#';
|
||||
item.className = 'list-group-item list-group-item-action py-1';
|
||||
var folderIcon = document.createElement('span');
|
||||
folderIcon.className = 'icon-folder';
|
||||
folderIcon.setAttribute('aria-hidden', 'true');
|
||||
item.appendChild(folderIcon);
|
||||
item.appendChild(document.createTextNode(' ' + dir.name));
|
||||
|
||||
item.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
loadSftpDir(dir.path);
|
||||
});
|
||||
|
||||
/* Double-click to select and close */
|
||||
item.addEventListener('dblclick', function(e) {
|
||||
e.preventDefault();
|
||||
input.value = dir.path;
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
hideModal();
|
||||
});
|
||||
|
||||
list.appendChild(item);
|
||||
});
|
||||
|
||||
if (dirs.length === 0) {
|
||||
var empty = document.createElement('div');
|
||||
empty.className = 'list-group-item text-muted py-2';
|
||||
empty.textContent = '(no subdirectories)';
|
||||
list.appendChild(empty);
|
||||
}
|
||||
|
||||
treeEl.appendChild(list);
|
||||
}
|
||||
|
||||
/* Browse button click */
|
||||
browseBtn.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
var startPath = input.value.trim() || '/';
|
||||
showModal();
|
||||
loadSftpDir(startPath);
|
||||
});
|
||||
|
||||
/* Select button — use the current directory */
|
||||
selectBtn.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
input.value = currentPath;
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
hideModal();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
HTML;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<?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
|
||||
*
|
||||
* Custom field for SSH private key input.
|
||||
* Supports both file upload (via FileReader JS) and paste-in textarea.
|
||||
* The key content is stored in the database, not as a file on disk.
|
||||
*/
|
||||
|
||||
namespace Joomla\Component\MokoSuiteBackup\Administrator\Field;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Form\FormField;
|
||||
use Joomla\CMS\Language\Text;
|
||||
|
||||
class SshKeyField extends FormField
|
||||
{
|
||||
protected $type = 'SshKey';
|
||||
|
||||
protected function getInput(): string
|
||||
{
|
||||
$value = $this->value ?? '';
|
||||
$id = $this->id;
|
||||
$name = $this->name;
|
||||
|
||||
$decoded = !empty($value) ? (base64_decode($value, true) ?: '') : '';
|
||||
$hasKey = !empty($value) && ($value === '__KEEP_EXISTING__'
|
||||
|| str_contains($value, 'PRIVATE KEY')
|
||||
|| str_contains($decoded, 'PRIVATE KEY'));
|
||||
|
||||
$html = '<div id="' . htmlspecialchars($id) . '-wrapper">';
|
||||
|
||||
/* Status badge */
|
||||
if ($hasKey) {
|
||||
$html .= '<span class="badge bg-success me-2">'
|
||||
. '<span class="icon-lock" aria-hidden="true"></span> '
|
||||
. Text::_('COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_LOADED')
|
||||
. '</span>';
|
||||
}
|
||||
|
||||
/* File upload button */
|
||||
$html .= '<label class="btn btn-outline-secondary btn-sm" for="' . htmlspecialchars($id) . '-file">';
|
||||
$html .= '<span class="icon-upload" aria-hidden="true"></span> ';
|
||||
$html .= $hasKey ? Text::_('COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_REPLACE') : Text::_('COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_UPLOAD');
|
||||
$html .= '</label>';
|
||||
$html .= '<input type="file" id="' . htmlspecialchars($id) . '-file"'
|
||||
. ' accept=".pem,.key,.openssh,.ppk,*" style="display:none;"'
|
||||
. ' onchange="mokoSshKeyFileSelected(\'' . htmlspecialchars($id) . '\', this)">';
|
||||
|
||||
$html .= '<span id="' . htmlspecialchars($id) . '-status" class="ms-2 text-muted small"></span>';
|
||||
|
||||
if ($hasKey) {
|
||||
$html .= ' <button type="button" class="btn btn-sm btn-outline-danger ms-2"'
|
||||
. ' onclick="mokoSshKeyClear(\'' . htmlspecialchars($id) . '\')">'
|
||||
. '<span class="icon-times" aria-hidden="true"></span> '
|
||||
. Text::_('COM_MOKOJOOMBACKUP_FIELD_SFTP_KEY_CLEAR')
|
||||
. '</button>';
|
||||
}
|
||||
|
||||
/* Hidden field — key data is NEVER rendered as visible text.
|
||||
On existing keys, we submit a sentinel value to preserve the DB value
|
||||
unless a new file is uploaded or clear is clicked. */
|
||||
if ($hasKey) {
|
||||
$html .= '<input type="hidden" name="' . htmlspecialchars($name) . '" id="' . htmlspecialchars($id) . '"'
|
||||
. ' value="__KEEP_EXISTING__">';
|
||||
} else {
|
||||
$html .= '<input type="hidden" name="' . htmlspecialchars($name) . '" id="' . htmlspecialchars($id) . '"'
|
||||
. ' value="">';
|
||||
}
|
||||
|
||||
$html .= '</div>';
|
||||
$html .= $this->getScript();
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
private function getScript(): string
|
||||
{
|
||||
return <<<'JS'
|
||||
<script>
|
||||
function mokoSshKeyFileSelected(fieldId, input) {
|
||||
if (!input.files || !input.files[0]) return;
|
||||
var file = input.files[0];
|
||||
var reader = new FileReader();
|
||||
reader.onload = function(e) {
|
||||
/* Base64 encode the key before storing in the hidden field */
|
||||
var content = e.target.result;
|
||||
var encoded = btoa(content);
|
||||
document.getElementById(fieldId).value = encoded;
|
||||
var status = document.getElementById(fieldId + '-status');
|
||||
if (status) status.textContent = file.name + ' uploaded';
|
||||
};
|
||||
reader.readAsText(file);
|
||||
}
|
||||
|
||||
function mokoSshKeyClear(fieldId) {
|
||||
document.getElementById(fieldId).value = '';
|
||||
var status = document.getElementById(fieldId + '-status');
|
||||
if (status) status.textContent = 'Key removed';
|
||||
var fileInput = document.getElementById(fieldId + '-file');
|
||||
if (fileInput) fileInput.value = '';
|
||||
}
|
||||
</script>
|
||||
JS;
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ class BackupModel extends AdminModel
|
||||
$data = $this->getItem();
|
||||
}
|
||||
|
||||
return $data;
|
||||
return is_array($data) ? (object) $data : $data;
|
||||
}
|
||||
|
||||
public function getTable($name = 'Backup', $prefix = 'Administrator', $options = [])
|
||||
|
||||
@@ -61,6 +61,13 @@ class BackupsModel extends ListModel
|
||||
$query->where($db->quoteName('a.profile_id') . ' = ' . (int) $profileId);
|
||||
}
|
||||
|
||||
// Filter by backup type
|
||||
$backupType = $this->getState('filter.backup_type');
|
||||
|
||||
if (!empty($backupType)) {
|
||||
$query->where($db->quoteName('a.backup_type') . ' = ' . $db->quote($backupType));
|
||||
}
|
||||
|
||||
// Filter by search
|
||||
$search = $this->getState('filter.search');
|
||||
|
||||
|
||||
@@ -198,6 +198,90 @@ class DashboardModel extends BaseDatabaseModel
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest snapshot info for the dashboard widget.
|
||||
*/
|
||||
public function getLatestSnapshot(): ?object
|
||||
{
|
||||
$db = $this->getDatabase();
|
||||
|
||||
try {
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'))
|
||||
->where($db->quoteName('status') . ' = ' . $db->quote('complete'))
|
||||
->order($db->quoteName('created') . ' DESC');
|
||||
$db->setQuery($query, 0, 1);
|
||||
|
||||
return $db->loadObject() ?: null;
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get snapshot count.
|
||||
*/
|
||||
public function getSnapshotCount(): int
|
||||
{
|
||||
$db = $this->getDatabase();
|
||||
|
||||
try {
|
||||
$query = $db->getQuery(true)
|
||||
->select('COUNT(*)')
|
||||
->from($db->quoteName('#__mokosuitebackup_snapshots'));
|
||||
$db->setQuery($query);
|
||||
|
||||
return (int) $db->loadResult();
|
||||
} catch (\Throwable $e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get backup size trend data for the last 30 days.
|
||||
* Returns array of {date, total_size, count, status} grouped by day.
|
||||
*/
|
||||
public function getBackupTrend(): array
|
||||
{
|
||||
$db = $this->getDatabase();
|
||||
$cutoff = date('Y-m-d', strtotime('-30 days'));
|
||||
|
||||
$query = $db->getQuery(true)
|
||||
->select('DATE(' . $db->quoteName('backupstart') . ') AS backup_date')
|
||||
->select('SUM(' . $db->quoteName('total_size') . ') AS day_size')
|
||||
->select('COUNT(*) AS day_count')
|
||||
->select('SUM(CASE WHEN ' . $db->quoteName('status') . ' = ' . $db->quote('fail') . ' THEN 1 ELSE 0 END) AS fail_count')
|
||||
->from($db->quoteName('#__mokosuitebackup_records'))
|
||||
->where('DATE(' . $db->quoteName('backupstart') . ') >= ' . $db->quote($cutoff))
|
||||
->group('DATE(' . $db->quoteName('backupstart') . ')')
|
||||
->order('backup_date ASC');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadObjectList() ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get storage breakdown by profile.
|
||||
*/
|
||||
public function getStorageByProfile(): array
|
||||
{
|
||||
$db = $this->getDatabase();
|
||||
|
||||
$query = $db->getQuery(true)
|
||||
->select('p.title AS profile_title')
|
||||
->select('COUNT(*) AS backup_count')
|
||||
->select('COALESCE(SUM(r.total_size), 0) AS total_size')
|
||||
->from($db->quoteName('#__mokosuitebackup_records', 'r'))
|
||||
->join('LEFT', $db->quoteName('#__mokosuitebackup_profiles', 'p') . ' ON p.id = r.profile_id')
|
||||
->where($db->quoteName('r.status') . ' = ' . $db->quote('complete'))
|
||||
->group($db->quoteName('r.profile_id'))
|
||||
->order('total_size DESC');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadObjectList() ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get published backup profiles for the quick-action selector.
|
||||
*
|
||||
@@ -210,7 +294,7 @@ class DashboardModel extends BaseDatabaseModel
|
||||
->select($db->quoteName(['id', 'title', 'backup_type']))
|
||||
->from($db->quoteName('#__mokosuitebackup_profiles'))
|
||||
->where($db->quoteName('published') . ' = 1')
|
||||
->order($db->quoteName('ordering') . ' ASC');
|
||||
->order($db->quoteName('id') . ' ASC');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadObjectList() ?: [];
|
||||
|
||||
@@ -36,7 +36,7 @@ class ProfileModel extends AdminModel
|
||||
$data = $this->getItem();
|
||||
}
|
||||
|
||||
return $data;
|
||||
return is_array($data) ? (object) $data : $data;
|
||||
}
|
||||
|
||||
public function getTable($name = 'Profile', $prefix = 'Administrator', $options = [])
|
||||
|
||||
@@ -25,7 +25,6 @@ class ProfilesModel extends ListModel
|
||||
'title', 'a.title',
|
||||
'backup_type', 'a.backup_type',
|
||||
'published', 'a.published',
|
||||
'ordering', 'a.ordering',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -40,6 +39,13 @@ class ProfilesModel extends ListModel
|
||||
$query->select('a.*')
|
||||
->from($db->quoteName('#__mokosuitebackup_profiles', 'a'));
|
||||
|
||||
// Subquery: count of backup records per profile
|
||||
$subQuery = $db->getQuery(true)
|
||||
->select('COUNT(*)')
|
||||
->from($db->quoteName('#__mokosuitebackup_records', 'r'))
|
||||
->where($db->quoteName('r.profile_id') . ' = ' . $db->quoteName('a.id'));
|
||||
$query->select('(' . $subQuery . ') AS ' . $db->quoteName('backup_count'));
|
||||
|
||||
$published = $this->getState('filter.published');
|
||||
|
||||
if (is_numeric($published)) {
|
||||
@@ -53,14 +59,14 @@ class ProfilesModel extends ListModel
|
||||
$query->where('(' . $db->quoteName('a.title') . ' LIKE ' . $search . ')');
|
||||
}
|
||||
|
||||
$orderCol = $this->state->get('list.ordering', 'a.ordering');
|
||||
$orderCol = $this->state->get('list.ordering', 'a.id');
|
||||
$orderDir = $this->state->get('list.direction', 'ASC');
|
||||
$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDir));
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
protected function populateState($ordering = 'a.ordering', $direction = 'ASC'): void
|
||||
protected function populateState($ordering = 'a.id', $direction = 'ASC'): void
|
||||
{
|
||||
parent::populateState($ordering, $direction);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?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\Model;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\Factory;
|
||||
use Joomla\CMS\MVC\Model\AdminModel;
|
||||
|
||||
class RemoteModel extends AdminModel
|
||||
{
|
||||
public function getForm($data = [], $loadData = true)
|
||||
{
|
||||
$form = $this->loadForm(
|
||||
'com_mokosuitebackup.remote',
|
||||
'remote',
|
||||
['control' => 'jform', 'load_data' => $loadData]
|
||||
);
|
||||
|
||||
return $form ?: false;
|
||||
}
|
||||
|
||||
protected function loadFormData(): object
|
||||
{
|
||||
$data = Factory::getApplication()->getUserState('com_mokosuitebackup.edit.remote.data', []);
|
||||
|
||||
if (empty($data)) {
|
||||
$data = $this->getItem();
|
||||
}
|
||||
|
||||
return is_array($data) ? (object) $data : $data;
|
||||
}
|
||||
|
||||
public function getTable($name = 'Remote', $prefix = 'Administrator', $options = [])
|
||||
{
|
||||
return parent::getTable($name, $prefix, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all enabled remotes for a given profile.
|
||||
*
|
||||
* @param int $profileId The profile ID
|
||||
*
|
||||
* @return array Array of remote objects
|
||||
*/
|
||||
public function getEnabledByProfile(int $profileId): array
|
||||
{
|
||||
$db = $this->getDatabase();
|
||||
$query = $db->getQuery(true)
|
||||
->select('*')
|
||||
->from($db->quoteName('#__mokosuitebackup_remotes'))
|
||||
->where($db->quoteName('profile_id') . ' = ' . (int) $profileId)
|
||||
->where($db->quoteName('enabled') . ' = 1')
|
||||
->order($db->quoteName('ordering') . ' ASC');
|
||||
$db->setQuery($query);
|
||||
|
||||
return $db->loadObjectList() ?: [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?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\Model;
|
||||
|
||||
defined('_JEXEC') or die;
|
||||
|
||||
use Joomla\CMS\MVC\Model\ListModel;
|
||||
use Joomla\Database\QueryInterface;
|
||||
|
||||
class RemotesModel extends ListModel
|
||||
{
|
||||
public function __construct($config = [])
|
||||
{
|
||||
if (empty($config['filter_fields'])) {
|
||||
$config['filter_fields'] = [
|
||||
'id', 'a.id',
|
||||
'profile_id', 'a.profile_id',
|
||||
'title', 'a.title',
|
||||
'type', 'a.type',
|
||||
'enabled', 'a.enabled',
|
||||
'ordering', 'a.ordering',
|
||||
];
|
||||
}
|
||||
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
protected function getListQuery(): QueryInterface
|
||||
{
|
||||
$db = $this->getDatabase();
|
||||
$query = $db->getQuery(true);
|
||||
|
||||
$query->select('a.*')
|
||||
->from($db->quoteName('#__mokosuitebackup_remotes', 'a'));
|
||||
|
||||
// Join profile title
|
||||
$query->select($db->quoteName('p.title', 'profile_title'))
|
||||
->join('LEFT', $db->quoteName('#__mokosuitebackup_profiles', 'p') . ' ON p.id = a.profile_id');
|
||||
|
||||
// Filter by profile
|
||||
$profileId = $this->getState('filter.profile_id');
|
||||
|
||||
if (is_numeric($profileId)) {
|
||||
$query->where($db->quoteName('a.profile_id') . ' = ' . (int) $profileId);
|
||||
}
|
||||
|
||||
// Filter by type
|
||||
$type = $this->getState('filter.type');
|
||||
|
||||
if (!empty($type)) {
|
||||
$query->where($db->quoteName('a.type') . ' = ' . $db->quote($type));
|
||||
}
|
||||
|
||||
// Filter by enabled
|
||||
$enabled = $this->getState('filter.enabled');
|
||||
|
||||
if (is_numeric($enabled)) {
|
||||
$query->where($db->quoteName('a.enabled') . ' = ' . (int) $enabled);
|
||||
}
|
||||
|
||||
// Filter by search
|
||||
$search = $this->getState('filter.search');
|
||||
|
||||
if (!empty($search)) {
|
||||
$search = $db->quote('%' . $db->escape(trim($search), true) . '%');
|
||||
$query->where('(' . $db->quoteName('a.title') . ' LIKE ' . $search . ')');
|
||||
}
|
||||
|
||||
$orderCol = $this->state->get('list.ordering', 'a.ordering');
|
||||
$orderDir = $this->state->get('list.direction', 'ASC');
|
||||
$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDir));
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
protected function populateState($ordering = 'a.ordering', $direction = 'ASC'): void
|
||||
{
|
||||
parent::populateState($ordering, $direction);
|
||||
}
|
||||
}
|
||||
@@ -39,11 +39,22 @@ class BackupTable extends Table
|
||||
|
||||
public function delete($pk = null): bool
|
||||
{
|
||||
// Delete the archive file if it exists
|
||||
if (!empty($this->absolute_path) && is_file($this->absolute_path)) {
|
||||
@unlink($this->absolute_path);
|
||||
$archivePath = $this->absolute_path;
|
||||
|
||||
// Delete DB record first — if this fails, the file is preserved
|
||||
$result = parent::delete($pk);
|
||||
|
||||
if ($result && !empty($archivePath) && is_file($archivePath)) {
|
||||
@unlink($archivePath);
|
||||
|
||||
// Also remove the log file if it exists alongside the archive
|
||||
$logPath = preg_replace('/\.(zip|tar\.gz)$/i', '.log', $archivePath);
|
||||
|
||||
if (is_file($logPath)) {
|
||||
@unlink($logPath);
|
||||
}
|
||||
}
|
||||
|
||||
return parent::delete($pk);
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,23 @@ class ProfileTable extends Table
|
||||
|
||||
public function store($updateNulls = true): bool
|
||||
{
|
||||
/* Handle SSH key sentinel — when __KEEP_EXISTING__ is submitted,
|
||||
preserve the current DB value instead of overwriting with the sentinel.
|
||||
This prevents the key from being exposed in the form HTML. */
|
||||
if (isset($this->sftp_key_data) && $this->sftp_key_data === '__KEEP_EXISTING__') {
|
||||
if ($this->id) {
|
||||
$db = $this->getDbo();
|
||||
$query = $db->getQuery(true)
|
||||
->select($db->quoteName('sftp_key_data'))
|
||||
->from($db->quoteName($this->_tbl))
|
||||
->where($db->quoteName('id') . ' = ' . (int) $this->id);
|
||||
$db->setQuery($query);
|
||||
$this->sftp_key_data = $db->loadResult() ?: '';
|
||||
} else {
|
||||
$this->sftp_key_data = '';
|
||||
}
|
||||
}
|
||||
|
||||
$result = parent::store($updateNulls);
|
||||
|
||||
if ($result && !empty($this->backup_dir)) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user