Completed
Push — instant-search-master ( eab1d5...2448d2 )
by
unknown
11:19 queued 05:30
created

Jetpack_Search_Widget::__construct()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 16
nop 1
dl 0
loc 34
rs 8.7537
c 0
b 0
f 0
1
<?php
2
/**
3
 * Jetpack Search: Jetpack_Search_Widget class
4
 *
5
 * @package    Jetpack
6
 * @subpackage Jetpack Search
7
 * @since      5.0.0
8
 */
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Status;
12
13
add_action( 'widgets_init', 'jetpack_search_widget_init' );
14
15
function jetpack_search_widget_init() {
16
	if (
17
		! Jetpack::is_active()
18
		|| ( method_exists( 'Jetpack_Plan', 'supports' ) && ! Jetpack_Plan::supports( 'search' ) )
19
	) {
20
		return;
21
	}
22
23
	require_once JETPACK__PLUGIN_DIR . 'modules/search/class.jetpack-search-helpers.php';
24
	require_once JETPACK__PLUGIN_DIR . 'modules/search/class.jetpack-search-options.php';
25
26
	register_widget( 'Jetpack_Search_Widget' );
27
}
28
29
/**
30
 * Provides a widget to show available/selected filters on searches.
31
 *
32
 * @since 5.0.0
33
 *
34
 * @see   WP_Widget
35
 */
36
class Jetpack_Search_Widget extends WP_Widget {
37
38
	/**
39
	 * The Jetpack_Search instance.
40
	 *
41
	 * @since 5.7.0
42
	 * @var Jetpack_Search
43
	 */
44
	protected $jetpack_search;
45
46
	/**
47
	 * Number of aggregations (filters) to show by default.
48
	 *
49
	 * @since 5.8.0
50
	 * @var int
51
	 */
52
	const DEFAULT_FILTER_COUNT = 5;
53
54
	/**
55
	 * Default sort order for search results.
56
	 *
57
	 * @since 5.8.0
58
	 * @var string
59
	 */
60
	const DEFAULT_SORT = 'relevance_desc';
61
62
	/**
63
	 * Jetpack_Search_Widget constructor.
64
	 *
65
	 * @since 5.0.0
66
	 */
67
	public function __construct( $name = null ) {
68
		if ( empty( $name ) ) {
69
			$name = esc_html__( 'Search', 'jetpack' );
70
		}
71
		parent::__construct(
72
			Jetpack_Search_Helpers::FILTER_WIDGET_BASE,
73
			/** This filter is documented in modules/widgets/facebook-likebox.php */
74
			apply_filters( 'jetpack_widget_name', $name ),
75
			array(
76
				'classname'   => 'jetpack-filters widget_search',
77
				'description' => __( 'Replaces the default search with an Elasticsearch-powered search interface and filters.', 'jetpack' ),
78
			)
79
		);
80
81
		if (
82
			Jetpack_Search_Helpers::is_active_widget( $this->id ) &&
83
			! $this->is_search_active()
84
		) {
85
			$this->activate_search();
86
		}
87
88
		if ( is_admin() ) {
89
			add_action( 'sidebar_admin_setup', array( $this, 'widget_admin_setup' ) );
90
		} else {
91
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
92
		}
93
94
		add_action( 'jetpack_search_render_filters_widget_title', array( 'Jetpack_Search_Template_Tags', 'render_widget_title' ), 10, 3 );
95
		if ( Jetpack_Search_Options::is_instant_enabled() ) {
96
			add_action( 'jetpack_search_render_filters', array( 'Jetpack_Search_Template_Tags', 'render_instant_filters' ), 10, 2 );
97
		} else {
98
			add_action( 'jetpack_search_render_filters', array( 'Jetpack_Search_Template_Tags', 'render_available_filters' ), 10, 2 );
99
		}
100
	}
101
102
	/**
103
	 * Check whether search is currently active
104
	 *
105
	 * @since 6.3
106
	 */
107
	public function is_search_active() {
108
		return Jetpack::is_module_active( 'search' );
109
	}
110
111
	/**
112
	 * Activate search
113
	 *
114
	 * @since 6.3
115
	 */
116
	public function activate_search() {
117
		Jetpack::activate_module( 'search', false, false );
118
	}
119
120
121
	/**
122
	 * Enqueues the scripts and styles needed for the customizer.
123
	 *
124
	 * @since 5.7.0
125
	 */
126
	public function widget_admin_setup() {
127
		wp_enqueue_style( 'widget-jetpack-search-filters', plugins_url( 'search/css/search-widget-admin-ui.css', __FILE__ ) );
128
129
		// Required for Tracks
130
		wp_register_script(
131
			'jp-tracks',
132
			'//stats.wp.com/w.js',
133
			array(),
134
			gmdate( 'YW' ),
135
			true
136
		);
137
138
		wp_register_script(
139
			'jp-tracks-functions',
140
			plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
141
			array(),
142
			JETPACK__VERSION,
143
			false
144
		);
145
146
		wp_register_script(
147
			'jetpack-search-widget-admin',
148
			plugins_url( 'search/js/search-widget-admin.js', __FILE__ ),
149
			array( 'jquery', 'jquery-ui-sortable', 'jp-tracks', 'jp-tracks-functions' ),
150
			JETPACK__VERSION
151
		);
152
153
		wp_localize_script(
154
			'jetpack-search-widget-admin', 'jetpack_search_filter_admin', array(
155
				'defaultFilterCount' => self::DEFAULT_FILTER_COUNT,
156
				'tracksUserData'     => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
157
				'tracksEventData'    => array(
158
					'is_customizer' => (int) is_customize_preview(),
159
				),
160
				'i18n'               => array(
161
					'month'        => Jetpack_Search_Helpers::get_date_filter_type_name( 'month', false ),
162
					'year'         => Jetpack_Search_Helpers::get_date_filter_type_name( 'year', false ),
163
					'monthUpdated' => Jetpack_Search_Helpers::get_date_filter_type_name( 'month', true ),
164
					'yearUpdated'  => Jetpack_Search_Helpers::get_date_filter_type_name( 'year', true ),
165
				),
166
			)
167
		);
168
169
		wp_enqueue_script( 'jetpack-search-widget-admin' );
170
	}
171
172
	/**
173
	 * Enqueue scripts and styles for the frontend.
174
	 *
175
	 * @since 5.8.0
176
	 */
177
	public function enqueue_frontend_scripts() {
178
		if ( ! is_active_widget( false, false, $this->id_base, true ) || Jetpack_Search_Options::is_instant_enabled() ) {
179
			return;
180
		}
181
182
		wp_enqueue_script(
183
			'jetpack-search-widget',
184
			plugins_url( 'search/js/search-widget.js', __FILE__ ),
185
			array( 'jquery' ),
186
			JETPACK__VERSION,
187
			true
188
		);
189
190
		wp_enqueue_style( 'jetpack-search-widget', plugins_url( 'search/css/search-widget-frontend.css', __FILE__ ) );
191
	}
192
193
	/**
194
	 * Get the list of valid sort types/orders.
195
	 *
196
	 * @since 5.8.0
197
	 *
198
	 * @return array The sort orders.
199
	 */
200
	private function get_sort_types() {
201
		return array(
202
			'relevance|DESC' => is_admin() ? esc_html__( 'Relevance (recommended)', 'jetpack' ) : esc_html__( 'Relevance', 'jetpack' ),
203
			'date|DESC'      => esc_html__( 'Newest first', 'jetpack' ),
204
			'date|ASC'       => esc_html__( 'Oldest first', 'jetpack' ),
205
		);
206
	}
207
208
	/**
209
	 * Callback for an array_filter() call in order to only get filters for the current widget.
210
	 *
211
	 * @see   Jetpack_Search_Widget::widget()
212
	 *
213
	 * @since 5.7.0
214
	 *
215
	 * @param array $item Filter item.
216
	 *
217
	 * @return bool Whether the current filter item is for the current widget.
218
	 */
219
	function is_for_current_widget( $item ) {
220
		return isset( $item['widget_id'] ) && $this->id == $item['widget_id'];
221
	}
222
223
	/**
224
	 * This method returns a boolean for whether the widget should show site-wide filters for the site.
225
	 *
226
	 * This is meant to provide backwards-compatibility for VIP, and other professional plan users, that manually
227
	 * configured filters via `Jetpack_Search::set_filters()`.
228
	 *
229
	 * @since 5.7.0
230
	 *
231
	 * @return bool Whether the widget should display site-wide filters or not.
232
	 */
233
	public function should_display_sitewide_filters() {
234
		$filter_widgets = get_option( 'widget_jetpack-search-filters' );
235
236
		// This shouldn't be empty, but just for sanity
237
		if ( empty( $filter_widgets ) ) {
238
			return false;
239
		}
240
241
		// If any widget has any filters, return false
242
		foreach ( $filter_widgets as $number => $widget ) {
243
			$widget_id = sprintf( '%s-%d', $this->id_base, $number );
244
			if ( ! empty( $widget['filters'] ) && is_active_widget( false, $widget_id, $this->id_base ) ) {
245
				return false;
246
			}
247
		}
248
249
		return true;
250
	}
251
252
	public function jetpack_search_populate_defaults( $instance ) {
253
		$instance = wp_parse_args(
254
			(array) $instance, array(
255
				'title'              => '',
256
				'search_box_enabled' => true,
257
				'user_sort_enabled'  => true,
258
				'sort'               => self::DEFAULT_SORT,
259
				'filters'            => array( array() ),
260
				'post_types'         => array(),
261
			)
262
		);
263
264
		return $instance;
265
	}
266
267
	/**
268
	 * Responsible for rendering the widget on the frontend.
269
	 *
270
	 * @since 5.0.0
271
	 *
272
	 * @param array $args     Widgets args supplied by the theme.
273
	 * @param array $instance The current widget instance.
274
	 */
275
	public function widget( $args, $instance ) {
276
		$instance = $this->jetpack_search_populate_defaults( $instance );
277
278
		if ( ( new Status() )->is_development_mode() ) {
279
			echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
280
			?><div id="<?php echo esc_attr( $this->id ); ?>-wrapper">
281
				<div class="jetpack-search-sort-wrapper">
282
					<label>
283
						<?php esc_html_e( 'Jetpack Search not supported in Development Mode', 'jetpack' ); ?>
284
					</label>
285
				</div>
286
			</div><?php
287
			echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
288
			return;
289
		}
290
291
		if ( Jetpack_Search_Options::is_instant_enabled() ) {
292
			if ( 'jetpack-instant-search-sidebar' === $args['id'] ) {
293
				$this->widget_empty_instant( $args, $instance );
294
			} else {
295
				$this->widget_instant( $args, $instance );
296
			}
297
		} else {
298
			$this->widget_non_instant( $args, $instance );
299
		}
300
	}
301
302
	/**
303
	 * Render the non-instant frontend widget.
304
	 *
305
	 * @since 8.3.0
306
	 *
307
	 * @param array $args     Widgets args supplied by the theme.
308
	 * @param array $instance The current widget instance.
309
	 */
310
	public function widget_non_instant( $args, $instance ) {
311
		$display_filters = false;
312
313
		if ( is_search() ) {
314
			if ( Jetpack_Search_Helpers::should_rerun_search_in_customizer_preview() ) {
315
				Jetpack_Search::instance()->update_search_results_aggregations();
316
			}
317
318
			$filters = Jetpack_Search::instance()->get_filters();
319
320 View Code Duplication
			if ( ! Jetpack_Search_Helpers::are_filters_by_widget_disabled() && ! $this->should_display_sitewide_filters() ) {
321
				$filters = array_filter( $filters, array( $this, 'is_for_current_widget' ) );
322
			}
323
324
			if ( ! empty( $filters ) ) {
325
				$display_filters = true;
326
			}
327
		}
328
329
		if ( ! $display_filters && empty( $instance['search_box_enabled'] ) && empty( $instance['user_sort_enabled'] ) ) {
330
			return;
331
		}
332
333
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
334
335
		if ( empty( $title ) ) {
336
			$title = '';
337
		}
338
339
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
340
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
341
342
		echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
343
		?>
344
			<div id="<?php echo esc_attr( $this->id ); ?>-wrapper" >
345
		<?php
346
347
		if ( ! empty( $title ) ) {
348
			/**
349
			 * Responsible for displaying the title of the Jetpack Search filters widget.
350
			 *
351
			 * @module search
352
			 *
353
			 * @since  5.7.0
354
			 *
355
			 * @param string $title                The widget's title
356
			 * @param string $args['before_title'] The HTML tag to display before the title
357
			 * @param string $args['after_title']  The HTML tag to display after the title
358
			 */
359
			do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
360
		}
361
362
		$default_sort            = isset( $instance['sort'] ) ? $instance['sort'] : self::DEFAULT_SORT;
363
		list( $orderby, $order ) = $this->sorting_to_wp_query_param( $default_sort );
364
		$current_sort            = "{$orderby}|{$order}";
365
366
		// we need to dynamically inject the sort field into the search box when the search box is enabled, and display
367
		// it separately when it's not.
368
		if ( ! empty( $instance['search_box_enabled'] ) ) {
369
			Jetpack_Search_Template_Tags::render_widget_search_form( $instance['post_types'], $orderby, $order );
370
		}
371
372
		if ( ! empty( $instance['search_box_enabled'] ) && ! empty( $instance['user_sort_enabled'] ) ) :
373
				?>
374
					<div class="jetpack-search-sort-wrapper">
375
				<label>
376
					<?php esc_html_e( 'Sort by', 'jetpack' ); ?>
377
					<select class="jetpack-search-sort">
378 View Code Duplication
						<?php foreach ( $this->get_sort_types() as $sort => $label ) { ?>
379
							<option value="<?php echo esc_attr( $sort ); ?>" <?php selected( $current_sort, $sort ); ?>>
380
								<?php echo esc_html( $label ); ?>
381
							</option>
382
						<?php } ?>
383
					</select>
384
				</label>
385
			</div>
386
		<?php
387
		endif;
388
389
		if ( $display_filters ) {
390
			/**
391
			 * Responsible for rendering filters to narrow down search results.
392
			 *
393
			 * @module search
394
			 *
395
			 * @since  5.8.0
396
			 *
397
			 * @param array $filters    The possible filters for the current query.
398
			 * @param array $post_types An array of post types to limit filtering to.
399
			 */
400
			do_action(
401
				'jetpack_search_render_filters',
402
				$filters,
0 ignored issues
show
Bug introduced by
The variable $filters does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
403
				isset( $instance['post_types'] ) ? $instance['post_types'] : null
404
			);
405
		}
406
407
		$this->maybe_render_sort_javascript( $instance, $order, $orderby );
408
409
		echo '</div>';
410
		echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
411
	}
412
413
	/**
414
	 * Render the instant frontend widget.
415
	 *
416
	 * @since 8.3.0
417
	 *
418
	 * @param array $args     Widgets args supplied by the theme.
419
	 * @param array $instance The current widget instance.
420
	 */
421
	public function widget_instant( $args, $instance ) {
422
		if ( Jetpack_Search_Helpers::should_rerun_search_in_customizer_preview() ) {
423
			Jetpack_Search::instance()->update_search_results_aggregations();
424
		}
425
426
		$filters = Jetpack_Search::instance()->get_filters();
427
428 View Code Duplication
		if ( ! Jetpack_Search_Helpers::are_filters_by_widget_disabled() && ! $this->should_display_sitewide_filters() ) {
429
			$filters = array_filter( $filters, array( $this, 'is_for_current_widget' ) );
430
		}
431
432
		$display_filters = ! empty( $filters );
433
434
		if ( ! $display_filters && empty( $instance['search_box_enabled'] ) ) {
435
			return;
436
		}
437
438
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
439
440
		if ( empty( $title ) ) {
441
			$title = '';
442
		}
443
444
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
445
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
446
447
		echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
448
		?>
449
			<div id="<?php echo esc_attr( $this->id ); ?>-wrapper" class="jetpack-instant-search-wrapper">
450
		<?php
451
452
		if ( ! empty( $title ) ) {
453
			/**
454
			 * Responsible for displaying the title of the Jetpack Search filters widget.
455
			 *
456
			 * @module search
457
			 *
458
			 * @since  5.7.0
459
			 *
460
			 * @param string $title                The widget's title
461
			 * @param string $args['before_title'] The HTML tag to display before the title
462
			 * @param string $args['after_title']  The HTML tag to display after the title
463
			 */
464
			do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
465
		}
466
467
		// TODO: create new search box?
468
		if ( ! empty( $instance['search_box_enabled'] ) ) {
469
			Jetpack_Search_Template_Tags::render_widget_search_form( array(), '', '' );
470
		}
471
472
		if ( $display_filters ) {
473
			/**
474
			 * Responsible for rendering filters to narrow down search results.
475
			 *
476
			 * @module search
477
			 *
478
			 * @since  5.8.0
479
			 *
480
			 * @param array $filters    The possible filters for the current query.
481
			 * @param array $post_types An array of post types to limit filtering to.
482
			 */
483
			do_action(
484
				'jetpack_search_render_filters',
485
				$filters,
486
				null
487
			);
488
		}
489
490
		echo '</div>';
491
		echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
492
	}
493
494
	/**
495
	 * Render the instant widget for the overlay.
496
	 *
497
	 * @since 8.3.0
498
	 *
499
	 * @param array $args     Widgets args supplied by the theme.
500
	 * @param array $instance The current widget instance.
501
	 */
502
	public function widget_empty_instant( $args, $instance ) {
503
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
504
505
		if ( empty( $title ) ) {
506
			$title = '';
507
		}
508
509
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
510
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
511
512
		echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
513
		?>
514
			<div id="<?php echo esc_attr( $this->id ); ?>-wrapper" class="jetpack-instant-search-wrapper">
515
		<?php
516
517
		if ( ! empty( $title ) ) {
518
			/**
519
			 * Responsible for displaying the title of the Jetpack Search filters widget.
520
			 *
521
			 * @module search
522
			 *
523
			 * @since  5.7.0
524
			 *
525
			 * @param string $title                The widget's title
526
			 * @param string $args['before_title'] The HTML tag to display before the title
527
			 * @param string $args['after_title']  The HTML tag to display after the title
528
			 */
529
			do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
530
		}
531
532
		echo '</div>';
533
		echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
534
	}
535
536
537
	/**
538
	 * Renders JavaScript for the sorting controls on the frontend.
539
	 *
540
	 * This JS is a bit complicated, but here's what it's trying to do:
541
	 * - find the search form
542
	 * - find the orderby/order fields and set default values
543
	 * - detect changes to the sort field, if it exists, and use it to set the order field values
544
	 *
545
	 * @since 5.8.0
546
	 *
547
	 * @param array  $instance The current widget instance.
548
	 * @param string $order    The order to initialize the select with.
549
	 * @param string $orderby  The orderby to initialize the select with.
550
	 */
551
	private function maybe_render_sort_javascript( $instance, $order, $orderby ) {
552
		if ( Jetpack_Search_Options::is_instant_enabled() ) {
553
			return;
554
		}
555
556
		if ( ! empty( $instance['user_sort_enabled'] ) ) :
557
		?>
558
		<script type="text/javascript">
559
				jQuery( document ).ready( function( $ ) {
560
					var orderByDefault = '<?php echo 'date' === $orderby ? 'date' : 'relevance'; ?>',
561
						orderDefault   = '<?php echo 'ASC' === $order ? 'ASC' : 'DESC'; ?>',
562
						widgetId       = decodeURIComponent( '<?php echo rawurlencode( $this->id ); ?>' ),
563
						searchQuery    = decodeURIComponent( '<?php echo rawurlencode( get_query_var( 's', '' ) ); ?>' ),
564
						isSearch       = <?php echo (int) is_search(); ?>;
565
566
					var container = $( '#' + widgetId + '-wrapper' ),
567
						form = container.find('.jetpack-search-form form'),
568
						orderBy = form.find( 'input[name=orderby]'),
569
						order = form.find( 'input[name=order]'),
570
						searchInput = form.find( 'input[name="s"]' );
571
572
					orderBy.val( orderByDefault );
573
					order.val( orderDefault );
574
575
					// Some themes don't set the search query, which results in the query being lost
576
					// when doing a sort selection. So, if the query isn't set, let's set it now. This approach
577
					// is chosen over running a regex over HTML for every search query performed.
578
					if ( isSearch && ! searchInput.val() ) {
579
						searchInput.val( searchQuery );
580
					}
581
582
					searchInput.addClass( 'show-placeholder' );
583
584
					container.find( '.jetpack-search-sort' ).change( function( event ) {
585
						var values  = event.target.value.split( '|' );
586
						orderBy.val( values[0] );
587
						order.val( values[1] );
588
589
						form.submit();
590
					});
591
				} );
592
			</script>
593
		<?php
594
		endif;
595
	}
596
597
	/**
598
	 * Convert a sort string into the separate order by and order parts.
599
	 *
600
	 * @since 5.8.0
601
	 *
602
	 * @param string $sort A sort string.
603
	 *
604
	 * @return array Order by and order.
605
	 */
606
	private function sorting_to_wp_query_param( $sort ) {
607
		$parts   = explode( '|', $sort );
608
		$orderby = isset( $_GET['orderby'] )
609
			? $_GET['orderby']
610
			: $parts[0];
611
612
		$order = isset( $_GET['order'] )
613
			? strtoupper( $_GET['order'] )
614
			: ( ( isset( $parts[1] ) && 'ASC' === strtoupper( $parts[1] ) ) ? 'ASC' : 'DESC' );
615
616
		return array( $orderby, $order );
617
	}
618
619
	/**
620
	 * Updates a particular instance of the widget. Validates and sanitizes the options.
621
	 *
622
	 * @since 5.0.0
623
	 *
624
	 * @param array $new_instance New settings for this instance as input by the user via Jetpack_Search_Widget::form().
625
	 * @param array $old_instance Old settings for this instance.
626
	 *
627
	 * @return array Settings to save.
628
	 */
629
	public function update( $new_instance, $old_instance ) {
630
		$instance = array();
631
632
		$instance['title']              = sanitize_text_field( $new_instance['title'] );
633
		$instance['search_box_enabled'] = empty( $new_instance['search_box_enabled'] ) ? '0' : '1';
634
		$instance['user_sort_enabled']  = empty( $new_instance['user_sort_enabled'] ) ? '0' : '1';
635
		$instance['sort']               = $new_instance['sort'];
636
		$instance['post_types']         = empty( $new_instance['post_types'] ) || empty( $instance['search_box_enabled'] )
637
			? array()
638
			: array_map( 'sanitize_key', $new_instance['post_types'] );
639
640
		$filters = array();
641
		if ( isset( $new_instance['filter_type'] ) ) {
642
			foreach ( (array) $new_instance['filter_type'] as $index => $type ) {
643
				$count = intval( $new_instance['num_filters'][ $index ] );
644
				$count = min( 50, $count ); // Set max boundary at 50.
645
				$count = max( 1, $count );  // Set min boundary at 1.
646
647
				switch ( $type ) {
648
					case 'taxonomy':
649
						$filters[] = array(
650
							'name'     => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
651
							'type'     => 'taxonomy',
652
							'taxonomy' => sanitize_key( $new_instance['taxonomy_type'][ $index ] ),
653
							'count'    => $count,
654
						);
655
						break;
656
					case 'post_type':
657
						$filters[] = array(
658
							'name'  => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
659
							'type'  => 'post_type',
660
							'count' => $count,
661
						);
662
						break;
663
					case 'date_histogram':
664
						$filters[] = array(
665
							'name'     => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
666
							'type'     => 'date_histogram',
667
							'count'    => $count,
668
							'field'    => sanitize_key( $new_instance['date_histogram_field'][ $index ] ),
669
							'interval' => sanitize_key( $new_instance['date_histogram_interval'][ $index ] ),
670
						);
671
						break;
672
				}
673
			}
674
		}
675
676
		if ( ! empty( $filters ) ) {
677
			$instance['filters'] = $filters;
678
		}
679
680
		return $instance;
681
	}
682
683
	/**
684
	 * Outputs the settings update form.
685
	 *
686
	 * @since 5.0.0
687
	 *
688
	 * @param array $instance Current settings.
689
	 */
690
	public function form( $instance ) {
691
		$instance = $this->jetpack_search_populate_defaults( $instance );
692
693
		$title = strip_tags( $instance['title'] );
694
695
		$hide_filters = Jetpack_Search_Helpers::are_filters_by_widget_disabled();
696
697
		$classes = sprintf(
698
			'jetpack-search-filters-widget %s %s %s',
699
			$hide_filters ? 'hide-filters' : '',
700
			$instance['search_box_enabled'] ? '' : 'hide-post-types',
701
			$this->id
702
		);
703
		?>
704
		<div class="<?php echo esc_attr( $classes ); ?>">
705
			<p>
706
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
707
					<?php esc_html_e( 'Title (optional):', 'jetpack' ); ?>
708
				</label>
709
				<input
710
					class="widefat"
711
					id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
712
					name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
713
					type="text"
714
					value="<?php echo esc_attr( $title ); ?>"
715
				/>
716
			</p>
717
718
			<p>
719
				<label>
720
					<input
721
						type="checkbox"
722
						class="jetpack-search-filters-widget__search-box-enabled"
723
						name="<?php echo esc_attr( $this->get_field_name( 'search_box_enabled' ) ); ?>"
724
						<?php checked( $instance['search_box_enabled'] ); ?>
725
					/>
726
					<?php esc_html_e( 'Show search box', 'jetpack' ); ?>
727
				</label>
728
			</p>
729
			<p>
730
				<label>
731
					<input
732
						type="checkbox"
733
						class="jetpack-search-filters-widget__sort-controls-enabled"
734
						name="<?php echo esc_attr( $this->get_field_name( 'user_sort_enabled' ) ); ?>"
735
						<?php checked( $instance['user_sort_enabled'] ); ?>
736
						<?php disabled( ! $instance['search_box_enabled'] ); ?>
737
					/>
738
					<?php esc_html_e( 'Show sort selection dropdown', 'jetpack' ); ?>
739
				</label>
740
			</p>
741
742
			<p class="jetpack-search-filters-widget__post-types-select">
743
				<label><?php esc_html_e( 'Post types to search (minimum of 1):', 'jetpack' ); ?></label>
744
				<?php foreach ( get_post_types( array( 'exclude_from_search' => false ), 'objects' ) as $post_type ) : ?>
745
					<label>
746
						<input
747
							type="checkbox"
748
							value="<?php echo esc_attr( $post_type->name ); ?>"
749
							name="<?php echo esc_attr( $this->get_field_name( 'post_types' ) ); ?>[]"
750
							<?php checked( empty( $instance['post_types'] ) || in_array( $post_type->name, $instance['post_types'] ) ); ?>
751
						/>&nbsp;
752
						<?php echo esc_html( $post_type->label ); ?>
753
					</label>
754
				<?php endforeach; ?>
755
			</p>
756
757
			<p>
758
				<label>
759
					<?php esc_html_e( 'Default sort order:', 'jetpack' ); ?>
760
					<select
761
						name="<?php echo esc_attr( $this->get_field_name( 'sort' ) ); ?>"
762
						class="widefat jetpack-search-filters-widget__sort-order">
763 View Code Duplication
						<?php foreach ( $this->get_sort_types() as $sort_type => $label ) { ?>
764
							<option value="<?php echo esc_attr( $sort_type ); ?>" <?php selected( $instance['sort'], $sort_type ); ?>>
765
								<?php echo esc_html( $label ); ?>
766
							</option>
767
						<?php } ?>
768
					</select>
769
				</label>
770
			</p>
771
772
			<?php if ( ! $hide_filters ) : ?>
773
				<script class="jetpack-search-filters-widget__filter-template" type="text/template">
774
					<?php echo $this->render_widget_edit_filter( array(), true ); ?>
775
				</script>
776
				<div class="jetpack-search-filters-widget__filters">
777
					<?php foreach ( (array) $instance['filters'] as $filter ) : ?>
778
						<?php $this->render_widget_edit_filter( $filter ); ?>
779
					<?php endforeach; ?>
780
				</div>
781
				<p class="jetpack-search-filters-widget__add-filter-wrapper">
782
					<a class="button jetpack-search-filters-widget__add-filter" href="#">
783
						<?php esc_html_e( 'Add a filter', 'jetpack' ); ?>
784
					</a>
785
				</p>
786
				<noscript>
787
					<p class="jetpack-search-filters-help">
788
						<?php echo esc_html_e( 'Adding filters requires JavaScript!', 'jetpack' ); ?>
789
					</p>
790
				</noscript>
791
				<?php if ( is_customize_preview() ) : ?>
792
					<p class="jetpack-search-filters-help">
793
						<a href="https://jetpack.com/support/search/#filters-not-showing-up" target="_blank">
794
							<?php esc_html_e( "Why aren't my filters appearing?", 'jetpack' ); ?>
795
						</a>
796
					</p>
797
				<?php endif; ?>
798
			<?php endif; ?>
799
		</div>
800
		<?php
801
	}
802
803
	/**
804
	 * We need to render HTML in two formats: an Underscore template (client-side)
805
	 * and native PHP (server-side). This helper function allows for easy rendering
806
	 * of attributes in both formats.
807
	 *
808
	 * @since 5.8.0
809
	 *
810
	 * @param string $name        Attribute name.
811
	 * @param string $value       Attribute value.
812
	 * @param bool   $is_template Whether this is for an Underscore template or not.
813
	 */
814
	private function render_widget_attr( $name, $value, $is_template ) {
815
		echo $is_template ? "<%= $name %>" : esc_attr( $value );
816
	}
817
818
	/**
819
	 * We need to render HTML in two formats: an Underscore template (client-size)
820
	 * and native PHP (server-side). This helper function allows for easy rendering
821
	 * of the "selected" attribute in both formats.
822
	 *
823
	 * @since 5.8.0
824
	 *
825
	 * @param string $name        Attribute name.
826
	 * @param string $value       Attribute value.
827
	 * @param string $compare     Value to compare to the attribute value to decide if it should be selected.
828
	 * @param bool   $is_template Whether this is for an Underscore template or not.
829
	 */
830
	private function render_widget_option_selected( $name, $value, $compare, $is_template ) {
831
		$compare_js = rawurlencode( $compare );
832
		echo $is_template ? "<%= decodeURIComponent( '$compare_js' ) === $name ? 'selected=\"selected\"' : '' %>" : selected( $value, $compare );
833
	}
834
835
	/**
836
	 * Responsible for rendering a single filter in the customizer or the widget administration screen in wp-admin.
837
	 *
838
	 * We use this method for two purposes - rendering the fields server-side, and also rendering a script template for Underscore.
839
	 *
840
	 * @since 5.7.0
841
	 *
842
	 * @param array $filter      The filter to render.
843
	 * @param bool  $is_template Whether this is for an Underscore template or not.
844
	 */
845
	public function render_widget_edit_filter( $filter, $is_template = false ) {
846
		$args = wp_parse_args(
847
			$filter, array(
848
				'name'      => '',
849
				'type'      => 'taxonomy',
850
				'taxonomy'  => '',
851
				'post_type' => '',
852
				'field'     => '',
853
				'interval'  => '',
854
				'count'     => self::DEFAULT_FILTER_COUNT,
855
			)
856
		);
857
858
		$args['name_placeholder'] = Jetpack_Search_Helpers::generate_widget_filter_name( $args );
859
860
		?>
861
		<div class="jetpack-search-filters-widget__filter is-<?php $this->render_widget_attr( 'type', $args['type'], $is_template ); ?>">
862
			<p class="jetpack-search-filters-widget__type-select">
863
				<label>
864
					<?php esc_html_e( 'Filter Type:', 'jetpack' ); ?>
865
					<select name="<?php echo esc_attr( $this->get_field_name( 'filter_type' ) ); ?>[]" class="widefat filter-select">
866
						<option value="taxonomy" <?php $this->render_widget_option_selected( 'type', $args['type'], 'taxonomy', $is_template ); ?>>
867
							<?php esc_html_e( 'Taxonomy', 'jetpack' ); ?>
868
						</option>
869
						<option value="post_type" <?php $this->render_widget_option_selected( 'type', $args['type'], 'post_type', $is_template ); ?>>
870
							<?php esc_html_e( 'Post Type', 'jetpack' ); ?>
871
						</option>
872
						<option value="date_histogram" <?php $this->render_widget_option_selected( 'type', $args['type'], 'date_histogram', $is_template ); ?>>
873
							<?php esc_html_e( 'Date', 'jetpack' ); ?>
874
						</option>
875
					</select>
876
				</label>
877
			</p>
878
879
			<p class="jetpack-search-filters-widget__taxonomy-select">
880
				<label>
881
					<?php
882
						esc_html_e( 'Choose a taxonomy:', 'jetpack' );
883
						$seen_taxonomy_labels = array();
884
					?>
885
					<select name="<?php echo esc_attr( $this->get_field_name( 'taxonomy_type' ) ); ?>[]" class="widefat taxonomy-select">
886
						<?php foreach ( get_taxonomies( array( 'public' => true ), 'objects' ) as $taxonomy ) : ?>
887
							<option value="<?php echo esc_attr( $taxonomy->name ); ?>" <?php $this->render_widget_option_selected( 'taxonomy', $args['taxonomy'], $taxonomy->name, $is_template ); ?>>
888
								<?php
889
									$label = in_array( $taxonomy->label, $seen_taxonomy_labels )
890
										? sprintf(
891
											/* translators: %1$s is the taxonomy name, %2s is the name of its type to help distinguish between several taxonomies with the same name, e.g. category and tag. */
892
											_x( '%1$s (%2$s)', 'A label for a taxonomy selector option', 'jetpack' ),
893
											$taxonomy->label,
894
											$taxonomy->name
895
										)
896
										: $taxonomy->label;
897
									echo esc_html( $label );
898
									$seen_taxonomy_labels[] = $taxonomy->label;
899
								?>
900
							</option>
901
						<?php endforeach; ?>
902
					</select>
903
				</label>
904
			</p>
905
906
			<p class="jetpack-search-filters-widget__date-histogram-select">
907
				<label>
908
					<?php esc_html_e( 'Choose a field:', 'jetpack' ); ?>
909
					<select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_field' ) ); ?>[]" class="widefat date-field-select">
910
						<option value="post_date" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date', $is_template ); ?>>
911
							<?php esc_html_e( 'Date', 'jetpack' ); ?>
912
						</option>
913
						<option value="post_date_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date_gmt', $is_template ); ?>>
914
							<?php esc_html_e( 'Date GMT', 'jetpack' ); ?>
915
						</option>
916
						<option value="post_modified" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified', $is_template ); ?>>
917
							<?php esc_html_e( 'Modified', 'jetpack' ); ?>
918
						</option>
919
						<option value="post_modified_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified_gmt', $is_template ); ?>>
920
							<?php esc_html_e( 'Modified GMT', 'jetpack' ); ?>
921
						</option>
922
					</select>
923
				</label>
924
			</p>
925
926
			<p class="jetpack-search-filters-widget__date-histogram-select">
927
				<label>
928
					<?php esc_html_e( 'Choose an interval:' ); ?>
929
					<select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_interval' ) ); ?>[]" class="widefat date-interval-select">
930
						<option value="month" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'month', $is_template ); ?>>
931
							<?php esc_html_e( 'Month', 'jetpack' ); ?>
932
						</option>
933
						<option value="year" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'year', $is_template ); ?>>
934
							<?php esc_html_e( 'Year', 'jetpack' ); ?>
935
						</option>
936
					</select>
937
				</label>
938
			</p>
939
940
			<p class="jetpack-search-filters-widget__title">
941
				<label>
942
					<?php esc_html_e( 'Title:', 'jetpack' ); ?>
943
					<input
944
						class="widefat"
945
						type="text"
946
						name="<?php echo esc_attr( $this->get_field_name( 'filter_name' ) ); ?>[]"
947
						value="<?php $this->render_widget_attr( 'name', $args['name'], $is_template ); ?>"
948
						placeholder="<?php $this->render_widget_attr( 'name_placeholder', $args['name_placeholder'], $is_template ); ?>"
949
					/>
950
				</label>
951
			</p>
952
953
			<p>
954
				<label>
955
					<?php esc_html_e( 'Maximum number of filters (1-50):', 'jetpack' ); ?>
956
					<input
957
						class="widefat filter-count"
958
						name="<?php echo esc_attr( $this->get_field_name( 'num_filters' ) ); ?>[]"
959
						type="number"
960
						value="<?php $this->render_widget_attr( 'count', $args['count'], $is_template ); ?>"
961
						min="1"
962
						max="50"
963
						step="1"
964
						required
965
					/>
966
				</label>
967
			</p>
968
969
			<p class="jetpack-search-filters-widget__controls">
970
				<a href="#" class="delete"><?php esc_html_e( 'Remove', 'jetpack' ); ?></a>
971
			</p>
972
		</div>
973
	<?php
974
	}
975
}
976