Completed
Push — master ( d10a7f...629a27 )
by Zack
9s
created

GVCommon::has_shortcode_r()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 31
rs 4.909
cc 9
eloc 16
nc 8
nop 2
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 19 and the first side effect is on line 16.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Set of common functions to separate main plugin from Gravity Forms API and other cross-plugin methods
4
 *
5
 * @package   GravityView
6
 * @license   GPL2+
7
 * @author    Katz Web Services, Inc.
8
 * @link      http://gravityview.co
9
 * @copyright Copyright 2014, Katz Web Services, Inc.
10
 *
11
 * @since 1.5.2
12
 */
13
14
/** If this file is called directly, abort. */
15
if ( ! defined( 'ABSPATH' ) ) {
16
	die;
17
}
18
19
class GVCommon {
20
21
	/**
22
	 * Returns the form object for a given Form ID.
23
	 *
24
	 * @access public
25
	 * @param mixed $form_id
26
	 * @return mixed False: no form ID specified or Gravity Forms isn't active. Array: Form returned from Gravity Forms
27
	 */
28
	public static function get_form( $form_id ) {
29
		if ( empty( $form_id ) ) {
30
			return false;
31
		}
32
33
		// Only get_form_meta is cached. ::facepalm::
34
		if ( class_exists( 'RGFormsModel' ) ) {
35
			return GFFormsModel::get_form_meta( $form_id );
36
		}
37
38
		if ( class_exists( 'GFAPI' ) ) {
39
			return GFAPI::get_form( $form_id );
40
		}
41
42
		return false;
43
	}
44
45
	/**
46
	 * Alias of GravityView_Roles_Capabilities::has_cap()
47
	 *
48
	 * @since 1.15
49
	 *
50
	 * @see GravityView_Roles_Capabilities::has_cap()
51
	 *
52
	 * @param string|array $caps Single capability or array of capabilities
53
	 * @param int $object_id (optional) Parameter can be used to check for capabilities against a specific object, such as a post or user
54
	 * @param int|null $user_id (optional) Check the capabilities for a user who is not necessarily the currently logged-in user
55
	 *
56
	 * @return bool True: user has at least one passed capability; False: user does not have any defined capabilities
57
	 */
58
	public static function has_cap( $caps = '', $object_id = null, $user_id = null ) {
59
		return GravityView_Roles_Capabilities::has_cap( $caps, $object_id, $user_id );
60
	}
61
62
	/**
63
	 * Return a Gravity Forms field array, whether using GF 1.9 or not
64
	 *
65
	 * @since 1.7
66
	 *
67
	 * @param array|GF_Fields $field Gravity Forms field or array
68
	 * @return array Array version of $field
69
	 */
70
	public static function get_field_array( $field ) {
71
72
		if ( class_exists( 'GF_Fields' ) ) {
73
74
			$field_object = GF_Fields::create( $field );
75
76
			// Convert the field object in 1.9 to an array for backward compatibility
77
			$field_array = get_object_vars( $field_object );
78
79
		} else {
80
			$field_array = $field;
81
		}
82
83
		return $field_array;
84
	}
85
86
	/**
87
	 * Get all existing Views
88
	 *
89
	 * @since  1.5.4
90
	 * @since  TODO Added $args array
91
	 *
92
	 * @param array $args Pass custom array of args, formatted as if for `get_posts()`
93
	 *
94
	 * @return array Array of Views as `WP_Post`. Empty array if none found.
95
	 */
96
	public static function get_all_views( $args = array() ) {
97
98
		$default_params = array(
99
			'post_type' => 'gravityview',
100
			'posts_per_page' => -1,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set posts_per_page to -1 ever.
Loading history...
101
			'post_status' => 'publish',
102
		);
103
104
		$params = wp_parse_args( $args, $default_params );
105
106
		/**
107
		 * @filter `gravityview/get_all_views/params` Modify the parameters sent to get all views.
108
		 * @param[in,out]  array $params Array of parameters to pass to `get_posts()`
109
		 */
110
		$views_params = apply_filters( 'gravityview/get_all_views/params', $params );
111
112
		$views = get_posts( $views_params );
113
114
		return $views;
115
	}
116
117
118
	/**
119
	 * Get the form array for an entry based only on the entry ID
120
	 * @param  int|string $entry_slug Entry slug
121
	 * @return array           Gravity Forms form array
122
	 */
123
	public static function get_form_from_entry_id( $entry_slug ) {
124
125
		$entry = self::get_entry( $entry_slug, true );
126
127
		$form = self::get_form( $entry['form_id'] );
128
129
		return $form;
130
	}
131
132
	/**
133
	 * Check whether a form has product fields
134
	 *
135
	 * @since 1.16
136
	 *
137
	 * @param array $form Gravity Forms form array
138
	 *
139
	 * @return bool|GF_Field[]
140
	 */
141
	public static function has_product_field( $form = array() ) {
142
143
		$product_fields = apply_filters( 'gform_product_field_types', array( 'option', 'quantity', 'product', 'total', 'shipping', 'calculation', 'price' ) );
144
145
		$fields = GFAPI::get_fields_by_type( $form, $product_fields );
146
147
		return empty( $fields ) ? false : $fields;
148
	}
149
150
	/**
151
	 * Get the entry ID from the entry slug, which may or may not be the entry ID
152
	 *
153
	 * @since  1.5.2
154
	 * @param  string $slug The entry slug, as returned by GravityView_API::get_entry_slug()
155
	 * @return int|null       The entry ID, if exists; `NULL` if not
156
	 */
157
	public static function get_entry_id_from_slug( $slug ) {
158
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
159
160
		$search_criteria = array(
161
			'field_filters' => array(
162
				array(
163
					'key' => 'gravityview_unique_id', // Search the meta values
164
					'value' => $slug,
165
					'operator' => 'is',
166
					'type' => 'meta',
167
				),
168
			)
169
		);
170
171
		// Limit to one for speed
172
		$paging = array(
173
			'page_size' => 1,
174
		);
175
176
		$results = GFAPI::get_entries( 0, $search_criteria, null, $paging );
177
178
		$result = ( ! empty( $results ) && ! empty( $results[0]['id'] ) ) ? $results[0]['id'] : null;
179
180
		return $result;
181
	}
182
183
184
	/**
185
	 * Returns the list of available forms
186
	 *
187
	 * @access public
188
	 * @param mixed $form_id
0 ignored issues
show
Bug introduced by
There is no parameter named $form_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
189
	 * @return array Empty array if GFAPI isn't available or no forms. Otherwise, associative array with id, title keys
190
	 */
191
	public static function get_forms() {
192
		$forms = array();
193
		if ( class_exists( 'GFAPI' ) ) {
194
			$gf_forms = GFAPI::get_forms();
195
			foreach ( $gf_forms as $form ) {
196
				$forms[] = array(
197
					'id' => $form['id'],
198
					'title' => $form['title'],
199
				);
200
			}
201
		}
202
		return $forms;
203
	}
204
205
	/**
206
	 * Return array of fields' id and label, for a given Form ID
207
	 *
208
	 * @access public
209
	 * @param string|array $form_id (default: '') or $form object
0 ignored issues
show
Bug introduced by
There is no parameter named $form_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
210
	 * @return array
211
	 */
212
	public static function get_form_fields( $form = '', $add_default_properties = false, $include_parent_field = true ) {
213
214
		if ( ! is_array( $form ) ) {
215
			$form = self::get_form( $form );
216
		}
217
218
		$fields = array();
219
		$has_product_fields = false;
220
		$has_post_fields = false;
221
		$has_quiz_fields = false;
222
		$has_poll_fields = false;
223
224
		// If GF_Field exists, we're using GF 1.9+, where add_default_properties has been deprecated.
225
		if ( false === class_exists( 'GF_Field' ) && $add_default_properties ) {
226
			$form = RGFormsModel::add_default_properties( $form );
227
		}
228
229
		if ( $form ) {
230
			foreach ( $form['fields'] as $field ) {
231
				if ( $include_parent_field || empty( $field['inputs'] ) ) {
232
					$fields[ $field['id'] ] = array(
233
						'label' => rgar( $field, 'label' ),
234
						'parent' => null,
235
						'type' => rgar( $field, 'type' ),
236
						'adminLabel' => rgar( $field, 'adminLabel' ),
237
						'adminOnly' => rgar( $field, 'adminOnly' ),
238
					);
239
				}
240
241
				if ( $add_default_properties && ! empty( $field['inputs'] ) ) {
242
					foreach ( $field['inputs'] as $input ) {
243
                        /**
244
                         * @hack
245
                         * In case of email/email confirmation, the input for email has the same id as the parent field
246
                         */
247
                        if( 'email' == rgar( $field, 'type' ) && false === strpos( $input['id'], '.' ) ) {
248
                            continue;
249
                        }
250
						$fields[ (string)$input['id'] ] = array(
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
251
							'label' => rgar( $input, 'label' ),
252
							'customLabel' => rgar( $input, 'customLabel' ),
253
							'parent' => $field,
254
							'type' => rgar( $field, 'type' ),
255
							'adminLabel' => rgar( $field, 'adminLabel' ),
256
							'adminOnly' => rgar( $field, 'adminOnly' ),
257
						);
258
					}
259
				}
260
261
				/** @since 1.14 */
262
				if( 'list' === $field['type'] && !empty( $field['enableColumns'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
263
264
					foreach ( (array)$field['choices'] as $key => $input ) {
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
265
266
						$input_id = sprintf( '%d.%d', $field['id'], $key ); // {field_id}.{column_key}
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
267
268
						$fields[ $input_id ] = array(
269
							'label'       => rgar( $input, 'text' ),
270
							'customLabel' => '',
271
							'parent'      => $field,
272
							'type'        => rgar( $field, 'type' ),
273
							'adminLabel'  => rgar( $field, 'adminLabel' ),
274
							'adminOnly'   => rgar( $field, 'adminOnly' ),
275
						);
276
					}
277
				}
278
279
				/**
280
				 * @since 1.8
281
				 */
282
				if( 'quiz' === $field['type'] ) {
283
					$has_quiz_fields = true;
284
				}
285
286
				/**
287
				 * @since 1.8
288
				 */
289
				if( 'poll' === $field['type'] ) {
290
					$has_poll_fields = true;
291
				}
292
293
				if( GFCommon::is_product_field( $field['type'] ) ){
294
					$has_product_fields = true;
295
				}
296
297
				/**
298
				 * @hack Version 1.9
299
				 */
300
				$field_for_is_post_field = class_exists( 'GF_Fields' ) ? (object) $field : (array) $field;
301
302
				if ( GFCommon::is_post_field( $field_for_is_post_field ) ) {
303
					$has_post_fields = true;
304
				}
305
			}
306
		}
307
308
		/**
309
		 * @since 1.7
310
		 */
311
		if ( $has_post_fields ) {
312
			$fields['post_id'] = array(
313
				'label' => __( 'Post ID', 'gravityview' ),
314
				'type' => 'post_id',
315
			);
316
		}
317
318
		if ( $has_product_fields ) {
319
320
			$payment_fields = GravityView_Fields::get_all( 'pricing' );
321
322
			foreach ( $payment_fields as $payment_field ) {
323
				if( isset( $fields["{$payment_field->name}"] ) ) {
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
324
					continue;
325
				}
326
				$fields["{$payment_field->name}"] = array(
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
327
					'label' => $payment_field->label,
328
					'desc' => $payment_field->description,
329
					'type' => $payment_field->name,
330
				);
331
			}
332
		}
333
334
		/**
335
		 * @since 1.8
336
		 */
337
		if( $has_quiz_fields ) {
338
339
			$fields['gquiz_score']   = array(
340
				'label' => __( 'Quiz Score Total', 'gravityview' ),
341
				'type'  => 'quiz_score',
342
				'desc'  => __( 'Displays the number of correct Quiz answers the user submitted.', 'gravityview' ),
343
			);
344
			$fields['gquiz_percent'] = array(
345
				'label' => __( 'Quiz Percentage Grade', 'gravityview' ),
346
				'type'  => 'quiz_percent',
347
				'desc'  => __( 'Displays the percentage of correct Quiz answers the user submitted.', 'gravityview' ),
348
			);
349
			$fields['gquiz_grade']   = array(
350
				/* translators: This is a field type used by the Gravity Forms Quiz Addon. "A" is 100-90, "B" is 89-80, "C" is 79-70, etc.  */
351
				'label' => __( 'Quiz Letter Grade', 'gravityview' ),
352
				'type'  => 'quiz_grade',
353
				'desc'  => __( 'Displays the Grade the user achieved based on Letter Grading configured in the Quiz Settings.', 'gravityview' ),
354
			);
355
			$fields['gquiz_is_pass'] = array(
356
				'label' => __( 'Quiz Pass/Fail', 'gravityview' ),
357
				'type'  => 'quiz_is_pass',
358
				'desc'  => __( 'Displays either Passed or Failed based on the Pass/Fail settings configured in the Quiz Settings.', 'gravityview' ),
359
			);
360
		}
361
362
		return $fields;
363
364
	}
365
366
	/**
367
	 * get extra fields from entry meta
368
	 * @param  string $form_id (default: '')
369
	 * @return array
370
	 */
371
	public static function get_entry_meta( $form_id, $only_default_column = true ) {
372
373
		$extra_fields = GFFormsModel::get_entry_meta( $form_id );
374
375
		$fields = array();
376
377
		foreach ( $extra_fields as $key => $field ){
378
			if ( ! empty( $only_default_column ) && ! empty( $field['is_default_column'] ) ) {
379
				$fields[ $key ] = array( 'label' => $field['label'], 'type' => 'entry_meta' );
380
			}
381
		}
382
383
		return $fields;
384
	}
385
386
387
	/**
388
	 * Wrapper for the Gravity Forms GFFormsModel::search_lead_ids() method
389
	 *
390
	 * @see  GFEntryList::leads_page()
391
	 * @param  int $form_id ID of the Gravity Forms form
392
	 * @since  1.1.6
393
	 * @return array|void          Array of entry IDs. Void if Gravity Forms isn't active.
394
	 */
395
	public static function get_entry_ids( $form_id, $search_criteria = array() ) {
396
397
		if ( ! class_exists( 'GFFormsModel' ) ) {
398
			return;
399
		}
400
401
		return GFFormsModel::search_lead_ids( $form_id, $search_criteria );
402
	}
403
404
	/**
405
	 * Calculates the Search Criteria used on the self::get_entries / self::get_entry methods
406
	 *
407
	 * @since 1.7.4
408
	 *
409
	 * @param array $passed_criteria array Input Criteria (search_criteria, sorting, paging)
410
	 * @param array $form_ids array Gravity Forms form IDs
411
	 * @return array
412
	 */
413
	public static function calculate_get_entries_criteria( $passed_criteria = array(), $form_ids = array() ) {
414
415
		$search_criteria_defaults = array(
416
			'search_criteria' => null,
417
			'sorting' => null,
418
			'paging' => null,
419
			'cache' => (isset( $passed_criteria['cache'] ) ? $passed_criteria['cache'] : true),
420
		);
421
422
		$criteria = wp_parse_args( $passed_criteria, $search_criteria_defaults );
423
424
		if ( ! empty( $criteria['search_criteria']['field_filters'] ) ) {
425
			foreach ( $criteria['search_criteria']['field_filters'] as &$filter ) {
426
427
				if ( ! is_array( $filter ) ) {
428
					continue;
429
				}
430
431
				// By default, we want searches to be wildcard for each field.
432
				$filter['operator'] = empty( $filter['operator'] ) ? 'contains' : $filter['operator'];
433
434
				/**
435
				 * @filter `gravityview_search_operator` Modify the search operator for the field (contains, is, isnot, etc)
436
				 * @param string $operator Existing search operator
437
				 * @param array $filter array with `key`, `value`, `operator`, `type` keys
438
				 */
439
				$filter['operator'] = apply_filters( 'gravityview_search_operator', $filter['operator'], $filter );
440
			}
441
442
			// don't send just the [mode] without any field filter.
443
			if( count( $criteria['search_criteria']['field_filters'] ) === 1 && array_key_exists( 'mode' , $criteria['search_criteria']['field_filters'] ) ) {
0 ignored issues
show
introduced by
Found "=== 1". Use Yoda Condition checks, you must
Loading history...
444
				unset( $criteria['search_criteria']['field_filters']['mode'] );
445
			}
1 ignored issue
show
introduced by
Blank line found after control structure
Loading history...
446
447
		}
448
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 3 empty lines
Loading history...
449
450
451
		/**
452
		 * Prepare date formats to be in Gravity Forms DB format;
453
		 * $passed_criteria may include date formats incompatible with Gravity Forms.
454
		 */
455
		foreach ( array('start_date', 'end_date' ) as $key ) {
0 ignored issues
show
introduced by
No space after opening parenthesis of array is bad style
Loading history...
456
457
			if ( ! empty( $criteria['search_criteria'][ $key ] ) ) {
458
459
				// Use date_create instead of new DateTime so it returns false if invalid date format.
460
				$date = date_create( $criteria['search_criteria'][ $key ] );
461
462
				if ( $date ) {
463
					// Gravity Forms wants dates in the `Y-m-d H:i:s` format.
464
					$criteria['search_criteria'][ $key ] = $date->format( 'Y-m-d H:i:s' );
465
				} else {
466
					// If it's an invalid date, unset it. Gravity Forms freaks out otherwise.
467
					unset( $criteria['search_criteria'][ $key ] );
468
469
					do_action( 'gravityview_log_error', '[filter_get_entries_criteria] '.$key.' Date format not valid:', $criteria['search_criteria'][ $key ] );
470
				}
471
			}
472
		}
473
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
474
475
		// When multiple views are embedded, OR single entry, calculate the context view id and send it to the advanced filter
476
		if ( class_exists( 'GravityView_View_Data' ) && GravityView_View_Data::getInstance()->has_multiple_views() || GravityView_frontend::getInstance()->getSingleEntry() ) {
477
			$criteria['context_view_id'] = GravityView_frontend::getInstance()->get_context_view_id();
478
		} elseif ( 'delete' === RGForms::get( 'action' ) ) {
479
			$criteria['context_view_id'] = isset( $_GET['view_id'] ) ? $_GET['view_id'] : null;
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
480
		} elseif( !isset( $criteria['context_view_id'] ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
481
            // Prevent overriding the Context View ID: Some widgets could set the context_view_id (e.g. Recent Entries widget)
482
			$criteria['context_view_id'] = null;
483
		}
484
485
		/**
486
		 * @filter `gravityview_search_criteria` Apply final criteria filter (Used by the Advanced Filter extension)
487
		 * @param array $criteria Search criteria used by GravityView
488
		 * @param array $form_ids Forms to search
489
		 * @param int $view_id ID of the view being used to search
490
		 */
491
		$criteria = apply_filters( 'gravityview_search_criteria', $criteria, $form_ids, $criteria['context_view_id'] );
492
493
		return (array)$criteria;
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
494
495
	}
496
497
498
	/**
499
	 * Retrieve entries given search, sort, paging criteria
500
	 *
501
	 * @see  GFAPI::get_entries()
502
	 * @see GFFormsModel::get_field_filters_where()
503
	 * @access public
504
	 * @param int|array $form_ids The ID of the form or an array IDs of the Forms. Zero for all forms.
505
	 * @param mixed $passed_criteria (default: null)
506
	 * @param mixed &$total Optional. An output parameter containing the total number of entries. Pass a non-null value to generate the total count. (default: null)
507
	 * @return mixed False: Error fetching entries. Array: Multi-dimensional array of Gravity Forms entry arrays
508
	 */
509
	public static function get_entries( $form_ids = null, $passed_criteria = null, &$total = null ) {
510
511
		// Filter the criteria before query (includes Adv Filter)
512
		$criteria = self::calculate_get_entries_criteria( $passed_criteria, $form_ids );
513
514
		do_action( 'gravityview_log_debug', '[gravityview_get_entries] Final Parameters', $criteria );
515
516
		// Return value
517
		$return = null;
518
519
		/** Reduce # of database calls */
520
		add_filter( 'gform_is_encrypted_field', '__return_false' );
521
522
		if ( ! empty( $criteria['cache'] ) ) {
523
524
			$Cache = new GravityView_Cache( $form_ids, $criteria );
525
526
			if ( $entries = $Cache->get() ) {
527
528
				// Still update the total count when using cached results
529
				if ( ! is_null( $total ) ) {
530
					$total = GFAPI::count_entries( $form_ids, $criteria['search_criteria'] );
531
				}
532
533
				$return = $entries;
534
			}
535
		}
536
537
		if ( is_null( $return ) && class_exists( 'GFAPI' ) && ( is_numeric( $form_ids ) || is_array( $form_ids ) ) ) {
538
539
			/**
540
			 * @filter `gravityview_pre_get_entries` Define entries to be used before GFAPI::get_entries() is called
541
			 * @since 1.14
542
			 * @param  null $return If you want to override GFAPI::get_entries() and define entries yourself, tap in here.
543
			 * @param  array $criteria The final search criteria used to generate the request to `GFAPI::get_entries()`
544
			 * @param array $passed_criteria The original search criteria passed to `GVCommon::get_entries()`
545
			 * @param  int|null $total Optional. An output parameter containing the total number of entries. Pass a non-null value to generate
546
			 */
547
			$entries = apply_filters( 'gravityview_before_get_entries', null, $criteria, $passed_criteria, $total );
548
549
			// No entries returned from gravityview_before_get_entries
550
			if( is_null( $entries ) ) {
551
552
				$entries = GFAPI::get_entries( $form_ids, $criteria['search_criteria'], $criteria['sorting'], $criteria['paging'], $total );
553
554
				if ( is_wp_error( $entries ) ) {
555
					do_action( 'gravityview_log_error', $entries->get_error_message(), $entries );
556
557
					return false;
558
				}
559
			}
560
561
			if ( ! empty( $criteria['cache'] ) && isset( $Cache ) ) {
562
563
				// Cache results
564
				$Cache->set( $entries, 'entries' );
565
566
			}
567
568
			$return = $entries;
569
		}
570
571
		/** Remove filter added above */
572
		remove_filter( 'gform_is_encrypted_field', '__return_false' );
573
574
		/**
575
		 * @filter `gravityview_entries` Modify the array of entries returned to GravityView after it has been fetched from the cache or from `GFAPI::get_entries()`.
576
		 * @param  array|null $entries Array of entries as returned by the cache or by `GFAPI::get_entries()`
577
		 * @param  array $criteria The final search criteria used to generate the request to `GFAPI::get_entries()`
578
		 * @param array $passed_criteria The original search criteria passed to `GVCommon::get_entries()`
579
		 * @param  int|null $total Optional. An output parameter containing the total number of entries. Pass a non-null value to generate
580
		 */
581
		$return = apply_filters( 'gravityview_entries', $return, $criteria, $passed_criteria, $total );
582
583
		return $return;
584
	}
585
586
587
	/**
588
	 * Return a single entry object
589
	 *
590
	 * Since 1.4, supports custom entry slugs. The way that GravityView fetches an entry based on the custom slug is by searching `gravityview_unique_id` meta. The `$entry_slug` is fetched by getting the current query var set by `is_single_entry()`
591
	 *
592
	 * @access public
593
	 * @param string|int $entry_slug Either entry ID or entry slug string
594
	 * @param boolean $force_allow_ids Force the get_entry() method to allow passed entry IDs, even if the `gravityview_custom_entry_slug_allow_id` filter returns false.
595
	 * @param boolean $check_entry_display Check whether the entry is visible for the current View configuration. Default: true. {@since 1.14}
596
	 * @return array|boolean
597
	 */
598
	public static function get_entry( $entry_slug, $force_allow_ids = false, $check_entry_display = true ) {
599
600
		if ( class_exists( 'GFAPI' ) && ! empty( $entry_slug ) ) {
601
602
			/**
603
			 * @filter `gravityview_custom_entry_slug` Whether to enable and use custom entry slugs.
604
			 * @param boolean True: Allow for slugs based on entry values. False: always use entry IDs (default)
605
			 */
606
			$custom_slug = apply_filters( 'gravityview_custom_entry_slug', false );
607
608
			/**
609
			 * @filter `gravityview_custom_entry_slug_allow_id` When using a custom slug, allow access to the entry using the original slug (the Entry ID).
610
			 * - If disabled (default), only allow access to an entry using the custom slug value.  (example: `/entry/custom-slug/` NOT `/entry/123/`)
611
			 * - If enabled, you could access using the custom slug OR the entry id (example: `/entry/custom-slug/` OR `/entry/123/`)
612
			 * @param boolean $custom_slug_id_access True: allow accessing the slug by ID; False: only use the slug passed to the method.
613
			 */
614
			$custom_slug_id_access = $force_allow_ids || apply_filters( 'gravityview_custom_entry_slug_allow_id', false );
615
616
			/**
617
			 * If we're using custom entry slugs, we do a meta value search
618
			 * instead of doing a straightup ID search.
619
			 */
620
			if ( $custom_slug ) {
621
622
				$entry_id = self::get_entry_id_from_slug( $entry_slug );
623
624
			}
625
626
			// If custom slug is off, search using the entry ID
627
			// ID allow ID access is on, also use entry ID as a backup
628
			if ( empty( $custom_slug ) || ! empty( $custom_slug_id_access ) ) {
629
				// Search for IDs matching $entry_slug
630
				$entry_id = $entry_slug;
631
			}
632
633
			if ( empty( $entry_id ) ) {
634
				return false;
635
			}
636
637
			// fetch the entry
638
			$entry = GFAPI::get_entry( $entry_id );
639
640
			/**
641
			 * @filter `gravityview/common/get_entry/check_entry_display` Override whether to check entry display rules against filters
642
			 * @since 1.16.2
643
			 * @param bool $check_entry_display Check whether the entry is visible for the current View configuration. Default: true.
644
			 * @param array $entry Gravity Forms entry array
645
			 */
646
			$check_entry_display = apply_filters( 'gravityview/common/get_entry/check_entry_display', $check_entry_display, $entry );
647
648
			if( $check_entry_display ) {
649
				// Is the entry allowed
650
				$entry = self::check_entry_display( $entry );
651
			}
652
653
			return is_wp_error( $entry ) ? false : $entry;
654
655
		}
656
657
		return false;
658
	}
659
660
	/**
661
	 * Wrapper for the GFFormsModel::matches_operation() method that adds additional comparisons, including:
662
	 * 'equals', 'greater_than_or_is', 'greater_than_or_equals', 'less_than_or_is', 'less_than_or_equals',
663
	 * and 'not_contains'
664
	 *
665
	 * @since 1.13 You can define context, which displays/hides based on what's being displayed (single, multiple, edit)
666
	 *
667
	 * @see http://docs.gravityview.co/article/252-gvlogic-shortcode
668
	 * @uses GFFormsModel::matches_operation
669
	 * @since 1.7.5
670
	 *
671
	 * @param string $val1 Left side of comparison
672
	 * @param string $val2 Right side of comparison
673
	 * @param string $operation Type of comparison
674
	 *
675
	 * @return bool True: matches, false: not matches
676
	 */
677
	public static function matches_operation( $val1, $val2, $operation ) {
678
679
		$value = false;
680
681
		if( 'context' === $val1 ) {
682
683
			$matching_contexts = array( $val2 );
684
685
			// We allow for non-standard contexts.
686
			switch( $val2 ) {
687
				// Check for either single or edit
688
				case 'singular':
689
					$matching_contexts = array( 'single', 'edit' );
690
					break;
691
				// Use multiple as alias for directory for consistency
692
				case 'multiple':
693
					$matching_contexts = array( 'directory' );
694
					break;
695
			}
696
697
			$val1 = in_array( gravityview_get_context(), $matching_contexts ) ? $val2 : false;
698
		}
699
700
		switch ( $operation ) {
701
			case 'equals':
702
				$value = GFFormsModel::matches_operation( $val1, $val2, 'is' );
703
				break;
704
			case 'greater_than_or_is':
705
			case 'greater_than_or_equals':
706
				$is    = GFFormsModel::matches_operation( $val1, $val2, 'is' );
707
				$gt    = GFFormsModel::matches_operation( $val1, $val2, 'greater_than' );
708
				$value = ( $is || $gt );
709
				break;
710
			case 'less_than_or_is':
711
			case 'less_than_or_equals':
712
				$is    = GFFormsModel::matches_operation( $val1, $val2, 'is' );
713
				$gt    = GFFormsModel::matches_operation( $val1, $val2, 'less_than' );
714
				$value = ( $is || $gt );
715
				break;
716
			case 'not_contains':
717
				$contains = GFFormsModel::matches_operation( $val1, $val2, 'contains' );
718
				$value    = ! $contains;
719
				break;
720
			default:
721
				$value = GFFormsModel::matches_operation( $val1, $val2, $operation );
722
		}
723
724
		return $value;
725
	}
726
727
	/**
728
	 *
729
	 * Checks if a certain entry is valid according to the View search filters (specially the Adv Filters)
730
	 *
731
	 * @see GFFormsModel::is_value_match()
732
	 *
733
	 * @since 1.7.4
734
	 * @todo Return WP_Error instead of boolean
735
	 *
736
	 * @param array $entry Gravity Forms Entry object
737
	 * @return bool|array Returns 'false' if entry is not valid according to the view search filters (Adv Filter)
738
	 */
739
	public static function check_entry_display( $entry ) {
740
741
		if ( ! $entry || is_wp_error( $entry ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $entry of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
742
			do_action( 'gravityview_log_debug', __METHOD__ . ' Entry was not found.', $entry );
743
			return false;
744
		}
745
746
		if ( empty( $entry['form_id'] ) ) {
747
			do_action( 'gravityview_log_debug', '[apply_filters_to_entry] Entry is empty! Entry:', $entry );
748
			return false;
749
		}
750
751
		$criteria = self::calculate_get_entries_criteria();
752
753
		// Make sure the current View is connected to the same form as the Entry
754
		if( ! empty( $criteria['context_view_id'] ) ) {
755
			$context_view_id = intval( $criteria['context_view_id'] );
756
			$context_form_id = gravityview_get_form_id( $context_view_id );
757
			if( intval( $context_form_id ) !== intval( $entry['form_id'] ) ) {
758
				do_action( 'gravityview_log_debug', sprintf( '[apply_filters_to_entry] Entry form ID does not match current View connected form ID:', $entry['form_id'] ), $criteria['context_view_id'] );
759
				return false;
760
			}
761
		}
762
763
		if ( empty( $criteria['search_criteria'] ) || ! is_array( $criteria['search_criteria'] ) ) {
764
			do_action( 'gravityview_log_debug', '[apply_filters_to_entry] Entry approved! No search criteria found:', $criteria );
765
			return $entry;
766
		}
767
768
		$search_criteria = $criteria['search_criteria'];
769
		unset( $criteria );
770
771
		// check entry status
772
		if ( array_key_exists( 'status', $search_criteria ) && $search_criteria['status'] != $entry['status'] ) {
773
			do_action( 'gravityview_log_debug', sprintf( '[apply_filters_to_entry] Entry status - %s - is not valid according to filter:', $entry['status'] ), $search_criteria );
774
			return false;
775
		}
776
777
		// check entry date
778
		// @todo: Does it make sense to apply the Date create filters to the single entry?
779
780
		// field_filters
781
		if ( empty( $search_criteria['field_filters'] ) || ! is_array( $search_criteria['field_filters'] ) ) {
782
			do_action( 'gravityview_log_debug', '[apply_filters_to_entry] Entry approved! No field filters criteria found:', $search_criteria );
783
			return $entry;
784
		}
785
786
		$filters = $search_criteria['field_filters'];
787
		unset( $search_criteria );
788
789
		$mode = array_key_exists( 'mode', $filters ) ? strtolower( $filters['mode'] ) : 'all';
790
		unset( $filters['mode'] );
791
792
		$form = self::get_form( $entry['form_id'] );
793
794
		foreach ( $filters as $filter ) {
795
796
			if ( ! isset( $filter['key'] ) ) {
797
				continue;
798
			}
799
800
			$k = $filter['key'];
801
802
			if ( in_array( $k, array( 'created_by', 'payment_status' ) ) ) {
803
				$field_value = $entry[ $k ];
804
				$field = null;
805
			} else {
806
				$field = self::get_field( $form, $k );
807
				$field_value  = GFFormsModel::get_lead_field_value( $entry, $field );
808
			}
809
810
			$operator = isset( $filter['operator'] ) ? strtolower( $filter['operator'] ) : 'is';
811
			$is_value_match = GFFormsModel::is_value_match( $field_value, $filter['value'], $operator, $field );
812
813
			// verify if we are already free to go!
814
			if ( ! $is_value_match && 'all' === $mode ) {
815
				do_action( 'gravityview_log_debug', '[apply_filters_to_entry] Entry cannot be displayed. Failed one criteria for ALL mode', $filter );
816
				return false;
817
			} elseif ( $is_value_match && 'any' === $mode ) {
818
				return $entry;
819
			}
820
		}
821
822
		// at this point, if in ALL mode, then entry is approved - all conditions were met.
823
		// Or, for ANY mode, means none of the conditions were satisfied, so entry is not approved
824
		if ( 'all' === $mode ) {
825
			return $entry;
826
		} else {
827
			do_action( 'gravityview_log_debug', '[apply_filters_to_entry] Entry cannot be displayed. Failed all the criteria for ANY mode', $filters );
828
			return false;
829
		}
830
831
	}
832
833
834
	/**
835
	 * Allow formatting date and time based on GravityView standards
836
	 *
837
	 * @since 1.16
838
	 *
839
	 * @see GVCommon_Test::test_format_date for examples
840
	 *
841
	 * @param string $date_string The date as stored by Gravity Forms (`Y-m-d h:i:s` GMT)
842
	 * @param string|array $args Array or string of settings for output parsed by `wp_parse_args()`; Can use `raw=1` or `array('raw' => true)` \n
843
	 * - `raw` Un-formatted date string in original `Y-m-d h:i:s` format
844
	 * - `timestamp` Integer timestamp returned by GFCommon::get_local_timestamp()
845
	 * - `diff` "%s ago" format, unless other `format` is defined
846
	 * - `human` Set $is_human parameter to true for `GFCommon::format_date()`. Shows `diff` within 24 hours or date after. Format based on blog setting, unless `format` is defined.
847
	 * - `time` Include time in the `GFCommon::format_date()` output
848
	 * - `format` Define your own date format, or `diff` format
849
	 *
850
	 * @return int|null|string Formatted date based on the original date
851
	 */
852
	public static function format_date( $date_string = '', $args = array() ) {
853
854
		$default_atts = array(
855
			'raw' => false,
856
			'timestamp' => false,
857
			'diff' => false,
858
			'human' => false,
859
			'format' => '',
860
			'time' => false,
861
		);
862
863
		$atts = wp_parse_args( $args, $default_atts );
864
865
		/**
866
		 * Gravity Forms code to adjust date to locally-configured Time Zone
867
		 * @see GFCommon::format_date() for original code
868
		 */
869
		$date_gmt_time   = mysql2date( 'G', $date_string );
870
		$date_local_timestamp = GFCommon::get_local_timestamp( $date_gmt_time );
871
872
		$format  = rgar( $atts, 'format' );
873
		$is_human  = ! empty( $atts['human'] );
874
		$is_diff  = ! empty( $atts['diff'] );
875
		$is_raw = ! empty( $atts['raw'] );
876
		$is_timestamp = ! empty( $atts['timestamp'] );
877
		$include_time = ! empty( $atts['time'] );
878
879
		// If we're using time diff, we want to have a different default format
880
		if( empty( $format ) ) {
881
			/* translators: %s: relative time from now, used for generic date comparisons. "1 day ago", or "20 seconds ago" */
882
			$format = $is_diff ? esc_html__( '%s ago', 'gravityview' ) : get_option( 'date_format' );
883
		}
884
885
		// If raw was specified, don't modify the stored value
886
		if ( $is_raw ) {
887
			$formatted_date = $date_string;
888
		} elseif( $is_timestamp ) {
889
			$formatted_date = $date_local_timestamp;
890
		} elseif ( $is_diff ) {
891
			$formatted_date = sprintf( $format, human_time_diff( $date_gmt_time ) );
892
		} else {
893
			$formatted_date = GFCommon::format_date( $date_string, $is_human, $format, $include_time );
894
		}
895
896
		unset( $format, $is_diff, $is_human, $is_timestamp, $is_raw, $date_gmt_time, $date_local_timestamp, $default_atts );
897
898
		return $formatted_date;
899
	}
900
901
	/**
902
	 * Retrieve the label of a given field id (for a specific form)
903
	 *
904
	 * @access public
905
	 * @param array $form
906
	 * @param string $field_id
907
	 * @return string
908
	 */
909
	public static function get_field_label( $form = array(), $field_id = '' ) {
910
911
		if ( empty( $form ) || empty( $field_id ) ) {
912
			return '';
913
		}
914
915
		$field = self::get_field( $form, $field_id );
916
		return isset( $field['label'] ) ?  $field['label'] : '';
917
918
	}
919
920
921
	/**
922
	 * Returns the field details array of a specific form given the field id
923
	 *
924
	 * Alias of GFFormsModel::get_field
925
	 *
926
	 * @uses GFFormsModel::get_field
927
	 * @see GFFormsModel::get_field
928
	 * @access public
929
	 * @param array $form
930
	 * @param string|int $field_id
931
	 * @return GF_Field|null Gravity Forms field object, or NULL: Gravity Forms GFFormsModel does not exist or field at $field_id doesn't exist.
932
	 */
933
	public static function get_field( $form, $field_id ) {
934
		if ( class_exists( 'GFFormsModel' ) ){
935
			return GFFormsModel::get_field( $form, $field_id );
936
		} else {
937
			return null;
938
		}
939
	}
940
941
942
	/**
943
	 * Check whether the post is GravityView
944
	 *
945
	 * - Check post type. Is it `gravityview`?
946
	 * - Check shortcode
947
	 *
948
	 * @param  WP_Post      $post WordPress post object
949
	 * @return boolean           True: yep, GravityView; No: not!
950
	 */
951
	public static function has_gravityview_shortcode( $post = null ) {
952
		if ( ! is_a( $post, 'WP_Post' ) ) {
953
			return false;
954
		}
955
956
		if ( 'gravityview' === get_post_type( $post ) ) {
957
			return true;
958
		}
959
960
		return self::has_shortcode_r( $post->post_content, 'gravityview' ) ? true : false;
961
962
	}
963
964
965
	/**
966
	 * Placeholder until the recursive has_shortcode() patch is merged
967
	 * @see https://core.trac.wordpress.org/ticket/26343#comment:10
968
	 * @param string $content Content to check whether there's a shortcode
969
	 * @param string $tag Current shortcode tag
970
	 */
971
	public static function has_shortcode_r( $content, $tag = 'gravityview' ) {
972
		if ( false === strpos( $content, '[' ) ) {
973
			return false;
974
		}
975
976
		if ( shortcode_exists( $tag ) ) {
977
978
			$shortcodes = array();
979
980
			preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER );
981
			if ( empty( $matches ) ){
982
				return false;
983
			}
984
985
			foreach ( $matches as $shortcode ) {
986
				if ( $tag === $shortcode[2] ) {
987
988
					// Changed this to $shortcode instead of true so we get the parsed atts.
989
					$shortcodes[] = $shortcode;
990
991
				} else if ( isset( $shortcode[5] ) && $results = self::has_shortcode_r( $shortcode[5], $tag ) ) {
992
					foreach( $results as $result ) {
993
						$shortcodes[] = $result;
994
					}
995
				}
996
			}
997
998
			return $shortcodes;
999
		}
1000
		return false;
1001
	}
1002
1003
1004
1005
	/**
1006
	 * Get the views for a particular form
1007
	 *
1008
	 * @since 1.15.2 Add $args array and limit posts_per_page to 500
1009
	 *
1010
	 * @uses get_posts()
1011
	 *
1012
	 * @param  int $form_id Gravity Forms form ID
1013
	 * @param  array $args Pass args sent to get_posts()
1014
	 *
1015
	 * @return array          Array with view details, as returned by get_posts()
1016
	 */
1017
	public static function get_connected_views( $form_id, $args = array() ) {
1018
1019
		$defaults = array(
1020
			'post_type' => 'gravityview',
1021
			'posts_per_page' => 100,
0 ignored issues
show
introduced by
Detected high pagination limit, posts_per_page is set to 100
Loading history...
1022
			'meta_key' => '_gravityview_form_id',
0 ignored issues
show
introduced by
Detected usage of meta_key, possible slow query.
Loading history...
1023
			'meta_value' => (int)$form_id,
0 ignored issues
show
introduced by
Detected usage of meta_value, possible slow query.
Loading history...
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
1024
		);
1025
1026
		$args = wp_parse_args( $args, $defaults );
1027
1028
		$views = get_posts( $args );
1029
1030
		return $views;
1031
	}
1032
1033
	/**
1034
	 * Get the Gravity Forms form ID connected to a View
1035
	 *
1036
	 * @param int $view_id The ID of the View to get the connected form of
1037
	 *
1038
	 * @return string ID of the connected Form, if exists. Empty string if not.
1039
	 */
1040
	public static function get_meta_form_id( $view_id ) {
1041
		return get_post_meta( $view_id, '_gravityview_form_id', true );
1042
	}
1043
1044
	/**
1045
	 * Get the template ID (`list`, `table`, `datatables`, `map`) for a View
1046
	 *
1047
	 * @see GravityView_Template::template_id
1048
	 *
1049
	 * @param int $view_id The ID of the View to get the layout of
1050
	 *
1051
	 * @return string GravityView_Template::template_id value. Empty string if not.
1052
	 */
1053
	public static function get_meta_template_id( $view_id ) {
1054
		return get_post_meta( $view_id, '_gravityview_directory_template', true );
1055
	}
1056
1057
1058
	/**
1059
	 * Get all the settings for a View
1060
	 *
1061
	 * @uses  GravityView_View_Data::get_default_args() Parses the settings with the plugin defaults as backups.
1062
	 * @param  int $post_id View ID
1063
	 * @return array          Associative array of settings with plugin defaults used if not set by the View
1064
	 */
1065
	public static function get_template_settings( $post_id ) {
1066
1067
		$settings = get_post_meta( $post_id, '_gravityview_template_settings', true );
1068
1069
		if ( class_exists( 'GravityView_View_Data' ) ) {
1070
1071
			$defaults = GravityView_View_Data::get_default_args();
1072
1073
			return wp_parse_args( (array)$settings, $defaults );
0 ignored issues
show
introduced by
No space after closing casting parenthesis is prohibited
Loading history...
1074
1075
		}
1076
1077
		// Backup, in case GravityView_View_Data isn't loaded yet.
1078
		return $settings;
1079
	}
1080
1081
	/**
1082
	 * Get the setting for a View
1083
	 *
1084
	 * If the setting isn't set by the View, it returns the plugin default.
1085
	 *
1086
	 * @param  int $post_id View ID
1087
	 * @param  string $key     Key for the setting
1088
	 * @return mixed|null          Setting value, or NULL if not set.
1089
	 */
1090
	public static function get_template_setting( $post_id, $key ) {
1091
1092
		$settings = self::get_template_settings( $post_id );
1093
1094
		if ( isset( $settings[ $key ] ) ) {
1095
			return $settings[ $key ];
1096
		}
1097
1098
		return null;
1099
	}
1100
1101
	/**
1102
	 * Get the field configuration for the View
1103
	 *
1104
	 * array(
1105
	 *
1106
	 * 	[other zones]
1107
	 *
1108
	 * 	'directory_list-title' => array(
1109
	 *
1110
	 *   	[other fields]
1111
	 *
1112
	 *  	'5372653f25d44' => array(
1113
	 *  		'id' => string '9' (length=1)
1114
	 *  		'label' => string 'Screenshots' (length=11)
1115
	 *			'show_label' => string '1' (length=1)
1116
	 *			'custom_label' => string '' (length=0)
1117
	 *			'custom_class' => string 'gv-gallery' (length=10)
1118
	 * 			'only_loggedin' => string '0' (length=1)
1119
	 *			'only_loggedin_cap' => string 'read' (length=4)
1120
	 *  	)
1121
	 *
1122
	 * 		[other fields]
1123
	 *  )
1124
	 *
1125
	 * 	[other zones]
1126
	 * )
1127
	 *
1128
	 * @param  int $post_id View ID
1129
	 * @return array          Multi-array of fields with first level being the field zones. See code comment.
1130
	 */
1131
	public static function get_directory_fields( $post_id ) {
1132
		return get_post_meta( $post_id, '_gravityview_directory_fields', true );
1133
	}
1134
1135
1136
	/**
1137
	 * Render dropdown (select) with the list of sortable fields from a form ID
1138
	 *
1139
	 * @access public
1140
	 * @param  int $formid Form ID
1141
	 * @return string         html
1142
	 */
1143
	public static function get_sortable_fields( $formid, $current = '' ) {
1144
		$output = '<option value="" ' . selected( '', $current, false ).'>' . esc_html__( 'Default', 'gravityview' ) .'</option>';
1145
1146
		if ( empty( $formid ) ) {
1147
			return $output;
1148
		}
1149
1150
		$fields = self::get_sortable_fields_array( $formid );
1151
1152
		if ( ! empty( $fields ) ) {
1153
1154
			$blacklist_field_types = apply_filters( 'gravityview_blacklist_field_types', array( 'list', 'textarea' ), null );
1155
1156
			foreach ( $fields as $id => $field ) {
1157
				if ( in_array( $field['type'], $blacklist_field_types ) ) {
1158
					continue;
1159
				}
1160
1161
				$output .= '<option value="'. $id .'" '. selected( $id, $current, false ).'>'. esc_attr( $field['label'] ) .'</option>';
1162
			}
1163
		}
1164
1165
		return $output;
1166
	}
1167
1168
	/**
1169
	 *
1170
	 * @param int $formid Gravity Forms form ID
1171
	 * @param array $blacklist Field types to exclude
1172
	 *
1173
	 * @since 1.8
1174
	 *
1175
	 * @todo Get all fields, check if sortable dynamically
1176
	 *
1177
	 * @return array
1178
	 */
1179
	public static function get_sortable_fields_array( $formid, $blacklist = array( 'list', 'textarea' ) ) {
1180
1181
		// Get fields with sub-inputs and no parent
1182
		$fields = self::get_form_fields( $formid, true, false );
1183
1184
		$date_created = array(
1185
			'date_created' => array(
1186
				'type' => 'date_created',
1187
				'label' => __( 'Date Created', 'gravityview' ),
1188
			),
1189
		);
1190
1191
        $fields = $date_created + $fields;
1192
1193
		$blacklist_field_types = apply_filters( 'gravityview_blacklist_field_types', $blacklist, NULL );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
1194
1195
		// TODO: Convert to using array_filter
1196
		foreach( $fields as $id => $field ) {
1197
1198
			if( in_array( $field['type'], $blacklist_field_types ) ) {
1199
				unset( $fields[ $id ] );
1200
			}
1201
		}
1202
1203
        /**
1204
         * @filter `gravityview/common/sortable_fields` Filter the sortable fields
1205
         * @since 1.12
1206
         * @param array $fields Sub-set of GF form fields that are sortable
1207
         * @param int $formid The Gravity Forms form ID that the fields are from
1208
         */
1209
        $fields = apply_filters( 'gravityview/common/sortable_fields', $fields, $formid );
1210
1211
		return $fields;
1212
	}
1213
1214
	/**
1215
	 * Returns the GF Form field type for a certain field(id) of a form
1216
	 * @param  object $form     Gravity Forms form
1217
	 * @param  mixed $field_id Field ID or Field array
1218
	 * @return string field type
1219
	 */
1220
	public static function get_field_type( $form = null, $field_id = '' ) {
1221
1222
		if ( ! empty( $field_id ) && ! is_array( $field_id ) ) {
1223
			$field = self::get_field( $form, $field_id );
1224
		} else {
1225
			$field = $field_id;
1226
		}
1227
1228
		return class_exists( 'RGFormsModel' ) ? RGFormsModel::get_input_type( $field ) : '';
1229
1230
	}
1231
1232
1233
	/**
1234
	 * Checks if the field type is a 'numeric' field type (e.g. to be used when sorting)
1235
	 * @param  int|array  $form  form ID or form array
1236
	 * @param  int|array  $field field key or field array
1237
	 * @return boolean
1238
	 */
1239
	public static function is_field_numeric(  $form = null, $field = '' ) {
1240
1241
		if ( ! is_array( $form ) && ! is_array( $field ) ) {
1242
			$form = self::get_form( $form );
1243
		}
1244
1245
		// If entry meta, it's a string. Otherwise, numeric
1246
		if( ! is_numeric( $field ) && is_string( $field ) ) {
1247
			$type = $field;
1248
		} else {
1249
			$type = self::get_field_type( $form, $field );
1250
		}
1251
1252
		/**
1253
		 * @filter `gravityview/common/numeric_types` What types of fields are numeric?
1254
		 * @since 1.5.2
1255
		 * @param array $numeric_types Fields that are numeric. Default: `[ number, time ]`
1256
		 */
1257
		$numeric_types = apply_filters( 'gravityview/common/numeric_types', array( 'number', 'time' ) );
1258
1259
		// Defer to GravityView_Field setting, if the field type is registered and `is_numeric` is true
1260
		if( $gv_field = GravityView_Fields::get( $type ) ) {
1261
			if( true === $gv_field->is_numeric ) {
1262
				$numeric_types[] = $gv_field->is_numeric;
1263
			}
1264
		}
1265
1266
		$return = in_array( $type, $numeric_types );
1267
1268
		return $return;
1269
	}
1270
1271
	/**
1272
	 * Encrypt content using Javascript so that it's hidden when JS is disabled.
1273
	 *
1274
	 * This is mostly used to hide email addresses from scraper bots.
1275
	 *
1276
	 * @param string $content Content to encrypt
1277
	 * @param string $message Message shown if Javascript is disabled
1278
	 *
1279
	 * @see  https://github.com/jnicol/standalone-phpenkoder StandalonePHPEnkoder on Github
1280
	 *
1281
	 * @since 1.7
1282
	 *
1283
	 * @return string Content, encrypted
1284
	 */
1285
	public static function js_encrypt( $content, $message = '' ) {
1286
1287
		$output = $content;
1288
1289
		if ( ! class_exists( 'StandalonePHPEnkoder' ) ) {
1290
			include_once( GRAVITYVIEW_DIR . 'includes/lib/standalone-phpenkoder/StandalonePHPEnkoder.php' );
1291
		}
1292
1293
		if ( class_exists( 'StandalonePHPEnkoder' ) ) {
1294
1295
			$enkoder = new StandalonePHPEnkoder;
1296
1297
			$message = empty( $message ) ? __( 'Email hidden; Javascript is required.', 'gravityview' ) : $message;
1298
1299
			/**
1300
			 * @filter `gravityview/phpenkoder/msg` Modify the message shown when Javascript is disabled and an encrypted email field is displayed
1301
			 * @since 1.7
1302
			 * @param string $message Existing message
1303
			 * @param string $content Content to encrypt
1304
			 */
1305
			$enkoder->enkode_msg = apply_filters( 'gravityview/phpenkoder/msg', $message, $content );
1306
1307
			$output = $enkoder->enkode( $content );
1308
		}
1309
1310
		return $output;
1311
	}
1312
1313
	/**
1314
	 *
1315
	 * Do the same than parse_str without max_input_vars limitation:
1316
	 * Parses $string as if it were the query string passed via a URL and sets variables in the current scope.
1317
	 * @param $string array string to parse (not altered like in the original parse_str(), use the second parameter!)
1318
	 * @param $result array  If the second parameter is present, variables are stored in this variable as array elements
1319
	 * @return bool true or false if $string is an empty string
1320
	 * @since  1.5.3
1321
	 *
1322
	 * @author rubo77 at https://gist.github.com/rubo77/6821632
1323
	 **/
1324
	public static function gv_parse_str( $string, &$result ) {
1325
		if ( empty( $string ) ) {
1326
			return false;
1327
		}
1328
1329
		$result = array();
1330
1331
		// find the pairs "name=value"
1332
		$pairs = explode( '&', $string );
1333
1334
		foreach ( $pairs as $pair ) {
1335
			// use the original parse_str() on each element
1336
			parse_str( $pair, $params );
1337
1338
			$k = key( $params );
1339
			if ( ! isset( $result[ $k ] ) ) {
1340
				$result += $params;
1341
			} elseif ( array_key_exists( $k, $params ) && is_array( $params[ $k ] ) ) {
1342
				$result[ $k ] = self::array_merge_recursive_distinct( $result[ $k ], $params[ $k ] );
1343
			}
1344
		}
1345
		return true;
1346
	}
1347
1348
1349
	/**
1350
	 * Generate an HTML anchor tag with a list of supported attributes
1351
	 *
1352
	 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a Supported attributes defined here
1353
	 * @uses esc_url_raw() to sanitize $href
1354
	 * @uses esc_attr() to sanitize $atts
1355
	 *
1356
	 * @since 1.6
1357
	 *
1358
	 * @param string $href URL of the link. Sanitized using `esc_url_raw()`
1359
	 * @param string $anchor_text The text or HTML inside the anchor. This is not sanitized in the function.
1360
	 * @param array|string $atts Attributes to be added to the anchor tag. Parsed by `wp_parse_args()`, sanitized using `esc_attr()`
1361
	 *
1362
	 * @return string HTML output of anchor link. If empty $href, returns NULL
1363
	 */
1364
	public static function get_link_html( $href = '', $anchor_text = '', $atts = array() ) {
1365
1366
		// Supported attributes for anchor tags. HREF left out intentionally.
1367
		$allowed_atts = array(
1368
			'href' => null, // Will override the $href argument if set
1369
			'title' => null,
1370
			'rel' => null,
1371
			'id' => null,
1372
			'class' => null,
1373
			'target' => null,
1374
			'style' => null,
1375
1376
			// Used by GravityView
1377
			'data-viewid' => null,
1378
1379
			// Not standard
1380
			'hreflang' => null,
1381
			'type' => null,
1382
			'tabindex' => null,
1383
1384
			// Deprecated HTML4 but still used
1385
			'name' => null,
1386
			'onclick' => null,
1387
			'onchange' => null,
1388
			'onkeyup' => null,
1389
1390
			// HTML5 only
1391
			'download' => null,
1392
			'media' => null,
1393
			'ping' => null,
1394
		);
1395
1396
		/**
1397
		 * @filter `gravityview/get_link/allowed_atts` Modify the attributes that are allowed to be used in generating links
1398
		 * @param array $allowed_atts Array of attributes allowed
1399
		 */
1400
		$allowed_atts = apply_filters( 'gravityview/get_link/allowed_atts', $allowed_atts );
1401
1402
		// Make sure the attributes are formatted as array
1403
		$passed_atts = wp_parse_args( $atts );
1404
1405
		// Make sure the allowed attributes are only the ones in the $allowed_atts list
1406
		$final_atts = shortcode_atts( $allowed_atts, $passed_atts );
1407
1408
		// Remove attributes with empty values
1409
		$final_atts = array_filter( $final_atts );
1410
1411
		// If the href wasn't passed as an attribute, use the value passed to the function
1412
		if ( empty( $final_atts['href'] ) && ! empty( $href ) ) {
1413
			$final_atts['href'] = $href;
1414
		}
1415
1416
		$final_atts['href'] = esc_url_raw( $href );
1417
1418
		// Sort the attributes alphabetically, to help testing
1419
		ksort( $final_atts );
1420
1421
		// For each attribute, generate the code
1422
		$output = '';
1423
		foreach ( $final_atts as $attr => $value ) {
1424
			$output .= sprintf( ' %s="%s"', $attr, esc_attr( $value ) );
1425
		}
1426
1427
		if( '' !== $output ) {
1428
			$output = '<a' . $output . '>' . $anchor_text . '</a>';
1429
		}
1430
1431
		return $output;
1432
	}
1433
1434
	/**
1435
	 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
1436
	 * keys to arrays rather than overwriting the value in the first array with the duplicate
1437
	 * value in the second array, as array_merge does.
1438
	 *
1439
	 * @see http://php.net/manual/en/function.array-merge-recursive.php
1440
	 *
1441
	 * @since  1.5.3
1442
	 * @param array $array1
1443
	 * @param array $array2
1444
	 * @return array
1445
	 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
1446
	 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
1447
	 */
1448
	public static function array_merge_recursive_distinct( array &$array1, array &$array2 ) {
1449
		$merged = $array1;
1450
1451
		foreach ( $array2 as $key => &$value )  {
1452
			if ( is_array( $value ) && isset( $merged[ $key ] ) && is_array( $merged[ $key ] ) ) {
1453
				$merged[ $key ] = self::array_merge_recursive_distinct( $merged[ $key ], $value );
1454
			} else {
1455
				$merged[ $key ] = $value;
1456
			}
1457
		}
1458
1459
		return $merged;
1460
	}
1461
1462
	/**
1463
	 * Get WordPress users with reasonable limits set
1464
	 *
1465
	 * @param string $context Where are we using this information (e.g. change_entry_creator, search_widget ..)
1466
	 * @param array $args Arguments to modify the user query. See get_users() {@since 1.14}
1467
	 * @return array Array of WP_User objects.
1468
	 */
1469
	public static function get_users( $context = 'change_entry_creator', $args = array() ) {
1470
1471
		$default_args = array(
1472
			'number' => 2000,
1473
			'orderby' => 'display_name',
1474
			'order' => 'ASC',
1475
			'fields' => array( 'ID', 'display_name', 'user_login', 'user_nicename' )
1476
		);
1477
1478
		// Merge in the passed arg
1479
		$get_users_settings = wp_parse_args( $args, $default_args );
1480
1481
		/**
1482
		 * @filter `gravityview/get_users/{$context}` There are issues with too many users using [get_users()](http://codex.wordpress.org/Function_Reference/get_users) where it breaks the select. We try to keep it at a reasonable number. \n
1483
		 * `$context` is where are we using this information (e.g. change_entry_creator, search_widget ..)
1484
		 * @param array $settings Settings array, with `number` key defining the # of users to display
1485
		 */
1486
		$get_users_settings = apply_filters( 'gravityview/get_users/'. $context, apply_filters( 'gravityview_change_entry_creator_user_parameters', $get_users_settings ) );
1487
1488
		return get_users( $get_users_settings );
1489
	}
1490
1491
1492
    /**
1493
     * Display updated/error notice
1494
     *
1495
     * @param string $notice text/HTML of notice
1496
     * @param string $class CSS class for notice (`updated` or `error`)
1497
     *
1498
     * @return string
1499
     */
1500
    public static function generate_notice( $notice, $class = '' ) {
1501
        return '<div class="gv-notice '.gravityview_sanitize_html_class( $class ) .'">'. $notice .'</div>';
1502
    }
1503
1504
1505
1506
1507
} //end class
1508
1509
1510
/**
1511
 * Generate an HTML anchor tag with a list of supported attributes
1512
 *
1513
 * @see GVCommon::get_link_html()
1514
 *
1515
 * @since 1.6
1516
 *
1517
 * @param string $href URL of the link.
1518
 * @param string $anchor_text The text or HTML inside the anchor. This is not sanitized in the function.
1519
 * @param array|string $atts Attributes to be added to the anchor tag
1520
 *
1521
 * @return string HTML output of anchor link. If empty $href, returns NULL
1522
 */
1523
function gravityview_get_link( $href = '', $anchor_text = '', $atts = array() ) {
1524
	return GVCommon::get_link_html( $href, $anchor_text, $atts );
1525
}
1526