Completed
Push — develop ( 3f375d...0f7d17 )
by Zack
28:11 queued 08:00
created

maybe_enqueue_flexibility()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 0
dl 0
loc 5
ccs 3
cts 4
cp 0.75
crap 3.1406
rs 10
c 0
b 0
f 0
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 16 and the first side effect is on line 13.

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
 * The GravityView New Search widget
4
 *
5
 * @package   GravityView-DataTables-Ext
6
 * @license   GPL2+
7
 * @author    Katz Web Services, Inc.
8
 * @link      http://gravityview.co
9
 * @copyright Copyright 2014, Katz Web Services, Inc.
10
 */
11
12
if ( ! defined( 'WPINC' ) ) {
13
	die;
14
}
15
16
class GravityView_Widget_Search extends \GV\Widget {
17
18
	public static $file;
19
	public static $instance;
20
21
	private $search_filters = array();
0 ignored issues
show
Unused Code introduced by
The property $search_filters is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
22
23
	/**
24
	 * whether search method is GET or POST ( default: GET )
25
	 * @since 1.16.4
26
	 * @var string
27
	 */
28
	private $search_method = 'get';
29
30 16
	public function __construct() {
31
32 16
		$this->widget_id = 'search_bar';
33 16
		$this->widget_description = esc_html__( 'Search form for searching entries.', 'gravityview' );
34
35 16
		self::$instance = &$this;
36
37 16
		self::$file = plugin_dir_path( __FILE__ );
38
39 16
		$default_values = array( 'header' => 0, 'footer' => 0 );
40
41
		$settings = array(
42 16
			'search_layout' => array(
43 16
				'type' => 'radio',
44
				'full_width' => true,
45 16
				'label' => esc_html__( 'Search Layout', 'gravityview' ),
46 16
				'value' => 'horizontal',
47
				'options' => array(
48 16
					'horizontal' => esc_html__( 'Horizontal', 'gravityview' ),
49 16
					'vertical' => esc_html__( 'Vertical', 'gravityview' ),
50
				),
51
			),
52
			'search_clear' => array(
53 16
				'type' => 'checkbox',
54 16
				'label' => __( 'Show Clear button', 'gravityview' ),
55
				'value' => false,
56
			),
57
			'search_fields' => array(
58
				'type' => 'hidden',
59
				'label' => '',
60
				'class' => 'gv-search-fields-value',
61
				'value' => '[{"field":"search_all","input":"input_text"}]', // Default: Search Everything text box
62
			),
63
			'search_mode' => array(
64 16
				'type' => 'radio',
65
				'full_width' => true,
66 16
				'label' => esc_html__( 'Search Mode', 'gravityview' ),
67 16
				'desc' => __('Should search results match all search fields, or any?', 'gravityview'),
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
68 16
				'value' => 'any',
69 16
				'class' => 'hide-if-js',
70
				'options' => array(
71 16
					'any' => esc_html__( 'Match Any Fields', 'gravityview' ),
72 16
					'all' => esc_html__( 'Match All Fields', 'gravityview' ),
73
				),
74
			),
75
		);
76
77 16
		if ( ! $this->is_registered() ) {
78
			// frontend - filter entries
79
			add_filter( 'gravityview_fe_search_criteria', array( $this, 'filter_entries' ), 10, 3 );
80
81
			// frontend - add template path
82
			add_filter( 'gravityview_template_paths', array( $this, 'add_template_path' ) );
83
84
			// Add hidden fields for "Default" permalink structure
85
			add_filter( 'gravityview_widget_search_filters', array( $this, 'add_no_permalink_fields' ), 10, 3 );
86
87
			// admin - add scripts - run at 1100 to make sure GravityView_Admin_Views::add_scripts_and_styles() runs first at 999
88
			add_action( 'admin_enqueue_scripts', array( $this, 'add_scripts_and_styles' ), 1100 );
89
			add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts') );
0 ignored issues
show
introduced by
No space before closing parenthesis of array is bad style
Loading history...
90
			add_filter( 'gravityview_noconflict_scripts', array( $this, 'register_no_conflict' ) );
91
92
			// ajax - get the searchable fields
93
			add_action( 'wp_ajax_gv_searchable_fields', array( 'GravityView_Widget_Search', 'get_searchable_fields' ) );
94
		}
95
96 16
		parent::__construct( esc_html__( 'Search Bar', 'gravityview' ), null, $default_values, $settings );
97
98
		// calculate the search method (POST / GET)
99 16
		$this->set_search_method();
100 16
	}
101
102
	/**
103
	 * @return GravityView_Widget_Search
104
	 */
105 5
	public static function getInstance() {
0 ignored issues
show
Coding Style introduced by
The function name getInstance is in camel caps, but expected get_instance instead as per the coding standard.
Loading history...
106 5
		if ( empty( self::$instance ) ) {
107
			self::$instance = new GravityView_Widget_Search;
108
		}
109 5
		return self::$instance;
110
	}
111
112
	/**
113
	 * Sets the search method to GET (default) or POST
114
	 * @since 1.16.4
115
	 */
116 16
	private function set_search_method() {
117
		/**
118
		 * @filter `gravityview/search/method` Modify the search form method (GET / POST)
119
		 * @since 1.16.4
120
		 * @param string $search_method Assign an input type according to the form field type. Defaults: `boolean`, `multi`, `select`, `date`, `text`
121
		 * @param string $field_type Gravity Forms field type (also the `name` parameter of GravityView_Field classes)
122
		 */
123 16
		$method = apply_filters( 'gravityview/search/method', $this->search_method );
124
125 16
		$method = strtolower( $method );
126
127 16
		$this->search_method = in_array( $method, array( 'get', 'post' ) ) ? $method : 'get';
128 16
	}
129
130
	/**
131
	 * Returns the search method
132
	 * @since 1.16.4
133
	 * @return string
134
	 */
135 5
	public function get_search_method() {
136 5
		return $this->search_method;
137
	}
138
139
	/**
140
	 * Get the input types available for different field types
141
	 *
142
	 * @since 1.17.5
143
	 *
144
	 * @return array [field type name] => (array|string) search bar input types
145
	 */
146
	public static function get_input_types_by_field_type() {
147
		/**
148
		 * Input Type groups
149
		 * @see admin-search-widget.js (getSelectInput)
150
		 * @var array
151
		 */
152
		$input_types = array(
153
			'text' => array( 'input_text' ),
154
			'address' => array( 'input_text' ),
155
			'number' => array( 'input_text' ),
156
			'date' => array( 'date', 'date_range' ),
157
			'boolean' => array( 'single_checkbox' ),
158
			'select' => array( 'select', 'radio', 'link' ),
159
			'multi' => array( 'select', 'multiselect', 'radio', 'checkbox', 'link' ),
160
		);
161
162
		/**
163
		 * @filter `gravityview/search/input_types` Change the types of search fields available to a field type
164
		 * @see GravityView_Widget_Search::get_search_input_labels() for the available input types
165
		 * @param array $input_types Associative array: key is field `name`, value is array of GravityView input types (note: use `input_text` for `text`)
166
		 */
167
		$input_types = apply_filters( 'gravityview/search/input_types', $input_types );
168
169
		return $input_types;
170
	}
171
172
	/**
173
	 * Get labels for different types of search bar inputs
174
	 *
175
	 * @since 1.17.5
176
	 *
177
	 * @return array [input type] => input type label
178
	 */
179
	public static function get_search_input_labels() {
180
		/**
181
		 * Input Type labels l10n
182
		 * @see admin-search-widget.js (getSelectInput)
183
		 * @var array
184
		 */
185
		$input_labels = array(
186
			'input_text' => esc_html__( 'Text', 'gravityview' ),
187
			'date' => esc_html__( 'Date', 'gravityview' ),
188
			'select' => esc_html__( 'Select', 'gravityview' ),
189
			'multiselect' => esc_html__( 'Select (multiple values)', 'gravityview' ),
190
			'radio' => esc_html__( 'Radio', 'gravityview' ),
191
			'checkbox' => esc_html__( 'Checkbox', 'gravityview' ),
192
			'single_checkbox' => esc_html__( 'Checkbox', 'gravityview' ),
193
			'link' => esc_html__( 'Links', 'gravityview' ),
194
			'date_range' => esc_html__( 'Date range', 'gravityview' ),
195
		);
196
197
		/**
198
		 * @filter `gravityview/search/input_types` Change the label of search field input types
199
		 * @param array $input_types Associative array: key is input type name, value is label
200
		 */
201
		$input_labels = apply_filters( 'gravityview/search/input_labels', $input_labels );
202
203
		return $input_labels;
204
	}
205
206
	public static function get_search_input_label( $input_type ) {
207
		$labels = self::get_search_input_labels();
208
209
		return \GV\Utils::get( $labels, $input_type, false );
210
	}
211
212
	/**
213
	 * Add script to Views edit screen (admin)
214
	 * @param  mixed $hook
215
	 */
216
	public function add_scripts_and_styles( $hook ) {
217
		global $pagenow;
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...
218
219
		// Don't process any scripts below here if it's not a GravityView page or the widgets screen
220
		if ( ! gravityview()->request->is_admin( $hook, 'single' ) && ( 'widgets.php' !== $pagenow ) ) {
0 ignored issues
show
Unused Code introduced by
The call to Request::is_admin() has too many arguments starting with $hook.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
221
			return;
222
		}
223
224
		$script_min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
225
		$script_source = empty( $script_min ) ? '/source' : '';
226
227
		wp_enqueue_script( 'gravityview_searchwidget_admin', plugins_url( 'assets/js'.$script_source.'/admin-search-widget'.$script_min.'.js', __FILE__ ), array( 'jquery', 'gravityview_views_scripts' ), \GV\Plugin::$version );
228
229
		wp_localize_script( 'gravityview_searchwidget_admin', 'gvSearchVar', array(
230
			'nonce' => wp_create_nonce( 'gravityview_ajaxsearchwidget' ),
231
			'label_nofields' => esc_html__( 'No search fields configured yet.', 'gravityview' ),
232
			'label_addfield' => esc_html__( 'Add Search Field', 'gravityview' ),
233
			'label_label' => esc_html__( 'Label', 'gravityview' ),
234
			'label_searchfield' => esc_html__( 'Search Field', 'gravityview' ),
235
			'label_inputtype' => esc_html__( 'Input Type', 'gravityview' ),
236
			'label_ajaxerror' => esc_html__( 'There was an error loading searchable fields. Save the View or refresh the page to fix this issue.', 'gravityview' ),
237
			'input_labels' => json_encode( self::get_search_input_labels() ),
238
			'input_types' => json_encode( self::get_input_types_by_field_type() ),
239
		) );
240
241
	}
242
243
	/**
244
	 * Add admin script to the no-conflict scripts whitelist
245
	 * @param array $allowed Scripts allowed in no-conflict mode
246
	 * @return array Scripts allowed in no-conflict mode, plus the search widget script
247
	 */
248
	public function register_no_conflict( $allowed ) {
249
		$allowed[] = 'gravityview_searchwidget_admin';
250
		return $allowed;
251
	}
252
253
	/**
254
	 * Ajax
255
	 * Returns the form fields ( only the searchable ones )
256
	 *
257
	 * @access public
258
	 * @return void
259
	 */
260
	public static function get_searchable_fields() {
261
262
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'gravityview_ajaxsearchwidget' ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
263
			exit( '0' );
0 ignored issues
show
Coding Style Compatibility introduced by
The method get_searchable_fields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
264
		}
265
266
		$form = '';
267
268
		// Fetch the form for the current View
269
		if ( ! empty( $_POST['view_id'] ) ) {
270
271
			$form = gravityview_get_form_id( $_POST['view_id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
272
273
		} elseif ( ! empty( $_POST['formid'] ) ) {
274
275
			$form = (int) $_POST['formid'];
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
276
277
		} elseif ( ! empty( $_POST['template_id'] ) && class_exists( 'GravityView_Ajax' ) ) {
278
279
			$form = GravityView_Ajax::pre_get_form_fields( $_POST['template_id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
280
281
		}
282
283
		// fetch form id assigned to the view
284
		$response = self::render_searchable_fields( $form );
285
286
		exit( $response );
0 ignored issues
show
Coding Style Compatibility introduced by
The method get_searchable_fields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
287
	}
288
289
	/**
290
	 * Generates html for the available Search Fields dropdown
291
	 * @param  int $form_id
292
	 * @param  string $current (for future use)
293
	 * @return string
294
	 */
295
	public static function render_searchable_fields( $form_id = null, $current = '' ) {
296
297
		if ( is_null( $form_id ) ) {
298
			return '';
299
		}
300
301
		// start building output
302
303
		$output = '<select class="gv-search-fields">';
304
305
		$custom_fields = array(
306
			'search_all' => array(
307
				'text' => esc_html__( 'Search Everything', 'gravityview' ),
308
				'type' => 'text',
309
			),
310
			'entry_date' => array(
311
				'text' => esc_html__( 'Entry Date', 'gravityview' ),
312
				'type' => 'date',
313
			),
314
			'entry_id' => array(
315
				'text' => esc_html__( 'Entry ID', 'gravityview' ),
316
				'type' => 'text',
317
			),
318
			'created_by' => array(
319
				'text' => esc_html__( 'Entry Creator', 'gravityview' ),
320
				'type' => 'select',
321
			),
322
			'is_starred' => array(
323
				'text' => esc_html__( 'Is Starred', 'gravityview' ),
324
				'type' => 'boolean',
325
			),
326
		);
327
328
		foreach( $custom_fields as $custom_field_key => $custom_field ) {
329
			$output .= sprintf( '<option value="%s" %s data-inputtypes="%s" data-placeholder="%s">%s</option>', $custom_field_key, selected( $custom_field_key, $current, false ), $custom_field['type'], self::get_field_label( array('field' => $custom_field_key ) ), $custom_field['text'] );
0 ignored issues
show
introduced by
No space after opening parenthesis of array is bad style
Loading history...
330
		}
331
332
		// Get fields with sub-inputs and no parent
333
		$fields = gravityview_get_form_fields( $form_id, true, true );
334
335
		/**
336
		 * @filter `gravityview/search/searchable_fields` Modify the fields that are displayed as searchable in the Search Bar dropdown\n
337
		 * @since 1.17
338
		 * @see gravityview_get_form_fields() Used to fetch the fields
339
		 * @see GravityView_Widget_Search::get_search_input_types See this method to modify the type of input types allowed for a field
340
		 * @param array $fields Array of searchable fields, as fetched by gravityview_get_form_fields()
341
		 * @param  int $form_id
342
		 */
343
		$fields = apply_filters( 'gravityview/search/searchable_fields', $fields, $form_id );
344
345
		if ( ! empty( $fields ) ) {
346
347
			$blacklist_field_types = apply_filters( 'gravityview_blacklist_field_types', array( 'fileupload', 'post_image', 'post_id', 'section' ), null );
348
349
			foreach ( $fields as $id => $field ) {
350
351
				if ( in_array( $field['type'], $blacklist_field_types ) ) {
352
					continue;
353
				}
354
355
				$types = self::get_search_input_types( $id, $field['type'] );
356
357
				$output .= '<option value="'. $id .'" '. selected( $id, $current, false ).'data-inputtypes="'. esc_attr( $types ) .'">'. esc_html( $field['label'] ) .'</option>';
358
			}
359
		}
360
361
		$output .= '</select>';
362
363
		return $output;
364
365
	}
366
367
	/**
368
	 * Assign an input type according to the form field type
369
	 *
370
	 * @see admin-search-widget.js
371
	 *
372
	 * @param string|int|float $field_id Gravity Forms field ID
373
	 * @param string $field_type Gravity Forms field type (also the `name` parameter of GravityView_Field classes)
374
	 *
375
	 * @return string GV field search input type ('multi', 'boolean', 'select', 'date', 'text')
376
	 */
377
	public static function get_search_input_types( $field_id = '', $field_type = null ) {
378
379
		// @todo - This needs to be improved - many fields have . including products and addresses
380
		if ( false !== strpos( (string) $field_id, '.' ) && in_array( $field_type, array( 'checkbox' ) ) || in_array( $field_id, array( 'is_fulfilled' ) ) ) {
381
			$input_type = 'boolean'; // on/off checkbox
382
		} elseif ( in_array( $field_type, array( 'checkbox', 'post_category', 'multiselect' ) ) ) {
383
			$input_type = 'multi'; //multiselect
384
		} elseif ( in_array( $field_type, array( 'select', 'radio' ) ) ) {
385
			$input_type = 'select';
386
		} elseif ( in_array( $field_type, array( 'date' ) ) || in_array( $field_id, array( 'payment_date' ) ) ) {
387
			$input_type = 'date';
388
		} elseif ( in_array( $field_type, array( 'number' ) ) || in_array( $field_id, array( 'payment_amount' ) ) ) {
389
			$input_type = 'number';
390
		} else {
391
			$input_type = 'text';
392
		}
393
394
		/**
395
		 * @filter `gravityview/extension/search/input_type` Modify the search form input type based on field type
396
		 * @since 1.2
397
		 * @since 1.19.2 Added $field_id parameter
398
		 * @param string $input_type Assign an input type according to the form field type. Defaults: `boolean`, `multi`, `select`, `date`, `text`
399
		 * @param string $field_type Gravity Forms field type (also the `name` parameter of GravityView_Field classes)
400
		 * @param string|int|float $field_id ID of the field being processed
401
		 */
402
		$input_type = apply_filters( 'gravityview/extension/search/input_type', $input_type, $field_type, $field_id );
403
404
		return $input_type;
405
	}
406
407
	/**
408
	 * Display hidden fields to add support for sites using Default permalink structure
409
	 *
410
	 * @since 1.8
411
	 * @return array Search fields, modified if not using permalinks
412
	 */
413 4
	public function add_no_permalink_fields( $search_fields, $object, $widget_args = array() ) {
414
		/** @global WP_Rewrite $wp_rewrite */
415 4
		global $wp_rewrite;
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...
416
417
		// Support default permalink structure
418 4
		if ( false === $wp_rewrite->using_permalinks() ) {
419
420
			// By default, use current post.
421 4
			$post_id = 0;
422
423
			// We're in the WordPress Widget context, and an overriding post ID has been set.
424 4
			if ( ! empty( $widget_args['post_id'] ) ) {
425
				$post_id = absint( $widget_args['post_id'] );
426
			}
427
			// We're in the WordPress Widget context, and the base View ID should be used
428 4
			else if ( ! empty( $widget_args['view_id'] ) ) {
429
				$post_id = absint( $widget_args['view_id'] );
430
			}
431
432 4
			$args = gravityview_get_permalink_query_args( $post_id );
433
434
			// Add hidden fields to the search form
435 4
			foreach ( $args as $key => $value ) {
0 ignored issues
show
Bug introduced by
The expression $args of type array|null 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...
436 4
				$search_fields[] = array(
437 4
					'name'  => $key,
438 4
					'input' => 'hidden',
439 4
					'value' => $value,
440
				);
441
			}
442
		}
443
444 4
		return $search_fields;
445
	}
446
447
	/**
448
	 * Get the fields that are searchable for a View
449
	 *
450
	 * @since 2.0
451
	 * @since 2.0.9 Added $with_full_field parameter
452
	 *
453
	 * @param \GV\View|null $view
454
	 * @param bool $with_full_field Return full field array, or just field ID? Default: false (just field ID)
455
	 *
456
	 * TODO: Move to \GV\View, perhaps? And return a Field_Collection
457
	 * TODO: Use in gravityview()->request->is_search() to calculate whether a valid search
458
	 *
459
	 * @return array If no View, returns empty array. Otherwise, returns array of fields configured in widgets and Search Bar for a View
460
	 */
461 11
	private function get_view_searchable_fields( $view, $with_full_field = false ) {
462
463
		/**
464
		 * Find all search widgets on the view and get the searchable fields settings.
465
		 */
466 11
		$searchable_fields = array();
467
468 11
		if ( ! $view ) {
469
			return $searchable_fields;
470
		}
471
472
		/**
473
		 * Include the sidebar Widgets.
474
		 */
475 11
		$widgets = (array) get_option( 'widget_gravityview_search', array() );
476
477 11
		foreach ( $widgets as $widget ) {
478 11
			if ( ! empty( $widget['view_id'] ) && $widget['view_id'] == $view->ID ) {
479
				if( $_fields = json_decode( $widget['search_fields'], true ) ) {
480
					foreach ( $_fields as $field ) {
481 11
						$searchable_fields [] = $with_full_field ? $field : $field['field'];
482
					}
483
				}
484
			}
485
		}
486
487 11
		foreach ( $view->widgets->by_id( $this->get_widget_id() )->all() as $widget ) {
488 11
			if( $_fields = json_decode( $widget->configuration->get( 'search_fields' ), true ) ) {
489 11
				foreach ( $_fields as $field ) {
490 11
					$searchable_fields [] = $with_full_field ? $field : $field['field'];
491
				}
492
			}
493
		}
494
495 11
		return $searchable_fields;
496
	}
497
498
	/** --- Frontend --- */
499
500
	/**
501
	 * Calculate the search criteria to filter entries
502
	 * @param  array $search_criteria
503
	 * @return array
504
	 */
505 40
	public function filter_entries( $search_criteria, $form_id = null, $args = array() ) {
506
507 40
		if( 'post' === $this->search_method ) {
508
			$get = $_POST;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
509
		} else {
510 40
			$get = $_GET;
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...
511
		}
512
513 40
		$view = \GV\View::by_id( \GV\Utils::get( $args, 'id' ) );
514
515 40
		gravityview()->log->debug( 'Requested $_{method}: ', array( 'method' => $this->search_method, 'data' => $get ) );
516
517 40
		if ( empty( $get ) || ! is_array( $get ) ) {
518 29
			return $search_criteria;
519
		}
520
521 12
		$get = stripslashes_deep( $get );
522
523 12
		$get = gv_map_deep( $get, 'rawurldecode' );
524
525
		// Make sure array key is set up
526 12
		$search_criteria['field_filters'] = \GV\Utils::get( $search_criteria, 'field_filters', array() );
527
528 12
		$searchable_fields = $this->get_view_searchable_fields( $view );
529
530
		// add free search
531 12
		if ( isset( $get['gv_search'] ) && '' !== $get['gv_search'] && in_array( 'search_all', $searchable_fields ) ) {
532
533 1
			$search_all_value = trim( $get['gv_search'] );
534
535
			/**
536
			 * @filter `gravityview/search-all-split-words` Search for each word separately or the whole phrase?
537
			 * @since 1.20.2
538
			 * @param bool $split_words True: split a phrase into words; False: search whole word only [Default: true]
539
			 */
540 1
			$split_words = apply_filters( 'gravityview/search-all-split-words', true );
541
542 1
			if ( $split_words ) {
543
544
				// Search for a piece
545 1
				$words = explode( ' ', $search_all_value );
546
547 1
				$words = array_filter( $words );
548
549
			} else {
550
551
				// Replace multiple spaces with one space
552 1
				$search_all_value = preg_replace( '/\s+/ism', ' ', $search_all_value );
553
554 1
				$words = array( $search_all_value );
555
			}
556
557 1
			foreach ( $words as $word ) {
558 1
				$search_criteria['field_filters'][] = array(
559 1
					'key' => null, // The field ID to search
560 1
					'value' => $word, // The value to search
561 1
					'operator' => 'contains', // What to search in. Options: `is` or `contains`
562
				);
563
			}
564
		}
565
566
		// start date & end date
567 12
		if ( in_array( 'entry_date', $searchable_fields ) ) {
568
			/**
569
			 * Get and normalize the dates according to the input format.
570
			 */
571 11
			if ( $curr_start = ! empty( $get['gv_start'] ) ? $get['gv_start'] : '' ) {
572 11
				if( $curr_start_date = date_create_from_format( $this->get_datepicker_format( true ), $curr_start ) ) {
573 11
					$curr_start = $curr_start_date->format( 'Y-m-d' );
574
				}
575
			}
576
577 11
			if ( $curr_end = ! empty( $get['gv_start'] ) ? ( ! empty( $get['gv_end'] ) ? $get['gv_end'] : '' ) : '' ) {
578 11
				if( $curr_end_date = date_create_from_format( $this->get_datepicker_format( true ), $curr_end ) ) {
579 11
					$curr_end = $curr_end_date->format( 'Y-m-d' );
580
				}
581
			}
582
583 11
			if ( $view ) {
584
				/**
585
				 * Override start and end dates if View is limited to some already.
586
				 */
587 11
				if ( $start_date = $view->settings->get( 'start_date' ) ) {
588 1
					if ( $start_timestamp = strtotime( $curr_start ) ) {
589 1
						$curr_start = $start_timestamp < strtotime( $start_date ) ? $start_date : $curr_start;
590
					}
591
				}
592 11
				if ( $end_date = $view->settings->get( 'end_date' ) ) {
593
					if ( $end_timestamp = strtotime( $curr_end ) ) {
594
						$curr_end = $end_timestamp > strtotime( $end_date ) ? $end_date : $curr_end;
595
					}
596
				}
597
			}
598
599
			/**
600
			 * @filter `gravityview_date_created_adjust_timezone` Whether to adjust the timezone for entries. \n
601
			 * date_created is stored in UTC format. Convert search date into UTC (also used on templates/fields/date_created.php)
602
			 * @since 1.12
603
			 * @param[out,in] boolean $adjust_tz  Use timezone-adjusted datetime? If true, adjusts date based on blog's timezone setting. If false, uses UTC setting. Default: true
604
			 * @param[in] string $context Where the filter is being called from. `search` in this case.
605
			 */
606 11
			$adjust_tz = apply_filters( 'gravityview_date_created_adjust_timezone', true, 'search' );
607
608
			/**
609
			 * Don't set $search_criteria['start_date'] if start_date is empty as it may lead to bad query results (GFAPI::get_entries)
610
			 */
611 11
			if ( ! empty( $curr_start ) ) {
612 11
				$curr_start = date( 'Y-m-d H:i:s', strtotime( $curr_start ) );
613 11
				$search_criteria['start_date'] = $adjust_tz ? get_gmt_from_date( $curr_start ) : $curr_start;
614
			}
615
616 11
			if ( ! empty( $curr_end ) ) {
617
				// Fast-forward 24 hour on the end time
618 11
				$curr_end = date( 'Y-m-d H:i:s', strtotime( $curr_end ) + DAY_IN_SECONDS );
619 11
				$search_criteria['end_date'] = $adjust_tz ? get_gmt_from_date( $curr_end ) : $curr_end;
620 11
				if ( strpos( $search_criteria['end_date'], '00:00:00' ) ) { // See https://github.com/gravityview/GravityView/issues/1056
621 11
					$search_criteria['end_date'] = date( 'Y-m-d H:i:s', strtotime( $search_criteria['end_date'] ) - 1 );
622
				}
623
			}
624
		}
625
626
		// search for a specific entry ID
627 12
		if ( ! empty( $get[ 'gv_id' ] ) && in_array( 'entry_id', $searchable_fields ) ) {
0 ignored issues
show
introduced by
Array keys should NOT be surrounded by spaces if they only contain a string or an integer.
Loading history...
628 2
			$search_criteria['field_filters'][] = array(
629 2
				'key' => 'id',
630 2
				'value' => absint( $get[ 'gv_id' ] ),
0 ignored issues
show
introduced by
Array keys should NOT be surrounded by spaces if they only contain a string or an integer.
Loading history...
631 2
				'operator' => '=',
632
			);
633
		}
634
635
		// search for a specific Created_by ID
636 12
		if ( ! empty( $get[ 'gv_by' ] ) && in_array( 'created_by', $searchable_fields ) ) {
0 ignored issues
show
introduced by
Array keys should NOT be surrounded by spaces if they only contain a string or an integer.
Loading history...
637 2
			$search_criteria['field_filters'][] = array(
638 2
				'key' => 'created_by',
639 2
				'value' => absint( $get['gv_by'] ),
640 2
				'operator' => '=',
641
			);
642
		}
643
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
644
645
		// Get search mode passed in URL
646 12
		$mode = isset( $get['mode'] ) && in_array( $get['mode'], array( 'any', 'all' ) ) ?  $get['mode'] : 'any';
647
648
		// get the other search filters
649 12
		foreach ( $get as $key => $value ) {
650
651 12
			if ( 0 !== strpos( $key, 'filter_' ) || gv_empty( $value, false, false ) || ( is_array( $value ) && count( $value ) === 1 && gv_empty( $value[0], false, false ) ) ) {
0 ignored issues
show
introduced by
Found "=== 1". Use Yoda Condition checks, you must
Loading history...
652 11
				continue;
653
			}
654
655 2
			$filter_key = $this->convert_request_key_to_filter_key( $key );
656
657
			// could return simple filter or multiple filters
658 2
			if ( ! in_array( 'search_all', $searchable_fields ) && ! in_array( $filter_key , $searchable_fields ) ) {
659 1
				continue;
660
			}
661
662 1
			$filter = $this->prepare_field_filter( $filter_key, $value, $view );
663
664 1
			if ( isset( $filter[0]['value'] ) ) {
665
				$search_criteria['field_filters'] = array_merge( $search_criteria['field_filters'], $filter );
666
667
				// if date range type, set search mode to ALL
668
				if ( ! empty( $filter[0]['operator'] ) && in_array( $filter[0]['operator'], array( '>=', '<=', '>', '<' ) ) ) {
669
					$mode = 'all';
670
				}
671 1
			} elseif( !empty( $filter ) ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
672 1
				$search_criteria['field_filters'][] = $filter;
673
			}
674
		}
675
676
		/**
677
		 * @filter `gravityview/search/mode` Set the Search Mode (`all` or `any`)
678
		 * @since 1.5.1
679
		 * @param[out,in] string $mode Search mode (`any` vs `all`)
680
		 */
681 12
		$search_criteria['field_filters']['mode'] = apply_filters( 'gravityview/search/mode', $mode );
682
683 12
		gravityview()->log->debug( 'Returned Search Criteria: ', array( 'data' => $search_criteria ) );
684
685 12
		unset( $get );
686
687 12
		return $search_criteria;
688
	}
689
690
	/**
691
	 * Convert $_GET/$_POST key to the field/meta ID
692
	 *
693
	 * Examples:
694
	 * - `filter_is_starred` => `is_starred`
695
	 * - `filter_1_2` => `1.2`
696
	 * - `filter_5` => `5`
697
	 *
698
	 * @since 2.0
699
	 *
700
	 * @param string $key $_GET/_$_POST search key
701
	 *
702
	 * @return string
703
	 */
704 2
	private function convert_request_key_to_filter_key( $key ) {
705
706 2
		$field_id = str_replace( 'filter_', '', $key );
707
708
		// calculates field_id, removing 'filter_' and for '_' for advanced fields ( like name or checkbox )
709 2
		if ( preg_match('/^[0-9_]+$/ism', $field_id ) ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
710 2
			$field_id = str_replace( '_', '.', $field_id );
711
		}
712
713 2
		return $field_id;
714
	}
715
716
	/**
717
	 * Prepare the field filters to GFAPI
718
	 *
719
	 * The type post_category, multiselect and checkbox support multi-select search - each value needs to be separated in an independent filter so we could apply the ANY search mode.
720
	 *
721
	 * Format searched values
722
	 *
723
	 * @param  string $filter_key ID of the field, or entry meta key
724
	 * @param  string $value $_GET/$_POST search value
725
	 * @param  \GV\View $view The view we're looking at
726
	 *
727
	 * @return array        1 or 2 deph levels
728
	 */
729 1
	public function prepare_field_filter( $filter_key, $value, $view ) {
730
731
		// get form field array
732 1
		$form_field = is_numeric( $filter_key ) ? \GV\GF_Field::by_id( $view->form, $filter_key ) : \GV\Internal_Field::by_id( $filter_key );
733
734
		// default filter array
735
		$filter = array(
736 1
			'key'   => $filter_key,
737 1
			'value' => $value,
738
		);
739
740 1
		switch ( $form_field->type ) {
741
742 1
			case 'select':
743 1
			case 'radio':
744 1
				$filter['operator'] = 'is';
745 1
				break;
746
747
			case 'post_category':
748
749
				if ( ! is_array( $value ) ) {
750
					$value = array( $value );
751
				}
752
753
				// Reset filter variable
754
				$filter = array();
755
756
				foreach ( $value as $val ) {
757
					$cat = get_term( $val, 'category' );
758
					$filter[] = array(
759
						'key'      => $filter_key,
760
						'value'    => esc_attr( $cat->name ) . ':' . $val,
761
						'operator' => 'is',
762
					);
763
				}
764
765
				break;
766
767
			case 'multiselect':
768
769
				if ( ! is_array( $value ) ) {
770
					break;
771
				}
772
773
				// Reset filter variable
774
				$filter = array();
775
776
				foreach ( $value as $val ) {
777
					$filter[] = array( 'key' => $filter_key, 'value' => $val );
778
				}
779
780
				break;
781
782
			case 'checkbox':
783
				// convert checkbox on/off into the correct search filter
784
				if ( false !== strpos( $filter_key, '.' ) && ! empty( $form_field->inputs ) && ! empty( $form_field->choices ) ) {
785
					foreach ( $form_field->inputs as $k => $input ) {
786
						if ( $input['id'] == $filter_key ) {
787
							$filter['value'] = $form_field->choices[ $k ]['value'];
788
							$filter['operator'] = 'is';
789
							break;
790
						}
791
					}
792
				} elseif ( is_array( $value ) ) {
793
794
					// Reset filter variable
795
					$filter = array();
796
797
					foreach ( $value as $val ) {
798
						$filter[] = array(
799
							'key'      => $filter_key,
800
							'value'    => $val,
801
							'operator' => 'is',
802
						);
803
					}
804
				}
805
806
				break;
807
808
			case 'name':
809
			case 'address':
810
811
				if ( false === strpos( $filter_key, '.' ) ) {
812
813
					$words = explode( ' ', $value );
814
815
					$filters = array();
816
					foreach ( $words as $word ) {
817
						if ( ! empty( $word ) && strlen( $word ) > 1 ) {
818
							// Keep the same key for each filter
819
							$filter['value'] = $word;
820
							// Add a search for the value
821
							$filters[] = $filter;
822
						}
823
					}
824
825
					$filter = $filters;
826
				}
827
828
				// State/Province should be exact matches
829
				if ( 'address' === $form_field->field->type ) {
830
831
					$searchable_fields = $this->get_view_searchable_fields( $view, true );
832
833
					foreach ( $searchable_fields as $searchable_field ) {
834
835
						if( $form_field->ID !== $searchable_field['field'] ) {
836
							continue;
837
						}
838
839
						// Only exact-match dropdowns, not text search
840
						if( in_array( $searchable_field['input'], array( 'text', 'search' ), true ) ) {
841
							continue;
842
						}
843
844
						$input_id = gravityview_get_input_id_from_id( $form_field->ID );
845
846
						if ( 4 === $input_id ) {
847
							$filter['operator'] = 'is';
848
						};
849
					}
850
				}
851
852
				break;
853
854
			case 'date':
855
856
				if ( is_array( $value ) ) {
857
858
					// Reset filter variable
859
					$filter = array();
860
861
					foreach ( $value as $k => $date ) {
862
						if ( empty( $date ) ) {
863
							continue;
864
						}
865
						$operator = 'start' === $k ? '>=' : '<=';
866
867
						/**
868
						 * @hack
869
						 * @since 1.16.3
870
						 * Safeguard until GF implements '<=' operator
871
						 */
872
						if( !GFFormsModel::is_valid_operator( $operator ) && $operator === '<=' ) {
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
873
							$operator = '<';
874
							$date = date( 'Y-m-d', strtotime( $date . ' +1 day' ) );
875
						}
876
877
						$filter[] = array(
878
							'key'      => $filter_key,
879
							'value'    => self::get_formatted_date( $date, 'Y-m-d' ),
880
							'operator' => $operator,
881
						);
882
					}
883
				} else {
884
					$filter['value'] = self::get_formatted_date( $value, 'Y-m-d' );
885
				}
886
887
				break;
888
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
889
890
		} // switch field type
891
892 1
		return $filter;
893
	}
894
895
	/**
896
	 * Get the Field Format form GravityForms
897
	 *
898
	 * @param GF_Field_Date $field The field object
899
	 * @since 1.10
900
	 *
901
	 * @return string Format of the date in the database
902
	 */
903
	public static function get_date_field_format( GF_Field_Date $field ) {
904
		$format = 'm/d/Y';
905
		$datepicker = array(
906
			'mdy' => 'm/d/Y',
907
			'dmy' => 'd/m/Y',
908
			'dmy_dash' => 'd-m-Y',
909
			'dmy_dot' => 'd.m.Y',
910
			'ymd_slash' => 'Y/m/d',
911
			'ymd_dash' => 'Y-m-d',
912
			'ymd_dot' => 'Y.m.d',
913
		);
914
915
		if ( ! empty( $field->dateFormat ) && isset( $datepicker[ $field->dateFormat ] ) ){
916
			$format = $datepicker[ $field->dateFormat ];
917
		}
918
919
		return $format;
920
	}
921
922
	/**
923
	 * Format a date value
924
	 *
925
	 * @param string $value Date value input
926
	 * @param string $format Wanted formatted date
927
	 * @return string
928
	 */
929
	public static function get_formatted_date( $value = '', $format = 'Y-m-d' ) {
930
931
		$date = date_create( $value );
932
933
		if ( empty( $date ) ) {
934
			gravityview()->log->debug( 'Date format not valid: {value}', array( 'value' => $value ) );
935
			return '';
936
		}
937
		return $date->format( $format );
938
	}
939
940
941
	/**
942
	 * Include this extension templates path
943
	 * @param array $file_paths List of template paths ordered
944
	 */
945 31
	public function add_template_path( $file_paths ) {
946
947
		// Index 100 is the default GravityView template path.
948 31
		$file_paths[102] = self::$file . 'templates/';
949
950 31
		return $file_paths;
951
	}
952
953
	/**
954
	 * Check whether the configured search fields have a date field
955
	 *
956
	 * @since 1.17.5
957
	 *
958
	 * @param array $search_fields
959
	 *
960
	 * @return bool True: has a `date` or `date_range` field
961
	 */
962 4
	private function has_date_field( $search_fields ) {
963
964 4
		$has_date = false;
965
966 4
		foreach ( $search_fields as $k => $field ) {
967 4
			if ( in_array( $field['input'], array( 'date', 'date_range', 'entry_date' ) ) ) {
968
				$has_date = true;
969 4
				break;
970
			}
971
		}
972
973 4
		return $has_date;
974
	}
975
976
	/**
977
	 * Renders the Search Widget
978
	 * @param array $widget_args
979
	 * @param string $content
980
	 * @param string $context
981
	 *
982
	 * @return void
983
	 */
984 4
	public function render_frontend( $widget_args, $content = '', $context = '' ) {
985
		/** @var GravityView_View $gravityview_view */
986 4
		$gravityview_view = GravityView_View::getInstance();
987
988 4
		if ( empty( $gravityview_view ) ) {
989
			gravityview()->log->debug( '$gravityview_view not instantiated yet.' );
990
			return;
991
		}
992
993
		// get configured search fields
994 4
		$search_fields = ! empty( $widget_args['search_fields'] ) ? json_decode( $widget_args['search_fields'], true ) : '';
995
996 4
		if ( empty( $search_fields ) || ! is_array( $search_fields ) ) {
997
			gravityview()->log->debug( 'No search fields configured for widget:', array( 'data' => $widget_args ) );
998
			return;
999
		}
1000
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1001
1002
		// prepare fields
1003 4
		foreach ( $search_fields as $k => $field ) {
1004
1005 4
			$updated_field = $field;
1006
1007 4
			$updated_field = $this->get_search_filter_details( $updated_field );
1008
1009 4
			switch ( $field['field'] ) {
1010
1011 4
				case 'search_all':
1012 4
					$updated_field['key'] = 'search_all';
1013 4
					$updated_field['input'] = 'search_all';
1014 4
					$updated_field['value'] = $this->rgget_or_rgpost( 'gv_search' );
1015 4
					break;
1016
1017
				case 'entry_date':
1018
					$updated_field['key'] = 'entry_date';
1019
					$updated_field['input'] = 'entry_date';
1020
					$updated_field['value'] = array(
1021
						'start' => $this->rgget_or_rgpost( 'gv_start' ),
1022
						'end' => $this->rgget_or_rgpost( 'gv_end' ),
1023
					);
1024
					break;
1025
1026
				case 'entry_id':
1027
					$updated_field['key'] = 'entry_id';
1028
					$updated_field['input'] = 'entry_id';
1029
					$updated_field['value'] = $this->rgget_or_rgpost( 'gv_id' );
1030
					break;
1031
1032
				case 'created_by':
1033
					$updated_field['key'] = 'created_by';
1034
					$updated_field['name'] = 'gv_by';
1035
					$updated_field['value'] = $this->rgget_or_rgpost( 'gv_by' );
1036
					$updated_field['choices'] = self::get_created_by_choices();
1037
					break;
1038
			}
1039
1040 4
			$search_fields[ $k ] = $updated_field;
1041
		}
1042
1043 4
		gravityview()->log->debug( 'Calculated Search Fields: ', array( 'data' => $search_fields ) );
1044
1045
		/**
1046
		 * @filter `gravityview_widget_search_filters` Modify what fields are shown. The order of the fields in the $search_filters array controls the order as displayed in the search bar widget.
1047
		 * @param array $search_fields Array of search filters with `key`, `label`, `value`, `type`, `choices` keys
1048
		 * @param GravityView_Widget_Search $this Current widget object
1049
		 * @param array $widget_args Args passed to this method. {@since 1.8}
1050
		 * @param \GV\Template_Context $context {@since 2.0}
1051
		 * @var array
1052
		 */
1053 4
		$gravityview_view->search_fields = apply_filters( 'gravityview_widget_search_filters', $search_fields, $this, $widget_args, $context );
0 ignored issues
show
Bug introduced by
The property search_fields does not seem to exist. Did you mean fields?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1054
1055 4
		$gravityview_view->search_layout = ! empty( $widget_args['search_layout'] ) ? $widget_args['search_layout'] : 'horizontal';
0 ignored issues
show
Bug introduced by
The property search_layout does not seem to exist in GravityView_View.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1056
1057
		/** @since 1.14 */
1058 4
		$gravityview_view->search_mode = ! empty( $widget_args['search_mode'] ) ? $widget_args['search_mode'] : 'any';
0 ignored issues
show
Bug introduced by
The property search_mode does not seem to exist in GravityView_View.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1059
1060 4
		$custom_class = ! empty( $widget_args['custom_class'] ) ? $widget_args['custom_class'] : '';
1061
1062 4
		$gravityview_view->search_class = self::get_search_class( $custom_class );
0 ignored issues
show
Bug introduced by
The property search_class does not seem to exist in GravityView_View.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1063
1064 4
		$gravityview_view->search_clear = ! empty( $widget_args['search_clear'] ) ? $widget_args['search_clear'] : false;
0 ignored issues
show
Bug introduced by
The property search_clear does not seem to exist in GravityView_View.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1065
1066 4
		if ( $this->has_date_field( $search_fields ) ) {
1067
			// enqueue datepicker stuff only if needed!
1068
			$this->enqueue_datepicker();
1069
		}
1070
1071 4
		$this->maybe_enqueue_flexibility();
1072
1073 4
		$gravityview_view->render( 'widget', 'search', false );
1074 4
	}
1075
1076
	/**
1077
	 * Get the search class for a search form
1078
	 *
1079
	 * @since 1.5.4
1080
	 *
1081
	 * @return string Sanitized CSS class for the search form
1082
	 */
1083 4
	public static function get_search_class( $custom_class = '' ) {
1084 4
		$gravityview_view = GravityView_View::getInstance();
1085
1086 4
		$search_class = 'gv-search-'.$gravityview_view->search_layout;
0 ignored issues
show
Documentation introduced by
The property search_layout does not exist on object<GravityView_View>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1087
1088 4
		if ( ! empty( $custom_class )  ) {
1089
			$search_class .= ' '.$custom_class;
1090
		}
1091
1092
		/**
1093
		 * @filter `gravityview_search_class` Modify the CSS class for the search form
1094
		 * @param string $search_class The CSS class for the search form
1095
		 */
1096 4
		$search_class = apply_filters( 'gravityview_search_class', $search_class );
1097
1098
		// Is there an active search being performed? Used by fe-views.js
1099 4
		$search_class .= GravityView_frontend::getInstance()->isSearch() ? ' gv-is-search' : '';
1100
1101 4
		return gravityview_sanitize_html_class( $search_class );
1102
	}
1103
1104
1105
	/**
1106
	 * Calculate the search form action
1107
	 * @since 1.6
1108
	 *
1109
	 * @return string
1110
	 */
1111 4
	public static function get_search_form_action() {
1112 4
		$gravityview_view = GravityView_View::getInstance();
1113
1114 4
		$post_id = $gravityview_view->getPostId() ? $gravityview_view->getPostId() : $gravityview_view->getViewId();
1115
1116 4
		$url = add_query_arg( array(), get_permalink( $post_id ) );
1117
1118 4
		return esc_url( $url );
1119
	}
1120
1121
	/**
1122
	 * Get the label for a search form field
1123
	 * @param  array $field      Field setting as sent by the GV configuration - has `field`, `input` (input type), and `label` keys
1124
	 * @param  array $form_field Form field data, as fetched by `gravityview_get_field()`
1125
	 * @return string             Label for the search form
1126
	 */
1127 4
	private static function get_field_label( $field, $form_field = array() ) {
1128
1129 4
		$label = \GV\Utils::_GET( 'label', \GV\Utils::get( $field, 'label' ) );
1130
1131 4
		if ( ! $label ) {
1132
1133 4
			$label = isset( $form_field['label'] ) ? $form_field['label'] : '';
1134
1135 4
			switch( $field['field'] ) {
1136 4
				case 'search_all':
1137 4
					$label = __( 'Search Entries:', 'gravityview' );
1138 4
					break;
1139
				case 'entry_date':
1140
					$label = __( 'Filter by date:', 'gravityview' );
1141
					break;
1142
				case 'entry_id':
1143
					$label = __( 'Entry ID:', 'gravityview' );
1144
					break;
1145
				default:
1146
					// If this is a field input, not a field
1147
					if ( strpos( $field['field'], '.' ) > 0 && ! empty( $form_field['inputs'] ) ) {
1148
1149
						// Get the label for the field in question, which returns an array
1150
						$items = wp_list_filter( $form_field['inputs'], array( 'id' => $field['field'] ) );
1151
1152
						// Get the item with the `label` key
1153
						$values = wp_list_pluck( $items, 'label' );
1154
1155
						// There will only one item in the array, but this is easier
1156
						foreach ( $values as $value ) {
1157
							$label = $value;
1158
							break;
1159
						}
1160
					}
1161
			}
1162
		}
1163
1164
		/**
1165
		 * @filter `gravityview_search_field_label` Modify the label for a search field. Supports returning HTML
1166
		 * @since 1.17.3 Added $field parameter
1167
		 * @param[in,out] string $label Existing label text, sanitized.
1168
		 * @param[in] array $form_field Gravity Forms field array, as returned by `GFFormsModel::get_field()`
1169
		 * @param[in] array $field Field setting as sent by the GV configuration - has `field`, `input` (input type), and `label` keys
1170
		 */
1171 4
		$label = apply_filters( 'gravityview_search_field_label', esc_attr( $label ), $form_field, $field );
1172
1173 4
		return $label;
1174
	}
1175
1176
	/**
1177
	 * Prepare search fields to frontend render with other details (label, field type, searched values)
1178
	 *
1179
	 * @param array $field
1180
	 * @return array
1181
	 */
1182 4
	private function get_search_filter_details( $field ) {
1183
1184 4
		$gravityview_view = GravityView_View::getInstance();
1185
1186 4
		$form = $gravityview_view->getForm();
1187
1188
		// for advanced field ids (eg, first name / last name )
1189 4
		$name = 'filter_' . str_replace( '.', '_', $field['field'] );
1190
1191
		// get searched value from $_GET/$_POST (string or array)
1192 4
		$value = $this->rgget_or_rgpost( $name );
1193
1194
		// get form field details
1195 4
		$form_field = gravityview_get_field( $form, $field['field'] );
1196
1197
		$filter = array(
1198 4
			'key' => $field['field'],
1199 4
			'name' => $name,
1200 4
			'label' => self::get_field_label( $field, $form_field ),
1201 4
			'input' => $field['input'],
1202 4
			'value' => $value,
1203 4
			'type' => $form_field['type'],
1204
		);
1205
1206
		// collect choices
1207 4
		if ( 'post_category' === $form_field['type'] && ! empty( $form_field['displayAllCategories'] ) && empty( $form_field['choices'] ) ) {
1208
			$filter['choices'] = gravityview_get_terms_choices();
1209 4
		} elseif ( ! empty( $form_field['choices'] ) ) {
1210
			$filter['choices'] = $form_field['choices'];
1211
		}
1212
1213 4
		if ( 'date_range' === $field['input'] && empty( $value ) ) {
1214
			$filter['value'] = array( 'start' => '', 'end' => '' );
1215
		}
1216
1217 4
		return $filter;
1218
1219
	}
1220
1221
	/**
1222
	 * Calculate the search choices for the users
1223
	 *
1224
	 * @since 1.8
1225
	 *
1226
	 * @return array Array of user choices (value = ID, text = display name)
1227
	 */
1228
	private static function get_created_by_choices() {
1229
1230
		/**
1231
		 * filter gravityview/get_users/search_widget
1232
		 * @see \GVCommon::get_users
1233
		 */
1234
		$users = GVCommon::get_users( 'search_widget', array( 'fields' => array( 'ID', 'display_name' ) ) );
1235
1236
		$choices = array();
1237
		foreach ( $users as $user ) {
1238
			$choices[] = array(
1239
				'value' => $user->ID,
1240
				'text' => $user->display_name,
1241
			);
1242
		}
1243
1244
		return $choices;
1245
	}
1246
1247
1248
	/**
1249
	 * Output the Clear Search Results button
1250
	 * @since 1.5.4
1251
	 */
1252 4
	public static function the_clear_search_button() {
1253 4
		$gravityview_view = GravityView_View::getInstance();
1254
1255 4
		if ( $gravityview_view->search_clear ) {
0 ignored issues
show
Documentation introduced by
The property search_clear does not exist on object<GravityView_View>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1256
1257
			$url = strtok( add_query_arg( array() ), '?' );
1258
1259
			echo gravityview_get_link( $url, esc_html__( 'Clear', 'gravityview' ), 'class=button gv-search-clear' );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'gravityview_get_link'
Loading history...
1260
1261
		}
1262 4
	}
1263
1264
	/**
1265
	 * Based on the search method, fetch the value for a specific key
1266
	 *
1267
	 * @since 1.16.4
1268
	 *
1269
	 * @param string $name Name of the request key to fetch the value for
1270
	 *
1271
	 * @return mixed|string Value of request at $name key. Empty string if empty.
1272
	 */
1273 4
	private function rgget_or_rgpost( $name ) {
1274 4
		$value = \GV\Utils::_REQUEST( $name );
1275
1276 4
		$value = stripslashes_deep( $value );
1277
1278 4
		$value = gv_map_deep( $value, 'rawurldecode' );
1279
1280 4
		$value = gv_map_deep( $value, '_wp_specialchars' );
1281
1282 4
		return $value;
1283
	}
1284
1285
1286
	/**
1287
	 * Require the datepicker script for the frontend GV script
1288
	 * @param array $js_dependencies Array of existing required scripts for the fe-views.js script
1289
	 * @return array Array required scripts, with `jquery-ui-datepicker` added
1290
	 */
1291
	public function add_datepicker_js_dependency( $js_dependencies ) {
1292
1293
		$js_dependencies[] = 'jquery-ui-datepicker';
1294
1295
		return $js_dependencies;
1296
	}
1297
1298
	/**
1299
	 * Modify the array passed to wp_localize_script()
1300
	 *
1301
	 * @param array $js_localization The data padded to the Javascript file
0 ignored issues
show
Bug introduced by
There is no parameter named $js_localization. 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...
1302
	 * @param array $view_data View data array with View settings
1303
	 *
1304
	 * @return array
1305
	 */
1306
	public function add_datepicker_localization( $localizations = array(), $view_data = array() ) {
1307
		global $wp_locale;
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...
1308
1309
		/**
1310
		 * @filter `gravityview_datepicker_settings` Modify the datepicker settings
1311
		 * @see http://api.jqueryui.com/datepicker/ Learn what settings are available
1312
		 * @see http://www.renegadetechconsulting.com/tutorials/jquery-datepicker-and-wordpress-i18n Thanks for the helpful information on $wp_locale
1313
		 * @param array $js_localization The data padded to the Javascript file
1314
		 * @param array $view_data View data array with View settings
1315
		 */
1316
		$datepicker_settings = apply_filters( 'gravityview_datepicker_settings', array(
1317
			'yearRange' => '-5:+5',
1318
			'changeMonth' => true,
1319
			'changeYear' => true,
1320
			'closeText' => esc_attr_x( 'Close', 'Close calendar', 'gravityview' ),
1321
			'prevText' => esc_attr_x( 'Prev', 'Previous month in calendar', 'gravityview' ),
1322
			'nextText' => esc_attr_x( 'Next', 'Next month in calendar', 'gravityview' ),
1323
			'currentText' => esc_attr_x( 'Today', 'Today in calendar', 'gravityview' ),
1324
			'weekHeader' => esc_attr_x( 'Week', 'Week in calendar', 'gravityview' ),
1325
			'monthStatus'       => __( 'Show a different month', 'gravityview' ),
1326
			'monthNames'        => array_values( $wp_locale->month ),
1327
			'monthNamesShort'   => array_values( $wp_locale->month_abbrev ),
1328
			'dayNames'          => array_values( $wp_locale->weekday ),
1329
			'dayNamesShort'     => array_values( $wp_locale->weekday_abbrev ),
1330
			'dayNamesMin'       => array_values( $wp_locale->weekday_initial ),
1331
			// get the start of week from WP general setting
1332
			'firstDay'          => get_option( 'start_of_week' ),
1333
			// is Right to left language? default is false
1334
			'isRTL'             => is_rtl(),
1335
		), $view_data );
1336
1337
		$localizations['datepicker'] = $datepicker_settings;
1338
1339
		return $localizations;
1340
1341
	}
1342
1343
	/**
1344
	 * Register search widget scripts, including Flexibility
1345
	 *
1346
	 * @see https://github.com/10up/flexibility
1347
	 *
1348
	 * @since 1.17
1349
	 *
1350
	 * @return void
1351
	 */
1352
	public function register_scripts() {
1353
		wp_register_script( 'gv-flexibility', plugins_url( 'assets/lib/flexibility/flexibility.js', GRAVITYVIEW_FILE ), array(), \GV\Plugin::$version, true );
1354
	}
1355
1356
	/**
1357
	 * If the current visitor is running IE 8 or 9, enqueue Flexibility
1358
	 *
1359
	 * @since 1.17
1360
	 *
1361
	 * @return void
1362
	 */
1363 4
	private function maybe_enqueue_flexibility() {
1364 4
		if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && preg_match( '/MSIE [8-9]/', $_SERVER['HTTP_USER_AGENT'] ) ) {
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_SERVER
Loading history...
1365
			wp_enqueue_script( 'gv-flexibility' );
1366
		}
1367 4
	}
1368
1369
	/**
1370
	 * Enqueue the datepicker script
1371
	 *
1372
	 * It sets the $gravityview->datepicker_class parameter
1373
	 *
1374
	 * @todo Use own datepicker javascript instead of GF datepicker.js - that way, we can localize the settings and not require the changeMonth and changeYear pickers.
1375
	 * @return void
1376
	 */
1377
	public function enqueue_datepicker() {
1378
		$gravityview_view = GravityView_View::getInstance();
1379
1380
		wp_enqueue_script( 'jquery-ui-datepicker' );
1381
1382
		add_filter( 'gravityview_js_dependencies', array( $this, 'add_datepicker_js_dependency' ) );
1383
		add_filter( 'gravityview_js_localization', array( $this, 'add_datepicker_localization' ), 10, 2 );
1384
1385
		$scheme = is_ssl() ? 'https://' : 'http://';
1386
		wp_enqueue_style( 'jquery-ui-datepicker', $scheme.'ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css' );
1387
1388
		/**
1389
		 * @filter `gravityview_search_datepicker_class`
1390
		 * Modify the CSS class for the datepicker, used by the CSS class is used by Gravity Forms' javascript to determine the format for the date picker. The `gv-datepicker` class is required by the GravityView datepicker javascript.
1391
		 * @param string $css_class CSS class to use. Default: `gv-datepicker datepicker mdy` \n
1392
		 * Options are:
1393
		 * - `mdy` (mm/dd/yyyy)
1394
		 * - `dmy` (dd/mm/yyyy)
1395
		 * - `dmy_dash` (dd-mm-yyyy)
1396
		 * - `dmy_dot` (dd.mm.yyyy)
1397
		 * - `ymd_slash` (yyyy/mm/dd)
1398
		 * - `ymd_dash` (yyyy-mm-dd)
1399
		 * - `ymd_dot` (yyyy.mm.dd)
1400
		 */
1401
		$datepicker_class = apply_filters( 'gravityview_search_datepicker_class', "gv-datepicker datepicker " . $this->get_datepicker_format() );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal gv-datepicker datepicker does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
1402
1403
		$gravityview_view->datepicker_class = $datepicker_class;
0 ignored issues
show
Bug introduced by
The property datepicker_class does not seem to exist in GravityView_View.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1404
1405
	}
1406
1407
	/**
1408
	 * Retrieve the datepicker format.
1409
	 *
1410
	 * @param bool $date_format Whether to return the PHP date format or the datpicker class name. Default: false.
1411
	 *
1412
	 * @see https://docs.gravityview.co/article/115-changing-the-format-of-the-search-widgets-date-picker
1413
	 *
1414
	 * @return string The datepicker format placeholder, or the PHP date format.
1415
	 */
1416 10
	private function get_datepicker_format( $date_format = false ) {
1417
1418 10
		$default_format = 'mdy';
1419
1420
		/**
1421
		 * @filter `gravityview/widgets/search/datepicker/format`
1422
		 * @since 2.1.1
1423
		 * @param string           $format Default: mdy
1424
		 * Options are:
1425
		 * - `mdy` (mm/dd/yyyy)
1426
		 * - `dmy` (dd/mm/yyyy)
1427
		 * - `dmy_dash` (dd-mm-yyyy)
1428
		 * - `dmy_dot` (dd.mm.yyyy)
1429
		 * - `ymd_slash` (yyyy/mm/dd)
1430
		 * - `ymd_dash` (yyyy-mm-dd)
1431
		 * - `ymd_dot` (yyyy.mm.dd)
1432
		 */
1433 10
		$format = apply_filters( 'gravityview/widgets/search/datepicker/format', $default_format );
1434
1435
		$gf_date_formats = array(
1436 10
			'mdy' => 'm/d/Y',
1437
1438
			'dmy_dash' => 'd-m-Y',
1439
			'dmy_dot' => 'd.m.Y',
1440
			'dmy' => 'd/m/Y',
1441
1442
			'ymd_slash' => 'Y/m/d',
1443
			'ymd_dash' => 'Y-m-d',
1444
			'ymd_dot' => 'Y.m.d',
1445
		);
1446
1447 10
		if ( ! $date_format ) {
1448
			// If the format key isn't valid, return default format key
1449
			return isset( $gf_date_formats[ $format ] ) ? $format : $default_format;
1450
		}
1451
1452
		// If the format key isn't valid, return default format value
1453 10
		return \GV\Utils::get( $gf_date_formats, $format, $gf_date_formats[ $default_format ] );
1454
	}
1455
1456
1457
} // end class
1458
1459
new GravityView_Widget_Search;
1460