Files
MokoCLI/deploy/deploy-joomla.php
T
Jonathan Miller b491241a58
Universal: Sync Feature Branch Versions / Sync feature branches with dev (push) Has been skipped
Merge branch 'main' into dev
# Conflicts:
#	.mokogitea/CLAUDE.md
#	.mokogitea/ISSUE_TEMPLATE/config.yml
#	.mokogitea/ISSUE_TEMPLATE/documentation.md
#	.mokogitea/ISSUE_TEMPLATE/feature_request.md
#	.mokogitea/ISSUE_TEMPLATE/security.md
#	.mokogitea/branch-protection.yml
#	.mokogitea/bulk-repo-sync.yml
#	.mokogitea/pr-branch-check.yml
#	.mokogitea/renovate.yml
#	.mokogitea/sync-wikis.yml
#	.mokogitea/workflows/auto-bump.yml
#	.mokogitea/workflows/auto-release.yml
#	.mokogitea/workflows/ci-platform.yml
#	.mokogitea/workflows/cleanup.yml
#	.mokogitea/workflows/gitleaks.yml
#	.mokogitea/workflows/issue-branch.yml
#	.mokogitea/workflows/notify.yml
#	.mokogitea/workflows/pre-release.yml
#	.mokogitea/workflows/repo-health.yml
#	.mokogitea/workflows/security-audit.yml
#	.script-registry.json
#	CHANGELOG.md
#	PLUGIN_SCRIPTS.md
#	README.md
#	analysis/index.md
#	automation/bulk_joomla_template.php
#	automation/bulk_sync.php
#	automation/enrich_manifest_xml.php
#	automation/enrich_mokostandards_xml.php
#	automation/index.md
#	automation/migrate_to_gitea.php
#	automation/push_files.php
#	automation/push_manifest_xml.php
#	automation/push_mokostandards_xml.php
#	automation/repo_cleanup.php
#	bin/moko
#	cli/archive_repo.php
#	cli/audit_query.php
#	cli/badge_update.php
#	cli/branch_rename.php
#	cli/bulk_workflow_push.php
#	cli/bulk_workflow_trigger.php
#	cli/changelog_promote.php
#	cli/changelog_prune.php
#	cli/client_dashboard.php
#	cli/client_health_check.php
#	cli/client_inventory.php
#	cli/client_provision.php
#	cli/completion.php
#	cli/create_project.php
#	cli/create_repo.php
#	cli/deploy_joomla.php
#	cli/dev_branch_reset.php
#	cli/grafana_dashboard.php
#	cli/joomla_build.php
#	cli/joomla_compat_check.php
#	cli/joomla_metadata_validate.php
#	cli/joomla_release.php
#	cli/license_manage.php
#	cli/manifest_element.php
#	cli/manifest_licensing.php
#	cli/manifest_read.php
#	cli/package_build.php
#	cli/platform_detect.php
#	cli/release.php
#	cli/release_body_update.php
#	cli/release_cascade.php
#	cli/release_create.php
#	cli/release_manage.php
#	cli/release_mirror.php
#	cli/release_notes.php
#	cli/release_package.php
#	cli/release_promote.php
#	cli/release_publish.php
#	cli/release_validate.php
#	cli/release_verify.php
#	cli/scaffold_client.php
#	cli/sync_rulesets.php
#	cli/theme_lint.php
#	cli/updates_xml_build.php
#	cli/updates_xml_sync.php
#	cli/version_auto_bump.php
#	cli/version_bump.php
#	cli/version_bump_remote.php
#	cli/version_check.php
#	cli/version_read.php
#	cli/version_reset_dev.php
#	cli/version_set_platform.php
#	cli/wiki_sync.php
#	cli/workflow_sync.php
#	composer.json
#	deploy/backup-before-deploy.php
#	deploy/deploy-dolibarr.php
#	deploy/deploy-joomla.php
#	deploy/deploy-sftp.php
#	deploy/health-check.php
#	deploy/rollback-joomla.php
#	deploy/sync-joomla.php
#	fix/fix_line_endings.php
#	fix/fix_permissions.php
#	fix/fix_tabs.php
#	fix/fix_trailing_spaces.php
#	fix/index.md
#	index.md
#	lib/CliBase.php
#	lib/Common.php
#	lib/Enterprise/AbstractProjectPlugin.php
#	lib/Enterprise/ApiClient.php
#	lib/Enterprise/AuditLogger.php
#	lib/Enterprise/CheckpointManager.php
#	lib/Enterprise/CliFramework.php
#	lib/Enterprise/Config.php
#	lib/Enterprise/ConfigValidator.php
#	lib/Enterprise/EnterpriseReadinessValidator.php
#	lib/Enterprise/ErrorRecovery.php
#	lib/Enterprise/FileFixUtility.php
#	lib/Enterprise/GitHubAdapter.php
#	lib/Enterprise/GitPlatformAdapter.php
#	lib/Enterprise/InputValidator.php
#	lib/Enterprise/ManifestParser.php
#	lib/Enterprise/ManifestReader.php
#	lib/Enterprise/MetricsCollector.php
#	lib/Enterprise/MokoGiteaAdapter.php
#	lib/Enterprise/PackageBuilder.php
#	lib/Enterprise/PlatformAdapterFactory.php
#	lib/Enterprise/PluginFactory.php
#	lib/Enterprise/PluginRegistry.php
#	lib/Enterprise/Plugins/ApiPlugin.php
#	lib/Enterprise/Plugins/DocumentationPlugin.php
#	lib/Enterprise/Plugins/DolibarrPlugin.php
#	lib/Enterprise/Plugins/GenericPlugin.php
#	lib/Enterprise/Plugins/JoomlaPlugin.php
#	lib/Enterprise/Plugins/McpServerPlugin.php
#	lib/Enterprise/Plugins/MobilePlugin.php
#	lib/Enterprise/Plugins/NodeJsPlugin.php
#	lib/Enterprise/Plugins/PythonPlugin.php
#	lib/Enterprise/Plugins/TerraformPlugin.php
#	lib/Enterprise/Plugins/WordPressPlugin.php
#	lib/Enterprise/ProjectConfigValidator.php
#	lib/Enterprise/ProjectMetricsCollector.php
#	lib/Enterprise/ProjectPluginInterface.php
#	lib/Enterprise/ProjectTypeDetector.php
#	lib/Enterprise/RecoveryError.php
#	lib/Enterprise/RecoveryManager.php
#	lib/Enterprise/RepositoryHealthChecker.php
#	lib/Enterprise/RepositorySynchronizer.php
#	lib/Enterprise/RetryHelper.php
#	lib/Enterprise/SecurityValidator.php
#	lib/Enterprise/SourceResolver.php
#	lib/Enterprise/SynchronizationException.php
#	lib/Enterprise/TransactionManager.php
#	lib/Enterprise/UnifiedValidation.php
#	lib/index.md
#	lib/plugins/Joomla/UpdateXmlGenerator.php
#	maintenance/index.md
#	maintenance/pin_action_shas.php
#	maintenance/repo_inventory.php
#	maintenance/rotate_secrets.php
#	maintenance/setup_labels.php
#	maintenance/sync_dolibarr_readmes.php
#	maintenance/update_repo_inventory.php
#	maintenance/update_sha_hashes.php
#	maintenance/update_version_from_readme.php
#	mcp/config.example.json
#	mcp/package.json
#	mcp/src/config.ts
#	mcp/src/index.ts
#	mcp/src/runner.ts
#	mcp/src/types.ts
#	phpcs.xml
#	plugin_health_check.php
#	plugin_list.php
#	plugin_metrics.php
#	plugin_readiness.php
#	plugin_validate.php
#	release/generate_dolibarr_version_txt.php
#	release/generate_joomla_update_xml.php
#	src/functions.php
#	templates/configs/README.md
#	templates/configs/index.md
#	templates/configs/manifest.xml.template
#	templates/configs/manifest.yml.template
#	templates/configs/mokostandards.xml.template
#	templates/configs/mokostandards.yml.template
#	templates/configs/phpcs.xml
#	templates/docs/README.md
#	templates/docs/extra/README.md
#	templates/docs/extra/index.md
#	templates/docs/index.md
#	templates/docs/required/GOVERNANCE.md
#	templates/docs/required/README.md
#	templates/docs/required/index.md
#	templates/docs/required/template-CONTRIBUTING.md
#	templates/docs/required/template-README.md
#	templates/docs/required/template-SECURITY.md
#	templates/index.md
#	templates/licenses/README.md
#	templates/licenses/index.md
#	templates/makefiles/README.md
#	templates/mokogitea/CLAUDE.dolibarr.md.template
#	templates/mokogitea/CLAUDE.joomla.md.template
#	templates/mokogitea/CLAUDE.md.template
#	templates/mokogitea/ISSUE_TEMPLATE/config.yml
#	templates/mokogitea/ISSUE_TEMPLATE/documentation.md
#	templates/mokogitea/ISSUE_TEMPLATE/dolibarr_module_id_request.md
#	templates/mokogitea/ISSUE_TEMPLATE/feature_request.md
#	templates/mokogitea/ISSUE_TEMPLATE/security.md
#	templates/mokogitea/README.md
#	templates/mokogitea/copilot-instructions.dolibarr.md.template
#	templates/mokogitea/copilot-instructions.joomla.md.template
#	templates/mokogitea/copilot-instructions.md.template
#	templates/mokogitea/dependabot.yml.template
#	templates/mokogitea/override.tf.template
#	templates/required/README.md
#	templates/schemas/README.md
#	templates/schemas/manifest-schema.xsd
#	templates/schemas/moko-platform-schema.xsd
#	templates/schemas/mokostandards-schema.xsd
#	templates/schemas/schemas/README.md
#	templates/schemas/template-repository-structure.xml
#	templates/scripts/README.md
#	templates/scripts/common/CliBase.template.php
#	templates/scripts/fix/index.md
#	templates/scripts/index.md
#	templates/scripts/release/index.md
#	templates/scripts/release/package_dolibarr.php
#	templates/scripts/release/package_joomla.php
#	templates/scripts/sftp-config/README.md
#	templates/scripts/validate/dolibarr_module.php
#	templates/scripts/validate/index.md
#	templates/scripts/validate/validate_manifest.php
#	templates/scripts/validate/validate_structure.php
#	templates/security/README.md
#	templates/security/index.php
#	templates/stubs/dolibarr.php
#	templates/stubs/joomla.php
#	templates/web/index.php
#	tests/Enterprise/GitPlatformAdapterTest.php
#	tests/Unit/VersionBumpTest.php
#	tests/Unit/VersionReadTest.php
#	tests/index.md
#	tests/test_circuit_breaker_handling.php
#	tests/test_enterprise_libraries.php
#	validate/SECURITY_SCANNING.md
#	validate/auto_detect_platform.php
#	validate/check_changelog.php
#	validate/check_client_theme.php
#	validate/check_composer_deps.php
#	validate/check_dolibarr_module.php
#	validate/check_enterprise_readiness.php
#	validate/check_file_integrity.php
#	validate/check_joomla_manifest.php
#	validate/check_language_structure.php
#	validate/check_license_headers.php
#	validate/check_no_secrets.php
#	validate/check_paths.php
#	validate/check_php_syntax.php
#	validate/check_repo_health.php
#	validate/check_structure.php
#	validate/check_tabs.php
#	validate/check_version_consistency.php
#	validate/check_wiki_health.php
#	validate/check_xml_wellformed.php
#	validate/index.md
#	validate/scan_drift.php
#	wrappers/auto_detect_platform.php
#	wrappers/bulk_sync.php
#	wrappers/check_changelog.php
#	wrappers/check_dolibarr_module.php
#	wrappers/check_enterprise_readiness.php
#	wrappers/check_joomla_manifest.php
#	wrappers/check_language_structure.php
#	wrappers/check_license_headers.php
#	wrappers/check_no_secrets.php
#	wrappers/check_paths.php
#	wrappers/check_php_syntax.php
#	wrappers/check_repo_health.php
#	wrappers/check_structure.php
#	wrappers/check_tabs.php
#	wrappers/check_version_consistency.php
#	wrappers/check_xml_wellformed.php
#	wrappers/deploy_sftp.php
#	wrappers/fix_line_endings.php
#	wrappers/fix_permissions.php
#	wrappers/fix_tabs.php
#	wrappers/fix_trailing_spaces.php
#	wrappers/gen_wrappers.php
#	wrappers/index.md
#	wrappers/pin_action_shas.php
#	wrappers/plugin_health_check.php
#	wrappers/plugin_list.php
#	wrappers/plugin_metrics.php
#	wrappers/plugin_readiness.php
#	wrappers/plugin_validate.php
#	wrappers/scan_drift.php
#	wrappers/setup_labels.php
#	wrappers/sync_dolibarr_readmes.php
#	wrappers/update_sha_hashes.php
#	wrappers/update_version_from_readme.php
2026-06-20 21:43:38 -05:00

575 lines
21 KiB
PHP

#!/usr/bin/env php
<?php
/* 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
*
* FILE INFORMATION
<<<<<<< HEAD
* DEFGROUP: MokoCLI.Scripts.Deploy
* INGROUP: MokoCLI
* REPO: https://git.mokoconsulting.tech/MokoConsulting/mokocli
=======
* DEFGROUP: MokoPlatform.Scripts.Deploy
* INGROUP: MokoPlatform
* REPO: https://git.mokoconsulting.tech/MokoConsulting/mokoplatform
>>>>>>> main
* PATH: /deploy/deploy-joomla.php
* BRIEF: Smart Joomla deploy — routes files to correct Joomla directories based on XML manifest
*
* Parses the extension's XML manifest to determine type (component, module,
* plugin, template, library, package) and deploys each section directly to
* its correct location on the Joomla server. No reinstall needed for code
* changes — only XML manifest changes require a Joomla reinstall.
*
* USAGE
* php deploy/deploy-joomla.php --path . --config /tmp/sftp-config.json
* php deploy/deploy-joomla.php --path . --config /tmp/sftp-config.json --dry-run
* php deploy/deploy-joomla.php --path . --env dev
*/
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
use MokoCli\CliFramework;
use phpseclib3\Net\SFTP;
use phpseclib3\Crypt\PublicKeyLoader;
/**
* Joomla-aware SFTP deployment.
*
* Reads the extension XML manifest to determine:
* - Extension type (component, module, plugin, template, library)
* - Element name (com_xxx, mod_xxx, plg_group_name, tpl_xxx)
* - Client (site or administrator)
* - Plugin group (system, content, etc.)
*
* Then maps src/ subdirectories to their correct Joomla server paths:
*
* Component:
* src/admin/ -> administrator/components/{element}/
* src/site/ -> components/{element}/
* src/media/ -> media/{element}/
* src/api/ -> api/components/{element}/
*
* Module:
* src/ -> modules/{element}/ (site) or administrator/modules/{element}/ (admin)
* src/media/ -> media/{element}/
*
* Plugin:
* src/ -> plugins/{group}/{name}/
* src/media/ -> media/{element}/
*
* Template:
* src/ -> templates/{name}/ (site) or administrator/templates/{name}/ (admin)
* src/media/ -> media/templates/site/{name}/ or media/templates/administrator/{name}/
*
* Library:
* src/ -> libraries/{name}/
* src/media/ -> media/{element}/
*/
class DeployJoomlaCli extends CliFramework
{
private string $repoPath = '.';
private string $srcDir = 'src';
private array $config = [];
private int $uploaded = 0;
private int $unchanged = 0;
private int $skipped = 0;
private int $deleted = 0;
private array $ignorePatterns = [];
protected function configure(): void
{
$this->setDescription('Smart Joomla deploy — routes files to correct Joomla directories based on XML manifest');
$this->addArgument('--path', 'Repository root path', '.');
$this->addArgument('--src-dir', 'Source directory relative to path', 'src');
$this->addArgument('--config', 'Path to sftp-config.json', '');
$this->addArgument('--key-passphrase', 'SSH key passphrase', '');
}
protected function run(): int
{
$this->repoPath = $this->getArgument('--path');
$this->srcDir = $this->getArgument('--src-dir');
$configPath = $this->getArgument('--config');
$keyPassphrase = $this->getArgument('--key-passphrase');
if ($keyPassphrase !== '') {
$this->config['key_passphrase'] = $keyPassphrase;
}
$this->repoPath = realpath($this->repoPath) ?: $this->repoPath;
// Resolve src dir
if (!str_starts_with($this->srcDir, '/')) {
$this->srcDir = "{$this->repoPath}/{$this->srcDir}";
}
// Try htdocs/ as fallback
if (!is_dir($this->srcDir) && is_dir("{$this->repoPath}/htdocs")) {
$this->srcDir = "{$this->repoPath}/htdocs";
}
// Load config
if ($configPath !== '' && file_exists($configPath)) {
$json = file_get_contents($configPath);
$json = preg_replace('#^\s*//.*$#m', '', $json);
$json = preg_replace('#,\s*([\]}])#', '$1', $json);
$parsed = json_decode($json, true);
if (is_array($parsed)) {
$this->config = array_merge($this->config, $parsed);
}
}
$manifest = $this->findManifest();
if ($manifest === null) {
$this->log('ERROR', "No Joomla XML manifest found in {$this->srcDir}");
return 1;
}
$ext = $this->parseManifest($manifest);
if ($ext === null) {
$this->log('ERROR', "Failed to parse manifest: {$manifest}");
return 1;
}
$this->log('INFO', "Extension: {$ext['type']} / {$ext['element']} (client: {$ext['client']})");
$deployMap = $this->buildDeployMap($ext);
if (empty($deployMap)) {
$this->log('ERROR', "No deploy mappings for extension type: {$ext['type']}");
return 1;
}
$this->log('INFO', "Deploy mappings:");
foreach ($deployMap as $map) {
$this->log('INFO', " {$map['local']} -> {$map['remote']}");
}
// Load ignore patterns
$this->ignorePatterns = $this->loadFtpIgnore();
// Check if manifest changed (warn user about reinstall)
$this->checkManifestChange($ext, $manifest);
if ($this->dryRun) {
$this->log('INFO', "[DRY RUN] Would deploy " . count($deployMap) . " mappings");
foreach ($deployMap as $map) {
if (is_dir($map['local'])) {
$count = iterator_count(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($map['local'], \FilesystemIterator::SKIP_DOTS)
)
);
$this->log('INFO', " {$map['local']} ({$count} files) -> {$map['remote']}");
}
}
return 0;
}
// Connect
$sftp = $this->connectSftp();
if ($sftp === null) {
return 1;
}
// Deploy each mapping
$errors = 0;
foreach ($deployMap as $map) {
if (!is_dir($map['local'])) {
if ($this->verbose) {
$this->log('INFO', " SKIP: {$map['local']} (directory not found)");
}
continue;
}
// Ensure remote directory exists
$stat = @$sftp->stat($map['remote']);
if ($stat === false) {
$this->log('INFO', " MKDIR: {$map['remote']}");
$sftp->mkdir($map['remote'], -1, true);
}
$result = $this->uploadDirectory($sftp, $map['local'], $map['remote']);
if ($result !== 0) {
$errors++;
}
}
// Also deploy the manifest file itself to the admin component directory
if ($ext['type'] === 'component' && file_exists($manifest)) {
$adminRemote = $this->getRemotePath($ext, 'admin');
$manifestName = basename($manifest);
$remoteDest = "{$adminRemote}/{$manifestName}";
$this->uploadFile($sftp, $manifest, $remoteDest);
$this->log('INFO', " Manifest: {$manifestName} -> {$remoteDest}");
}
$this->log('INFO', "Done. Uploaded: {$this->uploaded}, Unchanged: {$this->unchanged}, Skipped: {$this->skipped}");
return $errors > 0 ? 1 : 0;
}
/**
* Find the Joomla XML manifest file.
*/
private function findManifest(): ?string
{
$searchDirs = [$this->srcDir, $this->repoPath];
foreach ($searchDirs as $dir) {
$iterator = new \DirectoryIterator($dir);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'xml') {
$content = file_get_contents($file->getPathname());
if ($content !== false && str_contains($content, '<extension')) {
return $file->getPathname();
}
}
}
// Also check one level deep
foreach (new \DirectoryIterator($dir) as $subdir) {
if ($subdir->isDir() && !$subdir->isDot()) {
foreach (new \DirectoryIterator($subdir->getPathname()) as $file) {
if ($file->isFile() && $file->getExtension() === 'xml') {
$content = file_get_contents($file->getPathname());
if ($content !== false && str_contains($content, '<extension')) {
return $file->getPathname();
}
}
}
}
}
}
return null;
}
/**
* Parse extension metadata from the XML manifest.
*
* @return array{type: string, element: string, client: string, group: string, name: string}|null
*/
private function parseManifest(string $path): ?array
{
$xml = @simplexml_load_file($path);
if ($xml === false || $xml->getName() !== 'extension') {
return null;
}
$type = (string) ($xml['type'] ?? 'component');
$client = (string) ($xml['client'] ?? 'site');
$group = (string) ($xml['group'] ?? '');
$element = (string) ($xml->element ?? '');
$name = (string) ($xml->name ?? '');
// Derive element from type + name if not explicit
if (empty($element)) {
$cleanName = strtolower(preg_replace('/[^a-zA-Z0-9_]/', '', $name));
$element = match ($type) {
'component' => "com_{$cleanName}",
'module' => "mod_{$cleanName}",
'plugin' => "plg_{$group}_{$cleanName}",
'template' => "tpl_{$cleanName}",
'library' => "lib_{$cleanName}",
default => $cleanName,
};
}
// For plugins, derive the short name (without plg_group_ prefix)
$shortName = $element;
if ($type === 'plugin' && preg_match('/^plg_\w+_(.+)$/', $element, $m)) {
$shortName = $m[1];
} elseif ($type === 'template' && preg_match('/^tpl_(.+)$/', $element, $m)) {
$shortName = $m[1];
}
return [
'type' => $type,
'element' => $element,
'client' => $client,
'group' => $group,
'name' => $name,
'shortName' => $shortName,
];
}
/**
* Build the local->remote deploy mapping based on extension type.
*
* @return array<int, array{local: string, remote: string}>
*/
private function buildDeployMap(array $ext): array
{
$remotePath = rtrim((string) $this->config['remote_path'], '/');
$src = $this->srcDir;
$map = [];
switch ($ext['type']) {
case 'component':
// Admin files
if (is_dir("{$src}/admin") || is_dir("{$src}/administrator")) {
$adminLocal = is_dir("{$src}/admin") ? "{$src}/admin" : "{$src}/administrator";
$map[] = ['local' => $adminLocal, 'remote' => "{$remotePath}/administrator/components/{$ext['element']}"];
}
// Site files
if (is_dir("{$src}/site")) {
$map[] = ['local' => "{$src}/site", 'remote' => "{$remotePath}/components/{$ext['element']}"];
}
// Media files
if (is_dir("{$src}/media")) {
$map[] = ['local' => "{$src}/media", 'remote' => "{$remotePath}/media/{$ext['element']}"];
}
// API files (Joomla 4+)
if (is_dir("{$src}/api")) {
$map[] = ['local' => "{$src}/api", 'remote' => "{$remotePath}/api/components/{$ext['element']}"];
}
// Language files (admin)
if (is_dir("{$src}/language/admin") || is_dir("{$src}/admin/language")) {
$langDir = is_dir("{$src}/language/admin") ? "{$src}/language/admin" : "{$src}/admin/language";
$map[] = ['local' => $langDir, 'remote' => "{$remotePath}/administrator/language"];
}
// Language files (site)
if (is_dir("{$src}/language/site") || is_dir("{$src}/site/language")) {
$langDir = is_dir("{$src}/language/site") ? "{$src}/language/site" : "{$src}/site/language";
$map[] = ['local' => $langDir, 'remote' => "{$remotePath}/language"];
}
break;
case 'module':
$base = $ext['client'] === 'administrator'
? "{$remotePath}/administrator/modules/{$ext['element']}"
: "{$remotePath}/modules/{$ext['element']}";
$map[] = ['local' => $src, 'remote' => $base];
if (is_dir("{$src}/media")) {
$map[] = ['local' => "{$src}/media", 'remote' => "{$remotePath}/media/{$ext['element']}"];
}
break;
case 'plugin':
$map[] = ['local' => $src, 'remote' => "{$remotePath}/plugins/{$ext['group']}/{$ext['shortName']}"];
if (is_dir("{$src}/media")) {
$map[] = ['local' => "{$src}/media", 'remote' => "{$remotePath}/media/{$ext['element']}"];
}
break;
case 'template':
$clientDir = $ext['client'] === 'administrator' ? 'administrator/' : '';
$map[] = ['local' => $src, 'remote' => "{$remotePath}/{$clientDir}templates/{$ext['shortName']}"];
if (is_dir("{$src}/media")) {
$mediaClient = $ext['client'] === 'administrator' ? 'administrator' : 'site';
$map[] = ['local' => "{$src}/media", 'remote' => "{$remotePath}/media/templates/{$mediaClient}/{$ext['shortName']}"];
}
break;
case 'library':
$map[] = ['local' => $src, 'remote' => "{$remotePath}/libraries/{$ext['shortName']}"];
if (is_dir("{$src}/media")) {
$map[] = ['local' => "{$src}/media", 'remote' => "{$remotePath}/media/{$ext['element']}"];
}
break;
case 'package':
// Packages deploy their sub-extensions individually
// For now, deploy to administrator/manifests/packages/
$map[] = ['local' => $src, 'remote' => "{$remotePath}/administrator/manifests/packages"];
break;
}
return $map;
}
/**
* Get the remote path for a specific section of the extension.
*/
private function getRemotePath(array $ext, string $section): string
{
$remotePath = rtrim((string) $this->config['remote_path'], '/');
return match ($section) {
'admin' => "{$remotePath}/administrator/components/{$ext['element']}",
'site' => "{$remotePath}/components/{$ext['element']}",
'media' => "{$remotePath}/media/{$ext['element']}",
default => $remotePath,
};
}
/**
* Check if the XML manifest has changed and warn about reinstall.
*/
private function checkManifestChange(array $ext, string $manifestPath): void
{
$manifestName = basename($manifestPath);
$this->log('INFO', '');
$this->log('INFO', "NOTE: If {$manifestName} has changed (new fields, permissions, menu items,");
$this->log('INFO', ' database schema), you must reinstall the extension through Joomla.');
$this->log('INFO', ' Code changes (PHP, JS, CSS, language) do NOT require reinstall.');
$this->log('INFO', '');
}
/**
* Upload a directory recursively to the remote server.
*/
private function uploadDirectory(SFTP $sftp, string $localDir, string $remoteDir): int
{
$errors = 0;
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($localDir, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
$relativePath = substr($item->getPathname(), strlen($localDir) + 1);
$relativePath = str_replace('\\', '/', $relativePath);
$remotePath = "{$remoteDir}/{$relativePath}";
// Check ignore patterns
if ($this->shouldIgnore($relativePath)) {
$this->skipped++;
continue;
}
if ($item->isDir()) {
$stat = @$sftp->stat($remotePath);
if ($stat === false) {
$sftp->mkdir($remotePath, -1, true);
}
} else {
$result = $this->uploadFile($sftp, $item->getPathname(), $remotePath);
if (!$result) {
$errors++;
}
}
}
return $errors;
}
/**
* Upload a single file with smart diff (skip if unchanged).
*/
private function uploadFile(SFTP $sftp, string $localPath, string $remotePath): bool
{
$localSize = filesize($localPath);
$remoteStat = @$sftp->stat($remotePath);
// Smart diff: skip if same size and hash
if ($remoteStat !== false && ($remoteStat['size'] ?? -1) === $localSize) {
$remoteContent = @$sftp->get($remotePath);
if ($remoteContent !== false && md5($remoteContent) === md5_file($localPath)) {
$this->unchanged++;
return true;
}
}
// Ensure parent directory exists
$parentDir = dirname($remotePath);
$parentStat = @$sftp->stat($parentDir);
if ($parentStat === false) {
$sftp->mkdir($parentDir, -1, true);
}
$result = $sftp->put($remotePath, $localPath, SFTP::SOURCE_LOCAL_FILE);
if ($result) {
$this->uploaded++;
if ($this->verbose) {
$this->log('INFO', " UPLOAD: {$remotePath}");
}
} else {
$this->log('ERROR', " FAIL: {$remotePath}");
}
return $result;
}
/**
* Check if a relative path should be ignored.
*/
private function shouldIgnore(string $relativePath): bool
{
foreach ($this->ignorePatterns as $pattern) {
if (preg_match($pattern, $relativePath)) {
return true;
}
}
// Always skip dotfiles and common non-deploy files
$basename = basename($relativePath);
if (str_starts_with($basename, '.') && $basename !== '.htaccess') {
return true;
}
return false;
}
/**
* Load .ftpignore patterns.
*
* @return string[] Regex patterns
*/
private function loadFtpIgnore(): array
{
$patterns = [];
foreach ([$this->srcDir, $this->repoPath] as $dir) {
$file = "{$dir}/.ftpignore";
if (!file_exists($file)) {
continue;
}
foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '#')) {
continue;
}
// Convert glob to regex
$regex = str_replace(['.', '*', '?'], ['\\.', '.*', '.'], $line);
$patterns[] = "#^{$regex}(/|$)#i";
}
}
return $patterns;
}
/**
* Connect to the SFTP server.
*/
private function connectSftp(): ?SFTP
{
$host = (string) $this->config['host'];
$port = (int) ($this->config['port'] ?? 22);
$user = (string) $this->config['user'];
$this->log('INFO', "Connecting to {$user}@{$host}:{$port}...");
$sftp = new SFTP($host, $port, 30);
// Try key auth first
if (!empty($this->config['ssh_key_file'])) {
$keyPath = $this->config['ssh_key_file'];
if (!file_exists($keyPath)) {
$keyPath = "{$this->repoPath}/scripts/keys/{$keyPath}";
}
if (file_exists($keyPath)) {
$passphrase = $this->config['key_passphrase'] ?? '';
$key = PublicKeyLoader::load(file_get_contents($keyPath), $passphrase);
if ($sftp->login($user, $key)) {
$this->log('INFO', 'Connected via SSH key');
return $sftp;
}
$this->warning('Key auth failed');
}
}
// Fallback to password
if (!empty($this->config['password'])) {
if ($sftp->login($user, $this->config['password'])) {
$this->log('INFO', 'Connected via password');
return $sftp;
}
}
$this->log('ERROR', 'Authentication failed');
return null;
}
}
$app = new DeployJoomlaCli();
exit($app->execute());