class.jetpack-search.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. <?php
  2. /**
  3. * Jetpack Search: Main Jetpack_Search class
  4. *
  5. * @package Jetpack
  6. * @subpackage Jetpack Search
  7. * @since 5.0.0
  8. */
  9. /**
  10. * The main class for the Jetpack Search module.
  11. *
  12. * @since 5.0.0
  13. */
  14. class Jetpack_Search {
  15. /**
  16. * The number of found posts.
  17. *
  18. * @since 5.0.0
  19. *
  20. * @var int
  21. */
  22. protected $found_posts = 0;
  23. /**
  24. * The search result, as returned by the WordPress.com REST API.
  25. *
  26. * @since 5.0.0
  27. *
  28. * @var array
  29. */
  30. protected $search_result;
  31. /**
  32. * This site's blog ID on WordPress.com.
  33. *
  34. * @since 5.0.0
  35. *
  36. * @var int
  37. */
  38. protected $jetpack_blog_id;
  39. /**
  40. * The Elasticsearch aggregations (filters).
  41. *
  42. * @since 5.0.0
  43. *
  44. * @var array
  45. */
  46. protected $aggregations = array();
  47. /**
  48. * The maximum number of aggregations allowed.
  49. *
  50. * @since 5.0.0
  51. *
  52. * @var int
  53. */
  54. protected $max_aggregations_count = 100;
  55. /**
  56. * Statistics about the last Elasticsearch query.
  57. *
  58. * @since 5.6.0
  59. *
  60. * @var array
  61. */
  62. protected $last_query_info = array();
  63. /**
  64. * Statistics about the last Elasticsearch query failure.
  65. *
  66. * @since 5.6.0
  67. *
  68. * @var array
  69. */
  70. protected $last_query_failure_info = array();
  71. /**
  72. * The singleton instance of this class.
  73. *
  74. * @since 5.0.0
  75. *
  76. * @var Jetpack_Search
  77. */
  78. protected static $instance;
  79. /**
  80. * Languages with custom analyzers. Other languages are supported, but are analyzed with the default analyzer.
  81. *
  82. * @since 5.0.0
  83. *
  84. * @var array
  85. */
  86. public static $analyzed_langs = array( 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'eu', 'fa', 'fi', 'fr', 'he', 'hi', 'hu', 'hy', 'id', 'it', 'ja', 'ko', 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' );
  87. /**
  88. * Jetpack_Search constructor.
  89. *
  90. * @since 5.0.0
  91. *
  92. * Doesn't do anything. This class needs to be initialized via the instance() method instead.
  93. */
  94. protected function __construct() {
  95. }
  96. /**
  97. * Prevent __clone()'ing of this class.
  98. *
  99. * @since 5.0.0
  100. */
  101. public function __clone() {
  102. wp_die( "Please don't __clone Jetpack_Search" );
  103. }
  104. /**
  105. * Prevent __wakeup()'ing of this class.
  106. *
  107. * @since 5.0.0
  108. */
  109. public function __wakeup() {
  110. wp_die( "Please don't __wakeup Jetpack_Search" );
  111. }
  112. /**
  113. * Get singleton instance of Jetpack_Search.
  114. *
  115. * Instantiates and sets up a new instance if needed, or returns the singleton.
  116. *
  117. * @since 5.0.0
  118. *
  119. * @return Jetpack_Search The Jetpack_Search singleton.
  120. */
  121. public static function instance() {
  122. if ( ! isset( self::$instance ) ) {
  123. self::$instance = new Jetpack_Search();
  124. self::$instance->setup();
  125. }
  126. return self::$instance;
  127. }
  128. /**
  129. * Perform various setup tasks for the class.
  130. *
  131. * Checks various pre-requisites and adds hooks.
  132. *
  133. * @since 5.0.0
  134. */
  135. public function setup() {
  136. if ( ! Jetpack::is_active() || ! Jetpack::active_plan_supports( 'search' ) ) {
  137. return;
  138. }
  139. $this->jetpack_blog_id = Jetpack::get_option( 'id' );
  140. if ( ! $this->jetpack_blog_id ) {
  141. return;
  142. }
  143. require_once dirname( __FILE__ ) . '/class.jetpack-search-helpers.php';
  144. require_once dirname( __FILE__ ) . '/class.jetpack-search-template-tags.php';
  145. require_once JETPACK__PLUGIN_DIR . 'modules/widgets/search.php';
  146. $this->init_hooks();
  147. }
  148. /**
  149. * Setup the various hooks needed for the plugin to take over search duties.
  150. *
  151. * @since 5.0.0
  152. */
  153. public function init_hooks() {
  154. if ( ! is_admin() ) {
  155. add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
  156. add_filter( 'jetpack_search_es_wp_query_args', array( $this, 'filter__add_date_filter_to_query' ), 10, 2 );
  157. add_action( 'did_jetpack_search_query', array( $this, 'store_last_query_info' ) );
  158. add_action( 'failed_jetpack_search_query', array( $this, 'store_query_failure' ) );
  159. add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
  160. add_action( 'pre_get_posts', array( $this, 'maybe_add_post_type_as_var' ) );
  161. } else {
  162. add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
  163. }
  164. add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
  165. }
  166. /**
  167. * When an Elasticsearch query fails, this stores it and enqueues some debug information in the footer.
  168. *
  169. * @since 5.6.0
  170. *
  171. * @param array $meta Information about the failure.
  172. */
  173. public function store_query_failure( $meta ) {
  174. $this->last_query_failure_info = $meta;
  175. add_action( 'wp_footer', array( $this, 'print_query_failure' ) );
  176. }
  177. /**
  178. * Outputs information about the last Elasticsearch failure.
  179. *
  180. * @since 5.6.0
  181. */
  182. public function print_query_failure() {
  183. if ( $this->last_query_failure_info ) {
  184. printf(
  185. '<!-- Jetpack Search failed with code %s: %s - %s -->',
  186. esc_html( $this->last_query_failure_info['response_code'] ),
  187. esc_html( $this->last_query_failure_info['json']['error'] ),
  188. esc_html( $this->last_query_failure_info['json']['message'] )
  189. );
  190. }
  191. }
  192. /**
  193. * Stores information about the last Elasticsearch query and enqueues some debug information in the footer.
  194. *
  195. * @since 5.6.0
  196. *
  197. * @param array $meta Information about the query.
  198. */
  199. public function store_last_query_info( $meta ) {
  200. $this->last_query_info = $meta;
  201. add_action( 'wp_footer', array( $this, 'print_query_success' ) );
  202. }
  203. /**
  204. * Outputs information about the last Elasticsearch search.
  205. *
  206. * @since 5.6.0
  207. */
  208. public function print_query_success() {
  209. if ( $this->last_query_info ) {
  210. printf(
  211. '<!-- Jetpack Search took %s ms, ES time %s ms -->',
  212. intval( $this->last_query_info['elapsed_time'] ),
  213. esc_html( $this->last_query_info['es_time'] )
  214. );
  215. }
  216. }
  217. /**
  218. * Returns the last query information, or false if no information was stored.
  219. *
  220. * @since 5.8.0
  221. *
  222. * @return bool|array
  223. */
  224. public function get_last_query_info() {
  225. return empty( $this->last_query_info ) ? false : $this->last_query_info;
  226. }
  227. /**
  228. * Returns the last query failure information, or false if no failure information was stored.
  229. *
  230. * @since 5.8.0
  231. *
  232. * @return bool|array
  233. */
  234. public function get_last_query_failure_info() {
  235. return empty( $this->last_query_failure_info ) ? false : $this->last_query_failure_info;
  236. }
  237. /**
  238. * Wraps a WordPress filter called "jetpack_search_disable_widget_filters" that allows
  239. * developers to disable filters supplied by the search widget. Useful if filters are
  240. * being defined at the code level.
  241. *
  242. * @since 5.7.0
  243. * @deprecated 5.8.0 Use Jetpack_Search_Helpers::are_filters_by_widget_disabled() directly.
  244. *
  245. * @return bool
  246. */
  247. public function are_filters_by_widget_disabled() {
  248. return Jetpack_Search_Helpers::are_filters_by_widget_disabled();
  249. }
  250. /**
  251. * Retrieves a list of known Jetpack search filters widget IDs, gets the filters for each widget,
  252. * and applies those filters to this Jetpack_Search object.
  253. *
  254. * @since 5.7.0
  255. */
  256. public function set_filters_from_widgets() {
  257. if ( Jetpack_Search_Helpers::are_filters_by_widget_disabled() ) {
  258. return;
  259. }
  260. $filters = Jetpack_Search_Helpers::get_filters_from_widgets();
  261. if ( ! empty( $filters ) ) {
  262. $this->set_filters( $filters );
  263. }
  264. }
  265. /**
  266. * Restricts search results to certain post types via a GET argument.
  267. *
  268. * @since 5.8.0
  269. *
  270. * @param WP_Query $query A WP_Query instance.
  271. */
  272. public function maybe_add_post_type_as_var( WP_Query $query ) {
  273. if ( $query->is_main_query() && $query->is_search && ! empty( $_GET['post_type'] ) ) {
  274. $post_types = ( is_string( $_GET['post_type'] ) && false !== strpos( $_GET['post_type'], ',' ) )
  275. ? $post_type = explode( ',', $_GET['post_type'] )
  276. : (array) $_GET['post_type'];
  277. $post_types = array_map( 'sanitize_key', $post_types );
  278. $query->set( 'post_type', $post_types );
  279. }
  280. }
  281. /*
  282. * Run a search on the WordPress.com public API.
  283. *
  284. * @since 5.0.0
  285. *
  286. * @param array $es_args Args conforming to the WP.com /sites/<blog_id>/search endpoint.
  287. *
  288. * @return object|WP_Error The response from the public API, or a WP_Error.
  289. */
  290. public function search( array $es_args ) {
  291. $endpoint = sprintf( '/sites/%s/search', $this->jetpack_blog_id );
  292. $service_url = 'https://public-api.wordpress.com/rest/v1' . $endpoint;
  293. $do_authenticated_request = false;
  294. if ( class_exists( 'Jetpack_Client' ) &&
  295. isset( $es_args['authenticated_request'] ) &&
  296. true === $es_args['authenticated_request'] ) {
  297. $do_authenticated_request = true;
  298. }
  299. unset( $es_args['authenticated_request'] );
  300. $request_args = array(
  301. 'headers' => array(
  302. 'Content-Type' => 'application/json',
  303. ),
  304. 'timeout' => 10,
  305. 'user-agent' => 'jetpack_search',
  306. );
  307. $request_body = wp_json_encode( $es_args );
  308. $start_time = microtime( true );
  309. if ( $do_authenticated_request ) {
  310. $request_args['method'] = 'POST';
  311. $request = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, Jetpack_Client::WPCOM_JSON_API_VERSION, $request_args, $request_body );
  312. } else {
  313. $request_args = array_merge( $request_args, array(
  314. 'body' => $request_body,
  315. ) );
  316. $request = wp_remote_post( $service_url, $request_args );
  317. }
  318. $end_time = microtime( true );
  319. if ( is_wp_error( $request ) ) {
  320. return $request;
  321. }
  322. $response_code = wp_remote_retrieve_response_code( $request );
  323. $response = json_decode( wp_remote_retrieve_body( $request ), true );
  324. $took = is_array( $response ) && ! empty( $response['took'] )
  325. ? $response['took']
  326. : null;
  327. $query = array(
  328. 'args' => $es_args,
  329. 'response' => $response,
  330. 'response_code' => $response_code,
  331. 'elapsed_time' => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
  332. 'es_time' => $took,
  333. 'url' => $service_url,
  334. );
  335. /**
  336. * Fires after a search request has been performed.
  337. *
  338. * Includes the following info in the $query parameter:
  339. *
  340. * array args Array of Elasticsearch arguments for the search
  341. * array response Raw API response, JSON decoded
  342. * int response_code HTTP response code of the request
  343. * float elapsed_time Roundtrip time of the search request, in milliseconds
  344. * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
  345. * string url API url that was queried
  346. *
  347. * @module search
  348. *
  349. * @since 5.0.0
  350. * @since 5.8.0 This action now fires on all queries instead of just successful queries.
  351. *
  352. * @param array $query Array of information about the query performed
  353. */
  354. do_action( 'did_jetpack_search_query', $query );
  355. if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
  356. /**
  357. * Fires after a search query request has failed
  358. *
  359. * @module search
  360. *
  361. * @since 5.6.0
  362. *
  363. * @param array Array containing the response code and response from the failed search query
  364. */
  365. do_action( 'failed_jetpack_search_query', array(
  366. 'response_code' => $response_code,
  367. 'json' => $response,
  368. ) );
  369. return new WP_Error( 'invalid_search_api_response', 'Invalid response from API - ' . $response_code );
  370. }
  371. return $response;
  372. }
  373. /**
  374. * Bypass the normal Search query and offload it to Jetpack servers.
  375. *
  376. * This is the main hook of the plugin and is responsible for returning the posts that match the search query.
  377. *
  378. * @since 5.0.0
  379. *
  380. * @param array $posts Current array of posts (still pre-query).
  381. * @param WP_Query $query The WP_Query being filtered.
  382. *
  383. * @return array Array of matching posts.
  384. */
  385. public function filter__posts_pre_query( $posts, $query ) {
  386. /**
  387. * Determine whether a given WP_Query should be handled by ElasticSearch.
  388. *
  389. * @module search
  390. *
  391. * @since 5.6.0
  392. *
  393. * @param bool $should_handle Should be handled by Jetpack Search.
  394. * @param WP_Query $query The WP_Query object.
  395. */
  396. if ( ! apply_filters( 'jetpack_search_should_handle_query', ( $query->is_main_query() && $query->is_search() ), $query ) ) {
  397. return $posts;
  398. }
  399. $this->do_search( $query );
  400. if ( ! is_array( $this->search_result ) ) {
  401. return $posts;
  402. }
  403. // If no results, nothing to do
  404. if ( ! count( $this->search_result['results']['hits'] ) ) {
  405. return array();
  406. }
  407. $post_ids = array();
  408. foreach ( $this->search_result['results']['hits'] as $result ) {
  409. $post_ids[] = (int) $result['fields']['post_id'];
  410. }
  411. // Query all posts now
  412. $args = array(
  413. 'post__in' => $post_ids,
  414. 'orderby' => 'post__in',
  415. 'perm' => 'readable',
  416. 'post_type' => 'any',
  417. 'ignore_sticky_posts' => true,
  418. 'suppress_filters' => true,
  419. );
  420. $posts_query = new WP_Query( $args );
  421. // WP Core doesn't call the set_found_posts and its filters when filtering posts_pre_query like we do, so need to do these manually.
  422. $query->found_posts = $this->found_posts;
  423. $query->max_num_pages = ceil( $this->found_posts / $query->get( 'posts_per_page' ) );
  424. return $posts_query->posts;
  425. }
  426. /**
  427. * Build up the search, then run it against the Jetpack servers.
  428. *
  429. * @since 5.0.0
  430. *
  431. * @param WP_Query $query The original WP_Query to use for the parameters of our search.
  432. */
  433. public function do_search( WP_Query $query ) {
  434. if ( ! $query->is_main_query() || ! $query->is_search() ) {
  435. return;
  436. }
  437. $page = ( $query->get( 'paged' ) ) ? absint( $query->get( 'paged' ) ) : 1;
  438. // Get maximum allowed offset and posts per page values for the API.
  439. $max_offset = Jetpack_Search_Helpers::get_max_offset();
  440. $max_posts_per_page = Jetpack_Search_Helpers::get_max_posts_per_page();
  441. $posts_per_page = $query->get( 'posts_per_page' );
  442. if ( $posts_per_page > $max_posts_per_page ) {
  443. $posts_per_page = $max_posts_per_page;
  444. }
  445. // Start building the WP-style search query args.
  446. // They'll be translated to ES format args later.
  447. $es_wp_query_args = array(
  448. 'query' => $query->get( 's' ),
  449. 'posts_per_page' => $posts_per_page,
  450. 'paged' => $page,
  451. 'orderby' => $query->get( 'orderby' ),
  452. 'order' => $query->get( 'order' ),
  453. );
  454. if ( ! empty( $this->aggregations ) ) {
  455. $es_wp_query_args['aggregations'] = $this->aggregations;
  456. }
  457. // Did we query for authors?
  458. if ( $query->get( 'author_name' ) ) {
  459. $es_wp_query_args['author_name'] = $query->get( 'author_name' );
  460. }
  461. $es_wp_query_args['post_type'] = $this->get_es_wp_query_post_type_for_query( $query );
  462. $es_wp_query_args['terms'] = $this->get_es_wp_query_terms_for_query( $query );
  463. /**
  464. * Modify the search query parameters, such as controlling the post_type.
  465. *
  466. * These arguments are in the format of WP_Query arguments
  467. *
  468. * @module search
  469. *
  470. * @since 5.0.0
  471. *
  472. * @param array $es_wp_query_args The current query args, in WP_Query format.
  473. * @param WP_Query $query The original WP_Query object.
  474. */
  475. $es_wp_query_args = apply_filters( 'jetpack_search_es_wp_query_args', $es_wp_query_args, $query );
  476. // If page * posts_per_page is greater than our max offset, send a 404. This is necessary because the offset is
  477. // capped at Jetpack_Search_Helpers::get_max_offset(), so a high page would always return the last page of results otherwise.
  478. if ( ( $es_wp_query_args['paged'] * $es_wp_query_args['posts_per_page'] ) > $max_offset ) {
  479. $query->set_404();
  480. return;
  481. }
  482. // If there were no post types returned, then 404 to avoid querying against non-public post types, which could
  483. // happen if we don't add the post type restriction to the ES query.
  484. if ( empty( $es_wp_query_args['post_type'] ) ) {
  485. $query->set_404();
  486. return;
  487. }
  488. // Convert the WP-style args into ES args.
  489. $es_query_args = $this->convert_wp_es_to_es_args( $es_wp_query_args );
  490. //Only trust ES to give us IDs, not the content since it is a mirror
  491. $es_query_args['fields'] = array(
  492. 'post_id',
  493. );
  494. /**
  495. * Modify the underlying ES query that is passed to the search endpoint. The returned args must represent a valid ES query
  496. *
  497. * This filter is harder to use if you're unfamiliar with ES, but allows complete control over the query
  498. *
  499. * @module search
  500. *
  501. * @since 5.0.0
  502. *
  503. * @param array $es_query_args The raw Elasticsearch query args.
  504. * @param WP_Query $query The original WP_Query object.
  505. */
  506. $es_query_args = apply_filters( 'jetpack_search_es_query_args', $es_query_args, $query );
  507. // Do the actual search query!
  508. $this->search_result = $this->search( $es_query_args );
  509. if ( is_wp_error( $this->search_result ) || ! is_array( $this->search_result ) || empty( $this->search_result['results'] ) || empty( $this->search_result['results']['hits'] ) ) {
  510. $this->found_posts = 0;
  511. return;
  512. }
  513. // If we have aggregations, fix the ordering to match the input order (ES doesn't guarantee the return order).
  514. if ( isset( $this->search_result['results']['aggregations'] ) && ! empty( $this->search_result['results']['aggregations'] ) ) {
  515. $this->search_result['results']['aggregations'] = $this->fix_aggregation_ordering( $this->search_result['results']['aggregations'], $this->aggregations );
  516. }
  517. // Total number of results for paging purposes. Capped at $max_offset + $posts_per_page, as deep paging gets quite expensive.
  518. $this->found_posts = min( $this->search_result['results']['total'], $max_offset + $posts_per_page );
  519. }
  520. /**
  521. * If the query has already been run before filters have been updated, then we need to re-run the query
  522. * to get the latest aggregations.
  523. *
  524. * This is especially useful for supporting widget management in the customizer.
  525. *
  526. * @since 5.8.0
  527. *
  528. * @return bool Whether the query was successful or not.
  529. */
  530. public function update_search_results_aggregations() {
  531. if ( empty( $this->last_query_info ) || empty( $this->last_query_info['args'] ) ) {
  532. return false;
  533. }
  534. $es_args = $this->last_query_info['args'];
  535. $builder = new Jetpack_WPES_Query_Builder();
  536. $this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
  537. $es_args['aggregations'] = $builder->build_aggregation();
  538. $this->search_result = $this->search( $es_args );
  539. return ! is_wp_error( $this->search_result );
  540. }
  541. /**
  542. * Given a WP_Query, convert its WP_Tax_Query (if present) into the WP-style Elasticsearch term arguments for the search.
  543. *
  544. * @since 5.0.0
  545. *
  546. * @param WP_Query $query The original WP_Query object for which to parse the taxonomy query.
  547. *
  548. * @return array The new WP-style Elasticsearch arguments (that will be converted into 'real' Elasticsearch arguments).
  549. */
  550. public function get_es_wp_query_terms_for_query( WP_Query $query ) {
  551. $args = array();
  552. $the_tax_query = $query->tax_query;
  553. if ( ! $the_tax_query ) {
  554. return $args;
  555. }
  556. if ( ! $the_tax_query instanceof WP_Tax_Query || empty( $the_tax_query->queried_terms ) || ! is_array( $the_tax_query->queried_terms ) ) {
  557. return $args;
  558. }
  559. $args = array();
  560. foreach ( $the_tax_query->queries as $tax_query ) {
  561. // Right now we only support slugs...see note above
  562. if ( ! is_array( $tax_query ) || 'slug' !== $tax_query['field'] ) {
  563. continue;
  564. }
  565. $taxonomy = $tax_query['taxonomy'];
  566. if ( ! isset( $args[ $taxonomy ] ) || ! is_array( $args[ $taxonomy ] ) ) {
  567. $args[ $taxonomy ] = array();
  568. }
  569. $args[ $taxonomy ] = array_merge( $args[ $taxonomy ], $tax_query['terms'] );
  570. }
  571. return $args;
  572. }
  573. /**
  574. * Parse out the post type from a WP_Query.
  575. *
  576. * Only allows post types that are not marked as 'exclude_from_search'.
  577. *
  578. * @since 5.0.0
  579. *
  580. * @param WP_Query $query Original WP_Query object.
  581. *
  582. * @return array Array of searchable post types corresponding to the original query.
  583. */
  584. public function get_es_wp_query_post_type_for_query( WP_Query $query ) {
  585. $post_types = $query->get( 'post_type' );
  586. // If we're searching 'any', we want to only pass searchable post types to Elasticsearch.
  587. if ( 'any' === $post_types ) {
  588. $post_types = array_values( get_post_types( array(
  589. 'exclude_from_search' => false,
  590. ) ) );
  591. }
  592. if ( ! is_array( $post_types ) ) {
  593. $post_types = array( $post_types );
  594. }
  595. $post_types = array_unique( $post_types );
  596. $sanitized_post_types = array();
  597. // Make sure the post types are queryable.
  598. foreach ( $post_types as $post_type ) {
  599. if ( ! $post_type ) {
  600. continue;
  601. }
  602. $post_type_object = get_post_type_object( $post_type );
  603. if ( ! $post_type_object || $post_type_object->exclude_from_search ) {
  604. continue;
  605. }
  606. $sanitized_post_types[] = $post_type;
  607. }
  608. return $sanitized_post_types;
  609. }
  610. /**
  611. * Get the Elasticsearch result.
  612. *
  613. * @since 5.0.0
  614. *
  615. * @param bool $raw If true, does not check for WP_Error or return the 'results' array - the JSON decoded HTTP response.
  616. *
  617. * @return array|bool The search results, or false if there was a failure.
  618. */
  619. public function get_search_result( $raw = false ) {
  620. if ( $raw ) {
  621. return $this->search_result;
  622. }
  623. return ( ! empty( $this->search_result ) && ! is_wp_error( $this->search_result ) && is_array( $this->search_result ) && ! empty( $this->search_result['results'] ) ) ? $this->search_result['results'] : false;
  624. }
  625. /**
  626. * Add the date portion of a WP_Query onto the query args.
  627. *
  628. * @since 5.0.0
  629. *
  630. * @param array $es_wp_query_args The Elasticsearch query arguments in WordPress form.
  631. * @param WP_Query $query The original WP_Query.
  632. *
  633. * @return array The es wp query args, with date filters added (as needed).
  634. */
  635. public function filter__add_date_filter_to_query( array $es_wp_query_args, WP_Query $query ) {
  636. if ( $query->get( 'year' ) ) {
  637. if ( $query->get( 'monthnum' ) ) {
  638. // Padding
  639. $date_monthnum = sprintf( '%02d', $query->get( 'monthnum' ) );
  640. if ( $query->get( 'day' ) ) {
  641. // Padding
  642. $date_day = sprintf( '%02d', $query->get( 'day' ) );
  643. $date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 00:00:00';
  644. $date_end = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 23:59:59';
  645. } else {
  646. $days_in_month = date( 't', mktime( 0, 0, 0, $query->get( 'monthnum' ), 14, $query->get( 'year' ) ) ); // 14 = middle of the month so no chance of DST issues
  647. $date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-01 00:00:00';
  648. $date_end = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $days_in_month . ' 23:59:59';
  649. }
  650. } else {
  651. $date_start = $query->get( 'year' ) . '-01-01 00:00:00';
  652. $date_end = $query->get( 'year' ) . '-12-31 23:59:59';
  653. }
  654. $es_wp_query_args['date_range'] = array(
  655. 'field' => 'date',
  656. 'gte' => $date_start,
  657. 'lte' => $date_end,
  658. );
  659. }
  660. return $es_wp_query_args;
  661. }
  662. /**
  663. * Converts WP_Query style args to Elasticsearch args.
  664. *
  665. * @since 5.0.0
  666. *
  667. * @param array $args Array of WP_Query style arguments.
  668. *
  669. * @return array Array of ES style query arguments.
  670. */
  671. public function convert_wp_es_to_es_args( array $args ) {
  672. jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-parser' );
  673. $defaults = array(
  674. 'blog_id' => get_current_blog_id(),
  675. 'query' => null, // Search phrase
  676. 'query_fields' => array(), //list of fields to search
  677. 'post_type' => null, // string or an array
  678. 'terms' => array(), // ex: array( 'taxonomy-1' => array( 'slug' ), 'taxonomy-2' => array( 'slug-a', 'slug-b' ) )
  679. 'author' => null, // id or an array of ids
  680. 'author_name' => array(), // string or an array
  681. 'date_range' => null, // array( 'field' => 'date', 'gt' => 'YYYY-MM-dd', 'lte' => 'YYYY-MM-dd' ); date formats: 'YYYY-MM-dd' or 'YYYY-MM-dd HH:MM:SS'
  682. 'orderby' => null, // Defaults to 'relevance' if query is set, otherwise 'date'. Pass an array for multiple orders.
  683. 'order' => 'DESC',
  684. 'posts_per_page' => 10,
  685. 'offset' => null,
  686. 'paged' => null,
  687. /**
  688. * Aggregations. Examples:
  689. * array(
  690. * 'Tag' => array( 'type' => 'taxonomy', 'taxonomy' => 'post_tag', 'count' => 10 ) ),
  691. * 'Post Type' => array( 'type' => 'post_type', 'count' => 10 ) ),
  692. * );
  693. */
  694. 'aggregations' => null,
  695. );
  696. $args = wp_parse_args( $args, $defaults );
  697. $parser = new Jetpack_WPES_Search_Query_Parser( $args['query'], array( get_locale() ) );
  698. if ( empty( $args['query_fields'] ) ) {
  699. if ( defined( 'JETPACK_SEARCH_VIP_INDEX' ) && JETPACK_SEARCH_VIP_INDEX ) {
  700. // VIP indices do not have per language fields
  701. $match_fields = array(
  702. 'title^0.1',
  703. 'content^0.1',
  704. 'excerpt^0.1',
  705. 'tag.name^0.1',
  706. 'category.name^0.1',
  707. 'author_login^0.1',
  708. 'author^0.1',
  709. );
  710. $boost_fields = array(
  711. 'title^2',
  712. 'tag.name',
  713. 'category.name',
  714. 'author_login',
  715. 'author',
  716. );
  717. $boost_phrase_fields = array(
  718. 'title',
  719. 'content',
  720. 'excerpt',
  721. 'tag.name',
  722. 'category.name',
  723. 'author',
  724. );
  725. } else {
  726. $match_fields = $parser->merge_ml_fields(
  727. array(
  728. 'title' => 0.1,
  729. 'content' => 0.1,
  730. 'excerpt' => 0.1,
  731. 'tag.name' => 0.1,
  732. 'category.name' => 0.1,
  733. ),
  734. array(
  735. 'author_login^0.1',
  736. 'author^0.1',
  737. )
  738. );
  739. $boost_fields = $parser->merge_ml_fields(
  740. array(
  741. 'title' => 2,
  742. 'tag.name' => 1,
  743. 'category.name' => 1,
  744. ),
  745. array(
  746. 'author_login',
  747. 'author',
  748. )
  749. );
  750. $boost_phrase_fields = $parser->merge_ml_fields(
  751. array(
  752. 'title' => 1,
  753. 'content' => 1,
  754. 'excerpt' => 1,
  755. 'tag.name' => 1,
  756. 'category.name' => 1,
  757. ),
  758. array(
  759. 'author',
  760. )
  761. );
  762. }
  763. } else {
  764. // If code is overriding the fields, then use that. Important for backwards compatibility.
  765. $match_fields = $args['query_fields'];
  766. $boost_phrase_fields = $match_fields;
  767. $boost_fields = null;
  768. }
  769. $parser->phrase_filter( array(
  770. 'must_query_fields' => $match_fields,
  771. 'boost_query_fields' => null,
  772. ) );
  773. $parser->remaining_query( array(
  774. 'must_query_fields' => $match_fields,
  775. 'boost_query_fields' => $boost_fields,
  776. ) );
  777. // Boost on phrase matches
  778. $parser->remaining_query( array(
  779. 'boost_query_fields' => $boost_phrase_fields,
  780. 'boost_query_type' => 'phrase',
  781. ) );
  782. /**
  783. * Modify the recency decay parameters for the search query.
  784. *
  785. * The recency decay lowers the search scores based on the age of a post relative to an origin date. Basic adjustments:
  786. * - origin: A date. Posts with this date will have the highest score and no decay applied. Default is today.
  787. * - offset: Number of days/months/years (eg 30d). All posts within this time range of the origin (before and after) will have no decay applied. Default is no offset.
  788. * - scale: The number of days/months/years from the origin+offset at which the decay will equal the decay param. Default 360d
  789. * - decay: The amount of decay applied at offset+scale. Default 0.9.
  790. *
  791. * The curve applied is a Gaussian. More details available at {@see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html#function-decay}
  792. *
  793. * @module search
  794. *
  795. * @since 5.8.0
  796. *
  797. * @param array $decay_params The decay parameters.
  798. * @param array $args The WP query parameters.
  799. */
  800. $decay_params = apply_filters(
  801. 'jetpack_search_recency_score_decay',
  802. array(
  803. 'origin' => date( 'Y-m-d' ),
  804. 'scale' => '360d',
  805. 'decay' => 0.9,
  806. ),
  807. $args
  808. );
  809. if ( ! empty( $decay_params ) ) {
  810. // Newer content gets weighted slightly higher
  811. $parser->add_decay( 'gauss', array(
  812. 'date_gmt' => $decay_params
  813. ) );
  814. }
  815. $es_query_args = array(
  816. 'blog_id' => absint( $args['blog_id'] ),
  817. 'size' => absint( $args['posts_per_page'] ),
  818. );
  819. // ES "from" arg (offset)
  820. if ( $args['offset'] ) {
  821. $es_query_args['from'] = absint( $args['offset'] );
  822. } elseif ( $args['paged'] ) {
  823. $es_query_args['from'] = max( 0, ( absint( $args['paged'] ) - 1 ) * $es_query_args['size'] );
  824. }
  825. $es_query_args['from'] = min( $es_query_args['from'], Jetpack_Search_Helpers::get_max_offset() );
  826. if ( ! is_array( $args['author_name'] ) ) {
  827. $args['author_name'] = array( $args['author_name'] );
  828. }
  829. // ES stores usernames, not IDs, so transform
  830. if ( ! empty( $args['author'] ) ) {
  831. if ( ! is_array( $args['author'] ) ) {
  832. $args['author'] = array( $args['author'] );
  833. }
  834. foreach ( $args['author'] as $author ) {
  835. $user = get_user_by( 'id', $author );
  836. if ( $user && ! empty( $user->user_login ) ) {
  837. $args['author_name'][] = $user->user_login;
  838. }
  839. }
  840. }
  841. //////////////////////////////////////////////////
  842. // Build the filters from the query elements.
  843. // Filters rock because they are cached from one query to the next
  844. // but they are cached as individual filters, rather than all combined together.
  845. // May get performance boost by also caching the top level boolean filter too.
  846. if ( $args['post_type'] ) {
  847. if ( ! is_array( $args['post_type'] ) ) {
  848. $args['post_type'] = array( $args['post_type'] );
  849. }
  850. $parser->add_filter( array(
  851. 'terms' => array(
  852. 'post_type' => $args['post_type'],
  853. ),
  854. ) );
  855. }
  856. if ( $args['author_name'] ) {
  857. $parser->add_filter( array(
  858. 'terms' => array(
  859. 'author_login' => $args['author_name'],
  860. ),
  861. ) );
  862. }
  863. if ( ! empty( $args['date_range'] ) && isset( $args['date_range']['field'] ) ) {
  864. $field = $args['date_range']['field'];
  865. unset( $args['date_range']['field'] );
  866. $parser->add_filter( array(
  867. 'range' => array(
  868. $field => $args['date_range'],
  869. ),
  870. ) );
  871. }
  872. if ( is_array( $args['terms'] ) ) {
  873. foreach ( $args['terms'] as $tax => $terms ) {
  874. $terms = (array) $terms;
  875. if ( count( $terms ) && mb_strlen( $tax ) ) {
  876. switch ( $tax ) {
  877. case 'post_tag':
  878. $tax_fld = 'tag.slug';
  879. break;
  880. case 'category':
  881. $tax_fld = 'category.slug';
  882. break;
  883. default:
  884. $tax_fld = 'taxonomy.' . $tax . '.slug';
  885. break;
  886. }
  887. foreach ( $terms as $term ) {
  888. $parser->add_filter( array(
  889. 'term' => array(
  890. $tax_fld => $term,
  891. ),
  892. ) );
  893. }
  894. }
  895. }
  896. }
  897. if ( ! $args['orderby'] ) {
  898. if ( $args['query'] ) {
  899. $args['orderby'] = array( 'relevance' );
  900. } else {
  901. $args['orderby'] = array( 'date' );
  902. }
  903. }
  904. // Validate the "order" field
  905. switch ( strtolower( $args['order'] ) ) {
  906. case 'asc':
  907. $args['order'] = 'asc';
  908. break;
  909. case 'desc':
  910. default:
  911. $args['order'] = 'desc';
  912. break;
  913. }
  914. $es_query_args['sort'] = array();
  915. foreach ( (array) $args['orderby'] as $orderby ) {
  916. // Translate orderby from WP field to ES field
  917. switch ( $orderby ) {
  918. case 'relevance' :
  919. //never order by score ascending
  920. $es_query_args['sort'][] = array(
  921. '_score' => array(
  922. 'order' => 'desc',
  923. ),
  924. );
  925. break;
  926. case 'date' :
  927. $es_query_args['sort'][] = array(
  928. 'date' => array(
  929. 'order' => $args['order'],
  930. ),
  931. );
  932. break;
  933. case 'ID' :
  934. $es_query_args['sort'][] = array(
  935. 'id' => array(
  936. 'order' => $args['order'],
  937. ),
  938. );
  939. break;
  940. case 'author' :
  941. $es_query_args['sort'][] = array(
  942. 'author.raw' => array(
  943. 'order' => $args['order'],
  944. ),
  945. );
  946. break;
  947. } // End switch().
  948. } // End foreach().
  949. if ( empty( $es_query_args['sort'] ) ) {
  950. unset( $es_query_args['sort'] );
  951. }
  952. // Aggregations
  953. if ( ! empty( $args['aggregations'] ) ) {
  954. $this->add_aggregations_to_es_query_builder( $args['aggregations'], $parser );
  955. }
  956. $es_query_args['filter'] = $parser->build_filter();
  957. $es_query_args['query'] = $parser->build_query();
  958. $es_query_args['aggregations'] = $parser->build_aggregation();
  959. return $es_query_args;
  960. }
  961. /**
  962. * Given an array of aggregations, parse and add them onto the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
  963. *
  964. * @since 5.0.0
  965. *
  966. * @param array $aggregations Array of aggregations (filters) to add to the Jetpack_WPES_Query_Builder.
  967. * @param Jetpack_WPES_Query_Builder $builder The builder instance that is creating the Elasticsearch query.
  968. */
  969. public function add_aggregations_to_es_query_builder( array $aggregations, Jetpack_WPES_Query_Builder $builder ) {
  970. foreach ( $aggregations as $label => $aggregation ) {
  971. switch ( $aggregation['type'] ) {
  972. case 'taxonomy':
  973. $this->add_taxonomy_aggregation_to_es_query_builder( $aggregation, $label, $builder );
  974. break;
  975. case 'post_type':
  976. $this->add_post_type_aggregation_to_es_query_builder( $aggregation, $label, $builder );
  977. break;
  978. case 'date_histogram':
  979. $this->add_date_histogram_aggregation_to_es_query_builder( $aggregation, $label, $builder );
  980. break;
  981. }
  982. }
  983. }
  984. /**
  985. * Given an individual taxonomy aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
  986. *
  987. * @since 5.0.0
  988. *
  989. * @param array $aggregation The aggregation to add to the query builder.
  990. * @param string $label The 'label' (unique id) for this aggregation.
  991. * @param Jetpack_WPES_Query_Builder $builder The builder instance that is creating the Elasticsearch query.
  992. */
  993. public function add_taxonomy_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
  994. $field = null;
  995. switch ( $aggregation['taxonomy'] ) {
  996. case 'post_tag':
  997. $field = 'tag';
  998. break;
  999. case 'category':
  1000. $field = 'category';
  1001. break;
  1002. default:
  1003. $field = 'taxonomy.' . $aggregation['taxonomy'];
  1004. break;
  1005. }
  1006. $builder->add_aggs( $label, array(
  1007. 'terms' => array(
  1008. 'field' => $field . '.slug',
  1009. 'size' => min( (int) $aggregation['count'], $this->max_aggregations_count ),
  1010. ),
  1011. ) );
  1012. }
  1013. /**
  1014. * Given an individual post_type aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
  1015. *
  1016. * @since 5.0.0
  1017. *
  1018. * @param array $aggregation The aggregation to add to the query builder.
  1019. * @param string $label The 'label' (unique id) for this aggregation.
  1020. * @param Jetpack_WPES_Query_Builder $builder The builder instance that is creating the Elasticsearch query.
  1021. */
  1022. public function add_post_type_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
  1023. $builder->add_aggs( $label, array(
  1024. 'terms' => array(
  1025. 'field' => 'post_type',
  1026. 'size' => min( (int) $aggregation['count'], $this->max_aggregations_count ),
  1027. ),
  1028. ) );
  1029. }
  1030. /**
  1031. * Given an individual date_histogram aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
  1032. *
  1033. * @since 5.0.0
  1034. *
  1035. * @param array $aggregation The aggregation to add to the query builder.
  1036. * @param string $label The 'label' (unique id) for this aggregation.
  1037. * @param Jetpack_WPES_Query_Builder $builder The builder instance that is creating the Elasticsearch query.
  1038. */
  1039. public function add_date_histogram_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
  1040. $args = array(
  1041. 'interval' => $aggregation['interval'],
  1042. 'field' => ( ! empty( $aggregation['field'] ) && 'post_date_gmt' == $aggregation['field'] ) ? 'date_gmt' : 'date',
  1043. );
  1044. if ( isset( $aggregation['min_doc_count'] ) ) {
  1045. $args['min_doc_count'] = intval( $aggregation['min_doc_count'] );
  1046. } else {
  1047. $args['min_doc_count'] = 1;
  1048. }
  1049. $builder->add_aggs( $label, array(
  1050. 'date_histogram' => $args,
  1051. ) );
  1052. }
  1053. /**
  1054. * And an existing filter object with a list of additional filters.
  1055. *
  1056. * Attempts to optimize the filters somewhat.
  1057. *
  1058. * @since 5.0.0
  1059. *
  1060. * @param array $curr_filter The existing filters to build upon.
  1061. * @param array $filters The new filters to add.
  1062. *
  1063. * @return array The resulting merged filters.
  1064. */
  1065. public static function and_es_filters( array $curr_filter, array $filters ) {
  1066. if ( ! is_array( $curr_filter ) || isset( $curr_filter['match_all'] ) ) {
  1067. if ( 1 === count( $filters ) ) {
  1068. return $filters[0];
  1069. }
  1070. return array(
  1071. 'and' => $filters,
  1072. );
  1073. }
  1074. return array(
  1075. 'and' => array_merge( array( $curr_filter ), $filters ),
  1076. );
  1077. }
  1078. /**
  1079. * Set the available filters for the search.
  1080. *
  1081. * These get rendered via the Jetpack_Search_Widget() widget.
  1082. *
  1083. * Behind the scenes, these are implemented using Elasticsearch Aggregations.
  1084. *
  1085. * If you do not require counts of how many documents match each filter, please consider using regular WP Query
  1086. * arguments instead, such as via the jetpack_search_es_wp_query_args filter
  1087. *
  1088. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
  1089. *
  1090. * @since 5.0.0
  1091. *
  1092. * @param array $aggregations Array of filters (aggregations) to apply to the search
  1093. */
  1094. public function set_filters( array $aggregations ) {
  1095. foreach ( (array) $aggregations as $key => $agg ) {
  1096. if ( empty( $agg['name'] ) ) {
  1097. $aggregations[ $key ]['name'] = $key;
  1098. }
  1099. }
  1100. $this->aggregations = $aggregations;
  1101. }
  1102. /**
  1103. * Set the search's facets (deprecated).
  1104. *
  1105. * @deprecated 5.0 Please use Jetpack_Search::set_filters() instead.
  1106. *
  1107. * @see Jetpack_Search::set_filters()
  1108. *
  1109. * @param array $facets Array of facets to apply to the search.
  1110. */
  1111. public function set_facets( array $facets ) {
  1112. _deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::set_filters()' );
  1113. $this->set_filters( $facets );
  1114. }
  1115. /**
  1116. * Get the raw Aggregation results from the Elasticsearch response.
  1117. *
  1118. * @since 5.0.0
  1119. *
  1120. * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
  1121. *
  1122. * @return array Array of Aggregations performed on the search.
  1123. */
  1124. public function get_search_aggregations_results() {
  1125. $aggregations = array();
  1126. $search_result = $this->get_search_result();
  1127. if ( ! empty( $search_result ) && ! empty( $search_result['aggregations'] ) ) {
  1128. $aggregations = $search_result['aggregations'];
  1129. }
  1130. return $aggregations;
  1131. }
  1132. /**
  1133. * Get the raw Facet results from the Elasticsearch response.
  1134. *
  1135. * @deprecated 5.0 Please use Jetpack_Search::get_search_aggregations_results() instead.
  1136. *
  1137. * @see Jetpack_Search::get_search_aggregations_results()
  1138. *
  1139. * @return array Array of Facets performed on the search.
  1140. */
  1141. public function get_search_facets() {
  1142. _deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_search_aggregations_results()' );
  1143. return $this->get_search_aggregations_results();
  1144. }
  1145. /**
  1146. * Get the results of the Filters performed, including the number of matching documents.
  1147. *
  1148. * Returns an array of Filters (keyed by $label, as passed to Jetpack_Search::set_filters()), containing the Filter and all resulting
  1149. * matching buckets, the url for applying/removing each bucket, etc.
  1150. *
  1151. * NOTE - if this is called before the search is performed, an empty array will be returned. Use the $aggregations class
  1152. * member if you need to access the raw filters set in Jetpack_Search::set_filters().
  1153. *
  1154. * @since 5.0.0
  1155. *
  1156. * @param WP_Query $query The optional original WP_Query to use for determining which filters are active. Defaults to the main query.
  1157. *
  1158. * @return array Array of filters applied and info about them.
  1159. */
  1160. public function get_filters( WP_Query $query = null ) {
  1161. if ( ! $query instanceof WP_Query ) {
  1162. global $wp_query;
  1163. $query = $wp_query;
  1164. }
  1165. $aggregation_data = $this->aggregations;
  1166. if ( empty( $aggregation_data ) ) {
  1167. return $aggregation_data;
  1168. }
  1169. $aggregation_results = $this->get_search_aggregations_results();
  1170. if ( ! $aggregation_results ) {
  1171. return $aggregation_data;
  1172. }
  1173. // NOTE - Looping over the _results_, not the original configured aggregations, so we get the 'real' data from ES
  1174. foreach ( $aggregation_results as $label => $aggregation ) {
  1175. if ( empty( $aggregation ) ) {
  1176. continue;
  1177. }
  1178. $type = $this->aggregations[ $label ]['type'];
  1179. $aggregation_data[ $label ]['buckets'] = array();
  1180. $existing_term_slugs = array();
  1181. $tax_query_var = null;
  1182. // Figure out which terms are active in the query, for this taxonomy
  1183. if ( 'taxonomy' === $this->aggregations[ $label ]['type'] ) {
  1184. $tax_query_var = $this->get_taxonomy_query_var( $this->aggregations[ $label ]['taxonomy'] );
  1185. if ( ! empty( $query->tax_query ) && ! empty( $query->tax_query->queries ) && is_array( $query->tax_query->queries ) ) {
  1186. foreach ( $query->tax_query->queries as $tax_query ) {
  1187. if ( is_array( $tax_query ) && $this->aggregations[ $label ]['taxonomy'] === $tax_query['taxonomy'] &&
  1188. 'slug' === $tax_query['field'] &&
  1189. is_array( $tax_query['terms'] ) ) {
  1190. $existing_term_slugs = array_merge( $existing_term_slugs, $tax_query['terms'] );
  1191. }
  1192. }
  1193. }
  1194. }
  1195. // Now take the resulting found aggregation items and generate the additional info about them, such as activation/deactivation url, name, count, etc.
  1196. $buckets = array();
  1197. if ( ! empty( $aggregation['buckets'] ) ) {
  1198. $buckets = (array) $aggregation['buckets'];
  1199. }
  1200. if ( 'date_histogram' == $type ) {
  1201. //re-order newest to oldest
  1202. $buckets = array_reverse( $buckets );
  1203. }
  1204. // Some aggregation types like date_histogram don't support the max results parameter
  1205. if ( is_int( $this->aggregations[ $label ]['count'] ) && count( $buckets ) > $this->aggregations[ $label ]['count'] ) {
  1206. $buckets = array_slice( $buckets, 0, $this->aggregations[ $label ]['count'] );
  1207. }
  1208. foreach ( $buckets as $item ) {
  1209. $query_vars = array();
  1210. $active = false;
  1211. $remove_url = null;
  1212. $name = '';
  1213. // What type was the original aggregation?
  1214. switch ( $type ) {
  1215. case 'taxonomy':
  1216. $taxonomy = $this->aggregations[ $label ]['taxonomy'];
  1217. $term = get_term_by( 'slug', $item['key'], $taxonomy );
  1218. if ( ! $term || ! $tax_query_var ) {
  1219. continue 2; // switch() is considered a looping structure
  1220. }
  1221. $query_vars = array(
  1222. $tax_query_var => implode( '+', array_merge( $existing_term_slugs, array( $term->slug ) ) ),
  1223. );
  1224. $name = $term->name;
  1225. // Let's determine if this term is active or not
  1226. if ( in_array( $item['key'], $existing_term_slugs, true ) ) {
  1227. $active = true;
  1228. $slug_count = count( $existing_term_slugs );
  1229. if ( $slug_count > 1 ) {
  1230. $remove_url = Jetpack_Search_Helpers::add_query_arg(
  1231. $tax_query_var,
  1232. rawurlencode( implode( '+', array_diff( $existing_term_slugs, array( $item['key'] ) ) ) )
  1233. );
  1234. } else {
  1235. $remove_url = Jetpack_Search_Helpers::remove_query_arg( $tax_query_var );
  1236. }
  1237. }
  1238. break;
  1239. case 'post_type':
  1240. $post_type = get_post_type_object( $item['key'] );
  1241. if ( ! $post_type || $post_type->exclude_from_search ) {
  1242. continue 2; // switch() is considered a looping structure
  1243. }
  1244. $query_vars = array(
  1245. 'post_type' => $item['key'],
  1246. );
  1247. $name = $post_type->labels->singular_name;
  1248. // Is this post type active on this search?
  1249. $post_types = $query->get( 'post_type' );
  1250. if ( ! is_array( $post_types ) ) {
  1251. $post_types = array( $post_types );
  1252. }
  1253. if ( in_array( $item['key'], $post_types ) ) {
  1254. $active = true;
  1255. $post_type_count = count( $post_types );
  1256. // For the right 'remove filter' url, we need to remove the post type from the array, or remove the param entirely if it's the only one
  1257. if ( $post_type_count > 1 ) {
  1258. $remove_url = Jetpack_Search_Helpers::add_query_arg(
  1259. 'post_type',
  1260. rawurlencode( implode( ',', array_diff( $post_types, array( $item['key'] ) ) ) )
  1261. );
  1262. } else {
  1263. $remove_url = Jetpack_Search_Helpers::remove_query_arg( 'post_type' );
  1264. }
  1265. }
  1266. break;
  1267. case 'date_histogram':
  1268. $timestamp = $item['key'] / 1000;
  1269. $current_year = $query->get( 'year' );
  1270. $current_month = $query->get( 'monthnum' );
  1271. $current_day = $query->get( 'day' );
  1272. switch ( $this->aggregations[ $label ]['interval'] ) {
  1273. case 'year':
  1274. $year = (int) date( 'Y', $timestamp );
  1275. $query_vars = array(
  1276. 'year' => $year,
  1277. 'monthnum' => false,
  1278. 'day' => false,
  1279. );
  1280. $name = $year;
  1281. // Is this year currently selected?
  1282. if ( ! empty( $current_year ) && (int) $current_year === $year ) {
  1283. $active = true;
  1284. $remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum', 'day' ) );
  1285. }
  1286. break;
  1287. case 'month':
  1288. $year = (int) date( 'Y', $timestamp );
  1289. $month = (int) date( 'n', $timestamp );
  1290. $query_vars = array(
  1291. 'year' => $year,
  1292. 'monthnum' => $month,
  1293. 'day' => false,
  1294. );
  1295. $name = date( 'F Y', $timestamp );
  1296. // Is this month currently selected?
  1297. if ( ! empty( $current_year ) && (int) $current_year === $year &&
  1298. ! empty( $current_month ) && (int) $current_month === $month ) {
  1299. $active = true;
  1300. $remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum' ) );
  1301. }
  1302. break;
  1303. case 'day':
  1304. $year = (int) date( 'Y', $timestamp );
  1305. $month = (int) date( 'n', $timestamp );
  1306. $day = (int) date( 'j', $timestamp );
  1307. $query_vars = array(
  1308. 'year' => $year,
  1309. 'monthnum' => $month,
  1310. 'day' => $day,
  1311. );
  1312. $name = date( 'F jS, Y', $timestamp );
  1313. // Is this day currently selected?
  1314. if ( ! empty( $current_year ) && (int) $current_year === $year &&
  1315. ! empty( $current_month ) && (int) $current_month === $month &&
  1316. ! empty( $current_day ) && (int) $current_day === $day ) {
  1317. $active = true;
  1318. $remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'day' ) );
  1319. }
  1320. break;
  1321. default:
  1322. continue 3; // switch() is considered a looping structure
  1323. } // End switch().
  1324. break;
  1325. default:
  1326. //continue 2; // switch() is considered a looping structure
  1327. } // End switch().
  1328. // Need to urlencode param values since add_query_arg doesn't
  1329. $url_params = urlencode_deep( $query_vars );
  1330. $aggregation_data[ $label ]['buckets'][] = array(
  1331. 'url' => Jetpack_Search_Helpers::add_query_arg( $url_params ),
  1332. 'query_vars' => $query_vars,
  1333. 'name' => $name,
  1334. 'count' => $item['doc_count'],
  1335. 'active' => $active,
  1336. 'remove_url' => $remove_url,
  1337. 'type' => $type,
  1338. 'type_label' => $aggregation_data[ $label ]['name'],
  1339. 'widget_id' => ! empty( $aggregation_data[ $label ]['widget_id'] ) ? $aggregation_data[ $label ]['widget_id'] : 0
  1340. );
  1341. } // End foreach().
  1342. } // End foreach().
  1343. return $aggregation_data;
  1344. }
  1345. /**
  1346. * Get the results of the facets performed.
  1347. *
  1348. * @deprecated 5.0 Please use Jetpack_Search::get_filters() instead.
  1349. *
  1350. * @see Jetpack_Search::get_filters()
  1351. *
  1352. * @return array $facets Array of facets applied and info about them.
  1353. */
  1354. public function get_search_facet_data() {
  1355. _deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_filters()' );
  1356. return $this->get_filters();
  1357. }
  1358. /**
  1359. * Get the filters that are currently applied to this search.
  1360. *
  1361. * @since 5.0.0
  1362. *
  1363. * @return array Array of filters that were applied.
  1364. */
  1365. public function get_active_filter_buckets() {
  1366. $active_buckets = array();
  1367. $filters = $this->get_filters();
  1368. if ( ! is_array( $filters ) ) {
  1369. return $active_buckets;
  1370. }
  1371. foreach ( $filters as $filter ) {
  1372. if ( isset( $filter['buckets'] ) && is_array( $filter['buckets'] ) ) {
  1373. foreach ( $filter['buckets'] as $item ) {
  1374. if ( isset( $item['active'] ) && $item['active'] ) {
  1375. $active_buckets[] = $item;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. return $active_buckets;
  1381. }
  1382. /**
  1383. * Get the filters that are currently applied to this search.
  1384. *
  1385. * @deprecated 5.0 Please use Jetpack_Search::get_active_filter_buckets() instead.
  1386. *
  1387. * @see Jetpack_Search::get_active_filter_buckets()
  1388. *
  1389. * @return array Array of filters that were applied.
  1390. */
  1391. public function get_current_filters() {
  1392. _deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_active_filter_buckets()' );
  1393. return $this->get_active_filter_buckets();
  1394. }
  1395. /**
  1396. * Calculate the right query var to use for a given taxonomy.
  1397. *
  1398. * Allows custom code to modify the GET var that is used to represent a given taxonomy, via the jetpack_search_taxonomy_query_var filter.
  1399. *
  1400. * @since 5.0.0
  1401. *
  1402. * @param string $taxonomy_name The name of the taxonomy for which to get the query var.
  1403. *
  1404. * @return bool|string The query var to use for this taxonomy, or false if none found.
  1405. */
  1406. public function get_taxonomy_query_var( $taxonomy_name ) {
  1407. $taxonomy = get_taxonomy( $taxonomy_name );
  1408. if ( ! $taxonomy || is_wp_error( $taxonomy ) ) {
  1409. return false;
  1410. }
  1411. /**
  1412. * Modify the query var to use for a given taxonomy
  1413. *
  1414. * @module search
  1415. *
  1416. * @since 5.0.0
  1417. *
  1418. * @param string $query_var The current query_var for the taxonomy
  1419. * @param string $taxonomy_name The taxonomy name
  1420. */
  1421. return apply_filters( 'jetpack_search_taxonomy_query_var', $taxonomy->query_var, $taxonomy_name );
  1422. }
  1423. /**
  1424. * Takes an array of aggregation results, and ensures the array key ordering matches the key order in $desired
  1425. * which is the input order.
  1426. *
  1427. * Necessary because ES does not always return aggregations in the same order that you pass them in,
  1428. * and it should be possible to control the display order easily.
  1429. *
  1430. * @since 5.0.0
  1431. *
  1432. * @param array $aggregations Aggregation results to be reordered.
  1433. * @param array $desired Array with keys representing the desired ordering.
  1434. *
  1435. * @return array A new array with reordered keys, matching those in $desired.
  1436. */
  1437. public function fix_aggregation_ordering( array $aggregations, array $desired ) {
  1438. if ( empty( $aggregations ) || empty( $desired ) ) {
  1439. return $aggregations;
  1440. }
  1441. $reordered = array();
  1442. foreach ( array_keys( $desired ) as $agg_name ) {
  1443. if ( isset( $aggregations[ $agg_name ] ) ) {
  1444. $reordered[ $agg_name ] = $aggregations[ $agg_name ];
  1445. }
  1446. }
  1447. return $reordered;
  1448. }
  1449. /**
  1450. * Sends events to Tracks when a search filters widget is updated.
  1451. *
  1452. * @since 5.8.0
  1453. *
  1454. * @param string $option The option name. Only "widget_jetpack-search-filters" is cared about.
  1455. * @param array $old_value The old option value.
  1456. * @param array $new_value The new option value.
  1457. */
  1458. public function track_widget_updates( $option, $old_value, $new_value ) {
  1459. if ( 'widget_jetpack-search-filters' !== $option ) {
  1460. return;
  1461. }
  1462. $event = Jetpack_Search_Helpers::get_widget_tracks_value( $old_value, $new_value );
  1463. if ( ! $event ) {
  1464. return;
  1465. }
  1466. jetpack_tracks_record_event(
  1467. wp_get_current_user(),
  1468. sprintf( 'jetpack_search_widget_%s', $event['action'] ),
  1469. $event['widget']
  1470. );
  1471. }
  1472. /**
  1473. * Moves any active search widgets to the inactive category.
  1474. *
  1475. * @since 5.9.0
  1476. *
  1477. * @param string $module Unused. The Jetpack module being disabled.
  1478. */
  1479. public function move_search_widgets_to_inactive( $module ) {
  1480. if ( ! is_active_widget( false, false, Jetpack_Search_Helpers::FILTER_WIDGET_BASE, true ) ) {
  1481. return;
  1482. }
  1483. $sidebars_widgets = wp_get_sidebars_widgets();
  1484. if ( ! is_array( $sidebars_widgets ) ) {
  1485. return;
  1486. }
  1487. $changed = false;
  1488. foreach ( $sidebars_widgets as $sidebar => $widgets ) {
  1489. if ( 'wp_inactive_widgets' === $sidebar || 'orphaned_widgets' === substr( $sidebar, 0, 16 ) ) {
  1490. continue;
  1491. }
  1492. if ( is_array( $widgets ) ) {
  1493. foreach ( $widgets as $key => $widget ) {
  1494. if ( _get_widget_id_base( $widget ) == Jetpack_Search_Helpers::FILTER_WIDGET_BASE ) {
  1495. $changed = true;
  1496. array_unshift( $sidebars_widgets['wp_inactive_widgets'], $widget );
  1497. unset( $sidebars_widgets[ $sidebar ][ $key ] );
  1498. }
  1499. }
  1500. }
  1501. }
  1502. if ( $changed ) {
  1503. wp_set_sidebars_widgets( $sidebars_widgets );
  1504. }
  1505. }
  1506. }