PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.5.3
Jetpack – WP Security, Backup, Speed, & Growth v10.5.3
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / widgets / search.php
search.php
1,084 lines 36.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
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\Redirect;
11 use Automattic\Jetpack\Search\Helper;
12 use Automattic\Jetpack\Search\Options;
13 use Automattic\Jetpack\Status;
14 use Automattic\Jetpack\Tracking;
15
16 add_action( 'widgets_init', 'jetpack_search_widget_init' );
17
18 /**
19 * Register the widget if Jetpack Search is available and enabled.
20 */
21 function jetpack_search_widget_init() {
22 if (
23 ! Jetpack::is_connection_ready()
24 || ( method_exists( 'Jetpack_Plan', 'supports' ) && ! Jetpack_Plan::supports( 'search' ) )
25 || ! Jetpack::is_module_active( 'search' )
26 ) {
27 return;
28 }
29
30 register_widget( 'Jetpack_Search_Widget' );
31 }
32
33 /**
34 * Provides a widget to show available/selected filters on searches.
35 *
36 * @since 5.0.0
37 *
38 * @see WP_Widget
39 */
40 class Jetpack_Search_Widget extends WP_Widget {
41
42 /**
43 * The Jetpack_Search instance.
44 *
45 * @since 5.7.0
46 * @var Jetpack_Search
47 */
48 protected $jetpack_search;
49
50 /**
51 * Number of aggregations (filters) to show by default.
52 *
53 * @since 5.8.0
54 * @var int
55 */
56 const DEFAULT_FILTER_COUNT = 5;
57
58 /**
59 * Default sort order for search results.
60 *
61 * @since 5.8.0
62 * @var string
63 */
64 const DEFAULT_SORT = 'relevance_desc';
65
66 /**
67 * Jetpack_Search_Widget constructor.
68 *
69 * @since 5.0.0
70 *
71 * @param string $name Widget name.
72 */
73 public function __construct( $name = null ) {
74 if ( empty( $name ) ) {
75 $name = esc_html__( 'Search', 'jetpack' );
76 }
77 parent::__construct(
78 Helper::FILTER_WIDGET_BASE,
79 /** This filter is documented in modules/widgets/facebook-likebox.php */
80 apply_filters( 'jetpack_widget_name', $name ),
81 array(
82 'classname' => 'jetpack-filters widget_search',
83 'description' => __( 'Instant search and filtering to help visitors quickly find relevant answers and explore your site.', 'jetpack' ),
84 )
85 );
86
87 if (
88 Helper::is_active_widget( $this->id ) &&
89 ! $this->is_search_active()
90 ) {
91 $this->activate_search();
92 }
93
94 if ( is_admin() ) {
95 add_action( 'sidebar_admin_setup', array( $this, 'widget_admin_setup' ) );
96 } else {
97 add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
98 }
99
100 add_action( 'jetpack_search_render_filters_widget_title', array( 'Automattic\Jetpack\Search\Template_Tags', 'render_widget_title' ), 10, 3 );
101 if ( Options::is_instant_enabled() ) {
102 add_action( 'jetpack_search_render_filters', array( 'Automattic\Jetpack\Search\Template_Tags', 'render_instant_filters' ), 10, 2 );
103 } else {
104 add_action( 'jetpack_search_render_filters', array( 'Automattic\Jetpack\Search\Template_Tags', 'render_available_filters' ), 10, 2 );
105 }
106 }
107
108 /**
109 * Check whether search is currently active
110 *
111 * @since 6.3
112 */
113 public function is_search_active() {
114 return Jetpack::is_module_active( 'search' );
115 }
116
117 /**
118 * Activate search
119 *
120 * @since 6.3
121 */
122 public function activate_search() {
123 Jetpack::activate_module( 'search', false, false );
124 }
125
126 /**
127 * Enqueues the scripts and styles needed for the customizer.
128 *
129 * @since 5.7.0
130 */
131 public function widget_admin_setup() {
132 wp_enqueue_style(
133 'widget-jetpack-search-filters',
134 plugins_url( 'search/css/search-widget-admin-ui.css', __FILE__ ),
135 array(),
136 JETPACK__VERSION
137 );
138
139 // Register jp-tracks and jp-tracks-functions.
140 Tracking::register_tracks_functions_scripts();
141
142 wp_register_script(
143 'jetpack-search-widget-admin',
144 plugins_url( 'search/js/search-widget-admin.js', __FILE__ ),
145 array( 'jquery', 'jquery-ui-sortable', 'jp-tracks-functions' ),
146 JETPACK__VERSION,
147 false
148 );
149
150 wp_localize_script(
151 'jetpack-search-widget-admin',
152 'jetpack_search_filter_admin',
153 array(
154 'defaultFilterCount' => self::DEFAULT_FILTER_COUNT,
155 'tracksUserData' => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
156 'tracksEventData' => array(
157 'is_customizer' => (int) is_customize_preview(),
158 ),
159 'i18n' => array(
160 'month' => Helper::get_date_filter_type_name( 'month', false ),
161 'year' => Helper::get_date_filter_type_name( 'year', false ),
162 'monthUpdated' => Helper::get_date_filter_type_name( 'month', true ),
163 'yearUpdated' => Helper::get_date_filter_type_name( 'year', true ),
164 ),
165 )
166 );
167
168 wp_enqueue_script( 'jetpack-search-widget-admin' );
169 }
170
171 /**
172 * Enqueue scripts and styles for the frontend.
173 *
174 * @since 5.8.0
175 */
176 public function enqueue_frontend_scripts() {
177 if ( ! is_active_widget( false, false, $this->id_base, true ) || Options::is_instant_enabled() ) {
178 return;
179 }
180
181 wp_enqueue_script(
182 'jetpack-search-widget',
183 plugins_url( 'search/js/search-widget.js', __FILE__ ),
184 array(),
185 JETPACK__VERSION,
186 true
187 );
188
189 wp_enqueue_style(
190 'jetpack-search-widget',
191 plugins_url( 'search/css/search-widget-frontend.css', __FILE__ ),
192 array(),
193 JETPACK__VERSION
194 );
195 }
196
197 /**
198 * Get the list of valid sort types/orders.
199 *
200 * @since 5.8.0
201 *
202 * @return array The sort orders.
203 */
204 private function get_sort_types() {
205 return array(
206 'relevance|DESC' => is_admin() ? esc_html__( 'Relevance (recommended)', 'jetpack' ) : esc_html__( 'Relevance', 'jetpack' ),
207 'date|DESC' => esc_html__( 'Newest first', 'jetpack' ),
208 'date|ASC' => esc_html__( 'Oldest first', 'jetpack' ),
209 );
210 }
211
212 /**
213 * Callback for an array_filter() call in order to only get filters for the current widget.
214 *
215 * @see Jetpack_Search_Widget::widget()
216 *
217 * @since 5.7.0
218 *
219 * @param array $item Filter item.
220 *
221 * @return bool Whether the current filter item is for the current widget.
222 */
223 public function is_for_current_widget( $item ) {
224 return isset( $item['widget_id'] ) && $this->id == $item['widget_id']; // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
225 }
226
227 /**
228 * This method returns a boolean for whether the widget should show site-wide filters for the site.
229 *
230 * This is meant to provide backwards-compatibility for VIP, and other professional plan users, that manually
231 * configured filters via `Jetpack_Search::set_filters()`.
232 *
233 * @since 5.7.0
234 *
235 * @return bool Whether the widget should display site-wide filters or not.
236 */
237 public function should_display_sitewide_filters() {
238 $filter_widgets = get_option( 'widget_jetpack-search-filters' );
239
240 // This shouldn't be empty, but just for sanity.
241 if ( empty( $filter_widgets ) ) {
242 return false;
243 }
244
245 // If any widget has any filters, return false.
246 foreach ( $filter_widgets as $number => $widget ) {
247 $widget_id = sprintf( '%s-%d', $this->id_base, $number );
248 if ( ! empty( $widget['filters'] ) && is_active_widget( false, $widget_id, $this->id_base ) ) {
249 return false;
250 }
251 }
252
253 return true;
254 }
255
256 /**
257 * Widget defaults.
258 *
259 * @param array $instance Previously saved values from database.
260 */
261 public function jetpack_search_populate_defaults( $instance ) {
262 $instance = wp_parse_args(
263 (array) $instance,
264 array(
265 'title' => '',
266 'search_box_enabled' => true,
267 'user_sort_enabled' => true,
268 'sort' => self::DEFAULT_SORT,
269 'filters' => array( array() ),
270 'post_types' => array(),
271 )
272 );
273
274 return $instance;
275 }
276
277 /**
278 * Populates the instance array with appropriate default values.
279 *
280 * @since 8.6.0
281 * @param array $instance Previously saved values from database.
282 * @return array Instance array with default values approprate for instant search
283 */
284 public function populate_defaults_for_instant_search( $instance ) {
285 return wp_parse_args(
286 (array) $instance,
287 array(
288 'title' => '',
289 'filters' => array(),
290 )
291 );
292 }
293
294 /**
295 * Responsible for rendering the widget on the frontend.
296 *
297 * @since 5.0.0
298 *
299 * @param array $args Widgets args supplied by the theme.
300 * @param array $instance The current widget instance.
301 */
302 public function widget( $args, $instance ) {
303 $instance = $this->jetpack_search_populate_defaults( $instance );
304
305 if ( ( new Status() )->is_offline_mode() ) {
306 echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
307 ?><div id="<?php echo esc_attr( $this->id ); ?>-wrapper">
308 <div class="jetpack-search-sort-wrapper">
309 <label>
310 <?php esc_html_e( 'Jetpack Search not supported in Offline Mode', 'jetpack' ); ?>
311 </label>
312 </div>
313 </div>
314 <?php
315 echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
316 return;
317 }
318
319 if ( Options::is_instant_enabled() ) {
320 if ( array_key_exists( 'id', $args ) && 'jetpack-instant-search-sidebar' === $args['id'] ) {
321 $this->widget_empty_instant( $args, $instance );
322 } else {
323 $this->widget_instant( $args, $instance );
324 }
325 } else {
326 $this->widget_non_instant( $args, $instance );
327 }
328 }
329
330 /**
331 * Render the non-instant frontend widget.
332 *
333 * @since 8.3.0
334 *
335 * @param array $args Widgets args supplied by the theme.
336 * @param array $instance The current widget instance.
337 */
338 public function widget_non_instant( $args, $instance ) {
339 $display_filters = false;
340
341 if ( is_search() ) {
342 if ( Helper::should_rerun_search_in_customizer_preview() ) {
343 Jetpack_Search::instance()->update_search_results_aggregations();
344 }
345
346 $filters = Jetpack_Search::instance()->get_filters();
347
348 if ( ! Helper::are_filters_by_widget_disabled() && ! $this->should_display_sitewide_filters() ) {
349 $filters = array_filter( $filters, array( $this, 'is_for_current_widget' ) );
350 }
351
352 if ( ! empty( $filters ) ) {
353 $display_filters = true;
354 }
355 }
356
357 if ( ! $display_filters && empty( $instance['search_box_enabled'] ) && empty( $instance['user_sort_enabled'] ) ) {
358 return;
359 }
360
361 $title = ! empty( $instance['title'] ) ? $instance['title'] : '';
362
363 /** This filter is documented in core/src/wp-includes/default-widgets.php */
364 $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
365
366 echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
367 ?>
368 <div id="<?php echo esc_attr( $this->id ); ?>-wrapper" >
369 <?php
370
371 if ( ! empty( $title ) ) {
372 /**
373 * Responsible for displaying the title of the Jetpack Search filters widget.
374 *
375 * @module search
376 *
377 * @since 5.7.0
378 *
379 * @param string $title The widget's title
380 * @param string $args['before_title'] The HTML tag to display before the title
381 * @param string $args['after_title'] The HTML tag to display after the title
382 */
383 do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
384 }
385
386 $default_sort = isset( $instance['sort'] ) ? $instance['sort'] : self::DEFAULT_SORT;
387 list( $orderby, $order ) = $this->sorting_to_wp_query_param( $default_sort );
388 $current_sort = "{$orderby}|{$order}";
389
390 // we need to dynamically inject the sort field into the search box when the search box is enabled, and display
391 // it separately when it's not.
392 if ( ! empty( $instance['search_box_enabled'] ) ) {
393 Automattic\Jetpack\Search\Template_Tags::render_widget_search_form( $instance['post_types'], $orderby, $order );
394 }
395
396 if ( ! empty( $instance['search_box_enabled'] ) && ! empty( $instance['user_sort_enabled'] ) ) :
397 ?>
398 <div class="jetpack-search-sort-wrapper">
399 <label>
400 <?php esc_html_e( 'Sort by', 'jetpack' ); ?>
401 <select class="jetpack-search-sort">
402 <?php foreach ( $this->get_sort_types() as $sort => $label ) { ?>
403 <option value="<?php echo esc_attr( $sort ); ?>" <?php selected( $current_sort, $sort ); ?>>
404 <?php echo esc_html( $label ); ?>
405 </option>
406 <?php } ?>
407 </select>
408 </label>
409 </div>
410 <?php
411 endif;
412
413 if ( $display_filters ) {
414 /**
415 * Responsible for rendering filters to narrow down search results.
416 *
417 * @module search
418 *
419 * @since 5.8.0
420 *
421 * @param array $filters The possible filters for the current query.
422 * @param array $post_types An array of post types to limit filtering to.
423 */
424 do_action(
425 'jetpack_search_render_filters',
426 $filters,
427 isset( $instance['post_types'] ) ? $instance['post_types'] : null
428 );
429 }
430
431 $this->maybe_render_sort_javascript( $instance, $order, $orderby );
432
433 echo '</div>';
434 echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
435 }
436
437 /**
438 * Render the instant frontend widget.
439 *
440 * @since 8.3.0
441 *
442 * @param array $args Widgets args supplied by the theme.
443 * @param array $instance The current widget instance.
444 */
445 public function widget_instant( $args, $instance ) {
446 if ( Helper::should_rerun_search_in_customizer_preview() ) {
447 Jetpack_Search::instance()->update_search_results_aggregations();
448 }
449
450 $filters = Jetpack_Search::instance()->get_filters();
451 if ( ! Helper::are_filters_by_widget_disabled() && ! $this->should_display_sitewide_filters() ) {
452 $filters = array_filter( $filters, array( $this, 'is_for_current_widget' ) );
453 }
454
455 $display_filters = ! empty( $filters );
456
457 $title = ! empty( $instance['title'] ) ? $instance['title'] : '';
458
459 /** This filter is documented in core/src/wp-includes/default-widgets.php */
460 $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
461
462 echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
463 ?>
464 <div id="<?php echo esc_attr( $this->id ); ?>-wrapper" class="jetpack-instant-search-wrapper">
465 <?php
466
467 if ( ! empty( $title ) ) {
468 /**
469 * Responsible for displaying the title of the Jetpack Search filters widget.
470 *
471 * @module search
472 *
473 * @since 5.7.0
474 *
475 * @param string $title The widget's title
476 * @param string $args['before_title'] The HTML tag to display before the title
477 * @param string $args['after_title'] The HTML tag to display after the title
478 */
479 do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
480 }
481
482 Automattic\Jetpack\Search\Template_Tags::render_widget_search_form( array(), '', '' );
483
484 if ( $display_filters ) {
485 /**
486 * Responsible for rendering filters to narrow down search results.
487 *
488 * @module search
489 *
490 * @since 5.8.0
491 *
492 * @param array $filters The possible filters for the current query.
493 * @param array $post_types An array of post types to limit filtering to.
494 */
495 do_action(
496 'jetpack_search_render_filters',
497 $filters,
498 null
499 );
500 }
501
502 echo '</div>';
503 echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
504 }
505
506 /**
507 * Render the instant widget for the overlay.
508 *
509 * @since 8.3.0
510 *
511 * @param array $args Widgets args supplied by the theme.
512 * @param array $instance The current widget instance.
513 */
514 public function widget_empty_instant( $args, $instance ) {
515 $title = isset( $instance['title'] ) ? $instance['title'] : '';
516
517 if ( empty( $title ) ) {
518 $title = '';
519 }
520
521 /** This filter is documented in core/src/wp-includes/default-widgets.php */
522 $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
523
524 echo $args['before_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
525 ?>
526 <div id="<?php echo esc_attr( $this->id ); ?>-wrapper" class="jetpack-instant-search-wrapper">
527 <?php
528
529 if ( ! empty( $title ) ) {
530 /**
531 * Responsible for displaying the title of the Jetpack Search filters widget.
532 *
533 * @module search
534 *
535 * @since 5.7.0
536 *
537 * @param string $title The widget's title
538 * @param string $args['before_title'] The HTML tag to display before the title
539 * @param string $args['after_title'] The HTML tag to display after the title
540 */
541 do_action( 'jetpack_search_render_filters_widget_title', $title, $args['before_title'], $args['after_title'] );
542 }
543
544 echo '</div>';
545 echo $args['after_widget']; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
546 }
547
548 /**
549 * Renders JavaScript for the sorting controls on the frontend.
550 *
551 * This JS is a bit complicated, but here's what it's trying to do:
552 * - find the search form
553 * - find the orderby/order fields and set default values
554 * - detect changes to the sort field, if it exists, and use it to set the order field values
555 *
556 * @since 5.8.0
557 *
558 * @param array $instance The current widget instance.
559 * @param string $order The order to initialize the select with.
560 * @param string $orderby The orderby to initialize the select with.
561 */
562 private function maybe_render_sort_javascript( $instance, $order, $orderby ) {
563 if ( Options::is_instant_enabled() ) {
564 return;
565 }
566
567 if ( ! empty( $instance['user_sort_enabled'] ) ) :
568 ?>
569 <script type="text/javascript">
570 var jetpackSearchModuleSorting = function() {
571 var orderByDefault = '<?php echo 'date' === $orderby ? 'date' : 'relevance'; ?>',
572 orderDefault = '<?php echo 'ASC' === $order ? 'ASC' : 'DESC'; ?>',
573 widgetId = decodeURIComponent( '<?php echo rawurlencode( $this->id ); ?>' ),
574 searchQuery = decodeURIComponent( '<?php echo rawurlencode( get_query_var( 's', '' ) ); ?>' ),
575 isSearch = <?php echo (int) is_search(); ?>;
576
577 var container = document.getElementById( widgetId + '-wrapper' ),
578 form = container.querySelector( '.jetpack-search-form form' ),
579 orderBy = form.querySelector( 'input[name=orderby]' ),
580 order = form.querySelector( 'input[name=order]' ),
581 searchInput = form.querySelector( 'input[name="s"]' ),
582 sortSelectInput = container.querySelector( '.jetpack-search-sort' );
583
584 orderBy.value = orderByDefault;
585 order.value = orderDefault;
586
587 // Some themes don't set the search query, which results in the query being lost
588 // when doing a sort selection. So, if the query isn't set, let's set it now. This approach
589 // is chosen over running a regex over HTML for every search query performed.
590 if ( isSearch && ! searchInput.value ) {
591 searchInput.value = searchQuery;
592 }
593
594 searchInput.classList.add( 'show-placeholder' );
595
596 sortSelectInput.addEventListener( 'change', function( event ) {
597 var values = event.target.value.split( '|' );
598 orderBy.value = values[0];
599 order.value = values[1];
600
601 form.submit();
602 } );
603 }
604
605 if ( document.readyState === 'interactive' || document.readyState === 'complete' ) {
606 jetpackSearchModuleSorting();
607 } else {
608 document.addEventListener( 'DOMContentLoaded', jetpackSearchModuleSorting );
609 }
610 </script>
611 <?php
612 endif;
613 }
614
615 /**
616 * Convert a sort string into the separate order by and order parts.
617 *
618 * @since 5.8.0
619 *
620 * @param string $sort A sort string.
621 *
622 * @return array Order by and order.
623 */
624 private function sorting_to_wp_query_param( $sort ) {
625 // phpcs:disable WordPress.Security.NonceVerification.Recommended
626 $parts = explode( '|', $sort );
627 $orderby = isset( $_GET['orderby'] )
628 ? $_GET['orderby']
629 : $parts[0];
630
631 $order = isset( $_GET['order'] )
632 ? strtoupper( $_GET['order'] )
633 : ( ( isset( $parts[1] ) && 'ASC' === strtoupper( $parts[1] ) ) ? 'ASC' : 'DESC' );
634
635 // phpcs:enable WordPress.Security.NonceVerification.Recommended
636
637 return array( $orderby, $order );
638 }
639
640 /**
641 * Updates a particular instance of the widget. Validates and sanitizes the options.
642 *
643 * @since 5.0.0
644 *
645 * @param array $new_instance New settings for this instance as input by the user via Jetpack_Search_Widget::form().
646 * @param array $old_instance Old settings for this instance.
647 *
648 * @return array Settings to save.
649 */
650 public function update( $new_instance, $old_instance ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
651 $new_instance = $this->maybe_reformat_widget( $new_instance );
652 $instance = array();
653
654 $instance['title'] = sanitize_text_field( $new_instance['title'] );
655 $instance['search_box_enabled'] = empty( $new_instance['search_box_enabled'] ) ? '0' : '1';
656 $instance['user_sort_enabled'] = empty( $new_instance['user_sort_enabled'] ) ? '0' : '1';
657 $instance['sort'] = $new_instance['sort'];
658 $instance['post_types'] = empty( $new_instance['post_types'] ) || empty( $instance['search_box_enabled'] )
659 ? array()
660 : array_map( 'sanitize_key', $new_instance['post_types'] );
661
662 $filters = array();
663 if ( isset( $new_instance['filter_type'] ) ) {
664 foreach ( (array) $new_instance['filter_type'] as $index => $type ) {
665 $count = (int) $new_instance['num_filters'][ $index ];
666 $count = min( 50, $count ); // Set max boundary at 50.
667 $count = max( 1, $count ); // Set min boundary at 1.
668
669 switch ( $type ) {
670 case 'taxonomy':
671 $filters[] = array(
672 'name' => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
673 'type' => 'taxonomy',
674 'taxonomy' => sanitize_key( $new_instance['taxonomy_type'][ $index ] ),
675 'count' => $count,
676 );
677 break;
678 case 'post_type':
679 $filters[] = array(
680 'name' => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
681 'type' => 'post_type',
682 'count' => $count,
683 );
684 break;
685 case 'date_histogram':
686 $filters[] = array(
687 'name' => sanitize_text_field( $new_instance['filter_name'][ $index ] ),
688 'type' => 'date_histogram',
689 'count' => $count,
690 'field' => sanitize_key( $new_instance['date_histogram_field'][ $index ] ),
691 'interval' => sanitize_key( $new_instance['date_histogram_interval'][ $index ] ),
692 );
693 break;
694 }
695 }
696 }
697
698 if ( ! empty( $filters ) ) {
699 $instance['filters'] = $filters;
700 }
701
702 return $instance;
703 }
704
705 /**
706 * Reformats the widget instance array to one that is recognized by the `update` function.
707 * This is only necessary when handling changes from the block-based widget editor.
708 *
709 * @param array $widget_instance - Jetpack Search widget instance.
710 *
711 * @return array - Potentially reformatted instance compatible with the save function.
712 */
713 protected function maybe_reformat_widget( $widget_instance ) {
714 if ( isset( $widget_instance['filter_type'] ) || ! isset( $widget_instance['filters'] ) || ! is_array( $widget_instance['filters'] ) ) {
715 return $widget_instance;
716 }
717
718 $instance = $widget_instance;
719 foreach ( $widget_instance['filters'] as $filter ) {
720 $instance['filter_type'][] = isset( $filter['type'] ) ? $filter['type'] : '';
721 $instance['taxonomy_type'][] = isset( $filter['taxonomy'] ) ? $filter['taxonomy'] : '';
722 $instance['filter_name'][] = isset( $filter['name'] ) ? $filter['name'] : '';
723 $instance['num_filters'][] = isset( $filter['count'] ) ? $filter['count'] : 5;
724 $instance['date_histogram_field'][] = isset( $filter['field'] ) ? $filter['field'] : '';
725 $instance['date_histogram_interval'][] = isset( $filter['interval'] ) ? $filter['interval'] : '';
726 }
727 unset( $instance['filters'] );
728 return $instance;
729 }
730
731 /**
732 * Outputs the settings update form.
733 *
734 * @since 5.0.0
735 *
736 * @param array $instance Previously saved values from database.
737 */
738 public function form( $instance ) {
739 if ( Options::is_instant_enabled() ) {
740 return $this->form_for_instant_search( $instance );
741 }
742
743 $instance = $this->jetpack_search_populate_defaults( $instance );
744
745 $title = wp_strip_all_tags( $instance['title'] );
746
747 $hide_filters = Helper::are_filters_by_widget_disabled();
748
749 $classes = sprintf(
750 'jetpack-search-filters-widget %s %s %s',
751 $hide_filters ? 'hide-filters' : '',
752 $instance['search_box_enabled'] ? '' : 'hide-post-types',
753 $this->id
754 );
755 ?>
756 <div class="<?php echo esc_attr( $classes ); ?>">
757 <p>
758 <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
759 <?php esc_html_e( 'Title (optional):', 'jetpack' ); ?>
760 </label>
761 <input
762 class="widefat"
763 id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
764 name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
765 type="text"
766 value="<?php echo esc_attr( $title ); ?>"
767 />
768 </p>
769
770 <p>
771 <label>
772 <input
773 type="checkbox"
774 class="jetpack-search-filters-widget__search-box-enabled"
775 name="<?php echo esc_attr( $this->get_field_name( 'search_box_enabled' ) ); ?>"
776 <?php checked( $instance['search_box_enabled'] ); ?>
777 />
778 <?php esc_html_e( 'Show search box', 'jetpack' ); ?>
779 </label>
780 </p>
781
782 <p>
783 <label>
784 <input
785 type="checkbox"
786 class="jetpack-search-filters-widget__sort-controls-enabled"
787 name="<?php echo esc_attr( $this->get_field_name( 'user_sort_enabled' ) ); ?>"
788 <?php checked( $instance['user_sort_enabled'] ); ?>
789 <?php disabled( ! $instance['search_box_enabled'] ); ?>
790 />
791 <?php esc_html_e( 'Show sort selection dropdown', 'jetpack' ); ?>
792 </label>
793 </p>
794
795 <p class="jetpack-search-filters-widget__post-types-select">
796 <label><?php esc_html_e( 'Post types to search (minimum of 1):', 'jetpack' ); ?></label>
797 <?php foreach ( get_post_types( array( 'exclude_from_search' => false ), 'objects' ) as $post_type ) : ?>
798 <label>
799 <input
800 type="checkbox"
801 value="<?php echo esc_attr( $post_type->name ); ?>"
802 name="<?php echo esc_attr( $this->get_field_name( 'post_types' ) ); ?>[]"
803 <?php checked( empty( $instance['post_types'] ) || in_array( $post_type->name, $instance['post_types'], true ) ); ?>
804 />&nbsp;
805 <?php echo esc_html( $post_type->label ); ?>
806 </label>
807 <?php endforeach; ?>
808 </p>
809
810 <p>
811 <label>
812 <?php esc_html_e( 'Default sort order:', 'jetpack' ); ?>
813 <select
814 name="<?php echo esc_attr( $this->get_field_name( 'sort' ) ); ?>"
815 class="widefat jetpack-search-filters-widget__sort-order">
816 <?php foreach ( $this->get_sort_types() as $sort_type => $label ) { ?>
817 <option value="<?php echo esc_attr( $sort_type ); ?>" <?php selected( $instance['sort'], $sort_type ); ?>>
818 <?php echo esc_html( $label ); ?>
819 </option>
820 <?php } ?>
821 </select>
822 </label>
823 </p>
824
825 <?php if ( ! $hide_filters ) : ?>
826 <script class="jetpack-search-filters-widget__filter-template" type="text/template">
827 <?php
828 echo $this->render_widget_edit_filter( array(), true ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
829 ?>
830 </script>
831 <div class="jetpack-search-filters-widget__filters">
832 <?php foreach ( (array) $instance['filters'] as $filter ) : ?>
833 <?php $this->render_widget_edit_filter( $filter ); ?>
834 <?php endforeach; ?>
835 </div>
836 <p class="jetpack-search-filters-widget__add-filter-wrapper">
837 <a class="button jetpack-search-filters-widget__add-filter" href="#">
838 <?php esc_html_e( 'Add a filter', 'jetpack' ); ?>
839 </a>
840 </p>
841 <noscript>
842 <p class="jetpack-search-filters-help">
843 <?php echo esc_html_e( 'Adding filters requires JavaScript!', 'jetpack' ); ?>
844 </p>
845 </noscript>
846 <?php if ( is_customize_preview() ) : ?>
847 <p class="jetpack-search-filters-help">
848 <a href="<?php echo esc_url( Redirect::get_url( 'jetpack-support-search', array( 'anchor' => 'filters-not-showing-up' ) ) ); ?>" target="_blank">
849 <?php esc_html_e( "Why aren't my filters appearing?", 'jetpack' ); ?>
850 </a>
851 </p>
852 <?php endif; ?>
853 <?php endif; ?>
854 </div>
855 <?php
856 }
857
858 /**
859 * Outputs the widget update form to be used in the Customizer for Instant Search.
860 *
861 * @since 8.6.0
862 *
863 * @param array $instance Previously saved values from database.
864 */
865 private function form_for_instant_search( $instance ) {
866 $instance = $this->populate_defaults_for_instant_search( $instance );
867 $classes = sprintf( 'jetpack-search-filters-widget %s', $this->id );
868
869 ?>
870 <div class="<?php echo esc_attr( $classes ); ?>">
871 <!-- Title control -->
872 <p>
873 <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
874 <?php esc_html_e( 'Title (optional):', 'jetpack' ); ?>
875 </label>
876 <input
877 class="widefat"
878 id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
879 name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
880 type="text"
881 value="<?php echo esc_attr( wp_strip_all_tags( $instance['title'] ) ); ?>"
882 />
883 </p>
884
885 <!-- Filters control -->
886 <?php if ( ! Helper::are_filters_by_widget_disabled() ) : ?>
887 <div class="jetpack-search-filters-widget__filters">
888 <?php foreach ( (array) $instance['filters'] as $filter ) : ?>
889 <?php $this->render_widget_edit_filter( $filter ); ?>
890 <?php endforeach; ?>
891 </div>
892 <p class="jetpack-search-filters-widget__add-filter-wrapper">
893 <a class="button jetpack-search-filters-widget__add-filter" href="#">
894 <?php esc_html_e( 'Add a filter', 'jetpack' ); ?>
895 </a>
896 </p>
897 <script class="jetpack-search-filters-widget__filter-template" type="text/template">
898 <?php $this->render_widget_edit_filter( array(), true ); ?>
899 </script>
900 <noscript>
901 <p class="jetpack-search-filters-help">
902 <?php echo esc_html_e( 'Adding filters requires JavaScript!', 'jetpack' ); ?>
903 </p>
904 </noscript>
905 <?php endif; ?>
906 </div>
907 <?php
908 }
909
910 /**
911 * We need to render HTML in two formats: an Underscore template (client-side)
912 * and native PHP (server-side). This helper function allows for easy rendering
913 * of attributes in both formats.
914 *
915 * @since 5.8.0
916 *
917 * @param string $name Attribute name.
918 * @param string $value Attribute value.
919 * @param bool $is_template Whether this is for an Underscore template or not.
920 */
921 private function render_widget_attr( $name, $value, $is_template ) {
922 echo $is_template ? "<%= $name %>" : esc_attr( $value ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
923 }
924
925 /**
926 * We need to render HTML in two formats: an Underscore template (client-size)
927 * and native PHP (server-side). This helper function allows for easy rendering
928 * of the "selected" attribute in both formats.
929 *
930 * @since 5.8.0
931 *
932 * @param string $name Attribute name.
933 * @param string $value Attribute value.
934 * @param string $compare Value to compare to the attribute value to decide if it should be selected.
935 * @param bool $is_template Whether this is for an Underscore template or not.
936 */
937 private function render_widget_option_selected( $name, $value, $compare, $is_template ) {
938 $compare_js = rawurlencode( $compare );
939 echo $is_template ? "<%= decodeURIComponent( '$compare_js' ) === $name ? 'selected=\"selected\"' : '' %>" : selected( $value, $compare ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
940 }
941
942 /**
943 * Responsible for rendering a single filter in the customizer or the widget administration screen in wp-admin.
944 *
945 * We use this method for two purposes - rendering the fields server-side, and also rendering a script template for Underscore.
946 *
947 * @since 5.7.0
948 *
949 * @param array $filter The filter to render.
950 * @param bool $is_template Whether this is for an Underscore template or not.
951 */
952 public function render_widget_edit_filter( $filter, $is_template = false ) {
953 $args = wp_parse_args(
954 $filter,
955 array(
956 'name' => '',
957 'type' => 'taxonomy',
958 'taxonomy' => '',
959 'post_type' => '',
960 'field' => '',
961 'interval' => '',
962 'count' => self::DEFAULT_FILTER_COUNT,
963 )
964 );
965
966 $args['name_placeholder'] = Helper::generate_widget_filter_name( $args );
967
968 ?>
969 <div class="jetpack-search-filters-widget__filter is-<?php $this->render_widget_attr( 'type', $args['type'], $is_template ); ?>">
970 <p class="jetpack-search-filters-widget__type-select">
971 <label>
972 <?php esc_html_e( 'Filter Type:', 'jetpack' ); ?>
973 <select name="<?php echo esc_attr( $this->get_field_name( 'filter_type' ) ); ?>[]" class="widefat filter-select">
974 <option value="taxonomy" <?php $this->render_widget_option_selected( 'type', $args['type'], 'taxonomy', $is_template ); ?>>
975 <?php esc_html_e( 'Taxonomy', 'jetpack' ); ?>
976 </option>
977 <option value="post_type" <?php $this->render_widget_option_selected( 'type', $args['type'], 'post_type', $is_template ); ?>>
978 <?php esc_html_e( 'Post Type', 'jetpack' ); ?>
979 </option>
980 <option value="date_histogram" <?php $this->render_widget_option_selected( 'type', $args['type'], 'date_histogram', $is_template ); ?>>
981 <?php esc_html_e( 'Date', 'jetpack' ); ?>
982 </option>
983 </select>
984 </label>
985 </p>
986
987 <p class="jetpack-search-filters-widget__taxonomy-select">
988 <label>
989 <?php
990 esc_html_e( 'Choose a taxonomy:', 'jetpack' );
991 $seen_taxonomy_labels = array();
992 ?>
993 <select name="<?php echo esc_attr( $this->get_field_name( 'taxonomy_type' ) ); ?>[]" class="widefat taxonomy-select">
994 <?php foreach ( get_taxonomies( array( 'public' => true ), 'objects' ) as $taxonomy ) : ?>
995 <option value="<?php echo esc_attr( $taxonomy->name ); ?>" <?php $this->render_widget_option_selected( 'taxonomy', $args['taxonomy'], $taxonomy->name, $is_template ); ?>>
996 <?php
997 $label = in_array( $taxonomy->label, $seen_taxonomy_labels, true )
998 ? sprintf(
999 /* 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. */
1000 _x( '%1$s (%2$s)', 'A label for a taxonomy selector option', 'jetpack' ),
1001 $taxonomy->label,
1002 $taxonomy->name
1003 )
1004 : $taxonomy->label;
1005 echo esc_html( $label );
1006 $seen_taxonomy_labels[] = $taxonomy->label;
1007 ?>
1008 </option>
1009 <?php endforeach; ?>
1010 </select>
1011 </label>
1012 </p>
1013
1014 <p class="jetpack-search-filters-widget__date-histogram-select">
1015 <label>
1016 <?php esc_html_e( 'Choose a field:', 'jetpack' ); ?>
1017 <select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_field' ) ); ?>[]" class="widefat date-field-select">
1018 <option value="post_date" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date', $is_template ); ?>>
1019 <?php esc_html_e( 'Date', 'jetpack' ); ?>
1020 </option>
1021 <option value="post_date_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_date_gmt', $is_template ); ?>>
1022 <?php esc_html_e( 'Date GMT', 'jetpack' ); ?>
1023 </option>
1024 <option value="post_modified" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified', $is_template ); ?>>
1025 <?php esc_html_e( 'Modified', 'jetpack' ); ?>
1026 </option>
1027 <option value="post_modified_gmt" <?php $this->render_widget_option_selected( 'field', $args['field'], 'post_modified_gmt', $is_template ); ?>>
1028 <?php esc_html_e( 'Modified GMT', 'jetpack' ); ?>
1029 </option>
1030 </select>
1031 </label>
1032 </p>
1033
1034 <p class="jetpack-search-filters-widget__date-histogram-select">
1035 <label>
1036 <?php esc_html_e( 'Choose an interval:', 'jetpack' ); ?>
1037 <select name="<?php echo esc_attr( $this->get_field_name( 'date_histogram_interval' ) ); ?>[]" class="widefat date-interval-select">
1038 <option value="month" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'month', $is_template ); ?>>
1039 <?php esc_html_e( 'Month', 'jetpack' ); ?>
1040 </option>
1041 <option value="year" <?php $this->render_widget_option_selected( 'interval', $args['interval'], 'year', $is_template ); ?>>
1042 <?php esc_html_e( 'Year', 'jetpack' ); ?>
1043 </option>
1044 </select>
1045 </label>
1046 </p>
1047
1048 <p class="jetpack-search-filters-widget__title">
1049 <label>
1050 <?php esc_html_e( 'Title:', 'jetpack' ); ?>
1051 <input
1052 class="widefat"
1053 type="text"
1054 name="<?php echo esc_attr( $this->get_field_name( 'filter_name' ) ); ?>[]"
1055 value="<?php $this->render_widget_attr( 'name', $args['name'], $is_template ); ?>"
1056 placeholder="<?php $this->render_widget_attr( 'name_placeholder', $args['name_placeholder'], $is_template ); ?>"
1057 />
1058 </label>
1059 </p>
1060
1061 <p>
1062 <label>
1063 <?php esc_html_e( 'Maximum number of filters (1-50):', 'jetpack' ); ?>
1064 <input
1065 class="widefat filter-count"
1066 name="<?php echo esc_attr( $this->get_field_name( 'num_filters' ) ); ?>[]"
1067 type="number"
1068 value="<?php $this->render_widget_attr( 'count', $args['count'], $is_template ); ?>"
1069 min="1"
1070 max="50"
1071 step="1"
1072 required
1073 />
1074 </label>
1075 </p>
1076
1077 <p class="jetpack-search-filters-widget__controls">
1078 <a href="#" class="delete"><?php esc_html_e( 'Remove', 'jetpack' ); ?></a>
1079 </p>
1080 </div>
1081 <?php
1082 }
1083 }
1084