-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
344 lines (309 loc) · 9.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const fs = require('fs');
const path = require('path');
const connectMultiparty = require('connect-multiparty');
const fields = require('./lib/fields');
const recaptcha = require('./lib/recaptcha');
const processor = require('./lib/processor');
module.exports = {
extend: '@apostrophecms/piece-type',
options: {
label: 'aposForm:form',
pluralLabel: 'aposForm:forms',
quickCreate: true,
seoFields: false,
openGraph: false,
i18n: {
ns: 'aposForm',
browser: true
},
shortcut: 'G,O'
},
bundle: {
directory: 'modules',
modules: getBundleModuleNames()
},
fields (self) {
let add = fields.initial(self.options);
if (self.options.emailSubmissions !== false) {
add = {
...add,
...fields.emailFields
};
}
const group = {
basics: {
label: 'aposForm:groupForm',
fields: [ 'contents' ]
},
afterSubmit: {
label: 'aposForm:groupAfterSubmission',
fields: [
'thankYouHeading',
'thankYouBody',
'sendConfirmationEmail',
'emailConfirmationField'
]
.concat(
self.options.emailSubmissions !== false
? [
'emails',
'email'
]
: []
)
},
advanced: {
label: 'aposForm:groupAdvanced',
fields: [
'submitLabel',
'enableRecaptcha',
'enableQueryParams',
'queryParamList'
]
}
};
return {
add,
group
};
},
init (self) {
self.ensureCollection();
self.cleanOptions(self.options);
},
methods (self) {
return {
...recaptcha(self),
...processor(self),
async ensureCollection () {
self.db = self.apos.db.collection('aposFormSubmissions');
await self.db.ensureIndex({
formId: 1,
createdAt: 1
});
await self.db.ensureIndex({
formId: 1,
createdAt: -1
});
},
processQueryParams (form, input, output, fieldNames) {
if (!input.queryParams ||
(typeof input.queryParams !== 'object')) {
output.queryParams = null;
return;
}
if (Array.isArray(form.queryParamList) && form.queryParamList.length > 0) {
form.queryParamList.forEach(param => {
// Skip if this is an existing field submitted by the form. This value
// capture will be done by populating the form inputs client-side.
if (fieldNames.includes(param.key)) {
return;
}
const value = input.queryParams[param.key];
if (value) {
output[param.key] = self.tidyParamValue(param, value);
} else {
output[param.key] = null;
}
});
}
},
tidyParamValue(param, value) {
value = self.apos.launder.string(value);
if (param.lengthLimit && param.lengthLimit > 0) {
value = value.substring(0, (param.lengthLimit));
}
return value;
},
async sendEmailSubmissions (req, form, data) {
if (self.options.emailSubmissions === false ||
!form.emails || form.emails.length === 0) {
return;
}
let emails = [];
form.emails.forEach(mailRule => {
if (!mailRule.conditions || mailRule.conditions.length === 0) {
emails.push(mailRule.email);
return;
}
let passed = true;
mailRule.conditions.forEach(condition => {
if (!condition.value) {
return;
}
let answer = data[condition.field];
if (!answer) {
passed = false;
} else {
// Regex for comma-separation from https://stackoverflow.com/questions/11456850/split-a-string-by-commas-but-ignore-commas-within-double-quotes-using-javascript/11457952#comment56094979_11457952
const regex = /(".*?"|[^",]+)(?=\s*,|\s*$)/g;
let acceptable = condition.value.match(regex);
acceptable = acceptable.map(value => {
// Remove leading/trailing white space and bounding double-quotes.
value = value.trim();
if (value[0] === '"' && value[value.length - 1] === '"') {
value = value.slice(1, -1);
}
return value.trim();
});
// If the value is stored as a string, convert to an array for checking.
if (!Array.isArray(answer)) {
answer = [ answer ];
}
if (!(answer.some(val => acceptable.includes(val)))) {
passed = false;
}
}
});
if (passed === true) {
emails.push(mailRule.email);
}
});
// Get array of email addresses without duplicates.
emails = [ ...new Set(emails) ];
if (self.options.testing) {
return emails;
}
if (emails.length === 0) {
return null;
}
for (const key in data) {
// Add some space to array lists.
if (Array.isArray(data[key])) {
data[key] = data[key].join(', ');
}
}
try {
const emailOptions = {
form,
data,
to: emails.join(',')
};
await self.sendEmail(req, 'emailSubmission', emailOptions);
return null;
} catch (err) {
self.apos.util.error('⚠️ @apostrophecms/form submission email notification error: ', err);
return null;
}
},
// Should be handled async. Options are: form, data, from, to and subject
async sendEmail (req, emailTemplate, options) {
const form = options.form;
const data = options.data;
return self.email(
req,
emailTemplate,
{
form,
input: data
},
{
from: options.from || form.email,
to: options.to,
subject: options.subject || form.title
}
);
}
};
},
helpers (self) {
return {
prependIfPrefix(str) {
if (self.options.classPrefix) {
return `${self.options.classPrefix}${str}`;
}
return '';
}
};
},
apiRoutes (self) {
return {
post: {
// Route to accept the submitted form.
submit: [
connectMultiparty(),
async function (req) {
try {
await self.submitForm(req);
} finally {
for (const file of (Object.values(req.files || {}))) {
try {
fs.unlinkSync(file.path);
} catch (e) {
self.apos.util.warn(req.t('aposForm:fileMissingEarly', {
path: file
}));
}
}
}
}
]
}
};
},
handlers (self) {
return {
submission: {
async saveSubmission (req, form, data) {
if (self.options.saveSubmissions === false) {
return;
}
const submission = {
createdAt: new Date(),
formId: form._id,
data
};
await self.emit('beforeSaveSubmission', req, {
form,
data,
submission
});
return self.db.insertOne(submission);
},
async emailSubmission (req, form, data) {
await self.sendEmailSubmissions(req, form, data);
},
async emailConfirmation (req, form, data) {
if (form.sendConfirmationEmail !== true || !form.emailConfirmationField) {
return;
}
// Email validation (Regex reference: https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript)
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (
data[form.emailConfirmationField] &&
(typeof data[form.emailConfirmationField] !== 'string' ||
!re.test(data[form.emailConfirmationField]))
) {
await self.apos.notify(req, 'aposForm:errorEmailConfirm', {
type: 'warning',
icon: 'alert-circle-icon',
interpolate: {
field: form.emailConfirmationField
}
});
return null;
}
try {
const emailOptions = {
form,
data,
to: data[form.emailConfirmationField]
};
await self.sendEmail(req, 'emailConfirmation', emailOptions);
return null;
} catch (err) {
self.apos.util.error('⚠️ @apostrophecms/form submission email confirmation error: ', err);
return null;
}
}
}
};
}
};
function getBundleModuleNames() {
const source = path.join(__dirname, './modules/@apostrophecms');
return fs
.readdirSync(source, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => `@apostrophecms/${dirent.name}`);
}