@forgewp/compiler 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -0
- package/bin/add.js +20 -14
- package/bin/cli.js +145 -70
- package/bin/doctor.js +21 -12
- package/bin/export.js +69 -20
- package/bin/fresh.js +5 -0
- package/bin/i18n-extract.js +3 -10
- package/bin/i18n-translate.js +15 -24
- package/bin/make-block.js +13 -0
- package/bin/make-editable.js +166 -0
- package/bin/make-form.js +131 -0
- package/bin/make-loop.js +40 -43
- package/bin/make-mail.js +27 -0
- package/bin/make-post-type.js +57 -29
- package/bin/make-sandbox.js +62 -11
- package/bin/make-section.js +221 -0
- package/bin/make-shell.js +375 -0
- package/bin/repair.js +14 -26
- package/bin/seed.js +119 -0
- package/bin/sync-routes.js +107 -85
- package/lib/adapters/html-adapter.js +5 -0
- package/lib/adapters/stub-adapter.js +4 -0
- package/lib/add-component.js +153 -92
- package/lib/asset-loader.js +313 -3
- package/lib/assets/asset-graph.js +432 -0
- package/lib/assets/asset-pipeline.js +125 -0
- package/lib/assets/diagnostics-report.js +345 -0
- package/lib/assets/external-fetcher.js +173 -0
- package/lib/assets/font-orchestrator.js +348 -0
- package/lib/assets/font-usage-scanner.js +242 -0
- package/lib/assets/image-optimizer.js +229 -0
- package/lib/assets/index.js +51 -0
- package/lib/assets/preload-generator.js +70 -0
- package/lib/assets/public-url.js +153 -0
- package/lib/block-authoring-help.js +11 -0
- package/lib/blocks/ast-parser.js +67 -0
- package/lib/blocks/discover-blocks.js +146 -0
- package/lib/blocks/editor-scope.js +733 -0
- package/lib/blocks/editor-transpiler.js +1229 -0
- package/lib/blocks/index.js +2838 -0
- package/lib/blocks/php-transpiler.js +4928 -0
- package/lib/blocks/scanner.js +1487 -0
- package/lib/blocks/shared-utils.js +290 -0
- package/lib/blocks/source-sanitize.js +1449 -0
- package/lib/blueprints.js +31 -91
- package/lib/build-assets.js +38 -33
- package/lib/collect-page-template-routes.js +102 -0
- package/lib/collect-static-routes.js +175 -0
- package/lib/diagnostics.js +58 -33
- package/lib/export-theme.js +84 -5
- package/lib/extract-template-content.js +90 -0
- package/lib/forms-preview.js +42 -0
- package/lib/functions/cpt-routing.js +69 -0
- package/lib/functions/forms.js +2461 -0
- package/lib/functions/hydration-enqueuer.js +400 -0
- package/lib/functions/index.js +1623 -0
- package/lib/functions/load-menus.js +112 -0
- package/lib/functions/load-translations.js +148 -0
- package/lib/functions/rest-endpoints.js +2923 -0
- package/lib/functions/routing.js +765 -0
- package/lib/functions/seed-mock-data.js +392 -0
- package/lib/functions/seed-products.js +481 -0
- package/lib/functions/settings-page.js +273 -0
- package/lib/functions/theme-setup.js +494 -0
- package/lib/generate-theme.js +1916 -339
- package/lib/hydration/editable-schemas.js +332 -0
- package/lib/hydration/enter-hidden-initial.js +65 -0
- package/lib/hydration/form-schemas.js +227 -0
- package/lib/hydration/index.js +12 -0
- package/lib/hydration/is-interactive.js +951 -0
- package/lib/hydration/island-split.js +1231 -0
- package/lib/hydration/islands-scanner.js +599 -0
- package/lib/hydration/resolve-island-chunk.js +103 -0
- package/lib/hydration/resolve-island-component.js +52 -0
- package/lib/hydration/rollup-inputs.js +81 -0
- package/lib/hydration/root-class-extractor.js +220 -0
- package/lib/hydration/scan-app-providers.js +154 -0
- package/lib/hydration/static-lint.js +382 -0
- package/lib/hydration/transform.js +257 -0
- package/lib/hydration/uses-block-area.js +49 -0
- package/lib/hydration/utils.js +119 -0
- package/lib/i18n/translation-cache.js +141 -0
- package/lib/icon-registry.js +72 -0
- package/lib/index.d.ts +287 -8
- package/lib/index.js +2 -1
- package/lib/load-config.js +338 -242
- package/lib/mail-templates.js +37 -0
- package/lib/markup-processor.js +388 -102
- package/lib/node-runtime.js +7 -0
- package/lib/page-config-plugin.js +64 -20
- package/lib/php-builders.js +383 -44
- package/lib/react-adapter.js +983 -235
- package/lib/registration-metadata.js +11 -0
- package/lib/render-theme.mts +1410 -616
- package/lib/route-layout.js +76 -0
- package/lib/template-discovery.js +58 -0
- package/lib/theme-compatibility.js +32 -0
- package/lib/validate-export.js +2 -2
- package/lib/validate.js +27 -5
- package/lib/virtual-plugin.js +319 -0
- package/lib/walkthrough.md +26 -0
- package/package.json +16 -5
- package/templates/auth/cms/email-logs.json +9 -0
- package/templates/auth/cms/menus.json +11 -0
- package/templates/auth/cms/mock-data.json +123 -0
- package/templates/auth/cms/roles.json +7 -0
- package/templates/auth/cms/sessions.json +1 -0
- package/templates/auth/cms/site-settings.json +28 -0
- package/templates/auth/cms/translations.json +4 -0
- package/templates/auth/cms/users.json +46 -0
- package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/login-form-wrapper.tsx +118 -21
- package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/signup-form-wrapper.tsx +2 -2
- package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
- package/templates/auth/pages/DashboardPage.tsx +1 -4
- package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
- package/templates/auth/pages/LoginPage.tsx +1 -4
- package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
- package/templates/auth/pages/SignUpPage.tsx +1 -4
- package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
- package/templates/auth/ui/button.tsx +57 -0
- package/templates/auth/ui/card.tsx +76 -0
- package/templates/auth/ui/field.tsx +242 -0
- package/templates/auth/ui/input.tsx +22 -0
- package/templates/auth/ui/label.tsx +24 -0
- package/templates/auth/ui/separator.tsx +31 -0
- package/templates/menus.json +12 -10
- package/templates/users.json +8 -4
- package/templates/wordpress.tsx +690 -245
- package/lib/block-compiler.js +0 -552
- package/lib/functions-builder.js +0 -2970
- package/lib/hydration-scanner.js +0 -833
|
@@ -0,0 +1,2461 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ForgeWP Native Forms — generates the REST submission endpoint, the
|
|
3
|
+
* forgewp_submission CPT, the wp-admin "Forms" field editor, and the
|
|
4
|
+
* hydration payload helper for every form declared in wp.config.ts's
|
|
5
|
+
* `forms` key.
|
|
6
|
+
*
|
|
7
|
+
* See forgewp_forms_spec.md §4 for the full design. Emits nothing when
|
|
8
|
+
* config.forms is absent/empty, so themes without forms get byte-identical
|
|
9
|
+
* functions.php output.
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
const VALID_FIELD_TYPES = [
|
|
15
|
+
'text',
|
|
16
|
+
'email',
|
|
17
|
+
'tel',
|
|
18
|
+
'number',
|
|
19
|
+
'textarea',
|
|
20
|
+
'select',
|
|
21
|
+
'checkbox',
|
|
22
|
+
];
|
|
23
|
+
const FORM_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Config-shape diagnostics (Principle 10 — fail at compile time, not at
|
|
27
|
+
* runtime in a visitor's browser). Throws with an actionable message so a
|
|
28
|
+
* bad `forms` config never silently produces broken PHP.
|
|
29
|
+
*/
|
|
30
|
+
export function isShortcodeModeForm(formConfig) {
|
|
31
|
+
return formConfig.mode === 'shortcode';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function validateFormsConfig(forms) {
|
|
35
|
+
if (!forms) return;
|
|
36
|
+
|
|
37
|
+
for (const [name, formConfig] of Object.entries(forms)) {
|
|
38
|
+
if (!FORM_NAME_PATTERN.test(name)) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`[ForgeWP Forms] Invalid form name "${name}" in wp.config.ts's \`forms\` key. ` +
|
|
41
|
+
`Form names become REST route segments and option-name suffixes — they must match /^[a-z][a-z0-9-]*$/ (e.g. "contact", "hotel-inquiry").`,
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (const settingName of [
|
|
46
|
+
'subject',
|
|
47
|
+
'submissionTitle',
|
|
48
|
+
'notificationBody',
|
|
49
|
+
'successMessage',
|
|
50
|
+
]) {
|
|
51
|
+
if (
|
|
52
|
+
formConfig[settingName] !== undefined &&
|
|
53
|
+
typeof formConfig[settingName] !== 'string'
|
|
54
|
+
) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`[ForgeWP Forms] forms.${name}.${settingName} must be a string when configured.`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (isShortcodeModeForm(formConfig)) {
|
|
62
|
+
if (!formConfig.shortcode || typeof formConfig.shortcode !== 'string') {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`[ForgeWP Forms] forms.${name} has mode: 'shortcode' but no \`shortcode\` string. ` +
|
|
65
|
+
`Provide the plugin's default shortcode, e.g. shortcode: '[contact-form-7 id="58" title="Contact Form"]'.`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!formConfig.mailTo) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`[ForgeWP Forms] forms.${name} is missing \`mailTo\` (required in 'native' mode — the default). ` +
|
|
74
|
+
`Set mailTo: 'admin', an 'option:key', or a literal email — or set mode: 'shortcode' if this form is managed by a WordPress plugin instead.`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (!formConfig.fields || Object.keys(formConfig.fields).length === 0) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`[ForgeWP Forms] forms.${name} is missing \`fields\` (required in 'native' mode — the default). ` +
|
|
80
|
+
`Declare at least one dev-owned field, or set mode: 'shortcode' if this form is managed by a WordPress plugin instead.`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (formConfig.submissionTitle) {
|
|
85
|
+
for (const [, mergeField] of formConfig.submissionTitle.matchAll(
|
|
86
|
+
/\{([a-zA-Z0-9_-]+)\}/g,
|
|
87
|
+
)) {
|
|
88
|
+
if (
|
|
89
|
+
!Object.prototype.hasOwnProperty.call(formConfig.fields, mergeField)
|
|
90
|
+
) {
|
|
91
|
+
throw new Error(
|
|
92
|
+
`[ForgeWP Forms] forms.${name}.submissionTitle references undeclared developer-owned field "${mergeField}".`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (formConfig.confirmation?.enabled) {
|
|
99
|
+
const confirmation = formConfig.confirmation;
|
|
100
|
+
const recipientField = formConfig.fields[confirmation.emailField];
|
|
101
|
+
if (!recipientField || recipientField.type !== 'email') {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`[ForgeWP Forms] forms.${name}.confirmation.emailField must name a developer-owned field declared with type: 'email'.`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
if (
|
|
107
|
+
typeof confirmation.subject !== 'string' ||
|
|
108
|
+
typeof confirmation.body !== 'string'
|
|
109
|
+
) {
|
|
110
|
+
throw new Error(
|
|
111
|
+
`[ForgeWP Forms] forms.${name}.confirmation requires plain-text subject and body strings when enabled.`,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
const templateText = `${confirmation.subject}\n${confirmation.body}`;
|
|
115
|
+
for (const [, mergeField] of templateText.matchAll(
|
|
116
|
+
/\{([a-zA-Z0-9_-]+)\}/g,
|
|
117
|
+
)) {
|
|
118
|
+
if (
|
|
119
|
+
!Object.prototype.hasOwnProperty.call(formConfig.fields, mergeField)
|
|
120
|
+
) {
|
|
121
|
+
throw new Error(
|
|
122
|
+
`[ForgeWP Forms] forms.${name}.confirmation references undeclared developer-owned field "${mergeField}".`,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (formConfig.retentionDays !== undefined) {
|
|
129
|
+
if (
|
|
130
|
+
!Number.isSafeInteger(formConfig.retentionDays) ||
|
|
131
|
+
formConfig.retentionDays < 1
|
|
132
|
+
) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`[ForgeWP Forms] forms.${name}.retentionDays must be a positive integer when configured.`,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (formConfig.storeSubmissions === false) {
|
|
138
|
+
throw new Error(
|
|
139
|
+
`[ForgeWP Forms] forms.${name}.retentionDays requires storeSubmissions to be enabled.`,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const devFieldNames = new Set(Object.keys(formConfig.fields || {}));
|
|
145
|
+
const rawSeed = formConfig.clientFields?.enabled
|
|
146
|
+
? formConfig.clientFields.seed || []
|
|
147
|
+
: [];
|
|
148
|
+
const seedFields = Array.isArray(rawSeed)
|
|
149
|
+
? rawSeed
|
|
150
|
+
: Object.values(rawSeed).flat();
|
|
151
|
+
const notificationKeys = new Set([...devFieldNames, ...seedFields.map((field) => field.name)]);
|
|
152
|
+
for (const setting of ['subject', 'notificationBody']) {
|
|
153
|
+
for (const [, field] of (formConfig[setting] || '').matchAll(/\{([a-zA-Z0-9_-]+)\}/g)) {
|
|
154
|
+
if (!notificationKeys.has(field)) {
|
|
155
|
+
throw new Error(`[ForgeWP Forms] forms.${name}.${setting} references undeclared field "${field}". Use an exact developer-owned or client seed field key.`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const field of seedFields) {
|
|
160
|
+
if (devFieldNames.has(field.name)) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`[ForgeWP Forms] forms.${name}.clientFields.seed has a field named "${field.name}", which collides with a dev-owned field of the same name in forms.${name}.fields. ` +
|
|
163
|
+
`Field ownership must be exclusive — rename one of them.`,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Best-effort source scan for two common misuses that a config-only check
|
|
172
|
+
* can't catch: calling submitWpForm() with a name that isn't declared, and
|
|
173
|
+
* using <WpFormFields> on a form that doesn't have clientFields enabled.
|
|
174
|
+
* Warns only — never throws, since this is a plain regex scan and false
|
|
175
|
+
* positives are possible (e.g. a dynamically-built form name).
|
|
176
|
+
*/
|
|
177
|
+
export function lintFormsUsage(themeRoot, config) {
|
|
178
|
+
const forms = config.forms || {};
|
|
179
|
+
const declaredNames = Object.keys(forms);
|
|
180
|
+
const shortcodeModeNames = new Set(
|
|
181
|
+
declaredNames.filter((n) => isShortcodeModeForm(forms[n])),
|
|
182
|
+
);
|
|
183
|
+
const clientEnabledNames = new Set(
|
|
184
|
+
declaredNames.filter(
|
|
185
|
+
(n) => !shortcodeModeNames.has(n) && forms[n].clientFields?.enabled,
|
|
186
|
+
),
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
const srcDir = path.join(themeRoot, 'src');
|
|
190
|
+
if (!existsSync(srcDir)) return [];
|
|
191
|
+
|
|
192
|
+
const warnings = [];
|
|
193
|
+
const skipDirs = new Set([
|
|
194
|
+
'node_modules',
|
|
195
|
+
'.forgewp',
|
|
196
|
+
'.forgewp-islands',
|
|
197
|
+
'dist',
|
|
198
|
+
]);
|
|
199
|
+
const shortcodeUsageFound = new Set();
|
|
200
|
+
|
|
201
|
+
function walk(dir) {
|
|
202
|
+
let entries;
|
|
203
|
+
try {
|
|
204
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
205
|
+
} catch {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
for (const entry of entries) {
|
|
209
|
+
if (entry.isDirectory()) {
|
|
210
|
+
if (!skipDirs.has(entry.name)) walk(path.join(dir, entry.name));
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (!/\.(tsx|ts)$/.test(entry.name)) continue;
|
|
214
|
+
|
|
215
|
+
const filePath = path.join(dir, entry.name);
|
|
216
|
+
const relPath = path.relative(themeRoot, filePath);
|
|
217
|
+
let content;
|
|
218
|
+
try {
|
|
219
|
+
content = readFileSync(filePath, 'utf8');
|
|
220
|
+
} catch {
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
for (const match of content.matchAll(
|
|
225
|
+
/submitWpForm\(\s*['"]([a-zA-Z0-9_-]+)['"]/g,
|
|
226
|
+
)) {
|
|
227
|
+
const name = match[1];
|
|
228
|
+
if (!declaredNames.includes(name)) {
|
|
229
|
+
warnings.push(
|
|
230
|
+
`[ForgeWP Forms] ${relPath}: submitWpForm('${name}', …) — "${name}" is not declared in wp.config.ts's \`forms\` key. ` +
|
|
231
|
+
`Declared forms: ${declaredNames.length ? declaredNames.join(', ') : '(none)'}.`,
|
|
232
|
+
);
|
|
233
|
+
} else if (shortcodeModeNames.has(name)) {
|
|
234
|
+
warnings.push(
|
|
235
|
+
`[ForgeWP Forms] ${relPath}: submitWpForm('${name}', …) — "${name}" has mode: 'shortcode', so no REST endpoint was generated for it. Use <WpShortcode> instead, or switch its mode to 'native'.`,
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
for (const match of content.matchAll(
|
|
241
|
+
/<WpFormFields\s+[^>]*\bform=["']([a-zA-Z0-9_-]+)["']/g,
|
|
242
|
+
)) {
|
|
243
|
+
const name = match[1];
|
|
244
|
+
if (declaredNames.includes(name) && shortcodeModeNames.has(name)) {
|
|
245
|
+
warnings.push(
|
|
246
|
+
`[ForgeWP Forms] ${relPath}: <WpFormFields form="${name}"> — "${name}" has mode: 'shortcode', which has no client-field concept (the plugin manages its own fields). Remove this usage.`,
|
|
247
|
+
);
|
|
248
|
+
} else if (
|
|
249
|
+
declaredNames.includes(name) &&
|
|
250
|
+
!clientEnabledNames.has(name)
|
|
251
|
+
) {
|
|
252
|
+
warnings.push(
|
|
253
|
+
`[ForgeWP Forms] ${relPath}: <WpFormFields form="${name}"> — "${name}" does not have clientFields.enabled in wp.config.ts, so it will never render any fields.`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Dev-owned field name cross-check — catches a hand-typed <input
|
|
259
|
+
// name="..."> that doesn't match any declared forms.X.fields key
|
|
260
|
+
// (typo, or a field added in the component but never declared), and
|
|
261
|
+
// the inverse (a required field declared but never rendered). Scoped
|
|
262
|
+
// to the common, unambiguous case only — exactly one submitWpForm()
|
|
263
|
+
// call and exactly one <form> block in the file — rather than trying
|
|
264
|
+
// to associate inputs with forms in a file that has several of each.
|
|
265
|
+
// Client-owned fields (rendered via name={field.name}, an expression,
|
|
266
|
+
// never a string literal) never match this regex, so they're never
|
|
267
|
+
// flagged either way.
|
|
268
|
+
const submitCalls = [
|
|
269
|
+
...content.matchAll(/submitWpForm\(\s*['"]([a-zA-Z0-9_-]+)['"]/g),
|
|
270
|
+
];
|
|
271
|
+
const formBlocks = [...content.matchAll(/<form\b[^>]*>/g)];
|
|
272
|
+
if (submitCalls.length === 1 && formBlocks.length === 1) {
|
|
273
|
+
const formName = submitCalls[0][1];
|
|
274
|
+
const formConfig = forms[formName];
|
|
275
|
+
if (
|
|
276
|
+
formConfig &&
|
|
277
|
+
!isShortcodeModeForm(formConfig) &&
|
|
278
|
+
formConfig.fields
|
|
279
|
+
) {
|
|
280
|
+
const formStart = formBlocks[0].index;
|
|
281
|
+
const formEndIdx = content.indexOf('</form>', formStart);
|
|
282
|
+
const formBlockContent =
|
|
283
|
+
formEndIdx === -1
|
|
284
|
+
? content.slice(formStart)
|
|
285
|
+
: content.slice(formStart, formEndIdx);
|
|
286
|
+
|
|
287
|
+
const declaredFields = formConfig.fields;
|
|
288
|
+
const declaredFieldNames = new Set(Object.keys(declaredFields));
|
|
289
|
+
const foundNames = new Set();
|
|
290
|
+
for (const m of formBlockContent.matchAll(
|
|
291
|
+
/\sname=["']([a-zA-Z0-9_-]+)["']/g,
|
|
292
|
+
)) {
|
|
293
|
+
foundNames.add(m[1]);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
for (const foundName of foundNames) {
|
|
297
|
+
if (!declaredFieldNames.has(foundName)) {
|
|
298
|
+
warnings.push(
|
|
299
|
+
`[ForgeWP Forms] ${relPath}: name="${foundName}" inside the "${formName}" form doesn't match any dev-owned field declared in forms.${formName}.fields (${[...declaredFieldNames].join(', ') || '(none)'}). ` +
|
|
300
|
+
`If this is a typo, the field is silently treated as empty on submit — a required field would fail validation even though the user filled it in. If it's intentional, add it to forms.${formName}.fields.`,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
for (const declaredName of declaredFieldNames) {
|
|
306
|
+
if (
|
|
307
|
+
declaredFields[declaredName].required &&
|
|
308
|
+
!foundNames.has(declaredName)
|
|
309
|
+
) {
|
|
310
|
+
warnings.push(
|
|
311
|
+
`[ForgeWP Forms] ${relPath}: forms.${formName}.fields.${declaredName} is required, but no name="${declaredName}" was found in this form. If it's rendered dynamically (not a literal name="..." attribute), ignore this warning — otherwise every submission will fail validation.`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (shortcodeModeNames.size > 0 && /<WpShortcode\b/.test(content)) {
|
|
319
|
+
for (const name of shortcodeModeNames) shortcodeUsageFound.add(name);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
walk(srcDir);
|
|
325
|
+
|
|
326
|
+
for (const name of shortcodeModeNames) {
|
|
327
|
+
if (!shortcodeUsageFound.has(name)) {
|
|
328
|
+
warnings.push(
|
|
329
|
+
`[ForgeWP Forms] forms.${name} has mode: 'shortcode', but no <WpShortcode> usage was found anywhere in src/. This form is declared but not rendered anywhere.`,
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
for (const w of warnings) {
|
|
335
|
+
console.warn(w);
|
|
336
|
+
}
|
|
337
|
+
return warnings;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function phpString(str) {
|
|
341
|
+
return `'${String(str == null ? '' : str)
|
|
342
|
+
.replace(/\\/g, '\\\\')
|
|
343
|
+
.replace(/'/g, "\\'")}'`;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function safeFormSlug(name) {
|
|
347
|
+
return name.replace(/[^a-z0-9_]/gi, '_');
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* @param {object} [opts]
|
|
352
|
+
* @param {string} [opts.textDomain] - when set, the label is wrapped in
|
|
353
|
+
* __() for translation. Only appropriate for DEV-owned fields, whose
|
|
354
|
+
* label text is a compile-time-known string like any other themed
|
|
355
|
+
* string (matches the __() precedent used for CPT/taxonomy labels
|
|
356
|
+
* elsewhere in this codebase). Client-owned field labels are runtime
|
|
357
|
+
* content typed into wp-admin — wrapping those in __() would be wrong
|
|
358
|
+
* (gettext only ever translates literal source strings) and they get
|
|
359
|
+
* proper per-locale storage instead (see buildFormsPhp's isMultilingual path).
|
|
360
|
+
*/
|
|
361
|
+
function fieldDefToPhpArray(name, field, opts = {}) {
|
|
362
|
+
const type = VALID_FIELD_TYPES.includes(field.type) ? field.type : 'text';
|
|
363
|
+
const label =
|
|
364
|
+
field.label ||
|
|
365
|
+
name.replace(/[_-]/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
|
366
|
+
const labelPhp = opts.textDomain
|
|
367
|
+
? `__(${phpString(label)}, ${phpString(opts.textDomain)})`
|
|
368
|
+
: phpString(label);
|
|
369
|
+
const required = field.required ? 'true' : 'false';
|
|
370
|
+
const maxLength = field.maxLength
|
|
371
|
+
? parseInt(field.maxLength, 10)
|
|
372
|
+
: type === 'textarea'
|
|
373
|
+
? 5000
|
|
374
|
+
: 200;
|
|
375
|
+
const optionsPhp = Array.isArray(field.options)
|
|
376
|
+
? `array(${field.options.map((o) => phpString(o)).join(', ')})`
|
|
377
|
+
: 'array()';
|
|
378
|
+
const placeholderPhp =
|
|
379
|
+
opts.textDomain && field.placeholder
|
|
380
|
+
? `__(${phpString(field.placeholder)}, ${phpString(opts.textDomain)})`
|
|
381
|
+
: phpString(field.placeholder || '');
|
|
382
|
+
return `array(
|
|
383
|
+
'name' => ${phpString(name)},
|
|
384
|
+
'label' => ${labelPhp},
|
|
385
|
+
'type' => ${phpString(type)},
|
|
386
|
+
'required' => ${required},
|
|
387
|
+
'maxLength' => ${Number.isFinite(maxLength) ? maxLength : 200},
|
|
388
|
+
'options' => ${optionsPhp},
|
|
389
|
+
'placeholder' => ${placeholderPhp},
|
|
390
|
+
)`;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function devFieldsPhpArray(fields, textDomain) {
|
|
394
|
+
const entries = Object.entries(fields || {});
|
|
395
|
+
if (entries.length === 0) return 'array()';
|
|
396
|
+
return `array(\n${entries.map(([name, field]) => ` ${fieldDefToPhpArray(name, field, { textDomain })},`).join('\n')}\n )`;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function seedFieldsPhpArray(seed) {
|
|
400
|
+
if (!Array.isArray(seed) || seed.length === 0) return 'array()';
|
|
401
|
+
return `array(\n${seed.map((field) => ` ${fieldDefToPhpArray(field.name, field)},`).join('\n')}\n )`;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Normalizes a clientFields.seed value (flat array OR per-locale map) into
|
|
406
|
+
* a PHP array literal keyed by locale, e.g. array('en' => array(...), 'de' => array(...)).
|
|
407
|
+
* A flat array is used as-is for every configured locale.
|
|
408
|
+
*/
|
|
409
|
+
function seedByLocalePhpArray(seed, locales) {
|
|
410
|
+
const perLocale = Array.isArray(seed)
|
|
411
|
+
? Object.fromEntries(locales.map((l) => [l, seed]))
|
|
412
|
+
: seed || {};
|
|
413
|
+
const entries = locales.map(
|
|
414
|
+
(l) =>
|
|
415
|
+
` ${phpString(l)} => ${seedFieldsPhpArray(perLocale[l] || [])},`,
|
|
416
|
+
);
|
|
417
|
+
return `array(\n${entries.join('\n')}\n )`;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Shared runtime helpers, emitted once regardless of how many forms exist.
|
|
422
|
+
*/
|
|
423
|
+
function buildSharedHelpersPhp(defaultLocale) {
|
|
424
|
+
const fallbackLangPhp = phpString(defaultLocale || '');
|
|
425
|
+
return `
|
|
426
|
+
if (!function_exists('forgewp_forms_rate_limit_ok')) {
|
|
427
|
+
/**
|
|
428
|
+
* Max 5 submissions per 10 minutes per IP, across all forms. Uses
|
|
429
|
+
* REMOTE_ADDR only — X-Forwarded-For is attacker-controlled and would
|
|
430
|
+
* let a bot trivially reset its own limit.
|
|
431
|
+
*/
|
|
432
|
+
function forgewp_forms_rate_limit_ok() {
|
|
433
|
+
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
|
|
434
|
+
$key = 'forgewp_form_rl_' . md5($ip);
|
|
435
|
+
$count = (int) get_transient($key);
|
|
436
|
+
if ($count >= 5) {
|
|
437
|
+
return false;
|
|
438
|
+
}
|
|
439
|
+
set_transient($key, $count + 1, 10 * MINUTE_IN_SECONDS);
|
|
440
|
+
return true;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (!function_exists('forgewp_forms_strip_header_injection')) {
|
|
445
|
+
function forgewp_forms_strip_header_injection($value) {
|
|
446
|
+
if (!is_string($value)) {
|
|
447
|
+
return $value;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (!function_exists('forgewp_forms_interpolate_template')) {
|
|
451
|
+
function forgewp_forms_interpolate_template($template, $values) {
|
|
452
|
+
if (!is_string($template)) {
|
|
453
|
+
return '';
|
|
454
|
+
}
|
|
455
|
+
return preg_replace_callback('/\\{([a-zA-Z0-9_-]+)\\}/', function ($match) use ($values) {
|
|
456
|
+
if (!array_key_exists($match[1], $values) || !is_scalar($values[$match[1]])) {
|
|
457
|
+
return '';
|
|
458
|
+
}
|
|
459
|
+
return (string) $values[$match[1]];
|
|
460
|
+
}, $template);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return str_replace(array("\\r", "\\n"), '', $value);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
if (!function_exists('forgewp_forms_sanitize_field')) {
|
|
468
|
+
function forgewp_forms_sanitize_field($value, $field_def) {
|
|
469
|
+
$type = isset($field_def['type']) ? $field_def['type'] : 'text';
|
|
470
|
+
$max_length = isset($field_def['maxLength']) ? (int) $field_def['maxLength'] : 200;
|
|
471
|
+
|
|
472
|
+
if ($type === 'checkbox') {
|
|
473
|
+
return (!empty($value) && $value !== '0' && $value !== 'false') ? '1' : '';
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
$value = is_scalar($value) ? (string) $value : '';
|
|
477
|
+
$value = forgewp_forms_strip_header_injection($value);
|
|
478
|
+
|
|
479
|
+
if ($type === 'email') {
|
|
480
|
+
$value = sanitize_email($value);
|
|
481
|
+
} elseif ($type === 'textarea') {
|
|
482
|
+
$value = sanitize_textarea_field($value);
|
|
483
|
+
} else {
|
|
484
|
+
$value = sanitize_text_field($value);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
if ($max_length > 0 && function_exists('mb_substr')) {
|
|
488
|
+
$value = mb_substr($value, 0, $max_length);
|
|
489
|
+
} elseif ($max_length > 0) {
|
|
490
|
+
$value = substr($value, 0, $max_length);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return $value;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if (!function_exists('forgewp_forms_validate_and_sanitize')) {
|
|
498
|
+
/**
|
|
499
|
+
* Validates $submitted against $field_defs (the merged dev-owned +
|
|
500
|
+
* client-owned allowlist). Only keys present in $field_defs are ever
|
|
501
|
+
* read from $submitted — everything else is silently ignored, which is
|
|
502
|
+
* the field-ownership boundary that makes client-added/dropped fields
|
|
503
|
+
* safe without any theme code changes.
|
|
504
|
+
*
|
|
505
|
+
* @return array{values: array, errors: array}
|
|
506
|
+
*/
|
|
507
|
+
function forgewp_forms_validate_and_sanitize($submitted, $field_defs) {
|
|
508
|
+
$values = array();
|
|
509
|
+
$errors = array();
|
|
510
|
+
|
|
511
|
+
foreach ($field_defs as $field_def) {
|
|
512
|
+
$name = $field_def['name'];
|
|
513
|
+
$type = isset($field_def['type']) ? $field_def['type'] : 'text';
|
|
514
|
+
$required = !empty($field_def['required']);
|
|
515
|
+
$raw = isset($submitted[$name]) ? $submitted[$name] : '';
|
|
516
|
+
|
|
517
|
+
if ($type === 'select' && $raw !== '' && !empty($field_def['options']) && !in_array($raw, $field_def['options'], true)) {
|
|
518
|
+
$errors[$name] = __('Please choose a valid option.', 'forgewp');
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
$clean = forgewp_forms_sanitize_field($raw, $field_def);
|
|
523
|
+
|
|
524
|
+
if ($required && ($clean === '' || $clean === null)) {
|
|
525
|
+
$errors[$name] = __('This field is required.', 'forgewp');
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if ($type === 'email' && $clean !== '' && !is_email($clean)) {
|
|
530
|
+
$errors[$name] = __('Please enter a valid email address.', 'forgewp');
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
$values[$name] = $clean;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
return array('values' => $values, 'errors' => $errors);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
if (!function_exists('forgewp_forms_resolve_lang')) {
|
|
542
|
+
/**
|
|
543
|
+
* Same resolution order used for menus/translations elsewhere in
|
|
544
|
+
* generated functions.php: explicit request param, then Polylang/WPML,
|
|
545
|
+
* then the site locale. An explicit $requested_lang (from a submitted
|
|
546
|
+
* form's own 'lang' param) always wins — REST requests don't reliably
|
|
547
|
+
* carry the visited page's Polylang context the way a normal page
|
|
548
|
+
* load does.
|
|
549
|
+
*/
|
|
550
|
+
function forgewp_forms_resolve_lang($requested_lang = null) {
|
|
551
|
+
if (!empty($requested_lang)) {
|
|
552
|
+
return sanitize_key($requested_lang);
|
|
553
|
+
}
|
|
554
|
+
if (function_exists('pll_current_language')) {
|
|
555
|
+
$lang = pll_current_language();
|
|
556
|
+
if (!empty($lang)) {
|
|
557
|
+
return $lang;
|
|
558
|
+
}
|
|
559
|
+
} elseif (defined('ICL_LANGUAGE_CODE')) {
|
|
560
|
+
return ICL_LANGUAGE_CODE;
|
|
561
|
+
}
|
|
562
|
+
if (function_exists('pll_default_language')) {
|
|
563
|
+
$lang = pll_default_language();
|
|
564
|
+
if (!empty($lang)) {
|
|
565
|
+
return $lang;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
$locale = get_locale();
|
|
569
|
+
if (strpos($locale, '_') !== false) {
|
|
570
|
+
$locale = explode('_', $locale)[0];
|
|
571
|
+
}
|
|
572
|
+
return $locale ?: 'en';
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
if (!function_exists('forgewp_forms_get_client_fields')) {
|
|
577
|
+
/**
|
|
578
|
+
* Reads the currently stored client-owned field definitions for a form,
|
|
579
|
+
* falling back to its config-baked seed if the option was never
|
|
580
|
+
* initialized (should not normally happen — after_switch_theme/init
|
|
581
|
+
* seeds it — but production sites may have skipped that hook, e.g.
|
|
582
|
+
* after a manual DB import).
|
|
583
|
+
*
|
|
584
|
+
* $seed's own shape decides single- vs multi-locale behavior — the
|
|
585
|
+
* compiler passes a flat list for single-locale themes (unchanged
|
|
586
|
+
* behavior) or a locale-keyed map (array('en' => array(...), …)) for
|
|
587
|
+
* themes with more than one configured locale. Client-owned labels are
|
|
588
|
+
* runtime content typed into wp-admin, not compiled strings, so they
|
|
589
|
+
* can't go through __()/translations.json — they need this per-locale
|
|
590
|
+
* storage instead.
|
|
591
|
+
*/
|
|
592
|
+
function forgewp_forms_get_client_fields($form_name, $seed, $lang = null) {
|
|
593
|
+
$option_name = 'forgewp_form_fields_' . $form_name;
|
|
594
|
+
$stored = get_option($option_name, null);
|
|
595
|
+
$is_multilingual_seed = is_array($seed) && !isset($seed[0]);
|
|
596
|
+
|
|
597
|
+
if (!$is_multilingual_seed) {
|
|
598
|
+
// Single-locale theme — unchanged flat-list behavior.
|
|
599
|
+
return is_array($stored) ? $stored : $seed;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
$resolved_lang = forgewp_forms_resolve_lang($lang);
|
|
603
|
+
|
|
604
|
+
if (is_array($stored)) {
|
|
605
|
+
$stored_is_legacy_flat = isset($stored[0]) && is_array($stored[0]) && isset($stored[0]['name']);
|
|
606
|
+
if ($stored_is_legacy_flat) {
|
|
607
|
+
// Data saved before this form went multilingual — same
|
|
608
|
+
// content for every locale until the client re-saves a
|
|
609
|
+
// specific language tab, which splits storage per-locale.
|
|
610
|
+
return $stored;
|
|
611
|
+
}
|
|
612
|
+
if (isset($stored[$resolved_lang]) && is_array($stored[$resolved_lang])) {
|
|
613
|
+
return $stored[$resolved_lang];
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
if (isset($seed[$resolved_lang])) {
|
|
618
|
+
return $seed[$resolved_lang];
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// $resolved_lang isn't a locale this form actually has fields for
|
|
622
|
+
// (e.g. a forged/unrecognized 'lang' request param on a REST
|
|
623
|
+
// submission) — degrade to a REAL locale's field set instead of an
|
|
624
|
+
// empty array, so required client-owned fields still get validated
|
|
625
|
+
// rather than silently vanishing from validation entirely. Falls
|
|
626
|
+
// back to the theme's configured default locale, then to whichever
|
|
627
|
+
// locale the seed actually has.
|
|
628
|
+
$fallback_lang = ${fallbackLangPhp};
|
|
629
|
+
if ($fallback_lang !== '' && isset($seed[$fallback_lang])) {
|
|
630
|
+
return $seed[$fallback_lang];
|
|
631
|
+
}
|
|
632
|
+
if (is_array($seed) && !empty($seed)) {
|
|
633
|
+
return reset($seed);
|
|
634
|
+
}
|
|
635
|
+
return array();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
`;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function buildSubmissionCptPhp(textDomain, formNames, adminCapability) {
|
|
642
|
+
const formNamesPhpArray = `array(${formNames.map((n) => phpString(n)).join(', ')})`;
|
|
643
|
+
const submissionCapabilities = [
|
|
644
|
+
'edit_post',
|
|
645
|
+
'read_post',
|
|
646
|
+
'delete_post',
|
|
647
|
+
'edit_posts',
|
|
648
|
+
'edit_others_posts',
|
|
649
|
+
'publish_posts',
|
|
650
|
+
'read_private_posts',
|
|
651
|
+
'delete_posts',
|
|
652
|
+
'delete_private_posts',
|
|
653
|
+
'delete_published_posts',
|
|
654
|
+
'delete_others_posts',
|
|
655
|
+
'edit_private_posts',
|
|
656
|
+
'edit_published_posts',
|
|
657
|
+
]
|
|
658
|
+
.map(
|
|
659
|
+
(capability) =>
|
|
660
|
+
` '${capability}' => ${phpString(adminCapability)},`,
|
|
661
|
+
)
|
|
662
|
+
.join('\n');
|
|
663
|
+
|
|
664
|
+
return `
|
|
665
|
+
if (!function_exists('forgewp_register_submission_cpt')) {
|
|
666
|
+
function forgewp_register_submission_cpt() {
|
|
667
|
+
register_post_type('forgewp_submission', array(
|
|
668
|
+
'labels' => array(
|
|
669
|
+
'name' => __('Form Submissions', '${textDomain}'),
|
|
670
|
+
'singular_name' => __('Submission', '${textDomain}'),
|
|
671
|
+
'menu_name' => __('Form Submissions', '${textDomain}'),
|
|
672
|
+
'all_items' => __('All Submissions', '${textDomain}'),
|
|
673
|
+
'not_found' => __('No submissions yet.', '${textDomain}'),
|
|
674
|
+
),
|
|
675
|
+
'public' => false,
|
|
676
|
+
'show_ui' => true,
|
|
677
|
+
'show_in_menu' => true,
|
|
678
|
+
'menu_icon' => 'dashicons-email-alt',
|
|
679
|
+
'supports' => array('title'),
|
|
680
|
+
'capability_type' => 'forgewp_submission',
|
|
681
|
+
'capabilities' => array(
|
|
682
|
+
${submissionCapabilities}
|
|
683
|
+
'create_posts' => 'do_not_allow',
|
|
684
|
+
),
|
|
685
|
+
// The configured Forms capability is primitive; do not register it as a global meta-cap alias.
|
|
686
|
+
'map_meta_cap' => false,
|
|
687
|
+
));
|
|
688
|
+
}
|
|
689
|
+
add_action('init', 'forgewp_register_submission_cpt');
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
if (!function_exists('forgewp_submission_columns')) {
|
|
693
|
+
/**
|
|
694
|
+
* Adds a "Form" column so the submissions list stays legible once a
|
|
695
|
+
* theme has more than one form — without this, the list is just
|
|
696
|
+
* "contact — 2026-07-17" / "hotel-inquiry — 2026-07-17" rows with no
|
|
697
|
+
* way to tell forms apart at a glance or filter to just one.
|
|
698
|
+
*/
|
|
699
|
+
function forgewp_submission_columns($columns) {
|
|
700
|
+
$new_columns = array();
|
|
701
|
+
foreach ($columns as $key => $label) {
|
|
702
|
+
$new_columns[$key] = $label;
|
|
703
|
+
if ($key === 'title') {
|
|
704
|
+
$new_columns['forgewp_form'] = __('Form', '${textDomain}');
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return $new_columns;
|
|
708
|
+
}
|
|
709
|
+
add_filter('manage_forgewp_submission_posts_columns', 'forgewp_submission_columns');
|
|
710
|
+
|
|
711
|
+
function forgewp_submission_column_content($column, $post_id) {
|
|
712
|
+
if ($column === 'forgewp_form') {
|
|
713
|
+
$form_name = get_post_meta($post_id, '_form_name', true);
|
|
714
|
+
echo esc_html($form_name ? $form_name : '\\u2014');
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
add_action('manage_forgewp_submission_posts_custom_column', 'forgewp_submission_column_content', 10, 2);
|
|
718
|
+
|
|
719
|
+
function forgewp_submission_sortable_columns($columns) {
|
|
720
|
+
$columns['forgewp_form'] = 'forgewp_form';
|
|
721
|
+
return $columns;
|
|
722
|
+
}
|
|
723
|
+
add_filter('manage_edit-forgewp_submission_sortable_columns', 'forgewp_submission_sortable_columns');
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
if (!function_exists('forgewp_submission_filter_dropdown')) {
|
|
727
|
+
/**
|
|
728
|
+
* "Filter by form" dropdown above the submissions list — only worth
|
|
729
|
+
* showing once a theme actually has more than one form.
|
|
730
|
+
*/
|
|
731
|
+
function forgewp_submission_filter_dropdown() {
|
|
732
|
+
global $typenow;
|
|
733
|
+
if ($typenow !== 'forgewp_submission') {
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
$forms = ${formNamesPhpArray};
|
|
737
|
+
if (count($forms) < 2) {
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
$current = isset($_GET['forgewp_form']) ? sanitize_text_field($_GET['forgewp_form']) : '';
|
|
741
|
+
echo '<select name="forgewp_form">';
|
|
742
|
+
echo '<option value="">' . esc_html__('All forms', '${textDomain}') . '</option>';
|
|
743
|
+
foreach ($forms as $form) {
|
|
744
|
+
echo '<option value="' . esc_attr($form) . '"' . selected($current, $form, false) . '>' . esc_html($form) . '</option>';
|
|
745
|
+
}
|
|
746
|
+
echo '</select>';
|
|
747
|
+
}
|
|
748
|
+
add_action('restrict_manage_posts', 'forgewp_submission_filter_dropdown');
|
|
749
|
+
|
|
750
|
+
function forgewp_submission_filter_query($query) {
|
|
751
|
+
global $pagenow, $typenow;
|
|
752
|
+
if (!is_admin() || $pagenow !== 'edit.php' || $typenow !== 'forgewp_submission' || !$query->is_main_query()) {
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
if (!empty($_GET['forgewp_form'])) {
|
|
756
|
+
$query->set('meta_key', '_form_name');
|
|
757
|
+
$query->set('meta_value', sanitize_text_field($_GET['forgewp_form']));
|
|
758
|
+
}
|
|
759
|
+
if ($query->get('orderby') === 'forgewp_form') {
|
|
760
|
+
$query->set('meta_key', '_form_name');
|
|
761
|
+
$query->set('orderby', 'meta_value');
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
add_action('pre_get_posts', 'forgewp_submission_filter_query');
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
if (!function_exists('forgewp_submission_meta_box')) {
|
|
768
|
+
function forgewp_submission_meta_box() {
|
|
769
|
+
add_meta_box(
|
|
770
|
+
'forgewp_submission_fields',
|
|
771
|
+
__('Submission Details', '${textDomain}'),
|
|
772
|
+
'forgewp_render_submission_meta_box',
|
|
773
|
+
'forgewp_submission',
|
|
774
|
+
'normal',
|
|
775
|
+
'high'
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
add_action('add_meta_boxes', 'forgewp_submission_meta_box');
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
if (!function_exists('forgewp_render_submission_meta_box')) {
|
|
783
|
+
function forgewp_render_submission_meta_box($post) {
|
|
784
|
+
$meta = get_post_meta($post->ID);
|
|
785
|
+
echo '<table class="widefat"><tbody>';
|
|
786
|
+
foreach ($meta as $key => $values) {
|
|
787
|
+
if (strpos($key, 'field_') !== 0) {
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
$label = ucwords(str_replace(array('field_', '_'), array('', ' '), $key));
|
|
791
|
+
$value = isset($values[0]) ? $values[0] : '';
|
|
792
|
+
echo '<tr><th style="text-align:left;width:180px">' . esc_html($label) . '</th><td>' . esc_html($value) . '</td></tr>';
|
|
793
|
+
}
|
|
794
|
+
$form_name = get_post_meta($post->ID, '_form_name', true);
|
|
795
|
+
$submitted_at = get_post_meta($post->ID, '_submitted_at', true);
|
|
796
|
+
echo '<tr><th style="text-align:left">' . esc_html__('Form', '${textDomain}') . '</th><td>' . esc_html($form_name) . '</td></tr>';
|
|
797
|
+
echo '<tr><th style="text-align:left">' . esc_html__('Submitted', '${textDomain}') . '</th><td>' . esc_html($submitted_at) . '</td></tr>';
|
|
798
|
+
echo '</tbody></table>';
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
if (!function_exists('forgewp_store_submission')) {
|
|
803
|
+
function forgewp_store_submission($form_name, $values, $field_defs, $language = '', $title_template = '') {
|
|
804
|
+
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
|
|
805
|
+
$title = trim((string) $title_template) !== ''
|
|
806
|
+
? sanitize_text_field(forgewp_forms_interpolate_template($title_template, $values))
|
|
807
|
+
: '';
|
|
808
|
+
if ($title === '') {
|
|
809
|
+
$title = sprintf('%s — %s', $form_name, current_time('mysql'));
|
|
810
|
+
} else {
|
|
811
|
+
$title .= ' — ' . current_time('mysql');
|
|
812
|
+
}
|
|
813
|
+
$post_id = wp_insert_post(array(
|
|
814
|
+
'post_type' => 'forgewp_submission',
|
|
815
|
+
'post_status' => 'publish',
|
|
816
|
+
'post_title' => $title,
|
|
817
|
+
));
|
|
818
|
+
if (is_wp_error($post_id) || !$post_id) {
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
foreach ($values as $key => $value) {
|
|
822
|
+
update_post_meta($post_id, 'field_' . $key, $value);
|
|
823
|
+
}
|
|
824
|
+
foreach ($field_defs as $field_def) {
|
|
825
|
+
$email_field = isset($field_def['name']) ? $field_def['name'] : '';
|
|
826
|
+
if (
|
|
827
|
+
isset($field_def['type']) &&
|
|
828
|
+
$field_def['type'] === 'email' &&
|
|
829
|
+
$email_field !== '' &&
|
|
830
|
+
!empty($values[$email_field]) &&
|
|
831
|
+
is_email($values[$email_field])
|
|
832
|
+
) {
|
|
833
|
+
$normalized_email = strtolower(trim((string) $values[$email_field]));
|
|
834
|
+
add_post_meta(
|
|
835
|
+
$post_id,
|
|
836
|
+
'_privacy_email_hash',
|
|
837
|
+
hash_hmac('sha256', $normalized_email, wp_salt('auth')),
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
update_post_meta($post_id, '_form_name', $form_name);
|
|
842
|
+
update_post_meta($post_id, '_submitted_at', current_time('mysql'));
|
|
843
|
+
if (!empty($language)) {
|
|
844
|
+
update_post_meta($post_id, '_form_lang', sanitize_key($language));
|
|
845
|
+
}
|
|
846
|
+
update_post_meta($post_id, '_ip_hash', md5($ip));
|
|
847
|
+
return $post_id;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
`;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
function buildSubmissionToolsPhp(forms, textDomain, adminCapability, locales) {
|
|
854
|
+
const entries = Object.entries(forms);
|
|
855
|
+
const storedNamesPhp = `array(${entries.map(([name]) => phpString(name)).join(', ')})`;
|
|
856
|
+
const emailFields = entries
|
|
857
|
+
.map(([name, form]) => [
|
|
858
|
+
name,
|
|
859
|
+
Object.entries(form.fields || {})
|
|
860
|
+
.filter(([, field]) => field.type === 'email')
|
|
861
|
+
.map(([fieldName]) => fieldName),
|
|
862
|
+
])
|
|
863
|
+
.filter(([, fieldNames]) => fieldNames.length > 0);
|
|
864
|
+
const emailFieldsPhp = `array(
|
|
865
|
+
${emailFields
|
|
866
|
+
.map(
|
|
867
|
+
([name, fieldNames]) =>
|
|
868
|
+
` ${phpString(name)} => array(${fieldNames.map(phpString).join(', ')}),`,
|
|
869
|
+
)
|
|
870
|
+
.join('\n')}
|
|
871
|
+
)`;
|
|
872
|
+
const privacyForms = entries;
|
|
873
|
+
const staticLabelsPhp = `array(
|
|
874
|
+
${entries
|
|
875
|
+
.map(([name, form]) => {
|
|
876
|
+
const fields = Object.entries(form.fields || {}).map(
|
|
877
|
+
([fieldName, field]) => {
|
|
878
|
+
const label =
|
|
879
|
+
field.label ||
|
|
880
|
+
fieldName
|
|
881
|
+
.replace(/[_-]/g, ' ')
|
|
882
|
+
.replace(/\b\w/g, (letter) => letter.toUpperCase());
|
|
883
|
+
return ` ${phpString(fieldName)} => __( ${phpString(label)}, ${phpString(textDomain)} ),`;
|
|
884
|
+
},
|
|
885
|
+
);
|
|
886
|
+
const clientSeed = form.clientFields?.enabled
|
|
887
|
+
? Array.isArray(form.clientFields.seed)
|
|
888
|
+
? form.clientFields.seed
|
|
889
|
+
: Object.values(form.clientFields.seed || {}).flat()
|
|
890
|
+
: [];
|
|
891
|
+
fields.push(
|
|
892
|
+
...clientSeed.map(
|
|
893
|
+
(field) =>
|
|
894
|
+
` ${phpString(field.name)} => ${phpString(field.label || field.name)},`,
|
|
895
|
+
),
|
|
896
|
+
);
|
|
897
|
+
return ` ${phpString(name)} => array(\n${fields.join('\n')}\n ),`;
|
|
898
|
+
})
|
|
899
|
+
.join('\n')}
|
|
900
|
+
)`;
|
|
901
|
+
const clientSeeds = entries.filter(([, form]) => form.clientFields?.enabled);
|
|
902
|
+
const clientSeedsPhp = `array(
|
|
903
|
+
${clientSeeds
|
|
904
|
+
.map(([name, form]) => {
|
|
905
|
+
const seedPhp =
|
|
906
|
+
locales.length > 1
|
|
907
|
+
? seedByLocalePhpArray(form.clientFields.seed, locales)
|
|
908
|
+
: seedFieldsPhpArray(
|
|
909
|
+
Array.isArray(form.clientFields.seed)
|
|
910
|
+
? form.clientFields.seed
|
|
911
|
+
: Object.values(form.clientFields.seed || {}).flat(),
|
|
912
|
+
);
|
|
913
|
+
return ` ${phpString(name)} => ${seedPhp},`;
|
|
914
|
+
})
|
|
915
|
+
.join('\n')}
|
|
916
|
+
)`;
|
|
917
|
+
const retentionRules = entries.filter(
|
|
918
|
+
([, form]) => form.retentionDays !== undefined,
|
|
919
|
+
);
|
|
920
|
+
const retentionRulesPhp = `array(${retentionRules
|
|
921
|
+
.map(([name, form]) => `${phpString(name)} => ${form.retentionDays}`)
|
|
922
|
+
.join(', ')})`;
|
|
923
|
+
const langPhp =
|
|
924
|
+
locales.length > 1 ? ' $lang = forgewp_forms_resolve_lang();\n' : '';
|
|
925
|
+
const retentionPhp =
|
|
926
|
+
retentionRules.length > 0
|
|
927
|
+
? `
|
|
928
|
+
if (!function_exists('forgewp_forms_retention_cleanup')) {
|
|
929
|
+
function forgewp_forms_retention_cleanup() {
|
|
930
|
+
$retention_days = ${retentionRulesPhp};
|
|
931
|
+
$deleted = 0;
|
|
932
|
+
foreach ($retention_days as $form_name => $days) {
|
|
933
|
+
$cutoff = current_datetime()->modify('-' . (int) $days . ' days')->format('Y-m-d H:i:s');
|
|
934
|
+
do {
|
|
935
|
+
$ids = get_posts(array(
|
|
936
|
+
'post_type' => 'forgewp_submission',
|
|
937
|
+
'post_status' => 'any',
|
|
938
|
+
'posts_per_page' => 100,
|
|
939
|
+
'fields' => 'ids',
|
|
940
|
+
'orderby' => 'ID',
|
|
941
|
+
'order' => 'ASC',
|
|
942
|
+
'meta_query' => array(
|
|
943
|
+
'relation' => 'AND',
|
|
944
|
+
array('key' => '_form_name', 'value' => $form_name, 'compare' => '='),
|
|
945
|
+
array('key' => '_submitted_at', 'value' => $cutoff, 'compare' => '<', 'type' => 'DATETIME'),
|
|
946
|
+
),
|
|
947
|
+
));
|
|
948
|
+
$batch_deleted = 0;
|
|
949
|
+
foreach ($ids as $submission_id) {
|
|
950
|
+
if (wp_delete_post($submission_id, true)) {
|
|
951
|
+
$batch_deleted++;
|
|
952
|
+
$deleted++;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
} while (count($ids) === 100 && $batch_deleted > 0);
|
|
956
|
+
}
|
|
957
|
+
if ($deleted > 0) {
|
|
958
|
+
error_log('[ForgeWP Forms] Retention cleanup permanently deleted ' . $deleted . ' expired submission(s).');
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
add_action('forgewp_forms_retention_cleanup', 'forgewp_forms_retention_cleanup');
|
|
962
|
+
add_action('init', function () {
|
|
963
|
+
if (!wp_next_scheduled('forgewp_forms_retention_cleanup')) {
|
|
964
|
+
$scheduled = wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', 'forgewp_forms_retention_cleanup');
|
|
965
|
+
if (is_wp_error($scheduled) || $scheduled === false) {
|
|
966
|
+
error_log('[ForgeWP Forms] Could not schedule retention cleanup.');
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
`
|
|
972
|
+
: `
|
|
973
|
+
add_action('init', function () {
|
|
974
|
+
wp_clear_scheduled_hook('forgewp_forms_retention_cleanup');
|
|
975
|
+
});
|
|
976
|
+
`;
|
|
977
|
+
|
|
978
|
+
return `
|
|
979
|
+
if (!function_exists('forgewp_forms_submission_field_labels')) {
|
|
980
|
+
function forgewp_forms_submission_field_labels() {
|
|
981
|
+
$labels = ${staticLabelsPhp};
|
|
982
|
+
$client_seeds = ${clientSeedsPhp};
|
|
983
|
+
${langPhp} foreach ($client_seeds as $form_name => $seed) {
|
|
984
|
+
$client_fields = forgewp_forms_get_client_fields($form_name, $seed${locales.length > 1 ? ', $lang' : ''});
|
|
985
|
+
foreach ($client_fields as $field) {
|
|
986
|
+
if (isset($field['name'])) {
|
|
987
|
+
$labels[$form_name][$field['name']] = isset($field['label']) ? $field['label'] : $field['name'];
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
foreach (array(${Object.keys(forms).map(phpString).join(', ')}) as $form_name) {
|
|
992
|
+
$settings = get_option('forgewp_form_settings_' . $form_name, array());
|
|
993
|
+
if (isset($settings['fieldLabels']) && is_array($settings['fieldLabels'])) {
|
|
994
|
+
foreach ($settings['fieldLabels'] as $field_name => $label) {
|
|
995
|
+
if (isset($labels[$form_name][$field_name]) && is_string($label) && $label !== '') {
|
|
996
|
+
$labels[$form_name][$field_name] = $label;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
return $labels;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
if (!function_exists('forgewp_forms_csv_safe_value')) {
|
|
1006
|
+
function forgewp_forms_csv_safe_value($value) {
|
|
1007
|
+
$value = is_scalar($value) ? (string) $value : '';
|
|
1008
|
+
$first = substr($value, 0, 1);
|
|
1009
|
+
if (in_array($first, array('=', '+', '-', '@', chr(9), chr(13)), true)) {
|
|
1010
|
+
return "'" . $value;
|
|
1011
|
+
}
|
|
1012
|
+
return $value;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
if (!function_exists('forgewp_forms_render_export_page')) {
|
|
1017
|
+
function forgewp_forms_render_export_page() {
|
|
1018
|
+
if (!current_user_can(${phpString(adminCapability)})) {
|
|
1019
|
+
wp_die(__('You do not have permission to export form submissions.', '${textDomain}'));
|
|
1020
|
+
}
|
|
1021
|
+
$forms = ${storedNamesPhp};
|
|
1022
|
+
$field_labels = forgewp_forms_submission_field_labels();
|
|
1023
|
+
?>
|
|
1024
|
+
<div class="wrap forgewp-export-page">
|
|
1025
|
+
<h1><?php esc_html_e('Export form submissions', '${textDomain}'); ?></h1>
|
|
1026
|
+
<div class="notice notice-warning inline"><p><?php esc_html_e('CSV files contain submitted personal data. Store exports securely and delete them when they are no longer needed. IP hashes are never exported.', '${textDomain}'); ?></p></div>
|
|
1027
|
+
<form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>">
|
|
1028
|
+
<input type="hidden" name="action" value="forgewp_forms_export_csv" />
|
|
1029
|
+
<?php wp_nonce_field('forgewp_forms_export_csv'); ?>
|
|
1030
|
+
<table class="form-table"><tbody>
|
|
1031
|
+
<tr><th scope="row"><label for="forgewp-export-form"><?php esc_html_e('Form', '${textDomain}'); ?></label></th><td>
|
|
1032
|
+
<select id="forgewp-export-form" name="forgewp_form">
|
|
1033
|
+
<option value="all"><?php esc_html_e('All stored forms', '${textDomain}'); ?></option>
|
|
1034
|
+
<?php foreach ($forms as $form_name) : ?><option value="<?php echo esc_attr($form_name); ?>"><?php echo esc_html($form_name); ?></option><?php endforeach; ?>
|
|
1035
|
+
</select>
|
|
1036
|
+
</td></tr>
|
|
1037
|
+
<tr><th scope="row"><label for="forgewp-export-from"><?php esc_html_e('From date', '${textDomain}'); ?></label></th><td><input id="forgewp-export-from" type="date" name="forgewp_from" /></td></tr>
|
|
1038
|
+
<tr><th scope="row"><label for="forgewp-export-to"><?php esc_html_e('To date', '${textDomain}'); ?></label></th><td><input id="forgewp-export-to" type="date" name="forgewp_to" /></td></tr>
|
|
1039
|
+
</tbody></table>
|
|
1040
|
+
<fieldset class="forgewp-export-fields">
|
|
1041
|
+
<legend><?php esc_html_e('Personal-data fields to include', '${textDomain}'); ?></legend>
|
|
1042
|
+
<p><?php esc_html_e('Fields are unchecked by default. Select only the columns required for this export.', '${textDomain}'); ?></p>
|
|
1043
|
+
<?php foreach ($field_labels as $form_name => $fields) : ?>
|
|
1044
|
+
<fieldset class="forgewp-export-form-fields" data-export-form="<?php echo esc_attr($form_name); ?>">
|
|
1045
|
+
<legend><?php echo esc_html($form_name); ?></legend>
|
|
1046
|
+
<?php foreach ($fields as $field_name => $field_label) : ?>
|
|
1047
|
+
<label class="forgewp-export-field"><input type="checkbox" name="forgewp_fields[]" value="<?php echo esc_attr($form_name . '|' . $field_name); ?>" /> <span><?php echo esc_html($field_label); ?></span></label>
|
|
1048
|
+
<?php endforeach; ?>
|
|
1049
|
+
</fieldset>
|
|
1050
|
+
<?php endforeach; ?>
|
|
1051
|
+
</fieldset>
|
|
1052
|
+
<?php submit_button( __('Download CSV', '${textDomain}') ); ?>
|
|
1053
|
+
</form>
|
|
1054
|
+
</div>
|
|
1055
|
+
<style>
|
|
1056
|
+
.forgewp-export-page { max-width: 1160px; }
|
|
1057
|
+
.forgewp-export-page > p, .forgewp-export-page .notice { max-width: 900px; }
|
|
1058
|
+
.forgewp-export-page form { max-width: 1000px; }
|
|
1059
|
+
.forgewp-export-page .form-table { max-width: 820px; margin: 18px 0 24px; }
|
|
1060
|
+
.forgewp-export-page .form-table th { width: 190px; padding: 16px 18px 16px 0; }
|
|
1061
|
+
.forgewp-export-page .form-table td { padding: 10px 0; }
|
|
1062
|
+
.forgewp-export-fields { max-width: 1000px; margin: 20px 0; padding: 18px 20px 22px; border: 1px solid #c3c4c7; background: #fff; }
|
|
1063
|
+
.forgewp-export-fields > legend { padding: 0 8px; font-size: 14px; font-weight: 600; }
|
|
1064
|
+
.forgewp-export-fields > p { margin: 4px 0 18px; color: #646970; }
|
|
1065
|
+
.forgewp-export-form-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 10px 18px; margin: 14px 0 0; padding: 16px; border: 1px solid #dcdcde; background: #f6f7f7; }
|
|
1066
|
+
.forgewp-export-form-fields > legend { grid-column: 1 / -1; padding: 0 6px; font-weight: 600; }
|
|
1067
|
+
.forgewp-export-form-fields[hidden] { display: none !important; }
|
|
1068
|
+
.forgewp-export-field { display: flex; align-items: flex-start; gap: 8px; min-width: 0; line-height: 1.45; }
|
|
1069
|
+
.forgewp-export-field input { flex: 0 0 auto; margin: 2px 0 0; }
|
|
1070
|
+
.forgewp-export-field span { overflow-wrap: anywhere; }
|
|
1071
|
+
@media (max-width: 782px) {
|
|
1072
|
+
.forgewp-export-page .form-table, .forgewp-export-page .form-table tbody, .forgewp-export-page .form-table tr, .forgewp-export-page .form-table th, .forgewp-export-page .form-table td { display: block; width: auto; }
|
|
1073
|
+
.forgewp-export-page .form-table th { padding: 12px 0 4px; }
|
|
1074
|
+
.forgewp-export-page .form-table td { padding: 4px 0 8px; }
|
|
1075
|
+
.forgewp-export-fields { padding: 14px; }
|
|
1076
|
+
.forgewp-export-form-fields { grid-template-columns: minmax(0, 1fr); padding: 12px; }
|
|
1077
|
+
}
|
|
1078
|
+
</style>
|
|
1079
|
+
<?php
|
|
1080
|
+
}
|
|
1081
|
+
add_action('admin_menu', function () {
|
|
1082
|
+
add_submenu_page(
|
|
1083
|
+
'edit.php?post_type=forgewp_submission',
|
|
1084
|
+
__('Export form submissions', '${textDomain}'),
|
|
1085
|
+
__('Export CSV', '${textDomain}'),
|
|
1086
|
+
${phpString(adminCapability)},
|
|
1087
|
+
'forgewp-submission-export',
|
|
1088
|
+
'forgewp_forms_render_export_page'
|
|
1089
|
+
);
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
if (!function_exists('forgewp_forms_export_csv')) {
|
|
1094
|
+
function forgewp_forms_export_csv() {
|
|
1095
|
+
if (!current_user_can(${phpString(adminCapability)})) {
|
|
1096
|
+
wp_die(__('You do not have permission to export form submissions.', '${textDomain}'));
|
|
1097
|
+
}
|
|
1098
|
+
check_admin_referer('forgewp_forms_export_csv');
|
|
1099
|
+
$allowed_forms = ${storedNamesPhp};
|
|
1100
|
+
$selected_form = isset($_POST['forgewp_form']) ? sanitize_key(wp_unslash($_POST['forgewp_form'])) : 'all';
|
|
1101
|
+
if ($selected_form !== 'all' && !in_array($selected_form, $allowed_forms, true)) {
|
|
1102
|
+
wp_die(__('Invalid form filter.', '${textDomain}'));
|
|
1103
|
+
}
|
|
1104
|
+
$from = isset($_POST['forgewp_from']) ? sanitize_text_field(wp_unslash($_POST['forgewp_from'])) : '';
|
|
1105
|
+
$to = isset($_POST['forgewp_to']) ? sanitize_text_field(wp_unslash($_POST['forgewp_to'])) : '';
|
|
1106
|
+
foreach (array($from, $to) as $date) {
|
|
1107
|
+
if ($date !== '') {
|
|
1108
|
+
$parsed = DateTime::createFromFormat('!Y-m-d', $date);
|
|
1109
|
+
if (!$parsed || $parsed->format('Y-m-d') !== $date) {
|
|
1110
|
+
wp_die(__('Dates must use the YYYY-MM-DD format.', '${textDomain}'));
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
if ($from !== '' && $to !== '' && $from > $to) {
|
|
1115
|
+
wp_die(__('The start date must not be after the end date.', '${textDomain}'));
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
$meta_query = array('relation' => 'AND');
|
|
1119
|
+
if ($selected_form !== 'all') {
|
|
1120
|
+
$meta_query[] = array('key' => '_form_name', 'value' => $selected_form, 'compare' => '=');
|
|
1121
|
+
}
|
|
1122
|
+
if ($from !== '') {
|
|
1123
|
+
$meta_query[] = array('key' => '_submitted_at', 'value' => $from . ' 00:00:00', 'compare' => '>=', 'type' => 'DATETIME');
|
|
1124
|
+
}
|
|
1125
|
+
if ($to !== '') {
|
|
1126
|
+
$meta_query[] = array('key' => '_submitted_at', 'value' => $to . ' 23:59:59', 'compare' => '<=', 'type' => 'DATETIME');
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
$labels = forgewp_forms_submission_field_labels();
|
|
1130
|
+
$requested_fields = isset($_POST['forgewp_fields']) && is_array($_POST['forgewp_fields'])
|
|
1131
|
+
? array_map('sanitize_text_field', wp_unslash($_POST['forgewp_fields']))
|
|
1132
|
+
: array();
|
|
1133
|
+
$columns = array();
|
|
1134
|
+
foreach ($requested_fields as $field_key) {
|
|
1135
|
+
$separator = strpos($field_key, '|');
|
|
1136
|
+
if ($separator === false) {
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
$field_form = substr($field_key, 0, $separator);
|
|
1140
|
+
$field_name = substr($field_key, $separator + 1);
|
|
1141
|
+
if (
|
|
1142
|
+
($selected_form !== 'all' && $selected_form !== $field_form) ||
|
|
1143
|
+
!isset($labels[$field_form][$field_name])
|
|
1144
|
+
) {
|
|
1145
|
+
continue;
|
|
1146
|
+
}
|
|
1147
|
+
$columns[] = array(
|
|
1148
|
+
'form' => $field_form,
|
|
1149
|
+
'field' => $field_name,
|
|
1150
|
+
'label' => $selected_form === 'all'
|
|
1151
|
+
? $field_form . ' / ' . $labels[$field_form][$field_name]
|
|
1152
|
+
: $labels[$field_form][$field_name],
|
|
1153
|
+
);
|
|
1154
|
+
}
|
|
1155
|
+
if (empty($columns)) {
|
|
1156
|
+
wp_die(__('Select at least one valid field to export.', '${textDomain}'));
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
nocache_headers();
|
|
1160
|
+
header('Content-Type: text/csv; charset=utf-8');
|
|
1161
|
+
header('Content-Disposition: attachment; filename="forgewp-submissions-' . gmdate('Y-m-d') . '.csv"');
|
|
1162
|
+
$output = fopen('php://output', 'w');
|
|
1163
|
+
fwrite($output, chr(239) . chr(187) . chr(191));
|
|
1164
|
+
$header = array(__('Form', '${textDomain}'), __('Language', '${textDomain}'), __('Submitted at', '${textDomain}'));
|
|
1165
|
+
foreach ($columns as $column) {
|
|
1166
|
+
$header[] = forgewp_forms_csv_safe_value($column['label']);
|
|
1167
|
+
}
|
|
1168
|
+
fputcsv($output, $header);
|
|
1169
|
+
|
|
1170
|
+
$offset = 0;
|
|
1171
|
+
$exported = 0;
|
|
1172
|
+
do {
|
|
1173
|
+
$posts = get_posts(array(
|
|
1174
|
+
'post_type' => 'forgewp_submission',
|
|
1175
|
+
'post_status' => 'any',
|
|
1176
|
+
'posts_per_page' => 200,
|
|
1177
|
+
'offset' => $offset,
|
|
1178
|
+
'orderby' => 'ID',
|
|
1179
|
+
'order' => 'ASC',
|
|
1180
|
+
'meta_query' => count($meta_query) > 1 ? $meta_query : array(),
|
|
1181
|
+
));
|
|
1182
|
+
foreach ($posts as $submission) {
|
|
1183
|
+
$form_name = get_post_meta($submission->ID, '_form_name', true);
|
|
1184
|
+
if (!in_array($form_name, $allowed_forms, true)) {
|
|
1185
|
+
continue;
|
|
1186
|
+
}
|
|
1187
|
+
$row = array(
|
|
1188
|
+
forgewp_forms_csv_safe_value($form_name),
|
|
1189
|
+
forgewp_forms_csv_safe_value(get_post_meta($submission->ID, '_form_lang', true)),
|
|
1190
|
+
forgewp_forms_csv_safe_value(get_post_meta($submission->ID, '_submitted_at', true)),
|
|
1191
|
+
);
|
|
1192
|
+
foreach ($columns as $column) {
|
|
1193
|
+
$value = $column['form'] === $form_name
|
|
1194
|
+
? get_post_meta($submission->ID, 'field_' . $column['field'], true)
|
|
1195
|
+
: '';
|
|
1196
|
+
$row[] = forgewp_forms_csv_safe_value($value);
|
|
1197
|
+
}
|
|
1198
|
+
fputcsv($output, $row);
|
|
1199
|
+
$exported++;
|
|
1200
|
+
}
|
|
1201
|
+
$offset += count($posts);
|
|
1202
|
+
} while (count($posts) === 200);
|
|
1203
|
+
|
|
1204
|
+
fclose($output);
|
|
1205
|
+
error_log('[ForgeWP Forms] CSV export completed (user ID: ' . get_current_user_id() . ', form: ' . $selected_form . ', rows: ' . $exported . ').');
|
|
1206
|
+
exit;
|
|
1207
|
+
}
|
|
1208
|
+
add_action('admin_post_forgewp_forms_export_csv', 'forgewp_forms_export_csv');
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
${
|
|
1212
|
+
privacyForms.length > 0
|
|
1213
|
+
? `
|
|
1214
|
+
if (!function_exists('forgewp_forms_privacy_email_fields')) {
|
|
1215
|
+
function forgewp_forms_privacy_email_fields() {
|
|
1216
|
+
$email_fields = ${emailFieldsPhp};
|
|
1217
|
+
$client_seeds = ${clientSeedsPhp};
|
|
1218
|
+
${langPhp} foreach ($client_seeds as $form_name => $seed) {
|
|
1219
|
+
if (!isset($email_fields[$form_name])) {
|
|
1220
|
+
$email_fields[$form_name] = array();
|
|
1221
|
+
}
|
|
1222
|
+
$fields = forgewp_forms_get_client_fields($form_name, $seed${locales.length > 1 ? ', $lang' : ''});
|
|
1223
|
+
foreach ($fields as $field) {
|
|
1224
|
+
if (isset($field['name'], $field['type']) && $field['type'] === 'email') {
|
|
1225
|
+
$email_fields[$form_name][] = $field['name'];
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
$email_fields[$form_name] = array_values(array_unique($email_fields[$form_name]));
|
|
1229
|
+
}
|
|
1230
|
+
return $email_fields;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
if (!function_exists('forgewp_forms_privacy_submission_ids')) {
|
|
1235
|
+
function forgewp_forms_privacy_submission_ids($email_address, $page = 1) {
|
|
1236
|
+
$email_address = sanitize_email($email_address);
|
|
1237
|
+
if (!is_email($email_address)) {
|
|
1238
|
+
return array();
|
|
1239
|
+
}
|
|
1240
|
+
$normalized_email = strtolower(trim($email_address));
|
|
1241
|
+
$meta_query = array(
|
|
1242
|
+
'relation' => 'OR',
|
|
1243
|
+
array(
|
|
1244
|
+
'key' => '_privacy_email_hash',
|
|
1245
|
+
'value' => hash_hmac('sha256', $normalized_email, wp_salt('auth')),
|
|
1246
|
+
'compare' => '=',
|
|
1247
|
+
),
|
|
1248
|
+
);
|
|
1249
|
+
foreach (forgewp_forms_privacy_email_fields() as $form_name => $field_names) {
|
|
1250
|
+
foreach ($field_names as $field_name) {
|
|
1251
|
+
$meta_query[] = array(
|
|
1252
|
+
'relation' => 'AND',
|
|
1253
|
+
array('key' => '_form_name', 'value' => $form_name, 'compare' => '='),
|
|
1254
|
+
array('key' => 'field_' . $field_name, 'value' => $email_address, 'compare' => '='),
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
if (count($meta_query) < 2) {
|
|
1259
|
+
return array();
|
|
1260
|
+
}
|
|
1261
|
+
return get_posts(array(
|
|
1262
|
+
'post_type' => 'forgewp_submission',
|
|
1263
|
+
'post_status' => 'any',
|
|
1264
|
+
'posts_per_page' => 100,
|
|
1265
|
+
'offset' => max(0, ((int) $page - 1) * 100),
|
|
1266
|
+
'fields' => 'ids',
|
|
1267
|
+
'orderby' => 'ID',
|
|
1268
|
+
'order' => 'ASC',
|
|
1269
|
+
'meta_query' => $meta_query,
|
|
1270
|
+
));
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
if (!function_exists('forgewp_forms_privacy_export')) {
|
|
1275
|
+
function forgewp_forms_privacy_export($email_address, $page = 1) {
|
|
1276
|
+
$ids = forgewp_forms_privacy_submission_ids($email_address, $page);
|
|
1277
|
+
$labels = forgewp_forms_submission_field_labels();
|
|
1278
|
+
$data = array();
|
|
1279
|
+
foreach ($ids as $submission_id) {
|
|
1280
|
+
$form_name = get_post_meta($submission_id, '_form_name', true);
|
|
1281
|
+
$submitted_at = get_post_meta($submission_id, '_submitted_at', true);
|
|
1282
|
+
$fields = get_post_meta($submission_id);
|
|
1283
|
+
$item_data = array(
|
|
1284
|
+
array('name' => __('Form', '${textDomain}'), 'value' => $form_name),
|
|
1285
|
+
array('name' => __('Submitted at', '${textDomain}'), 'value' => $submitted_at),
|
|
1286
|
+
);
|
|
1287
|
+
foreach ($fields as $key => $values) {
|
|
1288
|
+
if (strpos($key, 'field_') !== 0) {
|
|
1289
|
+
continue;
|
|
1290
|
+
}
|
|
1291
|
+
$field_name = substr($key, 6);
|
|
1292
|
+
$label = isset($labels[$form_name][$field_name]) ? $labels[$form_name][$field_name] : $field_name;
|
|
1293
|
+
$item_data[] = array('name' => $label, 'value' => isset($values[0]) ? $values[0] : '');
|
|
1294
|
+
}
|
|
1295
|
+
$data[] = array(
|
|
1296
|
+
'group_id' => 'forgewp-submissions',
|
|
1297
|
+
'group_label' => __('Form submissions', '${textDomain}'),
|
|
1298
|
+
'item_id' => 'forgewp-submission-' . (int) $submission_id,
|
|
1299
|
+
'data' => $item_data,
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
return array(
|
|
1303
|
+
'data' => $data,
|
|
1304
|
+
'done' => count($ids) < 100,
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
if (!function_exists('forgewp_forms_privacy_erase')) {
|
|
1310
|
+
function forgewp_forms_privacy_erase($email_address) {
|
|
1311
|
+
$removed = 0;
|
|
1312
|
+
do {
|
|
1313
|
+
$ids = forgewp_forms_privacy_submission_ids($email_address, 1);
|
|
1314
|
+
$batch_removed = 0;
|
|
1315
|
+
foreach ($ids as $submission_id) {
|
|
1316
|
+
if (wp_delete_post($submission_id, true)) {
|
|
1317
|
+
$batch_removed++;
|
|
1318
|
+
$removed++;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
} while (count($ids) === 100 && $batch_removed > 0);
|
|
1322
|
+
return array(
|
|
1323
|
+
'items_removed' => $removed > 0,
|
|
1324
|
+
'items_retained' => false,
|
|
1325
|
+
'messages' => array(),
|
|
1326
|
+
'done' => true,
|
|
1327
|
+
);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
add_filter('wp_privacy_personal_data_exporters', function ($exporters) {
|
|
1332
|
+
$exporters['forgewp-form-submissions'] = array(
|
|
1333
|
+
'exporter_friendly_name' => __('ForgeWP form submissions', '${textDomain}'),
|
|
1334
|
+
'callback' => 'forgewp_forms_privacy_export',
|
|
1335
|
+
);
|
|
1336
|
+
return $exporters;
|
|
1337
|
+
});
|
|
1338
|
+
add_filter('wp_privacy_personal_data_erasers', function ($erasers) {
|
|
1339
|
+
$erasers['forgewp-form-submissions'] = array(
|
|
1340
|
+
'eraser_friendly_name' => __('ForgeWP form submissions', '${textDomain}'),
|
|
1341
|
+
'callback' => 'forgewp_forms_privacy_erase',
|
|
1342
|
+
);
|
|
1343
|
+
return $erasers;
|
|
1344
|
+
});
|
|
1345
|
+
`
|
|
1346
|
+
: ''
|
|
1347
|
+
}
|
|
1348
|
+
${retentionPhp}
|
|
1349
|
+
`;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
function buildFormHandlerPhp(name, formConfig, textDomain, locales) {
|
|
1353
|
+
const slug = safeFormSlug(name);
|
|
1354
|
+
const isMultilingual = locales.length > 1;
|
|
1355
|
+
const devFieldsPhp = devFieldsPhpArray(formConfig.fields, textDomain);
|
|
1356
|
+
const rawSeed = formConfig.clientFields?.enabled
|
|
1357
|
+
? formConfig.clientFields.seed
|
|
1358
|
+
: [];
|
|
1359
|
+
const seedPhp = isMultilingual
|
|
1360
|
+
? seedByLocalePhpArray(rawSeed, locales)
|
|
1361
|
+
: seedFieldsPhpArray(rawSeed);
|
|
1362
|
+
const storeSubmissions = formConfig.storeSubmissions !== false;
|
|
1363
|
+
|
|
1364
|
+
let mailToPhp;
|
|
1365
|
+
if (formConfig.mailTo === 'admin') {
|
|
1366
|
+
mailToPhp = `get_option('admin_email')`;
|
|
1367
|
+
} else if (
|
|
1368
|
+
typeof formConfig.mailTo === 'string' &&
|
|
1369
|
+
formConfig.mailTo.startsWith('option:')
|
|
1370
|
+
) {
|
|
1371
|
+
mailToPhp = `get_option(${phpString(formConfig.mailTo.slice('option:'.length))})`;
|
|
1372
|
+
} else {
|
|
1373
|
+
mailToPhp = phpString(formConfig.mailTo || 'admin_email');
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
const subjectTemplate = formConfig.subject || `New submission — ${name}`;
|
|
1377
|
+
const notificationBodyTemplate = formConfig.notificationBody || '';
|
|
1378
|
+
const successMessage = formConfig.successMessage || 'Your submission was received.';
|
|
1379
|
+
const confirmationPhp = formConfig.confirmation?.enabled
|
|
1380
|
+
? `
|
|
1381
|
+
$confirmation_to = $values[${phpString(formConfig.confirmation.emailField)}];
|
|
1382
|
+
$confirmation_subject = forgewp_forms_strip_header_injection(forgewp_forms_interpolate_template(isset($form_settings['confirmationSubject']) ? $form_settings['confirmationSubject'] : ${phpString(formConfig.confirmation.subject)}, $values));
|
|
1383
|
+
$confirmation_body = forgewp_forms_interpolate_template(isset($form_settings['confirmationBody']) ? $form_settings['confirmationBody'] : ${phpString(formConfig.confirmation.body)}, $values);
|
|
1384
|
+
if (is_email($confirmation_to)) {
|
|
1385
|
+
$confirmation_sent = wp_mail($confirmation_to, $confirmation_subject, $confirmation_body, array());
|
|
1386
|
+
if (!$confirmation_sent) {
|
|
1387
|
+
error_log('[ForgeWP Forms] Submitter confirmation email failed (form: ${name}).');
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
`
|
|
1391
|
+
: '';
|
|
1392
|
+
|
|
1393
|
+
const emailFieldName = Object.entries(formConfig.fields || {}).find(
|
|
1394
|
+
([, f]) => f.type === 'email',
|
|
1395
|
+
)?.[0];
|
|
1396
|
+
|
|
1397
|
+
return `
|
|
1398
|
+
if (!function_exists('forgewp_handle_form_${slug}')) {
|
|
1399
|
+
function forgewp_handle_form_${slug}(WP_REST_Request $request) {
|
|
1400
|
+
if (!forgewp_forms_rate_limit_ok()) {
|
|
1401
|
+
return new WP_REST_Response(array(
|
|
1402
|
+
'ok' => false,
|
|
1403
|
+
'message' => __('Too many submissions. Please try again later.', '${textDomain}'),
|
|
1404
|
+
), 429);
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
if (is_user_logged_in()) {
|
|
1408
|
+
$nonce = $request->get_header('X-WP-Nonce');
|
|
1409
|
+
if (!$nonce || !wp_verify_nonce($nonce, 'wp_rest')) {
|
|
1410
|
+
return new WP_REST_Response(array(
|
|
1411
|
+
'ok' => false,
|
|
1412
|
+
'message' => __('Security check failed. Please refresh and try again.', '${textDomain}'),
|
|
1413
|
+
), 403);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
$params = $request->get_params();
|
|
1418
|
+
|
|
1419
|
+
// Honeypot + time-trap: fail silently with an ok-shaped response so
|
|
1420
|
+
// spam bots never learn their submission was rejected.
|
|
1421
|
+
if (!empty($params['_forgewp_hp'])) {
|
|
1422
|
+
return new WP_REST_Response(array('ok' => true, 'message' => __('Thank you.', '${textDomain}')), 200);
|
|
1423
|
+
}
|
|
1424
|
+
$elapsed = isset($params['_forgewp_elapsed']) ? (int) $params['_forgewp_elapsed'] : 0;
|
|
1425
|
+
if ($elapsed < 3000) {
|
|
1426
|
+
return new WP_REST_Response(array('ok' => true, 'message' => __('Thank you.', '${textDomain}')), 200);
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
$dev_fields = ${devFieldsPhp};
|
|
1430
|
+
$seed_fields = ${seedPhp};
|
|
1431
|
+
$submitted_lang = isset($params['lang']) ? sanitize_key($params['lang']) : null;
|
|
1432
|
+
$client_fields = forgewp_forms_get_client_fields('${name}', $seed_fields, $submitted_lang);
|
|
1433
|
+
$field_defs = array_merge($dev_fields, is_array($client_fields) ? $client_fields : array());
|
|
1434
|
+
|
|
1435
|
+
$result = forgewp_forms_validate_and_sanitize($params, $field_defs);
|
|
1436
|
+
if (!empty($result['errors'])) {
|
|
1437
|
+
return new WP_REST_Response(array(
|
|
1438
|
+
'ok' => false,
|
|
1439
|
+
'errors' => $result['errors'],
|
|
1440
|
+
'message' => __('Please correct the errors below.', '${textDomain}'),
|
|
1441
|
+
), 400);
|
|
1442
|
+
}
|
|
1443
|
+
$values = $result['values'];
|
|
1444
|
+
$form_settings = get_option('forgewp_form_settings_${name}', array());
|
|
1445
|
+
if (!is_array($form_settings)) {
|
|
1446
|
+
$form_settings = array();
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
$stored = false;
|
|
1450
|
+
${storeSubmissions ? ` $stored = forgewp_store_submission('${name}', $values, $field_defs, forgewp_forms_resolve_lang($submitted_lang), ${phpString(formConfig.submissionTitle || '')});\n` : ''}
|
|
1451
|
+
$to = ${mailToPhp};
|
|
1452
|
+
$subject_template = isset($form_settings['notificationSubject']) ? $form_settings['notificationSubject'] : ${phpString(subjectTemplate)};
|
|
1453
|
+
$subject = forgewp_forms_strip_header_injection(forgewp_forms_interpolate_template($subject_template, $values));
|
|
1454
|
+
|
|
1455
|
+
$body_lines = array();
|
|
1456
|
+
foreach ($field_defs as $field_def) {
|
|
1457
|
+
$fname = $field_def['name'];
|
|
1458
|
+
if (!isset($values[$fname]) || $values[$fname] === '') {
|
|
1459
|
+
continue;
|
|
1460
|
+
}
|
|
1461
|
+
$body_lines[] = $field_def['label'] . ': ' . $values[$fname];
|
|
1462
|
+
}
|
|
1463
|
+
$default_body = implode("\\n", $body_lines);
|
|
1464
|
+
$body_template = isset($form_settings['notificationBody']) ? $form_settings['notificationBody'] : ${phpString(notificationBodyTemplate)};
|
|
1465
|
+
$body = trim($body_template) !== ''
|
|
1466
|
+
? forgewp_forms_interpolate_template($body_template, $values)
|
|
1467
|
+
: $default_body;
|
|
1468
|
+
|
|
1469
|
+
$headers = array();
|
|
1470
|
+
${emailFieldName ? ` if (!empty($values[${phpString(emailFieldName)}])) {\n $headers[] = 'Reply-To: ' . forgewp_forms_strip_header_injection($values[${phpString(emailFieldName)}]);\n }\n` : ''}
|
|
1471
|
+
$mail_sent = wp_mail($to, $subject, $body, $headers);
|
|
1472
|
+
${confirmationPhp}
|
|
1473
|
+
|
|
1474
|
+
if (!$mail_sent && !$stored) {
|
|
1475
|
+
return new WP_REST_Response(array(
|
|
1476
|
+
'ok' => false,
|
|
1477
|
+
'message' => __('Something went wrong. Please try again later.', '${textDomain}'),
|
|
1478
|
+
), 500);
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
if (!$mail_sent && $stored) {
|
|
1482
|
+
error_log('[ForgeWP Forms] Submission was stored but its notification email failed (form: ${name}, submission: ' . (int) $stored . ').');
|
|
1483
|
+
return new WP_REST_Response(array(
|
|
1484
|
+
'ok' => true,
|
|
1485
|
+
'message' => isset($form_settings['successMessage']) && $form_settings['successMessage'] !== ''
|
|
1486
|
+
? $form_settings['successMessage']
|
|
1487
|
+
: ${phpString(successMessage)},
|
|
1488
|
+
), 200);
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
${
|
|
1492
|
+
storeSubmissions
|
|
1493
|
+
? ` if ($mail_sent && !$stored) {
|
|
1494
|
+
error_log('[ForgeWP Forms] Notification email was sent but the submission could not be stored (form: ${name}).');
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
`
|
|
1498
|
+
: ''
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
return new WP_REST_Response(array(
|
|
1502
|
+
'ok' => true,
|
|
1503
|
+
'message' => isset($form_settings['successMessage']) && $form_settings['successMessage'] !== ''
|
|
1504
|
+
? $form_settings['successMessage']
|
|
1505
|
+
: ${phpString(successMessage)},
|
|
1506
|
+
), 200);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
if (!function_exists('forgewp_seed_form_fields_${slug}')) {
|
|
1511
|
+
function forgewp_seed_form_fields_${slug}() {
|
|
1512
|
+
$option_name = 'forgewp_form_fields_${name}';
|
|
1513
|
+
if (get_option($option_name, null) === null) {
|
|
1514
|
+
update_option($option_name, ${seedPhp});
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
// after_switch_theme only fires on activation — it never re-runs when an
|
|
1518
|
+
// already-active theme's files are simply redeployed (e.g. a file sync
|
|
1519
|
+
// to a live site), so the seed would silently never apply there. init
|
|
1520
|
+
// is a cheap self-healing fallback: get_option() is cached, and the
|
|
1521
|
+
// is-null guard above means it only ever writes once regardless of how
|
|
1522
|
+
// many times either hook fires.
|
|
1523
|
+
add_action('after_switch_theme', 'forgewp_seed_form_fields_${slug}');
|
|
1524
|
+
add_action('init', 'forgewp_seed_form_fields_${slug}');
|
|
1525
|
+
}
|
|
1526
|
+
`;
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
/**
|
|
1530
|
+
* Admin "Forms" page: one field-editor table per form with clientFields
|
|
1531
|
+
* enabled. Add/remove/move-up/move-down rows via inline vanilla JS,
|
|
1532
|
+
* serialized to a hidden JSON field on submit. No drag-and-drop library —
|
|
1533
|
+
* keeps this self-contained and keyboard-accessible. When the theme has
|
|
1534
|
+
* more than one configured locale, each form gets a language-tab switcher
|
|
1535
|
+
* and edits/saves one language's field set at a time.
|
|
1536
|
+
*/
|
|
1537
|
+
function humanizeFormName(name) {
|
|
1538
|
+
return name
|
|
1539
|
+
.split('-')
|
|
1540
|
+
.filter(Boolean)
|
|
1541
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
1542
|
+
.join(' ');
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
function buildFormsAdminPagePhp(forms, textDomain, locales, adminCapability) {
|
|
1546
|
+
const editableForms = Object.entries(forms).filter(
|
|
1547
|
+
([, f]) => f.clientFields?.enabled,
|
|
1548
|
+
);
|
|
1549
|
+
if (editableForms.length === 0) return '';
|
|
1550
|
+
|
|
1551
|
+
const isMultilingual = locales.length > 1;
|
|
1552
|
+
const nonceAction = 'forgewp_forms_admin_save';
|
|
1553
|
+
const pageSlug = 'forgewp-forms';
|
|
1554
|
+
|
|
1555
|
+
const formSectionsPhp = editableForms
|
|
1556
|
+
.map(([name, formConfig]) => {
|
|
1557
|
+
const rawSeed = formConfig.clientFields?.enabled
|
|
1558
|
+
? formConfig.clientFields.seed
|
|
1559
|
+
: [];
|
|
1560
|
+
const displayName = humanizeFormName(name);
|
|
1561
|
+
const seedPhp = isMultilingual
|
|
1562
|
+
? seedByLocalePhpArray(rawSeed, locales)
|
|
1563
|
+
: seedFieldsPhpArray(rawSeed);
|
|
1564
|
+
// Must go through forgewp_forms_get_client_fields (not a raw get_option)
|
|
1565
|
+
// so the admin table always shows at least the seed data even if the
|
|
1566
|
+
// option row hasn't been written yet for any reason — the same
|
|
1567
|
+
// fallback the REST handler and hydration payload already rely on.
|
|
1568
|
+
const initialJsonPhp = isMultilingual
|
|
1569
|
+
? `<?php
|
|
1570
|
+
$forgewp_seed_${safeFormSlug(name)} = ${seedPhp};
|
|
1571
|
+
$forgewp_initial_${safeFormSlug(name)} = array();
|
|
1572
|
+
foreach (array(${locales.map((l) => phpString(l)).join(', ')}) as $forgewp_lang) {
|
|
1573
|
+
$forgewp_initial_${safeFormSlug(name)}[$forgewp_lang] = forgewp_forms_get_client_fields( '${name}', $forgewp_seed_${safeFormSlug(name)}, $forgewp_lang );
|
|
1574
|
+
}
|
|
1575
|
+
echo esc_attr( wp_json_encode( $forgewp_initial_${safeFormSlug(name)} ) );
|
|
1576
|
+
?>`
|
|
1577
|
+
: `<?php echo esc_attr( wp_json_encode( forgewp_forms_get_client_fields( '${name}', ${seedPhp} ) ) ); ?>`;
|
|
1578
|
+
|
|
1579
|
+
const langTabsPhp = isMultilingual
|
|
1580
|
+
? `
|
|
1581
|
+
<div class="forgewp-forms-lang-tabs" style="margin-bottom:10px">
|
|
1582
|
+
${locales.map((l, i) => ` <button type="button" class="button forgewp-lang-tab${i === 0 ? ' active' : ''}" data-lang="${l}" aria-pressed="${i === 0 ? 'true' : 'false'}">${l.toUpperCase()}</button>`).join('\n')}
|
|
1583
|
+
</div>`
|
|
1584
|
+
: '';
|
|
1585
|
+
|
|
1586
|
+
const developerFields = Object.entries(formConfig.fields || {})
|
|
1587
|
+
.map(([fieldName, field]) => {
|
|
1588
|
+
const label = field.label || fieldName.replace(/[_-]/g, ' ');
|
|
1589
|
+
const fieldType = field.type || 'text';
|
|
1590
|
+
const requiredLabel = field.required ? 'Required' : 'Optional';
|
|
1591
|
+
return ` <li class="forgewp-dev-field"><label class="forgewp-field-control"><span><?php esc_html_e( 'Displayed label', '${textDomain}' ); ?></span><input type="text" form="forgewp-settings-${name}" name="forgewp_field_labels[${fieldName}]" value="<?php echo esc_attr( isset($forgewp_settings_${safeFormSlug(name)}['fieldLabels'][${phpString(fieldName)}]) ? $forgewp_settings_${safeFormSlug(name)}['fieldLabels'][${phpString(fieldName)}] : ${phpString(label)} ); ?>" /></label><span class="forgewp-dev-field-meta"><code><?php echo esc_html( ${phpString(fieldName)} ); ?></code><br /><?php echo esc_html( ${phpString(fieldType)} ); ?> · <?php echo esc_html( ${phpString(requiredLabel)} ); ?></span></li>`;
|
|
1592
|
+
})
|
|
1593
|
+
.join('\n');
|
|
1594
|
+
const storageStatus =
|
|
1595
|
+
formConfig.storeSubmissions === false
|
|
1596
|
+
? `<?php esc_html_e( 'Email delivery only', '${textDomain}' ); ?>`
|
|
1597
|
+
: `<?php esc_html_e( 'Submissions saved in WordPress', '${textDomain}' ); ?>`;
|
|
1598
|
+
const confirmationSettings = formConfig.confirmation?.enabled
|
|
1599
|
+
? `
|
|
1600
|
+
<label class="forgewp-message-control">
|
|
1601
|
+
<span><?php esc_html_e( 'Receipt email subject', '${textDomain}' ); ?></span>
|
|
1602
|
+
<input type="text" name="forgewp_confirmation_subject" value="<?php echo esc_attr( isset($forgewp_settings_${safeFormSlug(name)}['confirmationSubject']) ? $forgewp_settings_${safeFormSlug(name)}['confirmationSubject'] : ${phpString(formConfig.confirmation.subject)} ); ?>" />
|
|
1603
|
+
</label>
|
|
1604
|
+
<label class="forgewp-message-control forgewp-message-control--wide">
|
|
1605
|
+
<span><?php esc_html_e( 'Receipt email message', '${textDomain}' ); ?></span>
|
|
1606
|
+
<textarea name="forgewp_confirmation_body" rows="8"><?php echo esc_textarea( isset($forgewp_settings_${safeFormSlug(name)}['confirmationBody']) ? $forgewp_settings_${safeFormSlug(name)}['confirmationBody'] : ${phpString(formConfig.confirmation.body)} ); ?></textarea>
|
|
1607
|
+
<small><?php esc_html_e( 'Plain text only. Use {field_name} for submitted values.', '${textDomain}' ); ?></small>
|
|
1608
|
+
</label>`
|
|
1609
|
+
: '';
|
|
1610
|
+
const settingsSection = `
|
|
1611
|
+
<section class="forgewp-form-settings">
|
|
1612
|
+
<h3><?php esc_html_e( 'Form messages and labels', '${textDomain}' ); ?></h3>
|
|
1613
|
+
<p><?php esc_html_e( 'Edit visitor-facing copy and email text. Field keys, validation, and delivery addresses stay managed by the theme.', '${textDomain}' ); ?></p>
|
|
1614
|
+
<?php
|
|
1615
|
+
$forgewp_mail_keys = array(${Object.keys(formConfig.fields || {}).map(phpString).join(', ')});
|
|
1616
|
+
foreach (array(${(isMultilingual ? locales : [null]).map((locale) => locale === null ? 'null' : phpString(locale)).join(', ')}) as $forgewp_mail_lang) {
|
|
1617
|
+
foreach (forgewp_forms_get_client_fields(${phpString(name)}, ${seedPhp}, $forgewp_mail_lang) as $forgewp_mail_field) {
|
|
1618
|
+
if (isset($forgewp_mail_field['name'])) { $forgewp_mail_keys[] = $forgewp_mail_field['name']; }
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
?>
|
|
1622
|
+
<p><?php esc_html_e( 'Notification placeholders (case-sensitive):', '${textDomain}' ); ?> <code><?php echo esc_html('{' . implode('}, {', array_unique($forgewp_mail_keys)) . '}'); ?></code></p>
|
|
1623
|
+
${formConfig.confirmation?.enabled ? ` <p><?php esc_html_e( 'Receipt placeholders (developer-owned fields only):', '${textDomain}' ); ?> <code><?php echo esc_html(${phpString(Object.keys(formConfig.fields || {}).map((key) => `{${key}}`).join(', '))}); ?></code></p>` : ''}
|
|
1624
|
+
<form id="forgewp-settings-${name}" method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>">
|
|
1625
|
+
<input type="hidden" name="action" value="forgewp_forms_save_settings" />
|
|
1626
|
+
<input type="hidden" name="forgewp_form" value="${name}" />
|
|
1627
|
+
<?php wp_nonce_field('forgewp_forms_save_settings'); ?>
|
|
1628
|
+
<label class="forgewp-message-control forgewp-message-control--wide">
|
|
1629
|
+
<span><?php esc_html_e( 'Success message', '${textDomain}' ); ?></span>
|
|
1630
|
+
<textarea name="forgewp_success_message" rows="3"><?php echo esc_textarea( isset($forgewp_settings_${safeFormSlug(name)}['successMessage']) ? $forgewp_settings_${safeFormSlug(name)}['successMessage'] : ${phpString(formConfig.successMessage || 'Your submission was received.')} ); ?></textarea>
|
|
1631
|
+
</label>
|
|
1632
|
+
<label class="forgewp-message-control">
|
|
1633
|
+
<span><?php esc_html_e( 'Notification email subject', '${textDomain}' ); ?></span>
|
|
1634
|
+
<input type="text" name="forgewp_notification_subject" value="<?php echo esc_attr( isset($forgewp_settings_${safeFormSlug(name)}['notificationSubject']) ? $forgewp_settings_${safeFormSlug(name)}['notificationSubject'] : ${phpString(formConfig.subject || `New submission — ${name}`)} ); ?>" />
|
|
1635
|
+
</label>
|
|
1636
|
+
<label class="forgewp-message-control forgewp-message-control--wide">
|
|
1637
|
+
<span><?php esc_html_e( 'Notification email message', '${textDomain}' ); ?></span>
|
|
1638
|
+
<textarea name="forgewp_notification_body" rows="6"><?php echo esc_textarea( isset($forgewp_settings_${safeFormSlug(name)}['notificationBody']) ? $forgewp_settings_${safeFormSlug(name)}['notificationBody'] : ${phpString(formConfig.notificationBody || '')} ); ?></textarea>
|
|
1639
|
+
<small><?php esc_html_e( 'Leave blank to send the submitted fields as a list. Plain text only; use {field_name} for values.', '${textDomain}' ); ?></small>
|
|
1640
|
+
</label>
|
|
1641
|
+
${confirmationSettings}
|
|
1642
|
+
<?php submit_button( __('Save labels and messages', '${textDomain}') ); ?>
|
|
1643
|
+
</form>
|
|
1644
|
+
</section>`;
|
|
1645
|
+
|
|
1646
|
+
return `
|
|
1647
|
+
<?php $forgewp_settings_${safeFormSlug(name)} = get_option( 'forgewp_form_settings_${name}', array() ); if (!is_array($forgewp_settings_${safeFormSlug(name)})) { $forgewp_settings_${safeFormSlug(name)} = array(); } ?>
|
|
1648
|
+
<?php if ($active_form === '${name}') : ?>
|
|
1649
|
+
<section class="forgewp-form-panel" aria-labelledby="forgewp-form-title-${name}">
|
|
1650
|
+
<header class="forgewp-form-panel-header">
|
|
1651
|
+
<div>
|
|
1652
|
+
<p class="forgewp-form-eyebrow"><?php esc_html_e( 'Native form', '${textDomain}' ); ?></p>
|
|
1653
|
+
<h2 id="forgewp-form-title-${name}"><?php esc_html_e( '${displayName}', '${textDomain}' ); ?></h2>
|
|
1654
|
+
</div>
|
|
1655
|
+
<span class="forgewp-form-storage-status">${storageStatus}</span>
|
|
1656
|
+
</header>
|
|
1657
|
+
<details class="forgewp-dev-fields">
|
|
1658
|
+
<summary><?php esc_html_e( 'Core fields', '${textDomain}' ); ?> <span><?php echo (int) ${Object.keys(formConfig.fields || {}).length}; ?> · <?php esc_html_e( 'fixed keys and validation', '${textDomain}' ); ?></span></summary>
|
|
1659
|
+
<ul>${developerFields}</ul>
|
|
1660
|
+
</details>
|
|
1661
|
+
<div class="forgewp-forms-editor" data-form="${name}" data-multilingual="${isMultilingual ? 'true' : 'false'}" data-initial="${initialJsonPhp}">
|
|
1662
|
+
<div class="forgewp-client-fields-heading">
|
|
1663
|
+
<div>
|
|
1664
|
+
<h3><?php esc_html_e( 'Client-managed fields', '${textDomain}' ); ?></h3>
|
|
1665
|
+
<p><?php esc_html_e( 'These labels, types, and options can be changed without editing the theme code.', '${textDomain}' ); ?></p>
|
|
1666
|
+
</div>
|
|
1667
|
+
${langTabsPhp}
|
|
1668
|
+
</div>
|
|
1669
|
+
<div class="forgewp-forms-rows" role="list" aria-label="<?php esc_attr_e( 'Client-managed form fields', '${textDomain}' ); ?>"></div>
|
|
1670
|
+
<div class="forgewp-form-actions">
|
|
1671
|
+
<button type="button" class="button forgewp-forms-add-row"><?php esc_html_e( 'Add field', '${textDomain}' ); ?></button>
|
|
1672
|
+
<button type="button" class="button button-primary forgewp-forms-save"><?php esc_html_e( 'Save changes', '${textDomain}' ); ?></button>
|
|
1673
|
+
</div>
|
|
1674
|
+
<div class="forgewp-forms-notice" style="display:none"></div>
|
|
1675
|
+
</div>
|
|
1676
|
+
${settingsSection}
|
|
1677
|
+
</section>
|
|
1678
|
+
<?php endif; ?>
|
|
1679
|
+
`;
|
|
1680
|
+
})
|
|
1681
|
+
.join('\n');
|
|
1682
|
+
|
|
1683
|
+
const formIndexLinksPhp = editableForms
|
|
1684
|
+
.map(([name, formConfig]) => {
|
|
1685
|
+
const displayName = humanizeFormName(name);
|
|
1686
|
+
const storageStatus =
|
|
1687
|
+
formConfig.storeSubmissions === false
|
|
1688
|
+
? `<?php esc_html_e( 'Email delivery only', '${textDomain}' ); ?>`
|
|
1689
|
+
: `<?php esc_html_e( 'Submissions saved in WordPress', '${textDomain}' ); ?>`;
|
|
1690
|
+
return `
|
|
1691
|
+
<a class="forgewp-form-index-card" href="<?php echo esc_url( admin_url( 'admin.php?page=forgewp-form-${name}' ) ); ?>">
|
|
1692
|
+
<span>
|
|
1693
|
+
<strong><?php esc_html_e( '${displayName}', '${textDomain}' ); ?></strong>
|
|
1694
|
+
<small>${storageStatus}</small>
|
|
1695
|
+
</span>
|
|
1696
|
+
<span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
|
|
1697
|
+
</a>`;
|
|
1698
|
+
})
|
|
1699
|
+
.join('\n');
|
|
1700
|
+
|
|
1701
|
+
return `
|
|
1702
|
+
if (!function_exists('forgewp_forms_admin_menu')) {
|
|
1703
|
+
function forgewp_forms_admin_menu() {
|
|
1704
|
+
add_menu_page(
|
|
1705
|
+
__('Forms', '${textDomain}'),
|
|
1706
|
+
__('Forms', '${textDomain}'),
|
|
1707
|
+
${phpString(adminCapability)},
|
|
1708
|
+
'${pageSlug}',
|
|
1709
|
+
'forgewp_render_forms_admin_page',
|
|
1710
|
+
'dashicons-feedback',
|
|
1711
|
+
30
|
|
1712
|
+
);
|
|
1713
|
+
${editableForms
|
|
1714
|
+
.map(([name]) => {
|
|
1715
|
+
const displayName = humanizeFormName(name);
|
|
1716
|
+
return ` add_submenu_page(
|
|
1717
|
+
'${pageSlug}',
|
|
1718
|
+
__('${displayName}', '${textDomain}'),
|
|
1719
|
+
__('${displayName}', '${textDomain}'),
|
|
1720
|
+
${phpString(adminCapability)},
|
|
1721
|
+
'forgewp-form-${name}',
|
|
1722
|
+
'forgewp_render_forms_admin_page'
|
|
1723
|
+
);`;
|
|
1724
|
+
})
|
|
1725
|
+
.join('\n')}
|
|
1726
|
+
}
|
|
1727
|
+
add_action('admin_menu', 'forgewp_forms_admin_menu');
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
if (!function_exists('forgewp_forms_valid_field_shape')) {
|
|
1731
|
+
function forgewp_forms_valid_field_shape($field, $existing_names) {
|
|
1732
|
+
$valid_types = array('text', 'email', 'tel', 'number', 'textarea', 'select', 'checkbox');
|
|
1733
|
+
if (!is_array($field) || empty($field['label']) || !isset($field['type']) || !in_array($field['type'], $valid_types, true)) {
|
|
1734
|
+
return false;
|
|
1735
|
+
}
|
|
1736
|
+
if (isset($field['name']) && in_array($field['name'], $existing_names, true)) {
|
|
1737
|
+
// Name collides with a dev-owned field — reject.
|
|
1738
|
+
return false;
|
|
1739
|
+
}
|
|
1740
|
+
return true;
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
if (!function_exists('forgewp_forms_admin_save_handler')) {
|
|
1745
|
+
function forgewp_forms_admin_save_handler() {
|
|
1746
|
+
if (!current_user_can(${phpString(adminCapability)})) {
|
|
1747
|
+
wp_send_json_error(__('Unauthorized', '${textDomain}'), 403);
|
|
1748
|
+
}
|
|
1749
|
+
check_ajax_referer('${nonceAction}', 'nonce');
|
|
1750
|
+
|
|
1751
|
+
$form_name = isset($_POST['form']) ? sanitize_key($_POST['form']) : '';
|
|
1752
|
+
$known_forms = array(${editableForms.map(([n]) => phpString(n)).join(', ')});
|
|
1753
|
+
if (!in_array($form_name, $known_forms, true)) {
|
|
1754
|
+
wp_send_json_error(__('Unknown form.', '${textDomain}'), 400);
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
$lang = isset($_POST['lang']) ? sanitize_key($_POST['lang']) : null;
|
|
1758
|
+
$known_langs = array(${locales.map((l) => phpString(l)).join(', ')});
|
|
1759
|
+
$is_multilingual = ${isMultilingual ? 'true' : 'false'};
|
|
1760
|
+
if ($is_multilingual && !in_array($lang, $known_langs, true)) {
|
|
1761
|
+
wp_send_json_error(__('Unknown language.', '${textDomain}'), 400);
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
$raw = isset($_POST['fields']) ? wp_unslash($_POST['fields']) : '';
|
|
1765
|
+
$decoded = json_decode($raw, true);
|
|
1766
|
+
if (!is_array($decoded)) {
|
|
1767
|
+
wp_send_json_error(__('Invalid field data.', '${textDomain}'), 400);
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
$dev_field_names = apply_filters('forgewp_form_dev_field_names_' . $form_name, array());
|
|
1771
|
+
|
|
1772
|
+
$clean = array();
|
|
1773
|
+
$used_names = array();
|
|
1774
|
+
// Names dropped for colliding with a dev-owned field or an earlier
|
|
1775
|
+
// field in this same save — reported back to the admin UI instead
|
|
1776
|
+
// of failing silently, so a site owner isn't left wondering why the
|
|
1777
|
+
// field they just added never showed up after saving.
|
|
1778
|
+
$skipped_names = array();
|
|
1779
|
+
foreach ($decoded as $field) {
|
|
1780
|
+
if (!forgewp_forms_valid_field_shape($field, $dev_field_names)) {
|
|
1781
|
+
if (!empty($field['name'])) {
|
|
1782
|
+
$skipped_names[] = sanitize_key($field['name']);
|
|
1783
|
+
}
|
|
1784
|
+
continue;
|
|
1785
|
+
}
|
|
1786
|
+
$name = isset($field['name']) && $field['name'] !== ''
|
|
1787
|
+
? sanitize_key($field['name'])
|
|
1788
|
+
: sanitize_key($field['label']) . '_' . substr(md5($field['label'] . microtime()), 0, 6);
|
|
1789
|
+
if (in_array($name, $used_names, true) || in_array($name, $dev_field_names, true)) {
|
|
1790
|
+
$skipped_names[] = $name;
|
|
1791
|
+
continue;
|
|
1792
|
+
}
|
|
1793
|
+
$used_names[] = $name;
|
|
1794
|
+
|
|
1795
|
+
$options = array();
|
|
1796
|
+
if ($field['type'] === 'select' && !empty($field['options']) && is_array($field['options'])) {
|
|
1797
|
+
$options = array_values(array_filter(array_map(function ($o) {
|
|
1798
|
+
return sanitize_text_field(trim((string) $o));
|
|
1799
|
+
}, $field['options'])));
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
$clean[] = array(
|
|
1803
|
+
'name' => $name,
|
|
1804
|
+
'label' => sanitize_text_field($field['label']),
|
|
1805
|
+
'type' => $field['type'],
|
|
1806
|
+
'required' => !empty($field['required']),
|
|
1807
|
+
'maxLength' => $field['type'] === 'textarea' ? 5000 : 200,
|
|
1808
|
+
'options' => $options,
|
|
1809
|
+
'placeholder' => isset($field['placeholder']) ? sanitize_text_field($field['placeholder']) : '',
|
|
1810
|
+
);
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
$option_name = 'forgewp_form_fields_' . $form_name;
|
|
1814
|
+
if ($is_multilingual && !empty($lang)) {
|
|
1815
|
+
$stored = get_option($option_name, array());
|
|
1816
|
+
$stored_is_legacy_flat = is_array($stored) && isset($stored[0]) && is_array($stored[0]) && isset($stored[0]['name']);
|
|
1817
|
+
if (!is_array($stored) || $stored_is_legacy_flat) {
|
|
1818
|
+
// First per-language save — this language becomes
|
|
1819
|
+
// authoritative going forward; other languages keep
|
|
1820
|
+
// falling back to their seed until they're saved too.
|
|
1821
|
+
$stored = array();
|
|
1822
|
+
}
|
|
1823
|
+
$stored[$lang] = $clean;
|
|
1824
|
+
update_option($option_name, $stored);
|
|
1825
|
+
} else {
|
|
1826
|
+
update_option($option_name, $clean);
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
wp_send_json_success(array(
|
|
1830
|
+
'fields' => $clean,
|
|
1831
|
+
'skipped' => array_values(array_unique($skipped_names)),
|
|
1832
|
+
));
|
|
1833
|
+
}
|
|
1834
|
+
add_action('wp_ajax_forgewp_forms_admin_save', 'forgewp_forms_admin_save_handler');
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
if (!function_exists('forgewp_forms_admin_save_settings_handler')) {
|
|
1838
|
+
function forgewp_forms_admin_save_settings_handler() {
|
|
1839
|
+
if (!current_user_can(${phpString(adminCapability)})) {
|
|
1840
|
+
wp_die(__('You do not have permission to edit form settings.', '${textDomain}'));
|
|
1841
|
+
}
|
|
1842
|
+
check_admin_referer('forgewp_forms_save_settings');
|
|
1843
|
+
|
|
1844
|
+
$form_name = isset($_POST['forgewp_form']) ? sanitize_key(wp_unslash($_POST['forgewp_form'])) : '';
|
|
1845
|
+
$known_forms = array(${editableForms.map(([n]) => phpString(n)).join(', ')});
|
|
1846
|
+
if (!in_array($form_name, $known_forms, true)) {
|
|
1847
|
+
wp_die(__('Unknown form.', '${textDomain}'));
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
$form_defaults = array(
|
|
1851
|
+
${editableForms.map(([n, f]) => ` ${phpString(n)} => array(
|
|
1852
|
+
'successMessage' => ${phpString(f.successMessage || 'Your submission was received.')},
|
|
1853
|
+
'notificationSubject' => ${phpString(f.subject || `New submission — ${n}`)},
|
|
1854
|
+
${f.confirmation?.enabled ? ` 'confirmationSubject' => ${phpString(f.confirmation.subject)},
|
|
1855
|
+
'confirmationBody' => ${phpString(f.confirmation.body)},` : ''}
|
|
1856
|
+
),`).join('\n')}
|
|
1857
|
+
);
|
|
1858
|
+
$defaults = $form_defaults[$form_name];
|
|
1859
|
+
$field_keys = array(
|
|
1860
|
+
${editableForms.map(([n, f]) => ` ${phpString(n)} => array(${Object.keys(f.fields || {}).map(phpString).join(', ')}),`).join('\n')}
|
|
1861
|
+
);
|
|
1862
|
+
$raw_labels = isset($_POST['forgewp_field_labels']) && is_array($_POST['forgewp_field_labels'])
|
|
1863
|
+
? wp_unslash($_POST['forgewp_field_labels'])
|
|
1864
|
+
: array();
|
|
1865
|
+
$labels = array();
|
|
1866
|
+
foreach ($field_keys[$form_name] as $field_name) {
|
|
1867
|
+
if (isset($raw_labels[$field_name])) {
|
|
1868
|
+
$label = sanitize_text_field($raw_labels[$field_name]);
|
|
1869
|
+
if ($label !== '') {
|
|
1870
|
+
$labels[$field_name] = $label;
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
$success_message = sanitize_textarea_field(isset($_POST['forgewp_success_message']) ? wp_unslash($_POST['forgewp_success_message']) : '');
|
|
1876
|
+
if ($success_message === '') { $success_message = $defaults['successMessage']; }
|
|
1877
|
+
$notification_subject = sanitize_text_field(isset($_POST['forgewp_notification_subject']) ? wp_unslash($_POST['forgewp_notification_subject']) : '');
|
|
1878
|
+
if ($notification_subject === '') { $notification_subject = $defaults['notificationSubject']; }
|
|
1879
|
+
$settings = array(
|
|
1880
|
+
'fieldLabels' => $labels,
|
|
1881
|
+
'successMessage' => $success_message,
|
|
1882
|
+
'notificationSubject' => $notification_subject,
|
|
1883
|
+
'notificationBody' => sanitize_textarea_field(isset($_POST['forgewp_notification_body']) ? wp_unslash($_POST['forgewp_notification_body']) : ''),
|
|
1884
|
+
);
|
|
1885
|
+
$confirmation_forms = array(${editableForms.filter(([, f]) => f.confirmation?.enabled).map(([n]) => phpString(n)).join(', ')});
|
|
1886
|
+
if (in_array($form_name, $confirmation_forms, true)) {
|
|
1887
|
+
$confirmation_subject = sanitize_text_field(isset($_POST['forgewp_confirmation_subject']) ? wp_unslash($_POST['forgewp_confirmation_subject']) : '');
|
|
1888
|
+
$confirmation_body = sanitize_textarea_field(isset($_POST['forgewp_confirmation_body']) ? wp_unslash($_POST['forgewp_confirmation_body']) : '');
|
|
1889
|
+
$settings['confirmationSubject'] = $confirmation_subject !== '' ? $confirmation_subject : $defaults['confirmationSubject'];
|
|
1890
|
+
$settings['confirmationBody'] = $confirmation_body !== '' ? $confirmation_body : $defaults['confirmationBody'];
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
// Notification messages may use the currently saved client fields.
|
|
1894
|
+
// Receipt messages retain their developer-owned field contract.
|
|
1895
|
+
$notification_keys = $field_keys[$form_name];
|
|
1896
|
+
$client_seeds = array(
|
|
1897
|
+
${editableForms.map(([n, f]) => ` ${phpString(n)} => ${locales.length > 1 ? seedByLocalePhpArray(f.clientFields.seed || [], locales) : seedFieldsPhpArray(Array.isArray(f.clientFields.seed) ? f.clientFields.seed : [])},`).join('\n')}
|
|
1898
|
+
);
|
|
1899
|
+
foreach (array(${(locales.length > 1 ? locales : [null]).map((locale) => locale === null ? 'null' : phpString(locale)).join(', ')}) as $template_lang) {
|
|
1900
|
+
foreach (forgewp_forms_get_client_fields($form_name, $client_seeds[$form_name], $template_lang) as $client_field) {
|
|
1901
|
+
if (isset($client_field['name'])) { $notification_keys[] = $client_field['name']; }
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
foreach (array('notificationSubject', 'notificationBody', 'confirmationSubject', 'confirmationBody') as $setting_key) {
|
|
1905
|
+
if (!isset($settings[$setting_key])) { continue; }
|
|
1906
|
+
$allowed_keys = strpos($setting_key, 'confirmation') === 0 ? $field_keys[$form_name] : $notification_keys;
|
|
1907
|
+
preg_match_all('/\\{([a-zA-Z0-9_-]+)\\}/', $settings[$setting_key], $template_matches);
|
|
1908
|
+
$unknown_keys = array_diff($template_matches[1], $allowed_keys);
|
|
1909
|
+
if (!empty($unknown_keys)) {
|
|
1910
|
+
wp_die(esc_html(sprintf(
|
|
1911
|
+
__('Settings were not saved. Unknown email placeholders in %1$s: %2$s. Allowed field keys: %3$s. Placeholder names are case-sensitive. Go back to correct your message.', '${textDomain}'),
|
|
1912
|
+
$setting_key,
|
|
1913
|
+
implode(', ', array_unique($unknown_keys)),
|
|
1914
|
+
implode(', ', array_unique($allowed_keys))
|
|
1915
|
+
)), '', array('back_link' => true));
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
update_option('forgewp_form_settings_' . $form_name, $settings, false);
|
|
1920
|
+
wp_safe_redirect(add_query_arg(
|
|
1921
|
+
array(
|
|
1922
|
+
'page' => 'forgewp-form-' . $form_name,
|
|
1923
|
+
'forgewp-settings-saved' => '1',
|
|
1924
|
+
),
|
|
1925
|
+
admin_url('admin.php')
|
|
1926
|
+
));
|
|
1927
|
+
exit;
|
|
1928
|
+
}
|
|
1929
|
+
add_action('admin_post_forgewp_forms_save_settings', 'forgewp_forms_admin_save_settings_handler');
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
if (!function_exists('forgewp_render_forms_admin_page')) {
|
|
1933
|
+
function forgewp_render_forms_admin_page() {
|
|
1934
|
+
if (!current_user_can(${phpString(adminCapability)})) {
|
|
1935
|
+
wp_die(__('You do not have permission to access this page.', '${textDomain}'));
|
|
1936
|
+
}
|
|
1937
|
+
$current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '${pageSlug}';
|
|
1938
|
+
$active_form = $current_page === '${pageSlug}' ? '' : str_replace('forgewp-form-', '', $current_page);
|
|
1939
|
+
$known_forms = array(${editableForms.map(([name]) => phpString(name)).join(', ')});
|
|
1940
|
+
if ($active_form !== '' && !in_array($active_form, $known_forms, true)) {
|
|
1941
|
+
wp_die(__('Unknown form.', '${textDomain}'));
|
|
1942
|
+
}
|
|
1943
|
+
$nonce = wp_create_nonce('${nonceAction}');
|
|
1944
|
+
$ajax_url = admin_url('admin-ajax.php');
|
|
1945
|
+
?>
|
|
1946
|
+
<div class="wrap">
|
|
1947
|
+
<h1><?php echo $active_form === '' ? esc_html__('Forms', '${textDomain}') : esc_html( ucwords( str_replace( '-', ' ', $active_form ) ) ); ?></h1>
|
|
1948
|
+
<?php if (isset($_GET['forgewp-settings-saved'])) : ?><div class="notice notice-success is-dismissible"><p><?php esc_html_e('Form settings saved.', '${textDomain}'); ?></p></div><?php endif; ?>
|
|
1949
|
+
<?php if ($active_form === '') : ?>
|
|
1950
|
+
<p><?php esc_html_e('Choose a form to manage its labels, optional fields, and messages.', '${textDomain}'); ?></p>
|
|
1951
|
+
<div class="forgewp-form-index">${formIndexLinksPhp}
|
|
1952
|
+
</div>
|
|
1953
|
+
<?php else : ?>
|
|
1954
|
+
<p><?php esc_html_e('Core field keys and validation remain managed by the theme. You can change displayed labels, configure optional fields, and edit messages for this form.', '${textDomain}'); ?></p>
|
|
1955
|
+
${formSectionsPhp}
|
|
1956
|
+
<?php endif; ?>
|
|
1957
|
+
</div>
|
|
1958
|
+
<style>
|
|
1959
|
+
.forgewp-forms-lang-tabs .button.active { background: #2271b1; border-color: #2271b1; color: #fff; }
|
|
1960
|
+
.forgewp-form-panel { max-width: 1440px; margin: 20px 0 28px; border: 1px solid #c3c4c7; background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
|
|
1961
|
+
.forgewp-form-panel-header { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:20px 24px; border-bottom:1px solid #dcdcde; }
|
|
1962
|
+
.forgewp-form-panel-header h2 { margin:4px 0 0; font-size:20px; }
|
|
1963
|
+
.forgewp-form-eyebrow { margin:0; color:#646970; font-size:11px; font-weight:600; letter-spacing:.06em; text-transform:uppercase; }
|
|
1964
|
+
.forgewp-form-storage-status { display:inline-flex; align-items:center; min-height:30px; padding:0 10px; border-radius:16px; background:#edfaef; color:#176b2c; font-size:12px; font-weight:600; }
|
|
1965
|
+
.forgewp-dev-fields { padding:14px 24px; border-bottom:1px solid #dcdcde; background:#f6f7f7; }
|
|
1966
|
+
.forgewp-dev-fields summary { cursor:pointer; font-weight:600; }
|
|
1967
|
+
.forgewp-dev-fields summary span { margin-left:8px; color:#646970; font-size:12px; font-weight:400; }
|
|
1968
|
+
.forgewp-dev-fields ul { display:grid; gap:8px; margin:14px 0 0; }
|
|
1969
|
+
.forgewp-dev-field { display:flex; flex-wrap:wrap; justify-content:space-between; gap:8px 16px; padding:8px 10px; border:1px solid #dcdcde; background:#fff; }
|
|
1970
|
+
.forgewp-dev-field .forgewp-field-control { flex:1 1 240px; }
|
|
1971
|
+
.forgewp-dev-field code { margin-left:8px; color:#646970; }
|
|
1972
|
+
.forgewp-dev-field-meta { color:#646970; font-size:12px; }
|
|
1973
|
+
.forgewp-form-settings { max-width:none; padding:28px 32px 32px; border-top:1px solid #dcdcde; background:#f6f7f7; }
|
|
1974
|
+
.forgewp-form-settings h3 { margin:0; font-size:15px; }
|
|
1975
|
+
.forgewp-form-settings > p { color:#646970; }
|
|
1976
|
+
.forgewp-form-settings form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); column-gap:28px; align-items:start; }
|
|
1977
|
+
.forgewp-form-settings .forgewp-message-control { max-width:none; margin:16px 0; }
|
|
1978
|
+
.forgewp-form-settings .forgewp-message-control--wide { grid-column:1 / -1; }
|
|
1979
|
+
.forgewp-form-index { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr)); gap:12px; max-width:1100px; margin-top:20px; }
|
|
1980
|
+
.forgewp-form-index-card { display:flex; align-items:center; justify-content:space-between; gap:16px; min-height:76px; padding:16px 20px; border:1px solid #c3c4c7; background:#fff; color:#1d2327; text-decoration:none; }
|
|
1981
|
+
.forgewp-form-index-card:hover, .forgewp-form-index-card:focus { border-color:#2271b1; box-shadow:0 0 0 1px #2271b1; color:#135e96; }
|
|
1982
|
+
.forgewp-form-index-card strong, .forgewp-form-index-card small { display:block; }
|
|
1983
|
+
.forgewp-form-index-card small { margin-top:5px; color:#646970; }
|
|
1984
|
+
.forgewp-form-index-card > .dashicons { color:#646970; }
|
|
1985
|
+
.forgewp-message-control { display:grid; gap:6px; max-width:720px; margin:16px 0; color:#50575e; font-weight:600; }
|
|
1986
|
+
.forgewp-message-control input, .forgewp-message-control textarea { width:100%; max-width:100%; }
|
|
1987
|
+
.forgewp-message-control small { color:#646970; font-weight:400; }
|
|
1988
|
+
.forgewp-forms-editor { padding:20px 24px 24px; }
|
|
1989
|
+
.forgewp-client-fields-heading { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:16px; }
|
|
1990
|
+
.forgewp-client-fields-heading h3 { margin:0; font-size:15px; }
|
|
1991
|
+
.forgewp-client-fields-heading p { margin:4px 0 0; color:#646970; }
|
|
1992
|
+
.forgewp-forms-rows { display:grid; gap:12px; }
|
|
1993
|
+
.forgewp-forms-row { min-width:0; margin:0; padding:16px; border:1px solid #dcdcde; border-radius:4px; background:#fff; }
|
|
1994
|
+
.forgewp-forms-row legend { padding:0 6px; font-size:14px; font-weight:600; }
|
|
1995
|
+
.forgewp-forms-row-grid { display:grid; grid-template-columns:minmax(180px, 2fr) minmax(140px, 1fr); gap:12px; }
|
|
1996
|
+
.forgewp-field-control { display:grid; align-content:start; gap:5px; min-width:0; color:#50575e; font-size:12px; font-weight:600; }
|
|
1997
|
+
.forgewp-field-control input, .forgewp-field-control select { max-width:100%; }
|
|
1998
|
+
.forgewp-field-machine-name { margin-top:8px; color:#646970; font-size:12px; }
|
|
1999
|
+
.forgewp-field-machine-name code { user-select:all; }
|
|
2000
|
+
.forgewp-field-required-control { display:inline-flex; align-items:center; gap:8px; min-height:30px; color:#50575e; font-size:12px; font-weight:600; }
|
|
2001
|
+
.forgewp-field-actions, .forgewp-form-actions { display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin-top:14px; }
|
|
2002
|
+
.forgewp-field-error { margin:8px 0 0; color:#b32d2e; }
|
|
2003
|
+
.forgewp-forms-notice { max-width:100%; }
|
|
2004
|
+
.forgewp-field-options-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 6px; min-height: 22px; }
|
|
2005
|
+
.forgewp-field-option-chip { display: inline-flex; align-items: center; gap: 4px; background: #f0f0f1; border: 1px solid #dcdcde; border-radius: 4px; padding: 3px 4px 3px 10px; font-size: 12px; line-height: 1.4; }
|
|
2006
|
+
.forgewp-field-option-chip button { border: none; background: none; cursor: pointer; font-size: 14px; line-height: 1; color: #787c82; padding: 2px 4px; }
|
|
2007
|
+
.forgewp-field-option-chip button:hover { color: #b32d2e; }
|
|
2008
|
+
@media (max-width: 782px) {
|
|
2009
|
+
.forgewp-form-panel { max-width: none; }
|
|
2010
|
+
.forgewp-form-settings { padding:20px 16px 24px; }
|
|
2011
|
+
.forgewp-form-settings form { grid-template-columns:minmax(0,1fr); }
|
|
2012
|
+
.forgewp-form-settings .forgewp-message-control--wide { grid-column:auto; }
|
|
2013
|
+
}
|
|
2014
|
+
.forgewp-field-options-add { display: flex; gap: 6px; }
|
|
2015
|
+
.forgewp-field-options-add input { flex: 1; min-width: 0; }
|
|
2016
|
+
@media (max-width: 782px) { .forgewp-forms-row-grid { grid-template-columns:minmax(0, 1fr); } .forgewp-forms-row { padding:12px; } .forgewp-form-panel-header, .forgewp-client-fields-heading { flex-direction:column; } .forgewp-forms-editor, .forgewp-form-panel-header, .forgewp-dev-fields { padding-left:14px; padding-right:14px; } }
|
|
2017
|
+
</style>
|
|
2018
|
+
<script>
|
|
2019
|
+
(function () {
|
|
2020
|
+
var AJAX_URL = <?php echo wp_json_encode( $ajax_url ); ?>;
|
|
2021
|
+
var NONCE = <?php echo wp_json_encode( $nonce ); ?>;
|
|
2022
|
+
var exportFormSelect = document.getElementById('forgewp-export-form');
|
|
2023
|
+
if (exportFormSelect) {
|
|
2024
|
+
var exportFieldGroups = document.querySelectorAll('.forgewp-export-form-fields');
|
|
2025
|
+
function updateExportFieldGroups() {
|
|
2026
|
+
exportFieldGroups.forEach(function (group) {
|
|
2027
|
+
var hidden = exportFormSelect.value !== 'all' && group.dataset.exportForm !== exportFormSelect.value;
|
|
2028
|
+
group.hidden = hidden;
|
|
2029
|
+
if (hidden) {
|
|
2030
|
+
group.querySelectorAll('input[type="checkbox"]').forEach(function (checkbox) {
|
|
2031
|
+
checkbox.checked = false;
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
});
|
|
2035
|
+
}
|
|
2036
|
+
exportFormSelect.addEventListener('change', updateExportFieldGroups);
|
|
2037
|
+
updateExportFieldGroups();
|
|
2038
|
+
}
|
|
2039
|
+
var TYPE_LABELS = { text: 'Text', email: 'Email', tel: 'Phone', number: 'Number', textarea: 'Textarea', select: 'Select', checkbox: 'Checkbox' };
|
|
2040
|
+
var TYPES = ['text', 'email', 'tel', 'number', 'textarea', 'select', 'checkbox'];
|
|
2041
|
+
|
|
2042
|
+
function el(tag, attrs, children) {
|
|
2043
|
+
var node = document.createElement(tag);
|
|
2044
|
+
attrs = attrs || {};
|
|
2045
|
+
for (var key in attrs) {
|
|
2046
|
+
if (key === 'class') { node.className = attrs[key]; }
|
|
2047
|
+
else { node.setAttribute(key, attrs[key]); }
|
|
2048
|
+
}
|
|
2049
|
+
(children || []).forEach(function (child) {
|
|
2050
|
+
node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child);
|
|
2051
|
+
});
|
|
2052
|
+
return node;
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
function buildOptionsEditor(initialOptions) {
|
|
2056
|
+
var container = el('div', { 'class': 'forgewp-field-options' });
|
|
2057
|
+
var chips = el('div', { 'class': 'forgewp-field-options-chips' });
|
|
2058
|
+
var options = (initialOptions || []).slice();
|
|
2059
|
+
|
|
2060
|
+
function renderChips() {
|
|
2061
|
+
chips.innerHTML = '';
|
|
2062
|
+
options.forEach(function (opt, idx) {
|
|
2063
|
+
var removeBtn = el('button', { type: 'button', title: 'Remove option', 'aria-label': 'Remove option ' + opt }, ['\\u2715']);
|
|
2064
|
+
removeBtn.addEventListener('click', function () {
|
|
2065
|
+
options.splice(idx, 1);
|
|
2066
|
+
renderChips();
|
|
2067
|
+
});
|
|
2068
|
+
var chip = el('span', { 'class': 'forgewp-field-option-chip' }, [opt, removeBtn]);
|
|
2069
|
+
chips.appendChild(chip);
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
renderChips();
|
|
2073
|
+
|
|
2074
|
+
var addInput = el('input', { type: 'text', placeholder: 'Add option\\u2026' });
|
|
2075
|
+
var addBtn = el('button', { type: 'button', 'class': 'button' }, ['Add']);
|
|
2076
|
+
function commitAdd() {
|
|
2077
|
+
var val = addInput.value.trim();
|
|
2078
|
+
if (val && options.indexOf(val) === -1) {
|
|
2079
|
+
options.push(val);
|
|
2080
|
+
addInput.value = '';
|
|
2081
|
+
renderChips();
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
addBtn.addEventListener('click', commitAdd);
|
|
2085
|
+
addInput.addEventListener('keydown', function (e) {
|
|
2086
|
+
if (e.key === 'Enter') { e.preventDefault(); commitAdd(); }
|
|
2087
|
+
});
|
|
2088
|
+
|
|
2089
|
+
container.appendChild(chips);
|
|
2090
|
+
container.appendChild(el('div', { 'class': 'forgewp-field-options-add' }, [addInput, addBtn]));
|
|
2091
|
+
container.getOptions = function () { return options.slice(); };
|
|
2092
|
+
return container;
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
function buildRow(field) {
|
|
2096
|
+
field = field || { name: '', label: '', type: 'text', required: false, placeholder: '', options: [] };
|
|
2097
|
+
var card = el('fieldset', { 'class': 'forgewp-forms-row', role: 'listitem' });
|
|
2098
|
+
card.dataset.name = field.name || '';
|
|
2099
|
+
var legend = el('legend', {}, [field.label || 'New field']);
|
|
2100
|
+
card.appendChild(legend);
|
|
2101
|
+
|
|
2102
|
+
function control(label, input, className) {
|
|
2103
|
+
return el('label', { 'class': 'forgewp-field-control ' + (className || '') }, [
|
|
2104
|
+
el('span', {}, [label]),
|
|
2105
|
+
input,
|
|
2106
|
+
]);
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
function controlGroup(label, content, className) {
|
|
2110
|
+
return el('div', { 'class': 'forgewp-field-control ' + (className || '') }, [
|
|
2111
|
+
el('span', {}, [label]),
|
|
2112
|
+
content,
|
|
2113
|
+
]);
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
var labelInput = el('input', { type: 'text', value: field.label || '', 'class': 'regular-text forgewp-field-label', 'aria-label': 'Field label' });
|
|
2117
|
+
labelInput.addEventListener('input', function () {
|
|
2118
|
+
legend.textContent = labelInput.value || 'New field';
|
|
2119
|
+
});
|
|
2120
|
+
|
|
2121
|
+
var typeSelect = el('select', { 'class': 'forgewp-field-type' });
|
|
2122
|
+
TYPES.forEach(function (t) {
|
|
2123
|
+
var opt = el('option', { value: t }, [TYPE_LABELS[t]]);
|
|
2124
|
+
if (t === field.type) { opt.selected = true; }
|
|
2125
|
+
typeSelect.appendChild(opt);
|
|
2126
|
+
});
|
|
2127
|
+
|
|
2128
|
+
var requiredCheckbox = el('input', { type: 'checkbox', 'class': 'forgewp-field-required' });
|
|
2129
|
+
if (field.required) { requiredCheckbox.checked = true; }
|
|
2130
|
+
|
|
2131
|
+
var placeholderInput = el('input', { type: 'text', value: field.placeholder || '', 'class': 'regular-text forgewp-field-placeholder' });
|
|
2132
|
+
|
|
2133
|
+
var optionsEditor = buildOptionsEditor(field.options);
|
|
2134
|
+
optionsEditor.style.display = field.type === 'select' ? '' : 'none';
|
|
2135
|
+
|
|
2136
|
+
card.appendChild(el('div', { 'class': 'forgewp-forms-row-grid' }, [
|
|
2137
|
+
control('Label', labelInput),
|
|
2138
|
+
control('Field type', typeSelect),
|
|
2139
|
+
el('label', { 'class': 'forgewp-field-required-control' }, [requiredCheckbox, 'Required']),
|
|
2140
|
+
control('Placeholder', placeholderInput),
|
|
2141
|
+
controlGroup('Select options', optionsEditor, 'forgewp-field-options-control'),
|
|
2142
|
+
]));
|
|
2143
|
+
card.appendChild(el('div', { 'class': 'forgewp-field-machine-name' }, [
|
|
2144
|
+
'Field key: ',
|
|
2145
|
+
el('code', {}, [field.name || 'Assigned on first save']),
|
|
2146
|
+
]));
|
|
2147
|
+
|
|
2148
|
+
typeSelect.addEventListener('change', function () {
|
|
2149
|
+
optionsEditor.style.display = typeSelect.value === 'select' ? '' : 'none';
|
|
2150
|
+
});
|
|
2151
|
+
|
|
2152
|
+
var upBtn = el('button', { type: 'button', 'class': 'button', 'aria-label': 'Move field up' }, ['Move up']);
|
|
2153
|
+
var downBtn = el('button', { type: 'button', 'class': 'button', 'aria-label': 'Move field down' }, ['Move down']);
|
|
2154
|
+
var removeBtn = el('button', { type: 'button', 'class': 'button-link-delete', 'aria-label': 'Remove field' }, ['Remove']);
|
|
2155
|
+
upBtn.addEventListener('click', function () {
|
|
2156
|
+
var prev = card.previousElementSibling;
|
|
2157
|
+
if (prev) { card.parentNode.insertBefore(card, prev); }
|
|
2158
|
+
});
|
|
2159
|
+
downBtn.addEventListener('click', function () {
|
|
2160
|
+
var next = card.nextElementSibling;
|
|
2161
|
+
if (next) { card.parentNode.insertBefore(next, card); }
|
|
2162
|
+
});
|
|
2163
|
+
removeBtn.addEventListener('click', function () { card.remove(); });
|
|
2164
|
+
card.appendChild(el('div', { 'class': 'forgewp-field-actions' }, [upBtn, downBtn, removeBtn]));
|
|
2165
|
+
|
|
2166
|
+
var error = el('p', { 'class': 'forgewp-field-error', role: 'alert' });
|
|
2167
|
+
error.hidden = true;
|
|
2168
|
+
card.appendChild(error);
|
|
2169
|
+
|
|
2170
|
+
return card;
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
function readRow(row) {
|
|
2174
|
+
var optionsEditorEl = row.querySelector('.forgewp-field-options');
|
|
2175
|
+
return {
|
|
2176
|
+
name: row.dataset.name || '',
|
|
2177
|
+
label: row.querySelector('.forgewp-field-label').value,
|
|
2178
|
+
type: row.querySelector('.forgewp-field-type').value,
|
|
2179
|
+
required: row.querySelector('.forgewp-field-required').checked,
|
|
2180
|
+
placeholder: row.querySelector('.forgewp-field-placeholder').value,
|
|
2181
|
+
options: (optionsEditorEl && optionsEditorEl.getOptions) ? optionsEditorEl.getOptions() : [],
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
function showNotice(editorEl, success, message) {
|
|
2186
|
+
var noticeEl = editorEl.querySelector('.forgewp-forms-notice');
|
|
2187
|
+
noticeEl.innerHTML = '';
|
|
2188
|
+
noticeEl.className = 'forgewp-forms-notice notice ' + (success ? 'notice-success' : 'notice-error') + ' is-dismissible';
|
|
2189
|
+
noticeEl.style.display = 'block';
|
|
2190
|
+
noticeEl.style.marginTop = '12px';
|
|
2191
|
+
noticeEl.setAttribute('role', success ? 'status' : 'alert');
|
|
2192
|
+
noticeEl.setAttribute('aria-live', success ? 'polite' : 'assertive');
|
|
2193
|
+
|
|
2194
|
+
var p = document.createElement('p');
|
|
2195
|
+
p.textContent = (success ? '\\u2713 ' : '\\u26a0 ') + message;
|
|
2196
|
+
noticeEl.appendChild(p);
|
|
2197
|
+
|
|
2198
|
+
var dismissBtn = document.createElement('button');
|
|
2199
|
+
dismissBtn.type = 'button';
|
|
2200
|
+
dismissBtn.className = 'notice-dismiss';
|
|
2201
|
+
var srSpan = document.createElement('span');
|
|
2202
|
+
srSpan.className = 'screen-reader-text';
|
|
2203
|
+
srSpan.textContent = 'Dismiss this notice.';
|
|
2204
|
+
dismissBtn.appendChild(srSpan);
|
|
2205
|
+
dismissBtn.addEventListener('click', function () {
|
|
2206
|
+
noticeEl.style.display = 'none';
|
|
2207
|
+
});
|
|
2208
|
+
noticeEl.appendChild(dismissBtn);
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
var editors = document.querySelectorAll('.forgewp-forms-editor');
|
|
2212
|
+
editors.forEach(function (editorEl) {
|
|
2213
|
+
var isMultilingual = editorEl.dataset.multilingual === 'true';
|
|
2214
|
+
var tbody = editorEl.querySelector('.forgewp-forms-rows');
|
|
2215
|
+
var raw = {};
|
|
2216
|
+
try { raw = JSON.parse(editorEl.dataset.initial || (isMultilingual ? '{}' : '[]')); } catch (e) { raw = isMultilingual ? {} : []; }
|
|
2217
|
+
|
|
2218
|
+
var dataByLang = isMultilingual ? raw : { '_': Array.isArray(raw) ? raw : [] };
|
|
2219
|
+
var currentLang = '_';
|
|
2220
|
+
if (isMultilingual) {
|
|
2221
|
+
var activeTab = editorEl.querySelector('.forgewp-lang-tab.active');
|
|
2222
|
+
currentLang = activeTab ? activeTab.dataset.lang : Object.keys(dataByLang)[0];
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
function renderLang(lang) {
|
|
2226
|
+
tbody.innerHTML = '';
|
|
2227
|
+
(dataByLang[lang] || []).forEach(function (field) { tbody.appendChild(buildRow(field)); });
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
function captureCurrentRows() {
|
|
2231
|
+
var fields = [];
|
|
2232
|
+
tbody.querySelectorAll('.forgewp-forms-row').forEach(function (row) {
|
|
2233
|
+
fields.push(readRow(row));
|
|
2234
|
+
});
|
|
2235
|
+
return fields;
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
renderLang(currentLang);
|
|
2239
|
+
|
|
2240
|
+
if (isMultilingual) {
|
|
2241
|
+
editorEl.querySelectorAll('.forgewp-lang-tab').forEach(function (tabBtn) {
|
|
2242
|
+
tabBtn.addEventListener('click', function () {
|
|
2243
|
+
if (tabBtn.dataset.lang === currentLang) { return; }
|
|
2244
|
+
dataByLang[currentLang] = captureCurrentRows();
|
|
2245
|
+
editorEl.querySelectorAll('.forgewp-lang-tab').forEach(function (b) {
|
|
2246
|
+
b.classList.remove('active');
|
|
2247
|
+
b.setAttribute('aria-pressed', 'false');
|
|
2248
|
+
});
|
|
2249
|
+
tabBtn.classList.add('active');
|
|
2250
|
+
tabBtn.setAttribute('aria-pressed', 'true');
|
|
2251
|
+
currentLang = tabBtn.dataset.lang;
|
|
2252
|
+
renderLang(currentLang);
|
|
2253
|
+
});
|
|
2254
|
+
});
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
editorEl.querySelector('.forgewp-forms-add-row').addEventListener('click', function () {
|
|
2258
|
+
tbody.appendChild(buildRow(null));
|
|
2259
|
+
});
|
|
2260
|
+
|
|
2261
|
+
var saveButton = editorEl.querySelector('.forgewp-forms-save');
|
|
2262
|
+
saveButton.addEventListener('click', function () {
|
|
2263
|
+
var fields = captureCurrentRows();
|
|
2264
|
+
saveButton.disabled = true;
|
|
2265
|
+
showNotice(editorEl, true, 'Saving…');
|
|
2266
|
+
|
|
2267
|
+
var body = new URLSearchParams();
|
|
2268
|
+
body.set('action', 'forgewp_forms_admin_save');
|
|
2269
|
+
body.set('nonce', NONCE);
|
|
2270
|
+
body.set('form', editorEl.dataset.form);
|
|
2271
|
+
body.set('fields', JSON.stringify(fields));
|
|
2272
|
+
if (isMultilingual) { body.set('lang', currentLang); }
|
|
2273
|
+
|
|
2274
|
+
fetch(AJAX_URL, { method: 'POST', body: body })
|
|
2275
|
+
.then(function (res) { return res.json(); })
|
|
2276
|
+
.then(function (data) {
|
|
2277
|
+
if (data.success) {
|
|
2278
|
+
var payload = data.data || {};
|
|
2279
|
+
var savedFields = Array.isArray(payload.fields) ? payload.fields : (Array.isArray(payload) ? payload : []);
|
|
2280
|
+
var skipped = Array.isArray(payload.skipped) ? payload.skipped : [];
|
|
2281
|
+
var count = savedFields.length;
|
|
2282
|
+
var langNote = isMultilingual ? ' (' + currentLang.toUpperCase() + ')' : '';
|
|
2283
|
+
var msg = 'Saved' + langNote + ' \\u2014 ' + count + ' field' + (count === 1 ? '' : 's') + ' updated.';
|
|
2284
|
+
var skippedNames = new Set(skipped);
|
|
2285
|
+
tbody.querySelectorAll('.forgewp-forms-row').forEach(function (row) {
|
|
2286
|
+
var fieldError = row.querySelector('.forgewp-field-error');
|
|
2287
|
+
if (fieldError && skippedNames.has(row.dataset.name || '')) {
|
|
2288
|
+
fieldError.textContent = 'This field key conflicts with a developer-owned or duplicate field and was not saved.';
|
|
2289
|
+
fieldError.hidden = false;
|
|
2290
|
+
} else if (fieldError) {
|
|
2291
|
+
fieldError.hidden = true;
|
|
2292
|
+
}
|
|
2293
|
+
});
|
|
2294
|
+
if (skipped.length > 0) {
|
|
2295
|
+
msg += ' ' + skipped.length + ' field' + (skipped.length === 1 ? '' : 's') + ' could not be saved (name already in use): ' + skipped.join(', ') + '.';
|
|
2296
|
+
} else {
|
|
2297
|
+
dataByLang[currentLang] = savedFields;
|
|
2298
|
+
renderLang(currentLang);
|
|
2299
|
+
}
|
|
2300
|
+
showNotice(editorEl, skipped.length === 0, msg);
|
|
2301
|
+
} else {
|
|
2302
|
+
var errMsg = (data.data && typeof data.data === 'string') ? data.data : 'Could not save. Please check your changes and try again.';
|
|
2303
|
+
showNotice(editorEl, false, errMsg);
|
|
2304
|
+
}
|
|
2305
|
+
})
|
|
2306
|
+
.catch(function () {
|
|
2307
|
+
showNotice(editorEl, false, 'Could not save \\u2014 check your connection and try again.');
|
|
2308
|
+
})
|
|
2309
|
+
.finally(function () {
|
|
2310
|
+
saveButton.disabled = false;
|
|
2311
|
+
});
|
|
2312
|
+
});
|
|
2313
|
+
});
|
|
2314
|
+
})();
|
|
2315
|
+
</script>
|
|
2316
|
+
<?php
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
`;
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
/**
|
|
2323
|
+
* Emits the hydration payload helper used by hydration-enqueuer.js.
|
|
2324
|
+
* Returns client-owned field descriptors and explicit label overrides only
|
|
2325
|
+
* (never mailTo or other server-only config), resolved for the current locale.
|
|
2326
|
+
*/
|
|
2327
|
+
function buildFormsHydrationPayloadPhp(forms, locales) {
|
|
2328
|
+
const isMultilingual = locales.length > 1;
|
|
2329
|
+
const entries = Object.entries(forms)
|
|
2330
|
+
.map(([name, formConfig]) => {
|
|
2331
|
+
const rawSeed = formConfig.clientFields?.enabled
|
|
2332
|
+
? formConfig.clientFields.seed
|
|
2333
|
+
: [];
|
|
2334
|
+
const seedPhp = isMultilingual
|
|
2335
|
+
? seedByLocalePhpArray(rawSeed, locales)
|
|
2336
|
+
: seedFieldsPhpArray(rawSeed);
|
|
2337
|
+
const langArg = isMultilingual ? ', $forgewp_forms_current_lang' : '';
|
|
2338
|
+
return ` $forgewp_form_settings = get_option('forgewp_form_settings_${name}', array());
|
|
2339
|
+
if (!is_array($forgewp_form_settings)) { $forgewp_form_settings = array(); }
|
|
2340
|
+
$payload[${phpString(name)}] = array(
|
|
2341
|
+
'fields' => forgewp_forms_get_client_fields(${phpString(name)}, ${seedPhp}${langArg}),
|
|
2342
|
+
'fieldLabels' => isset($forgewp_form_settings['fieldLabels']) && is_array($forgewp_form_settings['fieldLabels']) ? $forgewp_form_settings['fieldLabels'] : array(),
|
|
2343
|
+
);`;
|
|
2344
|
+
})
|
|
2345
|
+
.join('\n');
|
|
2346
|
+
|
|
2347
|
+
return `
|
|
2348
|
+
if (!function_exists('forgewp_forms_hydration_payload')) {
|
|
2349
|
+
function forgewp_forms_hydration_payload($requested_lang = null) {
|
|
2350
|
+
$payload = array();
|
|
2351
|
+
${isMultilingual ? ` $forgewp_forms_current_lang = forgewp_forms_resolve_lang($requested_lang);\n` : ''}${entries}
|
|
2352
|
+
return $payload;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
`;
|
|
2356
|
+
}
|
|
2357
|
+
|
|
2358
|
+
export function buildFormsPhp(config) {
|
|
2359
|
+
const forms = config.forms;
|
|
2360
|
+
if (!forms || Object.keys(forms).length === 0) return '';
|
|
2361
|
+
|
|
2362
|
+
validateFormsConfig(forms);
|
|
2363
|
+
|
|
2364
|
+
const textDomain = config.textDomain || 'forgewp';
|
|
2365
|
+
const locales =
|
|
2366
|
+
Array.isArray(config.i18n?.locales) && config.i18n.locales.length > 0
|
|
2367
|
+
? config.i18n.locales
|
|
2368
|
+
: ['default'];
|
|
2369
|
+
// Shortcode-mode forms are a pure escape hatch — the developer renders
|
|
2370
|
+
// <WpShortcode> directly and the plugin (CF7/WPForms/…) owns everything.
|
|
2371
|
+
// ForgeWP generates no endpoint, no admin section, no storage for them.
|
|
2372
|
+
const nativeFormNames = Object.keys(forms).filter(
|
|
2373
|
+
(n) => !isShortcodeModeForm(forms[n]),
|
|
2374
|
+
);
|
|
2375
|
+
|
|
2376
|
+
if (nativeFormNames.length === 0) return '';
|
|
2377
|
+
|
|
2378
|
+
const adminCapability = config.formsAdminCapability ?? 'manage_options';
|
|
2379
|
+
if (
|
|
2380
|
+
typeof adminCapability !== 'string' ||
|
|
2381
|
+
!/^[A-Za-z][A-Za-z0-9_]*$/.test(adminCapability)
|
|
2382
|
+
) {
|
|
2383
|
+
throw new Error(
|
|
2384
|
+
`[ForgeWP Forms] Invalid formsAdminCapability "${String(adminCapability)}". ` +
|
|
2385
|
+
`Provide a non-empty WordPress capability name such as "manage_options" or "edit_pages".`,
|
|
2386
|
+
);
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
const anyStoreSubmissions = nativeFormNames.some(
|
|
2390
|
+
(n) => forms[n].storeSubmissions !== false,
|
|
2391
|
+
);
|
|
2392
|
+
|
|
2393
|
+
let php = `
|
|
2394
|
+
/**
|
|
2395
|
+
* ── ForgeWP Native Forms ─────────────────────────────────────────────────
|
|
2396
|
+
* Generated from the \`forms\` key in wp.config.ts. See forgewp_forms_spec.md.
|
|
2397
|
+
*/
|
|
2398
|
+
`;
|
|
2399
|
+
|
|
2400
|
+
php += buildSharedHelpersPhp(config.i18n?.defaultLocale);
|
|
2401
|
+
|
|
2402
|
+
if (anyStoreSubmissions) {
|
|
2403
|
+
const storingFormNames = nativeFormNames.filter(
|
|
2404
|
+
(n) => forms[n].storeSubmissions !== false,
|
|
2405
|
+
);
|
|
2406
|
+
php += buildSubmissionCptPhp(textDomain, storingFormNames, adminCapability);
|
|
2407
|
+
const storingForms = Object.fromEntries(
|
|
2408
|
+
storingFormNames.map((name) => [name, forms[name]]),
|
|
2409
|
+
);
|
|
2410
|
+
php += buildSubmissionToolsPhp(
|
|
2411
|
+
storingForms,
|
|
2412
|
+
textDomain,
|
|
2413
|
+
adminCapability,
|
|
2414
|
+
locales,
|
|
2415
|
+
);
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
php += `
|
|
2419
|
+
add_action('rest_api_init', function () {
|
|
2420
|
+
${nativeFormNames
|
|
2421
|
+
.map(
|
|
2422
|
+
(
|
|
2423
|
+
name,
|
|
2424
|
+
) => ` register_rest_route('forgewp/v1', '/forms/${name}/submit', array(
|
|
2425
|
+
'methods' => 'POST',
|
|
2426
|
+
'callback' => 'forgewp_handle_form_${safeFormSlug(name)}',
|
|
2427
|
+
'permission_callback' => '__return_true',
|
|
2428
|
+
));`,
|
|
2429
|
+
)
|
|
2430
|
+
.join('\n')}
|
|
2431
|
+
});
|
|
2432
|
+
`;
|
|
2433
|
+
|
|
2434
|
+
for (const name of nativeFormNames) {
|
|
2435
|
+
php += buildFormHandlerPhp(name, forms[name], textDomain, locales);
|
|
2436
|
+
|
|
2437
|
+
// Expose this form's dev-owned field names to the admin-save handler's
|
|
2438
|
+
// collision check without re-parsing config inside the AJAX callback.
|
|
2439
|
+
const devFieldNamesPhp = Object.keys(forms[name].fields || {})
|
|
2440
|
+
.map((n) => phpString(n))
|
|
2441
|
+
.join(', ');
|
|
2442
|
+
php += `
|
|
2443
|
+
add_filter('forgewp_form_dev_field_names_${name}', function () {
|
|
2444
|
+
return array(${devFieldNamesPhp});
|
|
2445
|
+
});
|
|
2446
|
+
`;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
const nativeForms = Object.fromEntries(
|
|
2450
|
+
nativeFormNames.map((n) => [n, forms[n]]),
|
|
2451
|
+
);
|
|
2452
|
+
php += buildFormsAdminPagePhp(
|
|
2453
|
+
nativeForms,
|
|
2454
|
+
textDomain,
|
|
2455
|
+
locales,
|
|
2456
|
+
adminCapability,
|
|
2457
|
+
);
|
|
2458
|
+
php += buildFormsHydrationPayloadPhp(nativeForms, locales);
|
|
2459
|
+
|
|
2460
|
+
return php;
|
|
2461
|
+
}
|