Completed
Push — master ( 537290...572154 )
by Stephanie
02:56
created

FrmForm::set_status()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 2
dl 0
loc 33
rs 9.0808
c 0
b 0
f 0
1
<?php
2
if ( ! defined( 'ABSPATH' ) ) {
3
    die( 'You are not allowed to call this page directly.' );
4
}
5
6
class FrmForm {
7
8
    /**
9
     * @return int|boolean id on success or false on failure
10
     */
11
    public static function create( $values ) {
12
        global $wpdb;
13
14
		$new_values = array(
15
			'form_key'      => FrmAppHelper::get_unique_key( $values['form_key'], $wpdb->prefix . 'frm_forms', 'form_key' ),
16
			'name'          => $values['name'],
17
			'description'   => $values['description'],
18
			'status'        => isset( $values['status'] ) ? $values['status'] : 'draft',
19
			'logged_in'     => isset( $values['logged_in'] ) ? $values['logged_in'] : 0,
20
			'is_template'   => isset( $values['is_template'] ) ? (int) $values['is_template'] : 0,
21
			'parent_form_id' => isset( $values['parent_form_id'] ) ? absint( $values['parent_form_id'] ) : 0,
22
			'editable'      => isset( $values['editable'] ) ? (int) $values['editable'] : 0,
23
			'created_at'    => isset( $values['created_at'] ) ? $values['created_at'] : current_time( 'mysql', 1 ),
24
		);
25
26
		$options = isset( $values['options'] ) ? (array) $values['options'] : array();
27
		FrmFormsHelper::fill_form_options( $options, $values );
28
29
		$options['before_html'] = isset( $values['options']['before_html'] ) ? $values['options']['before_html'] : FrmFormsHelper::get_default_html( 'before' );
30
		$options['after_html'] = isset( $values['options']['after_html'] ) ? $values['options']['after_html'] : FrmFormsHelper::get_default_html( 'after' );
31
		$options['submit_html'] = isset( $values['options']['submit_html'] ) ? $values['options']['submit_html'] : FrmFormsHelper::get_default_html( 'submit' );
32
33
		$options = apply_filters( 'frm_form_options_before_update', $options, $values );
34
		$new_values['options'] = serialize( $options );
35
36
        //if(isset($values['id']) && is_numeric($values['id']))
37
        //    $new_values['id'] = $values['id'];
38
39
		$wpdb->insert( $wpdb->prefix . 'frm_forms', $new_values );
40
41
        $id = $wpdb->insert_id;
42
43
		// Clear form caching
44
		self::clear_form_cache();
45
46
        return $id;
47
    }
48
49
    /**
50
     * @return int|boolean ID on success or false on failure
51
     */
52
    public static function duplicate( $id, $template = false, $copy_keys = false, $blog_id = false ) {
53
        global $wpdb;
54
55
        $values = self::getOne( $id, $blog_id );
56
        if ( ! $values ) {
57
            return false;
58
        }
59
60
        $new_key = $copy_keys ? $values->form_key : '';
61
62
        $new_values = array(
63
			'form_key'      => FrmAppHelper::get_unique_key( $new_key, $wpdb->prefix . 'frm_forms', 'form_key' ),
64
            'name'          => $values->name,
65
            'description'   => $values->description,
66
            'status'        => $template ? 'published' : 'draft',
67
            'logged_in'     => $values->logged_in ? $values->logged_in : 0,
68
            'editable'      => $values->editable ? $values->editable : 0,
69
			'created_at'    => current_time( 'mysql', 1 ),
70
            'is_template'   => $template ? 1 : 0,
71
        );
72
73
        if ( $blog_id ) {
74
            $new_values['status'] = 'published';
75
			$new_options = maybe_unserialize( $values->options );
76
			$new_options['email_to'] = get_option( 'admin_email' );
77
            $new_options['copy'] = false;
78
            $new_values['options'] = $new_options;
79
        } else {
80
            $new_values['options'] = $values->options;
81
        }
82
83
		if ( is_array( $new_values['options'] ) ) {
84
			$new_values['options'] = serialize( $new_values['options'] );
85
		}
86
87
		$query_results = $wpdb->insert( $wpdb->prefix . 'frm_forms', $new_values );
88
89
        if ( $query_results ) {
90
			// Clear form caching
91
			self::clear_form_cache();
92
93
            $form_id = $wpdb->insert_id;
94
			FrmField::duplicate( $id, $form_id, $copy_keys, $blog_id );
95
96
            // update form settings after fields are created
97
			do_action( 'frm_after_duplicate_form', $form_id, $new_values, array( 'old_id' => $id ) );
98
            return $form_id;
99
        }
100
101
        return false;
102
    }
103
104
	public static function after_duplicate( $form_id, $values ) {
105
		$new_opts = maybe_unserialize( $values['options'] );
106
		$values['options'] = $new_opts;
107
108
		if ( isset( $new_opts['success_msg'] ) ) {
109
			$new_opts['success_msg'] = FrmFieldsHelper::switch_field_ids( $new_opts['success_msg'] );
110
		}
111
112
		$new_opts = apply_filters( 'frm_after_duplicate_form_values', $new_opts, $form_id );
113
114
        if ( $new_opts != $values['options'] ) {
115
            global $wpdb;
116
			$wpdb->update( $wpdb->prefix . 'frm_forms', array( 'options' => maybe_serialize( $new_opts ) ), array( 'id' => $form_id ) );
117
        }
118
    }
119
120
    /**
121
     * @return int|boolean
122
     */
123
    public static function update( $id, $values, $create_link = false ) {
124
        global $wpdb;
125
126
        if ( ! isset( $values['status'] ) && ( $create_link || isset( $values['options'] ) || isset( $values['item_meta'] ) || isset( $values['field_options'] ) ) ) {
127
            $values['status'] = 'published';
128
        }
129
130
		if ( isset( $values['form_key'] ) ) {
131
			$values['form_key'] = FrmAppHelper::get_unique_key( $values['form_key'], $wpdb->prefix . 'frm_forms', 'form_key', $id );
132
        }
133
134
		$form_fields = array( 'form_key', 'name', 'description', 'status', 'parent_form_id' );
135
136
		$new_values = self::set_update_options( array(), $values );
137
138
        foreach ( $values as $value_key => $value ) {
139
			if ( $value_key && in_array( $value_key, $form_fields ) ) {
140
				$new_values[ $value_key ] = $value;
141
            }
142
        }
143
144
        if ( isset( $values['new_status'] ) && ! empty( $values['new_status'] ) ) {
145
            $new_values['status'] = $values['new_status'];
146
        }
147
148
        if ( ! empty( $new_values ) ) {
149
			$query_results = $wpdb->update( $wpdb->prefix . 'frm_forms', $new_values, array( 'id' => $id ) );
150
            if ( $query_results ) {
151
				self::clear_form_cache();
152
            }
153
        } else {
154
            $query_results = true;
155
        }
156
		unset( $new_values );
157
158
		$values = self::update_fields( $id, $values );
159
160
		do_action( 'frm_update_form', $id, $values );
161
		do_action( 'frm_update_form_' . $id, $values );
162
163
        return $query_results;
164
    }
165
166
    /**
167
     * @return array
168
     */
169
	public static function set_update_options( $new_values, $values ) {
170
		if ( ! isset( $values['options'] ) ) {
171
            return $new_values;
172
        }
173
174
		$options = isset( $values['options'] ) ? (array) $values['options'] : array();
175
		FrmFormsHelper::fill_form_options( $options, $values );
176
177
		$options['custom_style'] = isset( $values['options']['custom_style'] ) ? $values['options']['custom_style'] : 0;
178
		$options['before_html'] = isset( $values['options']['before_html'] ) ? $values['options']['before_html'] : FrmFormsHelper::get_default_html( 'before' );
179
		$options['after_html'] = isset( $values['options']['after_html'] ) ? $values['options']['after_html'] : FrmFormsHelper::get_default_html( 'after' );
180
		$options['submit_html'] = ( isset( $values['options']['submit_html'] ) && '' !== $values['options']['submit_html'] ) ? $values['options']['submit_html'] : FrmFormsHelper::get_default_html( 'submit' );
181
182
		$options = apply_filters( 'frm_form_options_before_update', $options, $values );
183
		$new_values['options'] = serialize( $options );
184
185
		return $new_values;
186
    }
187
188
189
    /**
190
     * @return array
191
     */
192
	public static function update_fields( $id, $values ) {
193
194
		if ( ! isset( $values['item_meta'] ) && ! isset( $values['field_options'] ) ) {
195
            return $values;
196
        }
197
198
		$all_fields = FrmField::get_all_for_form( $id );
199
		if ( empty( $all_fields ) ) {
200
			return $values;
201
		}
202
203
		if ( ! isset( $values['item_meta'] ) ) {
204
			$values['item_meta'] = array();
205
		}
206
207
        $field_array = array();
208
        $existing_keys = array_keys( $values['item_meta'] );
209
        foreach ( $all_fields as $fid ) {
210
			if ( ! in_array( $fid->id, $existing_keys ) && ( isset( $values['frm_fields_submitted'] ) && in_array( $fid->id, $values['frm_fields_submitted'] ) ) || isset( $values['options'] ) ) {
211
				$values['item_meta'][ $fid->id ] = '';
212
            }
213
			$field_array[ $fid->id ] = $fid;
214
        }
215
		unset( $all_fields );
216
217
        foreach ( $values['item_meta'] as $field_id => $default_value ) {
218
			if ( isset( $field_array[ $field_id ] ) ) {
219
				$field = $field_array[ $field_id ];
220
            } else {
221
				$field = FrmField::getOne( $field_id );
222
            }
223
224
            if ( ! $field ) {
225
                continue;
226
            }
227
228
			$is_settings_page = ( isset( $values['options'] ) || isset( $values['field_options'][ 'custom_html_' . $field_id ] ) );
229
			if ( $is_settings_page ) {
230
				self::get_settings_page_html( $values, $field );
231
232
				if ( ! defined( 'WP_IMPORTING' ) ) {
233
					continue;
234
				}
235
			}
236
237
			//updating the form
238
			$update_options = FrmFieldsHelper::get_default_field_options_from_field( $field );
239
			unset( $update_options['custom_html'] ); // don't check for POST html
240
			$update_options = apply_filters( 'frm_field_options_to_update', $update_options );
241
242
			foreach ( $update_options as $opt => $default ) {
243
				$field->field_options[ $opt ] = isset( $values['field_options'][ $opt . '_' . $field_id ] ) ? $values['field_options'][ $opt . '_' . $field_id ] : $default;
244
				self::sanitize_field_opt( $opt, $field->field_options[ $opt ] );
245
            }
246
247
			$field->field_options = apply_filters( 'frm_update_field_options', $field->field_options, $field, $values );
248
			$default_value = maybe_serialize( $values['item_meta'][ $field_id ] );
249
250
			$new_field = array(
251
				'field_options' => $field->field_options,
252
				'default_value' => $default_value,
253
			);
254
255
			self::prepare_field_update_values( $field, $values, $new_field );
256
257
			FrmField::update( $field_id, $new_field );
258
259
			FrmField::delete_form_transient( $field->form_id );
260
        }
261
		self::clear_form_cache();
262
263
        return $values;
264
    }
265
266
	private static function sanitize_field_opt( $opt, &$value ) {
267
		if ( is_string( $value ) ) {
268
			if ( $opt === 'calc' ) {
269
				$value = strip_tags( $value );
270
			} else {
271
				$value = FrmAppHelper::kses( $value, 'all' );
272
			}
273
			$value = trim( $value );
274
		}
275
	}
276
277
	/**
278
	 * Updating the settings page
279
	 */
280
	private static function get_settings_page_html( $values, &$field ) {
281
		if ( isset( $values['field_options'][ 'custom_html_' . $field->id ] ) ) {
282
			$prev_opts = array();
283
			$fallback_html = isset( $field->field_options['custom_html'] ) ? $field->field_options['custom_html'] : FrmFieldsHelper::get_default_html( $field->type );
284
			$field->field_options['custom_html'] = isset( $values['field_options'][ 'custom_html_' . $field->id ] ) ? $values['field_options'][ 'custom_html_' . $field->id ] : $fallback_html;
285
		} elseif ( $field->type == 'hidden' || $field->type == 'user_id' ) {
286
			$prev_opts = $field->field_options;
287
		}
288
289
		if ( isset( $prev_opts ) ) {
290
			$field->field_options = apply_filters( 'frm_update_form_field_options', $field->field_options, $field, $values );
291
			if ( $prev_opts != $field->field_options ) {
292
				FrmField::update( $field->id, array( 'field_options' => $field->field_options ) );
293
			}
294
		}
295
	}
296
297
	private static function prepare_field_update_values( $field, $values, &$new_field ) {
298
		$field_cols = array(
299
			'field_key'   => '',
300
			'required'    => false,
301
			'type'        => '',
302
			'description' => '',
303
			'options'     => '',
304
			'name'        => '',
305
		);
306
		foreach ( $field_cols as $col => $default ) {
307
			$default = ( $default === '' ) ? $field->{$col} : $default;
308
			$new_field[ $col ] = isset( $values['field_options'][ $col . '_' . $field->id ] ) ? $values['field_options'][ $col . '_' . $field->id ] : $default;
309
		}
310
	}
311
312
	/**
313
	 * Get a list of all form settings that should be translated
314
	 * on a multilingual site.
315
	 *
316
	 * @since 3.06.01
317
	 * @param object $form - The form object
318
	 */
319
	public static function translatable_strings( $form ) {
320
		$strings = array(
321
			'name',
322
			'description',
323
			'submit_value',
324
			'submit_msg',
325
			'success_msg',
326
		);
327
328
		return apply_filters( 'frm_form_strings', $strings, $form );
329
	}
330
331
    /**
332
     * @param string $status
333
     * @return int|boolean
334
     */
335
	public static function set_status( $id, $status ) {
336
        if ( 'trash' == $status ) {
337
			return self::trash( $id );
338
        }
339
340
		$statuses  = array( 'published', 'draft', 'trash' );
341
        if ( ! in_array( $status, $statuses ) ) {
342
            return false;
343
        }
344
345
        global $wpdb;
346
347
		if ( is_array( $id ) ) {
348
			$where = array(
349
				'id' => $id,
350
				'parent_form_id' => $id,
351
				'or' => 1,
352
			);
353
			FrmDb::get_where_clause_and_values( $where );
354
			array_unshift( $where['values'], $status );
355
356
			$query_results = $wpdb->query( $wpdb->prepare( 'UPDATE ' . $wpdb->prefix . 'frm_forms SET status = %s ' . $where['where'], $where['values'] ) ); // WPCS: unprepared SQL ok.
357
        } else {
358
			$query_results = $wpdb->update( $wpdb->prefix . 'frm_forms', array( 'status' => $status ), array( 'id' => $id ) );
359
			$wpdb->update( $wpdb->prefix . 'frm_forms', array( 'status' => $status ), array( 'parent_form_id' => $id ) );
360
        }
361
362
        if ( $query_results ) {
363
			self::clear_form_cache();
364
        }
365
366
        return $query_results;
367
    }
368
369
    /**
370
     * @return int|boolean
371
     */
372
	public static function trash( $id ) {
373
        if ( ! EMPTY_TRASH_DAYS ) {
374
            return self::destroy( $id );
375
        }
376
377
		$form = self::getOne( $id );
378
        if ( ! $form ) {
379
            return false;
380
        }
381
382
        $options = $form->options;
383
        $options['trash_time'] = time();
384
385
		global $wpdb;
386
		$query_results = $wpdb->update(
387
			$wpdb->prefix . 'frm_forms',
388
			array(
389
				'status'  => 'trash',
390
				'options' => serialize( $options ),
391
			),
392
			array(
393
				'id' => $id,
394
			)
395
		);
396
397
		$wpdb->update(
398
			$wpdb->prefix . 'frm_forms',
399
			array(
400
				'status'  => 'trash',
401
				'options' => serialize( $options ),
402
			),
403
			array(
404
				'parent_form_id' => $id,
405
			)
406
		);
407
408
        if ( $query_results ) {
409
			self::clear_form_cache();
410
        }
411
412
        return $query_results;
413
    }
414
415
    /**
416
     * @return int|boolean
417
     */
418
	public static function destroy( $id ) {
419
        global $wpdb;
420
421
		$form = self::getOne( $id );
422
        if ( ! $form ) {
423
            return false;
424
        }
425
		$id = $form->id;
426
427
        // Disconnect the entries from this form
428
		$entries = FrmDb::get_col( $wpdb->prefix . 'frm_items', array( 'form_id' => $id ) );
429
		foreach ( $entries as $entry_id ) {
0 ignored issues
show
Bug introduced by
The expression $entries of type array|null|string|object is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
430
			FrmEntry::destroy( $entry_id );
431
			unset( $entry_id );
432
		}
433
434
        // Disconnect the fields from this form
435
		$wpdb->query( $wpdb->prepare( 'DELETE fi FROM ' . $wpdb->prefix . 'frm_fields AS fi LEFT JOIN ' . $wpdb->prefix . 'frm_forms fr ON (fi.form_id = fr.id) WHERE fi.form_id=%d OR parent_form_id=%d', $id, $id ) );
436
437
		$query_results = $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . $wpdb->prefix . 'frm_forms WHERE id=%d OR parent_form_id=%d', $id, $id ) );
438
        if ( $query_results ) {
439
            // Delete all form actions linked to this form
440
            $action_control = FrmFormActionsController::get_form_actions( 'email' );
441
			$action_control->destroy( $id, 'all' );
442
443
			// Clear form caching
444
			self::clear_form_cache();
445
446
			do_action( 'frm_destroy_form', $id );
447
			do_action( 'frm_destroy_form_' . $id );
448
        }
449
450
        return $query_results;
451
    }
452
453
	/**
454
	 * Delete trashed forms based on how long they have been trashed
455
	 *
456
	 * @return int The number of forms deleted
457
	 */
458
	public static function scheduled_delete( $delete_timestamp = '' ) {
459
		global $wpdb;
460
461
		$trash_forms = FrmDb::get_results( $wpdb->prefix . 'frm_forms', array( 'status' => 'trash' ), 'id, options' );
462
463
		if ( ! $trash_forms ) {
464
			return;
465
		}
466
467
		if ( empty( $delete_timestamp ) ) {
468
			$delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
469
		}
470
471
		$count = 0;
472
		foreach ( $trash_forms as $form ) {
0 ignored issues
show
Bug introduced by
The expression $trash_forms of type array|string|object is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
473
			$form->options = maybe_unserialize( $form->options );
474
			if ( ! isset( $form->options['trash_time'] ) || $form->options['trash_time'] < $delete_timestamp ) {
475
				self::destroy( $form->id );
476
				$count++;
477
			}
478
479
			unset( $form );
480
		}
481
		return $count;
482
	}
483
484
    /**
485
     * @return string form name
486
     */
487
    public static function getName( $id ) {
0 ignored issues
show
Coding Style introduced by
The function name getName is in camel caps, but expected get_name instead as per the coding standard.
Loading history...
488
		$form = FrmDb::check_cache( $id, 'frm_form' );
489
        if ( $form ) {
490
			$r = stripslashes( $form->name );
491
            return $r;
492
        }
493
494
        $query_key = is_numeric( $id ) ? 'id' : 'form_key';
495
        $r = FrmDb::get_var( 'frm_forms', array( $query_key => $id ), 'name' );
496
		$r = stripslashes( $r );
497
498
        return $r;
499
    }
500
501
    /**
502
	 * @since 3.0
503
     * @param string $key
504
     * @return int form id
505
     */
506
	public static function get_id_by_key( $key ) {
507
		return (int) FrmDb::get_var( 'frm_forms', array( 'form_key' => sanitize_title( $key ) ) );
508
    }
509
510
    /**
511
	 * @since 3.0
512
     * @param int $id
513
     * @return string form key
514
     */
515
	public static function get_key_by_id( $id ) {
516
        $id = (int) $id;
517
		$cache = FrmDb::check_cache( $id, 'frm_form' );
518
        if ( $cache ) {
519
            return $cache->form_key;
520
        }
521
522
        $key = FrmDb::get_var( 'frm_forms', array( 'id' => $id ), 'form_key' );
523
524
        return $key;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $key; (array|null|string|object) is incompatible with the return type documented by FrmForm::get_key_by_id of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
525
    }
526
527
	/**
528
	 * If $form is numeric, get the form object
529
	 *
530
	 * @param object|int $form
531
	 * @since 2.0.9
532
	 */
533
	public static function maybe_get_form( &$form ) {
534
		if ( ! is_object( $form ) && ! is_array( $form ) && ! empty( $form ) ) {
535
			$form = self::getOne( $form );
536
		}
537
	}
538
539
    /**
540
     * @return object form
541
     */
542
    public static function getOne( $id, $blog_id = false ) {
0 ignored issues
show
Coding Style introduced by
The function name getOne is in camel caps, but expected get_one instead as per the coding standard.
Loading history...
543
        global $wpdb;
544
545
        if ( $blog_id && is_multisite() ) {
546
            global $wpmuBaseTablePrefix;
547
			$prefix = $wpmuBaseTablePrefix ? $wpmuBaseTablePrefix . $blog_id . '_' : $wpdb->get_blog_prefix( $blog_id );
548
549
			$table_name = $prefix . 'frm_forms';
550
        } else {
551
			$table_name = $wpdb->prefix . 'frm_forms';
552
			$cache = wp_cache_get( $id, 'frm_form' );
553
            if ( $cache ) {
554
				if ( isset( $cache->options ) ) {
555
					$cache->options = maybe_unserialize( $cache->options );
556
                }
557
558
				return stripslashes_deep( $cache );
559
            }
560
        }
561
562
		if ( is_numeric( $id ) ) {
563
            $where = array( 'id' => $id );
564
        } else {
565
            $where = array( 'form_key' => $id );
566
        }
567
568
        $results = FrmDb::get_row( $table_name, $where );
569
570 View Code Duplication
		if ( isset( $results->options ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
571
			FrmDb::set_cache( $results->id, $results, 'frm_form' );
572
			$results->options = maybe_unserialize( $results->options );
573
        }
574
		return stripslashes_deep( $results );
575
    }
576
577
    /**
578
     * @return object|array of objects
579
     */
580
	public static function getAll( $where = array(), $order_by = '', $limit = '' ) {
0 ignored issues
show
Coding Style introduced by
The function name getAll is in camel caps, but expected get_all instead as per the coding standard.
Loading history...
581
		if ( is_array( $where ) && ! empty( $where ) ) {
582
			if ( isset( $where['is_template'] ) && $where['is_template'] && ! isset( $where['status'] ) ) {
583
				// don't get trashed templates
584
				$where['status'] = array( null, '', 'published' );
585
			}
586
587
			$results = FrmDb::get_results( 'frm_forms', $where, '*', compact( 'order_by', 'limit' ) );
588
		} else {
589
			global $wpdb;
590
591
			// the query has already been prepared if this is not an array
592
			$query = 'SELECT * FROM ' . $wpdb->prefix . 'frm_forms' . FrmDb::prepend_and_or_where( ' WHERE ', $where ) . FrmDb::esc_order( $order_by ) . FrmDb::esc_limit( $limit );
593
			$results = $wpdb->get_results( $query ); // WPCS: unprepared SQL ok.
594
		}
595
596 View Code Duplication
		if ( $results ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
597
			foreach ( $results as $result ) {
598
				FrmDb::set_cache( $result->id, $result, 'frm_form' );
599
				$result->options = maybe_unserialize( $result->options );
600
			}
601
		}
602
603
		if ( $limit == ' LIMIT 1' || $limit == 1 ) {
604
			// return the first form object if we are only getting one form
605
			$results = reset( $results );
606
		}
607
608
		return stripslashes_deep( $results );
609
    }
610
611
	/**
612
	 * Get all published forms
613
	 *
614
	 * @since 2.0
615
	 * @return array of forms
616
	 */
617
	public static function get_published_forms( $query = array(), $limit = 999, $inc_children = 'exclude' ) {
618
		$query['is_template'] = 0;
619
		$query['status'] = array( null, '', 'published' );
620
		if ( $inc_children == 'exclude' ) {
621
			$query['parent_form_id'] = array( null, 0 );
622
		}
623
624
		$forms = self::getAll( $query, 'name', $limit );
625
		return $forms;
626
	}
627
628
    /**
629
     * @return int count of forms
630
     */
631
    public static function get_count() {
632
    	global $wpdb;
633
634
    	$cache_key = 'frm_form_counts';
635
636
    	$counts = wp_cache_get( $cache_key, 'frm_form' );
637
    	if ( false !== $counts ) {
638
    	    return $counts;
639
    	}
640
641
		$results = (array) FrmDb::get_results(
642
			'frm_forms',
643
			array(
644
				'or'               => 1,
645
				'parent_form_id'   => null,
646
				'parent_form_id <' => 0,
647
			),
648
			'status, is_template'
649
		);
650
651
		$statuses = array( 'published', 'draft', 'template', 'trash' );
652
    	$counts = array_fill_keys( $statuses, 0 );
653
654
    	foreach ( $results as $row ) {
655
            if ( 'trash' != $row->status ) {
656
    	        if ( $row->is_template ) {
657
					$counts['template']++;
658
    	        } else {
659
					$counts['published']++;
660
    	        }
661
    	    } else {
662
				$counts['trash']++;
663
        	}
664
665
    	    if ( 'draft' == $row->status ) {
666
				$counts['draft']++;
667
    	    }
668
669
			unset( $row );
670
    	}
671
672
    	$counts = (object) $counts;
673
		FrmDb::set_cache( $cache_key, $counts, 'frm_form' );
674
675
    	return $counts;
676
    }
677
678
	/**
679
	 * Clear form caching
680
	 * Called when a form is created, updated, duplicated, or deleted
681
	 * or when the form status is changed
682
	 *
683
	 * @since 2.0.4
684
	 */
685
	public static function clear_form_cache() {
686
		FrmDb::cache_delete_group( 'frm_form' );
687
	}
688
689
    /**
690
     * @return array of errors
691
     */
692
	public static function validate( $values ) {
693
        $errors = array();
694
695
		return apply_filters( 'frm_validate_form', $errors, $values );
696
    }
697
698
	public static function get_params( $form = null ) {
699
		global $frm_vars;
700
701
		if ( ! $form ) {
702
			$form = self::getAll( array(), 'name', 1 );
703
		} else {
704
			self::maybe_get_form( $form );
705
		}
706
707
		if ( isset( $frm_vars['form_params'] ) && is_array( $frm_vars['form_params'] ) && isset( $frm_vars['form_params'][ $form->id ] ) ) {
708
			return $frm_vars['form_params'][ $form->id ];
709
		}
710
711
		$action_var = isset( $_REQUEST['frm_action'] ) ? 'frm_action' : 'action'; // WPCS: CSRF ok.
712
		$action = apply_filters( 'frm_show_new_entry_page', FrmAppHelper::get_param( $action_var, 'new', 'get', 'sanitize_title' ), $form );
713
714
		$default_values = array(
715
			'id'        => '',
716
			'form_name' => '',
717
			'paged'     => 1,
718
			'form'      => $form->id,
719
			'form_id'   => $form->id,
720
			'field_id'  => '',
721
			'search'    => '',
722
			'sort'      => '',
723
			'sdir'      => '',
724
			'action'    => $action,
725
		);
726
727
		$values = array();
728
		$values['posted_form_id'] = FrmAppHelper::get_param( 'form_id', '', 'get', 'absint' );
729
		if ( ! $values['posted_form_id'] ) {
730
			$values['posted_form_id'] = FrmAppHelper::get_param( 'form', '', 'get', 'absint' );
731
		}
732
733
		if ( $form->id == $values['posted_form_id'] ) {
734
			//if there are two forms on the same page, make sure not to submit both
735
			foreach ( $default_values as $var => $default ) {
736
				if ( $var == 'action' ) {
737
					$values[ $var ] = FrmAppHelper::get_param( $action_var, $default, 'get', 'sanitize_title' );
738
				} else {
739
					$values[ $var ] = FrmAppHelper::get_param( $var, $default, 'get', 'sanitize_text_field' );
740
				}
741
				unset( $var, $default );
742
			}
743
		} else {
744
			foreach ( $default_values as $var => $default ) {
745
				$values[ $var ] = $default;
746
				unset( $var, $default );
747
			}
748
		}
749
750
		if ( in_array( $values['action'], array( 'create', 'update' ) ) && ( ! $_POST || ( ! isset( $_POST['action'] ) && ! isset( $_POST['frm_action'] ) ) ) ) { // WPCS: CSRF ok.
751
			$values['action'] = 'new';
752
		}
753
754
		return $values;
755
	}
756
757
	public static function list_page_params() {
758
		$values = array();
759
		$defaults = array(
760
			'template' => 0,
761
			'id'     => '',
762
			'paged'  => 1,
763
			'form'   => '',
764
			'search' => '',
765
			'sort'   => '',
766
			'sdir'   => '',
767
		);
768
		foreach ( $defaults as $var => $default ) {
769
			$values[ $var ] = FrmAppHelper::get_param( $var, $default, 'get', 'sanitize_text_field' );
770
		}
771
772
		return $values;
773
	}
774
775
	public static function get_admin_params( $form = null ) {
776
		$form_id = $form;
777
		if ( $form === null ) {
778
			$form_id = self::get_current_form_id();
779
		} else if ( $form && is_object( $form ) ) {
780
			$form_id = $form->id;
781
		}
782
783
		$values = array();
784
		$defaults = array(
785
			'id'        => '',
786
			'form_name' => '',
787
			'paged'     => 1,
788
			'form'      => $form_id,
789
			'field_id'  => '',
790
			'search'    => '',
791
			'sort'      => '',
792
			'sdir'      => '',
793
			'fid'       => '',
794
			'keep_post' => '',
795
		);
796
		foreach ( $defaults as $var => $default ) {
797
			$values[ $var ] = FrmAppHelper::get_param( $var, $default, 'get', 'sanitize_text_field' );
798
		}
799
800
		return $values;
801
	}
802
803
	public static function get_current_form_id( $default_form = 'none' ) {
804
		if ( 'first' == $default_form ) {
805
			$form = self::get_current_form();
806
		} else {
807
			$form = self::maybe_get_current_form();
808
		}
809
		$form_id = $form ? $form->id : 0;
810
811
		return $form_id;
812
	}
813
814
	public static function maybe_get_current_form( $form_id = 0 ) {
815
		global $frm_vars;
816
817
		if ( isset( $frm_vars['current_form'] ) && $frm_vars['current_form'] && ( ! $form_id || $form_id == $frm_vars['current_form']->id ) ) {
818
			return $frm_vars['current_form'];
819
		}
820
821
		$form_id = FrmAppHelper::get_param( 'form', $form_id, 'get', 'absint' );
822
		if ( $form_id ) {
823
			$form_id = self::set_current_form( $form_id );
824
		}
825
		return $form_id;
826
	}
827
828
	public static function get_current_form( $form_id = 0 ) {
829
		$form = self::maybe_get_current_form( $form_id );
830
		if ( is_numeric( $form ) ) {
831
			 $form = self::set_current_form( $form );
832
		}
833
		return $form;
834
	}
835
836
	public static function set_current_form( $form_id ) {
837
		global $frm_vars;
838
839
		$query = array();
840
		if ( $form_id ) {
841
			$query['id'] = $form_id;
842
		}
843
844
		$frm_vars['current_form'] = self::get_published_forms( $query, 1 );
845
846
		return $frm_vars['current_form'];
847
	}
848
849
	public static function is_form_loaded( $form, $this_load, $global_load ) {
850
		global $frm_vars;
851
		$small_form = new stdClass();
852
		foreach ( array( 'id', 'form_key', 'name' ) as $var ) {
853
			$small_form->{$var} = $form->{$var};
854
			unset( $var );
855
		}
856
857
		$frm_vars['forms_loaded'][] = $small_form;
858
859
		if ( $this_load && empty( $global_load ) ) {
860
			$global_load = true;
861
			$frm_vars['load_css'] = true;
862
		}
863
864
		return ( ( ! isset( $frm_vars['css_loaded'] ) || ! $frm_vars['css_loaded'] ) && $global_load );
865
	}
866
867
	public static function show_submit( $form ) {
868
		$show = ( ! $form->is_template && $form->status == 'published' && ! FrmAppHelper::is_admin() );
869
		$show = apply_filters( 'frm_show_submit_button', $show, $form );
870
		return $show;
871
	}
872
873
	/**
874
	 * @since 2.3
875
	 */
876
	public static function get_option( $atts ) {
877
		$form = $atts['form'];
878
		return isset( $form->options[ $atts['option'] ] ) ? $form->options[ $atts['option'] ] : $atts['default'];
879
	}
880
881
	/**
882
	 * @deprecated 3.0
883
	 * @codeCoverageIgnore
884
	 *
885
	 * @param string $key
886
	 * @return int form id
887
	 */
888
	public static function getIdByKey( $key ) {
0 ignored issues
show
Coding Style introduced by
The function name getIdByKey is in camel caps, but expected get_id_by_key instead as per the coding standard.
Loading history...
889
		return FrmFormDeprecated::getIdByKey( $key );
1 ignored issue
show
Deprecated Code introduced by
The method FrmFormDeprecated::getIdByKey() has been deprecated with message: 2.03.05

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
890
	}
891
892
	/**
893
	 * @deprecated 3.0
894
	 * @codeCoverageIgnore
895
	 */
896
	public static function getKeyById( $id ) {
0 ignored issues
show
Coding Style introduced by
The function name getKeyById is in camel caps, but expected get_key_by_id instead as per the coding standard.
Loading history...
897
		return FrmFormDeprecated::getKeyById( $id );
1 ignored issue
show
Deprecated Code introduced by
The method FrmFormDeprecated::getKeyById() has been deprecated with message: 2.03.05

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
898
	}
899
}
900