Merge pull request 'Dev' (#8) from dev into main

Reviewed-on: #8
This commit was merged in pull request #8.
This commit is contained in:
2026-11-26 09:04:24 +00:00
114 changed files with 5428 additions and 3207 deletions
+2 -1
View File
@@ -17,7 +17,8 @@ cache
uploads
extensions/dev_*
docs
docs/*
.agents
skills-lock.json
# Editor directories and files
.vscode/*
@@ -19,17 +19,19 @@ if(isset($_GET['id']))
$isEditing = isset($form['id']) && $form['id'] > 0;
?>
<div class="mb-6">
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-3">
<a href="?tab=ext--form" class="btn btn-ghost btn-sm btn-circle">
<i class="ph-duotone ph-arrow-left text-xl"></i>
<a href="?tab=ext--form" class="btn btn-ghost btn-square btn-sm" aria-label="Back to forms" title="Back to forms">
<i class="ph-duotone ph-arrow-left text-xl" aria-hidden="true"></i>
</a>
<div>
<h2 class="text-xl font-bold"><?= $isEditing ? 'Edit form' : 'New form' ?></h2>
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Form builder</p>
<h2 class="text-xl font-bold tracking-tight"><?= $isEditing ? 'Edit form' : 'New form' ?></h2>
<p class="text-sm text-base-content/60"><?= $isEditing ? 'Change your form settings.' : 'Create a new form with fields and actions.' ?></p>
</div>
</div>
</div>
<span class="badge badge-outline self-start sm:self-center"><?= $isEditing ? 'Editing form' : 'New form' ?></span>
</header>
<script>
const fields = <?= $form["fields"] ?>;
@@ -37,7 +39,7 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
const finisherDefinitions = <?= json_encode($finisherDefinitions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
</script>
<form action="/ext--form/save-form" method="post" x-data="{
<form action="/ext--form/save-form" method="post" class="space-y-6" x-data="{
fields: fields,
finishers: finishers,
defaultField: {name: 'form_field', label: 'Form field', type: 'text', required: false, options: []},
@@ -104,42 +106,52 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
if(isset($form['id'])) echo '<input type="hidden" name="id" value="'.$form['id'].'">';
?>
<div class="card bg-base-100 shadow mb-6">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-text-aa text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Basics</h3>
</div>
<div class="form-control">
<label class="label">
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="form-basics-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<header class="flex items-start gap-3 border-b border-base-300 pb-4">
<span class="grid size-10 shrink-0 place-items-center rounded-xl bg-primary/10 text-primary">
<i class="text-xl ph-duotone ph-text-aa" aria-hidden="true"></i>
</span>
<div>
<h3 class="card-title text-lg" id="form-basics-title">Basics</h3>
<p class="mt-1 text-sm text-base-content/60">Give the form a name that will be easy to identify later.</p>
</div>
</header>
<div class="form-control w-full max-w-2xl gap-1">
<label class="label" for="form-name">
<span class="label-text font-medium">Form name</span>
<span class="label-text-alt">Required</span>
</label>
<input type="text" name="name" value="<?= $form['name'] ?>" placeholder="e.g. Contact form" class="input input-bordered w-full" required />
<span class="label-text-alt text-base-content/60">A unique name for your form.</span>
<input id="form-name" type="text" name="name" value="<?= phpb_e($form['name']) ?>" placeholder="e.g. Contact form" class="input input-bordered w-full" required aria-describedby="form-name-help" />
<span class="label-text-alt mt-1 text-base-content/60" id="form-name-help">A unique name for your form.</span>
</div>
</div>
</div>
</section>
<div class="card bg-base-100 shadow mb-6">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-list-dashes text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Form fields</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">Define the fields users can fill out.</p>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="form-fields-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<header class="flex items-start gap-3 border-b border-base-300 pb-4">
<span class="grid size-10 shrink-0 place-items-center rounded-xl bg-secondary/10 text-secondary">
<i class="text-xl ph-duotone ph-list-dashes" aria-hidden="true"></i>
</span>
<div>
<h3 class="card-title text-lg" id="form-fields-title">Form fields</h3>
<p class="mt-1 text-sm text-base-content/60">Define the fields people can fill out. Drag a field to change its order.</p>
</div>
</header>
<input type="hidden" name="fields" :value="JSON.stringify(fields)">
<div x-show="fields.length === 0" class="text-center py-8 border-2 border-dashed border-base-300 rounded-lg">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30"></i>
<p class="text-sm text-base-content/50 mt-2">No fields added yet</p>
<a href="javascript:void(0)" @click="addField()" class="btn btn-sm btn-primary mt-2">Add your first field</a>
<div x-show="fields.length === 0" class="rounded-box border border-dashed border-base-300 bg-base-200/40 px-4 py-10 text-center">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30" aria-hidden="true"></i>
<p class="mt-2 text-sm text-base-content/60">No fields added yet</p>
<button type="button" @click="addField()" class="btn btn-primary btn-sm mt-3">Add your first field</button>
</div>
<div x-show="fields.length > 0" class="space-y-3">
<div x-show="fields.length > 0" class="space-y-4">
<template x-for="(field, index) in fields">
<div
class="border rounded-lg p-3 bg-base-200/50 transition-colors"
class="rounded-box border border-base-300 bg-base-200/40 p-4 shadow-sm transition-colors sm:p-5"
:class="{
'border-error': getValidationErrors(field, index).length > 0,
'border-base-300': getValidationErrors(field, index).length === 0,
@@ -151,42 +163,44 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
@drop.prevent="moveField(dragIndex, index)"
@dragend="dragIndex = null"
>
<div class="flex items-center gap-2 mb-2">
<div class="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center">
<!-- Drag handle -->
<button type="button" class="btn btn-ghost btn-xs btn-square cursor-grab active:cursor-grabbing text-base-content/40 hover:text-base-content" title="Drag to move">
<i class="ph-duotone ph-dots-six-vertical text-lg"></i>
<button type="button" class="btn btn-ghost btn-xs btn-square cursor-grab active:cursor-grabbing text-base-content/40 hover:text-base-content" title="Drag to move" aria-label="Drag to move field">
<i class="ph-duotone ph-dots-six-vertical text-lg" aria-hidden="true"></i>
</button>
<span class="text-xs font-mono text-base-content/40 w-6">#[<span x-text="index + 1"></span>]</span>
<div class="flex-1">
<div class="w-full flex-1">
<input
type="text"
x-model="field.name"
placeholder="Field name"
placeholder="Field name"
:aria-label="'Field ' + (index + 1) + ' name'"
class="input input-bordered input-sm w-full"
:class="{'input-error': getValidationErrors(field, index).some(e => e.includes('Field name'))}"
/>
</div>
<div class="flex-1">
<div class="w-full flex-1">
<input
type="text"
x-model="field.label"
placeholder="Label"
placeholder="Label"
:aria-label="'Field ' + (index + 1) + ' label'"
class="input input-bordered input-sm w-full"
:class="{'input-error': getValidationErrors(field, index).some(e => e.includes('Label'))}"
/>
</div>
</div>
<!-- Validation errors -->
<div x-show="getValidationErrors(field, index).length > 0" x-transition class="mb-2 p-2 bg-error/10 border border-error/30 rounded text-error text-xs">
<div x-show="getValidationErrors(field, index).length > 0" x-transition class="alert alert-error alert-soft mb-3 px-3 py-2 text-xs" role="alert" aria-live="polite">
<template x-for="(error, errIndex) in getValidationErrors(field, index)">
<div :key="errIndex" class="flex items-center gap-1">
<i class="ph-duotone ph-warning text-sm"></i>
<i class="ph-duotone ph-warning text-sm" aria-hidden="true"></i>
<span x-text="error"></span>
</div>
</template>
</div>
<div class="flex items-center gap-2">
<select x-model="field.type" class="select select-bordered select-sm flex-1">
<div class="flex flex-wrap items-center gap-2">
<select x-model="field.type" class="select select-bordered select-sm min-w-40 flex-1" :aria-label="'Field ' + (index + 1) + ' type'">
<option value="text">Text</option>
<option value="email">Email</option>
<option value="textarea">Text area</option>
@@ -196,27 +210,27 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
</select>
<label class="label cursor-pointer gap-2">
<span class="label-text text-sm">Required</span>
<input type="checkbox" x-model="field.required" class="checkbox checkbox-sm checkbox-primary" />
<input type="checkbox" x-model="field.required" class="checkbox checkbox-sm checkbox-primary" :aria-label="'Field ' + (index + 1) + ' is required'" />
</label>
<button @click="fields.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove">
<button @click="fields.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove" :aria-label="'Remove field ' + (index + 1)">
<i class="ph-duotone ph-trash"></i>
</button>
</div>
<div x-show="field.type === 'select' || field.type === 'checkbox' || field.type === 'radio'" x-transition class="mt-3 ml-2 pl-4 border-l-2 border-primary/30">
<div class="flex items-center gap-2 mb-2">
<span class="text-xs font-medium text-base-content/60 uppercase tracking-wide" x-text="getOptionsLabel(field.type)"></span>
<a href="javascript:void(0)" @click="field.options.push({label: 'Option', value: 'option'})" class="btn btn-xs btn-ghost btn-primary">
<i class="ph-duotone ph-plus"></i>
<div x-show="field.type === 'select' || field.type === 'checkbox' || field.type === 'radio'" x-transition class="mt-4 rounded-box border-l-2 border-primary/50 bg-base-100 p-3 sm:ml-2 sm:p-4">
<div class="mb-3 flex items-center gap-2">
<span class="text-xs font-semibold uppercase tracking-wide text-base-content/60" x-text="getOptionsLabel(field.type)"></span>
<button type="button" @click="field.options.push({label: 'Option', value: 'option'})" class="btn btn-xs btn-ghost btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Add
</a>
</button>
</div>
<div class="space-y-1">
<template x-for="(option, optIndex) in field.options">
<div class="flex items-center gap-2">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<span class="text-xs text-base-content/40 w-4">#[<span x-text="optIndex + 1"></span>]</span>
<input type="text" x-model="option.label" placeholder="Label" class="input input-bordered input-sm flex-1" />
<input type="text" x-model="option.value" placeholder="Value" class="input input-bordered input-sm flex-1" />
<button @click="field.options.splice(optIndex, 1)" type="button" class="btn btn-ghost btn-xs btn-circle text-error" title="Remove">
<input type="text" x-model="option.label" placeholder="Label" class="input input-bordered input-sm w-full flex-1" :aria-label="'Field ' + (index + 1) + ' option ' + (optIndex + 1) + ' label'" />
<input type="text" x-model="option.value" placeholder="Value" class="input input-bordered input-sm w-full flex-1" :aria-label="'Field ' + (index + 1) + ' option ' + (optIndex + 1) + ' value'" />
<button @click="field.options.splice(optIndex, 1)" type="button" class="btn btn-ghost btn-xs btn-circle text-error" title="Remove" :aria-label="'Remove option ' + (optIndex + 1) + ' from field ' + (index + 1)">
<i class="ph-duotone ph-x"></i>
</button>
</div>
@@ -227,51 +241,55 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
</template>
</div>
<div class="mt-4">
<a href="javascript:void(0)" @click="addField()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus"></i>
<div class="border-t border-base-300 pt-4">
<button type="button" @click="addField()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Add field
</a>
</button>
</div>
</div>
</div>
</section>
<div class="card bg-base-100 shadow mb-6">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-gear text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Actions</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">What should happen when a form is submitted?</p>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="form-actions-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<header class="flex items-start gap-3 border-b border-base-300 pb-4">
<span class="grid size-10 shrink-0 place-items-center rounded-xl bg-accent/15 text-base-content">
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
</span>
<div>
<h3 class="card-title text-lg" id="form-actions-title">Actions</h3>
<p class="mt-1 text-sm text-base-content/60">Choose what should happen when someone submits this form.</p>
</div>
</header>
<input type="hidden" name="finishers" :value="JSON.stringify(finishers)">
<div x-show="finishers.length === 0" class="text-center py-8 border-2 border-dashed border-base-300 rounded-lg">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30"></i>
<p class="text-sm text-base-content/50 mt-2">No actions added yet</p>
<a href="javascript:void(0)" @click="addFinisher()" class="btn btn-sm btn-primary mt-2">Add your first action</a>
<div x-show="finishers.length === 0" class="rounded-box border border-dashed border-base-300 bg-base-200/40 px-4 py-10 text-center">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30" aria-hidden="true"></i>
<p class="mt-2 text-sm text-base-content/60">No actions added yet</p>
<button type="button" @click="addFinisher()" class="btn btn-primary btn-sm mt-3">Add your first action</button>
</div>
<div x-show="finishers.length > 0" class="space-y-2">
<div x-show="finishers.length > 0" class="space-y-4">
<template x-for="(finisher, index) in finishers">
<div class="p-3 border border-base-300 rounded-lg bg-base-200/50 space-y-3">
<div class="flex items-center gap-3">
<div class="space-y-4 rounded-box border border-base-300 bg-base-200/40 p-4 shadow-sm sm:p-5">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
<span class="text-xs font-mono text-base-content/40">#[<span x-text="index + 1"></span>]</span>
<select :value="finisher.type" @change="setFinisherType(finisher, $event.target.value)" class="select select-bordered select-sm flex-1">
<select :value="finisher.type" @change="setFinisherType(finisher, $event.target.value)" class="select select-bordered select-sm min-w-40 flex-1" :aria-label="'Action ' + (index + 1) + ' type'">
<template x-for="(definition, type) in finisherDefinitions" :key="type">
<option :value="type" x-text="definition.label"></option>
</template>
</select>
<button @click="finishers.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove">
<i class="ph-duotone ph-trash"></i>
<button @click="finishers.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove" :aria-label="'Remove action ' + (index + 1)">
<i class="ph-duotone ph-trash" aria-hidden="true"></i>
</button>
</div>
<div x-show="getFinisherSettings(finisher.type).length > 0" class="space-y-3 pl-8">
<div x-show="getFinisherSettings(finisher.type).length > 0" class="space-y-4 border-t border-base-300 pt-4 sm:pl-9">
<template x-for="setting in getFinisherSettings(finisher.type)" :key="setting.name">
<div class="form-control">
<label class="label"><span class="label-text" x-text="setting.label"></span></label>
<label class="label" :for="'finisher-' + index + '-' + setting.name"><span class="label-text" x-text="setting.label"></span></label>
<template x-if="setting.type === 'emailField'">
<select x-model="finisher.options[setting.name]" :required="setting.required || false" class="select select-bordered select-sm w-full">
<select :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :required="setting.required || false" class="select select-bordered select-sm w-full">
<option value="">Select an email field</option>
<template x-for="field in fields.filter(field => field.type === 'email')" :key="field.name">
<option :value="field.name" x-text="field.label + ' (' + field.name + ')' "></option>
@@ -279,42 +297,42 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
</select>
</template>
<template x-if="setting.type === 'select'">
<select x-model="finisher.options[setting.name]" :required="setting.required || false" class="select select-bordered select-sm w-full">
<select :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :required="setting.required || false" class="select select-bordered select-sm w-full">
<template x-for="option in setting.options || []" :key="option.value">
<option :value="option.value" x-text="option.label"></option>
</template>
</select>
</template>
<template x-if="setting.type === 'textarea'">
<textarea x-model="finisher.options[setting.name]" :required="setting.required || false" :placeholder="setting.placeholder || ''" class="textarea textarea-bordered w-full" rows="4"></textarea>
<textarea :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :required="setting.required || false" :placeholder="setting.placeholder || ''" class="textarea textarea-bordered w-full" rows="4"></textarea>
</template>
<template x-if="!['emailField', 'select', 'textarea'].includes(setting.type)">
<input x-model="finisher.options[setting.name]" :type="setting.type" :required="setting.required || false" :min="setting.min" :max="setting.max" :placeholder="setting.placeholder || ''" class="input input-bordered input-sm w-full" />
<input :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :type="setting.type" :required="setting.required || false" :min="setting.min" :max="setting.max" :placeholder="setting.placeholder || ''" class="input input-bordered input-sm w-full" />
</template>
<span x-show="setting.help" class="label-text-alt text-base-content/60 mt-1" x-text="setting.help"></span>
</div>
</template>
<span x-show="getFinisherSettings(finisher.type).some(setting => setting.type === 'emailField') && fields.filter(field => field.type === 'email').length === 0" class="label-text-alt text-warning">Add an email field to the form before using this action.</span>
<span x-show="getFinisherSettings(finisher.type).some(setting => setting.type === 'emailField') && fields.filter(field => field.type === 'email').length === 0" class="alert alert-warning alert-soft text-sm" role="status">Add an email field to the form before using this action.</span>
</div>
</div>
</template>
</div>
<div class="mt-4">
<a href="javascript:void(0)" @click="addFinisher()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus"></i>
<div class="border-t border-base-300 pt-4">
<button type="button" @click="addFinisher()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Add action
</a>
</button>
</div>
</div>
</div>
</section>
<div class="flex justify-end gap-2">
<a href="?tab=ext--form" class="btn btn-ghost btn-sm">
<div class="flex flex-col-reverse gap-2 border-t border-base-300 pt-5 sm:flex-row sm:justify-end">
<a href="?tab=ext--form" class="btn btn-ghost btn-sm sm:min-w-28">
Cancel
</a>
<button type="submit" class="btn btn-primary btn-sm">
<i class="ph-duotone ph-floppy-disk"></i>
<button type="submit" class="btn btn-primary btn-sm sm:min-w-28">
<i class="ph-duotone ph-floppy-disk" aria-hidden="true"></i>
Save
</button>
</div>
@@ -1,11 +1,16 @@
<div class="card bg-base-100 shadow">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-gear text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Settings</h3>
<section class="card border border-base-300/60 bg-base-100 shadow-sm" aria-labelledby="form-extension-settings-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div class="flex items-start gap-3 border-b border-base-300 pb-5">
<span class="grid size-11 shrink-0 place-items-center rounded-2xl bg-primary/10 text-primary">
<i class="text-2xl ph-duotone ph-gear" aria-hidden="true"></i>
</span>
<div>
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Form extension</p>
<h2 class="card-title mt-1 text-xl" id="form-extension-settings-title">Settings</h2>
<p class="mt-1 text-sm text-base-content/60">Configure the global settings for the Form extension.</p>
</div>
</div>
<p class="text-sm text-base-content/60 mb-4">Configure the global settings for the Form extension.</p>
<div class="space-y-4">
<div class="space-y-5">
<?php
foreach (\Plugi\Extensions::getSettings('form') as $setting) {
phpb_render_setting($setting);
@@ -13,4 +18,4 @@
?>
</div>
</div>
</div>
</section>
@@ -13,76 +13,78 @@ $entries = $entriesRepository->findWhere('formId', $id);
?>
<div class="mb-6">
<div class="flex items-center gap-3">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form']) ?>" class="btn btn-ghost btn-sm btn-circle">
<i class="ph-duotone ph-arrow-left text-xl"></i>
</a>
<div>
<h2 class="text-xl font-bold"><?= phpb_e($form['name']) ?></h2>
<p class="text-sm text-base-content/60"><?= count($entries) ?> submission<?= count($entries) !== 1 ? 's' : '' ?> for this form</p>
<section class="space-y-5">
<header class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-3">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form']) ?>" class="btn btn-ghost btn-square btn-sm" aria-label="Back to forms" title="Back to forms">
<i class="ph-duotone ph-arrow-left text-xl" aria-hidden="true"></i>
</a>
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Form submissions</p>
<h2 class="text-xl font-bold tracking-tight"><?= phpb_e($form['name']) ?></h2>
<p class="text-sm text-base-content/60"><?= count($entries) ?> submission<?= count($entries) !== 1 ? 's' : '' ?> for this form</p>
</div>
</div>
</div>
</div>
<span class="badge badge-outline self-start sm:self-center"><?= count($entries) ?> total</span>
</header>
<?php if (empty($entries)): ?>
<div class="card bg-base-100 shadow">
<div class="card-body items-center text-center py-16">
<i class="ph-duotone ph-inbox text-6xl text-base-content/20"></i>
<h3 class="card-title text-lg mt-4">No submissions yet</h3>
<p class="text-base-content/60 mt-1">Submissions will appear here when someone fills out the form.</p>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center gap-3 px-5 py-12 text-center sm:py-16">
<span class="grid size-14 place-items-center rounded-2xl bg-info/10 text-info">
<i class="text-3xl ph-duotone ph-inbox" aria-hidden="true"></i>
</span>
<h3 class="card-title mt-1 text-lg">No submissions yet</h3>
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Submissions will appear here when someone fills out the form.</p>
</div>
</div>
<?php else: ?>
<div class="card bg-base-100 shadow">
<div class="card-body p-0">
<div class="overflow-x-auto">
<table class="table w-full">
<thead>
<tr class="bg-base-200/50">
<th class="w-16">ID</th>
<th class="w-40">Created</th>
<?php foreach ($fields as $field): ?>
<th><?= phpb_e($field['label']) ?></th>
<?php endforeach; ?>
<th class="w-12 text-center"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($entries as $entry):
$entryData = json_decode($entry['data'], true);
$createdDate = new DateTime($entry['created'] . ' UTC');
$createdDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[48rem]">
<thead>
<tr>
<th class="w-16">ID</th>
<th class="w-40">Created</th>
<?php foreach ($fields as $field): ?>
<th><?= phpb_e($field['label']) ?></th>
<?php endforeach; ?>
<th class="w-40 text-right"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($entries as $entry):
$entryData = json_decode($entry['data'], true);
$createdDate = new DateTime($entry['created'] . ' UTC');
$createdDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
?>
<tr>
<td><span class="badge badge-ghost font-mono"><?= phpb_e($entry['id']) ?></span></td>
<td class="text-sm"><?= $createdDate->format('d.m.Y H:i') ?></td>
<?php foreach ($fields as $field):
$fieldName = $field['name'];
$fieldValue = '';
if (isset($entryData['fields'][$fieldName])) {
$fieldValue = $entryData['fields'][$fieldName];
// Handle array values (e.g., from checkboxes)
if (is_array($fieldValue)) {
$fieldValue = implode(', ', $fieldValue);
}
}
?>
<tr class="hover:bg-base-200/30">
<td class="font-mono text-sm text-base-content/60"><?= phpb_e($entry['id']) ?></td>
<td class="text-sm"><?= $createdDate->format('d.m.Y H:i') ?></td>
<?php foreach ($fields as $field):
$fieldName = $field['name'];
$fieldValue = '';
if (isset($entryData['fields'][$fieldName])) {
$fieldValue = $entryData['fields'][$fieldName];
// Handle array values (e.g., from checkboxes)
if (is_array($fieldValue)) {
$fieldValue = implode(', ', $fieldValue);
}
}
?>
<td class="text-sm"><?= phpb_e($fieldValue) ?></td>
<?php endforeach; ?>
<td>
<div class="flex justify-center">
<a href="/ext--form/delete-entry?id=<?= $entry['id'] ?>&formId=<?= $id ?>" class="btn btn-ghost btn-sm btn-circle text-error" title="<?= phpb_trans('website-manager.remove') ?>">
<i class="ph-duotone ph-trash text-lg"></i>
</a>
</div>
</td>
</tr>
<td class="max-w-72 text-sm"><span class="line-clamp-3 break-words"><?= phpb_e($fieldValue) ?></span></td>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<td>
<div class="flex justify-end">
<a href="/ext--form/delete-entry?id=<?= $entry['id'] ?>&formId=<?= $id ?>" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> submission <?= phpb_e($entry['id']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</a>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
@@ -6,67 +6,68 @@ $forms = $formsRepository->getAll();
?>
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-xl font-bold">Forms</h2>
<p class="text-sm text-base-content/60"><?= count($forms) ?> form<?= count($forms) !== 1 ? 's' : '' ?> available</p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary btn-sm">
<i class="ph-duotone ph-plus"></i>
New form
</a>
</div>
<section class="space-y-5">
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Form extension</p>
<h2 class="text-xl font-bold tracking-tight text-base-content">Forms</h2>
<p class="text-sm text-base-content/60"><?= count($forms) ?> form<?= count($forms) !== 1 ? 's' : '' ?> available</p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
New form
</a>
</header>
<?php if (empty($forms)): ?>
<div class="card bg-base-100 shadow">
<div class="card-body items-center text-center py-16">
<i class="ph-duotone ph-notebook text-6xl text-base-content/20"></i>
<h3 class="card-title text-lg mt-4">No forms yet</h3>
<p class="text-base-content/60 mt-1">Create your first form to collect submissions from your website.</p>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary mt-4">
<i class="ph-duotone ph-plus"></i>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center gap-3 px-5 py-12 text-center sm:py-16">
<span class="grid size-14 place-items-center rounded-2xl bg-primary/10 text-primary">
<i class="text-3xl ph-duotone ph-notebook" aria-hidden="true"></i>
</span>
<h3 class="card-title mt-1 text-lg">No forms yet</h3>
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Create your first form to collect submissions from your website.</p>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary mt-2">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Create your first form
</a>
</div>
</div>
<?php else: ?>
<div class="card bg-base-100 shadow">
<div class="card-body p-0">
<div class="overflow-x-auto">
<table class="table w-full">
<thead>
<tr class="bg-base-200/50">
<th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th class="w-16 text-center"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($forms as $form): ?>
<tr class="hover:bg-base-200/30">
<td class="font-mono text-sm text-base-content/60"><?= phpb_e($form['id']) ?></td>
<td>
<div class="font-medium"><?= phpb_e($form['name']) ?></div>
</td>
<td>
<div class="flex items-center justify-center gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-sm btn-circle" title="View entries">
<i class="ph-duotone ph-eye text-lg"></i>
</a>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-sm btn-circle" title="<?= phpb_trans('website-manager.edit') ?>">
<i class="ph-duotone ph-pencil-line text-lg"></i>
</a>
<a href="/ext--form/delete-form?id=<?= $form['id'] ?>" class="btn btn-ghost btn-sm btn-circle text-error" title="<?= phpb_trans('website-manager.remove') ?>">
<i class="ph-duotone ph-trash text-lg"></i>
</a>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[36rem]">
<thead>
<tr>
<th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th class="w-40 text-right"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($forms as $form): ?>
<tr>
<td><span class="badge badge-ghost font-mono"><?= phpb_e($form['id']) ?></span></td>
<td>
<div class="font-medium"><?= phpb_e($form['name']) ?></div>
</td>
<td>
<div class="flex items-center justify-end gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="View entries" aria-label="View entries for <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-eye text-lg" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_trans('website-manager.edit') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<a href="/ext--form/delete-form?id=<?= $form['id'] ?>" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</a>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
+5 -3
View File
@@ -33,20 +33,22 @@ if (isset($_GET['action']) && array_key_exists($_GET['action'], $modules)) $acti
<?php
if ($modules[$activeModule]['showTabs'] === true):
?>
<div class="tabs tabs-boxed bg-base-200/50 mb-6">
<nav class="mb-6 overflow-x-auto" aria-label="Form extension navigation">
<div class="tabs tabs-box w-max min-w-full bg-base-200/50">
<?php
foreach ($modules as $name => $module):
if ($module['inMenu'] === false) continue;
$icon = $module['icon'] ?? 'ph-circle';
?>
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => $name]) ?>">
<i class="ph-duotone <?= $icon ?>"></i>
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" <?= $name === $activeModule ? 'aria-current="page"' : '' ?> href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => $name]) ?>">
<i class="ph-duotone <?= $icon ?>" aria-hidden="true"></i>
<?= $module['label'] ?>
</a>
<?php
endforeach;
?>
</div>
</nav>
<?php
endif;
?>
+225 -40
View File
@@ -9,6 +9,7 @@
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace;
--spacing: 0.25rem;
--container-md: 28rem;
--container-2xl: 42rem;
--text-xs: 0.75rem;
--text-xs--line-height: calc(1 / 0.75);
@@ -24,12 +25,14 @@
--text-3xl--line-height: calc(2.25 / 1.875);
--text-4xl: 2.25rem;
--text-4xl--line-height: calc(2.5 / 2.25);
--text-6xl: 3.75rem;
--text-6xl--line-height: 1;
--font-weight-medium: 500;
--font-weight-semibold: 600;
--font-weight-bold: 700;
--tracking-tight: -0.025em;
--tracking-wide: 0.025em;
--radius-lg: 0.5rem;
--leading-relaxed: 1.625;
--radius-xl: 0.75rem;
--radius-2xl: 1rem;
--default-transition-duration: 150ms;
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
--default-font-family: var(--font-sans);
@@ -185,6 +188,20 @@
}
}
@layer utilities {
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border-width: 0;
}
.static {
position: static;
}
.mx-auto {
margin-inline: auto;
}
@@ -209,8 +226,11 @@
.mb-2 {
margin-bottom: calc(var(--spacing) * 2);
}
.mb-4 {
margin-bottom: calc(var(--spacing) * 4);
.mb-3 {
margin-bottom: calc(var(--spacing) * 3);
}
.mb-5 {
margin-bottom: calc(var(--spacing) * 5);
}
.mb-6 {
margin-bottom: calc(var(--spacing) * 6);
@@ -218,18 +238,36 @@
.ml-1 {
margin-left: var(--spacing);
}
.ml-2 {
margin-left: calc(var(--spacing) * 2);
.line-clamp-3 {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
.flex {
display: flex;
}
.grid {
display: grid;
}
.hidden {
display: none;
}
.table {
display: table;
}
.size-10 {
width: calc(var(--spacing) * 10);
height: calc(var(--spacing) * 10);
}
.size-11 {
width: calc(var(--spacing) * 11);
height: calc(var(--spacing) * 11);
}
.size-14 {
width: calc(var(--spacing) * 14);
height: calc(var(--spacing) * 14);
}
.h-16 {
height: calc(var(--spacing) * 16);
}
@@ -239,9 +277,6 @@
.w-6 {
width: calc(var(--spacing) * 6);
}
.w-12 {
width: calc(var(--spacing) * 12);
}
.w-16 {
width: calc(var(--spacing) * 16);
}
@@ -251,23 +286,59 @@
.w-full {
width: 100%;
}
.w-max {
width: max-content;
}
.max-w-2xl {
max-width: var(--container-2xl);
}
.max-w-72 {
max-width: calc(var(--spacing) * 72);
}
.max-w-md {
max-width: var(--container-md);
}
.min-w-40 {
min-width: calc(var(--spacing) * 40);
}
.min-w-\[36rem\] {
min-width: 36rem;
}
.min-w-\[48rem\] {
min-width: 48rem;
}
.min-w-full {
min-width: 100%;
}
.flex-1 {
flex: 1;
}
.shrink-0 {
flex-shrink: 0;
}
.cursor-grab {
cursor: grab;
}
.cursor-pointer {
cursor: pointer;
}
.flex-col {
flex-direction: column;
}
.flex-col-reverse {
flex-direction: column-reverse;
}
.flex-wrap {
flex-wrap: wrap;
}
.place-items-center {
place-items: center;
}
.items-center {
align-items: center;
}
.justify-between {
justify-content: space-between;
.items-start {
align-items: flex-start;
}
.justify-center {
justify-content: center;
@@ -275,6 +346,9 @@
.justify-end {
justify-content: flex-end;
}
.justify-start {
justify-content: flex-start;
}
.gap-1 {
gap: var(--spacing);
}
@@ -284,6 +358,12 @@
.gap-3 {
gap: calc(var(--spacing) * 3);
}
.gap-4 {
gap: calc(var(--spacing) * 4);
}
.gap-5 {
gap: calc(var(--spacing) * 5);
}
:where(.space-y-1 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(var(--spacing) * var(--tw-space-y-reverse));
@@ -294,27 +374,35 @@
margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-3 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-4 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-5 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-6 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)));
}
.self-start {
align-self: flex-start;
}
.overflow-x-auto {
overflow-x: auto;
}
.rounded {
border-radius: 0.25rem;
.rounded-2xl {
border-radius: var(--radius-2xl);
}
.rounded-full {
border-radius: calc(infinity * 1px);
}
.rounded-lg {
border-radius: var(--radius-lg);
.rounded-xl {
border-radius: var(--radius-xl);
}
.border {
border-style: var(--tw-border-style);
@@ -324,6 +412,14 @@
border-style: var(--tw-border-style);
border-width: 2px;
}
.border-t {
border-top-style: var(--tw-border-style);
border-top-width: 1px;
}
.border-b {
border-bottom-style: var(--tw-border-style);
border-bottom-width: 1px;
}
.border-l-2 {
border-left-style: var(--tw-border-style);
border-left-width: 2px;
@@ -332,27 +428,54 @@
--tw-border-style: dashed;
border-style: dashed;
}
.p-0 {
padding: 0px;
}
.p-2 {
padding: calc(var(--spacing) * 2);
}
.p-3 {
padding: calc(var(--spacing) * 3);
}
.p-4 {
padding: calc(var(--spacing) * 4);
}
.px-0 {
padding-inline: 0px;
}
.px-3 {
padding-inline: calc(var(--spacing) * 3);
}
.px-4 {
padding-inline: calc(var(--spacing) * 4);
}
.px-5 {
padding-inline: calc(var(--spacing) * 5);
}
.py-2 {
padding-block: calc(var(--spacing) * 2);
}
.py-8 {
padding-block: calc(var(--spacing) * 8);
}
.py-16 {
padding-block: calc(var(--spacing) * 16);
.py-10 {
padding-block: calc(var(--spacing) * 10);
}
.pl-4 {
padding-left: calc(var(--spacing) * 4);
.py-12 {
padding-block: calc(var(--spacing) * 12);
}
.pt-4 {
padding-top: calc(var(--spacing) * 4);
}
.pt-5 {
padding-top: calc(var(--spacing) * 5);
}
.pb-4 {
padding-bottom: calc(var(--spacing) * 4);
}
.pb-5 {
padding-bottom: calc(var(--spacing) * 5);
}
.text-center {
text-align: center;
}
.text-right {
text-align: right;
}
.font-mono {
font-family: var(--font-mono);
}
@@ -368,10 +491,6 @@
font-size: var(--text-4xl);
line-height: var(--tw-leading, var(--text-4xl--line-height));
}
.text-6xl {
font-size: var(--text-6xl);
line-height: var(--tw-leading, var(--text-6xl--line-height));
}
.text-lg {
font-size: var(--text-lg);
line-height: var(--tw-leading, var(--text-lg--line-height));
@@ -388,6 +507,10 @@
font-size: var(--text-xs);
line-height: var(--tw-leading, var(--text-xs--line-height));
}
.leading-relaxed {
--tw-leading: var(--leading-relaxed);
line-height: var(--leading-relaxed);
}
.font-bold {
--tw-font-weight: var(--font-weight-bold);
font-weight: var(--font-weight-bold);
@@ -396,21 +519,32 @@
--tw-font-weight: var(--font-weight-medium);
font-weight: var(--font-weight-medium);
}
.font-semibold {
--tw-font-weight: var(--font-weight-semibold);
font-weight: var(--font-weight-semibold);
}
.tracking-\[0\.18em\] {
--tw-tracking: 0.18em;
letter-spacing: 0.18em;
}
.tracking-tight {
--tw-tracking: var(--tracking-tight);
letter-spacing: var(--tracking-tight);
}
.tracking-wide {
--tw-tracking: var(--tracking-wide);
letter-spacing: var(--tracking-wide);
}
.break-words {
overflow-wrap: break-word;
}
.uppercase {
text-transform: uppercase;
}
.shadow {
.shadow-sm {
--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));
box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
.shadow-lg {
--tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));
box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
.transition-colors {
transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
@@ -419,6 +553,52 @@
.active\:cursor-grabbing:active {
cursor: grabbing;
}
@media (width >= 40rem) {
.sm\:ml-2 {
margin-left: calc(var(--spacing) * 2);
}
.sm\:min-w-28 {
min-width: calc(var(--spacing) * 28);
}
.sm\:flex-row {
flex-direction: row;
}
.sm\:items-center {
align-items: center;
}
.sm\:items-end {
align-items: flex-end;
}
.sm\:justify-between {
justify-content: space-between;
}
.sm\:justify-end {
justify-content: flex-end;
}
.sm\:self-center {
align-self: center;
}
.sm\:p-4 {
padding: calc(var(--spacing) * 4);
}
.sm\:p-5 {
padding: calc(var(--spacing) * 5);
}
.sm\:p-6 {
padding: calc(var(--spacing) * 6);
}
.sm\:py-16 {
padding-block: calc(var(--spacing) * 16);
}
.sm\:pl-9 {
padding-left: calc(var(--spacing) * 9);
}
}
@media (width >= 64rem) {
.lg\:p-8 {
padding: calc(var(--spacing) * 8);
}
}
}
@layer theme, base, components, utilities;
@layer theme;
@@ -581,6 +761,10 @@
inherits: false;
initial-value: solid;
}
@property --tw-leading {
syntax: "*";
inherits: false;
}
@property --tw-font-weight {
syntax: "*";
inherits: false;
@@ -659,6 +843,7 @@
*, ::before, ::after, ::backdrop {
--tw-space-y-reverse: 0;
--tw-border-style: solid;
--tw-leading: initial;
--tw-font-weight: initial;
--tw-tracking: initial;
--tw-shadow: 0 0 #0000;
+1
View File
@@ -0,0 +1 @@
(()=>{let e=`Your submission could not be completed. Please try again.`;function t(e,t){e&&(e.hidden=!t,e.classList.toggle(`hidden`,!t))}function n(e){let t=Array.from(e.querySelectorAll(`input[type="checkbox"]`));t.length!==0&&(t[0].required=!t.some(e=>e.checked))}function r(e){let t={},n=Array.from(e.querySelectorAll(`input[name], select[name], textarea[name]`)).filter(e=>!e.matches(`:disabled`)),r=/* @__PURE__ */ new Map;return n.forEach(e=>{e instanceof HTMLInputElement&&[`button`,`submit`,`reset`,`image`].includes(e.type)||(r.has(e.name)||r.set(e.name,[]),r.get(e.name).push(e))}),r.forEach((e,n)=>{let r=e[0];if(r instanceof HTMLInputElement&&r.type===`checkbox`)t[n]=e.filter(e=>e.checked).map(e=>e.value);else if(r instanceof HTMLInputElement&&r.type===`radio`){let r=e.find(e=>e.checked);t[n]=r?r.value:``}else t[n]=r.value}),{fields:t}}function i(e,n){let r=e.querySelector(`[data-form-submit]`),i=e.querySelector(`[data-form-submit-idle]`),a=e.querySelector(`[data-form-submit-busy]`);e.setAttribute(`aria-busy`,String(n)),r&&(r.disabled=n,r.setAttribute(`aria-busy`,String(n))),t(i,!n),t(a,n)}function a(){document.querySelectorAll(`[data-field-type="checkbox"][data-field-required="true"]`).forEach(n)}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,a,{once:!0}):a(),document.addEventListener(`change`,e=>{if(!(e.target instanceof HTMLInputElement)||e.target.type!==`checkbox`)return;let t=e.target.closest(`[data-field-type="checkbox"][data-field-required="true"]`);t&&n(t)}),document.addEventListener(`submit`,async n=>{let a=n.target;if(!(a instanceof HTMLFormElement)||!a.matches(`[data-form-wrapper]`)||(n.preventDefault(),a.dataset.submitting===`true`))return;a.dataset.submitting=`true`;let o=a.parentElement,s=o.querySelector(`[data-form-error]`),c=o.querySelector(`[data-form-success]`);t(s,!1),s&&(s.textContent=``),i(a,!0);try{let n=await fetch(`/ext--form/submit?id=${encodeURIComponent(a.dataset.formId)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r(a))}),i=await n.json();if(!n.ok||!i||!i.success){let t=i&&Array.isArray(i.errors)?i.errors.join(` `):``;throw Error(t||e)}a.hidden=!0,a.classList.add(`hidden`),t(c,!0)}catch(n){s&&(s.textContent=n instanceof Error&&n.message?n.message:e,t(s,!0))}finally{i(a,!1),delete a.dataset.submitting}})})();
+145
View File
@@ -0,0 +1,145 @@
(() => {
const defaultErrorMessage = 'Your submission could not be completed. Please try again.';
function setVisible(element, visible) {
if (!element) {
return;
}
element.hidden = !visible;
element.classList.toggle('hidden', !visible);
}
function updateCheckboxGroupRequired(group) {
const checkboxes = Array.from(group.querySelectorAll('input[type="checkbox"]'));
if (checkboxes.length === 0) {
return;
}
checkboxes[0].required = !checkboxes.some(checkbox => checkbox.checked);
}
function collectFields(form) {
const fields = {};
const controls = Array.from(form.querySelectorAll('input[name], select[name], textarea[name]'))
.filter(control => !control.matches(':disabled'));
const groups = new Map();
controls.forEach(control => {
if (control instanceof HTMLInputElement && ['button', 'submit', 'reset', 'image'].includes(control.type)) {
return;
}
if (!groups.has(control.name)) {
groups.set(control.name, []);
}
groups.get(control.name).push(control);
});
groups.forEach((groupControls, name) => {
const firstControl = groupControls[0];
if (firstControl instanceof HTMLInputElement && firstControl.type === 'checkbox') {
fields[name] = groupControls
.filter(control => control.checked)
.map(control => control.value);
return;
}
if (firstControl instanceof HTMLInputElement && firstControl.type === 'radio') {
const selectedControl = groupControls.find(control => control.checked);
fields[name] = selectedControl ? selectedControl.value : '';
return;
}
fields[name] = firstControl.value;
});
return { fields };
}
function setBusy(form, busy) {
const submitButton = form.querySelector('[data-form-submit]');
const idleContent = form.querySelector('[data-form-submit-idle]');
const busyContent = form.querySelector('[data-form-submit-busy]');
form.setAttribute('aria-busy', String(busy));
if (submitButton) {
submitButton.disabled = busy;
submitButton.setAttribute('aria-busy', String(busy));
}
setVisible(idleContent, !busy);
setVisible(busyContent, busy);
}
function initializeCheckboxGroups() {
document.querySelectorAll('[data-field-type="checkbox"][data-field-required="true"]')
.forEach(updateCheckboxGroupRequired);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeCheckboxGroups, { once: true });
} else {
initializeCheckboxGroups();
}
document.addEventListener('change', event => {
if (!(event.target instanceof HTMLInputElement) || event.target.type !== 'checkbox') {
return;
}
const group = event.target.closest('[data-field-type="checkbox"][data-field-required="true"]');
if (group) {
updateCheckboxGroupRequired(group);
}
});
document.addEventListener('submit', async event => {
const form = event.target;
if (!(form instanceof HTMLFormElement) || !form.matches('[data-form-wrapper]')) {
return;
}
event.preventDefault();
if (form.dataset.submitting === 'true') {
return;
}
form.dataset.submitting = 'true';
const formContainer = form.parentElement;
const errorMessage = formContainer.querySelector('[data-form-error]');
const successMessage = formContainer.querySelector('[data-form-success]');
setVisible(errorMessage, false);
if (errorMessage) {
errorMessage.textContent = '';
}
setBusy(form, true);
try {
const response = await fetch(`/ext--form/submit?id=${encodeURIComponent(form.dataset.formId)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(collectFields(form))
});
const result = await response.json();
if (!response.ok || !result || !result.success) {
const errors = result && Array.isArray(result.errors) ? result.errors.join(' ') : '';
throw new Error(errors || defaultErrorMessage);
}
form.hidden = true;
form.classList.add('hidden');
setVisible(successMessage, true);
} catch (error) {
if (errorMessage) {
errorMessage.textContent = error instanceof Error && error.message
? error.message
: defaultErrorMessage;
setVisible(errorMessage, true);
}
} finally {
setBusy(form, false);
delete form.dataset.submitting;
}
});
})();
@@ -5,117 +5,117 @@ if ($id > 0):
$form = $formRepository->findWithId($id);
$fields = json_decode($form["fields"], true);
$formInstanceId = uniqid("form-$id-");
?>
<div class="max-w-2xl mx-auto">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false, errorMessage: ''}">
<form x-show="!submitted" x-transition:leave x-transition:leave-opacity-0 x-on:submit.prevent="
status = 'busy';
errorMessage = '';
try {
const response = await fetch('/ext--form/submit?id=<?= $id ?>', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
const result = await response.json();
if (!response.ok || !result.success) {
throw new Error((result.errors || []).join(' ') || 'Your submission could not be completed. Please try again.');
}
submitted = true;
} catch (error) {
errorMessage = error.message || 'Your submission could not be completed. Please try again.';
} finally {
status = 'idle';
}
">
<?php foreach ($fields as $field):
<div class="mx-auto w-full max-w-2xl">
<div class="space-y-4">
<form data-form-wrapper data-form-id="<?= phpb_e($id) ?>" aria-busy="false">
<?php foreach ($fields as $fieldIndex => $field):
$fieldName = $field["name"];
$fieldLabel = $field["label"];
$fieldType = $field["type"];
$fieldId = $formInstanceId . "-field-" . (int) $fieldIndex;
$fieldRequired =
isset($field["required"]) && $field["required"];
$fieldOptions = isset($field["options"])
? $field["options"]
: [];
?>
<div class="form-control mb-4">
<label class="label mb-1">
?>
<div class="form-control mb-5">
<?php if ($fieldType === "checkbox" || $fieldType === "radio"): ?>
<fieldset class="space-y-2" data-field-type="<?= phpb_e($fieldType) ?>" data-field-required="<?= $fieldRequired ? "true" : "false" ?>">
<legend class="label mb-1 px-0">
<span class="label-text font-medium">
<?= $fieldLabel ?>
<?= phpb_e($fieldLabel) ?>
<?php if ($fieldRequired): ?>
<span class="text-error ml-1">*</span>
<span class="ml-1 text-error" aria-hidden="true">*</span>
<span class="sr-only">(required)</span>
<?php endif; ?>
</span>
</legend>
<?php else: ?>
<label for="<?= phpb_e($fieldId) ?>" class="label mb-1 px-0">
<span class="label-text font-medium">
<?= phpb_e($fieldLabel) ?>
<?php if ($fieldRequired): ?>
<span class="ml-1 text-error" aria-hidden="true">*</span>
<span class="sr-only">(required)</span>
<?php endif; ?>
</span>
</label>
<?php endif; ?>
<?php if ($fieldType === "select"): ?>
<select x-model="data.fields.<?= $fieldName ?>" class="select select-bordered w-full" <?= $fieldRequired
<select id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" class="select select-bordered w-full" <?= $fieldRequired
? "required"
: "" ?>>
<option value="" disabled selected>Please select</option>
<?php foreach ($fieldOptions as $option): ?>
<option value="<?= $option[
<option value="<?= phpb_e($option[
"value"
] ?>"><?= $option["label"] ?></option>
]) ?>"><?= phpb_e($option["label"]) ?></option>
<?php endforeach; ?>
</select>
<?php elseif ($fieldType === "checkbox"): ?>
<div class="space-y-2">
<?php foreach ($fieldOptions as $option): ?>
<label class="label cursor-pointer gap-3">
<span class="label-text"><?= $option[
"label"
] ?></span>
<input type="checkbox" value="<?= $option[
<?php foreach ($fieldOptions as $optionIndex => $option): ?>
<label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2">
<input type="checkbox" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[
"value"
] ?>" x-model="data.fields.<?= $fieldName ?>" class="checkbox checkbox-sm checkbox-primary" />
]) ?>" <?= $fieldRequired && $optionIndex === 0 ? "required" : "" ?> class="checkbox checkbox-sm checkbox-primary" />
<span class="label-text"><?= phpb_e($option[
"label"
]) ?></span>
</label>
<?php endforeach; ?>
</div>
<?php elseif ($fieldType === "radio"): ?>
<div class="space-y-2">
<?php foreach ($fieldOptions as $option): ?>
<label class="label cursor-pointer gap-3">
<span class="label-text"><?= $option[
"label"
] ?></span>
<input type="radio" name="<?= $fieldName ?>" value="<?= $option[
<?php foreach ($fieldOptions as $optionIndex => $option): ?>
<label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2">
<input type="radio" id="<?= phpb_e($fieldId) ?>-<?= (int) $optionIndex ?>" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[
"value"
] ?>" x-model="data.fields.<?= $fieldName ?>" class="radio radio-sm radio-primary" />
]) ?>" <?= $fieldRequired && $optionIndex === 0 ? "required" : "" ?> class="radio radio-sm radio-primary" />
<span class="label-text"><?= phpb_e($option[
"label"
]) ?></span>
</label>
<?php endforeach; ?>
</div>
<?php elseif ($fieldType === "textarea"): ?>
<textarea x-model="data.fields.<?= $fieldName ?>" class="textarea textarea-bordered w-full" placeholder="<?= $fieldLabel ?>" <?= $fieldRequired
<textarea id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" class="textarea textarea-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired
? "required"
: "" ?> rows="4"></textarea>
<?php else: ?>
<input type="<?= $fieldType ?>" x-model="data.fields.<?= $fieldName ?>" class="input input-bordered w-full" placeholder="<?= $fieldLabel ?>" <?= $fieldRequired
<input id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" type="<?= phpb_e($fieldType) ?>" class="input input-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired
? "required"
: "" ?>>
<?php endif; ?>
<?php if ($fieldType === "checkbox" || $fieldType === "radio"): ?>
</fieldset>
<?php endif; ?>
</div>
<?php
endforeach; ?>
<div class="mt-6">
<button type="submit" class="btn btn-primary w-full" :disabled="status === 'busy'">
<span x-show="status === 'idle'">
<i class="ph-duotone ph-paper-plane-tilt"></i>
<button type="submit" class="btn btn-primary w-full" data-form-submit aria-busy="false">
<span data-form-submit-idle aria-live="polite">
<i class="ph-duotone ph-paper-plane-tilt" aria-hidden="true"></i>
Submit
</span>
<span x-show="status === 'busy'">
<span class="loading loading-spinner loading-sm"></span>
<span data-form-submit-busy class="hidden" hidden role="status" aria-live="polite">
<span class="loading loading-spinner loading-sm" aria-hidden="true"></span>
Sending...
</span>
</button>
</div>
</form>
<div x-show="errorMessage" x-text="errorMessage" class="alert alert-error mt-4" role="alert"></div>
<div x-show="submitted" x-transition:enter x-transition:enter-opacity-0 x-transition:enter-delay-100 class="card bg-base-100 shadow-lg mt-4">
<div data-form-error class="alert alert-error mt-4 shadow-sm hidden" hidden role="alert" aria-live="assertive" aria-atomic="true"></div>
<div data-form-success class="card mt-4 border border-success/30 bg-base-100 shadow-sm hidden" hidden role="status" aria-live="polite">
<div class="card-body items-center text-center">
<div class="w-16 h-16 rounded-full bg-success/20 flex items-center justify-center mb-2">
<i class="ph-duotone ph-check text-3xl text-success"></i>
<div class="mb-2 flex h-16 w-16 items-center justify-center rounded-full bg-success/20">
<i class="ph-duotone ph-check text-3xl text-success" aria-hidden="true"></i>
</div>
<h3 class="card-title text-lg">Thank you!</h3>
<p class="text-base-content/60">Your message has been sent successfully.</p>
@@ -126,10 +126,10 @@ if ($id > 0):
<?php
else:
?>
<div class="form-wrapper max-w-2xl mx-auto">
<div class="card bg-base-200 border-2 border-dashed border-base-300">
<div class="card-body items-center text-center py-8">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30"></i>
<div class="form-wrapper mx-auto w-full max-w-2xl">
<div class="card border-2 border-dashed border-base-300 bg-base-200/50">
<div class="card-body items-center py-8 text-center">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30" aria-hidden="true"></i>
<p class="text-sm text-base-content/50 mt-2">Select a form in the settings</p>
</div>
</div>
+5
View File
@@ -20,6 +20,11 @@ return [
"type" => "style",
"location" => "header",
],
[
"src" => "/assets/dist.js",
"type" => "script",
"location" => "footer",
],
],
"tables" => [
"entries" => [
+405 -1
View File
@@ -1,5 +1,5 @@
{
"name": "dev_plugi-ext-form",
"name": "plugi-ext-form",
"lockfileVersion": 3,
"requires": true,
"packages": {
@@ -7,6 +7,43 @@
"dependencies": {
"@tailwindcss/cli": "^4.3.5",
"tailwindcss": "^4.3.5"
},
"devDependencies": {
"rolldown": "^1.3.3"
}
},
"node_modules/@emnapi/core": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
"integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
"integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@jridgewell/gen-mapping": {
@@ -54,6 +91,38 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
"integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
}
},
"node_modules/@oxc-project/types": {
"version": "0.159.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.159.0.tgz",
"integrity": "sha512-QWjWhxheluOJ82kDHNyps00UvRpQCtI34B5A/SzpgQycUD/79FuvT4I0aQIfE/bdPwKmX4QPftnywFBH6FxJhQ==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@parcel/watcher": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz",
@@ -328,6 +397,287 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.3.tgz",
"integrity": "sha512-K1itOg1Xl50XyjLDa4qQZqaYsfiQbFbFRWXOEOupOsGr3whhm5ed4lgySd6Inohv2TB0+sdU4AxORKuS/TGang==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.3.tgz",
"integrity": "sha512-re+E0E3YSJXjEFzdOvBgkVUev1Gg49ileia04qy+Djn0lIMBr7pnwVOYQ+4vc9XbLClCmMziasqXHM7KTmKNKQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.3.tgz",
"integrity": "sha512-6pMLYsUiQJXPkUj/CG447hOBKtbe+hjWw/wbxe/mucoPKgnLSVRTzey7s0kXfqrjxhDd3gQ2hj6lgUKRumsIzw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-x64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.3.tgz",
"integrity": "sha512-Lz+TskwvhceQgwnP+0ox5ZeL7HDDXHKWVRpOqC1Eo05y6rYyfvvep0msGqC95kQTykXrmGgP6qwJB1NdgNZVhg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.3.tgz",
"integrity": "sha512-sIzqNDbA7GFDXU8k9/vcJyV1p45mCe+xHOLo9qD7gdbTbMlwB+SpnFoP7WSpC2iYdGfOX9pjBxCfViRn/Nu3Jw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.3.tgz",
"integrity": "sha512-HYysnZZ7HD3FM5RIBN6wDMoxtOjw4LS9HhRuQ57MsZt5XGpGRPxVpplvr7vUXRN+9MD8zb6vn1JRP06PXIuMYQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.3.tgz",
"integrity": "sha512-XAyLqWSoEKVc8wsDbCIz5o2sBY6ye+0YByK9ib5QxFReoM1KHyThSHsdUODa1DKNzlEfae+p9QwK62LsVwo6Nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.3.tgz",
"integrity": "sha512-oVyicDPj6vUVFRnuoQS7M2Ab8EkGWoq3a5ntyQqjtZoXfgVykIJqN2IAJSi9q9UyNoQUW0vbBLQSgGtlPJ40Kg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.3.tgz",
"integrity": "sha512-k7aFSWgUoi/X7jCst7UEof7pS5jc5ymD8mT/pdFE+pO1IBBI2+JU5Os4HEDqS/tYhetRggwM7MOiLP3cg1bSBQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.3.tgz",
"integrity": "sha512-D5mxHpr1qIb1Pt5UT+Bm2p6vJ7+VxcxWcxZCYVDFzZwWRq9iLiEg4/ROsaXFQl1O8sDQZZJ55UoRWWMK64uH5w==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.3.tgz",
"integrity": "sha512-nmW1O4BbNEmQI9+KTHbJgbDv0EuyZy64oBnRlMCtLJ8lQMIJ/H/iziQ0g2IUlHEhNrSebGvs9cRrlRj8oEfP+g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.3.tgz",
"integrity": "sha512-ivU4JFHK5nFzrRbzp3+vwYdLj8mFckH4oz3hEl5LH/YeThr9/m2N2vF3NvLevtHq6e0COimgrEVyYTwQhh4ODg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.3.tgz",
"integrity": "sha512-XxZoRIkNZ/7pFgvOA8QJmx3uFjMyVz7zS2/urzlaFffoOGclDvpUAMu3AHKT551E8JBKXLxIjpYxYMdF6Mz9vQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.3.tgz",
"integrity": "sha512-bBl1MB2gF26PSPy3CiDLiv+A6JGI546WbsDR34LfKAywSGeBeQXaDanoDG6QdZDJs53M1QyJir5MTKTu1n4ptA==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "2.0.0-beta.2",
"@emnapi/runtime": "2.0.0-beta.2",
"@napi-rs/wasm-runtime": "1.2.6"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.3.tgz",
"integrity": "sha512-6rZur0hyen4LPhOxWIg7az1YX+Eo8Vvauc0D6lFYGK/QCvN+1XpnB8aFe3jQc/PBUGIReJJnLX3sS8h33/5v7A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.3.tgz",
"integrity": "sha512-Ggzyuq1mN7claruAZH10aiiM1N3LRCoMP5xDXPdU514ulL0D2bksCWgFqEmEM2/pDzEP7Dq+dcv7IH452jtr1w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
"integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
"dev": true,
"license": "MIT"
},
"node_modules/@tailwindcss/cli": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz",
@@ -649,6 +999,17 @@
"node": ">= 20"
}
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -998,6 +1359,41 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/rolldown": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.3.tgz",
"integrity": "sha512-ksB1g74e7haRy02OYm4lOQAlr6sK6hBpAY5R+YC30Gkv4L1COwF6M9umBAYAPxWpGow6Vr+IXtyDjH9fq7A+Zg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.159.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
"rolldown": "bin/cli.mjs"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm-eabi": "1.3.3",
"@rolldown/binding-android-arm64": "1.3.3",
"@rolldown/binding-darwin-arm64": "1.3.3",
"@rolldown/binding-darwin-x64": "1.3.3",
"@rolldown/binding-freebsd-x64": "1.3.3",
"@rolldown/binding-linux-arm-gnueabihf": "1.3.3",
"@rolldown/binding-linux-arm64-gnu": "1.3.3",
"@rolldown/binding-linux-arm64-musl": "1.3.3",
"@rolldown/binding-linux-ppc64-gnu": "1.3.3",
"@rolldown/binding-linux-s390x-gnu": "1.3.3",
"@rolldown/binding-linux-x64-gnu": "1.3.3",
"@rolldown/binding-linux-x64-musl": "1.3.3",
"@rolldown/binding-openharmony-arm64": "1.3.3",
"@rolldown/binding-wasm32-wasi": "1.3.3",
"@rolldown/binding-win32-arm64-msvc": "1.3.3",
"@rolldown/binding-win32-x64-msvc": "1.3.3"
}
},
"node_modules/source-map-js": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
@@ -1025,6 +1421,14 @@
"type": "opencollective",
"url": "https://opencollective.com/webpack"
}
},
"node_modules/tslib": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
"dev": true,
"license": "0BSD",
"optional": true
}
}
}
+7 -1
View File
@@ -1,10 +1,16 @@
{
"type": "module",
"dependencies": {
"@tailwindcss/cli": "^4.3.5",
"tailwindcss": "^4.3.5"
},
"devDependencies": {
"rolldown": "^1.3.3"
},
"scripts": {
"dev": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css --watch",
"build": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css"
"build": "npm run build:js && npm run build:css",
"build:css": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css",
"build:js": "rolldown assets/main.js --file assets/dist.js -m"
}
}
@@ -256,12 +256,21 @@ namespace {
assertSameValue(422, $result['status'], 'Malformed action options must be rejected');
$view = file_get_contents(dirname(__DIR__) . '/blocks/form-wrapper/view.php');
if (strpos($view, '!response.ok || !result.success') === false || strpos($view, 'x-show="errorMessage"') === false) {
$frontendScript = file_get_contents(dirname(__DIR__) . '/assets/main.js');
if (strpos($view, 'data-form-wrapper') === false || preg_match('/\bx-(?:data|model|show|on|transition|text)\b/', $view) === 1) {
throw new \RuntimeException('The public form wrapper must use vanilla JavaScript hooks without Alpine directives.');
}
if (strpos($frontendScript, 'if (!response.ok || !result || !result.success)') === false || strpos($frontendScript, 'setVisible(errorMessage, true)') === false) {
throw new \RuntimeException('The frontend must check the response and expose a retryable error state.');
}
if (preg_match('/if \(!response\.ok \|\| !result\.success\).*?submitted = true;/s', $view) !== 1) {
$responseCheck = strpos($frontendScript, 'if (!response.ok || !result || !result.success)');
$successState = strpos($frontendScript, 'setVisible(successMessage, true)');
if ($successState === false || $responseCheck === false || $responseCheck > $successState) {
throw new \RuntimeException('The frontend may only show its success state after a successful response.');
}
if (strpos($frontendScript, 'finally') === false || strpos($frontendScript, 'setBusy(form, false)') === false) {
throw new \RuntimeException('The frontend must restore its busy state after a submission attempt.');
}
$editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php');
foreach (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) {
+24 -7
View File
@@ -163,9 +163,12 @@ async function buildWebsiteManagerJs() {
);
}
function runTailwindCli({ watch = false } = {}) {
const input = path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/style.css');
const output = path.join(DIST_DIR, 'WebsiteManager.css');
function runTailwindCli({
watch = false,
input = path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/style.css'),
output = path.join(DIST_DIR, 'WebsiteManager.css'),
label = 'WebsiteManager.css',
} = {}) {
const tailwindBin = path.resolve(__dirname, 'node_modules/.bin/tailwindcss');
const args = ['-i', input, '-o', output];
@@ -194,10 +197,10 @@ function runTailwindCli({ watch = false } = {}) {
if (code === 0) {
const duration = (performance.now() - start).toFixed(1);
const size = (fs.statSync(output).size / 1024).toFixed(1);
console.log(` \x1b[32m✓\x1b[0m CSS dist/WebsiteManager.css (${size} kB, ${duration}ms)`);
console.log(` \x1b[32m✓\x1b[0m CSS dist/${label} (${size} kB, ${duration}ms)`);
resolve();
} else {
console.error(`\x1b[31mError compiling Tailwind CSS:\x1b[0m\n${stderr}`);
console.error(`\x1b[31mError compiling ${label}:\x1b[0m\n${stderr}`);
reject(new Error(`Tailwind CLI exited with code ${code}`));
}
});
@@ -215,6 +218,12 @@ async function buildAll() {
await Promise.all([
buildWebsiteManagerJs(),
runTailwindCli({ watch: false }),
runTailwindCli({
watch: false,
input: path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/admin.css'),
output: path.join(DIST_DIR, 'Admin.css'),
label: 'Admin.css',
}),
buildGrapesHead(),
buildGrapesBody(),
buildPageInjectionJs(),
@@ -226,7 +235,15 @@ async function buildAll() {
}
function startWatch() {
const tailwindProcess = runTailwindCli({ watch: true });
const tailwindProcesses = [
runTailwindCli({ watch: true }),
runTailwindCli({
watch: true,
input: path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/admin.css'),
output: path.join(DIST_DIR, 'Admin.css'),
label: 'Admin.css',
}),
];
const srcDir = path.resolve(__dirname, 'src');
console.log(`\x1b[36mWatching for changes in ${srcDir}...\x1b[0m\n`);
@@ -284,7 +301,7 @@ function startWatch() {
const cleanup = () => {
console.log('\nStopping watchers...');
if (tailwindProcess) tailwindProcess.kill();
tailwindProcesses.forEach((tailwindProcess) => tailwindProcess?.kill());
watcher.close();
process.exit(0);
};
+2
View File
@@ -45,6 +45,8 @@ return [
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
],
'primaryKey' => 'id',
'autoIncrement' => 'id',
'uniqueKeys' => [
'page_id' => ['page_id','locale']
],
+2
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sourceRoot":"","sources":["file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/fields.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss"],"names":[],"mappings":"AAMA,eACE,uBACA,SACA,gBAGF,EACE,mCACA,gCACA,2BAGF,kCACE,cAGF,gBACE,eAGF,YACE,gBAGF,OACE,qBACA,YACA,WACA,gBAEA,qBACE,mBAIJ,cACE,kBACA,YACA,WACA,sBACA,cACA,sCAEA,qBACE,kBACA,UAGF,sBACE,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACE,eACA,eACA,gBACA,kBACA,cAGJ,sBACE,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEF,kBACE,+BAIJ,sBACE,gBAGF,eACE,YACA,MACA,yBAEF,aACE,uBAGF,cACE,UAEA,8BACE,uBAGJ,mDAGE,aAEF,eACE,UAEF,YACE,yBACA,mBACA,cAEF,eACE,cAEF,gBACE,cAEF,wBACE,cAEF,iBACE,WACA,wBACA,qBACA,gBAEF,oBACE,UACA,WAEF,0BACE,8BAEF,0BACE,oCACA,kBAEA,gCACE,oCAMJ,cACE,SAEA,0BACE,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACE,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIN,gBACE,QAEF,sCAEE,OACA,wBACA,qBACA,gBACA,MA1Lc,MA2Ld,iBACA,gBACA,cACA,eACA,eACA,gBAEF,wBACE,iBACA,mBACA,yBACA,gBAEA,0CACE,gBAGF,4BACE,YACA,gBAGF,gCACE,mBACA,YAGJ,iCAEE,KAxNc,MA2Nd,4BACE,2BAEF,6BACE,4BAEF,8BACE,4BAOJ,cACE,yBAGA,6DAEE,WAGJ,WACE,yBACA,gBACA,YAEA,uDAGE,YAGF,0BACE,6BAOJ,gBACE,kBACA,gBACA,MAxQc,MAyQd,eACA,mBACA,YACA,YACA,aACA,mBAEA,mCACE,iBAEA,0CACE,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gDACE,qBAKR,gBACE,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAMF,cACE,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACE,kBACA,SACA,SACA,eACA,cAGF,oBACE,mBACA,4BACA,gBACA,YAEA,iCACE,cAKN,WACE,YACA,gBACA,mBACA,WACA,uBAEA,cACE,YAGF,iBACE,yBAGF,wBACE,YACA,gBACA,kBACA,WAEA,4BACE,WAIN,cACE,mBACA,YAEF,sBACE,mBACA,oBAEF,iBACE,gBACA,YACA,aAEA,mBACE,iBACA,gBAGJ,oBACE,mBAEF,6BACE,8BACA,mBAEF,eACE,8BAMF,4BACE,8BAEF,yCACE,oCAEF,wCACE,wDAEF,6HAKE,8BACA,2CACA,iBACA,eACA,mBAEF,sHAGE,8BAEF,gBACE,gBACA,oBAEF,iBACE,aAEF,eACE,iBAMF,2BACE,uCAMF,eACE,cAEF,gBACE,mBAEF,oDAEE,WAEF,oBACE,uBACA,sBAEF,kBACE,mBACA,eACA,mBAEF,yDAEE,kBAEF,+BACE,WAEF,8BACE,iBACA,oBAEF,kCACE,gBAEF,iCACE,mBAEF,eACE,oBAEF,gCACE,gBACA,UAEA,0DACE,kBAEA,gFACE,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGF,8DACE,eACA,iBAQN,wBACE,kBACA,OACA,SACA,OAjgB8B,KAkgB9B,MAngBc,MAogBd,SACA,UACA,mBACA,gBACA,aAEA,yDAEE,OACA,oBACA,mBACA,uBACA,YACA,8BACA,gBACA,cACA,eACA,cACA,qBACA,YACA,8BAEA,qEACE,mBACA,WAEF,iFACE,iBAIJ,uCACE,mBACA,sBAEA,iDACE,aAIJ,uCACE,mBAEF,yCACE,mBChjBJ,WACE,yBAGA,yBACE,sBACA,WAGJ,gBACE,cAEF,kBACE,cAEF,oCACE,cAEA,2CACE,yBACA,WAGJ,mBACE,6BAEF,mBACE,gCAGF,iBACE,qBAEF,sCACE,iBACA,gBACA,oBACA,WAEF,oDACE,yBCxCF,+BACE,mBACA,cAGF,cACE,WACA,cACA,iBAEA,gEAEE,aAEF,2BACE,cAEF,+BACE,yBACA,YACA,gDACA,WAEA,qCACE,yBAMJ,gEAEE,cAGF,+CACE,uCACA,uCAGF,+BACE,yBAEA,2CACE,gBACA,WACA,iBAGF,0CACE,UACA,yBAEA,iDACE,WACA,mBAKN,0CACE,WAEA,gDACE,WChEN,sBACE,aAEF,oBACE,gBACA,cAEF,eACE,aAEF,cACE,2BACA,yBACA,sBACA,qBACA,iBAGF,cACE,qBACA,gBACA,uBACA,gBACA,kBACA,sBACA,yBACA,sBACA,qBACA,iBACA,eACA,gBACA,qBACA,8HACA,WACA,yBACA,yBAIA,yBACE,WACA,WAEF,oCACE,WAKF,2BACE,uCACA,0BAEF,oCACE,cACA,iBHigBJ,qBACE,cACA,eAEA,gCACE,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACE,qBAIJ,sCACE,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGF,0BACE,iBACA,kBACA,eACA,eACA,YACA,6CIxlBF,kCACE,uBAGF,kCACE,aAEF,uEACE,OAGF,mCACE,kBACA,eACA,qDACA,kDACA,2CACA"}
{"version":3,"sourceRoot":"","sources":["file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/fields.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss"],"names":[],"mappings":"AAMA,eACE,uBACA,SACA,gBAGF,EACE,mCACA,gCACA,2BAGF,kCACE,cAGF,gBACE,eAGF,YACE,gBAGF,OACE,qBACA,YACA,WACA,gBAEA,qBACE,mBAIJ,cACE,kBACA,YACA,WACA,sBACA,cACA,sCAEA,qBACE,kBACA,UAGF,sBACE,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACE,eACA,eACA,gBACA,kBACA,cAGJ,sBACE,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEF,kBACE,+BAIJ,sBACE,gBAGF,eACE,YACA,MACA,yBAEF,aACE,uBAGF,cACE,UAEA,8BACE,uBAGJ,mDAGE,aAEF,eACE,UAEF,YACE,yBACA,mBACA,cAEF,eACE,cAEF,gBACE,cAEF,wBACE,cAEF,iBACE,WACA,wBACA,qBACA,gBAEF,oBACE,UACA,WAEF,0BACE,8BAEF,0BACE,oCACA,kBAEA,gCACE,oCAMJ,cACE,SAEA,0BACE,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACE,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIN,gBACE,QAEF,sCAEE,OACA,wBACA,qBACA,gBACA,MA1Lc,MA2Ld,iBACA,gBACA,cACA,eACA,eACA,gBAEF,wBACE,iBACA,mBACA,yBACA,gBAEA,0CACE,gBAGF,4BACE,YACA,gBAGF,gCACE,mBACA,YAGJ,iCAEE,KAxNc,MA2Nd,4BACE,2BAEF,6BACE,4BAEF,8BACE,4BAOJ,cACE,yBAGA,6DAEE,WAGJ,WACE,yBACA,gBACA,YAEA,uDAGE,YAGF,0BACE,6BAOJ,gBACE,kBACA,gBACA,MAxQc,MAyQd,eACA,mBACA,YACA,YACA,aACA,mBAEA,sEACE,iBAEA,oFACE,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gGACE,qBAKR,gBACE,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAMF,cACE,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACE,kBACA,SACA,SACA,eACA,cAGF,oBACE,mBACA,4BACA,gBACA,YAEA,iCACE,cAKN,WACE,YACA,gBACA,mBACA,WACA,uBAEA,cACE,YAGF,iBACE,yBAGF,wBACE,YACA,gBACA,kBACA,WAEA,4BACE,WAIN,cACE,mBACA,YAEF,sBACE,mBACA,oBAEF,iBACE,gBACA,YACA,aAEA,mBACE,iBACA,gBAGJ,oBACE,mBAEF,6BACE,8BACA,mBAEF,eACE,8BAMF,4BACE,8BAEF,yCACE,oCAEF,wCACE,wDAEF,6HAKE,8BACA,2CACA,iBACA,eACA,mBAEF,sHAGE,8BAEF,gBACE,gBACA,oBAEF,iBACE,aAEF,eACE,iBAMF,2BACE,uCAMF,eACE,cAEF,gBACE,mBAEF,oDAEE,WAEF,oBACE,uBACA,sBAEF,kBACE,mBACA,eACA,mBAEF,yDAEE,kBAEF,+BACE,WAEF,8BACE,iBACA,oBAEF,kCACE,gBAEF,iCACE,mBAEF,eACE,oBAEF,gCACE,gBACA,UAEA,0DACE,kBAEA,gFACE,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGF,8DACE,eACA,iBAQN,wBACE,kBACA,OACA,SACA,OAjgB8B,KAkgB9B,MAngBc,MAogBd,SACA,UACA,mBACA,gBACA,aAEA,yDAEE,OACA,oBACA,mBACA,uBACA,YACA,8BACA,gBACA,cACA,eACA,cACA,qBACA,YACA,8BAEA,qEACE,mBACA,WAEF,iFACE,iBAIJ,uCACE,mBACA,sBAEA,iDACE,aAIJ,uCACE,mBAEF,yCACE,mBChjBJ,WACE,yBAGA,yBACE,sBACA,WAGJ,gBACE,cAEF,kBACE,cAEF,oCACE,cAEA,2CACE,yBACA,WAGJ,mBACE,6BAEF,mBACE,gCAGF,iBACE,qBAEF,sCACE,iBACA,gBACA,oBACA,WAEF,oDACE,yBCxCF,+BACE,mBACA,cAGF,cACE,WACA,cACA,iBAEA,gEAEE,aAEF,2BACE,cAEF,+BACE,yBACA,YACA,gDACA,WAEA,qCACE,yBAMJ,gEAEE,cAGF,+CACE,uCACA,uCAGF,+BACE,yBAEA,2CACE,gBACA,WACA,iBAGF,0CACE,UACA,yBAEA,iDACE,WACA,mBAKN,0CACE,WAEA,gDACE,WChEN,sBACE,aAEF,oBACE,gBACA,cAEF,eACE,aAEF,cACE,2BACA,yBACA,sBACA,qBACA,iBAGF,cACE,qBACA,gBACA,uBACA,gBACA,kBACA,sBACA,yBACA,sBACA,qBACA,iBACA,eACA,gBACA,qBACA,8HACA,WACA,yBACA,yBAIA,yBACE,WACA,WAEF,oCACE,WAKF,2BACE,uCACA,0BAEF,oCACE,cACA,iBHigBJ,qBACE,cACA,eAEA,gCACE,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACE,qBAIJ,sCACE,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGF,0BACE,iBACA,kBACA,eACA,eACA,YACA,6CIxlBF,kCACE,uBAGF,kCACE,aAEF,uEACE,OAGF,mCACE,kBACA,eACA,qDACA,kDACA,2CACA"}
+1 -1
View File
File diff suppressed because one or more lines are too long
+26
View File
@@ -33,6 +33,7 @@ return [
'page-create-failed' => 'Die Seite konnte nicht erstellt werden. Prüfen Sie Pflichtfelder, übersetzte Werte, Routen und die Datenbankverbindung und versuchen Sie es erneut.',
'page-updated' => 'Seite aktualisiert',
'page-deleted' => 'Seite gelöscht',
'page-delete-failed' => 'Die Seite konnte nicht gelöscht werden. Versuchen Sie es erneut oder prüfen Sie die Datenbankverbindung.',
'page-type' => 'Seitentyp',
'page-types' => [
'static' => 'Statische Seite',
@@ -40,6 +41,27 @@ return [
],
'target-redirect' => 'Ziel der Weiterleitung',
'files' => 'Dateien',
'quality' => 'Qualitätsprüfungen',
'quality-heading' => 'Qualitätsprüfung der veröffentlichten Website',
'quality-description' => 'Prüft veröffentlichte Seiten auf häufige Barrierefreiheitsprobleme und defekte interne Links oder Uploads.',
'quality-synchronous-note' => 'Die Prüfung läuft in dieser Anfrage. Ergebnisse werden nicht gespeichert.',
'quality-run-scan' => 'Website prüfen',
'quality-running' => 'Veröffentlichte Seiten werden geprüft…',
'quality-awaiting-scan' => 'Starten Sie die Prüfung, um veröffentlichte Seitenrouten und aktive Sprachen zu überprüfen.',
'quality-pages-checked' => 'Seiten-Sprachen geprüft',
'quality-findings-count' => 'Befunde',
'quality-errors-count' => 'Seitenfehler',
'quality-no-findings' => 'In den geprüften Seiten wurden keine Barrierefreiheits- oder internen Linkprobleme gefunden.',
'quality-report' => 'Bericht zur Qualitätsprüfung',
'quality-target' => 'Betroffenes Element oder Ziel',
'quality-severity-warning' => 'Hinweis',
'quality-severity-error' => 'Seitenfehler',
'quality-rule-image-alt' => 'Alternativtext für Bilder',
'quality-rule-form-control-name' => 'Zugänglicher Name des Formularfelds',
'quality-rule-heading-level' => 'Reihenfolge der Überschriftenebenen',
'quality-rule-missing-internal-route' => 'Interne Seitenroute nicht gefunden',
'quality-rule-missing-local-asset' => 'Lokaler Upload nicht gefunden',
'quality-rule-coverage-error' => 'Seite konnte nicht geprüft werden',
'settings' => 'Einstellungen',
'info' => 'Info',
'required' => 'Pflichtfeld',
@@ -71,6 +93,10 @@ return [
'save-page' => 'Speichern',
'view-page' => 'Ansehen',
'go-back' => 'Zurück',
'viewport-selector' => 'Vorschauansicht',
'viewport-desktop' => 'Desktop',
'viewport-tablet' => 'Tablet',
'viewport-mobile' => 'Mobil',
'page' => 'Seite',
'page-content' => 'Seiteninhalte',
'toastr-changes-saved' => 'Änderungen gespeichert',
+26
View File
@@ -33,6 +33,7 @@ return [
'page-create-failed' => 'Page could not be created. Check required fields, localized values, routes, and the database connection, then try again.',
'page-updated' => 'Page successfully updated',
'page-deleted' => 'Page removed',
'page-delete-failed' => 'Page could not be deleted. Try again or check the database connection.',
'page-type' => 'Page type',
'page-types' => [
'static' => 'Static page',
@@ -40,6 +41,27 @@ return [
],
'target-redirect' => 'Target of redirect',
'files' => 'Files',
'quality' => 'Quality checks',
'quality-heading' => 'Published-site quality audit',
'quality-description' => 'Check rendered published pages for common accessibility issues and broken internal links or uploads.',
'quality-synchronous-note' => 'This scan runs in the current request. Results are temporary and are not saved.',
'quality-run-scan' => 'Run site audit',
'quality-running' => 'Checking published pages…',
'quality-awaiting-scan' => 'Run the audit to review published page routes and their active languages.',
'quality-pages-checked' => 'page locales checked',
'quality-findings-count' => 'findings',
'quality-errors-count' => 'page errors',
'quality-no-findings' => 'No accessibility or internal-link findings were detected in the scanned pages.',
'quality-report' => 'Quality audit report',
'quality-target' => 'Affected target',
'quality-severity-warning' => 'Warning',
'quality-severity-error' => 'Page error',
'quality-rule-image-alt' => 'Image alternative text',
'quality-rule-form-control-name' => 'Form control accessible name',
'quality-rule-heading-level' => 'Heading level order',
'quality-rule-missing-internal-route' => 'Missing internal page route',
'quality-rule-missing-local-asset' => 'Missing local upload',
'quality-rule-coverage-error' => 'Page could not be checked',
'settings' => 'Settings',
'info' => 'Info',
'required' => 'Required',
@@ -71,6 +93,10 @@ return [
'save-page' => 'Save',
'view-page' => 'View',
'go-back' => 'Back',
'viewport-selector' => 'Preview viewport',
'viewport-desktop' => 'Desktop',
'viewport-tablet' => 'Tablet',
'viewport-mobile' => 'Mobile',
'page' => 'Page',
'page-content' => 'Page contents',
'toastr-changes-saved' => 'Changes saved',
+26
View File
@@ -32,6 +32,7 @@ return [
'page-created' => 'Sidan har skapats',
'page-updated' => 'Sidan har uppdaterats',
'page-deleted' => 'Sidan har tagits bort',
'page-delete-failed' => 'Sidan kunde inte tas bort. Försök igen eller kontrollera databasanslutningen.',
'page-type' => 'Sidtyp',
'page-types' => [
'static' => 'Statisk sida',
@@ -39,6 +40,27 @@ return [
],
'target-redirect' => 'Mål för omdirigering',
'files' => 'Filer',
'quality' => 'Kvalitetskontroller',
'quality-heading' => 'Kvalitetsgranskning av publicerade sidor',
'quality-description' => 'Kontrollera publicerade sidor efter vanliga tillgänglighetsproblem och trasiga interna länkar eller uppladdningar.',
'quality-synchronous-note' => 'Granskningen körs i den aktuella förfrågan. Resultaten sparas inte.',
'quality-run-scan' => 'Granska webbplatsen',
'quality-running' => 'Kontrollerar publicerade sidor…',
'quality-awaiting-scan' => 'Kör granskningen för att kontrollera publicerade sidrutter och aktiva språk.',
'quality-pages-checked' => 'sidornas språk kontrollerade',
'quality-findings-count' => 'resultat',
'quality-errors-count' => 'sidfel',
'quality-no-findings' => 'Inga tillgänglighetsproblem eller interna länkproblem hittades på de granskade sidorna.',
'quality-report' => 'Kvalitetsrapport',
'quality-target' => 'Berört element eller mål',
'quality-severity-warning' => 'Varning',
'quality-severity-error' => 'Sidfel',
'quality-rule-image-alt' => 'Alternativtext för bild',
'quality-rule-form-control-name' => 'Tillgängligt namn på formulärkontroll',
'quality-rule-heading-level' => 'Rubriknivåernas ordning',
'quality-rule-missing-internal-route' => 'Intern sidrutt saknas',
'quality-rule-missing-local-asset' => 'Lokal uppladdning saknas',
'quality-rule-coverage-error' => 'Sidan kunde inte kontrolleras',
'settings' => 'Inställningar',
'info' => 'Info',
'required' => 'Obligatoriskt',
@@ -70,6 +92,10 @@ return [
'save-page' => 'Spara',
'view-page' => 'Visa',
'go-back' => 'Tillbaka',
'viewport-selector' => 'Förhandsgranskningens vy',
'viewport-desktop' => 'Dator',
'viewport-tablet' => 'Surfplatta',
'viewport-mobile' => 'Mobil',
'page' => 'Sida',
'page-content' => 'Sidinnehåll',
'toastr-changes-saved' => 'Ändringarna har sparats',
@@ -4,4 +4,20 @@ namespace Plugi\Contracts;
interface PageTranslationRepositoryContract
{
/**
* Determine whether a route is already used by another page translation.
*
* @param string $route
* @param mixed|null $excludedPageId
* @return bool
*/
public function routeExists(string $route, $excludedPageId = null): bool;
/**
* Return translations belonging to the given page IDs.
*
* @param array $pageIds
* @return array
*/
public function getForPages(array $pageIds): array;
}
+64 -3
View File
@@ -201,6 +201,35 @@ class DB
}
}
public function primaryKeyExists(string $table, string $column): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
$columnName = phpb_remove_non_alpha_numeric($column);
try {
return ! empty($this->select(
"SELECT 1 FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? AND CONSTRAINT_NAME = 'PRIMARY' LIMIT 1",
[$this->databaseName, $tableName, $columnName]
));
} catch (Exception $e) {
return false;
}
}
public function autoIncrementExists(string $table, string $column): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
$columnName = phpb_remove_non_alpha_numeric($column);
try {
$columns = $this->select(
'SELECT EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?',
[$this->databaseName, $tableName, $columnName]
);
return isset($columns[0]['EXTRA']) && stripos($columns[0]['EXTRA'], 'auto_increment') !== false;
} catch (Exception $e) {
return false;
}
}
public function getDBDefinition() {
$tables = include __DIR__.'/../../config/tables.php';
foreach (Extensions::getConfigs() as $extkey => $config){
@@ -233,6 +262,16 @@ class DB
foreach ($tableDefinition['uniqueKeys'] as $key => $keyDefinition) {
if(!$this->uniqueKeyExists($table, $key)) $diff[$table]['uniqueKeys'][$key] = '`'.implode('`,`', $keyDefinition).'`';
}
if (isset($tableDefinition['primaryKey'])) {
$diff[$table]['primaryKey'] = $this->primaryKeyExists($table, $tableDefinition['primaryKey'])
? null
: $tableDefinition['primaryKey'];
}
if (isset($tableDefinition['autoIncrement'])) {
$diff[$table]['autoIncrement'] = $this->autoIncrementExists($table, $tableDefinition['autoIncrement'])
? null
: $tableDefinition['autoIncrement'];
}
}
}
@@ -241,6 +280,7 @@ class DB
}
public function resolveDiffDB() {
$definitions = $this->getDBDefinition();
$diff = $this->diffDB();
foreach ($diff as $table => $tableDiff) {
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
@@ -248,22 +288,43 @@ class DB
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)");
$this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT");
} elseif (is_array($tableDiff)) {
$tableDefinition = $definitions[$table] ?? ['columns' => [], 'uniqueKeys' => []];
$tableDiff = [
'columns' => $tableDefinition['columns'] ?? [],
'uniqueKeys' => [],
];
foreach ($tableDefinition['uniqueKeys'] ?? [] as $key => $columns) {
$tableDiff['uniqueKeys'][$key] = '`' . implode('`,`', $columns) . '`';
}
}
if (is_array($tableDiff)) {
foreach ($tableDiff['columns'] as $column => $columnDefinition) {
// Validate column name to prevent SQL injection
$sanitizedColumn = phpb_remove_non_alpha_numeric($column);
if (empty($sanitizedColumn)) continue;
// Validate column definition against a safe pattern
if (!preg_match('/^[A-Z\s(),0-9_`]+$/', $columnDefinition)) continue;
if (!is_string($columnDefinition) || !preg_match('/^[A-Z\s(),0-9_`]+$/i', $columnDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
}
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
// Validate key name and definition
$sanitizedKey = phpb_remove_non_alpha_numeric($key);
if (empty($sanitizedKey)) continue;
if (!preg_match('/^[A-Z,`\s_]+$/', $keyDefinition)) continue;
if (!preg_match('/^[A-Z,`\s_]+$/i', $keyDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$sanitizedKey} ($keyDefinition)");
}
if (! empty($tableDiff['primaryKey'])) {
$column = phpb_remove_non_alpha_numeric($tableDiff['primaryKey']);
if (! empty($column)) {
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`{$column}`)");
}
}
if (! empty($tableDiff['autoIncrement'])) {
$column = phpb_remove_non_alpha_numeric($tableDiff['autoIncrement']);
if (! empty($column)) {
$this->query("ALTER TABLE {$tableName} MODIFY `{$column}` int NOT NULL AUTO_INCREMENT");
}
}
}
}
$settingRepository = new SettingRepository;
@@ -1,22 +1,33 @@
<!doctype html>
<html lang="<?= phpb_current_language() ?>">
<html lang="<?= phpb_current_language() ?>" class="plugi-admin-theme">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= phpb_trans("auth.title") ?></title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link href="<?= phpb_asset("WebsiteManager.css") ?>" rel="stylesheet">
<link href="<?= phpb_asset("Admin.css") ?>" rel="stylesheet">
</head>
<body>
<body class="min-h-screen bg-base-200 text-base-content antialiased">
<div class="container p-4">
<?php require __DIR__ . "/" . $viewFile . ".php"; ?>
<main class="relative flex min-h-screen flex-col items-center justify-center gap-7 overflow-hidden px-4 py-10">
<div class="pointer-events-none absolute inset-x-0 top-0 h-2 bg-gradient-to-r from-primary via-secondary to-accent" aria-hidden="true"></div>
<section class="card w-full max-w-md border border-base-300 bg-base-100 shadow-xl shadow-base-content/5">
<div class="card-body gap-6 p-6 sm:p-8">
<a href="<?= phpb_url('website_manager') ?>" class="mx-auto flex items-center gap-3 rounded-box focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-primary">
<span class="grid size-11 place-items-center rounded-2xl bg-primary text-primary-content">
<i class="text-2xl ph-bold ph-brackets-square rotate-90" aria-hidden="true"></i>
</span>
<span class="text-xl font-bold tracking-tight text-base-content">Plugi</span>
</a>
<?php require __DIR__ . "/" . $viewFile . ".php"; ?>
</div>
</section>
<footer class="my-5 pt-5 text-muted text-center text-small">
<p class="mb-1">Powered by <a href="https://github.com/deepDiverPaul/plugi" target="_blank">Plugi Page Builder</a></p>
<footer class="text-center text-sm text-base-content/60">
<p>Powered by <a class="link link-hover" href="https://github.com/deepDiverPaul/plugi" target="_blank" rel="noopener noreferrer">Plugi Page Builder</a></p>
</footer>
</div>
</main>
</body>
</html>
@@ -1,23 +1,33 @@
<div class="py-5 text-center">
<h2><?= phpb_trans('auth.title') ?></h2>
<div class="space-y-1 text-center">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Secure access</p>
<h1 class="text-2xl font-bold tracking-tight text-base-content"><?= phpb_trans('auth.title') ?></h1>
</div>
<form class="login-form mt-3 flex flex-col gap-3 items-center" method="post" action="<?= phpb_url('auth', ['action' => 'login']) ?>">
<form class="login-form flex w-full flex-col gap-4" method="post" action="<?= phpb_url('auth', ['action' => 'login']) ?>">
<?php phpb_csrf_field(); ?>
<?php
if (phpb_flash('message')):
?>
<div class="hidden alert-warning"></div>
<div class="alert alert-<?= phpb_flash('message-type') ?> mb-6">
<i class="text-xl ph-duotone ph-warning"></i>
<div class="hidden alert alert-warning alert-error alert-info alert-success"></div>
<div class="alert alert-<?= phpb_flash('message-type') ?> w-full" role="alert">
<i class="text-xl ph-duotone ph-warning-circle" aria-hidden="true"></i>
<span><?= phpb_flash('message') ?></span>
</div>
<?php
endif;
?>
<input type="text" name="username" class="input input-bordered w-full max-w-xs" placeholder="<?= phpb_trans('auth.username') ?>" required autofocus>
<input type="password" name="password" class="input input-bordered w-full max-w-xs" placeholder="<?= phpb_trans('auth.password') ?>" required>
<label class="form-control w-full gap-2">
<span class="label-text font-medium"><?= phpb_trans('auth.username') ?></span>
<input type="text" name="username" class="input input-bordered w-full" placeholder="<?= phpb_trans('auth.username') ?>" autocomplete="username" required autofocus aria-label="<?= phpb_e(phpb_trans('auth.username')) ?>">
</label>
<label class="form-control w-full gap-2">
<span class="label-text font-medium"><?= phpb_trans('auth.password') ?></span>
<input type="password" name="password" class="input input-bordered w-full" placeholder="<?= phpb_trans('auth.password') ?>" autocomplete="current-password" required aria-label="<?= phpb_e(phpb_trans('auth.password')) ?>">
</label>
<button class="btn btn-outline btn-primary w-full max-w-xs" type="submit"><?= phpb_trans('auth.login-button') ?></button>
<button class="btn btn-primary mt-2 w-full" type="submit">
<?= phpb_trans('auth.login-button') ?>
<i class="ph-bold ph-arrow-right" aria-hidden="true"></i>
</button>
</form>
@@ -8,6 +8,7 @@ use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\Block\BlockAdapter;
use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator;
use Plugi\Modules\GrapesJS\Upload\Uploader;
use Plugi\PageTranslationService;
use Plugi\Repositories\PageRepository;
use Plugi\Repositories\UploadRepository;
use Exception;
@@ -101,14 +102,22 @@ class PageBuilder implements PageBuilderContract
}
break;
case 'renderBlock':
if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) {
$this->renderPageBuilderBlock($page, $_POST['language'], json_decode($_POST['data'], true));
$language = $this->getValidPostedLanguage();
if ($language === null) {
$this->respondToInvalidLanguageRequest();
}
if (isset($_POST['data'])) {
$this->renderPageBuilderBlock($page, $language, json_decode($_POST['data'], true));
exit();
}
break;
case 'renderLanguageVariant':
if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) {
$this->renderLanguageVariant($page, $_POST['language'], json_decode($_POST['data'], true));
$language = $this->getValidPostedLanguage();
if ($language === null) {
$this->respondToInvalidLanguageRequest();
}
if (isset($_POST['data'])) {
$this->renderLanguageVariant($page, $language, json_decode($_POST['data'], true));
exit();
}
break;
@@ -204,8 +213,13 @@ class PageBuilder implements PageBuilderContract
// init variables that should be accessible in the view
$pageBuilder = $this;
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]);
if (! empty($_SESSION['plugi_language'])) {
$pageRenderer->setLanguage($_SESSION['plugi_language']);
$activeLanguages = array_keys(phpb_active_languages());
$currentLanguage = (new PageTranslationService())->resolveLocale($_SESSION['plugi_language'] ?? null, $activeLanguages);
if ($currentLanguage !== null) {
$_SESSION['plugi_language'] = $currentLanguage;
$pageRenderer->setLanguage($currentLanguage);
} else {
unset($_SESSION['plugi_language']);
}
// create an array of theme blocks and theme block settings for in the page builder sidebar
@@ -279,6 +293,9 @@ class PageBuilder implements PageBuilderContract
public function renderLanguageVariant(PageContract $page, string $language, $blockData = [])
{
phpb_set_in_editmode();
if (! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
$this->respondToInvalidLanguageRequest();
}
$_SESSION['plugi_language'] = $language;
$blockData = is_array($blockData) ? $blockData : [];
@@ -291,6 +308,32 @@ class PageBuilder implements PageBuilderContract
]);
}
/**
* Return the requested language only when it is an active locale.
*
* @return string|null
*/
protected function getValidPostedLanguage(): ?string
{
$language = $_POST['language'] ?? null;
if (! is_string($language) || ! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
return null;
}
return $language;
}
/**
* Return a clear client error for an unsupported language request.
*/
protected function respondToInvalidLanguageRequest(): void
{
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['message' => 'Unsupported language.']);
exit();
}
/**
* Update the given page with the given data (an array of html blocks).
*
@@ -5,6 +5,7 @@ namespace Plugi\Modules\GrapesJS;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\Block\BlockRenderer;
use Plugi\PageTranslationService;
use Plugi\ThemeBlock;
use Exception;
use Plugi\Extensions;
@@ -93,9 +94,7 @@ class PageRenderer
}
}
if ($blockKeysAreLanguages) {
if (! in_array($language, $supportedLanguages)) {
$language = $supportedLanguages[0] ?? $language;
}
$language = (new PageTranslationService())->resolveLocale($language, $supportedLanguages) ?? $language;
}
$this->language = $language;
@@ -78,8 +78,12 @@
if (!select) return;
let selectedLanguage = select.value;
window.switchLanguage(selectedLanguage, function() {
activateLanguage(selectedLanguage);
window.switchLanguage(selectedLanguage, function(success) {
if (success) {
activateLanguage(selectedLanguage);
} else {
select.value = window.currentLanguage;
}
});
});
@@ -1,11 +1,16 @@
import { bindViewportSelector } from './viewport-selection.js';
const editorEl = document.querySelector('.gjs-editor');
const editorEl = document.querySelector('.gjs-editor');
const toggleSidebarBtn = document.getElementById('toggle-sidebar');
const sidebarHeader = document.getElementById('sidebar-header');
const sidebarBottomButtons = document.getElementById('sidebar-bottom-buttons');
const panelsEl = document.querySelector('.gjs-pn-panels');
const gjsEl = document.getElementById('gjs');
const viewportSelector = document.getElementById('viewport-select');
if (window.editor) {
bindViewportSelector(window.editor, viewportSelector);
}
if (editorEl && toggleSidebarBtn) {
editorEl.appendChild(toggleSidebarBtn);
@@ -74,7 +74,7 @@
errorMessage = errData.message ? (errorMessage + ': "' + errData.message + '"') : errorMessage;
window.toastr.error(errorMessage);
window.toastr.error(window.translations['toastr-switching-language-failed']);
callback();
callback(false);
window.setWaiting(false);
return;
}
@@ -82,10 +82,10 @@
const responseText = await response.text();
let parsed = JSON.parse(responseText);
window.pageBlocks[newLanguage] = parsed.dynamicBlocks ? parsed.dynamicBlocks : {};
callback();
callback(true);
window.setWaiting(false);
} catch (error) {
callback();
callback(false);
console.error(error);
window.toastr.error(error.message || 'Error');
window.toastr.error(window.translations['toastr-switching-language-failed']);
@@ -95,81 +95,70 @@
};
/**
* Copy new blocks of the current language to the new language or remove old blocks from the new language.
* Copy new shared blocks of the current language to the new language.
*
* @param newLanguage
*/
function applyChangesFromCurrentLanguageToNewLanguage(newLanguage) {
let newLanguageBlocks = window.pageBlocks[newLanguage];
let currentLanguageBlocks = window.pageBlocks[window.currentLanguage];
if (newLanguageBlocks === undefined) {
newLanguageBlocks = currentLanguageBlocks;
} else {
updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks);
// copy missing blocks from the current language to the target language
for (let blockId in currentLanguageBlocks) {
if (newLanguageBlocks[blockId] === undefined) {
newLanguageBlocks[blockId] = currentLanguageBlocks[blockId];
}
}
}
// copy the content of blocks containers of the current language to the blocks containers of the new language
for (let blockId in currentLanguageBlocks) {
let currentBlockHtml = (currentLanguageBlocks[blockId] && currentLanguageBlocks[blockId]['html']) || '';
let newBlockHtml = (newLanguageBlocks[blockId] && newLanguageBlocks[blockId]['html']) || '';
let currDiv = document.createElement("div");
currDiv.innerHTML = currentBlockHtml;
let newDiv = document.createElement("div");
newDiv.innerHTML = newBlockHtml;
let currContainers = currDiv.querySelectorAll("[phpb-blocks-container]");
let newContainers = newDiv.querySelectorAll("[phpb-blocks-container]");
currContainers.forEach((cont, index) => {
if (newContainers[index]) {
newContainers[index].innerHTML = cont.innerHTML;
}
});
newLanguageBlocks[blockId]['html'] = newDiv.innerHTML;
}
window.pageBlocks[newLanguage] = newLanguageBlocks;
const currentLanguageBlocks = window.pageBlocks[window.currentLanguage] || {};
window.pageBlocks[newLanguage] = window.synchronizePageBlockVariants(
currentLanguageBlocks,
window.pageBlocks[newLanguage] || {}
);
}
/**
* Replace phpb-blocks-container html snippets if a block of the current language already exists in the target language.
* This ensures all child blocks are present for all languages and they remain in the same order
* Synchronize shared block structure without replacing existing locale-specific block data.
*/
function updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks) {
for (let blockId in currentLanguageBlocks) {
// skip if the parent block does not yet exist in the target language
if (newLanguageBlocks[blockId] === undefined) {
continue;
window.synchronizePageBlockVariants = function(sourceBlocks, targetBlocks) {
sourceBlocks = sourceBlocks && typeof sourceBlocks === 'object' ? sourceBlocks : {};
targetBlocks = targetBlocks && typeof targetBlocks === 'object' && !Array.isArray(targetBlocks) ? targetBlocks : {};
Object.keys(sourceBlocks).forEach(blockId => {
const sourceBlock = sourceBlocks[blockId];
const targetBlock = targetBlocks[blockId];
if (! targetBlock || typeof targetBlock !== 'object') {
targetBlocks[blockId] = JSON.parse(JSON.stringify(sourceBlock));
return;
}
for (let subBlockId in currentLanguageBlocks[blockId].blocks) {
let updatedSubBlock = currentLanguageBlocks[blockId].blocks[subBlockId];
let oldSubBlock = newLanguageBlocks[blockId].blocks[subBlockId];
if (! updatedSubBlock || ! oldSubBlock) {
continue;
}
let updatedSubBlockMatches = updatedSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g);
let oldSubBlockMatches = oldSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g);
if (! updatedSubBlockMatches || ! oldSubBlockMatches) {
continue;
}
for (let i = 0; i < updatedSubBlockMatches.length; i++) {
newLanguageBlocks[blockId].blocks[subBlockId].html =
newLanguageBlocks[blockId].blocks[subBlockId].html.replace(oldSubBlockMatches[i], updatedSubBlockMatches[i]);
}
if (typeof sourceBlock?.html === 'string' && typeof targetBlock.html === 'string') {
targetBlock.html = synchronizeBlockContainers(sourceBlock.html, targetBlock.html);
}
if (sourceBlock?.blocks && typeof sourceBlock.blocks === 'object') {
targetBlock.blocks = window.synchronizePageBlockVariants(sourceBlock.blocks, targetBlock.blocks || {});
}
});
return targetBlocks;
};
/**
* Copy only shared child structure from the source language into existing block containers.
*/
function synchronizeBlockContainers(sourceHtml, targetHtml) {
if (! sourceHtml.includes('phpb-blocks-container')) {
return targetHtml;
}
const sourceElement = document.createElement('div');
sourceElement.innerHTML = sourceHtml;
const targetElement = document.createElement('div');
targetElement.innerHTML = targetHtml;
const sourceContainers = sourceElement.querySelectorAll('[phpb-blocks-container]');
const targetContainers = targetElement.querySelectorAll('[phpb-blocks-container]');
sourceContainers.forEach((sourceContainer, index) => {
if (targetContainers[index]) {
targetContainers[index].innerHTML = sourceContainer.innerHTML;
} else {
targetElement.appendChild(sourceContainer.cloneNode(true));
}
});
return targetElement.innerHTML;
}
/**
@@ -0,0 +1,11 @@
export function bindViewportSelector(editor, selector) {
if (!editor || typeof editor.setDevice !== 'function' || !selector || typeof selector.addEventListener !== 'function') {
return;
}
selector.addEventListener('change', function() {
if (selector.value) {
editor.setDevice(selector.value);
}
});
}
@@ -270,7 +270,7 @@ html, body, #gjs {
display: flex;
align-items: center;
#language-selector {
#language-selector, #viewport-selector {
margin-left: auto;
select {
@@ -601,4 +601,4 @@ html, body, #gjs {
border: none;
transition: background-color 0.15s ease-in-out;
}
}
}
@@ -10,6 +10,13 @@ return [
'autoload' => false,
'autosave' => false
],
'deviceManager' => [
'devices' => [
['name' => 'Desktop', 'width' => ''],
['name' => 'Tablet', 'width' => '768px', 'widthMedia' => '992px'],
['name' => 'Mobile', 'width' => '375px', 'widthMedia' => '480px'],
],
],
'canvasCss' => 'body {height: auto;}', // prevent scrollbar jump on pasting in CKEditor
'assetManager' => [
'upload' => phpb_url('pagebuilder', ['action' => 'upload', 'page' => $page->getId()]),
@@ -18,13 +18,6 @@
<script type="text/javascript" src="<?= phpb_asset('pagebuilder/grapesjs-touch-v0.1.1.min.js') ?>"></script>
<script type="text/javascript">
<?php
$currentLanguage = in_array(phpb_config('general.language'), phpb_active_languages()) ?
phpb_config('general.language') : array_keys(phpb_active_languages())[0];
if (! empty($_SESSION['plugi_language'])) {
$currentLanguage = $_SESSION['plugi_language'];
}
?>
window.languages = <?= json_encode(phpb_active_languages()) ?>;
window.currentLanguage = <?= json_encode($currentLanguage) ?>;
window.translations = <?= json_encode(phpb_trans('pagebuilder')) ?>;
@@ -110,12 +103,12 @@ require __DIR__ . '/grapesjs/trait-manager.php';
<button id="toggle-sidebar" class="btn btn-sm btn-ghost">
<i class="fa fa-bars"></i>
</button>
<div id="sidebar-header" class="flex items-center justify-between px-2">
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 px-2">
<?php
if (sizeof(phpb_active_languages()) > 1):
?>
<div id="language-selector" class="ml-auto">
<select class="select select-bordered select-xs text-xs">
<div id="language-selector">
<select class="select select-xs w-24 text-xs">
<?php
foreach (phpb_active_languages() as $languageCode => $languageTranslation):
?>
@@ -130,6 +123,14 @@ require __DIR__ . '/grapesjs/trait-manager.php';
<?php
endif;
?>
<div id="viewport-selector" class="ml-auto">
<label class="sr-only" for="viewport-select"><?= phpb_trans('pagebuilder.viewport-selector') ?></label>
<select id="viewport-select" class="select select-xs w-28 text-xs" aria-label="<?= phpb_e(phpb_trans('pagebuilder.viewport-selector')) ?>">
<option value="Desktop"><?= phpb_trans('pagebuilder.viewport-desktop') ?></option>
<option value="Tablet"><?= phpb_trans('pagebuilder.viewport-tablet') ?></option>
<option value="Mobile"><?= phpb_trans('pagebuilder.viewport-mobile') ?></option>
</select>
</div>
</div>
<div id="sidebar-bottom-buttons" class="flex items-center justify-between">
@@ -0,0 +1,437 @@
<?php
namespace Plugi\Modules\WebsiteManager;
use DOMDocument;
use DOMElement;
use DOMXPath;
use RuntimeException;
class SiteQualityAnalyzer
{
protected $routes;
protected $assets;
protected $baseUrl;
protected $basePath;
protected $uploadsPath;
public function __construct(array $routes, array $assets, ?string $baseUrl = null, ?string $uploadsUrl = null)
{
$this->baseUrl = $baseUrl ?? ($_ENV['BASE_URL'] ?? '');
$this->basePath = $this->normalizePath(rawurldecode(parse_url($this->baseUrl, PHP_URL_PATH) ?: ''));
$uploadsUrl = $uploadsUrl ?? (function_exists('phpb_config') ? phpb_config('general.uploads_url') : '/uploads');
$uploadsPath = $this->normalizePath(rawurldecode((string) $uploadsUrl));
$this->uploadsPath = $this->stripBasePath($uploadsPath) ?? $uploadsPath;
$this->routes = [];
foreach ($routes as $route) {
if (is_string($route) && trim($route) !== '') {
$this->routes[$this->normalizePath(rawurldecode($route))] = true;
}
}
$this->assets = [];
foreach ($assets as $asset) {
if (is_string($asset) && trim($asset) !== '') {
$assetPath = $this->normalizeInventoryPath($asset);
if ($assetPath !== null) {
$this->assets[$assetPath] = true;
}
}
}
}
/**
* Inspect rendered page markup and return actionable findings.
*/
public function analyze(string $html, string $pageRoute = '/'): array
{
if (! class_exists(DOMDocument::class)) {
throw new RuntimeException('The PHP DOM extension is required to inspect rendered markup.');
}
$document = new DOMDocument();
$previousErrorMode = libxml_use_internal_errors(true);
libxml_clear_errors();
$loaded = $document->loadHTML('<?xml encoding="UTF-8">' . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_HTML_NODEFDTD);
$parseErrors = libxml_get_errors();
libxml_clear_errors();
libxml_use_internal_errors($previousErrorMode);
if (! $loaded) {
throw new RuntimeException('The rendered page markup could not be parsed.');
}
foreach ($parseErrors as $parseError) {
if ($parseError->level === LIBXML_ERR_FATAL) {
throw new RuntimeException('The rendered page markup could not be parsed.');
}
}
$xpath = new DOMXPath($document);
$findings = array_merge(
$this->findMissingImageAlternatives($xpath),
$this->findUnnamedFormControls($xpath),
$this->findSkippedHeadingLevels($xpath),
$this->findBrokenLinks($xpath, $pageRoute)
);
return $findings;
}
private function findMissingImageAlternatives(DOMXPath $xpath): array
{
$findings = [];
foreach ($xpath->query('//img[not(@alt)]') as $image) {
if (! ($image instanceof DOMElement)) {
continue;
}
$target = 'img';
if ($image->hasAttribute('src') && trim($image->getAttribute('src')) !== '') {
$target .= '[src="' . trim($image->getAttribute('src')) . '"]';
}
$findings[] = [
'rule' => 'image-alt',
'severity' => 'warning',
'explanation' => 'Add an alt attribute that describes the image, or use an empty alt attribute when the image is decorative.',
'target' => $target,
];
}
return $findings;
}
private function findUnnamedFormControls(DOMXPath $xpath): array
{
$idText = [];
foreach ($xpath->query('//*[@id]') as $element) {
if ($element instanceof DOMElement) {
$idText[$element->getAttribute('id')] = $this->hasText($element->textContent);
}
}
$findings = [];
foreach ($xpath->query('//input[not(translate(@type,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")="hidden")] | //select | //textarea | //button') as $control) {
if (! ($control instanceof DOMElement) || $this->hasAccessibleName($control, $xpath, $idText)) {
continue;
}
$tag = strtolower($control->tagName);
$target = $tag;
if ($control->hasAttribute('id') && trim($control->getAttribute('id')) !== '') {
$target .= '#' . trim($control->getAttribute('id'));
} elseif ($control->hasAttribute('name') && trim($control->getAttribute('name')) !== '') {
$target .= '[name="' . trim($control->getAttribute('name')) . '"]';
}
$findings[] = [
'rule' => 'form-control-name',
'severity' => 'warning',
'explanation' => 'Give this form control an accessible name using a visible label, aria-label, or aria-labelledby.',
'target' => $target,
];
}
return $findings;
}
private function hasAccessibleName(DOMElement $control, DOMXPath $xpath, array $idText): bool
{
foreach (['aria-label', 'title'] as $attribute) {
if ($control->hasAttribute($attribute) && $this->hasText($control->getAttribute($attribute))) {
return true;
}
}
if ($control->hasAttribute('aria-labelledby')) {
foreach (preg_split('/\s+/', trim($control->getAttribute('aria-labelledby'))) as $labelId) {
if ($labelId !== '' && ! empty($idText[$labelId])) {
return true;
}
}
}
if ($control->tagName === 'button' && $this->hasText($control->textContent)) {
return true;
}
if ($control->tagName === 'input') {
$type = strtolower($control->getAttribute('type'));
if ($type === 'image' && $this->hasText($control->getAttribute('alt'))) {
return true;
}
if (in_array($type, ['submit', 'reset'], true)) {
return true;
}
if (in_array($type, ['button', 'submit', 'reset'], true) && $this->hasText($control->getAttribute('value'))) {
return true;
}
}
if ($control->hasAttribute('id')) {
$controlId = $control->getAttribute('id');
foreach ($xpath->query('//label[@for]') as $label) {
if ($label instanceof DOMElement
&& $label->getAttribute('for') === $controlId
&& $this->hasText($label->textContent)) {
return true;
}
}
}
for ($parent = $control->parentNode; $parent !== null; $parent = $parent->parentNode) {
if ($parent instanceof DOMElement && strtolower($parent->tagName) === 'label' && $this->hasText($parent->textContent)) {
return true;
}
}
return false;
}
private function findSkippedHeadingLevels(DOMXPath $xpath): array
{
$findings = [];
$previousLevel = null;
foreach ($xpath->query('//h1 | //h2 | //h3 | //h4 | //h5 | //h6') as $heading) {
if (! ($heading instanceof DOMElement)) {
continue;
}
$level = (int) substr(strtolower($heading->tagName), 1);
if ($previousLevel !== null && $level > $previousLevel + 1) {
$findings[] = [
'rule' => 'heading-level',
'severity' => 'warning',
'explanation' => sprintf('The heading level jumps from h%d to h%d; use the intervening heading level.', $previousLevel, $level),
'target' => 'h' . $level,
];
}
$previousLevel = $level;
}
return $findings;
}
private function findBrokenLinks(DOMXPath $xpath, string $pageRoute): array
{
$findings = [];
foreach ($xpath->query('//a[@href] | //area[@href]') as $link) {
if (! ($link instanceof DOMElement)) {
continue;
}
$url = trim($link->getAttribute('href'));
$path = $this->resolveInternalPath($url, $pageRoute);
if ($path === null) {
continue;
}
if ($this->isUploadsPath($path)) {
if (! isset($this->assets[$path])) {
$findings[] = [
'rule' => 'missing-local-asset',
'severity' => 'warning',
'explanation' => 'This link points to a site upload that is not present in the configured public uploads inventory.',
'target' => $url,
];
}
} elseif (! $this->routeExists($path)) {
$findings[] = [
'rule' => 'missing-internal-route',
'severity' => 'warning',
'explanation' => 'This same-site link does not match a published page route.',
'target' => $url,
];
}
}
foreach ($xpath->query('//img[@src] | //script[@src] | //iframe[@src] | //source[@src] | //audio[@src] | //video[@src] | //track[@src] | //input[@src] | //link[@href] | //video[@poster]') as $assetElement) {
if (! ($assetElement instanceof DOMElement)) {
continue;
}
$attribute = $assetElement->hasAttribute('src') ? 'src' : ($assetElement->hasAttribute('poster') ? 'poster' : 'href');
$url = trim($assetElement->getAttribute($attribute));
$path = $this->resolveInternalPath($url, $pageRoute);
if ($path !== null && $this->isUploadsPath($path) && ! isset($this->assets[$path])) {
$findings[] = [
'rule' => 'missing-local-asset',
'severity' => 'warning',
'explanation' => 'This element references a site upload that is not present in the configured public uploads inventory.',
'target' => $url,
];
}
}
return $findings;
}
private function resolveInternalPath(string $url, string $pageRoute): ?string
{
if ($url === '' || str_starts_with($url, '#')) {
return null;
}
$parts = parse_url($url);
if ($parts === false) {
return null;
}
$scheme = strtolower($parts['scheme'] ?? '');
if ($scheme !== '' && ! in_array($scheme, ['http', 'https'], true)) {
return null;
}
if (isset($parts['host']) && ! $this->isSameSiteHost($parts['host'], $parts['port'] ?? null)) {
return null;
}
$path = $parts['path'] ?? '';
if ($path === '') {
return $this->normalizePath(rawurldecode($pageRoute));
}
$path = rawurldecode($path);
if (! str_starts_with($path, '/')) {
$currentPath = $this->normalizePath(rtrim($this->basePath, '/') . '/' . ltrim(rawurldecode($pageRoute), '/'));
$currentDirectory = substr($currentPath, 0, (int) strrpos($currentPath, '/'));
$path = $this->normalizePath($currentDirectory . '/' . $path);
return $this->toAppPath($path);
}
$path = $this->normalizePath($path);
return $this->toAppPath($path);
}
private function normalizeInventoryPath(string $asset): ?string
{
$parts = parse_url($asset);
if ($parts === false) {
return null;
}
if (isset($parts['host']) && ! $this->isSameSiteHost($parts['host'], $parts['port'] ?? null)) {
return null;
}
$path = rawurldecode($parts['path'] ?? '');
if ($path === '') {
return null;
}
$path = $this->normalizePath($path);
$appRelativePath = $this->stripBasePath($path);
return $appRelativePath ?? $path;
}
private function isSameSiteHost(string $host, ?int $port): bool
{
$base = parse_url($this->baseUrl);
if (! isset($base['host']) || strtolower($host) !== strtolower($base['host'])) {
return false;
}
if ($port === null) {
return true;
}
$basePort = $base['port'] ?? (($base['scheme'] ?? '') === 'https' ? 443 : 80);
return $port === $basePort;
}
private function stripBasePath(string $path): ?string
{
if ($this->basePath === '/' || $this->basePath === '') {
return $path;
}
if ($path === $this->basePath) {
return '/';
}
if (str_starts_with($path, rtrim($this->basePath, '/') . '/')) {
return $this->normalizePath(substr($path, strlen(rtrim($this->basePath, '/'))));
}
return null;
}
private function toAppPath(string $path): string
{
$appPath = $this->stripBasePath($path);
if ($appPath !== null) {
return $appPath;
}
return $this->basePath === '' || $this->basePath === '/'
? $path
: '/__outside_app_base__' . $path;
}
private function normalizePath(string $path): string
{
$segments = [];
foreach (explode('/', str_replace('\\', '/', $path)) as $segment) {
if ($segment === '' || $segment === '.') {
continue;
}
if ($segment === '..') {
if (! empty($segments)) {
array_pop($segments);
}
continue;
}
$segments[] = $segment;
}
return '/' . implode('/', $segments);
}
private function isUploadsPath(string $path): bool
{
return $path === $this->uploadsPath
|| str_starts_with($path, rtrim($this->uploadsPath, '/') . '/');
}
private function routeExists(string $path): bool
{
if (isset($this->routes[$path])) {
return true;
}
$pathSegments = $this->pathSegments($path);
foreach (array_keys($this->routes) as $route) {
$routeSegments = $this->pathSegments($route);
$hasWildcard = end($routeSegments) === '*';
if ((! $hasWildcard && count($routeSegments) !== count($pathSegments))
|| ($hasWildcard && count($pathSegments) < count($routeSegments) - 1)) {
continue;
}
foreach ($routeSegments as $index => $routeSegment) {
if ($routeSegment === '*') {
return true;
}
if (preg_match('/^\{[^{}]+\}$/', $routeSegment) === 1) {
continue;
}
if (! isset($pathSegments[$index]) || $pathSegments[$index] !== $routeSegment) {
continue 2;
}
}
return true;
}
return false;
}
private function pathSegments(string $path): array
{
$trimmedPath = trim($path, '/');
return $trimmedPath === '' ? [] : explode('/', $trimmedPath);
}
private function hasText(?string $text): bool
{
return trim(preg_replace('/\s+/u', ' ', (string) $text)) !== '';
}
}
@@ -0,0 +1,195 @@
<?php
namespace Plugi\Modules\WebsiteManager;
use Throwable;
class SiteQualityCheckService
{
protected $pageRepository;
protected $translationRepository;
protected $uploadRepository;
protected $renderPage;
protected $pageBuilder;
public function __construct($pageRepository = null, $translationRepository = null, $uploadRepository = null, ?callable $renderPage = null)
{
$this->pageRepository = $pageRepository;
$this->translationRepository = $translationRepository;
$this->uploadRepository = $uploadRepository;
$this->renderPage = $renderPage;
}
/**
* Audit canonical pages in every active language and return a transient report.
*/
public function run(): array
{
$pageRepository = $this->pageRepository ?? new \Plugi\Repositories\PageRepository();
$translationRepository = $this->translationRepository ?? new \Plugi\Repositories\PageTranslationRepository();
$pages = $pageRepository->getAll();
$pagesById = [];
foreach ($pages as $page) {
$pageId = $this->getPageId($page);
if ($pageId !== null) {
$pagesById[(string) $pageId] = $page;
}
}
$activeLanguages = function_exists('phpb_active_languages') ? array_keys(phpb_active_languages()) : [];
$translationForeignKey = function_exists('phpb_config')
? (phpb_config('page.translation.foreign_key') ?: 'page_id')
: 'page_id';
$translationsByPage = [];
$routes = [];
if (! empty($pagesById)) {
foreach ($translationRepository->getForPages(array_keys($pagesById)) as $translation) {
$pageId = $this->readValue($translation, $translationForeignKey);
$locale = $this->readValue($translation, 'locale');
$route = $this->readValue($translation, 'route');
if ($pageId === null || ! isset($pagesById[(string) $pageId])
|| ! is_string($locale) || ! in_array($locale, $activeLanguages, true)
|| ! is_string($route) || trim($route) === '') {
continue;
}
$translationsByPage[(string) $pageId][$locale] = $route;
$routes[] = $route;
}
}
$uploadsUrl = function_exists('phpb_config') ? (phpb_config('general.uploads_url') ?: '/uploads') : '/uploads';
$analyzer = new SiteQualityAnalyzer(
$routes,
$this->getVerifiedAssetUrls($uploadsUrl),
$_ENV['BASE_URL'] ?? '',
$uploadsUrl
);
$report = [
'pages_checked' => 0,
'findings' => [],
'errors' => [],
];
foreach ($translationsByPage as $pageId => $localizedRoutes) {
$pageId = (string) $pageId;
$page = $pagesById[$pageId];
foreach ($localizedRoutes as $locale => $route) {
$report['pages_checked']++;
try {
$html = $this->render($page, $locale);
foreach ($analyzer->analyze($html, $route) as $finding) {
$report['findings'][] = $this->addPageContext($finding, $page, $pageId, $locale, $route);
}
} catch (Throwable $exception) {
$report['errors'][] = [
'page_id' => $pageId,
'page_name' => $this->getPageName($page),
'route' => $route,
'locale' => $locale,
'rule' => 'coverage-error',
'severity' => 'error',
'explanation' => 'This page could not be inspected: ' . $exception->getMessage(),
'target' => $route,
];
}
}
}
return $report;
}
private function render($page, string $locale): string
{
if ($this->renderPage !== null) {
$html = call_user_func($this->renderPage, $page, $locale);
} else {
if ($this->pageBuilder === null) {
$this->pageBuilder = function_exists('phpb_instance') ? phpb_instance('pagebuilder') : null;
}
if (! is_object($this->pageBuilder) || ! method_exists($this->pageBuilder, 'renderPage')) {
throw new \RuntimeException('The configured page renderer is unavailable.');
}
$html = $this->pageBuilder->renderPage($page, $locale);
}
if (! is_string($html)) {
throw new \RuntimeException('The page renderer did not return HTML.');
}
return $html;
}
private function getVerifiedAssetUrls(string $uploadsUrl): array
{
$uploadRepository = $this->uploadRepository ?? new \Plugi\Repositories\UploadRepository();
$configuredUploadFolder = function_exists('phpb_config') ? phpb_config('storage.uploads_folder') : null;
$uploadRoot = is_string($configuredUploadFolder) ? realpath($configuredUploadFolder) : false;
if ($uploadRoot === false || ! is_dir($uploadRoot)) {
return [];
}
$assets = [];
foreach ($uploadRepository->getAll() as $upload) {
$serverFile = $this->readValue($upload, 'server_file');
$publicId = $this->readValue($upload, 'public_id');
$originalFile = $this->readValue($upload, 'original_file');
if (! is_string($serverFile) || ! is_string($publicId) || ! is_string($originalFile)) {
continue;
}
$resolvedFile = realpath($uploadRoot . DIRECTORY_SEPARATOR . ltrim($serverFile, '/\\'));
if ($resolvedFile === false || ! is_file($resolvedFile)
|| ! str_starts_with($resolvedFile, rtrim($uploadRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)) {
continue;
}
$encodedPublicId = implode('/', array_map('rawurlencode', explode('/', $publicId)));
$encodedOriginalFile = implode('/', array_map('rawurlencode', explode('/', $originalFile)));
$assets[] = rtrim($uploadsUrl, '/') . '/' . $encodedPublicId . '/' . $encodedOriginalFile;
}
return $assets;
}
private function addPageContext(array $finding, $page, string $pageId, string $locale, string $route): array
{
return array_merge([
'page_id' => $pageId,
'page_name' => $this->getPageName($page),
'route' => $route,
'locale' => $locale,
], $finding);
}
private function getPageId($page)
{
if (is_object($page) && method_exists($page, 'getId')) {
return $page->getId();
}
return $this->readValue($page, 'id');
}
private function getPageName($page): string
{
if (is_object($page) && method_exists($page, 'getName')) {
return (string) $page->getName();
}
return (string) ($this->readValue($page, 'name') ?? '');
}
private function readValue($record, string $key)
{
if (is_array($record)) {
return $record[$key] ?? null;
}
if (is_object($record) && method_exists($record, 'get')) {
return $record->get($key);
}
if (is_object($record) && isset($record->{$key})) {
return $record->{$key};
}
return null;
}
}
@@ -5,9 +5,9 @@ namespace Plugi\Modules\WebsiteManager;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\WebsiteManagerContract;
use Plugi\Extensions;
use Plugi\PageTranslationService;
use Plugi\Repositories\MenuRepository;
use Plugi\Repositories\PageRepository;
use Plugi\Repositories\PageTranslationRepository;
use Plugi\Repositories\SettingRepository;
use Plugi\Repositories\UploadRepository;
@@ -26,6 +26,16 @@ class WebsiteManager implements WebsiteManagerContract
exit();
}
if ($route === 'quality' && $action === 'scan' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
if (! function_exists('phpb_validate_csrf') || ! phpb_validate_csrf()) {
http_response_code(403);
die('Invalid CSRF token. Please refresh the page and try again.');
}
$_GET['tab'] = 'quality';
$this->renderQualityChecks((new SiteQualityCheckService())->run());
exit();
}
if ($route === 'settings') {
if ($action === 'renderBlockThumbs') {
$this->renderBlockThumbs();
@@ -127,7 +137,12 @@ class WebsiteManager implements WebsiteManagerContract
public function handleDestroy(PageContract $page)
{
$pageRepository = new PageRepository;
$pageRepository->destroy($page->getId());
if (! $pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'error',
'message' => phpb_trans('website-manager.page-delete-failed')
]);
}
phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'success',
'message' => phpb_trans('website-manager.page-deleted')
@@ -194,8 +209,8 @@ class WebsiteManager implements WebsiteManagerContract
return ($a->getRoute() < $b->getRoute()) ? -1 : 1;
});
$pageTranslationRepository = new PageTranslationRepository;
$pageTranslations = $pageTranslationRepository->getAll();
$activeLanguages = phpb_active_languages();
$pageTranslationCoverage = (new PageTranslationService())->getPageCoverage($pages, $activeLanguages);
$filesRepository = new UploadRepository;
$files = $filesRepository->getAll();
@@ -218,6 +233,15 @@ class WebsiteManager implements WebsiteManagerContract
require __DIR__ . '/resources/layouts/master.php';
}
/**
* Render the quality-check tab with an optional transient report.
*/
public function renderQualityChecks(?array $qualityReport = null)
{
$viewFile = 'overview';
require __DIR__ . '/resources/layouts/master.php';
}
/**
* Render the website manager page settings (add/edit page form).
*
@@ -0,0 +1,82 @@
@import "tailwindcss";
@import "./plugi-theme.css";
@plugin "daisyui" {
themes: false;
}
@plugin "daisyui/theme" {
name: "plugi-light";
default: true;
prefersdark: false;
color-scheme: light;
--color-base-100: var(--plugi-light-base-100);
--color-base-200: var(--plugi-light-base-200);
--color-base-300: var(--plugi-light-base-300);
--color-base-content: var(--plugi-light-base-content);
--color-primary: var(--plugi-light-primary);
--color-primary-content: var(--plugi-light-primary-content);
--color-secondary: var(--plugi-light-secondary);
--color-secondary-content: var(--plugi-light-secondary-content);
--color-accent: var(--plugi-light-accent);
--color-accent-content: var(--plugi-light-accent-content);
--color-neutral: var(--plugi-light-neutral);
--color-neutral-content: var(--plugi-light-neutral-content);
--color-info: var(--plugi-light-info);
--color-info-content: var(--plugi-light-info-content);
--color-success: var(--plugi-light-success);
--color-success-content: var(--plugi-light-success-content);
--color-warning: var(--plugi-light-warning);
--color-warning-content: var(--plugi-light-warning-content);
--color-error: var(--plugi-light-error);
--color-error-content: var(--plugi-light-error-content);
--radius-selector: var(--plugi-light-radius-selector);
--radius-field: var(--plugi-light-radius-field);
--radius-box: var(--plugi-light-radius-box);
--size-selector: var(--plugi-light-size-selector);
--size-field: var(--plugi-light-size-field);
--border: var(--plugi-light-border);
--depth: var(--plugi-light-depth);
--noise: var(--plugi-light-noise);
}
@plugin "daisyui/theme" {
name: "plugi-dark";
default: false;
prefersdark: true;
color-scheme: dark;
--color-base-100: var(--plugi-dark-base-100);
--color-base-200: var(--plugi-dark-base-200);
--color-base-300: var(--plugi-dark-base-300);
--color-base-content: var(--plugi-dark-base-content);
--color-primary: var(--plugi-dark-primary);
--color-primary-content: var(--plugi-dark-primary-content);
--color-secondary: var(--plugi-dark-secondary);
--color-secondary-content: var(--plugi-dark-secondary-content);
--color-accent: var(--plugi-dark-accent);
--color-accent-content: var(--plugi-dark-accent-content);
--color-neutral: var(--plugi-dark-neutral);
--color-neutral-content: var(--plugi-dark-neutral-content);
--color-info: var(--plugi-dark-info);
--color-info-content: var(--plugi-dark-info-content);
--color-success: var(--plugi-dark-success);
--color-success-content: var(--plugi-dark-success-content);
--color-warning: var(--plugi-dark-warning);
--color-warning-content: var(--plugi-dark-warning-content);
--color-error: var(--plugi-dark-error);
--color-error-content: var(--plugi-dark-error-content);
--radius-selector: var(--plugi-dark-radius-selector);
--radius-field: var(--plugi-dark-radius-field);
--radius-box: var(--plugi-dark-radius-box);
--size-selector: var(--plugi-dark-size-selector);
--size-field: var(--plugi-dark-size-field);
--border: var(--plugi-dark-border);
--depth: var(--plugi-dark-depth);
--noise: var(--plugi-dark-noise);
}
@source "../../views";
@source "../../layouts";
@source "../../../../Auth/resources/views";
@source "../../../../../../../extensions/plugi-ext-form/admin/Views";
@source "../../../../../../../extensions/plugi-ext-form/admin/form.php";
@@ -0,0 +1,59 @@
:where(.plugi-admin-theme, .plugi-form-wrapper) {
--plugi-light-base-100: oklch(98% 0.008 250);
--plugi-light-base-200: oklch(95% 0.014 250);
--plugi-light-base-300: oklch(90% 0.022 250);
--plugi-light-base-content: oklch(24% 0.035 255);
--plugi-light-primary: oklch(48% 0.18 250);
--plugi-light-primary-content: oklch(99% 0.006 250);
--plugi-light-secondary: oklch(52% 0.13 190);
--plugi-light-secondary-content: oklch(99% 0.006 190);
--plugi-light-accent: oklch(76% 0.15 72);
--plugi-light-accent-content: oklch(25% 0.05 72);
--plugi-light-neutral: oklch(29% 0.035 255);
--plugi-light-neutral-content: oklch(97% 0.008 255);
--plugi-light-info: oklch(50% 0.16 240);
--plugi-light-info-content: oklch(99% 0.006 240);
--plugi-light-success: oklch(47% 0.15 155);
--plugi-light-success-content: oklch(99% 0.006 155);
--plugi-light-warning: oklch(78% 0.15 82);
--plugi-light-warning-content: oklch(25% 0.05 82);
--plugi-light-error: oklch(52% 0.19 27);
--plugi-light-error-content: oklch(99% 0.006 27);
--plugi-light-radius-selector: 0.75rem;
--plugi-light-radius-field: 0.75rem;
--plugi-light-radius-box: 1rem;
--plugi-light-size-selector: 0.25rem;
--plugi-light-size-field: 0.25rem;
--plugi-light-border: 1px;
--plugi-light-depth: 1;
--plugi-light-noise: 0;
--plugi-dark-base-100: oklch(22% 0.025 255);
--plugi-dark-base-200: oklch(18% 0.025 255);
--plugi-dark-base-300: oklch(30% 0.032 255);
--plugi-dark-base-content: oklch(94% 0.012 255);
--plugi-dark-primary: oklch(74% 0.14 245);
--plugi-dark-primary-content: oklch(21% 0.04 255);
--plugi-dark-secondary: oklch(75% 0.12 188);
--plugi-dark-secondary-content: oklch(19% 0.03 200);
--plugi-dark-accent: oklch(82% 0.13 75);
--plugi-dark-accent-content: oklch(22% 0.05 75);
--plugi-dark-neutral: oklch(31% 0.035 255);
--plugi-dark-neutral-content: oklch(95% 0.01 255);
--plugi-dark-info: oklch(75% 0.13 235);
--plugi-dark-info-content: oklch(20% 0.035 245);
--plugi-dark-success: oklch(74% 0.14 155);
--plugi-dark-success-content: oklch(19% 0.035 155);
--plugi-dark-warning: oklch(82% 0.14 82);
--plugi-dark-warning-content: oklch(22% 0.05 82);
--plugi-dark-error: oklch(73% 0.16 27);
--plugi-dark-error-content: oklch(20% 0.04 27);
--plugi-dark-radius-selector: 0.75rem;
--plugi-dark-radius-field: 0.75rem;
--plugi-dark-radius-box: 1rem;
--plugi-dark-size-selector: 0.25rem;
--plugi-dark-size-field: 0.25rem;
--plugi-dark-border: 1px;
--plugi-dark-depth: 1;
--plugi-dark-noise: 0;
}
@@ -2,18 +2,16 @@
<html lang="<?= phpb_current_language() ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plugi Page Builder</title>
<link href="<?= phpb_asset('WebsiteManager.css') ?>" rel="stylesheet">
</head>
<body class="bg-light">
<body class="min-h-screen bg-base-200 text-base-content">
<div class="container">
<?php
require __DIR__ . '/../views/' . $viewFile . '.php';
?>
<div class="mx-auto min-h-screen w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
<?php require __DIR__ . '/../views/' . $viewFile . '.php'; ?>
</div>
<script src="<?= phpb_asset('WebsiteManager.js') ?>"></script>
@@ -9,82 +9,93 @@ if (isset($_GET['tab'])) {
}
?>
<!doctype html>
<html lang="<?= phpb_current_language() ?>">
<html lang="<?= phpb_current_language() ?>" class="plugi-admin-theme">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= phpb_trans('website-manager.title') ?></title>
<link rel="icon" href="/plugi-core/dist/images/logo-color.png">
<?php phpb_registered_assets('admin-header') ?>
<link href="<?= phpb_asset('WebsiteManager.css') ?>" rel="stylesheet">
<link href="<?= phpb_asset('Admin.css') ?>" rel="stylesheet">
<link href="<?= phpb_asset('icons/duotone/style.css') ?>" rel="stylesheet">
<link href="<?= phpb_asset('icons/regular/style.css') ?>" rel="stylesheet">
<link href="<?= phpb_asset('icons/bold/style.css') ?>" rel="stylesheet">
<?= Extensions::getHtmlBlocks('admin-head') ?>
</head>
<body>
<body class="min-h-screen bg-base-200 text-base-content antialiased">
<?= Extensions::getHtmlBlocks('admin-body-start') ?>
<div class="drawer lg:drawer-open">
<input id="my-drawer-2" type="checkbox" class="drawer-toggle" />
<div class="drawer-content flex flex-col items-center justify-top">
<!-- Page content here -->
<div class="navbar lg:hidden bg-base-100">
<div class="navbar-start">
<label for="my-drawer-2" class="btn btn-square btn-accent drawer-button border-primary">
<i class="text-lg ph-bold ph-list"></i>
<div class="drawer min-h-screen bg-base-200 lg:drawer-open">
<input id="admin-navigation-drawer" type="checkbox" class="drawer-toggle" />
<div class="drawer-content flex min-h-screen min-w-0 flex-col">
<header class="navbar sticky top-0 z-30 min-h-16 border-b border-base-300 bg-base-100/95 px-3 backdrop-blur sm:px-6">
<div class="navbar-start gap-3">
<label for="admin-navigation-drawer" class="btn btn-square btn-ghost drawer-button lg:hidden" aria-label="Open navigation" title="Open navigation">
<i class="text-xl ph-bold ph-list" aria-hidden="true"></i>
</label>
</div>
<div class="navbar-center">
<span class="text-xl text-primary">
<i class="inline-block ph-bold ph-brackets-square rotate-90"></i> <?= phpb_trans('website-manager.title') ?>
</span>
<div class="leading-tight">
<p class="hidden text-xs font-semibold uppercase tracking-[0.18em] text-base-content/50 sm:block">Plugi workspace</p>
<p class="font-semibold text-base-content"><?= phpb_e($tabs[$activeSlug]['title']) ?></p>
</div>
</div>
<div class="navbar-end">
<a href="<?= phpb_url('auth', ['action' => 'logout']) ?>" class="btn btn-square btn-ghost">
<i class="text-lg ph ph-sign-out"></i>
<a href="<?= phpb_url('auth', ['action' => 'logout']) ?>" class="btn btn-ghost btn-sm lg:hidden">
<i class="ph ph-sign-out" aria-hidden="true"></i>
<span><?= phpb_trans('website-manager.logout') ?></span>
</a>
</div>
</div>
</header>
<?php
require __DIR__ . '/../views/' . $viewFile . '.php';
?>
<footer class="my-5 pt-5 text-muted text-center text-small">
<p class="mb-1">Powered by <a href="https://github.com/deepDiverPaul/plugi" target="_blank">Plugi Page Builder</a></p>
<footer class="mt-auto px-4 py-6 text-center text-sm text-base-content/60 sm:px-6">
<p>Powered by <a class="link link-hover" href="https://github.com/deepDiverPaul/plugi" target="_blank" rel="noopener noreferrer">Plugi Page Builder</a></p>
</footer>
</div>
<div class="drawer-side">
<label for="my-drawer-2" class="drawer-overlay"></label>
<ul class="menu p-4 w-80 h-full bg-base-200 text-base-content">
<!-- Sidebar content here -->
<div class="py-5 text-2xl text-center text-primary">
<h2"><i class="inline-block ph-bold ph-brackets-square rotate-90"></i> <?= phpb_trans('website-manager.title') ?></h2>
</div>
<div class="drawer-side z-40 lg:z-0">
<label for="admin-navigation-drawer" aria-label="Close navigation" class="drawer-overlay"></label>
<aside class="flex min-h-full w-72 flex-col border-r border-base-300 bg-base-100 p-4 shadow-xl lg:shadow-none">
<a href="<?= phpb_url('website_manager') ?>" class="flex items-center gap-3 rounded-box px-3 py-4 transition-colors hover:bg-base-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">
<span class="grid size-11 shrink-0 place-items-center rounded-2xl bg-primary text-primary-content shadow-sm">
<i class="text-2xl ph-bold ph-brackets-square rotate-90" aria-hidden="true"></i>
</span>
<span class="min-w-0">
<span class="block text-lg font-bold leading-tight tracking-tight text-base-content">Plugi</span>
<span class="block text-xs font-medium text-base-content/60">Page Builder</span>
</span>
</a>
<div class="divider my-2"></div>
<nav class="flex-1" aria-label="Website administration">
<ul class="menu menu-md w-full gap-1 px-0">
<li class="menu-title px-3 text-xs uppercase tracking-[0.16em]"><span>Workspace</span></li>
<?php
foreach ($tabs as $slug => $tab) :
?>
<li class="mb-1">
<a class="<?= phpb_e($slug === $activeSlug ? 'bg-accent text-primary' : '' ) ?>" href="?tab=<?= phpb_e($slug) ?>">
<li>
<a class="<?= phpb_e($slug === $activeSlug ? 'menu-active font-semibold' : '' ) ?>" href="?tab=<?= phpb_e($slug) ?>" <?= $slug === $activeSlug ? 'aria-current="page"' : '' ?>>
<?= $tab['icon'] ?: '<i class="ph ph-circles-four"></i>' ?> <?= phpb_e($tab['title']) ?>
</a>
</li>
<?php
endforeach;
?>
</ul>
</nav>
<?php
if (phpb_config('auth.use_login')):
?>
<li class="lg:flex hidden">
<a href="<?= phpb_url('auth', ['action' => 'logout']) ?>" class="">
<i class="ph ph-sign-out"></i> <?= phpb_trans('website-manager.logout') ?>
<div class="mt-auto border-t border-base-300 pt-4">
<a class="btn btn-ghost w-full justify-start" href="<?= phpb_url('auth', ['action' => 'logout']) ?>">
<i class="ph ph-sign-out" aria-hidden="true"></i>
<?= phpb_trans('website-manager.logout') ?>
</a>
</li>
</div>
<?php
endif;
?>
</ul>
</aside>
</div>
</div>
@@ -5,26 +5,24 @@ if (isset($page)) {
}
?>
<div class="py-5 text-center">
<h2><?= phpb_trans('website-manager.title') ?></h2>
</div>
<div class="row">
<div class="col-12">
<div class="manager-panel">
<h4><?= phpb_trans('website-manager.render-thumbs') ?></h4>
<div class="main-spacing">
<iframe class="thumb-renderer" src="<?= phpb_url('pagebuilder', ['route' => 'thumb_generator', 'action' => 'renderNextBlockThumb']) ?>"></iframe>
</div>
<hr class="mb-3">
<a href="<?= phpb_url('website_manager') ?>" class="btn btn-light btn-sm mr-1">
<?= phpb_trans('website-manager.back') ?>
</a>
<main class="mx-auto flex w-full max-w-7xl flex-1 flex-col gap-6 px-4 py-6 sm:px-6 lg:px-8 lg:py-8">
<header class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-base-content/50">Page builder maintenance</p>
<h1 class="text-2xl font-bold tracking-tight text-base-content sm:text-3xl"><?= phpb_trans('website-manager.title') ?></h1>
</div>
</div>
<a href="<?= phpb_url('website_manager') ?>" class="btn btn-ghost btn-sm self-start sm:self-auto">
<i class="ph ph-arrow-left" aria-hidden="true"></i> <?= phpb_trans('website-manager.back') ?>
</a>
</header>
</div>
<section class="card min-w-0 border border-base-300 bg-base-100 shadow-sm">
<div class="card-body min-w-0 gap-5 p-4 sm:p-6">
<div class="space-y-1">
<h2 class="card-title text-lg"><?= phpb_trans('website-manager.render-thumbs') ?></h2>
<p class="text-sm text-base-content/60">This maintenance view renders the next missing block thumbnail.</p>
</div>
<iframe class="thumb-renderer min-h-[32rem] w-full rounded-box border border-base-300 bg-base-100" src="<?= phpb_url('pagebuilder', ['route' => 'thumb_generator', 'action' => 'renderNextBlockThumb']) ?>" title="<?= phpb_e(phpb_trans('website-manager.render-thumbs')) ?>"></iframe>
</div>
</section>
</main>
@@ -1,22 +1,28 @@
<div class="max-w-4xl p-8 mx-auto w-full">
<div class="text-center text-3xl font-bold mb-8 mt-2">
<?= phpb_e($tabs[$activeSlug]['title']) ?>
</div>
<main class="mx-auto flex w-full max-w-7xl flex-1 flex-col gap-6 px-4 py-6 sm:px-6 lg:px-8 lg:py-8">
<header class="flex items-center gap-4">
<span class="grid size-12 shrink-0 place-items-center rounded-2xl bg-primary/10 text-primary" aria-hidden="true">
<?= $tabs[$activeSlug]['icon'] ?: '<i class="ph ph-circles-four"></i>' ?>
</span>
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-base-content/50">Website management</p>
<h1 class="text-2xl font-bold tracking-tight text-base-content sm:text-3xl">
<?= phpb_e($tabs[$activeSlug]['title']) ?>
</h1>
</div>
</header>
<?php
if (phpb_flash('message')):
?>
<div class="hidden alert-success alert-error"></div>
<div class="alert alert-<?= phpb_flash('message-type') ?> mb-6">
<?= phpb_flash('message-type') === 'success' ? '<i class="text-xl ph-duotone ph-info"></i>' : '' ?>
<?= phpb_flash('message-type') === 'error' ? '<i class="text-xl ph-duotone ph-warning-circle"></i>' : '' ?>
<div class="hidden alert alert-success alert-error"></div>
<div class="alert alert-<?= phpb_flash('message-type') ?> shadow-sm" role="<?= phpb_flash('message-type') === 'error' ? 'alert' : 'status' ?>">
<?= phpb_flash('message-type') === 'success' ? '<i class="text-xl ph-duotone ph-check-circle" aria-hidden="true"></i>' : '' ?>
<?= phpb_flash('message-type') === 'error' ? '<i class="text-xl ph-duotone ph-warning-circle" aria-hidden="true"></i>' : '' ?>
<span><?= phpb_flash('message') ?></span>
</div>
<?php
endif;
?>
<div class="">
<?php
include $tabs[$activeSlug]['include'];
?>
</div>
</div>
<section class="min-w-0">
<?php include $tabs[$activeSlug]['include']; ?>
</section>
</main>
@@ -5,6 +5,7 @@ if (isset($page)) {
}
$pageTranslations = $page ? $page->getTranslations() : [];
$activeLanguages = phpb_active_languages();
$fieldValue = static function (string $field, ?string $languageCode = null) use ($page, $pageTranslations): string {
if ($languageCode !== null) {
$postedValues = $_POST[$field] ?? null;
@@ -23,63 +24,69 @@ $javascriptValue = static function (string $value): string {
?>
<div class="manager-panel p-8 w-full">
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => $action]) ?><?= $pageUrlParam ?>">
<main class="mx-auto flex w-full max-w-5xl flex-1 flex-col justify-center px-4 py-6 sm:px-6 lg:py-8">
<section class="card w-full border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-6 p-4 sm:p-8">
<form class="space-y-6" method="post" action="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => $action]) ?><?= $pageUrlParam ?>">
<?php phpb_csrf_field(); ?>
<div class="text-center text-3xl font-bold mb-8 mt-2">
<?php
if ($action === 'create'):
echo phpb_trans('website-manager.add-new-page');
else:
echo phpb_trans('website-manager.edit-page');
endif;
?>
</div>
<header class="space-y-2 border-b border-base-300 pb-5">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Page configuration</p>
<h1 class="text-2xl font-bold tracking-tight text-base-content sm:text-3xl">
<?php
if ($action === 'create'):
echo phpb_trans('website-manager.add-new-page');
else:
echo phpb_trans('website-manager.edit-page');
endif;
?>
</h1>
<p class="max-w-2xl text-sm leading-relaxed text-base-content/60">Set the page type and layout, then configure its route and metadata for each enabled language.</p>
</header>
<?php if (! empty($errorMessage)): ?>
<div class="alert alert-error mb-6" role="alert">
<div class="alert alert-error" role="alert">
<span><?= phpb_e($errorMessage) ?></span>
</div>
<?php endif; ?>
<div class="max-w-lg p-4 mx-auto" x-data="{type: <?= $javascriptValue($fieldValue('type') !== '' ? $fieldValue('type') : 'static') ?>}">
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text"> <?= phpb_trans('website-manager.name') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" id="name" name="name" value="<?= phpb_e($fieldValue('name')) ?>" required class="input input-bordered w-full" />
<label class="label">
<span class="label-text-alt"><?= phpb_trans('website-manager.visible-in-page-overview') ?></span>
</label>
</div>
<div class="w-full space-y-6" x-data="{type: <?= $javascriptValue($fieldValue('type') !== '' ? $fieldValue('type') : 'static') ?>}">
<section class="grid gap-4 rounded-box border border-base-300 bg-base-200/50 p-4 sm:grid-cols-2 sm:p-5">
<div class="form-control w-full">
<label class="label" for="name">
<span class="label-text"> <?= phpb_trans('website-manager.name') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" id="name" name="name" value="<?= phpb_e($fieldValue('name')) ?>" required aria-describedby="page-name-help" class="input input-bordered w-full" />
<p id="page-name-help" class="label text-sm text-base-content/60"><?= phpb_trans('website-manager.visible-in-page-overview') ?></p>
</div>
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text"><?= phpb_trans('website-manager.page-type') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span> <!-- TODO add to lang -->
</label>
<select class="select select-bordered" x-model="type" id="type" name="type" required>
<?php
$types = ['static', 'redirect'];
$value = $fieldValue('type');
foreach ($types as $type):
if ($type === $value):
echo '<option value="' . phpb_e($type) . '" selected>' . phpb_trans('website-manager.page-types.'.$type) . '</option>';
else:
echo '<option value="' . phpb_e($type) . '">' . phpb_trans('website-manager.page-types.'.$type) . '</option>';
endif;
endforeach;
?>
</select>
</div>
<div class="form-control w-full">
<label class="label" for="type">
<span class="label-text"><?= phpb_trans('website-manager.page-type') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span> <!-- TODO add to lang -->
</label>
<select class="select select-bordered w-full" x-model="type" id="type" name="type" required>
<?php
$types = ['static', 'redirect'];
$value = $fieldValue('type');
foreach ($types as $type):
if ($type === $value):
echo '<option value="' . phpb_e($type) . '" selected>' . phpb_trans('website-manager.page-types.'.$type) . '</option>';
else:
echo '<option value="' . phpb_e($type) . '">' . phpb_trans('website-manager.page-types.'.$type) . '</option>';
endif;
endforeach;
?>
</select>
</div>
</section>
<div class="form-control w-full mb-4" x-show="type !== 'redirect'">
<label class="label">
<div class="form-control w-full" x-show="type !== 'redirect'">
<label class="label" for="layout">
<span class="label-text"><?= phpb_trans('website-manager.layout') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span> <!-- TODO add to lang -->
</label>
<select class="select select-bordered" id="layout" name="layout" required>
<select class="select select-bordered w-full" id="layout" name="layout" required>
<?php
$value = $fieldValue('layout');
foreach ($theme->getThemeLayouts() as $layout):
@@ -93,53 +100,95 @@ $javascriptValue = static function (string $value): string {
</select>
</div>
<?php
$firstLang = true;
foreach (phpb_active_languages() as $languageCode => $languageTranslation):
<section class="space-y-4">
<div class="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 class="text-lg font-semibold text-base-content">Localized page details</h2>
<p class="text-sm text-base-content/60">Each language shows its own saved values; missing translations are left blank instead of using fallback text.</p>
</div>
<span class="badge badge-outline"><?= count($activeLanguages) ?> languages</span>
</div>
<?php
$firstLang = true;
foreach ($activeLanguages as $languageCode => $languageTranslation):
$savedTranslation = $pageTranslations[$languageCode] ?? null;
$hasSavedTranslation = is_array($savedTranslation);
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
$hasRequiredTranslationValues = $hasSavedTranslation
&& trim((string) ($savedTranslation['route'] ?? '')) !== ''
&& ($translationType === 'redirect'
? trim((string) ($savedTranslation['target'] ?? '')) !== ''
: trim((string) ($savedTranslation['title'] ?? '')) !== '');
$localeStatus = $action === 'create'
? 'New translation'
: (! $hasSavedTranslation ? 'Missing' : ($hasRequiredTranslationValues ? 'Complete' : 'Needs attention'));
$localeStatusClass = $action === 'create'
? 'badge-outline'
: (! $hasSavedTranslation ? 'badge-error' : ($hasRequiredTranslationValues ? 'badge-success' : 'badge-warning'));
?>
<details class="collapse collapse-plus bg-white mt-6" <?= phpb_e($firstLang ? 'open' : '') ?>>
<summary class="collapse-title text-xl font-medium"><?= phpb_trans('languages.' . $languageCode) ?></summary>
<div class="collapse-content">
<div x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
<div class="form-control w-full mb-2">
<details class="collapse collapse-arrow border border-base-300 bg-base-100" <?= phpb_e($firstLang ? 'open' : '') ?>>
<summary class="collapse-title flex min-h-14 flex-wrap items-center gap-2 text-base font-semibold sm:text-lg">
<span><?= phpb_trans('languages.' . $languageCode) ?></span>
<span class="badge badge-ghost ml-3"><?= phpb_e($languageCode) ?></span>
<span class="badge badge-sm <?= $localeStatusClass ?>"><?= $localeStatus ?></span>
</summary>
<div class="collapse-content space-y-5">
<?php if ($action === 'create' || ! $hasSavedTranslation || ! $hasRequiredTranslationValues): ?>
<div class="alert <?= $hasSavedTranslation ? 'alert-warning' : 'alert-info' ?>" role="status">
<span>
<?php if ($action === 'create'): ?>
Enter the actual values for this language; other locales will not be used to fill these fields.
<?php elseif (! $hasSavedTranslation): ?>
No saved translation exists for this language. Enter its actual values; fields are not filled from another locale.
<?php else: ?>
This saved translation is missing a required title, route, or redirect target. Complete these fields before saving.
<?php endif; ?>
</span>
</div>
<?php endif; ?>
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
<div class="form-control w-full">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-title" name="title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('title', $languageCode)) ?>" @input="if(empty){route=`${locale}/${slugify($event.target.value)}`}" :required="type==='static'" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-title" name="title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('title', $languageCode)) ?>" @input="if(empty){route=`${locale}/${slugify($event.target.value,{lower:true})}`}" :required="type==='static'" />
</div>
<div class="form-control w-full mb-2" x-show="type === 'static'">
<div class="grid gap-4 md:grid-cols-2" x-show="type === 'static'">
<div class="form-control w-full">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-meta-title">
<span class="label-text"><?= phpb_trans('website-manager.page-meta-title') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-meta-title" name="meta_title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('meta_title', $languageCode)) ?>" />
</div>
<div class="form-control w-full mb-2" x-show="type === 'static'">
<div class="form-control w-full">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-meta-description">
<span class="label-text"><?= phpb_trans('website-manager.page-meta-description') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-meta-description" name="meta_description[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('meta_description', $languageCode)) ?>" />
</div>
</div>
<div class="form-control w-full mb-2" x-show="type === 'redirect'">
<div class="form-control w-full" x-show="type === 'redirect'">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-target-redirect">
<span class="label-text"><?= phpb_trans('website-manager.target-redirect') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" :required="type==='redirect'" />
</div>
<div class="form-control w-full mb-2">
<div class="form-control w-full">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-route">
<span class="label-text"><?= phpb_trans('website-manager.route') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<div class="join" x-data="{disabled: true}">
<input type="text" :class="{'join-item': type !== 'redirect'}" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-route" name="route[<?= phpb_e($languageCode) ?>]" x-model="route" :readonly="disabled && type !== 'redirect'" required />
<button class="btn join-item btn-outline text-2xl" @click.stop.prevent="disabled=!disabled" type="button" x-show="type !== 'redirect'">
<i class="ph ph-pencil" x-show="disabled"></i>
<i class="ph ph-pencil-slash" x-show="!disabled"></i>
<div class="join w-full" x-data="{disabled: true}">
<input type="text" :class="{'join-item': type !== 'redirect'}" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-route" name="route[<?= phpb_e($languageCode) ?>]" x-model="route" :readonly="disabled && type !== 'redirect'" :aria-readonly="disabled && type !== 'redirect'" required />
<button class="btn join-item btn-outline" @click.stop.prevent="disabled=!disabled" type="button" x-show="type !== 'redirect'" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" title="<?= phpb_e(phpb_trans('website-manager.edit')) ?>">
<i class="ph ph-pencil" x-show="disabled" aria-hidden="true"></i>
<i class="ph ph-pencil-slash" x-show="!disabled" aria-hidden="true"></i>
</button>
</div>
</div>
@@ -151,12 +200,13 @@ $javascriptValue = static function (string $value): string {
$firstLang = false;
endforeach;
?>
</section>
<div class="text-center mt-8">
<a href="<?= phpb_url('website_manager') ?>" class="btn btn-light btn-sm mr-1">
<div class="flex flex-col-reverse justify-end gap-3 border-t border-base-300 pt-6 sm:flex-row">
<a href="<?= phpb_url('website_manager') ?>" class="btn btn-ghost sm:btn-sm">
<?= phpb_trans('website-manager.back') ?>
</a>
<button class="btn btn-primary btn-sm">
<button type="submit" class="btn btn-primary sm:btn-sm">
<?php
if ($action === 'create'):
echo phpb_trans('website-manager.add-new-page');
@@ -172,3 +222,5 @@ $javascriptValue = static function (string $value): string {
</form>
</div>
</section>
</main>
@@ -16,6 +16,11 @@ return [
'include' => __DIR__ . '/files.php',
'icon' => '<i class="ph ph-folder-notch-open"></i>',
],
'quality' => [
'title' => phpb_trans('website-manager.quality'),
'include' => __DIR__ . '/quality.php',
'icon' => '<i class="ph ph-check-circle"></i>',
],
'settings' => [
'title' => phpb_trans('website-manager.settings'),
'include' => __DIR__ . '/settings.php',
@@ -1,32 +1,46 @@
<div class="mb-8 flex justify-center">
<input type="file" id="fileupload" class="file-input file-input-bordered file-input-primary w-full max-w-md" name="fileupload" onchange="uploadFile()" onselect="uploadFile()" />
</div>
<div class="flex flex-wrap justify-center gap-4">
<?php
foreach ($files as $file) :
?>
<div class="relative">
<img src="<?= phpb_e($file->getUrl()) ?>" alt="<?= phpb_e($file->public_id) ?>" class="h-40 rounded">
<div class="absolute top-1 right-1">
<button onclick="deleteFile('<?= phpb_e($file->public_id) ?>')" class="btn btn-error btn-circle btn-sm mb-2">
<i class="ph-duotone ph-trash"></i>
</button>
<section class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-6 p-4 sm:p-6 lg:p-8">
<div class="flex flex-col gap-5 border-b border-base-300 pb-5 sm:flex-row sm:items-end sm:justify-between">
<div class="space-y-1">
<h2 class="text-xl font-bold tracking-tight text-base-content">Media library</h2>
<p class="text-sm text-base-content/60">Upload and manage the files used across your pages.</p>
</div>
<div class="form-control w-full max-w-md gap-1">
<label class="label" for="fileupload">
<span class="label-text font-medium">Upload a file</span>
<span class="label-text-alt">Choose a file</span>
</label>
<input type="file" id="fileupload" class="file-input file-input-bordered file-input-primary w-full" name="fileupload" onchange="uploadFile()" onselect="uploadFile()" />
</div>
</div>
<?php if (count($files) === 0) : ?>
<div class="rounded-box border border-dashed border-base-300 bg-base-200/50 px-5 py-12 text-center" role="status">
<span class="mx-auto mb-4 grid size-12 place-items-center rounded-2xl bg-info/10 text-info">
<i class="text-2xl ph-duotone ph-image" aria-hidden="true"></i>
</span>
<h3 class="font-semibold text-base-content">No files yet</h3>
<p class="mt-1 text-sm text-base-content/60">Your uploaded files will appear here as a visual library.</p>
</div>
<?php else : ?>
<ul class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<?php foreach ($files as $file) : ?>
<li class="card overflow-hidden border border-base-300 bg-base-100 shadow-sm transition-shadow hover:shadow-md">
<figure class="relative aspect-video bg-base-200">
<img src="<?= phpb_e($file->getUrl()) ?>" alt="<?= phpb_e($file->public_id) ?>" class="h-full w-full object-cover">
<button type="button" onclick="deleteFile('<?= phpb_e($file->public_id) ?>')" class="btn btn-error btn-square btn-sm absolute right-3 top-3 shadow-sm" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?> <?= phpb_e($file->public_id) ?>" title="<?= phpb_e(phpb_trans('website-manager.remove')) ?>">
<i class="ph-duotone ph-trash" aria-hidden="true"></i>
</button>
</figure>
<div class="card-body gap-1 p-3">
<p class="truncate text-sm font-medium" title="<?= phpb_e($file->public_id) ?>"><?= phpb_e($file->public_id) ?></p>
</div>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
<?php
endforeach;
?>
<?php
if (count($files) === 0) :
?>
<div class="relative">
No files...
</div>
<?php
endif;
?>
</div>
</section>
<script>
async function uploadFile() {
@@ -3,15 +3,20 @@
use Plugi\Setting;
?>
<div class="overflow-x-auto">
<table class="table table-zebra">
<section class="space-y-5">
<header class="space-y-1">
<h2 class="text-xl font-bold tracking-tight text-base-content">System information</h2>
<p class="text-sm text-base-content/60">Review runtime details, database health, and installed extensions.</p>
</header>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra min-w-[42rem]">
<tbody>
<tr>
<th class="w-36 md:w-60">PHP Version</th>
<td><?= phpversion() ?></td>
<th scope="row" class="w-36 md:w-60">PHP Version</th>
<td><span class="badge badge-outline"><?= phpversion() ?></span></td>
</tr>
<tr>
<th>Database</th>
<th scope="row" class="align-top">Database</th>
<td>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'database', 'action' => 'update']) ?>">
<?php phpb_csrf_field(); ?>
@@ -24,16 +29,17 @@ use Plugi\Setting;
if(!is_array($tableDiff)) $actionNeeded = true;
if(is_array($tableDiff) && empty($tableDiff['columns']) && empty($tableDiff['uniqueKeys'])) continue;
?>
<div>
table <strong><?= phpb_e($table) ?></strong> (<?= phpb_e(is_array($tableDiff) ? (empty($tableDiff['columns']) && empty($tableDiff['uniqueKeys']) ? 'is fine' : 'has diff') : 'is not existent') ?>)
<div class="rounded-box border border-base-300 bg-base-200/50 px-3 py-2 text-sm">
Table <strong><?= phpb_e($table) ?></strong>
<span class="text-base-content/60">(<?= phpb_e(is_array($tableDiff) ? (empty($tableDiff['columns']) && empty($tableDiff['uniqueKeys']) ? 'is fine' : 'has diff') : 'is not existent') ?>)</span>
</div>
<?php
if (is_array($tableDiff)) :
foreach ($tableDiff['columns'] as $column => $def) :
$actionNeeded = true;
?>
<div class="ml-4">
<i class="ph ph-arrow-elbow-down-right"></i> column <strong><?= phpb_e($column) ?></strong> (not existent)
<div class="ml-4 flex items-center gap-2 text-sm text-base-content/70">
<i class="ph ph-arrow-elbow-down-right" aria-hidden="true"></i> Column <strong><?= phpb_e($column) ?></strong> (not existent)
</div>
<?php
endforeach;
@@ -44,8 +50,8 @@ use Plugi\Setting;
foreach ($tableDiff['uniqueKeys'] as $key => $def) :
$actionNeeded = true;
?>
<div class="ml-4">
<i class="ph ph-arrow-elbow-down-right"></i> unique key <strong><?= phpb_e($key) ?></strong> (not existent)
<div class="ml-4 flex items-center gap-2 text-sm text-base-content/70">
<i class="ph ph-arrow-elbow-down-right" aria-hidden="true"></i> Unique key <strong><?= phpb_e($key) ?></strong> (not existent)
</div>
<?php
endforeach;
@@ -55,11 +61,17 @@ use Plugi\Setting;
endforeach;
if ($actionNeeded) :
?>
<button class="btn" type="submit">Update</button>
<button class="btn btn-primary" type="submit">
<i class="ph-bold ph-arrows-clockwise" aria-hidden="true"></i>
Update database
</button>
<?php
else :
?>
<div>Database is up-to-date. <span class="hidden md:inline text-gray-400">(<?= $phpb_db->getDBDefinitionHash() ?>)</span></div>
<div class="alert alert-success alert-soft" role="status">
<i class="ph-duotone ph-check-circle" aria-hidden="true"></i>
<span>Database is up-to-date. <span class="hidden md:inline text-base-content/60">(<?= $phpb_db->getDBDefinitionHash() ?>)</span></span>
</div>
<?php
endif;
?>
@@ -68,45 +80,46 @@ use Plugi\Setting;
</td>
</tr>
<tr>
<th class="align-top">Installed extensions</th>
<th scope="row" class="align-top">Installed extensions</th>
<td x-data="{show: false}">
<ul>
<ul class="space-y-2">
<?php
foreach (\Plugi\Extensions::getConfigs() as $ext) :
?>
<li>
<?= phpb_e($ext['title']) ?> (<?= phpb_e($ext['version']) ?>)
<li class="flex flex-wrap items-center justify-between gap-2 rounded-box border border-base-300 px-3 py-2">
<span class="font-medium"><?= phpb_e($ext['title']) ?></span>
<span class="badge badge-ghost"><?= phpb_e($ext['version']) ?></span>
</li>
<?php
endforeach;
?>
</ul>
<div>
<button @click="show = !show" class="btn btn-xs btn-outline" x-text="show ? 'hide' : 'show config'"></button>
<div class="mt-3">
<button type="button" @click="show = !show" class="btn btn-ghost btn-xs" :aria-expanded="show" aria-controls="installed-extension-config" x-text="show ? 'Hide configuration' : 'Show configuration'"></button>
</div>
<pre class="mt-4" x-show="show"><?php
<pre id="installed-extension-config" class="mt-3 max-h-96 overflow-auto rounded-box border border-base-300 bg-base-200 p-4 text-xs" x-show="show"><?php
print_r(\Plugi\Extensions::getConfigs());
?></pre>
</td>
</tr>
<tr>
<th class="align-top">Config</th>
<th scope="row" class="align-top">Config</th>
<td x-data="{show: false}">
<div>
<button @click="show = !show" class="btn btn-xs btn-outline" x-text="show ? 'hide' : 'show'"></button>
<button type="button" @click="show = !show" class="btn btn-ghost btn-xs" :aria-expanded="show" aria-controls="application-config" x-text="show ? 'Hide configuration' : 'Show configuration'"></button>
</div>
<pre class="mt-4" x-show="show"><?php
<pre id="application-config" class="mt-3 max-h-96 overflow-auto rounded-box border border-base-300 bg-base-200 p-4 text-xs" x-show="show"><?php
print_r(phpb_config());
?></pre>
</td>
</tr>
<tr>
<th class="align-top">Environment</th>
<th scope="row" class="align-top">Environment</th>
<td x-data="{show: false}">
<div class="">
<button @click="show = !show" class="btn btn-xs btn-outline" x-text="show ? 'hide' : 'show'"></button>
<button type="button" @click="show = !show" class="btn btn-ghost btn-xs" :aria-expanded="show" aria-controls="environment-config" x-text="show ? 'Hide values' : 'Show values'"></button>
</div>
<pre class="mt-4" x-show="show"><?php
<pre id="environment-config" class="mt-3 max-h-96 overflow-auto rounded-box border border-base-300 bg-base-200 p-4 text-xs" x-show="show"><?php
print_r([
'STAGE'=>$_ENV['STAGE'],
'BASE_URL'=>$_ENV['BASE_URL']
@@ -115,5 +128,6 @@ print_r([
</td>
</tr>
</tbody>
</table>
</div>
</table>
</div>
</section>
@@ -10,81 +10,106 @@ $pages = $pageRepository->getAll();
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'menus', 'action' => 'update', 'tab' => 'menus']) ?>">
<?php phpb_csrf_field(); ?>
<div class="main-spacing" x-data="{menus: <?= phpb_e($menusJson) ?>, pages: <?= phpb_e($menuPagesJson) ?>}">
<div class="space-y-6" x-data="{menus: <?= phpb_e($menusJson) ?>, pages: <?= phpb_e($menuPagesJson) ?>}">
<div class="text-center mb-8">
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div class="space-y-1">
<h2 class="text-xl font-bold tracking-tight text-base-content">Navigation menus</h2>
<p class="text-sm text-base-content/60">Arrange pages and control the order visitors see in your menus.</p>
</div>
<button type="button" @click.stop.prevent="menus.push({name:'New Menu',pages:[]})" class="btn btn-primary">
<i class="ph-bold ph-plus" aria-hidden="true"></i>
<?= phpb_trans('website-manager.create-menu'); ?>
</button>
</div>
</header>
<div class="flex flex-col gap-12">
<div class="flex flex-col gap-6">
<template x-if="menus.length === 0">
<div class="rounded-box border border-dashed border-base-300 bg-base-100 px-5 py-10 text-center">
<span class="mx-auto mb-3 grid size-11 place-items-center rounded-2xl bg-info/10 text-info">
<i class="text-2xl ph-duotone ph-list-dashes" aria-hidden="true"></i>
</span>
<h3 class="font-semibold text-base-content">No menus created</h3>
<p class="mt-1 text-sm text-base-content/60">Create a menu, then add and arrange pages.</p>
</div>
</template>
<template x-for="(menu, menuIndex) in menus">
<div class="">
<div class="px-6 mb-4 flex justify-between" x-data="{ edit: false }">
<input type="text" x-model="menu.name" class="input input-bordered w-full max-w-xs" x-show="edit" >
<div class="text-2xl font-bold" x-text="menu.name" x-show="!edit"></div>
<div>
<a href="javascript:void(0)" class="btn btn-square btn-sm" @click="edit = !edit">
<i class=" text-2xl ph ph-pencil-line"></i>
</a>
<a href="javascript:void(0)" class="btn btn-square btn-sm" @click="if (confirm(`<?= phpb_trans('website-manager.delete-menu') ?> ${menu.name}`) === true) arraymove(menus,menuIndex);">
<i class=" text-2xl ph ph-trash"></i>
</a>
<div class="dropdown dropdown-end dropdown-hover" x-show="(menu.pages.length < pages.length)">
<label tabindex="0" class="btn btn-square btn-sm">
<i class=" text-2xl ph ph-list-plus"></i>
</label>
<ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52 z-10">
<template x-for="page in pages.filter(p=> !menu.pages.map(m=>m.id).includes(p.id))">
<li>
<a href="javascript:void(0)" @click="menu.pages.push(page)">
<span x-text="page.id" class="mr-3 font-bold"></span>
<span x-text="page.title"></span>
</a>
</li>
</template>
</ul>
<section class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-5 p-4 sm:p-6">
<div class="flex flex-col gap-4 border-b border-base-300 pb-4 sm:flex-row sm:items-center sm:justify-between" x-data="{ edit: false }">
<input type="text" x-model="menu.name" class="input input-bordered w-full max-w-md" x-show="edit" aria-label="<?= phpb_e(phpb_trans('website-manager.name')) ?>">
<h3 class="text-lg font-bold text-base-content sm:text-xl" x-text="menu.name" x-show="!edit"></h3>
<div class="flex items-center gap-2">
<button type="button" class="btn btn-ghost btn-square btn-sm" @click="edit = !edit" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" title="<?= phpb_e(phpb_trans('website-manager.edit')) ?>">
<i class="text-xl ph ph-pencil-line" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-error btn-square btn-sm" @click="if (confirm(`<?= phpb_trans('website-manager.delete-menu') ?> ${menu.name}`) === true) arraymove(menus,menuIndex);" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?>" title="<?= phpb_e(phpb_trans('website-manager.remove')) ?>">
<i class="text-xl ph ph-trash" aria-hidden="true"></i>
</button>
<details class="dropdown dropdown-end" x-show="(menu.pages.length < pages.length)">
<summary class="btn btn-ghost btn-square btn-sm list-none" aria-label="Add pages to menu" title="Add pages to menu">
<i class="text-xl ph ph-list-plus" aria-hidden="true"></i>
</summary>
<ul class="dropdown-content menu z-10 mt-2 w-64 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg">
<template x-for="page in pages.filter(p=> !menu.pages.map(m=>m.id).includes(p.id))">
<li>
<a href="javascript:void(0)" @click="menu.pages.push(page)">
<span x-text="page.id" class="mr-3 font-bold"></span>
<span x-text="page.title"></span>
</a>
</li>
</template>
</ul>
</details>
</div>
</div>
<input type="hidden" :name="menu.name" :value="menu.pages.map(p=>p.id).join(',')">
<div class="alert alert-info alert-soft" x-show="menu.pages.length === 0" role="status">
<i class="ph-duotone ph-info" aria-hidden="true"></i>
<span>Add pages to this menu, then use the arrows to arrange their order.</span>
</div>
<div class="overflow-x-auto rounded-box border border-base-300" x-show="menu.pages.length > 0">
<table class="table table-zebra w-full min-w-[42rem]">
<thead>
<tr>
<th class="w-16">ID</th>
<th class="w-5/12"><?= phpb_trans('website-manager.name') ?></th>
<th><?= phpb_trans('website-manager.route') ?></th>
<th class="w-36"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<template x-for="(page, index) in menu.pages">
<tr>
<th x-text="page.id"></th>
<td class="font-medium" x-text="page.title"></td>
<td x-text="page.route"></td>
<td>
<div class="flex items-center gap-1">
<button type="button" @click.stop.prevent="arraymove(menu.pages,index,index-1)" class="btn btn-ghost btn-square btn-sm" :disabled="index === 0" aria-label="Move page up" title="Move page up">
<i class="ph-duotone ph-arrow-fat-up text-xl" aria-hidden="true"></i>
</button>
<button type="button" @click.stop.prevent="arraymove(menu.pages,index,index+1)" class="btn btn-ghost btn-square btn-sm" :disabled="index === menu.pages.length - 1" aria-label="Move page down" title="Move page down">
<i class="ph-duotone ph-arrow-fat-down text-xl" aria-hidden="true"></i>
</button>
<button type="button" @click.stop.prevent="arraymove(menu.pages,index)" class="btn btn-error btn-square btn-sm" aria-label="Remove page" title="Remove page">
<i class="ph-duotone ph-trash text-xl" aria-hidden="true"></i>
</button>
</div>
</td>
</tr>
</template>
</tbody>
</table>
</div>
</div>
<input type="hidden" :name="menu.name" :value="menu.pages.map(p=>p.id).join(',')">
<table class="table table-zebra w-full" x-show="menu.pages.length > 0">
<thead>
<tr>
<th class="w-5">ID</th>
<th class="w-5/12"><?= phpb_trans('website-manager.name') ?></th>
<th><?= phpb_trans('website-manager.route') ?></th>
<th class="w-36"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<template x-for="(page, index) in menu.pages">
<tr>
<th x-text="page.id"></th>
<td x-text="page.title"></td>
<td x-text="page.route"></td>
<td>
<button type="button" @click.stop.prevent="arraymove(menu.pages,index,index-1)" class="btn btn-outline btn-circle btn-sm" :disabled="index === 0">
<i class="ph-duotone ph-arrow-fat-up text-xl"></i>
</button>
<button type="button" @click.stop.prevent="arraymove(menu.pages,index,index+1)" class="btn btn-outline btn-circle btn-sm" :disabled="index === menu.pages.length - 1">
<i class="ph-duotone ph-arrow-fat-down text-xl"></i>
</button>
<button @click.stop.prevent="arraymove(menu.pages,index)" class="btn btn-outline btn-circle btn-error btn-sm">
<i class="ph-duotone ph-trash text-xl"></i>
</button>
</td>
</tr>
</template>
</tbody>
</table>
</div>
</section>
</template>
</div>
<div class="text-center mt-8">
<button class="btn btn-primary">
<div class="flex justify-end border-t border-base-300 pt-5">
<button type="submit" class="btn btn-primary">
<i class="ph-bold ph-floppy-disk" aria-hidden="true"></i>
<?= phpb_trans('website-manager.save-menus'); ?>
</button>
</div>
@@ -1,54 +1,109 @@
<table class="table table-zebra w-full">
<thead>
<tr>
<th class="w-5">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th><?= phpb_trans('website-manager.route') ?></th>
<th class="w-36 md:w-44"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php
foreach ($pages as $page):
?>
<tr>
<td>
<?= phpb_e($page->getId()) ?>
</td>
<td>
<?= phpb_e($page->getName()) ?>
</td>
<td>
<div class="hidden pl-4 pl-8"></div>
<div class="pl-<?= phpb_e((count(explode('/', $page->getRoute()))-2)*4) ?>">
<?= phpb_e($page->getRoute()) ?>
</div>
<div class="space-y-5">
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div class="space-y-1">
<h2 class="text-xl font-bold tracking-tight text-base-content">Your pages</h2>
<p class="text-sm text-base-content/60">Review routes and open the page editor or page settings.</p>
</div>
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'create']) ?>" class="btn btn-primary">
<i class="ph-bold ph-plus" aria-hidden="true"></i>
<?= phpb_trans('website-manager.add-new-page') ?>
</a>
</header>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[64rem]">
<thead>
<tr>
<th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th>Localized titles and routes</th>
<th>Coverage</th>
<th class="w-44"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php if (empty($pages)): ?>
<tr>
<td colspan="5" class="py-12 text-center">
<span class="mx-auto mb-3 grid size-11 place-items-center rounded-2xl bg-info/10 text-info">
<i class="text-2xl ph-duotone ph-files" aria-hidden="true"></i>
</span>
<span class="block font-semibold text-base-content">No pages yet</span>
<span class="mt-1 block text-sm text-base-content/60">Add a page to get your site started.</span>
</td>
</tr>
<?php endif; ?>
<?php foreach ($pages as $page): ?>
<?php
$pageRoute = $page->getRoute();
$canViewPage = $page->get('type') !== 'redirect' && is_string($pageRoute) && $pageRoute !== '';
?>
<tr>
<td><?= phpb_e($page->getId()) ?></td>
<td class="font-medium"><?= phpb_e($page->getName()) ?></td>
<td>
<div class="grid gap-2 sm:grid-cols-2">
<?php foreach ($activeLanguages as $languageCode => $languageTranslation): ?>
<?php
$localeCoverage = $pageTranslationCoverage[$page->getId()]['locales'][$languageCode] ?? null;
$localeExists = $localeCoverage['exists'] ?? false;
$localeComplete = $localeCoverage['complete'] ?? false;
$localeStatus = $localeComplete ? 'Complete' : ($localeExists ? 'Needs attention' : 'Missing');
$localeBadgeClass = $localeComplete ? 'badge-success' : ($localeExists ? 'badge-warning' : 'badge-error');
$localeTitle = $localeCoverage['title'] ?? null;
$localeRoute = $localeCoverage['route'] ?? null;
$localeTitleLabel = is_string($localeTitle) && trim($localeTitle) !== ''
? phpb_e($localeTitle)
: ($page->get('type') === 'redirect' ? 'Redirect page' : 'Title not set');
?>
<div class="min-w-0 rounded-box border border-base-300 p-3">
<div class="mb-1 flex flex-wrap items-center justify-between gap-2">
<span class="text-xs font-semibold text-base-content/70">
<?= phpb_trans('languages.' . $languageCode) ?>
<span class="font-mono">(<?= phpb_e($languageCode) ?>)</span>
</span>
<span class="badge badge-sm <?= $localeBadgeClass ?>"><?= $localeStatus ?></span>
</div>
<p class="truncate text-sm font-medium" title="<?= phpb_e($localeTitle) ?>">
<?= $localeTitleLabel ?>
</p>
<p class="break-all font-mono text-xs text-base-content/60" title="<?= phpb_e($localeRoute) ?>">
<?= is_string($localeRoute) && trim($localeRoute) !== '' ? phpb_e($localeRoute) : 'Route not set' ?>
</p>
</div>
<?php endforeach; ?>
</div>
</td>
<td>
<?php
$pageCoverage = $pageTranslationCoverage[$page->getId()] ?? ['completeCount' => 0, 'localeCount' => count($activeLanguages)];
$coverageClass = $pageCoverage['localeCount'] > 0 && $pageCoverage['completeCount'] === $pageCoverage['localeCount']
? 'badge-success'
: ($pageCoverage['completeCount'] > 0 ? 'badge-warning' : 'badge-error');
?>
<span class="badge <?= $coverageClass ?>">
<?= phpb_e($pageCoverage['completeCount']) ?> / <?= phpb_e($pageCoverage['localeCount']) ?> complete
</span>
</td>
<td>
<div class="flex items-center gap-1">
<a href="<?= phpb_e($canViewPage ? phpb_full_url($pageRoute) : '#') ?>" title="<?= phpb_trans('website-manager.view') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.view')) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $canViewPage ? '' : 'btn-disabled' ?>" <?= $canViewPage ? '' : 'tabindex="-1" aria-disabled="true"' ?>>
<i class="text-xl ph-duotone ph-eye" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url('pagebuilder', ['page' => $page->getId()]) ?>" class="btn btn-primary btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>>
<i class="text-xl ph-duotone ph-pencil-line" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'edit', 'page' => $page->getId()]) ?>" title="<?= phpb_trans('website-manager.settings') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.settings')) ?>" class="btn btn-ghost btn-square btn-sm">
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'destroy', 'page' => $page->getId()]) ?>" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?>" class="btn btn-error btn-square btn-sm">
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
</a>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</td>
<td class="actions">
<a href="<?= phpb_e(phpb_full_url($page->getRoute())) ?>" title="<?= phpb_trans('website-manager.view') ?>" target="_blank" class="btn btn-light btn-outline btn-sm btn-circle <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>">
<i class="text-xl ph-duotone ph-eye"></i>
</a>
<a href="<?= phpb_url('pagebuilder', ['page' => $page->getId()]) ?>" class="btn btn-primary hidden md:inline-flex btn-sm btn-circle <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" title="<?= phpb_trans('website-manager.edit') ?>">
<i class="text-xl ph-duotone ph-pencil-line"></i>
</a>
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'edit', 'page' => $page->getId()]) ?>" title="<?= phpb_trans('website-manager.settings') ?>" class="btn btn-secondary btn-sm btn-circle">
<i class="text-xl ph-duotone ph-gear"></i>
</a>
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'destroy', 'page' => $page->getId()]) ?>" title="<?= phpb_trans('website-manager.remove') ?>" class="btn btn-error btn-sm btn-circle">
<i class="text-xl ph-duotone ph-trash"></i>
</a>
</td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
<div class="text-center mt-8">
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'create']) ?>" class="btn btn-primary">
<?= phpb_trans('website-manager.add-new-page') ?>
</a>
</div>
@@ -0,0 +1,122 @@
<?php
$qualityReport = isset($qualityReport) && is_array($qualityReport) ? $qualityReport : null;
$qualityFindings = $qualityReport['findings'] ?? [];
$qualityErrors = $qualityReport['errors'] ?? [];
$qualityItems = array_merge($qualityFindings, $qualityErrors);
$qualityGroups = [];
$qualityRuleLabels = [
'image-alt' => phpb_trans('website-manager.quality-rule-image-alt'),
'form-control-name' => phpb_trans('website-manager.quality-rule-form-control-name'),
'heading-level' => phpb_trans('website-manager.quality-rule-heading-level'),
'missing-internal-route' => phpb_trans('website-manager.quality-rule-missing-internal-route'),
'missing-local-asset' => phpb_trans('website-manager.quality-rule-missing-local-asset'),
'coverage-error' => phpb_trans('website-manager.quality-rule-coverage-error'),
];
foreach ($qualityItems as $qualityItem) {
$pageId = (string) ($qualityItem['page_id'] ?? '');
$locale = (string) ($qualityItem['locale'] ?? '');
$groupKey = $pageId . '|' . $locale;
if (! isset($qualityGroups[$groupKey])) {
$qualityGroups[$groupKey] = [
'page_id' => $pageId,
'page_name' => (string) ($qualityItem['page_name'] ?? ''),
'route' => (string) ($qualityItem['route'] ?? ''),
'locale' => $locale,
'rules' => [],
];
}
$rule = (string) ($qualityItem['rule'] ?? '');
$qualityGroups[$groupKey]['rules'][$rule][] = $qualityItem;
}
?>
<section class="space-y-5">
<header class="space-y-1">
<h2 class="text-xl font-bold tracking-tight text-base-content"><?= phpb_trans('website-manager.quality-heading') ?></h2>
<p class="max-w-3xl text-sm leading-relaxed text-base-content/60"><?= phpb_trans('website-manager.quality-description') ?></p>
</header>
<div class="card card-border bg-base-100 shadow-sm">
<div class="card-body gap-4 p-4 sm:p-6">
<p class="text-sm leading-relaxed text-base-content/70"><?= phpb_trans('website-manager.quality-synchronous-note') ?></p>
<form method="post" action="<?= phpb_e(phpb_url('website_manager', ['route' => 'quality', 'action' => 'scan', 'tab' => 'quality'])) ?>" x-data="{scanning: false}" @submit="scanning = true">
<?php phpb_csrf_field(); ?>
<div class="mb-4" role="status" x-cloak x-show="scanning">
<div class="alert alert-info alert-soft">
<i class="ph ph-spinner-gap animate-spin" aria-hidden="true"></i>
<span><?= phpb_trans('website-manager.quality-running') ?></span>
</div>
</div>
<button class="btn" type="submit" :disabled="scanning">
<i class="ph ph-magnifying-glass" aria-hidden="true"></i>
<span x-show="!scanning"><?= phpb_trans('website-manager.quality-run-scan') ?></span>
<span x-cloak x-show="scanning"><?= phpb_trans('website-manager.quality-running') ?></span>
</button>
</form>
</div>
</div>
<?php if ($qualityReport === null): ?>
<div class="alert alert-info alert-soft" role="status">
<i class="ph ph-info" aria-hidden="true"></i>
<span><?= phpb_trans('website-manager.quality-awaiting-scan') ?></span>
</div>
<?php else: ?>
<div class="flex flex-wrap items-center gap-3 rounded-box border border-base-300 bg-base-100 px-4 py-3">
<span class="badge badge-outline"><?= (int) ($qualityReport['pages_checked'] ?? 0) ?> <?= phpb_trans('website-manager.quality-pages-checked') ?></span>
<span class="badge badge-outline"><?= count($qualityFindings) ?> <?= phpb_trans('website-manager.quality-findings-count') ?></span>
<span class="badge badge-outline"><?= count($qualityErrors) ?> <?= phpb_trans('website-manager.quality-errors-count') ?></span>
</div>
<?php if (empty($qualityItems)): ?>
<div class="alert alert-success alert-soft" role="status">
<i class="ph ph-check-circle" aria-hidden="true"></i>
<span><?= phpb_trans('website-manager.quality-no-findings') ?></span>
</div>
<?php else: ?>
<section class="space-y-4" aria-label="<?= phpb_e(phpb_trans('website-manager.quality-report')) ?>">
<?php foreach ($qualityGroups as $qualityGroup): ?>
<article class="card card-border bg-base-100 shadow-sm">
<div class="card-body gap-4 p-4 sm:p-6">
<header class="flex flex-col gap-2 border-b border-base-300 pb-4 sm:flex-row sm:items-start sm:justify-between">
<div class="min-w-0 space-y-1">
<h3 class="text-lg font-semibold text-base-content">
<?= phpb_e($qualityGroup['page_name'] !== '' ? $qualityGroup['page_name'] : $qualityGroup['page_id']) ?>
</h3>
<p class="break-all text-sm text-base-content/60"><?= phpb_e($qualityGroup['route']) ?></p>
</div>
<span class="badge badge-ghost"><?= phpb_e($qualityGroup['locale']) ?></span>
</header>
<?php foreach ($qualityGroup['rules'] as $rule => $ruleFindings): ?>
<section class="space-y-2">
<h4 class="font-semibold text-base-content"><?= phpb_e($qualityRuleLabels[$rule] ?? $rule) ?></h4>
<ul class="space-y-2">
<?php foreach ($ruleFindings as $qualityItem): ?>
<?php $severity = ($qualityItem['severity'] ?? '') === 'error' ? 'error' : 'warning'; ?>
<?php $severityClass = $severity === 'error' ? 'badge-error' : 'badge-warning'; ?>
<li class="rounded-box border border-base-300 bg-base-200/40 p-3">
<div class="mb-2 flex flex-wrap items-center gap-2">
<span class="badge <?= $severityClass ?> badge-soft">
<?= phpb_trans('website-manager.quality-severity-' . $severity) ?>
</span>
</div>
<p class="text-sm leading-relaxed text-base-content/80"><?= phpb_e($qualityItem['explanation'] ?? '') ?></p>
<?php if (! empty($qualityItem['target'])): ?>
<p class="mt-2 break-all text-xs text-base-content/60">
<?= phpb_trans('website-manager.quality-target') ?>:
<code class="rounded bg-base-300/70 px-1.5 py-0.5 text-base-content"><?= phpb_e($qualityItem['target']) ?></code>
</p>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</section>
<?php endforeach; ?>
</div>
</article>
<?php endforeach; ?>
</section>
<?php endif; ?>
<?php endif; ?>
</section>
@@ -7,24 +7,28 @@ $settingIns = phpb_instance('setting');
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'settings', 'action' => 'update', 'tab' => 'settings']) ?>">
<?php phpb_csrf_field(); ?>
<div class="" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
<div class="tabs mb-6">
<div class="border-b border-base-300 grow"></div>
<div class="space-y-6" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
<header class="space-y-1">
<h2 class="text-xl font-bold tracking-tight text-base-content">Site settings</h2>
<p class="text-sm text-base-content/60">Configure language, appearance, and extension options for this site.</p>
</header>
<div class="tabs tabs-border mb-6 max-w-full gap-1 overflow-x-auto" role="tablist" aria-label="Site settings sections">
<template x-for="(tab, index) in tabs">
<a class="tab tab-lifted" x-text="tab" @click="activeTab = index" :class="activeTab === index ? 'tab-active' : ''"></a>
<button type="button" class="tab" role="tab" :id="'settings-tab-' + index" :aria-controls="'settings-panel-' + index" :aria-selected="activeTab === index" :tabindex="activeTab === index ? 0 : -1" x-text="tab" @click="activeTab = index" :class="activeTab === index ? 'tab-active' : ''"></button>
</template>
<div class="border-b border-base-300 grow"></div>
</div>
<div class="" x-show="activeTab === 0">
<div id="settings-panel-0" class="rounded-box border border-base-300 bg-base-200/50 p-4 text-sm text-base-content/70 sm:p-5" role="tabpanel" aria-labelledby="settings-tab-0" tabindex="0" x-show="activeTab === 0">
Website-wide options are organized in the Language, Theme, and Extensions sections.
</div>
<div class="" x-show="activeTab === 1">
<div class="w-full mb-6">
<div class="label-text text-left"><?= phpb_trans('website-manager.website-languages') ?></div>
<div id="settings-panel-1" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-1" tabindex="0" x-show="activeTab === 1">
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
<h2 class="text-lg font-semibold"><?= phpb_trans('website-manager.website-languages') ?></h2>
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<?php
foreach (phpb_trans('languages') as $locale => $localeText):
?>
<div class="form-control">
<label class="label cursor-pointer">
<label class="flex cursor-pointer items-center justify-between gap-4 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition-colors hover:border-primary/40 hover:bg-base-200/50">
<span class="label-text"><?= phpb_e($localeText) ?></span>
<input type="checkbox" name="languages[]" value="<?= phpb_e($locale) ?>" <?= phpb_e($settingIns::has('languages', $locale)) ? 'checked' : '' ?> class="checkbox checkbox-sm" />
</label>
@@ -32,64 +36,67 @@ $settingIns = phpb_instance('setting');
<?php
endforeach;
?>
</div>
<div class="form-control w-full mb-6">
<label for="admin_language" class="label">
<span class="label-text"><?= phpb_trans('website-manager.admin-language') ?> <strong><?= phpb_current_language() ?></strong></span>
</label>
<select class="select select-bordered w-full" id="admin_language" name="admin_language" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
<?php
$beLanguages = ['de', 'en', 'sv'];
foreach ($beLanguages as $locale):
</div>
</section>
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
<div class="form-control w-full">
<label for="admin_language" class="label">
<span class="label-text"><?= phpb_trans('website-manager.admin-language') ?> <strong><?= phpb_current_language() ?></strong></span>
</label>
<select class="select select-bordered w-full" id="admin_language" name="admin_language" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
<?php
$beLanguages = ['de', 'en', 'sv'];
foreach ($beLanguages as $locale):
?>
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(phpb_config('general.language') === $locale ? 'selected' : '') ?>><?= phpb_e(phpb_trans('languages.'.$locale)) ?></option>
<?php
endforeach;
?>
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(phpb_config('general.language') === $locale ? 'selected' : '') ?>><?= phpb_e(phpb_trans('languages.'.$locale)) ?></option>
</select>
</div>
</section>
</div>
<div id="settings-panel-2" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-2" tabindex="0" x-show="activeTab === 2">
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
<div class="form-control w-full">
<label for="selected_theme" class="label">
<span class="label-text"><?= phpb_trans('website-manager.selected-theme') ?></span>
</label>
<select class="select select-bordered w-full" id="selected_theme" name="selected_theme" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
<?php
$themes = phpb_themes();
foreach ($themes as $theme => $themeConfig):
?>
<option value="<?= phpb_e($theme) ?>" <?= phpb_e(phpb_config('theme.active_theme') === $theme ? 'selected' : '') ?>><?= phpb_e($themeConfig['title']) ?></option>
<?php
endforeach;
?>
</select>
</div>
</select>
</div>
</section>
</div>
<div class="" x-show="activeTab === 2">
<div class="form-control w-full mb-6">
<label for="selected_theme" class="label">
<span class="label-text"><?= phpb_trans('website-manager.selected-theme') ?></span>
</label>
<select class="select select-bordered w-full" id="selected_theme" name="selected_theme" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
<?php
$themes = phpb_themes();
foreach ($themes as $theme => $themeConfig):
?>
<option value="<?= phpb_e($theme) ?>" <?= phpb_e(phpb_config('theme.active_theme') === $theme ? 'selected' : '') ?>><?= phpb_e($themeConfig['title']) ?></option>
<?php
endforeach;
?>
</select>
</div>
</div>
<div class="" x-show="activeTab === 3">
<div class="flex flex-col gap-6">
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
<div class="flex flex-col gap-4">
<?php
foreach (Extensions::getConfigs() as $extKey => $config):
if(count(Extensions::getSettings($extKey)) === 0){
continue;
}
?>
<details class="collapse collapse-plus bg-base-200">
<summary class="collapse-title text-xl font-medium"><?= phpb_e($config['title']) ?></summary>
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
<summary class="collapse-title text-lg font-semibold"><?= phpb_e($config['title']) ?></summary>
<div class="collapse-content">
<div class="">
<div class="space-y-4">
<?php
foreach (Extensions::getSettings($extKey) as $setting):
?>
<?php
if ($setting['type'] === 'text'):
?>
<div class="form-control w-full">
<label class="label">
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
</label>
<label class="form-control w-full gap-2">
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
<input type="text" name="<?= phpb_e($setting['key']) ?>" value="<?= phpb_e($setting['value']) ?>" class="input input-bordered w-full" />
</div>
</label>
<?php
endif;
?>
@@ -100,7 +107,7 @@ $settingIns = phpb_instance('setting');
<label class="label cursor-pointer">
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
<input type='hidden' :value="state" name="<?= phpb_e($setting['key']) ?>">
<input type="checkbox" class="toggle" x-model="state" />
<input type="checkbox" class="toggle" x-model="state" />
</label>
</div>
<?php
@@ -117,8 +124,9 @@ $settingIns = phpb_instance('setting');
?>
</div>
</div>
<div class="text-center mt-8">
<button class="btn btn-primary ">
<div class="flex justify-end border-t border-base-300 pt-6">
<button type="submit" class="btn btn-primary">
<i class="ph-bold ph-floppy-disk" aria-hidden="true"></i>
<?= phpb_trans('website-manager.save-settings'); ?>
</button>
</div>
@@ -1,10 +1,21 @@
<div id="welcome-page">
<h1 class="text-center">Welcome to Plugi Page Builder</h1>
<div class="text-center intro-links">
<a href="<?= phpb_url('website_manager') ?>">Get started</a>
<a href="https://github.com/deepDiverPaul/plugi" target="_blank"><i class="fab fa-github"></i> Visit GitHub</a>
</div>
</div>
<main id="welcome-page" class="mx-auto flex min-h-full w-full max-w-5xl flex-1 items-center px-4 py-10 sm:px-6 lg:py-16">
<section class="card w-full overflow-hidden border border-base-300 bg-base-100 shadow-xl shadow-base-content/5">
<div class="h-2 bg-gradient-to-r from-primary via-secondary to-accent" aria-hidden="true"></div>
<div class="card-body items-center gap-7 p-8 text-center sm:p-12 lg:p-16">
<span class="grid size-20 place-items-center rounded-[1.75rem] bg-primary text-primary-content shadow-lg shadow-primary/20">
<i class="text-4xl ph-bold ph-brackets-square rotate-90" aria-hidden="true"></i>
</span>
<div class="space-y-2">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-primary">Your site workspace</p>
<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl">Welcome to Plugi Page Builder</h1>
<p class="mx-auto max-w-xl text-base leading-relaxed text-base-content/70">Manage your pages, menus, and files from one clear, focused workspace.</p>
</div>
<div class="card-actions flex-col gap-3 sm:flex-row">
<a class="btn btn-primary" href="<?= phpb_url('website_manager') ?>">Get started</a>
<a class="btn btn-outline" href="https://github.com/deepDiverPaul/plugi" target="_blank" rel="noopener noreferrer">
Visit GitHub
</a>
</div>
</div>
</section>
</main>
+5 -13
View File
@@ -129,14 +129,7 @@ class Page implements PageContract
public function getTranslation(string $setting, ?string $locale = null)
{
$translations = $this->getTranslations();
if (empty($translations)) {
return null;
}
$locale = $locale ?? phpb_config('general.language');
return $translations[$locale][$setting] ??
$translations['en'][$setting] ??
$translations[array_keys($translations)[0]][$setting] ??
null;
return (new PageTranslationService())->resolveTranslation($translations, $setting, $locale);
}
/**
@@ -178,11 +171,10 @@ class Page implements PageContract
*/
public function invalidateCache()
{
$cache = phpb_instance('cache');
$routes = array_map(function ($translation) {
return $translation['route'] ?? null;
}, $this->getTranslations());
foreach ($this->getTranslations() as $locale => $translationData) {
$languageRoute = $this->getRoute($locale);
$cache->invalidate($languageRoute);
}
(new PageTranslationService())->invalidateRoutes($routes);
}
}
+206
View File
@@ -0,0 +1,206 @@
<?php
namespace Plugi;
use Plugi\Repositories\PageTranslationRepository;
class PageTranslationService
{
/**
* Return the requested locale, configured default, or first available locale, in that order.
*
* @param string|null $locale
* @param array $availableLocales
* @return string[]
*/
public function getLocaleFallbackOrder(?string $locale, array $availableLocales): array
{
$availableLocales = $this->getAvailableLocales($availableLocales);
$fallbackLocales = [];
foreach ([$locale, phpb_config('general.language')] as $preferredLocale) {
if (is_string($preferredLocale) && in_array($preferredLocale, $availableLocales, true)) {
$fallbackLocales[] = $preferredLocale;
}
}
foreach ($availableLocales as $availableLocale) {
$fallbackLocales[] = $availableLocale;
}
return array_values(array_unique($fallbackLocales));
}
/**
* Resolve a locale using the shared fallback order.
*
* @param string|null $locale
* @param array $availableLocales
* @return string|null
*/
public function resolveLocale(?string $locale, array $availableLocales): ?string
{
return $this->getLocaleFallbackOrder($locale, $availableLocales)[0] ?? null;
}
/**
* Determine whether a locale is active without applying fallback.
*
* @param string|null $locale
* @param array $availableLocales
* @return bool
*/
public function isAvailableLocale(?string $locale, array $availableLocales): bool
{
return $locale !== null && in_array($locale, $this->getAvailableLocales($availableLocales), true);
}
/**
* Return the setting from the first translation containing a non-null value.
*
* @param array $translations
* @param string $setting
* @param string|null $locale
* @return mixed|null
*/
public function resolveTranslation(array $translations, string $setting, ?string $locale = null)
{
foreach ($this->getLocaleFallbackOrder($locale, array_keys($translations)) as $fallbackLocale) {
if (array_key_exists($setting, $translations[$fallbackLocale]) && $translations[$fallbackLocale][$setting] !== null) {
return $translations[$fallbackLocale][$setting];
}
}
return null;
}
/**
* Return every stored route for a page, including inactive locales.
*
* @param mixed $pageId
* @return string[]
*/
public function getPageRoutes($pageId): array
{
$translations = (new PageTranslationRepository())->getForPages([$pageId]);
$routes = [];
foreach ($translations as $translation) {
$route = $translation->route ?? null;
if (is_string($route) && $route !== '') {
$routes[] = $route;
}
}
$routes = array_values(array_unique($routes));
sort($routes, SORT_STRING);
return $routes;
}
/**
* Invalidate routes after their corresponding persistence operation succeeds.
*
* @param array $routes
*/
public function invalidateRoutes(array $routes): void
{
$routes = array_values(array_unique(array_filter($routes, function ($route) {
return is_string($route) && $route !== '';
})));
sort($routes, SORT_STRING);
if (empty($routes)) {
return;
}
$cache = phpb_instance('cache');
if (! $cache) {
return;
}
foreach ($routes as $route) {
$cache->invalidate($route);
}
}
/**
* Return actual saved translation coverage for the given pages and active locales.
*
* @param array $pages
* @param array $activeLanguages
* @return array
*/
public function getPageCoverage(array $pages, array $activeLanguages): array
{
$coverage = [];
$pageTypes = [];
$pageIds = [];
foreach ($pages as $page) {
$pageId = (string) $page->getId();
$pageIds[] = $page->getId();
$pageTypes[$pageId] = $page->get('type');
$coverage[$pageId] = [
'completeCount' => 0,
'localeCount' => count($activeLanguages),
'locales' => [],
];
foreach ($activeLanguages as $locale => $language) {
$coverage[$pageId]['locales'][$locale] = [
'exists' => false,
'complete' => false,
'title' => null,
'route' => null,
];
}
}
if (empty($pageIds)) {
return $coverage;
}
$foreignKey = phpb_config('page.translation.foreign_key');
$translations = (new PageTranslationRepository())->getForPages($pageIds);
foreach ($translations as $translation) {
$pageId = (string) ($translation->$foreignKey ?? '');
$locale = $translation->locale ?? null;
if (! isset($coverage[$pageId]) || ! is_string($locale) || ! array_key_exists($locale, $activeLanguages)) {
continue;
}
$title = $translation->title ?? null;
$route = $translation->route ?? null;
$target = $translation->target ?? null;
$hasRequiredValue = $pageTypes[$pageId] === 'redirect'
? trim((string) $target) !== ''
: trim((string) $title) !== '';
$isComplete = trim((string) $route) !== '' && $hasRequiredValue;
$coverage[$pageId]['locales'][$locale] = [
'exists' => true,
'complete' => $isComplete,
'title' => $title,
'route' => $route,
];
if ($isComplete) {
$coverage[$pageId]['completeCount']++;
}
}
return $coverage;
}
/**
* Normalize a list or locale-keyed language map to locale codes.
*
* @param array $availableLocales
* @return string[]
*/
private function getAvailableLocales(array $availableLocales): array
{
if ($availableLocales === [] || array_keys($availableLocales) !== range(0, count($availableLocales) - 1)) {
$availableLocales = array_keys($availableLocales);
}
return array_values(array_filter($availableLocales, function ($availableLocale) {
return is_string($availableLocale) && $availableLocale !== '';
}));
}
}
+13 -1
View File
@@ -234,7 +234,19 @@ class Plugi
public function checkDatabaseDefinition()
{
global $phpb_db;
if (Setting::get('db-definition') !== $phpb_db->getDBDefinitionHash()) {
$schemaNeedsUpdate = Setting::get('db-definition') !== $phpb_db->getDBDefinitionHash();
if (! $schemaNeedsUpdate) {
foreach ($phpb_db->diffDB() as $tableDiff) {
if ($tableDiff === false
|| ! empty($tableDiff['columns'])
|| ! empty($tableDiff['uniqueKeys'])) {
$schemaNeedsUpdate = true;
break;
}
}
}
if ($schemaNeedsUpdate) {
$module = 'website_manager';
$parameters = [
['tab' => 'info'],
+27 -11
View File
@@ -5,6 +5,7 @@ namespace Plugi\Repositories;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\PageRepositoryContract;
use Plugi\Contracts\PageTranslationContract;
use Plugi\PageTranslationService;
class PageRepository extends BaseRepository implements PageRepositoryContract
{
@@ -90,7 +91,10 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return false;
}
$updateResult = $this->db->transaction(function () use ($page, $data) {
$translationService = new PageTranslationService();
$oldRoutes = [];
$updateResult = $this->db->transaction(function () use ($page, $data, $translationService, &$oldRoutes) {
$oldRoutes = $translationService->getPageRoutes($page->getId());
if (! $this->replaceTranslations($page, $data)) {
return false;
}
@@ -102,7 +106,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
]);
});
if ($updateResult) {
$page->invalidateCache();
$translationService->invalidateRoutes(array_merge($oldRoutes, array_values($data['route'])));
}
return $updateResult;
}
@@ -185,13 +189,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$routes[$route] = true;
}
$foreignKey = phpb_config('page.translation.foreign_key');
$pageTranslationRepository = new PageTranslationRepository;
foreach ($pageTranslationRepository->getAll(['route', $foreignKey]) as $translation) {
if ($pageId !== null && (string) $translation->$foreignKey === (string) $pageId) {
continue;
}
if (array_key_exists($translation->route, $routes)) {
foreach (array_keys($routes) as $route) {
if ($pageTranslationRepository->routeExists($route, $pageId)) {
return true;
}
}
@@ -211,7 +211,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$updateResult = parent::update($page, [
'data' => json_encode($data),
]);
$page->invalidateCache();
if ($updateResult) {
$page->invalidateCache();
}
return $updateResult;
}
@@ -223,8 +225,22 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*/
public function destroy($id)
{
$this->findWithId($id)->invalidateCache();
$translationService = new PageTranslationService();
$routes = [];
$destroyResult = $this->db->transaction(function () use ($id, $translationService, &$routes) {
$routes = $translationService->getPageRoutes($id);
$pageTranslationRepository = new PageTranslationRepository();
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $id)) {
return false;
}
return parent::destroy($id);
return parent::destroy($id);
});
if ($destroyResult) {
$translationService->invalidateRoutes($routes);
}
return $destroyResult;
}
}
@@ -29,4 +29,47 @@ class PageTranslationRepository extends BaseRepository implements PageTranslatio
parent::__construct();
$this->class = phpb_instance('page.translation');
}
/**
* Determine whether a route is already used by another page translation.
*
* @param string $route
* @param mixed|null $excludedPageId
* @return bool
*/
public function routeExists(string $route, $excludedPageId = null): bool
{
$query = "SELECT 1 FROM {$this->table} WHERE route = ?";
$parameters = [$route];
if ($excludedPageId !== null) {
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
$query .= " AND {$foreignKey} != ?";
$parameters[] = $excludedPageId;
}
$query .= ' LIMIT 1';
return ! empty($this->db->select($query, $parameters));
}
/**
* Return translations belonging to the given page IDs.
*
* @param array $pageIds
* @return array
*/
public function getForPages(array $pageIds): array
{
if (empty($pageIds)) {
return [];
}
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
$placeholders = implode(', ', array_fill(0, count($pageIds), '?'));
$records = $this->db->select(
"SELECT * FROM {$this->table} WHERE {$foreignKey} IN ({$placeholders})",
array_values($pageIds)
);
return $this->createInstances($records);
}
}
@@ -0,0 +1,110 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const sourcePath = new URL('../src/Modules/GrapesJS/resources/assets/js/save-page.js', import.meta.url);
const source = fs.readFileSync(sourcePath, 'utf8');
class TestElement {
constructor() {
this._innerHTML = '';
}
set innerHTML(value) {
this._innerHTML = value;
}
get innerHTML() {
return this._innerHTML;
}
querySelectorAll() {
const pattern = /<div([^>]*\bphpb-blocks-container\b[^>]*)>([\s\S]*?)<\/div>/g;
return [...this._innerHTML.matchAll(pattern)].map((match, index) => {
return new TestContainer(this, index, `<div${match[1]}>`, match[2]);
});
}
replaceContainer(index, containerHtml) {
const pattern = /<div([^>]*\bphpb-blocks-container\b[^>]*)>([\s\S]*?)<\/div>/g;
let currentIndex = 0;
this._innerHTML = this._innerHTML.replace(pattern, match => {
return currentIndex++ === index ? containerHtml : match;
});
}
appendChild(container) {
this._innerHTML += container.outerHTML;
}
}
class TestContainer {
constructor(parent, index, openingTag, innerHTML) {
this.parent = parent;
this.index = index;
this.openingTag = openingTag;
this._innerHTML = innerHTML;
}
set innerHTML(value) {
this._innerHTML = value;
this.parent.replaceContainer(this.index, `${this.openingTag}${value}</div>`);
}
get innerHTML() {
return this._innerHTML;
}
get outerHTML() {
return `${this.openingTag}${this._innerHTML}</div>`;
}
cloneNode() {
return new TestContainer(null, 0, this.openingTag, this._innerHTML);
}
}
const window = {};
const document = {
getElementById: () => null,
addEventListener: () => {},
createElement: () => new TestElement(),
};
vm.runInNewContext(source, { window, document, console, setTimeout, URLSearchParams });
const sourceBlocks = {
parent: {
html: '<p>Source locale text</p><div phpb-blocks-container>[block slug="child" id="new-child"]</div>',
settings: {label: 'Source setting'},
blocks: {
existingChild: {html: '<p>Source child text</p>', settings: {label: 'Source child setting'}},
newChild: {html: '<p>New shared block</p>', settings: {label: 'New setting'}},
},
},
newParent: {html: '<p>New shared parent</p>', settings: {label: 'New parent setting'}},
};
const targetBlocks = {
parent: {
html: '<p>Translated parent text</p><div phpb-blocks-container>[block slug="child" id="existing-child"]</div>',
settings: {label: 'Translated parent setting'},
blocks: {
existingChild: {html: '<p>Existing translated child</p>', settings: {label: 'Translated child setting'}},
},
},
localeOnlyParent: {html: '<p>Existing locale-only content</p>'},
};
const synchronizedBlocks = window.synchronizePageBlockVariants(sourceBlocks, targetBlocks);
assert.match(synchronizedBlocks.parent.html, /Translated parent text/);
assert.match(synchronizedBlocks.parent.html, /id="new-child"/);
assert.equal(synchronizedBlocks.parent.settings.label, 'Translated parent setting');
assert.equal(synchronizedBlocks.parent.blocks.existingChild.html, '<p>Existing translated child</p>');
assert.equal(synchronizedBlocks.parent.blocks.existingChild.settings.label, 'Translated child setting');
assert.equal(synchronizedBlocks.parent.blocks.newChild.html, '<p>New shared block</p>');
assert.equal(synchronizedBlocks.newParent.html, '<p>New shared parent</p>');
assert.equal(synchronizedBlocks.localeOnlyParent.html, '<p>Existing locale-only content</p>');
sourceBlocks.parent.blocks.newChild.html = '<p>Source changed after synchronization</p>';
assert.equal(synchronizedBlocks.parent.blocks.newChild.html, '<p>New shared block</p>');
console.log('PASS: shared block structure synchronizes without overwriting existing locale content.');
@@ -7,6 +7,7 @@ use Plugi\Modules\GrapesJS\PageBuilder;
use Plugi\Modules\Router\DatabasePageRouter;
use Plugi\Page;
use Plugi\PageTranslation;
use Plugi\Setting;
use Plugi\Modules\WebsiteManager\WebsiteManager;
use Plugi\Repositories\PageRepository;
@@ -18,21 +19,41 @@ require_once __DIR__ . '/../src/Contracts/WebsiteManagerContract.php';
require_once __DIR__ . '/../src/Contracts/RouterContract.php';
require_once __DIR__ . '/../src/Contracts/PageBuilderContract.php';
require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
require_once __DIR__ . '/../src/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
require_once __DIR__ . '/../src/PageTranslationService.php';
require_once __DIR__ . '/../src/Page.php';
require_once __DIR__ . '/../src/PageTranslation.php';
require_once __DIR__ . '/../src/Setting.php';
require_once __DIR__ . '/../src/Repositories/PageRepository.php';
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php';
require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
require_once __DIR__ . '/../src/Plugi.php';
class PageCreationRedirectException extends RuntimeException
{
public function __construct(public string $redirectUrl)
{
parent::__construct('Redirect requested.');
}
}
class PageCreationTestDatabase extends DB
{
public int $translationInsertCount = 0;
public int $pageTranslationAllCallCount = 0;
public int $pageTranslationBatchSelectCount = 0;
public ?int $failOnTranslationInsert = null;
public bool $throwOnTranslationFailure = false;
public ?string $failOnDeleteTable = null;
public bool $throwOnDeleteFailure = false;
public bool $failOnPageUpdate = false;
public array $schemaDiffs = [];
public function __construct()
{
@@ -43,6 +64,16 @@ class PageCreationTestDatabase extends DB
public function query(string $query, array $parameters = [])
{
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
if ($this->throwOnDeleteFailure) {
throw new PDOException('Simulated page deletion failure.');
}
return false;
}
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
return false;
}
if (str_starts_with($query, 'INSERT INTO page_translations')) {
$this->translationInsertCount++;
if ($this->translationInsertCount === $this->failOnTranslationInsert) {
@@ -56,6 +87,24 @@ class PageCreationTestDatabase extends DB
return parent::query($query, $parameters);
}
public function all(string $table, array|string $columns = '*'): array
{
if ($table === 'page_translations') {
$this->pageTranslationAllCallCount++;
}
return parent::all($table, $columns);
}
public function select(string $query, array $parameters): array
{
if (str_starts_with($query, 'SELECT * FROM page_translations WHERE page_id IN (')) {
$this->pageTranslationBatchSelectCount++;
}
return parent::select($query, $parameters);
}
public function createSchema(): void
{
$this->pdo->exec('CREATE TABLE pages (
@@ -84,12 +133,79 @@ class PageCreationTestDatabase extends DB
)');
}
public function diffDB(): array
{
return $this->schemaDiffs;
}
public function getDBDefinitionHash(): string
{
return 'test-schema-hash';
}
public function rows(string $table): array
{
return $this->select("SELECT * FROM {$table}", []);
}
}
class PageCreationSchemaMigrationTestDatabase extends DB
{
public array $queries = [];
public function __construct()
{
}
public function diffDB(): array
{
return [
'pages' => [
'columns' => ['type' => 'varchar(63)'],
'uniqueKeys' => [],
],
'page_translations' => [
'columns' => ['target' => 'varchar(255)'],
'uniqueKeys' => [],
],
'missing_table' => false,
];
}
public function getDBDefinition(): array
{
return [
'pages' => ['columns' => ['type' => 'varchar(63)'], 'uniqueKeys' => []],
'page_translations' => ['columns' => ['target' => 'varchar(255)'], 'uniqueKeys' => []],
'missing_table' => [
'columns' => ['label' => 'varchar(255)'],
'uniqueKeys' => ['label' => ['label']],
],
];
}
public function query(string $query, array $parameters = [])
{
$this->queries[] = $query;
return true;
}
public function select(string $query, array $parameters): array
{
return [];
}
public function lastInsertId(): string
{
return '0';
}
public function getDBDefinitionHash(): string
{
return 'test-schema-hash';
}
}
class PageCreationTestWebsiteManager extends WebsiteManager
{
public ?string $renderedErrorMessage = null;
@@ -102,8 +218,11 @@ class PageCreationTestWebsiteManager extends WebsiteManager
class PageCreationTestCache
{
public static array $invalidatedRoutes = [];
public function invalidate(string $route): void
{
self::$invalidatedRoutes[] = $route;
}
}
@@ -165,6 +284,26 @@ function phpb_url(string $module, array $parameters = []): string
return '/' . $module;
}
function phpb_on_url(string $module, array $parameters = []): bool
{
return false;
}
function phpb_current_relative_url(): string
{
return '/admin/page_settings';
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{
throw new PageCreationRedirectException($url);
}
function phpb_full_url(string $route): string
{
return 'https://example.test' . $route;
}
function phpb_csrf_field(): void
{
}
@@ -175,6 +314,9 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
$_ENV['DATABASE_PREFIX'] = '';
$pageCreationConfig = [
'general' => [
'language' => 'en',
],
'page' => [
'table' => 'pages',
'translation' => [
@@ -184,6 +326,7 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
],
];
$pageCreationLanguages = $languages;
PageCreationTestCache::$invalidatedRoutes = [];
$phpb_db = new PageCreationTestDatabase();
$phpb_db->createSchema();
}
@@ -222,6 +365,71 @@ function runPageCreationCase(string $name, callable $case): bool
}
$cases = [
'startup prompts for database updates when schema drifts despite a matching hash' => function (): void {
resetPageCreationDatabase();
global $phpb_db, $pageCreationConfig;
$pageCreationConfig['auth'] = ['url' => '/auth'];
$phpb_db->schemaDiffs = [
'pages' => [
'columns' => ['type' => 'varchar(63)'],
'uniqueKeys' => [],
],
];
$settings = new ReflectionProperty(Setting::class, 'settings');
$settings->setValue(null, ['db-definition' => $phpb_db->getDBDefinitionHash()]);
try {
(new \Plugi\Plugi())->checkDatabaseDefinition();
} catch (PageCreationRedirectException $exception) {
assertPageCreation(
$exception->redirectUrl === '/website_manager',
'Schema drift redirected to an unexpected page.'
);
return;
}
throw new RuntimeException('Schema drift with a matching hash did not prompt for a database update.');
},
'database updates apply lowercase schema definitions needed to create pages' => function (): void {
$_ENV['DATABASE_PREFIX'] = '';
$database = new PageCreationSchemaMigrationTestDatabase();
global $phpb_db;
$phpb_db = $database;
$database->resolveDiffDB();
assertPageCreation(
in_array('ALTER TABLE pages ADD type varchar(63)', $database->queries, true),
'Database update skipped the lowercase pages.type definition.'
);
assertPageCreation(
in_array('ALTER TABLE page_translations ADD target varchar(255)', $database->queries, true),
'Database update skipped the lowercase page_translations.target definition.'
);
assertPageCreation(
in_array('ALTER TABLE missing_table ADD label varchar(255)', $database->queries, true),
'Database update did not add configured columns to a newly created table.'
);
assertPageCreation(
in_array('ALTER TABLE missing_table ADD UNIQUE KEY label (`label`)', $database->queries, true),
'Database update skipped a lowercase unique-key definition.'
);
},
'configured locale is preferred over the first available translation' => function (): void {
resetPageCreationDatabase(['de' => [], 'fr' => []]);
global $pageCreationConfig;
$pageCreationConfig['general']['language'] = 'fr';
$page = new Page();
$page->setTranslations([
'de' => ['title' => 'Deutscher Titel'],
'fr' => ['title' => 'Titre français'],
]);
assertPageCreation(
$page->getTranslation('title', 'it') === 'Titre français',
'Missing requested locale should fall back to the configured default, not the first saved locale.'
);
},
'locked generated routes do not leave a base page without translations' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload();
@@ -321,6 +529,72 @@ $cases = [
assertPageCreation(str_contains($malformedHtml, '\\u0027\\u003C/script\\u003E'), 'Submitted route was not safely encoded for Alpine.');
$_POST = [];
},
'page settings leave missing locale values blank and explain the missing translation' => function (): void {
resetPageCreationDatabase();
$page = new Page();
$page->setData([
'id' => 42,
'name' => 'English page',
'layout' => 'default',
'type' => 'static',
]);
$page->setTranslations([
'en' => [
'title' => 'English title',
'route' => '/english-page',
'meta_title' => '',
'meta_description' => '',
'target' => '',
],
]);
$_POST = [];
$action = 'edit';
$errorMessage = null;
$theme = new class {
public function getThemeLayouts(): array
{
return [new class {
public function getSlug(): string
{
return 'default';
}
public function getTitle(): string
{
return 'Default';
}
}];
}
};
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/page-settings.php';
$html = ob_get_clean();
preg_match('/name="title\[de\]" value="([^"]*)"/', $html, $germanTitle);
assertPageCreation(($germanTitle[1] ?? null) === '', 'Missing German title was filled from the English translation.');
assertPageCreation(str_contains($html, 'No saved translation exists for this language.'), 'The missing locale was not explained.');
assertPageCreation(str_contains($html, 'Each language shows its own saved values; missing translations are left blank instead of using fallback text.'), 'Locale-specific editing guidance was not shown.');
$_POST = [];
},
'homepage routes persist for the submitted English and German values' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload([
'name' => 'Hom',
'layout' => 'master',
'title' => ['en' => 'Home', 'de' => 'Start'],
'route' => ['en' => '/', 'de' => '/de/'],
]);
$page = (new PageRepository())->create($payload);
global $phpb_db;
$translations = $phpb_db->rows('page_translations');
assertPageCreation($page === true, 'The submitted homepage payload did not create a page.');
assertPageCreation(count($translations) === 2, 'The homepage did not persist both localized translations.');
assertPageCreation($translations[0]['route'] === '/', 'The English homepage route was not preserved.');
assertPageCreation($translations[1]['route'] === '/de/', 'The German homepage route was not preserved.');
},
'generated routes persist for every active locale' => function (): void {
resetPageCreationDatabase();
@@ -403,6 +677,156 @@ $cases = [
assertPageCreation($secondPage === false, 'Duplicate route was not rejected.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Duplicate create left an extra base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Duplicate create changed translations.');
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
},
'route collision checks allow an unchanged page route and reject another locale collision' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
assertPageCreation($repository->update($page, pageCreationPayload()) === true, 'An unchanged route should not collide with its own page.');
assertPageCreation(
$repository->create(pageCreationPayload([
'name' => 'German route collision',
'route' => ['en' => '/unique-route', 'de' => '/de/new-page'],
])) === false,
'A route collision in a non-default locale was not rejected.'
);
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
},
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/complete-en', 'de' => '/complete-de'],
]));
$repository->create(pageCreationPayload([
'name' => 'Partial page',
'route' => ['en' => '/partial-en', 'de' => '/partial-de'],
]));
$repository->create(pageCreationPayload([
'name' => 'Missing locale page',
'route' => ['en' => '/missing-en', 'de' => '/missing-de'],
]));
$pages = $repository->getAll();
$pageRows = [];
foreach ($pages as $page) {
$pageRows[$page->getId()] = $page;
}
global $phpb_db;
$pageIds = array_keys($pageRows);
$phpb_db->query('UPDATE page_translations SET title = ? WHERE page_id = ? AND locale = ?', ['', $pageIds[1], 'de']);
$phpb_db->query('DELETE FROM page_translations WHERE page_id = ? AND locale = ?', [$pageIds[2], 'de']);
$missingPage = new Page();
$missingPage->setData(['id' => 999, 'type' => 'static']);
$pages[] = $missingPage;
$phpb_db->pageTranslationBatchSelectCount = 0;
$coverage = (new Plugi\PageTranslationService())->getPageCoverage($pages, phpb_active_languages());
assertPageCreation($coverage[$pageIds[0]]['completeCount'] === 2, 'A complete page did not report all active locales complete.');
assertPageCreation($coverage[$pageIds[1]]['completeCount'] === 1, 'A partially complete page reported the wrong coverage count.');
assertPageCreation($coverage[$pageIds[1]]['locales']['de']['exists'] === true, 'An incomplete saved locale was reported as missing.');
assertPageCreation($coverage[$pageIds[1]]['locales']['de']['complete'] === false, 'An incomplete saved locale was reported as complete.');
assertPageCreation($coverage[$pageIds[2]]['locales']['de']['exists'] === false, 'An absent locale was reported as saved.');
assertPageCreation($coverage[999]['completeCount'] === 0, 'A page without translation records reported complete locales.');
assertPageCreation($phpb_db->pageTranslationBatchSelectCount === 1, 'Translation coverage used more than one batched repository query.');
$activeLanguages = phpb_active_languages();
$pageTranslationCoverage = $coverage;
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/pages.php';
$html = ob_get_clean();
assertPageCreation(str_contains($html, '/complete-en'), 'The page overview did not render the saved English route.');
assertPageCreation(str_contains($html, '/complete-de'), 'The page overview did not render the saved German route.');
assertPageCreation(str_contains($html, 'New page'), 'The page overview did not render a saved localized title.');
assertPageCreation(str_contains($html, '2 / 2 complete'), 'The page overview did not render the translation coverage summary.');
},
'successful route updates invalidate old and new localized routes' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$result = $repository->update($page, pageCreationPayload([
'route' => ['en' => '/changed-en', 'de' => '/changed-de'],
]));
assertPageCreation($result === true, 'A valid route update failed.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/changed-de', '/changed-en', '/de/new-page', '/new-page'],
'A successful route update did not invalidate both old and new localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'page deletion removes translations and invalidates routes after commit' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/delete-en', 'de' => '/delete-de'],
]));
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
assertPageCreation($repository->destroy($pageId) === true, 'Page deletion failed.');
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Page deletion left the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Page deletion left translation rows.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/delete-de', '/delete-en'],
'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$phpb_db->failOnDeleteTable = 'pages';
assertPageCreation($repository->destroy($pageId) === false, 'A failed base-row deletion was reported as successful.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Failed deletion removed the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Failed deletion did not roll back translation cleanup.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed deletion invalidated route caches.');
},
'exception during page deletion rolls back rows and leaves caches intact' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$phpb_db->failOnDeleteTable = 'pages';
$phpb_db->throwOnDeleteFailure = true;
try {
$repository->destroy($pageId);
} catch (PDOException) {
}
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Deletion exception removed the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Deletion exception did not roll back translation cleanup.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Deletion exception invalidated route caches.');
},
'page content cache invalidation occurs only after successful writes' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$phpb_db->failOnPageUpdate = true;
assertPageCreation($repository->updatePageData($page, ['html' => []]) === false, 'A failed page-data update was reported as successful.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'A failed page-data update invalidated route caches.');
$phpb_db->failOnPageUpdate = false;
assertPageCreation($repository->updatePageData($page, ['html' => []]) === true, 'A valid page-data update failed.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/de/new-page', '/new-page'],
'A successful page-data update did not invalidate localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'translation write failures roll back the base page and translations' => function (): void {
resetPageCreationDatabase();
@@ -449,6 +873,7 @@ $cases = [
assertPageCreation(count($translations) === 2, 'Failed update changed the translation count.');
assertPageCreation($translations[0]['route'] === '/new-page', 'Failed update did not restore the English route.');
assertPageCreation($translations[1]['route'] === '/de/new-page', 'Failed update did not restore the German route.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed metadata update invalidated route caches.');
},
];
@@ -0,0 +1,111 @@
<?php
require_once __DIR__ . '/../src/PageTranslationService.php';
$pageTranslationServiceConfig = [
'general' => [
'language' => 'en',
],
];
function phpb_config(?string $key = null): mixed
{
global $pageTranslationServiceConfig;
if ($key === null) {
return $pageTranslationServiceConfig;
}
$value = $pageTranslationServiceConfig;
foreach (explode('.', $key) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return '';
}
$value = $value[$segment];
}
return $value;
}
function assertPageTranslationService(bool $condition, string $message): void
{
if (! $condition) {
throw new RuntimeException($message);
}
}
function runPageTranslationServiceCase(string $name, callable $case): bool
{
try {
$case();
fwrite(STDOUT, "PASS: {$name}\n");
return true;
} catch (Throwable $exception) {
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
return false;
}
}
$service = new Plugi\PageTranslationService();
$cases = [
'requested locale wins when available' => function () use ($service): void {
assertPageTranslationService(
$service->resolveLocale('fr', ['de', 'fr']) === 'fr',
'An available requested locale should be selected before the configured default.'
);
},
'configured locale wins when requested locale is absent' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'fr';
assertPageTranslationService(
$service->resolveLocale('it', ['de', 'fr']) === 'fr',
'The configured default should be used when the requested locale is unavailable.'
);
},
'first available locale is used when configured locale is unavailable' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'en';
assertPageTranslationService(
$service->resolveLocale('it', ['de', 'fr']) === 'de',
'The first available locale should be used without assuming an English translation exists.'
);
},
'no available locale resolves to null' => function () use ($service): void {
assertPageTranslationService($service->resolveLocale('en', []) === null, 'An empty locale list should resolve to null.');
},
'unsupported locales are rejected instead of receiving fallback' => function () use ($service): void {
assertPageTranslationService(
$service->isAvailableLocale('en', ['en' => 'English'])
&& ! $service->isAvailableLocale('it', ['en' => 'English']),
'Locale validation should accept active languages only and must not apply fallback.'
);
},
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'fr';
$translations = [
'de' => ['title' => 'Deutscher Titel', 'meta_title' => ''],
'fr' => ['title' => 'Titre français', 'meta_title' => 'Titre de métadonnées'],
];
assertPageTranslationService(
$service->resolveTranslation($translations, 'title', 'it') === 'Titre français',
'Translation metadata did not use the configured locale fallback.'
);
assertPageTranslationService(
$service->resolveTranslation($translations, 'meta_title', 'de') === '',
'An intentionally empty translation should not be replaced by fallback text.'
);
},
];
$passed = 0;
foreach ($cases as $name => $case) {
if (runPageTranslationServiceCase($name, $case)) {
$passed++;
}
}
fwrite(STDOUT, sprintf("%d/%d page translation service cases passed.\n", $passed, count($cases)));
exit($passed === count($cases) ? 0 : 1);
@@ -0,0 +1,39 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindViewportSelector } from '../src/Modules/GrapesJS/resources/assets/js/viewport-selection.js';
test('viewport changes select a device without changing project data or invoking save', () => {
const projectData = { pages: [{ id: 'page-1' }] };
const originalProjectData = structuredClone(projectData);
const selectedDevices = [];
let saveCalls = 0;
let changeHandler;
const editor = {
setDevice(device) {
selectedDevices.push(device);
},
getProjectData() {
return projectData;
},
store() {
saveCalls++;
},
};
const selector = {
value: 'Desktop',
addEventListener(eventName, handler) {
assert.equal(eventName, 'change');
changeHandler = handler;
},
};
bindViewportSelector(editor, selector);
for (const device of ['Desktop', 'Tablet', 'Mobile']) {
selector.value = device;
changeHandler();
}
assert.deepEqual(selectedDevices, ['Desktop', 'Tablet', 'Mobile']);
assert.deepEqual(editor.getProjectData(), originalProjectData);
assert.equal(saveCalls, 0);
});
+298
View File
@@ -0,0 +1,298 @@
<?php
require_once __DIR__ . '/../src/Modules/WebsiteManager/SiteQualityAnalyzer.php';
require_once __DIR__ . '/../src/Modules/WebsiteManager/SiteQualityCheckService.php';
$siteQualityConfig = [
'page' => ['translation' => ['foreign_key' => 'page_id']],
'general' => ['uploads_url' => '/uploads'],
'storage' => ['uploads_folder' => sys_get_temp_dir()],
];
$siteQualityLanguages = ['en' => 'English', 'de' => 'German'];
function phpb_config(?string $key = null)
{
global $siteQualityConfig;
if ($key === null) {
return $siteQualityConfig;
}
$value = $siteQualityConfig;
foreach (explode('.', $key) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return '';
}
$value = $value[$segment];
}
return $value;
}
function phpb_active_languages(): array
{
global $siteQualityLanguages;
return $siteQualityLanguages;
}
function phpb_trans(string $key): string
{
return $key;
}
function phpb_e($value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
function phpb_url(string $module, array $parameters = []): string
{
return '/' . $module . '?' . http_build_query($parameters);
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_csrf_token" value="test-token">';
}
function assertSiteQuality(bool $condition, string $message): void
{
if (! $condition) {
throw new RuntimeException($message);
}
}
function runSiteQualityCase(string $name, callable $case): bool
{
try {
$case();
fwrite(STDOUT, "PASS: {$name}\n");
return true;
} catch (Throwable $exception) {
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
return false;
}
}
class SiteQualityTestPage
{
public function __construct(public string $id, public string $name)
{
}
public function getId(): string
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
}
class SiteQualityTestPageRepository
{
public function __construct(private array $pages)
{
}
public function getAll(): array
{
return $this->pages;
}
}
class SiteQualityTestTranslationRepository
{
public function __construct(private array $translations)
{
}
public function getForPages(array $pageIds): array
{
return $this->translations;
}
}
class SiteQualityTestUploadRepository
{
public function __construct(private array $uploads)
{
}
public function getAll(): array
{
return $this->uploads;
}
}
function siteQualityTranslation(string $pageId, string $locale, string $route): object
{
return (object) ['page_id' => $pageId, 'locale' => $locale, 'route' => $route];
}
function siteQualityRules(array $findings): array
{
return array_column($findings, 'rule');
}
$cases = [
'compliant markup, active routes, and known assets produce no findings' => function (): void {
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
['/home', '/contact', '/de/about'],
['/uploads/file-1/logo.png'],
'https://example.test/plugi',
'/uploads'
);
$html = '<h1>Home</h1><h2>Section</h2><label for="email">Email</label><input id="email" type="email">'
. '<img alt="Logo" src="https://example.test/plugi/uploads/file-1/logo.png">'
. '<a href="https://example.test/plugi/contact?source=home#form">Contact</a>';
assertSiteQuality($analyzer->analyze($html, '/home') === [], 'Compliant markup or known links produced unexpected findings.');
},
'missing image alt, unnamed controls, and skipped heading levels are reported' => function (): void {
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(['/home'], [], 'https://example.test/plugi', '/uploads');
$findings = $analyzer->analyze('<img src="/plugi/photo.png"><input type="text"><h1>Title</h1><h3>Subheading</h3>', '/home');
assertSiteQuality(in_array('image-alt', siteQualityRules($findings), true), 'An image without an alt attribute was not reported.');
assertSiteQuality(in_array('form-control-name', siteQualityRules($findings), true), 'An unnamed form control was not reported.');
assertSiteQuality(in_array('heading-level', siteQualityRules($findings), true), 'A skipped heading level was not reported.');
},
'localized internal routes and ignored external or non-navigation links are handled offline' => function (): void {
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
['/home', '/de/ueber-uns'],
['/uploads/image-1/photo.jpg'],
'https://example.test/plugi',
'/uploads'
);
$html = '<a href="/plugi/de/ueber-uns">German route</a>'
. '<a href="https://outside.test/anything">External</a>'
. '<a href="mailto:team@example.test">Email</a><a href="tel:+123">Phone</a>'
. '<a href="#details">Fragment</a>'
. '<img alt="Photo" src="/plugi/uploads/image-1/photo.jpg">';
assertSiteQuality($analyzer->analyze($html, '/home') === [], 'A valid localized route, local asset, or ignored external link was incorrectly reported.');
},
'same-site links outside the configured application base are not treated as local uploads' => function (): void {
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
['/home'],
['/uploads/image-1/photo.jpg'],
'https://example.test/plugi',
'/uploads'
);
$findings = $analyzer->analyze('<a href="/uploads/image-1/photo.jpg">Photo</a>', '/home');
assertSiteQuality(
in_array('missing-internal-route', siteQualityRules($findings), true),
'A root-level path outside the application base was incorrectly resolved to an application upload.'
);
},
'missing same-site routes and uploads are reported with actionable targets' => function (): void {
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
['/home'],
[],
'https://example.test/plugi',
'/uploads'
);
$findings = $analyzer->analyze('<a href="/plugi/not-found">Missing page</a><img alt="Missing" src="/plugi/uploads/no-file.png">', '/home');
assertSiteQuality(in_array('missing-internal-route', siteQualityRules($findings), true), 'A missing same-site route was not reported.');
assertSiteQuality(in_array('missing-local-asset', siteQualityRules($findings), true), 'A missing local upload was not reported.');
assertSiteQuality(count(array_filter($findings, static fn(array $finding): bool => $finding['target'] !== '')) === 2, 'Findings did not identify affected targets.');
},
'only active language routes are scanned' => function (): void {
global $siteQualityLanguages;
$siteQualityLanguages = ['en' => 'English'];
$renderedLocales = [];
$service = new Plugi\Modules\WebsiteManager\SiteQualityCheckService(
new SiteQualityTestPageRepository([new SiteQualityTestPage('1', 'Localized page')]),
new SiteQualityTestTranslationRepository([
siteQualityTranslation('1', 'en', '/localized'),
siteQualityTranslation('1', 'fr', '/fr/localized'),
]),
new SiteQualityTestUploadRepository([]),
static function (SiteQualityTestPage $page, string $locale) use (&$renderedLocales): string {
$renderedLocales[] = $locale;
return '<h1>Page</h1>';
}
);
$report = $service->run();
assertSiteQuality($report['pages_checked'] === 1 && $renderedLocales === ['en'], 'An inactive translation was included in the live-site scan.');
},
'renderer failure is page-scoped and does not stop later page locales' => function (): void {
global $siteQualityLanguages;
$siteQualityLanguages = ['en' => 'English'];
$pages = [new SiteQualityTestPage('1', 'Broken render'), new SiteQualityTestPage('2', 'Available page')];
$translations = [siteQualityTranslation('1', 'en', '/broken'), siteQualityTranslation('2', 'en', '/available')];
$service = new Plugi\Modules\WebsiteManager\SiteQualityCheckService(
new SiteQualityTestPageRepository($pages),
new SiteQualityTestTranslationRepository($translations),
new SiteQualityTestUploadRepository([]),
static function (SiteQualityTestPage $page): string {
if ($page->id === '1') {
throw new RuntimeException('template failure');
}
return '<h1>Available</h1>';
}
);
$report = $service->run();
assertSiteQuality($report['pages_checked'] === 2, 'The audit did not continue after a renderer failure.');
assertSiteQuality(count($report['errors']) === 1, 'The renderer failure was not captured as one page-scoped error.');
assertSiteQuality($report['errors'][0]['page_id'] === '1' && $report['errors'][0]['locale'] === 'en', 'The coverage error omitted its page or locale.');
},
'upload inventory rejects file paths resolved outside the configured uploads directory' => function (): void {
global $siteQualityConfig, $siteQualityLanguages;
$siteQualityLanguages = ['en' => 'English'];
$siteQualityConfig['storage']['uploads_folder'] = sys_get_temp_dir();
$page = new SiteQualityTestPage('1', 'Path safety');
$outsidePath = str_repeat('../', 64) . ltrim(__FILE__, DIRECTORY_SEPARATOR);
$upload = (object) ['public_id' => 'outside', 'original_file' => 'test.php', 'server_file' => $outsidePath];
$service = new Plugi\Modules\WebsiteManager\SiteQualityCheckService(
new SiteQualityTestPageRepository([$page]),
new SiteQualityTestTranslationRepository([siteQualityTranslation('1', 'en', '/safety')]),
new SiteQualityTestUploadRepository([$upload]),
static fn(): string => '<img alt="Outside" src="/uploads/outside/test.php">'
);
$report = $service->run();
assertSiteQuality(
in_array('missing-local-asset', siteQualityRules($report['findings']), true),
'An upload path outside the configured public area was trusted as a valid asset.'
);
},
'quality tab groups findings and escapes actionable context' => function (): void {
$qualityReport = [
'pages_checked' => 1,
'findings' => [[
'page_id' => '1',
'page_name' => '<script>alert(1)</script>',
'route' => '/home',
'locale' => 'en',
'rule' => 'missing-internal-route',
'severity' => 'warning',
'explanation' => 'The linked page was not found.',
'target' => '/missing"><script>alert(2)</script>',
]],
'errors' => [],
];
ob_start();
require __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/quality.php';
$html = ob_get_clean();
assertSiteQuality(str_contains($html, 'route=quality&amp;action=scan&amp;tab=quality'), 'The quality scan form does not target its authenticated action.');
assertSiteQuality(str_contains($html, 'name="_csrf_token"'), 'The quality scan form is missing its CSRF token field.');
assertSiteQuality(str_contains($html, 'website-manager.quality-rule-missing-internal-route'), 'Findings were not grouped under their rule label.');
assertSiteQuality(str_contains($html, '&lt;script&gt;alert(1)&lt;/script&gt;'), 'The affected page name was not escaped.');
assertSiteQuality(str_contains($html, '&lt;script&gt;alert(2)&lt;/script&gt;'), 'The affected target was not escaped.');
},
];
$passed = 0;
foreach ($cases as $name => $case) {
if (runSiteQualityCase($name, $case)) {
$passed++;
}
}
fwrite(STDOUT, sprintf("%d/%d site quality check cases passed.\n", $passed, count($cases)));
exit($passed === count($cases) ? 0 : 1);
@@ -0,0 +1,39 @@
<?php
return [
'title' => 'About Me',
'category' => 'Sections',
'icon' => 'ph ph-user-circle',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'A little about me'
],
'name' => [
'label' => 'Name',
'type' => 'text',
'value' => 'Your name'
],
'role' => [
'label' => 'Role or profession',
'type' => 'text',
'value' => 'Designer and maker'
],
'biography' => [
'label' => 'Biography',
'type' => 'text',
'value' => 'I help people turn good ideas into thoughtful, useful experiences. I believe the best work comes from listening carefully, staying curious, and paying attention to the details.'
],
'image_src' => [
'label' => 'Portrait image URL',
'type' => 'text',
'value' => 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=900&q=80'
],
'image_alt' => [
'label' => 'Image alternative text',
'type' => 'text',
'value' => 'Portrait of a creative professional'
],
]
];
+15
View File
@@ -0,0 +1,15 @@
<section class="bg-slate-50 px-4 py-12 sm:py-16">
<div class="mx-auto grid max-w-6xl gap-10 md:grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] md:items-center">
<?php if (strlen($block->setting('image_src')) > 0) : ?>
<div class="overflow-hidden rounded-2xl bg-slate-200">
<img class="aspect-square h-full w-full object-cover" src="<?= $block->setting('image_src') ?>" alt="<?= $block->setting('image_alt') ?>" loading="lazy" decoding="async">
</div>
<?php endif; ?>
<div>
<h2 class="mb-6 text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<h3 class="text-xl font-semibold text-slate-900"><?= $block->setting('name') ?></h3>
<p class="mt-1 text-sm font-medium text-slate-500"><?= $block->setting('role') ?></p>
<p class="mt-5 text-base leading-7 text-slate-600"><?= $block->setting('biography') ?></p>
</div>
</div>
</section>
+2 -19
View File
@@ -2,24 +2,7 @@
return [
'title' => 'Button',
'category' => 'Layout',
'category' => 'Content',
'hidden' => true,
'icon' => 'fa fa-hand-peace-o',
'settings' => [
"order" => [
"type" => "select",
"label" => "Image Position",
"value" => "md:flex-row",
"options" => [
[
"id" => "md:flex-row",
"name" => "Right"
],
[
"id" => "md:flex-row-reverse",
"name" => "Left"
]
]
],
]
'icon' => 'ph ph-cursor-click',
];
+2 -2
View File
@@ -1,3 +1,3 @@
<a class="p-4 rounded bg-primary-300" href="#">
button
<a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900" href="/contact">
Get in touch
</a>
+1 -15
View File
@@ -4,19 +4,5 @@ return [
'title' => 'Column',
'category' => 'Layout',
'hidden' => true,
'icon' => 'fa fa-hand-peace-o',
'settings' => [
'text' => [
'label'=> 'Text',
'type' => 'text',
'placeholder' =>'auto',
'value' => 'Micheal Gough'
],
'texti' => [
'label'=> 'Text',
'type' => 'text',
'placeholder' =>'auto',
'value' => 'Micheal Gough'
],
]
'icon' => 'ph ph-columns',
];
+1 -1
View File
@@ -1,3 +1,3 @@
<div class="col p-8 border rounded" phpb-blocks-container>
<div class="min-w-0 rounded-xl border border-slate-200 bg-white p-6 sm:p-8" phpb-blocks-container>
[block slug="paragraph"]
</div>
+22 -6
View File
@@ -3,13 +3,29 @@
return [
'title' => 'CTA',
'category' => 'General',
'icon' => 'fa fa-hand-peace-o',
'icon' => 'ph ph-megaphone',
'settings' => [
'person' => [
'label'=> 'Height',
'heading' => [
'label' => 'Heading',
'type' => 'text',
'placeholder' =>'auto',
'value' => 'Micheal Gough'
]
'placeholder' => 'Add a short call to action',
'value' => 'Ready to take the next step?'
],
'message' => [
'label' => 'Supporting text',
'type' => 'text',
'placeholder' => 'Explain what visitors can do next',
'value' => 'Get in touch to talk about how we can help.'
],
'button_label' => [
'label' => 'Button label',
'type' => 'text',
'value' => 'Contact us'
],
'button_url' => [
'label' => 'Button URL',
'type' => 'text',
'value' => '/contact'
],
]
];
+7 -7
View File
@@ -1,9 +1,9 @@
<section class="bg-gray-50 dark:bg-gray-800">
<div class="max-w-screen-xl px-4 py-8 mx-auto lg:py-16 lg:px-6">
<div class="max-w-screen-sm mx-auto text-center">
<h2 class="mb-4 text-3xl font-extrabold leading-tight tracking-tight text-gray-900 dark:text-white">Start your free trial today</h2>
<p class="mb-6 font-light text-gray-500 dark:text-gray-400 md:text-lg">Try Landwind Platform for 30 days. No credit card required.</p>
<a href="#" class="text-white bg-purple-700 hover:bg-purple-800 focus:ring-4 focus:ring-purple-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-purple-600 dark:hover:bg-purple-700 focus:outline-none dark:focus:ring-purple-800">Free trial for 30 days</a>
</div>
<section class="bg-slate-100 px-4 py-12 sm:py-16">
<div class="mx-auto max-w-3xl text-center">
<h2 class="mb-4 text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<p class="mb-8 text-lg leading-7 text-slate-600"><?= $block->setting('message') ?></p>
<a href="<?= $block->setting('button_url') ?>" class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900">
<?= $block->setting('button_label') ?>
</a>
</div>
</section>
@@ -0,0 +1,7 @@
<?php
return [
'title' => 'Embedded Code',
'category' => 'Content',
'icon' => 'ph ph-code-block',
];
@@ -0,0 +1,5 @@
<section class="px-4 py-8">
<div class="mx-auto max-w-5xl rounded-xl border border-dashed border-slate-300 bg-slate-50 p-6 text-slate-500 sm:p-8" data-raw-content phpb-editable>
<p>Place approved embed content here using the existing trusted page-editor workflow.</p>
</div>
</section>
@@ -0,0 +1,20 @@
<?php
return [
'title' => 'FAQ Item',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-question',
'settings' => [
'question' => [
'label' => 'Question',
'type' => 'text',
'value' => 'How does the process begin?'
],
'answer' => [
'label' => 'Answer',
'type' => 'text',
'value' => 'We start with a conversation about your goals, audience, and the outcome you want to achieve.'
],
]
];
@@ -0,0 +1,9 @@
<details class="group rounded-xl border border-slate-200 bg-white">
<summary class="flex cursor-pointer list-none items-center justify-between gap-4 px-5 py-4 font-semibold text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-700">
<span><?= $block->setting('question') ?></span>
<span class="text-xl font-normal text-slate-500 transition group-open:rotate-45" aria-hidden="true">+</span>
</summary>
<div class="px-5 pb-5 text-slate-600">
<p class="leading-7"><?= $block->setting('answer') ?></p>
</div>
</details>
+25
View File
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'FAQ Section',
'category' => 'Sections',
'icon' => 'ph ph-question',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Frequently asked questions'
],
'intro' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'Find quick answers to common questions about our services and process.'
],
'item_count' => [
'label' => 'Number of questions (1–10)',
'type' => 'number',
'value' => '5',
'placeholder' => '5'
],
]
];
+16
View File
@@ -0,0 +1,16 @@
<?php
$itemCount = max(1, min(10, intval($block->setting('item_count'))));
?>
<section class="px-4 py-12 sm:py-16">
<div class="mx-auto max-w-4xl">
<div class="mb-8 max-w-3xl">
<h2 class="text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<p class="mt-4 text-lg leading-7 text-slate-600"><?= $block->setting('intro') ?></p>
</div>
<div class="space-y-3">
<?php for ($i = 0; $i < $itemCount; $i++): ?>
[block slug="faq-item" id="faq-item-<?= $i ?>"]
<?php endfor; ?>
</div>
</div>
</section>
@@ -0,0 +1,35 @@
<?php
return [
'title' => 'Feature Card',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-cardholder',
'settings' => [
'symbol' => [
'label' => 'Icon or symbol',
'type' => 'text',
'value' => '✦'
],
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Clear direction'
],
'description' => [
'label' => 'Description',
'type' => 'text',
'value' => 'Start with a clear plan shaped around your goals and the people you want to reach.'
],
'link_label' => [
'label' => 'Link label',
'type' => 'text',
'value' => 'Learn more'
],
'link_url' => [
'label' => 'Link URL',
'type' => 'text',
'value' => '/services'
],
]
];
@@ -0,0 +1,10 @@
<article class="h-full rounded-xl border border-slate-200 bg-white p-6 shadow-sm transition hover:shadow-md">
<span class="mb-5 inline-flex h-11 w-11 items-center justify-center rounded-lg bg-slate-100 text-xl text-slate-900" aria-hidden="true"><?= $block->setting('symbol') ?></span>
<h3 class="text-xl font-semibold text-slate-900"><?= $block->setting('heading') ?></h3>
<p class="mt-3 leading-7 text-slate-600"><?= $block->setting('description') ?></p>
<?php if (strlen($block->setting('link_url')) > 0) : ?>
<a class="mt-5 inline-flex items-center gap-2 text-sm font-semibold text-slate-900 underline decoration-slate-300 underline-offset-4 hover:decoration-slate-900" href="<?= $block->setting('link_url') ?>">
<?= $block->setting('link_label') ?>
</a>
<?php endif; ?>
</article>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Feature Cards',
'category' => 'Sections',
'icon' => 'ph ph-cards',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Thoughtful solutions for every stage'
],
'intro' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'Highlight the services, strengths, or benefits that matter most to your visitors.'
],
'card_count' => [
'label' => 'Number of cards (1–6)',
'type' => 'number',
'value' => '3',
'placeholder' => '3'
],
]
];
@@ -0,0 +1,16 @@
<?php
$cardCount = max(1, min(6, intval($block->setting('card_count'))));
?>
<section class="px-4 py-12 sm:py-16">
<div class="mx-auto max-w-7xl">
<div class="mb-10 max-w-3xl">
<h2 class="text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<p class="mt-4 text-lg leading-7 text-slate-600"><?= $block->setting('intro') ?></p>
</div>
<div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
<?php for ($i = 0; $i < $cardCount; $i++): ?>
[block slug="feature-card" id="feature-card-<?= $i ?>"]
<?php endfor; ?>
</div>
</div>
</section>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Gallery Image',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-image',
'settings' => [
'image_src' => [
'label' => 'Image source URL',
'type' => 'text',
'value' => 'https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?auto=format&fit=crop&w=1200&q=80'
],
'image_alt' => [
'label' => 'Image alternative text',
'type' => 'text',
'value' => 'Rolling hills beneath a cloudy sky'
],
'caption' => [
'label' => 'Caption',
'type' => 'text',
'value' => 'A quiet moment in the landscape'
],
]
];
@@ -0,0 +1,10 @@
<figure class="overflow-hidden rounded-xl bg-slate-100">
<?php if (strlen($block->setting('image_src')) > 0) : ?>
<a class="group block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-700" href="<?= $block->setting('image_src') ?>" target="_blank" rel="noopener noreferrer" data-gallery-trigger>
<img class="aspect-square w-full object-cover transition duration-300 group-hover:scale-105" src="<?= $block->setting('image_src') ?>" alt="<?= $block->setting('image_alt') ?>" loading="lazy" decoding="async">
</a>
<?php endif; ?>
<?php if (strlen($block->setting('caption')) > 0) : ?>
<figcaption class="px-3 py-2 text-sm text-slate-600"><?= $block->setting('caption') ?></figcaption>
<?php endif; ?>
</figure>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Gallery',
'category' => 'Sections',
'icon' => 'ph ph-images',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'A selection of our work'
],
'item_count' => [
'label' => 'Number of images (1–12)',
'type' => 'number',
'value' => '6',
'placeholder' => '6'
],
'lightbox_enabled' => [
'label' => 'Enable image lightbox',
'type' => 'yes_no',
'value' => 1
],
]
];
+24
View File
@@ -0,0 +1,24 @@
<?php
$itemCount = max(1, min(12, intval($block->setting('item_count'))));
$lightboxEnabled = (int) $block->setting('lightbox_enabled') === 1;
?>
<section class="px-4 py-12 sm:py-16" data-gallery data-gallery-lightbox="<?= $lightboxEnabled ? 'true' : 'false' ?>">
<div class="mx-auto max-w-7xl">
<h2 class="mb-8 text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
<?php for ($i = 0; $i < $itemCount; $i++): ?>
[block slug="gallery-item" id="gallery-item-<?= $i ?>"]
<?php endfor; ?>
</div>
<?php if ($lightboxEnabled) : ?>
<dialog class="m-auto max-h-[90vh] max-w-[90vw] overflow-visible border-0 bg-transparent p-0 text-white backdrop:bg-slate-950/80" data-gallery-dialog aria-label="Gallery image preview">
<form method="dialog" class="absolute right-2 top-2 z-10">
<button class="rounded-full bg-white/90 p-2 text-slate-900 shadow hover:bg-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" aria-label="Close image preview">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 6l12 12M18 6L6 18" /></svg>
</button>
</form>
<img class="max-h-[90vh] max-w-[90vw] rounded-lg object-contain" data-gallery-lightbox-image alt="">
</dialog>
<?php endif; ?>
</div>
</section>
@@ -3,7 +3,8 @@
return [
'title' => 'Hello World',
'category' => 'General',
'icon' => 'fa fa-hand-peace-o',
'hidden' => true,
'icon' => 'ph ph-hand-wave',
'settings' => [
'height' => [
'label'=> 'Height',
+44
View File
@@ -0,0 +1,44 @@
<?php
return [
'title' => 'Hero',
'category' => 'Sections',
'icon' => 'ph ph-panorama',
'settings' => [
'eyebrow' => [
'label' => 'Eyebrow',
'type' => 'text',
'value' => 'A better way to build your website'
],
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Make your next idea a reality'
],
'message' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'Introduce your business, explain what makes it different, and help visitors find their next step.'
],
'button_label' => [
'label' => 'Button label',
'type' => 'text',
'value' => 'Explore our services'
],
'button_url' => [
'label' => 'Button URL',
'type' => 'text',
'value' => '/services'
],
'image_src' => [
'label' => 'Image source URL',
'type' => 'text',
'value' => 'https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&fit=crop&w=1200&q=80'
],
'image_alt' => [
'label' => 'Image alternative text',
'type' => 'text',
'value' => 'A bright, welcoming workspace'
],
]
];
+17
View File
@@ -0,0 +1,17 @@
<section class="bg-white px-4 py-16 sm:py-20 lg:py-24">
<div class="mx-auto grid max-w-7xl gap-12 lg:grid-cols-2 lg:items-center">
<div>
<p class="mb-4 text-sm font-semibold uppercase tracking-wide text-slate-600"><?= $block->setting('eyebrow') ?></p>
<h1 class="text-4xl font-semibold tracking-tight text-slate-950 sm:text-5xl lg:text-6xl"><?= $block->setting('heading') ?></h1>
<p class="mt-6 max-w-2xl text-lg leading-8 text-slate-600"><?= $block->setting('message') ?></p>
<a href="<?= $block->setting('button_url') ?>" class="mt-8 inline-flex items-center justify-center rounded-lg bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900">
<?= $block->setting('button_label') ?>
</a>
</div>
<?php if (strlen($block->setting('image_src')) > 0) : ?>
<div class="overflow-hidden rounded-2xl bg-slate-100">
<img class="aspect-[4/3] h-full w-full object-cover" src="<?= $block->setting('image_src') ?>" alt="<?= $block->setting('image_alt') ?>" fetchpriority="high">
</div>
<?php endif; ?>
</div>
</section>
+3 -2
View File
@@ -1,7 +1,8 @@
<?php
return [
'title' => 'image',
'title' => 'Image',
'category' => 'Content',
'hidden' => true,
'icon' => 'fa fa-hand-peace-o'
'icon' => 'ph ph-image'
];
+1 -1
View File
@@ -1 +1 @@
<img src="" alt="" data-blubb="foo">
<img class="h-auto w-full rounded-xl object-cover" src="https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&amp;fit=crop&amp;w=1200&amp;q=80" alt="A bright, welcoming workspace" loading="lazy" decoding="async">
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'title' => 'List',
'category' => 'Content',
'icon' => 'ph ph-list-bullets',
];
+10
View File
@@ -0,0 +1,10 @@
<section class="px-4 py-12 sm:py-16">
<div class="mx-auto max-w-3xl">
<h2 class="mb-6 text-2xl font-semibold tracking-tight text-slate-900 sm:text-3xl" phpb-editable>What you can expect</h2>
<ul class="list-disc space-y-3 pl-6 text-base leading-7 text-slate-600 marker:text-slate-400">
<li phpb-editable>Clear communication from the first conversation to the final delivery</li>
<li phpb-editable>Practical recommendations tailored to your goals</li>
<li phpb-editable>Thoughtful, reliable support at every stage</li>
</ul>
</div>
</section>
+2 -2
View File
@@ -2,7 +2,7 @@
return [
'title' => 'Paragraph',
'category' => 'Layout',
'category' => 'Content',
'hidden' => true,
'icon' => 'fa fa-hand-peace-o',
'icon' => 'ph ph-text-align-left',
];
+3 -3
View File
@@ -1,3 +1,3 @@
<div class="" phpb-editable>
Dolore cillum et tempor. Nulla mollit quis sunt duis aliqua ad consectetur minim Lorem irure non duis. Et est elit cillum magna non. Culpa nisi aute occaecat aliqua eiusmod. Sunt tempor eu dolore duis ad mollit enim elit commodo labore aute quis dolor. Consequat consectetur elit officia non anim cillum reprehenderit nulla duis deserunt ex id. Veniam ex in reprehenderit in ut id tempor occaecat. Nisi ea velit adipisicing minim voluptate.
</div>
<p class="text-base leading-7 text-slate-600" phpb-editable>
Add a paragraph that explains your service, shares useful information, or gives visitors the context they need.
</p>
+15 -6
View File
@@ -3,13 +3,22 @@
return [
'title' => 'Quote',
'category' => 'General',
'icon' => 'fa fa-hand-peace-o',
'icon' => 'ph ph-quotes',
'settings' => [
'person' => [
'label'=> 'Height',
'quote' => [
'label' => 'Quote',
'type' => 'text',
'placeholder' =>'auto',
'value' => 'Micheal Gough'
]
'value' => 'Clear communication and thoughtful planning make every project better.'
],
'person' => [
'label' => 'Name',
'type' => 'text',
'value' => 'Jordan Lee'
],
'role' => [
'label' => 'Role or attribution',
'type' => 'text',
'value' => 'Customer'
],
]
];
+13 -18
View File
@@ -1,19 +1,14 @@
<section class="bg-gray-50 dark:bg-gray-800">
<div class="max-w-screen-xl px-4 py-8 mx-auto text-center lg:py-24 lg:px-6">
<figure class="max-w-screen-md mx-auto">
<svg class="h-12 mx-auto mb-3 text-gray-400 dark:text-gray-600" viewBox="0 0 24 27" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.017 18L14.017 10.609C14.017 4.905 17.748 1.039 23 0L23.995 2.151C21.563 3.068 20 5.789 20 8H24V18H14.017ZM0 18V10.609C0 4.905 3.748 1.038 9 0L9.996 2.151C7.563 3.068 6 5.789 6 8H9.983L9.983 18L0 18Z" fill="currentColor"></path>
</svg>
<blockquote>
<p class="text-xl font-medium text-gray-900 md:text-2xl dark:text-white">"Landwind is just awesome. It contains tons of predesigned components and pages starting from login screen to complex dashboard. Perfect choice for your next SaaS application."</p>
</blockquote>
<figcaption class="flex items-center justify-center mt-6 space-x-3">
<img class="w-6 h-6 rounded-full" src="https://flowbite.s3.amazonaws.com/blocks/marketing-ui/avatars/michael-gouch.png" alt="profile picture">
<div class="flex items-center divide-x-2 divide-gray-500 dark:divide-gray-700">
<div class="pr-3 font-medium text-gray-900 dark:text-white"><?php echo $block->setting('person'); ?></div>
<div class="pl-3 text-sm font-light text-gray-500 dark:text-gray-400">CEO at Google</div>
</div>
</figcaption>
</figure>
</div>
<section class="bg-slate-50 px-4 py-12 sm:py-16">
<figure class="mx-auto max-w-3xl text-center">
<svg class="mx-auto mb-5 h-10 w-10 text-slate-300" viewBox="0 0 24 27" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path d="M14.017 18L14.017 10.609C14.017 4.905 17.748 1.039 23 0L23.995 2.151C21.563 3.068 20 5.789 20 8H24V18H14.017ZM0 18V10.609C0 4.905 3.748 1.038 9 0L9.996 2.151C7.563 3.068 6 5.789 6 8H9.983L9.983 18L0 18Z" />
</svg>
<blockquote>
<p class="text-xl font-medium leading-8 text-slate-900 sm:text-2xl">“<?= $block->setting('quote') ?>”</p>
</blockquote>
<figcaption class="mt-6 text-sm text-slate-600">
<span class="font-semibold text-slate-900"><?= $block->setting('person') ?></span>
<span> · <?= $block->setting('role') ?></span>
</figcaption>
</figure>
</section>
+4 -3
View File
@@ -3,12 +3,13 @@
return [
'title' => 'Row',
'category' => 'Layout',
'icon' => 'fa fa-hand-peace-o',
'icon' => 'ph ph-columns',
'settings' => [
"column_count" => [
"type" => "number",
"label" => "Number of columns",
"value" => "3"
"label" => "Number of columns (1–4)",
"value" => "3",
"placeholder" => "3"
],
]
];

Some files were not shown because too many files have changed in this diff Show More