class-wp-site-query.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. /**
  3. * Site API: WP_Site_Query class
  4. *
  5. * @package WordPress
  6. * @subpackage Sites
  7. * @since 4.6.0
  8. */
  9. /**
  10. * Core class used for querying sites.
  11. *
  12. * @since 4.6.0
  13. *
  14. * @see WP_Site_Query::__construct() for accepted arguments.
  15. */
  16. class WP_Site_Query {
  17. /**
  18. * SQL for database query.
  19. *
  20. * @since 4.6.0
  21. * @var string
  22. */
  23. public $request;
  24. /**
  25. * SQL query clauses.
  26. *
  27. * @since 4.6.0
  28. * @var array
  29. */
  30. protected $sql_clauses = array(
  31. 'select' => '',
  32. 'from' => '',
  33. 'where' => array(),
  34. 'groupby' => '',
  35. 'orderby' => '',
  36. 'limits' => '',
  37. );
  38. /**
  39. * Metadata query container.
  40. *
  41. * @since 5.1.0
  42. * @var WP_Meta_Query
  43. */
  44. public $meta_query = false;
  45. /**
  46. * Metadata query clauses.
  47. *
  48. * @since 5.1.0
  49. * @var array
  50. */
  51. protected $meta_query_clauses;
  52. /**
  53. * Date query container.
  54. *
  55. * @since 4.6.0
  56. * @var object WP_Date_Query
  57. */
  58. public $date_query = false;
  59. /**
  60. * Query vars set by the user.
  61. *
  62. * @since 4.6.0
  63. * @var array
  64. */
  65. public $query_vars;
  66. /**
  67. * Default values for query vars.
  68. *
  69. * @since 4.6.0
  70. * @var array
  71. */
  72. public $query_var_defaults;
  73. /**
  74. * List of sites located by the query.
  75. *
  76. * @since 4.6.0
  77. * @var array
  78. */
  79. public $sites;
  80. /**
  81. * The amount of found sites for the current query.
  82. *
  83. * @since 4.6.0
  84. * @var int
  85. */
  86. public $found_sites = 0;
  87. /**
  88. * The number of pages.
  89. *
  90. * @since 4.6.0
  91. * @var int
  92. */
  93. public $max_num_pages = 0;
  94. /**
  95. * Sets up the site query, based on the query vars passed.
  96. *
  97. * @since 4.6.0
  98. * @since 4.8.0 Introduced the 'lang_id', 'lang__in', and 'lang__not_in' parameters.
  99. * @since 5.1.0 Introduced the 'update_site_meta_cache', 'meta_query', 'meta_key',
  100. * 'meta_value', 'meta_type' and 'meta_compare' parameters.
  101. *
  102. * @param string|array $query {
  103. * Optional. Array or query string of site query parameters. Default empty.
  104. *
  105. * @type array $site__in Array of site IDs to include. Default empty.
  106. * @type array $site__not_in Array of site IDs to exclude. Default empty.
  107. * @type bool $count Whether to return a site count (true) or array of site objects.
  108. * Default false.
  109. * @type array $date_query Date query clauses to limit sites by. See WP_Date_Query.
  110. * Default null.
  111. * @type string $fields Site fields to return. Accepts 'ids' (returns an array of site IDs)
  112. * or empty (returns an array of complete site objects). Default empty.
  113. * @type int $ID A site ID to only return that site. Default empty.
  114. * @type int $number Maximum number of sites to retrieve. Default 100.
  115. * @type int $offset Number of sites to offset the query. Used to build LIMIT clause.
  116. * Default 0.
  117. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
  118. * @type string|array $orderby Site status or array of statuses. Accepts 'id', 'domain', 'path',
  119. * 'network_id', 'last_updated', 'registered', 'domain_length',
  120. * 'path_length', 'site__in' and 'network__in'. Also accepts false,
  121. * an empty array, or 'none' to disable `ORDER BY` clause.
  122. * Default 'id'.
  123. * @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
  124. * @type int $network_id Limit results to those affiliated with a given network ID. If 0,
  125. * include all networks. Default 0.
  126. * @type array $network__in Array of network IDs to include affiliated sites for. Default empty.
  127. * @type array $network__not_in Array of network IDs to exclude affiliated sites for. Default empty.
  128. * @type string $domain Limit results to those affiliated with a given domain. Default empty.
  129. * @type array $domain__in Array of domains to include affiliated sites for. Default empty.
  130. * @type array $domain__not_in Array of domains to exclude affiliated sites for. Default empty.
  131. * @type string $path Limit results to those affiliated with a given path. Default empty.
  132. * @type array $path__in Array of paths to include affiliated sites for. Default empty.
  133. * @type array $path__not_in Array of paths to exclude affiliated sites for. Default empty.
  134. * @type int $public Limit results to public sites. Accepts '1' or '0'. Default empty.
  135. * @type int $archived Limit results to archived sites. Accepts '1' or '0'. Default empty.
  136. * @type int $mature Limit results to mature sites. Accepts '1' or '0'. Default empty.
  137. * @type int $spam Limit results to spam sites. Accepts '1' or '0'. Default empty.
  138. * @type int $deleted Limit results to deleted sites. Accepts '1' or '0'. Default empty.
  139. * @type int $lang_id Limit results to a language ID. Default empty.
  140. * @type array $lang__in Array of language IDs to include affiliated sites for. Default empty.
  141. * @type array $lang__not_in Array of language IDs to exclude affiliated sites for. Default empty.
  142. * @type string $search Search term(s) to retrieve matching sites for. Default empty.
  143. * @type array $search_columns Array of column names to be searched. Accepts 'domain' and 'path'.
  144. * Default empty array.
  145. * @type bool $update_site_cache Whether to prime the cache for found sites. Default true.
  146. * @type bool $update_site_meta_cache Whether to prime the metadata cache for found sites. Default true.
  147. * @type array $meta_query Meta query clauses to limit retrieved sites by. See `WP_Meta_Query`.
  148. * Default empty.
  149. * @type string $meta_key Limit sites to those matching a specific metadata key.
  150. * Can be used in conjunction with `$meta_value`. Default empty.
  151. * @type string $meta_value Limit sites to those matching a specific metadata value.
  152. * Usually used in conjunction with `$meta_key`. Default empty.
  153. * @type string $meta_type Data type that the `$meta_value` column will be CAST to for
  154. * comparisons. Default empty.
  155. * @type string $meta_compare Comparison operator to test the `$meta_value`. Default empty.
  156. * }
  157. */
  158. public function __construct( $query = '' ) {
  159. $this->query_var_defaults = array(
  160. 'fields' => '',
  161. 'ID' => '',
  162. 'site__in' => '',
  163. 'site__not_in' => '',
  164. 'number' => 100,
  165. 'offset' => '',
  166. 'no_found_rows' => true,
  167. 'orderby' => 'id',
  168. 'order' => 'ASC',
  169. 'network_id' => 0,
  170. 'network__in' => '',
  171. 'network__not_in' => '',
  172. 'domain' => '',
  173. 'domain__in' => '',
  174. 'domain__not_in' => '',
  175. 'path' => '',
  176. 'path__in' => '',
  177. 'path__not_in' => '',
  178. 'public' => null,
  179. 'archived' => null,
  180. 'mature' => null,
  181. 'spam' => null,
  182. 'deleted' => null,
  183. 'lang_id' => null,
  184. 'lang__in' => '',
  185. 'lang__not_in' => '',
  186. 'search' => '',
  187. 'search_columns' => array(),
  188. 'count' => false,
  189. 'date_query' => null, // See WP_Date_Query
  190. 'update_site_cache' => true,
  191. 'update_site_meta_cache' => true,
  192. 'meta_query' => '',
  193. 'meta_key' => '',
  194. 'meta_value' => '',
  195. 'meta_type' => '',
  196. 'meta_compare' => '',
  197. );
  198. if ( ! empty( $query ) ) {
  199. $this->query( $query );
  200. }
  201. }
  202. /**
  203. * Parses arguments passed to the site query with default query parameters.
  204. *
  205. * @since 4.6.0
  206. *
  207. * @see WP_Site_Query::__construct()
  208. *
  209. * @param string|array $query Array or string of WP_Site_Query arguments. See WP_Site_Query::__construct().
  210. */
  211. public function parse_query( $query = '' ) {
  212. if ( empty( $query ) ) {
  213. $query = $this->query_vars;
  214. }
  215. $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
  216. /**
  217. * Fires after the site query vars have been parsed.
  218. *
  219. * @since 4.6.0
  220. *
  221. * @param WP_Site_Query $this The WP_Site_Query instance (passed by reference).
  222. */
  223. do_action_ref_array( 'parse_site_query', array( &$this ) );
  224. }
  225. /**
  226. * Sets up the WordPress query for retrieving sites.
  227. *
  228. * @since 4.6.0
  229. *
  230. * @param string|array $query Array or URL query string of parameters.
  231. * @return array|int List of WP_Site objects, a list of site ids when 'fields' is set to 'ids',
  232. * or the number of sites when 'count' is passed as a query var.
  233. */
  234. public function query( $query ) {
  235. $this->query_vars = wp_parse_args( $query );
  236. return $this->get_sites();
  237. }
  238. /**
  239. * Retrieves a list of sites matching the query vars.
  240. *
  241. * @since 4.6.0
  242. *
  243. * @global wpdb $wpdb WordPress database abstraction object.
  244. *
  245. * @return array|int List of WP_Site objects, a list of site ids when 'fields' is set to 'ids',
  246. * or the number of sites when 'count' is passed as a query var.
  247. */
  248. public function get_sites() {
  249. global $wpdb;
  250. $this->parse_query();
  251. // Parse meta query.
  252. $this->meta_query = new WP_Meta_Query();
  253. $this->meta_query->parse_query_vars( $this->query_vars );
  254. /**
  255. * Fires before sites are retrieved.
  256. *
  257. * @since 4.6.0
  258. *
  259. * @param WP_Site_Query $this Current instance of WP_Site_Query (passed by reference).
  260. */
  261. do_action_ref_array( 'pre_get_sites', array( &$this ) );
  262. // Reparse query vars, in case they were modified in a 'pre_get_sites' callback.
  263. $this->meta_query->parse_query_vars( $this->query_vars );
  264. if ( ! empty( $this->meta_query->queries ) ) {
  265. $this->meta_query_clauses = $this->meta_query->get_sql( 'blog', $wpdb->blogs, 'blog_id', $this );
  266. }
  267. $site_data = null;
  268. /**
  269. * Filter the site data before the get_sites query takes place.
  270. *
  271. * Return a non-null value to bypass WordPress's default site queries.
  272. *
  273. * The expected return type from this filter depends on the value passed in the request query_vars:
  274. * When `$this->query_vars['count']` is set, the filter should return the site count as an int.
  275. * When `'ids' == $this->query_vars['fields']`, the filter should return an array of site ids.
  276. * Otherwise the filter should return an array of WP_Site objects.
  277. *
  278. * @since 5.2.0
  279. *
  280. * @param array|int|null $site_data Return an array of site data to short-circuit WP's site query,
  281. * the site count as an integer if `$this->query_vars['count']` is set,
  282. * or null to run the normal queries.
  283. * @param WP_Site_Query $this The WP_Site_Query instance, passed by reference.
  284. */
  285. $site_data = apply_filters_ref_array( 'sites_pre_query', array( $site_data, &$this ) );
  286. if ( null !== $site_data ) {
  287. return $site_data;
  288. }
  289. // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
  290. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
  291. // Ignore the $fields argument as the queried result will be the same regardless.
  292. unset( $_args['fields'] );
  293. $key = md5( serialize( $_args ) );
  294. $last_changed = wp_cache_get_last_changed( 'sites' );
  295. $cache_key = "get_sites:$key:$last_changed";
  296. $cache_value = wp_cache_get( $cache_key, 'sites' );
  297. if ( false === $cache_value ) {
  298. $site_ids = $this->get_site_ids();
  299. if ( $site_ids ) {
  300. $this->set_found_sites();
  301. }
  302. $cache_value = array(
  303. 'site_ids' => $site_ids,
  304. 'found_sites' => $this->found_sites,
  305. );
  306. wp_cache_add( $cache_key, $cache_value, 'sites' );
  307. } else {
  308. $site_ids = $cache_value['site_ids'];
  309. $this->found_sites = $cache_value['found_sites'];
  310. }
  311. if ( $this->found_sites && $this->query_vars['number'] ) {
  312. $this->max_num_pages = ceil( $this->found_sites / $this->query_vars['number'] );
  313. }
  314. // If querying for a count only, there's nothing more to do.
  315. if ( $this->query_vars['count'] ) {
  316. // $site_ids is actually a count in this case.
  317. return intval( $site_ids );
  318. }
  319. $site_ids = array_map( 'intval', $site_ids );
  320. if ( 'ids' == $this->query_vars['fields'] ) {
  321. $this->sites = $site_ids;
  322. return $this->sites;
  323. }
  324. // Prime site network caches.
  325. if ( $this->query_vars['update_site_cache'] ) {
  326. _prime_site_caches( $site_ids, $this->query_vars['update_site_meta_cache'] );
  327. }
  328. // Fetch full site objects from the primed cache.
  329. $_sites = array();
  330. foreach ( $site_ids as $site_id ) {
  331. $_site = get_site( $site_id );
  332. if ( $_site ) {
  333. $_sites[] = $_site;
  334. }
  335. }
  336. /**
  337. * Filters the site query results.
  338. *
  339. * @since 4.6.0
  340. *
  341. * @param WP_Site[] $_sites An array of WP_Site objects.
  342. * @param WP_Site_Query $this Current instance of WP_Site_Query (passed by reference).
  343. */
  344. $_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
  345. // Convert to WP_Site instances.
  346. $this->sites = array_map( 'get_site', $_sites );
  347. return $this->sites;
  348. }
  349. /**
  350. * Used internally to get a list of site IDs matching the query vars.
  351. *
  352. * @since 4.6.0
  353. *
  354. * @global wpdb $wpdb WordPress database abstraction object.
  355. *
  356. * @return int|array A single count of site IDs if a count query. An array of site IDs if a full query.
  357. */
  358. protected function get_site_ids() {
  359. global $wpdb;
  360. $order = $this->parse_order( $this->query_vars['order'] );
  361. // Disable ORDER BY with 'none', an empty array, or boolean false.
  362. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  363. $orderby = '';
  364. } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
  365. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  366. $this->query_vars['orderby'] :
  367. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  368. $orderby_array = array();
  369. foreach ( $ordersby as $_key => $_value ) {
  370. if ( ! $_value ) {
  371. continue;
  372. }
  373. if ( is_int( $_key ) ) {
  374. $_orderby = $_value;
  375. $_order = $order;
  376. } else {
  377. $_orderby = $_key;
  378. $_order = $_value;
  379. }
  380. $parsed = $this->parse_orderby( $_orderby );
  381. if ( ! $parsed ) {
  382. continue;
  383. }
  384. if ( 'site__in' === $_orderby || 'network__in' === $_orderby ) {
  385. $orderby_array[] = $parsed;
  386. continue;
  387. }
  388. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  389. }
  390. $orderby = implode( ', ', $orderby_array );
  391. } else {
  392. $orderby = "{$wpdb->blogs}.blog_id $order";
  393. }
  394. $number = absint( $this->query_vars['number'] );
  395. $offset = absint( $this->query_vars['offset'] );
  396. $limits = '';
  397. if ( ! empty( $number ) ) {
  398. if ( $offset ) {
  399. $limits = 'LIMIT ' . $offset . ',' . $number;
  400. } else {
  401. $limits = 'LIMIT ' . $number;
  402. }
  403. }
  404. if ( $this->query_vars['count'] ) {
  405. $fields = 'COUNT(*)';
  406. } else {
  407. $fields = "{$wpdb->blogs}.blog_id";
  408. }
  409. // Parse site IDs for an IN clause.
  410. $site_id = absint( $this->query_vars['ID'] );
  411. if ( ! empty( $site_id ) ) {
  412. $this->sql_clauses['where']['ID'] = $wpdb->prepare( "{$wpdb->blogs}.blog_id = %d", $site_id );
  413. }
  414. // Parse site IDs for an IN clause.
  415. if ( ! empty( $this->query_vars['site__in'] ) ) {
  416. $this->sql_clauses['where']['site__in'] = "{$wpdb->blogs}.blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
  417. }
  418. // Parse site IDs for a NOT IN clause.
  419. if ( ! empty( $this->query_vars['site__not_in'] ) ) {
  420. $this->sql_clauses['where']['site__not_in'] = "{$wpdb->blogs}.blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
  421. }
  422. $network_id = absint( $this->query_vars['network_id'] );
  423. if ( ! empty( $network_id ) ) {
  424. $this->sql_clauses['where']['network_id'] = $wpdb->prepare( 'site_id = %d', $network_id );
  425. }
  426. // Parse site network IDs for an IN clause.
  427. if ( ! empty( $this->query_vars['network__in'] ) ) {
  428. $this->sql_clauses['where']['network__in'] = 'site_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
  429. }
  430. // Parse site network IDs for a NOT IN clause.
  431. if ( ! empty( $this->query_vars['network__not_in'] ) ) {
  432. $this->sql_clauses['where']['network__not_in'] = 'site_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
  433. }
  434. if ( ! empty( $this->query_vars['domain'] ) ) {
  435. $this->sql_clauses['where']['domain'] = $wpdb->prepare( 'domain = %s', $this->query_vars['domain'] );
  436. }
  437. // Parse site domain for an IN clause.
  438. if ( is_array( $this->query_vars['domain__in'] ) ) {
  439. $this->sql_clauses['where']['domain__in'] = "domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
  440. }
  441. // Parse site domain for a NOT IN clause.
  442. if ( is_array( $this->query_vars['domain__not_in'] ) ) {
  443. $this->sql_clauses['where']['domain__not_in'] = "domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
  444. }
  445. if ( ! empty( $this->query_vars['path'] ) ) {
  446. $this->sql_clauses['where']['path'] = $wpdb->prepare( 'path = %s', $this->query_vars['path'] );
  447. }
  448. // Parse site path for an IN clause.
  449. if ( is_array( $this->query_vars['path__in'] ) ) {
  450. $this->sql_clauses['where']['path__in'] = "path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
  451. }
  452. // Parse site path for a NOT IN clause.
  453. if ( is_array( $this->query_vars['path__not_in'] ) ) {
  454. $this->sql_clauses['where']['path__not_in'] = "path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
  455. }
  456. if ( is_numeric( $this->query_vars['archived'] ) ) {
  457. $archived = absint( $this->query_vars['archived'] );
  458. $this->sql_clauses['where']['archived'] = $wpdb->prepare( 'archived = %s ', absint( $archived ) );
  459. }
  460. if ( is_numeric( $this->query_vars['mature'] ) ) {
  461. $mature = absint( $this->query_vars['mature'] );
  462. $this->sql_clauses['where']['mature'] = $wpdb->prepare( 'mature = %d ', $mature );
  463. }
  464. if ( is_numeric( $this->query_vars['spam'] ) ) {
  465. $spam = absint( $this->query_vars['spam'] );
  466. $this->sql_clauses['where']['spam'] = $wpdb->prepare( 'spam = %d ', $spam );
  467. }
  468. if ( is_numeric( $this->query_vars['deleted'] ) ) {
  469. $deleted = absint( $this->query_vars['deleted'] );
  470. $this->sql_clauses['where']['deleted'] = $wpdb->prepare( 'deleted = %d ', $deleted );
  471. }
  472. if ( is_numeric( $this->query_vars['public'] ) ) {
  473. $public = absint( $this->query_vars['public'] );
  474. $this->sql_clauses['where']['public'] = $wpdb->prepare( 'public = %d ', $public );
  475. }
  476. if ( is_numeric( $this->query_vars['lang_id'] ) ) {
  477. $lang_id = absint( $this->query_vars['lang_id'] );
  478. $this->sql_clauses['where']['lang_id'] = $wpdb->prepare( 'lang_id = %d ', $lang_id );
  479. }
  480. // Parse site language IDs for an IN clause.
  481. if ( ! empty( $this->query_vars['lang__in'] ) ) {
  482. $this->sql_clauses['where']['lang__in'] = 'lang_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['lang__in'] ) ) . ' )';
  483. }
  484. // Parse site language IDs for a NOT IN clause.
  485. if ( ! empty( $this->query_vars['lang__not_in'] ) ) {
  486. $this->sql_clauses['where']['lang__not_in'] = 'lang_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['lang__not_in'] ) ) . ' )';
  487. }
  488. // Falsey search strings are ignored.
  489. if ( strlen( $this->query_vars['search'] ) ) {
  490. $search_columns = array();
  491. if ( $this->query_vars['search_columns'] ) {
  492. $search_columns = array_intersect( $this->query_vars['search_columns'], array( 'domain', 'path' ) );
  493. }
  494. if ( ! $search_columns ) {
  495. $search_columns = array( 'domain', 'path' );
  496. }
  497. /**
  498. * Filters the columns to search in a WP_Site_Query search.
  499. *
  500. * The default columns include 'domain' and 'path.
  501. *
  502. * @since 4.6.0
  503. *
  504. * @param string[] $search_columns Array of column names to be searched.
  505. * @param string $search Text being searched.
  506. * @param WP_Site_Query $this The current WP_Site_Query instance.
  507. */
  508. $search_columns = apply_filters( 'site_search_columns', $search_columns, $this->query_vars['search'], $this );
  509. $this->sql_clauses['where']['search'] = $this->get_search_sql( $this->query_vars['search'], $search_columns );
  510. }
  511. $date_query = $this->query_vars['date_query'];
  512. if ( ! empty( $date_query ) && is_array( $date_query ) ) {
  513. $this->date_query = new WP_Date_Query( $date_query, 'registered' );
  514. $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
  515. }
  516. $join = '';
  517. $groupby = '';
  518. if ( ! empty( $this->meta_query_clauses ) ) {
  519. $join .= $this->meta_query_clauses['join'];
  520. // Strip leading 'AND'.
  521. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
  522. if ( ! $this->query_vars['count'] ) {
  523. $groupby = "{$wpdb->blogs}.blog_id";
  524. }
  525. }
  526. $where = implode( ' AND ', $this->sql_clauses['where'] );
  527. $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
  528. /**
  529. * Filters the site query clauses.
  530. *
  531. * @since 4.6.0
  532. *
  533. * @param string[] $pieces An associative array of site query clauses.
  534. * @param WP_Site_Query $this Current instance of WP_Site_Query (passed by reference).
  535. */
  536. $clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
  537. $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
  538. $join = isset( $clauses['join'] ) ? $clauses['join'] : '';
  539. $where = isset( $clauses['where'] ) ? $clauses['where'] : '';
  540. $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
  541. $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
  542. $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
  543. if ( $where ) {
  544. $where = 'WHERE ' . $where;
  545. }
  546. if ( $groupby ) {
  547. $groupby = 'GROUP BY ' . $groupby;
  548. }
  549. if ( $orderby ) {
  550. $orderby = "ORDER BY $orderby";
  551. }
  552. $found_rows = '';
  553. if ( ! $this->query_vars['no_found_rows'] ) {
  554. $found_rows = 'SQL_CALC_FOUND_ROWS';
  555. }
  556. $this->sql_clauses['select'] = "SELECT $found_rows $fields";
  557. $this->sql_clauses['from'] = "FROM $wpdb->blogs $join";
  558. $this->sql_clauses['groupby'] = $groupby;
  559. $this->sql_clauses['orderby'] = $orderby;
  560. $this->sql_clauses['limits'] = $limits;
  561. $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
  562. if ( $this->query_vars['count'] ) {
  563. return intval( $wpdb->get_var( $this->request ) );
  564. }
  565. $site_ids = $wpdb->get_col( $this->request );
  566. return array_map( 'intval', $site_ids );
  567. }
  568. /**
  569. * Populates found_sites and max_num_pages properties for the current query
  570. * if the limit clause was used.
  571. *
  572. * @since 4.6.0
  573. *
  574. * @global wpdb $wpdb WordPress database abstraction object.
  575. */
  576. private function set_found_sites() {
  577. global $wpdb;
  578. if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
  579. /**
  580. * Filters the query used to retrieve found site count.
  581. *
  582. * @since 4.6.0
  583. *
  584. * @param string $found_sites_query SQL query. Default 'SELECT FOUND_ROWS()'.
  585. * @param WP_Site_Query $site_query The `WP_Site_Query` instance.
  586. */
  587. $found_sites_query = apply_filters( 'found_sites_query', 'SELECT FOUND_ROWS()', $this );
  588. $this->found_sites = (int) $wpdb->get_var( $found_sites_query );
  589. }
  590. }
  591. /**
  592. * Used internally to generate an SQL string for searching across multiple columns.
  593. *
  594. * @since 4.6.0
  595. *
  596. * @global wpdb $wpdb WordPress database abstraction object.
  597. *
  598. * @param string $string Search string.
  599. * @param string[] $columns Array of columns to search.
  600. * @return string Search SQL.
  601. */
  602. protected function get_search_sql( $string, $columns ) {
  603. global $wpdb;
  604. if ( false !== strpos( $string, '*' ) ) {
  605. $like = '%' . implode( '%', array_map( array( $wpdb, 'esc_like' ), explode( '*', $string ) ) ) . '%';
  606. } else {
  607. $like = '%' . $wpdb->esc_like( $string ) . '%';
  608. }
  609. $searches = array();
  610. foreach ( $columns as $column ) {
  611. $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
  612. }
  613. return '(' . implode( ' OR ', $searches ) . ')';
  614. }
  615. /**
  616. * Parses and sanitizes 'orderby' keys passed to the site query.
  617. *
  618. * @since 4.6.0
  619. *
  620. * @global wpdb $wpdb WordPress database abstraction object.
  621. *
  622. * @param string $orderby Alias for the field to order by.
  623. * @return string|false Value to used in the ORDER clause. False otherwise.
  624. */
  625. protected function parse_orderby( $orderby ) {
  626. global $wpdb;
  627. $parsed = false;
  628. switch ( $orderby ) {
  629. case 'site__in':
  630. $site__in = implode( ',', array_map( 'absint', $this->query_vars['site__in'] ) );
  631. $parsed = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
  632. break;
  633. case 'network__in':
  634. $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
  635. $parsed = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
  636. break;
  637. case 'domain':
  638. case 'last_updated':
  639. case 'path':
  640. case 'registered':
  641. $parsed = $orderby;
  642. break;
  643. case 'network_id':
  644. $parsed = 'site_id';
  645. break;
  646. case 'domain_length':
  647. $parsed = 'CHAR_LENGTH(domain)';
  648. break;
  649. case 'path_length':
  650. $parsed = 'CHAR_LENGTH(path)';
  651. break;
  652. case 'id':
  653. $parsed = "{$wpdb->blogs}.blog_id";
  654. break;
  655. }
  656. if ( ! empty( $parsed ) || empty( $this->meta_query_clauses ) ) {
  657. return $parsed;
  658. }
  659. $meta_clauses = $this->meta_query->get_clauses();
  660. if ( empty( $meta_clauses ) ) {
  661. return $parsed;
  662. }
  663. $primary_meta_query = reset( $meta_clauses );
  664. if ( ! empty( $primary_meta_query['key'] ) && $primary_meta_query['key'] === $orderby ) {
  665. $orderby = 'meta_value';
  666. }
  667. switch ( $orderby ) {
  668. case 'meta_value':
  669. if ( ! empty( $primary_meta_query['type'] ) ) {
  670. $parsed = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
  671. } else {
  672. $parsed = "{$primary_meta_query['alias']}.meta_value";
  673. }
  674. break;
  675. case 'meta_value_num':
  676. $parsed = "{$primary_meta_query['alias']}.meta_value+0";
  677. break;
  678. default:
  679. if ( isset( $meta_clauses[ $orderby ] ) ) {
  680. $meta_clause = $meta_clauses[ $orderby ];
  681. $parsed = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
  682. }
  683. }
  684. return $parsed;
  685. }
  686. /**
  687. * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary.
  688. *
  689. * @since 4.6.0
  690. *
  691. * @param string $order The 'order' query variable.
  692. * @return string The sanitized 'order' query variable.
  693. */
  694. protected function parse_order( $order ) {
  695. if ( ! is_string( $order ) || empty( $order ) ) {
  696. return 'ASC';
  697. }
  698. if ( 'ASC' === strtoupper( $order ) ) {
  699. return 'ASC';
  700. } else {
  701. return 'DESC';
  702. }
  703. }
  704. }