Skip to content

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.

feat(wordpress): one-click create wizard — PHP + page/object cache (#15)

Juan Denis8bc5cc551209
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index cdac194e..52315e67 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -33,12 +33,23 @@ def create_site():
data = request.get_json() or {}
name = data.get('name')
admin_email = data.get('adminEmail', '')
+ php_version = data.get('phpVersion') or None
+ enable_page_cache = bool(data.get('enablePageCache'))
+ enable_object_cache = bool(data.get('enableObjectCache'))
if not name:
return jsonify({'error': 'Site name is required'}), 400
+ if php_version and php_version not in WordPressService.get_available_php_versions():
+ return jsonify({'error': f'Unsupported PHP version: {php_version}'}), 400
+
current_user_id = get_jwt_identity()
- result = WordPressService.create_site(name, admin_email, current_user_id)
+ result = WordPressService.create_site(
+ name, admin_email, current_user_id,
+ php_version=php_version,
+ enable_page_cache=enable_page_cache,
+ enable_object_cache=enable_object_cache,
+ )
if result.get('success'):
return jsonify(result), 201
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 405a721d..822db0ab 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -263,8 +263,11 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
if not m:
return {'success': False, 'error': 'wordpress image line not found in compose file'}
current_tag = m.group(1)
- wp_core = current_tag.split('-')[0] if current_tag and current_tag[0].isdigit() else ''
- new_tag = (f'{wp_core}-php{version}-apache' if wp_core else f'php{version}-apache')
+ # Derive the WP core from the existing tag; fall back to the known core for
+ # legacy compose files that still carry an unresolved ${VERSION...} literal,
+ # so the switch never drops the core pin (e.g. -> php8.2-apache).
+ wp_core = current_tag.split('-')[0] if current_tag and current_tag[0].isdigit() else cls.WP_CORE
+ new_tag = f'{wp_core}-php{version}-apache'
new_content = content.replace(f'image: wordpress:{current_tag}', f'image: wordpress:{new_tag}')
with open(compose_file, 'w') as f:
f.write(new_content)
@@ -1405,9 +1408,21 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
return {'success': False, 'error': str(e),
'site': wp_site.to_dict(), 'http_port': http_port}
+ # WordPress core line baked into every managed stack's image tag. Kept in sync
+ # with the template default (backend/templates/wordpress.yaml) and wp_version below.
+ WP_CORE = '6.4'
+
@classmethod
- def create_site(cls, name: str, admin_email: str, user_id: int, admin_user: str = 'admin') -> Dict:
- """Create a new WordPress site via Docker."""
+ def create_site(cls, name: str, admin_email: str, user_id: int, admin_user: str = 'admin',
+ php_version: str = None, enable_page_cache: bool = False,
+ enable_object_cache: bool = False) -> Dict:
+ """Create a new WordPress site via Docker.
+
+ One-click orchestration: provision the Docker stack on a chosen PHP version,
+ finalize + harden the install, then optionally enable the full-page and/or
+ Redis object cache — all in a single call. Cache enablement is best-effort
+ and never fails the create. The generated admin password is returned ONCE.
+ """
from app import db
from app.models import Application, WordPressSite
from app.services.template_service import TemplateService
@@ -1421,11 +1436,18 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
if existing:
return {'success': False, 'error': f'A site with name "{safe_name}" already exists'}
+ # Bake the chosen PHP version into the initial image tag so the site is
+ # created on the right PHP from the start (no post-create container recreate).
+ # Invalid/empty values fall through to the template default (WP_CORE-apache).
+ user_variables = {}
+ if php_version and php_version in cls.get_available_php_versions():
+ user_variables['VERSION'] = f'{cls.WP_CORE}-php{php_version}-apache'
+
try:
result = TemplateService.install_template(
template_id='wordpress',
app_name=safe_name,
- user_variables={},
+ user_variables=user_variables,
user_id=user_id
)
@@ -1448,6 +1470,9 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'
wp_warning = None
harden_actions = []
+ cache_actions = []
+ cache_warnings = []
+ page_cache_on = False
if cls._wait_for_wp_ready(app.root_path):
install_res = cls.wp_cli(app.root_path, [
'core', 'install',
@@ -1460,6 +1485,24 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
])
if install_res.get('success'):
harden_actions = cls._harden_docker_site(app.root_path)
+ # Optional caches (best-effort; never fail the create). These are
+ # wp_cli calls inside the now-running container, so they must run
+ # AFTER the core install has finalized.
+ if enable_object_cache:
+ oc = cls.enable_object_cache(app.root_path)
+ # Record whatever work succeeded — the helper returns its partial
+ # 'actions' even on failure (e.g. redis added + plugin installed
+ # but the drop-in enable failed) — then note any failure non-fatally.
+ cache_actions.extend(oc.get('actions') or [])
+ if not oc.get('success'):
+ cache_warnings.append('object cache: ' + (oc.get('error') or 'unknown error'))
+ if enable_page_cache:
+ pc = cls.enable_page_cache(app.root_path)
+ if pc.get('success'):
+ cache_actions.append('Enabled full-page cache')
+ page_cache_on = True
+ else:
+ cache_warnings.append('page cache: ' + (pc.get('error') or 'unknown error'))
else:
admin_password = None
wp_warning = (
@@ -1478,16 +1521,23 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
# only meaningful if the automated install finalized).
multisite = cls.is_multisite(app.root_path) if admin_password else False
- # Create WordPressSite record
+ # Surface any best-effort cache failures without failing the create.
+ if cache_warnings:
+ note = 'Site created, but some caches could not be enabled — ' + '; '.join(cache_warnings) + '.'
+ wp_warning = (wp_warning + ' ' + note) if wp_warning else note
+
+ # Create WordPressSite record. Persist the page-cache flag in sync_config
+ # to mirror the per-site page-cache route (object cache + PHP are read live).
wp_site = WordPressSite(
application_id=app.id,
admin_user=admin_user if admin_password else None,
admin_email=admin_email,
is_production=True,
environment_type='production',
- wp_version='6.4',
+ wp_version=cls.WP_CORE,
compose_project_name=safe_name,
- multisite=multisite
+ multisite=multisite,
+ sync_config=json.dumps({'page_cache_enabled': True}) if page_cache_on else None,
)
db.session.add(wp_site)
db.session.commit()
@@ -1500,6 +1550,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
'admin_user': admin_user if admin_password else None,
'admin_password': admin_password,
'hardening': harden_actions,
+ 'cache': cache_actions,
}
if wp_warning:
result['warning'] = wp_warning
diff --git a/backend/templates/wordpress-external-db.yaml b/backend/templates/wordpress-external-db.yaml
index 72655604..c0a1b697 100644
--- a/backend/templates/wordpress-external-db.yaml
+++ b/backend/templates/wordpress-external-db.yaml
@@ -12,6 +12,11 @@ categories:
- development
variables:
+ - name: VERSION
+ description: WordPress image tag (WP core + PHP variant, e.g. 6.4-php8.2-apache)
+ type: string
+ default: "6.4-apache"
+ hidden: true
- name: HTTP_PORT
description: HTTP port for WordPress
type: port
@@ -57,7 +62,7 @@ volumes:
compose:
services:
wordpress:
- image: wordpress:${VERSION:-6.4-apache}
+ image: wordpress:${VERSION}
container_name: ${APP_NAME}
restart: unless-stopped
environment:
diff --git a/backend/templates/wordpress.yaml b/backend/templates/wordpress.yaml
index ad6b55a5..5e0592ab 100644
--- a/backend/templates/wordpress.yaml
+++ b/backend/templates/wordpress.yaml
@@ -11,6 +11,11 @@ categories:
- website
variables:
+ - name: VERSION
+ description: WordPress image tag (WP core + PHP variant, e.g. 6.4-php8.2-apache)
+ type: string
+ default: "6.4-apache"
+ hidden: true
- name: HTTP_PORT
description: HTTP port
type: port
@@ -43,7 +48,7 @@ volumes:
compose:
services:
wordpress:
- image: wordpress:${VERSION:-6.4-apache}
+ image: wordpress:${VERSION}
container_name: ${APP_NAME}
restart: unless-stopped
environment:
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 9ca5e294..363468e8 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -157,11 +157,12 @@ Every task here reuses a service that already exists and is verified present. **
These are the features that make a user say "this is a managed platform, not a folder." They sit directly on the primitives glued in Phase A. **Estimated cluster: 3–5 days.**
-### #15 — True one-click site lifecycle `[L]` ❌
+### #15 — True one-click site lifecycle `[L]` ❌ — ✅ Done (Docker-correct create bundle: PHP + page/object cache + admin in one wizard; TLS/custom-domain deferred — same infra gap as #21)
- **Today:** Create is incoherent (see #1/#2): UI collects only `{name, adminEmail}`; no SSL/PHP/cache options anywhere in the flow.
- **Do:** A single `WordPressSiteService.create` that orchestrates existing services in sequence — provision DB + admin (`install_wordpress` + `harden_wordpress`), issue SSL (#8), honor a chosen PHP version (#24), optionally enable cache (#22/#23), then register the `WordPressSite`. Expose domain + PHP version + admin + "enable SSL/cache" in `CreateSiteModal`.
- **Reuse:** everything from Phase 0 + #8.
- **Done when:** One wizard produces a hardened, TLS'd, admin-ready site on a real domain.
+- **Landed:** `WordPressService.create_site` is now the single orchestrator and gained `php_version` / `enable_page_cache` / `enable_object_cache`. The chosen **PHP version is baked into the initial image tag** (concrete `6.4-php<x.y>-apache`, so the site boots on the right PHP with **no** post-create recreate), followed by the existing finalize+`_harden_docker_site`, then **best-effort** page cache (#22) and Redis object cache (#23) *after* `wp core install` (redis already ships in the stack, so no recreate). Cache enablement never fails the create — failures degrade to a non-fatal `warning`; the one-time admin password is still surfaced once. The live create modal (inline in `WordPress.jsx`, not the orphaned `CreateSiteModal.jsx`) gained a **PHP version selector** (Default / 8.1 / 8.2 / 8.3) and **page-cache / object-cache** toggles, threaded through `createForm` → `POST /sites` as `phpVersion` / `enablePageCache` / `enableObjectCache` (PHP version validated server-side against `get_available_php_versions()`). **Mechanism:** declared a hidden `VERSION` template var and switched the image line to bare `${VERSION}` in both `wordpress.yaml` and `wordpress-external-db.yaml` so a concrete tag is written at install — this *also fixes a latent #24 bug* where the unresolved `${VERSION:-…}` literal made `set_php_version` drop the WP-core pin (`set_php_version` now also falls back to the known core for legacy compose files). **No DB migration:** PHP / object-cache / SSL are read live; the page-cache flag rides the existing `sync_config` JSON column (mirroring the per-site page-cache route). Verified: backend `py_compile`, frontend lint-clean + production build, a 3-lens adversarial review (no blockers), and Docker Hub confirms all `6.4-php8.{1,2,3}-apache` tags exist. *(Deferred: SSL/TLS + custom-domain at create. Managed sites are `http://localhost:PORT` containers with no per-site reverse proxy and no domain attached at create — a public, routable domain + nginx vhost is the same missing infrastructure that blocks #21 and that #8 left as frontend-only. TLS is already operable post-create via `SiteSSLPanel` (#8) once a domain is routed; the `domains.py` → `NginxService.create_site` primitive exists for a future create-time wiring.)*
### #16 — Passwordless WP-admin login (the signature feature) `[M]` ❌ — ✅ Done (WP-CLI magic link; needs container egress to install the wp-cli-login package once)
- **Today:** "Open WP Admin" is a dumb `window.open` to `{site.url}/wp-admin`. Grep confirms **zero** login/magic/token/SSO code in the WP API. `create_user` (`:646`) and `reset_password` (`:666`) exist, so managed-admin provisioning is half-done.
diff --git a/frontend/src/pages/WordPress.jsx b/frontend/src/pages/WordPress.jsx
index fab5e43a..5e098edf 100644
--- a/frontend/src/pages/WordPress.jsx
+++ b/frontend/src/pages/WordPress.jsx
@@ -18,7 +18,9 @@ function WordPress() {
const [activeTag, setActiveTag] = useState(null); // null = show all
const [showCreateModal, setShowCreateModal] = useState(false);
const [createLoading, setCreateLoading] = useState(false);
- const [createForm, setCreateForm] = useState({ name: '', adminEmail: '' });
+ const [createForm, setCreateForm] = useState({
+ name: '', adminEmail: '', phpVersion: '', enablePageCache: false, enableObjectCache: false,
+ });
const [createdCreds, setCreatedCreds] = useState(null);
const [showImportModal, setShowImportModal] = useState(false);
const [importLoading, setImportLoading] = useState(false);
@@ -59,12 +61,13 @@ function WordPress() {
if (result.admin_password) {
// The generated admin password is returned once — surface it.
setCreatedCreds({ user: result.admin_user || 'admin', password: result.admin_password });
- } else if (result.warning) {
+ }
+ if (result.warning) {
toast.info(result.warning, { duration: 8000 });
}
toast.success('WordPress site created successfully');
setShowCreateModal(false);
- setCreateForm({ name: '', adminEmail: '' });
+ setCreateForm({ name: '', adminEmail: '', phpVersion: '', enablePageCache: false, enableObjectCache: false });
await loadSites();
} else {
toast.error(result.error || 'Failed to create site');
@@ -423,6 +426,47 @@ function WordPress() {
disabled={createLoading}
/>
</div>
+
+ <div className="form-group">
+ <Label>PHP Version</Label>
+ <select
+ value={createForm.phpVersion}
+ onChange={e => setCreateForm({ ...createForm, phpVersion: e.target.value })}
+ disabled={createLoading}
+ >
+ <option value="">Default (latest for WordPress 6.4)</option>
+ <option value="8.1">PHP 8.1</option>
+ <option value="8.2">PHP 8.2</option>
+ <option value="8.3">PHP 8.3</option>
+ </select>
+ <span className="form-hint">Baked into the container image at creation. Changeable later from the PHP tab.</span>
+ </div>
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ checked={createForm.enablePageCache}
+ onChange={e => setCreateForm({ ...createForm, enablePageCache: e.target.checked })}
+ disabled={createLoading}
+ />
+ Enable full-page cache
+ </label>
+ <span className="form-hint">Disk page cache with WordPress-aware skip rules (admin, login, cart, checkout).</span>
+ </div>
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ checked={createForm.enableObjectCache}
+ onChange={e => setCreateForm({ ...createForm, enableObjectCache: e.target.checked })}
+ disabled={createLoading}
+ />
+ Enable Redis object cache
+ </label>
+ <span className="form-hint">Uses the bundled Redis container with the redis-cache drop-in.</span>
+ </div>
</div>
<div className="modal-footer">
<Button