Completed
Push — master ( 6ea130...d307f6 )
by Stephanie
02:36
created

FrmEntriesHelper::prepare_display_value()   C

Complexity

Conditions 13
Paths 84

Size

Total Lines 50
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 25
nc 84
nop 3
dl 0
loc 50
rs 5.3808
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
if ( ! defined('ABSPATH') ) {
3
	die( 'You are not allowed to call this page directly.' );
4
}
5
6
class FrmEntriesHelper {
7
8
    public static function setup_new_vars( $fields, $form = '', $reset = false, $args = array() ) {
9
		$values = array( 'name' => '', 'description' => '', 'item_key' => '' );
10
11
        $values['fields'] = array();
12
        if ( empty($fields) ) {
13
            return apply_filters('frm_setup_new_entry', $values);
14
        }
15
16
        foreach ( (array) $fields as $field ) {
17
			self::prepare_field_default_value( $field );
18
            $new_value = self::get_field_value_for_new_entry( $field, $reset, $args );
19
20
            $field_array = array(
21
                'id' => $field->id,
22
                'value' => $new_value,
23
                'default_value' => $field->default_value,
24
                'name' => $field->name,
25
                'description' => $field->description,
26
                'type' => apply_filters('frm_field_type', $field->type, $field, $new_value),
27
                'options' => $field->options,
28
                'required' => $field->required,
29
                'field_key' => $field->field_key,
30
                'field_order' => $field->field_order,
31
                'form_id' => $field->form_id,
32
				'parent_form_id' => isset( $args['parent_form_id'] ) ? $args['parent_form_id'] : $field->form_id,
33
	            'reset_value' => $reset,
34
				'in_embed_form' => isset( $args['in_embed_form'] ) ? $args['in_embed_form'] : '0',
35
            );
36
37
            $opt_defaults = FrmFieldsHelper::get_default_field_opts($field_array['type'], $field, true);
38
            $opt_defaults['required_indicator'] = '';
39
			$opt_defaults['original_type'] = $field->type;
40
41
			foreach ( $opt_defaults as $opt => $default_opt ) {
42
                $field_array[ $opt ] = ( isset( $field->field_options[ $opt ] ) && $field->field_options[ $opt ] != '' ) ? $field->field_options[ $opt ] : $default_opt;
43
                unset($opt, $default_opt);
44
            }
45
46
            unset($opt_defaults);
47
48
            if ( $field_array['custom_html'] == '' ) {
49
                $field_array['custom_html'] = FrmFieldsHelper::get_default_html($field->type);
50
            }
51
52
            $field_array = apply_filters('frm_setup_new_fields_vars', $field_array, $field, $args );
53
            $field_array = array_merge( $field->field_options, $field_array );
54
55
            $values['fields'][] = $field_array;
56
57
            if ( ! $form || ! isset($form->id) ) {
58
                $form = FrmForm::getOne($field->form_id);
59
            }
60
        }
61
62
		$form->options = maybe_unserialize( $form->options );
63
		if ( is_array( $form->options ) ) {
64
			$values = array_merge( $values, $form->options );
65
		}
66
67
		$form_defaults = FrmFormsHelper::get_default_opts();
68
69
		$frm_settings = FrmAppHelper::get_settings();
70
		$form_defaults['custom_style']  = ( $frm_settings->load_style != 'none' );
71
72
		$values = array_merge( $form_defaults, $values );
73
74
		return apply_filters( 'frm_setup_new_entry', $values );
75
    }
76
77
	/**
78
	 * @since 2.05
79
	 */
80
	private static function prepare_field_default_value( &$field ) {
81
		//If checkbox, multi-select dropdown, or checkbox data from entries field, the value should be an array
82
		$return_array = FrmField::is_field_with_multiple_values( $field );
83
84
		// Do any shortcodes in default value and allow customization of default value
85
		$field->default_value = apply_filters( 'frm_get_default_value', $field->default_value, $field, true, $return_array );
86
		// Calls FrmProFieldsHelper::get_default_value
87
	}
88
89
	/**
90
	* Set the value for each field
91
	* This function is used when the form is first loaded and on all page turns *for a new entry*
92
	*
93
	* @since 2.0.13
94
	*
95
	* @param object $field - this is passed by reference since it is an object
96
	* @param boolean $reset
97
	* @param array $args
98
	* @return string|array $new_value
99
	*/
100
	private static function get_field_value_for_new_entry( $field, $reset, $args ) {
101
		$new_value = $field->default_value;
102
103
		if ( ! $reset && self::value_is_posted( $field, $args ) ) {
104
			self::get_posted_value( $field, $new_value, $args );
105
		} else if ( FrmField::is_option_true( $field, 'clear_on_focus' ) ) {
106
			// If clear on focus is selected, the value should be blank (unless it was posted, of course)
107
108
			// TODO: move to Pro
109
			if ( 'address' == $field->type && isset( $new_value['country'] ) ) {
110
				$new_value = array( 'country' => $new_value['country'] );
111
			} else {
112
				$new_value = '';
113
			}
114
		}
115
116
		if ( ! is_array( $new_value ) ) {
117
			$new_value = str_replace('"', '&quot;', $new_value);
118
		}
119
120
		return $new_value;
121
	}
122
123
	/**
124
	* Check if a field has a posted value
125
	*
126
	* @since 2.01.0
127
	* @param object $field
128
	* @param array $args
129
	* @return boolean $value_is_posted
130
	*/
131
	public static function value_is_posted( $field, $args ) {
132
		$value_is_posted = false;
133
		if ( $_POST ) {
134
			$repeating = isset( $args['repeating'] ) && $args['repeating'];
135
			if ( $repeating ) {
136
				if ( isset( $_POST['item_meta'][ $args['parent_field_id'] ][ $args['key_pointer'] ][ $field->id ] ) ) {
137
					$value_is_posted = true;
138
				}
139
			} else if ( isset( $_POST['item_meta'][ $field->id ] ) ) {
140
				$value_is_posted = true;
141
			}
142
		}
143
		return $value_is_posted;
144
	}
145
146
	public static function setup_edit_vars( $values, $record ) {
147
		$values['item_key'] = FrmAppHelper::get_post_param( 'item_key', $record->item_key, 'sanitize_title' );
148
        $values['form_id'] = $record->form_id;
149
        $values['is_draft'] = $record->is_draft;
150
        return apply_filters('frm_setup_edit_entry_vars', $values, $record);
151
    }
152
153
    public static function get_admin_params( $form = null ) {
154
		_deprecated_function( __FUNCTION__, '2.0.9', 'FrmForm::get_admin_params' );
155
		return FrmForm::set_current_form( $form );
156
    }
157
158
	public static function set_current_form( $form_id ) {
159
		_deprecated_function( __FUNCTION__, '2.0.9', 'FrmForm::set_current_form' );
160
		return FrmForm::set_current_form( $form_id );
161
	}
162
163
	public static function get_current_form( $form_id = 0 ) {
164
		_deprecated_function( __FUNCTION__, '2.0.9', 'FrmForm::get_current_form' );
165
		return FrmForm::get_current_form( $form_id );
166
	}
167
168
    public static function get_current_form_id() {
169
		_deprecated_function( __FUNCTION__, '2.0.9', 'FrmForm::get_current_form_id' );
170
		return FrmForm::get_current_form_id();
171
    }
172
173
    public static function maybe_get_entry( &$entry ) {
174
		_deprecated_function( __FUNCTION__, '2.0.9', 'FrmEntry::maybe_get_entry' );
175
		FrmEntry::maybe_get_entry( $entry );
176
    }
177
178
	public static function replace_default_message( $message, $atts ) {
179
        if ( strpos($message, '[default-message') === false &&
180
            strpos($message, '[default_message') === false &&
181
            ! empty( $message ) ) {
182
            return $message;
183
        }
184
185
        if ( empty($message) ) {
186
            $message = '[default-message]';
187
        }
188
189
        preg_match_all("/\[(default-message|default_message)\b(.*?)(?:(\/))?\]/s", $message, $shortcodes, PREG_PATTERN_ORDER);
190
191
        foreach ( $shortcodes[0] as $short_key => $tag ) {
192
			$add_atts = FrmShortcodeHelper::get_shortcode_attribute_array( $shortcodes[2][ $short_key ] );
193
			if ( ! empty( $add_atts ) ) {
194
                $this_atts = array_merge($atts, $add_atts);
195
            } else {
196
                $this_atts = $atts;
197
            }
198
199
			$default = FrmEntriesController::show_entry_shortcode( $this_atts );
200
201
            // Add the default message
202
            $message = str_replace( $shortcodes[0][ $short_key ], $default, $message );
203
        }
204
205
        return $message;
206
    }
207
208
	public static function prepare_display_value( $entry, $field, $atts ) {
209
		$field_value = isset( $entry->metas[ $field->id ] ) ? $entry->metas[ $field->id ] : false;
210
211
        if ( FrmAppHelper::pro_is_installed() ) {
212
			FrmProEntriesHelper::get_dynamic_list_values( $field, $entry, $field_value );
213
        }
214
215
        if ( $field->form_id == $entry->form_id || empty($atts['embedded_field_id']) ) {
216
            return self::display_value($field_value, $field, $atts);
217
        }
218
219
        // this is an embeded form
220
        $val = '';
221
222
	    if ( strpos($atts['embedded_field_id'], 'form') === 0 ) {
223
            //this is a repeating section
224
			$child_entries = FrmEntry::getAll( array( 'it.parent_item_id' => $entry->id ) );
225
        } else {
226
            // get all values for this field
227
	        $child_values = isset( $entry->metas[ $atts['embedded_field_id'] ] ) ? $entry->metas[ $atts['embedded_field_id'] ] : false;
228
229
            if ( $child_values ) {
230
	            $child_entries = FrmEntry::getAll( array( 'it.id' => (array) $child_values ) );
231
	        }
232
	    }
233
234
	    $field_value = array();
235
236
        if ( ! isset($child_entries) || ! $child_entries || ! FrmAppHelper::pro_is_installed() ) {
237
            return $val;
238
        }
239
240
        foreach ( $child_entries as $child_entry ) {
241
            $atts['item_id'] = $child_entry->id;
242
            $atts['post_id'] = $child_entry->post_id;
243
244
            // get the value for this field -- check for post values as well
245
            $entry_val = FrmProEntryMetaHelper::get_post_or_meta_value($child_entry, $field);
246
247
            if ( $entry_val ) {
248
                // foreach entry get display_value
249
                $field_value[] = self::display_value($entry_val, $field, $atts);
250
            }
251
252
            unset($child_entry);
253
        }
254
255
        $val = implode(', ', (array) $field_value );
256
		return FrmAppHelper::kses( $val );
257
    }
258
259
    /**
260
     * Prepare the saved value for display
261
     * @return string
262
     */
263
	public static function display_value( $value, $field, $atts = array() ) {
264
265
        $defaults = array(
266
            'type' => '', 'html' => false, 'show_filename' => true,
267
            'truncate' => false, 'sep' => ', ', 'post_id' => 0,
268
            'form_id' => $field->form_id, 'field' => $field, 'keepjs' => 0,
269
			'return_array' => false,
270
        );
271
272
        $atts = wp_parse_args( $atts, $defaults );
273
        $atts = apply_filters('frm_display_value_atts', $atts, $field, $value);
274
275
        if ( ! isset($field->field_options['post_field']) ) {
276
            $field->field_options['post_field'] = '';
277
        }
278
279
        if ( ! isset($field->field_options['custom_field']) ) {
280
            $field->field_options['custom_field'] = '';
281
        }
282
283
        if ( FrmAppHelper::pro_is_installed() && $atts['post_id'] && ( $field->field_options['post_field'] || $atts['type'] == 'tag' ) ) {
284
            $atts['pre_truncate'] = $atts['truncate'];
285
            $atts['truncate'] = true;
286
            $atts['exclude_cat'] = isset($field->field_options['exclude_cat']) ? $field->field_options['exclude_cat'] : 0;
287
288
            $value = FrmProEntryMetaHelper::get_post_value($atts['post_id'], $field->field_options['post_field'], $field->field_options['custom_field'], $atts);
289
            $atts['truncate'] = $atts['pre_truncate'];
290
        }
291
292
        if ( $value == '' ) {
293
            return $value;
294
        }
295
296
        $value = apply_filters('frm_display_value_custom', maybe_unserialize($value), $field, $atts);
297
		$value = apply_filters( 'frm_display_' . $field->type . '_value_custom', $value, compact( 'field', 'atts' ) );
298
299
        $new_value = '';
300
301
        if ( is_array($value) && $atts['type'] != 'file' ) {
302
            foreach ( $value as $val ) {
303
                if ( is_array($val) ) {
304
					//TODO: add options for display (li or ,)
305
                    $new_value .= implode($atts['sep'], $val);
306
                    if ( $atts['type'] != 'data' ) {
307
                        $new_value .= '<br/>';
308
                    }
309
                }
310
                unset($val);
311
            }
312
        }
313
314
        if ( ! empty($new_value) ) {
315
            $value = $new_value;
316
        } else if ( is_array($value) && $atts['type'] != 'file' && ! $atts['return_array'] ) {
317
            $value = implode($atts['sep'], $value);
318
        }
319
320
        if ( $atts['truncate'] && $atts['type'] != 'image' ) {
321
            $value = FrmAppHelper::truncate($value, 50);
322
        }
323
324
		if ( ! $atts['keepjs'] && ! is_array( $value ) ) {
325
			$value = FrmAppHelper::kses( $value );
326
		}
327
328
        return apply_filters('frm_display_value', $value, $field, $atts);
329
    }
330
331
	public static function set_posted_value( $field, $value, $args ) {
332
        // If validating a field with "other" opt, set back to prev value now
333
        if ( isset( $args['other'] ) && $args['other'] ) {
334
            $value = $args['temp_value'];
335
        }
336
        if ( empty($args['parent_field_id']) ) {
337
            $_POST['item_meta'][ $field->id ] = $value;
338
        } else {
339
            $_POST['item_meta'][ $args['parent_field_id'] ][ $args['key_pointer'] ][ $field->id ] = $value;
340
        }
341
    }
342
343
	public static function get_posted_value( $field, &$value, $args ) {
344
		$field_id = is_object( $field ) ? $field->id : $field;
345
346
        if ( empty($args['parent_field_id']) ) {
347
            $value = isset( $_POST['item_meta'][ $field_id ] ) ? $_POST['item_meta'][ $field_id ] : '';
348
        } else {
349
            $value = isset( $_POST['item_meta'][ $args['parent_field_id'] ][ $args['key_pointer'] ][ $field_id ] ) ? $_POST['item_meta'][ $args['parent_field_id'] ][ $args['key_pointer'] ][ $field_id ] : '';
350
        }
351
		FrmAppHelper::sanitize_value( 'wp_kses_post', $value );
352
		$value = stripslashes_deep( $value );
353
    }
354
355
    /**
356
    * Check if field has an "Other" option and if any other values are posted
357
    *
358
    * @since 2.0
359
    *
360
    * @param object $field
361
    * @param string|array $value
362
    * @param array $args
363
    */
364
    public static function maybe_set_other_validation( $field, &$value, &$args ) {
365
        $args['other'] = false;
366
        if ( ! $value || empty( $value ) || ! FrmAppHelper::pro_is_installed() ) {
367
            return;
368
        }
369
370
        // Get other value for fields in repeating section
371
        self::set_other_repeating_vals( $field, $value, $args );
372
373
        // Check if there are any posted "Other" values
374
		if ( FrmField::is_option_true( $field, 'other' ) && isset( $_POST['item_meta']['other'][ $field->id ] ) ) {
375
376
            // Save original value
377
            $args['temp_value'] = $value;
378
            $args['other'] = true;
379
            $other_vals = stripslashes_deep( $_POST['item_meta']['other'][ $field->id ] );
380
381
            // Set the validation value now
382
            self::set_other_validation_val( $value, $other_vals, $field, $args );
383
        }
384
    }
385
386
    /**
387
    * Sets radio or checkbox value equal to "other" value if it is set - FOR REPEATING SECTIONS
388
    *
389
    * @since 2.0
390
    *
391
    * @param object $field
392
    * @param string|array $value
393
    * @param array $args
394
    */
395
    public static function set_other_repeating_vals( $field, &$value, &$args ) {
396
        if ( ! $args['parent_field_id'] ) {
397
            return;
398
        }
399
400
        // Check if there are any other posted "other" values for this field
401
		if ( FrmField::is_option_true( $field, 'other' ) && isset( $_POST['item_meta'][ $args['parent_field_id'] ][ $args['key_pointer'] ]['other'][ $field->id ] ) ) {
402
            // Save original value
403
            $args['temp_value'] = $value;
404
            $args['other'] = true;
405
406
            $other_vals = $_POST['item_meta'][ $args['parent_field_id'] ][ $args['key_pointer'] ]['other'][ $field->id ];
407
408
            // Set the validation value now
409
            self::set_other_validation_val( $value, $other_vals, $field, $args );
410
        }
411
    }
412
413
    /**
414
    * Modify value used for validation
415
    * This function essentially removes the "Other" radio or checkbox value from the $value being validated.
416
    * It also adds any text from the free text fields to the value
417
    *
418
    * Needs to accommodate for times when other opt is selected, but no other free text is entered
419
    *
420
    * @since 2.0
421
    *
422
    * @param string|array $value
423
    * @param string|array $other_vals (usually of posted values)
424
    * @param object $field
425
    * @param array $args
426
    */
427
    public static function set_other_validation_val( &$value, $other_vals, $field, &$args ) {
428
        // Checkboxes and multi-select dropdowns
429
        if ( is_array( $value ) && $field->type == 'checkbox' ) {
430
            // Combine "Other" values with checked values. "Other" values will override checked box values.
431
            $value = array_merge( $value, $other_vals );
432
            $value = array_filter( $value );
433
            if ( count( $value ) == 0 ) {
434
                $value = '';
435
            }
436
        } else {
437
			// Radio and dropdowns
438
            $other_key = array_filter( array_keys($field->options), 'is_string');
439
            $other_key = reset( $other_key );
440
441
            // Multi-select dropdown
442
            if ( is_array( $value ) ) {
443
                $o_key = array_search( $field->options[ $other_key ], $value );
444
445
				if ( $o_key !== false ) {
446
					// Modify the original value so other key will be preserved
447
					$value[ $other_key ] = $value[ $o_key ];
448
449
					// By default, the array keys will be numeric for multi-select dropdowns
450
					// If going backwards and forwards between pages, the array key will match the other key
451
					if ( $o_key != $other_key ) {
452
						unset( $value[ $o_key ] );
453
					}
454
455
					$args['temp_value'] = $value;
456
					$value[ $other_key ] = reset( $other_vals );
457
				}
458
            } else if ( $field->options[ $other_key ] == $value ) {
459
                $value = $other_vals;
460
            }
461
        }
462
    }
463
464
	public static function enqueue_scripts( $params ) {
465
		_deprecated_function( __FUNCTION__, '2.0.9', 'FrmFormsController::enqueue_scripts' );
466
		FrmFormsController::enqueue_scripts( $params );
467
	}
468
469
    // Add submitted values to a string for spam checking
470
	public static function entry_array_to_string( $values ) {
471
        $content = '';
472
		foreach ( $values['item_meta'] as $val ) {
473
			if ( $content != '' ) {
474
				$content .= "\n\n";
475
			}
476
477
			if ( is_array($val) ) {
478
				$val = FrmAppHelper::array_flatten( $val );
479
				$val = implode( ', ', $val );
480
			}
481
482
			$content .= $val;
483
		}
484
485
		return $content;
486
    }
487
488
	/**
489
	 * Get the browser from the user agent
490
	 *
491
	 * @since 2.04
492
	 *
493
	 * @param string $u_agent
494
	 *
495
	 * @return string
496
	 */
497
	public static function get_browser( $u_agent ) {
498
		$bname = __( 'Unknown', 'formidable' );
499
		$platform = __( 'Unknown', 'formidable' );
500
		$ub = '';
501
502
		// Get the operating system
503
		if ( preg_match( '/windows|win32/i', $u_agent ) ) {
504
			$platform = 'Windows';
505
		} else if ( preg_match( '/android/i', $u_agent ) ) {
506
			$platform = 'Android';
507
		} else if ( preg_match( '/linux/i', $u_agent ) ) {
508
			$platform = 'Linux';
509
		} else if ( preg_match( '/macintosh|mac os x/i', $u_agent ) ) {
510
			$platform = 'OS X';
511
		}
512
513
		$agent_options = array(
514
			'Chrome'   => 'Google Chrome',
515
			'Safari'   => 'Apple Safari',
516
			'Opera'    => 'Opera',
517
			'Netscape' => 'Netscape',
518
			'Firefox'  => 'Mozilla Firefox',
519
		);
520
521
		// Next get the name of the useragent yes seperately and for good reason
522
		if ( strpos( $u_agent, 'MSIE' ) !== false && strpos( $u_agent, 'Opera' ) === false ) {
523
			$bname = 'Internet Explorer';
524
			$ub = 'MSIE';
525
		} else {
526
			foreach ( $agent_options as $agent_key => $agent_name ) {
527
				if ( strpos( $u_agent, $agent_key ) !== false ) {
528
					$bname = $agent_name;
529
					$ub = $agent_key;
530
					break;
531
				}
532
			}
533
		}
534
535
		// finally get the correct version number
536
		$known = array( 'Version', $ub, 'other' );
537
		$pattern = '#(?<browser>' . join( '|', $known ) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
538
		preg_match_all( $pattern, $u_agent, $matches ); // get the matching numbers
539
540
		// see how many we have
541
		$i = count($matches['browser']);
542
543
		if ( $i > 1 ) {
544
			//we will have two since we are not using 'other' argument yet
545
			//see if version is before or after the name
546
			if ( strripos( $u_agent, 'Version' ) < strripos( $u_agent, $ub ) ) {
547
				$version = $matches['version'][0];
548
			} else {
549
				$version = $matches['version'][1];
550
			}
551
		} else if ( $i === 1 ) {
552
			$version = $matches['version'][0];
553
		} else {
554
			$version = '';
555
		}
556
557
		// check if we have a number
558
		if ( $version == '' ) {
559
			$version = '?';
560
		}
561
562
		return $bname . ' ' . $version . ' / ' . $platform;
563
	}
564
565
}
566