-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-wpforms.php
545 lines (445 loc) · 17.9 KB
/
class-wpforms.php
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
<?php
namespace SLCA\WPForms;
use wpCloud\StatelessMedia\Compatibility;
use wpCloud\StatelessMedia\Utility;
use wpCloud\StatelessMedia\Helper;
/**
* Class WPForms
*/
class WPForms extends Compatibility {
const STORAGE_PATH = 'wpforms/';
const TMP_PATH = self::STORAGE_PATH . 'tmp/';
const UPLOAD_FIELD_TYPE = 'file-upload';
const MESSAGE_KEY = 'stateless-wpforms-modern';
const DISMISSED_MESSAGE_KEY = 'dismissed_notice_' . self::MESSAGE_KEY;
const WPFORMS_BUILDER_PAGE = 'wpforms-builder';
protected $id = 'wpforms';
protected $title = 'WPForms';
protected $constant = 'WP_STATELESS_COMPATIBILITY_WPFORMS';
protected $description = 'Ensures compatibility with WPForms.';
protected $plugin_file = ['wpforms-lite/wpforms.php', 'wpforms/wpforms.php'];
protected $filesystem = null;
/**
* @param $sm
*/
public function module_init($sm) {
if ( !class_exists('\WP_Filesystem_Direct') ) {
require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');
}
$this->filesystem = new \WP_Filesystem_Direct( false );
/**
* Disable cache busting for WPForms Builder page
*/
if ( isset($_GET['page']) ) {
$page = sanitize_text_field($_GET['page']);
if ( $page === self::WPFORMS_BUILDER_PAGE ) {
$this->remove_cache_busting();
}
}
add_action( 'wp', [$this, 'check_processing_form_submit'], 5);
add_action( 'wp_ajax_wpforms_upload_chunk_init', [$this, 'remove_cache_busting'], 5);
add_action( 'wp_ajax_nopriv_wpforms_upload_chunk_init', [$this, 'remove_cache_busting'], 5);
add_action( 'wp_ajax_wpforms_submit', [$this, 'remove_cache_busting'], 5);
add_action( 'wp_ajax_nopriv_wpforms_submit', [$this, 'remove_cache_busting'], 5);
add_action( 'wpforms_process_entry_saved', [ $this, 'entry_saved' ], 10, 4 );
add_action( 'wpforms_pre_delete_entries', [ $this, 'pre_delete_entries' ], 10, 1 );
add_action( 'wpforms_pro_admin_entries_page_empty_trash_before', [ $this, 'before_empty_trash' ], 10, 1 );
add_action( 'wpforms_pre_delete_entry_fields', [ $this, 'pre_delete_entry_fields' ], 10, 2 );
add_action( 'wpforms_builder_save_form', [ $this, 'builder_save_form' ], 10, 2 );
add_action( 'admin_init', [ $this, 'show_message' ]);
add_filter( 'wpforms_process_after_filter', [ $this, 'upload_complete' ], 10, 3 );
add_filter( 'wpforms_entry_email_data', [ $this, 'entry_email_data' ], 10, 3 );
add_filter( 'sm:sync::syncArgs', [$this, 'sync_args'], 10, 4);
add_filter( 'sm:sync::nonMediaFiles', [$this, 'sync_non_media_files'], 20);
}
/**
* Remove cache busting before processing WPForm submition.
*/
public function check_processing_form_submit() {
if ( isset( $_POST['wpforms'] ) && !empty($_POST['wpforms']) ) {
$this->remove_cache_busting();
}
}
/**
* Get the position of 'so-css/' dir in the filename.
*
* @param $name
* @return bool
*/
protected function storage_position($name) {
return strpos($name, self::STORAGE_PATH);
}
/**
* Check if the uploaded file is in the media library.
*
* @return bool
*/
protected function is_media_library($form_data, $field_id) {
$field_data = isset( $form_data['fields'] ) && isset( $form_data['fields'][$field_id] ) ? $form_data['fields'][$field_id] : [];
return isset( $field_data['media_library'] ) && !empty( $field_data['media_library'] );
}
/**
* Skip cache busting for WPForms files.
*/
public function remove_cache_busting() {
remove_filter('sanitize_file_name', ['wpCloud\StatelessMedia\Utility', 'randomize_filename'], 10);
}
/**
* Update args when uploading/syncing file to GCS.
*
* @param array $args
* @param string $name
* @param string $file
* @param bool $force
*
* @return array
*/
public function sync_args($args, $name, $file, $force) {
if ( $this->storage_position($name) !== 0 ) {
return $args;
}
if ( ud_get_stateless_media()->is_mode('stateless') ) {
$args['name_with_root'] = false;
}
$args['source'] = 'WPForms';
$args['source_version'] = defined('WPFORMS_VERSION') ? WPFORMS_VERSION : '';
return $args;
}
/**
* In Stateless mode move the file from /tmp to GCS, so thar WPForms could complete the upload.
*
* @param array $fields Fields data.
* @param array $entry Submitted form entry.
* @param array $form_data Form data and settings.
*
* @return array
*
*/
public function upload_complete($fields, $entry, $form_data) {
if ( !ud_get_stateless_media()->is_mode('stateless') ) {
return $fields;
}
foreach ( $fields as $field_id => $field ) {
if ( !isset( $field['type'] ) || $field['type'] !== self::UPLOAD_FIELD_TYPE ) {
continue;
}
// If uploads are saved to the media library
if ( $this->is_media_library($form_data, $field_id) ) {
continue;
}
$is_visible = ! isset( wpforms()->get( 'process' )->fields[ $field_id ]['visible'] ) || ! empty( wpforms()->get( 'process' )->fields[ $field_id ]['visible'] );
if ( ! $is_visible ) {
continue;
}
$input_name = sprintf( 'wpforms_%d_%d', absint( $form_data['id'] ), $field_id );
// we are $_FILES after WPForms performed all the security checks
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$file = isset( $_FILES[ $input_name ] ) && !empty( $_FILES[ $input_name ] ) ? $_FILES[ $input_name ] : false;
// If there was no file uploaded stop here before we continue with the upload process.
if ( ! $file || $file['error'] !== 0 ) {
continue;
}
$dir = apply_filters('wp_stateless_addon_sync_files_path', '', self::TMP_PATH);
// we are $_FILES after WPForms performed all the security checks
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$filename = $dir . $_FILES[ $input_name ]['name'];
// we are $_FILES after WPForms performed all the security checks
// phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( $this->filesystem->move( $_FILES[ $input_name ]['tmp_name'], $filename, true ) ) {
$_FILES[ $input_name ]['tmp_name'] = $filename;
}
}
return $fields;
}
/**
* If Media Library is not used for file upload
* - move the file to '/wpforms' dir
* - run sync
* - update entry data with the new file path
*/
public function entry_saved($fields, $entry, $form_data, $entry_id) {
$wp_uploads_dir = wp_get_upload_dir();
global $wpdb;
foreach ( $fields as $field_id => $field ) {
if ( !isset( $field['type'] ) || $field['type'] !== self::UPLOAD_FIELD_TYPE ) {
continue;
}
if ( !isset( $field['value'] ) || empty($field['value']) ) {
continue;
}
// If uploads are saved to the media library
if ( $this->is_media_library($form_data, $field_id) ) {
continue;
}
$url = $field['value'];
/**
* Multifile upload support
*/
$files = explode("\n", $url);
foreach ($files as $file) {
$name = str_replace($wp_uploads_dir['baseurl'] . '/', '', $file);
$absolutePath = apply_filters('wp_stateless_addon_files_root', '');
$absolutePath .= '/' . $name;
// Move file to the correct location
if ( ud_get_stateless_media()->is_mode('stateless') ) {
$source = str_replace( ud_get_stateless_media()->get_gs_host(), ud_get_stateless_media()->get_gs_path(), $file );
$destination = str_replace( ud_get_stateless_media()->get_gs_host(), ud_get_stateless_media()->get_gs_path(), $absolutePath );
$this->filesystem->move( $source, $destination, true );
}
// Sync non-media file
$name = apply_filters('wp_stateless_file_name', $name, 0);
do_action('sm:sync::syncFile', $name, $absolutePath);
}
// Update entry data with the new file path
if ( !ud_get_stateless_media()->is_mode( ['disabled', 'backup'] ) ) {
$url = ud_get_stateless_media()->is_mode('stateless')
? str_replace( ud_get_stateless_media()->get_gs_path(), ud_get_stateless_media()->get_gs_host(), $absolutePath )
: str_replace( $wp_uploads_dir['baseurl'], ud_get_stateless_media()->get_gs_host(), $url );
try {
// WPForms uses direct database access and ignores caching, we should too
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$entry_fields = $wpdb->get_var(
$wpdb->prepare(
"SELECT fields FROM {$wpdb->prefix}wpforms_entries WHERE entry_id = %d AND form_id = %d",
$entry_id,
$form_data['id']
)
);
$entry_fields = json_decode($entry_fields, true);
if ( isset( $entry_fields[ $field_id ] ) && isset( $entry_fields[ $field_id ]['value'] ) ) {
$entry_fields[ $field_id ]['value'] = $url;
if ( isset( $entry_fields[ $field_id ]['value_raw'] ) && is_array( $entry_fields[ $field_id ]['value_raw'] ) && !empty( $entry_fields[ $field_id ]['value_raw'] )) {
foreach ( $entry_fields[ $field_id ]['value_raw'] as $key => $value_raw ) {
$entry_fields[ $field_id ]['value_raw'][ $key ]['value'] = ud_get_stateless_media()->is_mode('stateless')
? str_replace( ud_get_stateless_media()->get_gs_path(), ud_get_stateless_media()->get_gs_host(), $value_raw['value'] )
: str_replace( $wp_uploads_dir['baseurl'], ud_get_stateless_media()->get_gs_host(), $value_raw['value'] );
}
}
// WPForms uses direct database access and ignores caching, we should too
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->update(
$wpdb->prefix . 'wpforms_entries',
['fields' => wp_json_encode($entry_fields)],
[
'entry_id' => $entry_id,
'form_id' => $form_data['id'],
],
);
Helper::debug( $entry_fields );
}
// WPForms uses direct database access and ignores caching, we should too
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->update(
$wpdb->prefix . 'wpforms_entry_fields',
['value' => $url],
[
'entry_id' => $entry_id,
'field_id' => $field_id,
'form_id' => $form_data['id'],
],
);
Helper::debug( $url );
} catch (\Throwable $e) {
error_log( $e->getMessage() );
}
$fields[$field_id]['value'] = $url;
}
}
}
/**
* Update email data with the new file path
*/
public function entry_email_data($fields, $entry, $form_data) {
if ( !ud_get_stateless_media()->is_mode('stateless') ) {
return $fields;
}
$wp_uploads_dir = wp_get_upload_dir();
foreach ( $fields as $field_id => $field ) {
if ( !isset( $field['type'] ) || $field['type'] !== self::UPLOAD_FIELD_TYPE ) {
continue;
}
// If uploads are saved to the media library
if ( $this->is_media_library($form_data, $field_id) ) {
continue;
}
$url = $field['value'];
$name = str_replace($wp_uploads_dir['baseurl'] . '/', '', $url);
$absolutePath = apply_filters('wp_stateless_addon_files_root', '');
$absolutePath .= '/' . $name;
$absolutePath = str_replace( ud_get_stateless_media()->get_gs_path(), ud_get_stateless_media()->get_gs_host(), $absolutePath );
$fields[$field_id]['value'] = $absolutePath;
}
return $fields;
}
/**
* Delete files from GCS when deleting entries.
*/
public function pre_delete_entries($entry_id) {
global $wpdb;
try {
// WPForms uses direct database access and ignores caching, we should too
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$entry_fields = $wpdb->get_var(
$wpdb->prepare(
"SELECT fields FROM {$wpdb->prefix}wpforms_entries WHERE entry_id = %d",
$entry_id,
)
);
$entry_fields = json_decode($entry_fields, true);
foreach ( $entry_fields as $field_id => $field ) {
if ( !isset( $field['type'] ) || $field['type'] !== self::UPLOAD_FIELD_TYPE ) {
continue;
}
// If uploads were saved to the media library
if ( isset( $field['attachment_id'] ) && !empty($field['attachment_id']) ) {
continue;
}
$url = isset($field['value']) ? $field['value'] : false;
if ( empty($url) ) {
continue;
}
$name = str_replace( trailingslashit( ud_get_stateless_media()->get_gs_host() ), '', $url);
do_action('sm:sync::deleteFile', $name);
}
} catch (\Throwable $e) {
error_log( $e->getMessage() );
}
}
/**
* Delete files from GCS when emptying entries trash.
*/
public function before_empty_trash($entry_ids) {
foreach ( $entry_ids as $id ) {
$this->pre_delete_entries($id);
}
}
/**
* Filter files created by WPForms for sync.
*
* @param array $file_list
* @return array
*/
public function sync_non_media_files($file_list) {
if ( !method_exists('\wpCloud\StatelessMedia\Utility', 'get_files') ) {
Helper::log('WP-Stateless version too old, please update.');
return $file_list;
}
$dir = apply_filters('wp_stateless_addon_sync_files_path', '', self::STORAGE_PATH);
if (is_dir($dir)) {
// Getting all the files from dir recursively.
$files = Utility::get_files($dir);
// validating and adding to the $files array.
foreach ($files as $file) {
if (!file_exists($file)) {
continue;
}
// filter temporary files
if (strpos($file, self::TMP_PATH) !== false) {
continue;
}
// filter index.html, .htaccess files
$basename = basename($file);
if ( in_array($basename, array('index.html', '.htaccess')) ) {
continue;
}
$file = self::STORAGE_PATH . str_replace( $dir, '', wp_normalize_path($file) );
$file = trim($file, '/');
if ( !in_array($file, $file_list) ) {
$file_list[] = $file;
}
}
}
return $file_list;
}
/**
* Delete files from GCS when file deleted from entry.
*/
public function pre_delete_entry_fields($row_id, $primary_key) {
// other cases are handled by other hooks
if ( $primary_key !== 'id' ) {
return;
}
global $wpdb;
try {
// WPForms uses direct database access and ignores caching, we should too
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$value = $wpdb->get_var(
$wpdb->prepare(
"SELECT value FROM {$wpdb->prefix}wpforms_entry_fields WHERE id = %d",
$row_id,
)
);
// Not a file or not on GCS
if ( strpos( $value, ud_get_stateless_media()->get_gs_host() ) === false ) {
return;
}
// Not a WPForms file or Media Library file
if ( $this->storage_position($value) === false ) {
return;
}
$name = str_replace( trailingslashit( ud_get_stateless_media()->get_gs_host() ), '', $value);
do_action('sm:sync::deleteFile', $name);
} catch (\Throwable $e) {
error_log( $e->getMessage() );
}
}
/**
* Show message in Admin Panel when Modern upload style is used during using Stateless mode
*/
public function show_message() {
if ( !ud_get_stateless_media()->is_mode('stateless') ) {
return;
}
$message_option = get_option(self::MESSAGE_KEY, []);
if ( empty($message_option) ) {
return;
}
$form_names = array_filter( array_values($message_option) );
if ( empty($form_names) ) {
return;
}
$form_names = implode(', ', $form_names);
$form_names = '<strong>' . $form_names . '</strong>';
/* translators: %s: list of forms */
$message = __('The <em>File Upload</em> field with a <em>Modern</em> style is not compatible with <em>Stateless</em> mode. Change the WPForms field style to <em>Classic</em> or use another WP-Stateless mode with the <em>Modern</em> field style. <strong>Affected Form: %s</strong>', ud_get_stateless_media()->domain);
$message = sprintf($message, $form_names);
ud_get_stateless_media()->errors->add([
'title' => __('WP-Stateless: Problem Detected With WPForms', ud_get_stateless_media()->domain),
'message' => $message,
'key' => self::MESSAGE_KEY,
], 'warning');
}
/**
* When saving form - show warning for the Modern upload style during using Stateless mode
*/
public function builder_save_form($form_id, $form_data) {
$fields = is_array($form_data) && isset( $form_data['fields'] ) ? $form_data['fields'] : [];
$message_option = get_option(self::MESSAGE_KEY, []);
$found = false;
foreach ( $fields as $field ) {
if ( !isset( $field['type'] ) || $field['type'] !== self::UPLOAD_FIELD_TYPE ) {
continue;
}
if ( isset( $field['style'] ) && $field['style'] == 'modern' ) {
$found = true;
break;
}
}
if ( $found ) {
$title = isset( $form_data['settings']['form_title'] )
? $form_data['settings']['form_title']
/* translators: %d: form ID */
: sprintf( __('Form %d', 'wp-stateless-wpforms-addon'), $form_id);
$message_option[$form_id] = $title;
delete_option(self::DISMISSED_MESSAGE_KEY);
} else {
unset($message_option[$form_id]);
}
if ( empty($message_option) ) {
delete_option(self::MESSAGE_KEY);
} else {
update_option(self::MESSAGE_KEY, $message_option);
}
}
}