ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): existing-site import (.sql) and clone-to-new-independent-site
Juan Denis1f3ff4fcaf91
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex c4e5d92e..0b3de9f8 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -44,6 +44,49 @@ def create_site():return jsonify(result), 400+@wordpress_bp.route('/sites/import', methods=['POST'])+@jwt_required()+def import_site():+ """Import an existing WordPress site from an uploaded SQL dump (multipart)."""+ import os+ import tempfile+ name = request.form.get('name')+ admin_email = request.form.get('adminEmail', '')+ old_url = request.form.get('oldUrl', '').strip()+ if not name:+ return jsonify({'error': 'Site name is required'}), 400+ if not old_url:+ return jsonify({'error': 'Original site URL (old_url) is required for search-replace'}), 400+ if 'sql' not in request.files:+ return jsonify({'error': 'A .sql or .sql.gz database dump is required'}), 400+ sql_file = request.files['sql']+ if not sql_file.filename:+ return jsonify({'error': 'No SQL file selected'}), 400+ fname = sql_file.filename.lower()+ if not (fname.endswith('.sql') or fname.endswith('.sql.gz') or fname.endswith('.gz')):+ return jsonify({'error': 'Dump must be a .sql or .sql.gz file'}), 400++ suffix = '.sql.gz' if fname.endswith('.gz') else '.sql'+ fd, tmp_path = tempfile.mkstemp(suffix=suffix, prefix='wp_import_')+ os.close(fd)+ try:+ sql_file.save(tmp_path)+ current_user_id = get_jwt_identity()+ result = WordPressService.import_site(+ name=name,+ admin_email=admin_email,+ user_id=current_user_id,+ sql_path=tmp_path,+ old_url=old_url,+ )+ finally:+ try:+ os.remove(tmp_path)+ except OSError:+ pass+ return (jsonify(result), 201) if result.get('success') else (jsonify(result), 400)++@wordpress_bp.route('/sites/<int:site_id>', methods=['GET'])@jwt_required()def get_site(site_id):@@ -54,6 +97,22 @@ def get_site(site_id):return jsonify(result), 200+@wordpress_bp.route('/sites/<int:site_id>/clone', methods=['POST'])+@jwt_required()+def clone_site(site_id):+ """Clone a site into a new INDEPENDENT top-level site with fresh admin creds."""+ data = request.get_json() or {}+ new_name = data.get('name')+ if not new_name:+ return jsonify({'error': 'New site name is required'}), 400++ current_user_id = get_jwt_identity()+ result = WordPressService.clone_site(site_id, new_name, current_user_id)+ if result.get('success'):+ return jsonify(result), 201+ return jsonify(result), 400++@wordpress_bp.route('/sites/<int:site_id>/tags', methods=['PATCH'])@jwt_required()def set_site_tags(site_id):diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex df57d180..acaca23f 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -773,6 +773,49 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]alphabet = string.ascii_letters + string.digits + '!@#$%^&*'return ''.join(secrets.choice(alphabet) for _ in range(length))+ @staticmethod+ def _read_env_value(root_path: str, key: str) -> Optional[str]:+ """Read a single KEY from a Docker stack's <root>/.env (None if absent)."""+ env_path = os.path.join(root_path, '.env')+ if not os.path.exists(env_path):+ return None+ try:+ with open(env_path, 'r') as f:+ for line in f:+ line = line.strip()+ if line.startswith(f'{key}='):+ return line.split('=', 1)[1]+ except Exception:+ pass+ return None++ @classmethod+ def _copy_wp_content_between_containers(cls, source_container: str, target_container: str) -> Dict:+ """Best-effort copy of /var/www/html/wp-content from source to target+ WordPress container using `docker cp` via a host tmp dir. Never raises.+ """+ import tempfile+ try:+ tmp = tempfile.mkdtemp(prefix='wpclone_')+ staged = os.path.join(tmp, 'wp-content')+ cp_out = subprocess.run(+ ['docker', 'cp', f'{source_container}:/var/www/html/wp-content', staged],+ capture_output=True, text=True, timeout=600,+ )+ if cp_out.returncode != 0:+ shutil.rmtree(tmp, ignore_errors=True)+ return {'success': False, 'error': cp_out.stderr}+ cp_in = subprocess.run(+ ['docker', 'cp', f'{staged}/.', f'{target_container}:/var/www/html/wp-content'],+ capture_output=True, text=True, timeout=600,+ )+ shutil.rmtree(tmp, ignore_errors=True)+ if cp_in.returncode != 0:+ return {'success': False, 'error': cp_in.stderr}+ return {'success': True}+ except Exception as e:+ return {'success': False, 'error': str(e)}+# ========================================# WORDPRESS STANDALONE (DOCKER) MANAGEMENT# ========================================@@ -1080,6 +1123,76 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]return {'site': site_data}+ @classmethod+ def import_site(cls, name: str, admin_email: str, user_id: int, sql_path: str,+ old_url: str, wp_content_zip_path: str = None) -> Dict:+ """Import an existing WordPress site from a SQL dump into a fresh Docker stack.++ Stands up a normal blank stack via create_site (reusing the full Docker+ provisioning + Application/WordPressSite rows), then OVERWRITES its DB+ with the uploaded dump and rewrites the site URL to the new localhost+ port. ``sql_path`` is a host-side temp file owned by the caller.+ """+ from app import db+ from app.models import WordPressSite+ from app.services.db_sync_service import DatabaseSyncService++ # 1) Stand up a fresh stack (reuses all Docker provisioning + rows).+ result = cls.create_site(name, admin_email, user_id)+ if not result.get('success'):+ return result+ http_port = result.get('http_port')+ wp_site = WordPressSite.query.get(result['site']['id'])+ root_path = wp_site.application.root_path+ compose_file = os.path.join(root_path, 'docker-compose.yml')++ try:+ # 2) Overwrite the fresh DB with the user's dump. Root user, since a+ # real dump issues DROP/CREATE on the wordpress DB.+ db_password = cls._read_env_value(root_path, 'DB_PASSWORD')+ imp = DatabaseSyncService.import_to_container(+ compose_path=compose_file,+ snapshot_path=sql_path,+ db_name='wordpress',+ db_user='root',+ db_password=db_password,+ )+ if not imp.get('success'):+ return {'success': False,+ 'error': 'Database import failed: ' + (imp.get('error') or ''),+ 'site': wp_site.to_dict(), 'http_port': http_port}++ # 3) Rewrite the site URL to this server's localhost address.+ new_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'+ cls.wp_cli(root_path, ['option', 'update', 'home', new_url])+ cls.wp_cli(root_path, ['option', 'update', 'siteurl', new_url])+ sr = cls.search_replace(root_path, old_url, new_url, dry_run=False)+ cls.wp_cli(root_path, ['cache', 'flush'])+ cls.wp_cli(root_path, ['rewrite', 'flush'])++ # 4) The imported DB carries the source's users, so the create-time+ # admin no longer matches; clear it and re-detect multisite.+ wp_site.admin_user = None+ wp_site.multisite = cls.is_multisite(root_path)+ db.session.commit()++ out = {+ 'success': True,+ 'message': 'WordPress site imported successfully',+ 'site': wp_site.to_dict(),+ 'http_port': http_port,+ 'old_url': old_url,+ 'new_url': new_url,+ }+ if not sr.get('success'):+ out['warning'] = 'Search-replace reported an issue; verify links inside wp-admin.'+ if wp_content_zip_path:+ out['warning'] = 'wp-content import is not yet supported; only the database was imported.'+ return out+ except Exception as e:+ return {'success': False, 'error': str(e),+ 'site': wp_site.to_dict(), 'http_port': http_port}+@classmethoddef create_site(cls, name: str, admin_email: str, user_id: int, admin_user: str = 'admin') -> Dict:"""Create a new WordPress site via Docker."""@@ -1184,6 +1297,101 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]db.session.rollback()return {'success': False, 'error': str(e)}+ @classmethod+ def clone_site(cls, source_site_id: int, new_name: str, user_id: int) -> Dict:+ """Clone an existing Docker WordPress site into a NEW independent top-level+ site (is_production=True, no production_site_id) with FRESH admin creds.++ (1) stand up a brand-new stack via create_site; (2) container-to-container+ clone the source DB into it with a URL search-replace to the new localhost+ URL; (3) best-effort copy wp-content between containers; (4) create a fresh+ admin user (new generated password) so the clone does NOT share the+ source's credentials. Returns the new admin_password ONCE.+ """+ from app import db+ from app.models import WordPressSite+ from app.services.db_sync_service import DatabaseSyncService++ source = WordPressSite.query.get(source_site_id)+ if not source:+ return {'success': False, 'error': 'Source site not found'}+ if not source.application or not source.application.root_path:+ return {'success': False, 'error': 'Source site has no application/root path'}+ source_root = source.application.root_path+ source_compose = os.path.join(source_root, 'docker-compose.yml')+ if not os.path.exists(source_compose):+ return {'success': False, 'error': 'Source is not a Docker-stack site (no docker-compose.yml)'}++ # 1) Stand up a NEW independent stack (fresh install + an admin we will replace).+ admin_email = source.admin_email or ''+ create_res = cls.create_site(new_name, admin_email, user_id)+ if not create_res.get('success'):+ return create_res+ new_site = WordPressSite.query.get(create_res['site']['id'])+ new_root = new_site.application.root_path+ new_compose = os.path.join(new_root, 'docker-compose.yml')+ http_port = create_res.get('http_port')+ new_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'++ try:+ src_port = source.application.port+ source_url = f'http://localhost:{src_port}' if src_port else None++ # 2) Clone the source DB into the new stack (root user for a clean overwrite;+ # both stacks use db name 'wordpress'; root pw lives in each .env DB_PASSWORD).+ src_pw = cls._read_env_value(source_root, 'DB_PASSWORD')+ new_pw = cls._read_env_value(new_root, 'DB_PASSWORD')+ clone_options = {+ 'truncate_tables': ['actionscheduler_actions', 'actionscheduler_logs'],+ }+ if source_url and new_url and source_url != new_url:+ clone_options['search_replace'] = {+ source_url: new_url,+ f'localhost:{src_port}': f'localhost:{http_port}',+ }+ clone_res = DatabaseSyncService.clone_between_containers(+ source_compose_path=source_compose,+ target_compose_path=new_compose,+ source_db='wordpress', target_db='wordpress',+ source_user='root', target_user='root',+ source_password=src_pw, target_password=new_pw,+ options=clone_options,+ )+ if not clone_res.get('success'):+ return {'success': False, 'error': f"Database clone failed: {clone_res.get('error')}"}++ # 3) Best-effort copy wp-content from source container to the new one.+ cls._copy_wp_content_between_containers(source.application.name, new_site.application.name)++ # 4) Fresh admin: the DB import replaced users with the SOURCE users, so+ # create a brand-new administrator with a generated password.+ new_admin_user = 'admin'+ new_admin_pass = cls._generate_password()+ exists = cls.wp_cli(new_root, ['user', 'get', new_admin_user, '--field=ID'])+ if exists.get('success'):+ new_admin_user = f'admin_{new_site.id}'+ cu = cls.create_user(new_root, new_admin_user, admin_email or f'{new_admin_user}@example.com',+ role='administrator', password=new_admin_pass)+ if not cu.get('success'):+ return {'success': False, 'error': f"Failed to create fresh admin: {cu.get('error')}"}++ new_site.admin_user = new_admin_user+ if admin_email:+ new_site.admin_email = admin_email+ db.session.commit()++ return {+ 'success': True,+ 'message': f'Site cloned from "{source.application.name}" successfully',+ 'site': new_site.to_dict(),+ 'http_port': http_port,+ 'admin_user': new_admin_user,+ 'admin_password': new_admin_pass,+ }+ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}+@classmethoddef delete_site(cls, site_id: int, create_backup: bool = True) -> Dict:"""Delete a WordPress site and all its environments.diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex ddf1c6e2..6d304263 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -174,13 +174,13 @@ These are the features that make a user say "this is a managed platform, not a f- **Reuse:** `wordpress_service.wp_cli` (`:61-143`), `create_user`/`reset_password`, `AuditLog`, panel RBAC.- **Done when:** "Auto Login" drops a permitted operator straight into `wp-admin`, logged, with no stored WP password.-### #17 — Existing-site import `[M]` ❌+### #17 — Existing-site import `[M]` ❌ — ✅ Done (.sql/.sql.gz MVP; wp-content zip + SFTP deferred)- **Today:** No import path exists — only blank create or prod→child-env clone.- **Do:** Accept a `wp-content`/full-site zip + `.sql` dump (or an SFTP pull), provision DB + files, run the serialized-safe `search-replace` for the new URL, and register a `WordPressSite`.- **Reuse:** `db_sync_service` search-replace/clone, `_copy_wordpress_files`, `install_wordpress`, `ftp_service`.- **Done when:** An exported site comes up running on a new domain.-### #18 — Clone-to-new-independent-site with fresh credentials `[M]` 🟡+### #18 — Clone-to-new-independent-site with fresh credentials `[M]` 🟡 — ✅ Done- **Today:** `create_environment` (`services/wordpress_env_service.py:97-228`) clones files + DB (table-prefix + search-replace) but always links via `production_site_id` and **inherits** the parent's `admin_user`/`admin_email`/credentials (`:165-171`). No "duplicate as a brand-new top-level site".- **Do:** Generalize the clone to produce a standalone site and generate **fresh** admin credentials via `create_user`/`reset_password`.- **Reuse:** `create_environment` internals, `db_sync_service`.@@ -198,7 +198,7 @@ These are the features that make a user say "this is a managed platform, not a f- **Reuse:** `WordPressSite.to_dict`, `WordPressSiteCard.jsx`.- **Done when:** Sites can be tagged and filtered.-### #21 — Temporary preview URL before DNS is pointed `[M]` ❌+### #21 — Temporary preview URL before DNS is pointed `[M]` ❌ — ⏸️ Deferred (BLOCKED: a genuinely public, TLS-valid preview URL needs a pre-configured public base domain + wildcard DNS; managed sites are localhost:port only. Revisit after a public base-domain setting exists.)- **Today:** `EnvironmentDomainService.generate_domain` only emits real subdomains or a `.localhost` fallback; the env nginx template listens on `:80` only. No preview hostname scheme.- **Do:** Add a wildcard/preview hostname (e.g. `<site>.preview.<panel-domain>` or a `*.sslip.io`-style scheme) with auto TLS so a site is reachable and verifiable pre-DNS.- **Reuse:** `environment_domain_service`, wildcard SSL (#8).diff --git a/frontend/src/pages/WordPress.jsx b/frontend/src/pages/WordPress.jsxindex 3977afe6..fab5e43a 100644--- a/frontend/src/pages/WordPress.jsx+++ b/frontend/src/pages/WordPress.jsx@@ -20,6 +20,10 @@ function WordPress() {const [createLoading, setCreateLoading] = useState(false);const [createForm, setCreateForm] = useState({ name: '', adminEmail: '' });const [createdCreds, setCreatedCreds] = useState(null);+ const [showImportModal, setShowImportModal] = useState(false);+ const [importLoading, setImportLoading] = useState(false);+ const [importForm, setImportForm] = useState({ name: '', adminEmail: '', oldUrl: '' });+ const [importFile, setImportFile] = useState(null);const navigate = useNavigate();const toast = useToast();@@ -72,6 +76,35 @@ function WordPress() {}};+ const handleImport = async () => {+ if (!importForm.name) { toast.error('Site name is required'); return; }+ if (!importForm.oldUrl) { toast.error('Original site URL is required'); return; }+ if (!importFile) { toast.error('A .sql or .sql.gz dump is required'); return; }+ setImportLoading(true);+ try {+ const result = await wordpressApi.importSite({+ name: importForm.name,+ adminEmail: importForm.adminEmail,+ oldUrl: importForm.oldUrl,+ sqlFile: importFile,+ });+ if (result.success) {+ toast.success('WordPress site imported successfully');+ if (result.warning) toast.info(result.warning, { duration: 8000 });+ setShowImportModal(false);+ setImportForm({ name: '', adminEmail: '', oldUrl: '' });+ setImportFile(null);+ await loadSites();+ } else {+ toast.error(result.error || 'Failed to import site');+ }+ } catch (error) {+ toast.error(`Failed to import site: ${error.message}`);+ } finally {+ setImportLoading(false);+ }+ };+if (loading) {return (<div className="page-container wordpress-page">@@ -128,6 +161,10 @@ function WordPress() {<p className="page-description">Manage your WordPress sites</p></div><div className="page-header-actions">+ <Button variant="outline" onClick={() => setShowImportModal(true)}>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>+ Import Site+ </Button><Button onClick={() => setShowCreateModal(true)}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Create Site@@ -258,6 +295,87 @@ function WordPress() {</>)}+ {/* Import Site Modal */}+ {showImportModal && (+ <div className="modal-overlay" onClick={() => !importLoading && setShowImportModal(false)}>+ <div className="modal modal-lg" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h3>Import WordPress Site</h3>+ <button className="modal-close" onClick={() => !importLoading && setShowImportModal(false)}>+ ×+ </button>+ </div>+ <div className="modal-body">+ <div className="install-warning">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>+ <div>+ <strong>Imports a database dump into a new stack:</strong>+ <ul>+ <li>Provisions a fresh WordPress + MySQL container</li>+ <li>Loads your .sql / .sql.gz dump</li>+ <li>Rewrites the site URL to this server</li>+ </ul>+ </div>+ </div>++ <div className="form-group">+ <Label>Site Name <span className="required">*</span></Label>+ <Input+ type="text"+ value={importForm.name}+ onChange={e => setImportForm({ ...importForm, name: e.target.value })}+ placeholder="my-imported-site"+ disabled={importLoading}+ />+ <span className="form-hint">Used as the Docker project name. Letters, numbers, and hyphens only.</span>+ </div>++ <div className="form-group">+ <Label>Original Site URL <span className="required">*</span></Label>+ <Input+ type="text"+ value={importForm.oldUrl}+ onChange={e => setImportForm({ ...importForm, oldUrl: e.target.value })}+ placeholder="https://old-site.com"+ disabled={importLoading}+ />+ <span className="form-hint">The live URL in your dump; we rewrite it to the localhost address on this server.</span>+ </div>++ <div className="form-group">+ <Label>Admin Email</Label>+ <Input+ type="email"+ value={importForm.adminEmail}+ onChange={e => setImportForm({ ...importForm, adminEmail: e.target.value })}+ placeholder="[email protected]"+ disabled={importLoading}+ />+ </div>++ <div className="form-group">+ <Label>Database Dump <span className="required">*</span></Label>+ <input+ type="file"+ accept=".sql,.gz,.sql.gz"+ disabled={importLoading}+ onChange={e => setImportFile(e.target.files?.[0] || null)}+ />+ <span className="form-hint">Export via phpMyAdmin or the wp db export command. .sql.gz is supported and recommended (100MB upload limit).</span>+ </div>+ </div>+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setShowImportModal(false)} disabled={importLoading}>+ Cancel+ </Button>+ <Button onClick={handleImport} disabled={importLoading || !importForm.name || !importForm.oldUrl || !importFile}>+ {importLoading ? <><Spinner size="sm" /> Importing...</> : 'Import Site'}+ </Button>+ </div>+ </div>+ </div>+ )}+{/* Create Site Modal */}{showCreateModal && (<div className="modal-overlay" onClick={() => !createLoading && setShowCreateModal(false)}>diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 55976b35..e8de656b 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -1,6 +1,6 @@import React, { useState, useEffect } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';-import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock } from 'lucide-react';+import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText, Lock, Copy } from 'lucide-react';import useTabParam from '../hooks/useTabParam';import wordpressApi from '../services/wordpress';import api from '../services/api';@@ -81,6 +81,10 @@ const WordPressDetail = () => {const [loading, setLoading] = useState(true);const [activeTab, setActiveTab] = useTabParam(`/wordpress/${id}`, VALID_TABS);const [autoLoggingIn, setAutoLoggingIn] = useState(false);+ const [showCloneModal, setShowCloneModal] = useState(false);+ const [cloning, setCloning] = useState(false);+ const [cloneName, setCloneName] = useState('');+ const [clonedCreds, setClonedCreds] = useState(null);useEffect(() => {loadSite();@@ -98,6 +102,32 @@ const WordPressDetail = () => {}}+ async function handleClone() {+ if (!cloneName.trim()) {+ toast.error('New site name is required');+ return;+ }+ setCloning(true);+ toast.info('Cloning site... this spins up a new stack and may take a minute.', { duration: 6000 });+ try {+ const res = await wordpressApi.cloneSite(site.id, { name: cloneName.trim() });+ if (res.success) {+ setShowCloneModal(false);+ setCloneName('');+ if (res.admin_password) {+ setClonedCreds({ user: res.admin_user || 'admin', password: res.admin_password, id: res.site?.id });+ }+ toast.success('Site cloned successfully');+ } else {+ toast.error(res.error || 'Failed to clone site');+ }+ } catch (err) {+ toast.error(err.message || 'Failed to clone site');+ } finally {+ setCloning(false);+ }+ }+async function handleAutoLogin() {setAutoLoggingIn(true);toast.info('Creating one-time login link...', { duration: 3000 });@@ -134,6 +164,21 @@ const WordPressDetail = () => {return (<div className="app-detail-page wp-detail-page">+ {/* One-time cloned-admin credentials banner */}+ {clonedCreds && (+ <div className="wp-creds-banner">+ <div className="wp-creds-banner-text">+ <strong>New site created — save these admin credentials, shown only once.</strong>+ <span>Username: <code>{clonedCreds.user}</code></span>+ <span>Password: <code>{clonedCreds.password}</code></span>+ {clonedCreds.id && (+ <Button variant="ghost" onClick={() => navigate(`/wordpress/${clonedCreds.id}`)}>Open new site</Button>+ )}+ </div>+ <Button variant="ghost" onClick={() => setClonedCreds(null)}>Dismiss</Button>+ </div>+ )}+{/* Top Bar */}<div className="app-detail-topbar"><div className="app-detail-breadcrumbs">@@ -193,6 +238,14 @@ const WordPressDetail = () => {</Button></>)}+ <Button+ variant="ghost"+ onClick={() => setShowCloneModal(true)}+ title="Duplicate this site as a new independent site with fresh admin credentials"+ >+ <Copy size={16} />+ Clone+ </Button><Buttonvariant="default"onClick={handleAutoLogin}@@ -284,6 +337,36 @@ const WordPressDetail = () => {</div></div>+ {/* Clone Site Modal */}+ {showCloneModal && (+ <div className="modal-overlay" onClick={() => !cloning && setShowCloneModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Clone Site</h2>+ <button className="modal-close" onClick={() => !cloning && setShowCloneModal(false)}>×</button>+ </div>+ <form onSubmit={(e) => { e.preventDefault(); handleClone(); }}>+ <p className="hint">Creates a brand-new independent WordPress site (its own Docker stack and database) seeded from <strong>{site.name}</strong>, with fresh admin credentials shown once.</p>+ <div className="form-group">+ <Label>New Site Name *</Label>+ <Input+ type="text"+ value={cloneName}+ onChange={(e) => setCloneName(e.target.value)}+ placeholder={`${site.name}-copy`}+ autoFocus+ disabled={cloning}+ />+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={() => setShowCloneModal(false)} disabled={cloning}>Cancel</Button>+ <Button type="submit" disabled={cloning || !cloneName.trim()}>{cloning ? 'Cloning...' : 'Clone Site'}</Button>+ </div>+ </form>+ </div>+ </div>+ )}+{/* Tab Content */}<div className="app-detail-content"><ErrorBoundary key={activeTab} onRetry={loadSite}>diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex c6133381..12e01111 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -11,6 +11,22 @@ const wordpressApi = {body: data}),+ // Import an existing WP site from an uploaded SQL dump (multipart upload).+ importSite: ({ name, adminEmail, oldUrl, sqlFile }) => {+ const fd = new FormData();+ fd.append('name', name);+ fd.append('adminEmail', adminEmail || '');+ fd.append('oldUrl', oldUrl);+ fd.append('sql', sqlFile);+ return api.request(`${BASE_PATH}/import`, { method: 'POST', body: fd });+ },++ // Clone a site into a new independent top-level site (fresh admin creds returned once).+ cloneSite: (id, data) => api.request(`${BASE_PATH}/${id}/clone`, {+ method: 'POST',+ body: data+ }),+getSite: (id) => api.request(`${BASE_PATH}/${id}`),// Replace the tag list for a site (agency organization labels)