class-wp-network-query.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. <?php
  2. /**
  3. * Network API: WP_Network_Query class
  4. *
  5. * @package WordPress
  6. * @subpackage Multisite
  7. * @since 4.6.0
  8. */
  9. /**
  10. * Core class used for querying networks.
  11. *
  12. * @since 4.6.0
  13. *
  14. * @see WP_Network_Query::__construct() for accepted arguments.
  15. */
  16. #[AllowDynamicProperties]
  17. class WP_Network_Query {
  18. /**
  19. * SQL for database query.
  20. *
  21. * @since 4.6.0
  22. * @var string
  23. */
  24. public $request;
  25. /**
  26. * SQL query clauses.
  27. *
  28. * @since 4.6.0
  29. * @var array
  30. */
  31. protected $sql_clauses = array(
  32. 'select' => '',
  33. 'from' => '',
  34. 'where' => array(),
  35. 'groupby' => '',
  36. 'orderby' => '',
  37. 'limits' => '',
  38. );
  39. /**
  40. * Query vars set by the user.
  41. *
  42. * @since 4.6.0
  43. * @var array
  44. */
  45. public $query_vars;
  46. /**
  47. * Default values for query vars.
  48. *
  49. * @since 4.6.0
  50. * @var array
  51. */
  52. public $query_var_defaults;
  53. /**
  54. * List of networks located by the query.
  55. *
  56. * @since 4.6.0
  57. * @var array
  58. */
  59. public $networks;
  60. /**
  61. * The amount of found networks for the current query.
  62. *
  63. * @since 4.6.0
  64. * @var int
  65. */
  66. public $found_networks = 0;
  67. /**
  68. * The number of pages.
  69. *
  70. * @since 4.6.0
  71. * @var int
  72. */
  73. public $max_num_pages = 0;
  74. /**
  75. * Constructor.
  76. *
  77. * Sets up the network query, based on the query vars passed.
  78. *
  79. * @since 4.6.0
  80. *
  81. * @param string|array $query {
  82. * Optional. Array or query string of network query parameters. Default empty.
  83. *
  84. * @type int[] $network__in Array of network IDs to include. Default empty.
  85. * @type int[] $network__not_in Array of network IDs to exclude. Default empty.
  86. * @type bool $count Whether to return a network count (true) or array of network objects.
  87. * Default false.
  88. * @type string $fields Network fields to return. Accepts 'ids' (returns an array of network IDs)
  89. * or empty (returns an array of complete network objects). Default empty.
  90. * @type int $number Maximum number of networks to retrieve. Default empty (no limit).
  91. * @type int $offset Number of networks to offset the query. Used to build LIMIT clause.
  92. * Default 0.
  93. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
  94. * @type string|array $orderby Network status or array of statuses. Accepts 'id', 'domain', 'path',
  95. * 'domain_length', 'path_length' and 'network__in'. Also accepts false,
  96. * an empty array, or 'none' to disable `ORDER BY` clause. Default 'id'.
  97. * @type string $order How to order retrieved networks. Accepts 'ASC', 'DESC'. Default 'ASC'.
  98. * @type string $domain Limit results to those affiliated with a given domain. Default empty.
  99. * @type string[] $domain__in Array of domains to include affiliated networks for. Default empty.
  100. * @type string[] $domain__not_in Array of domains to exclude affiliated networks for. Default empty.
  101. * @type string $path Limit results to those affiliated with a given path. Default empty.
  102. * @type string[] $path__in Array of paths to include affiliated networks for. Default empty.
  103. * @type string[] $path__not_in Array of paths to exclude affiliated networks for. Default empty.
  104. * @type string $search Search term(s) to retrieve matching networks for. Default empty.
  105. * @type bool $update_network_cache Whether to prime the cache for found networks. Default true.
  106. * }
  107. */
  108. public function __construct( $query = '' ) {
  109. $this->query_var_defaults = array(
  110. 'network__in' => '',
  111. 'network__not_in' => '',
  112. 'count' => false,
  113. 'fields' => '',
  114. 'number' => '',
  115. 'offset' => '',
  116. 'no_found_rows' => true,
  117. 'orderby' => 'id',
  118. 'order' => 'ASC',
  119. 'domain' => '',
  120. 'domain__in' => '',
  121. 'domain__not_in' => '',
  122. 'path' => '',
  123. 'path__in' => '',
  124. 'path__not_in' => '',
  125. 'search' => '',
  126. 'update_network_cache' => true,
  127. );
  128. if ( ! empty( $query ) ) {
  129. $this->query( $query );
  130. }
  131. }
  132. /**
  133. * Parses arguments passed to the network query with default query parameters.
  134. *
  135. * @since 4.6.0
  136. *
  137. * @param string|array $query WP_Network_Query arguments. See WP_Network_Query::__construct()
  138. */
  139. public function parse_query( $query = '' ) {
  140. if ( empty( $query ) ) {
  141. $query = $this->query_vars;
  142. }
  143. $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
  144. /**
  145. * Fires after the network query vars have been parsed.
  146. *
  147. * @since 4.6.0
  148. *
  149. * @param WP_Network_Query $query The WP_Network_Query instance (passed by reference).
  150. */
  151. do_action_ref_array( 'parse_network_query', array( &$this ) );
  152. }
  153. /**
  154. * Sets up the WordPress query for retrieving networks.
  155. *
  156. * @since 4.6.0
  157. *
  158. * @param string|array $query Array or URL query string of parameters.
  159. * @return array|int List of WP_Network objects, a list of network IDs when 'fields' is set to 'ids',
  160. * or the number of networks when 'count' is passed as a query var.
  161. */
  162. public function query( $query ) {
  163. $this->query_vars = wp_parse_args( $query );
  164. return $this->get_networks();
  165. }
  166. /**
  167. * Gets a list of networks matching the query vars.
  168. *
  169. * @since 4.6.0
  170. *
  171. * @return array|int List of WP_Network objects, a list of network IDs when 'fields' is set to 'ids',
  172. * or the number of networks when 'count' is passed as a query var.
  173. */
  174. public function get_networks() {
  175. $this->parse_query();
  176. /**
  177. * Fires before networks are retrieved.
  178. *
  179. * @since 4.6.0
  180. *
  181. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference).
  182. */
  183. do_action_ref_array( 'pre_get_networks', array( &$this ) );
  184. $network_data = null;
  185. /**
  186. * Filters the network data before the query takes place.
  187. *
  188. * Return a non-null value to bypass WordPress' default network queries.
  189. *
  190. * The expected return type from this filter depends on the value passed
  191. * in the request query vars:
  192. * - When `$this->query_vars['count']` is set, the filter should return
  193. * the network count as an integer.
  194. * - When `'ids' === $this->query_vars['fields']`, the filter should return
  195. * an array of network IDs.
  196. * - Otherwise the filter should return an array of WP_Network objects.
  197. *
  198. * Note that if the filter returns an array of network data, it will be assigned
  199. * to the `networks` property of the current WP_Network_Query instance.
  200. *
  201. * Filtering functions that require pagination information are encouraged to set
  202. * the `found_networks` and `max_num_pages` properties of the WP_Network_Query object,
  203. * passed to the filter by reference. If WP_Network_Query does not perform a database
  204. * query, it will not have enough information to generate these values itself.
  205. *
  206. * @since 5.2.0
  207. * @since 5.6.0 The returned array of network data is assigned to the `networks` property
  208. * of the current WP_Network_Query instance.
  209. *
  210. * @param array|int|null $network_data Return an array of network data to short-circuit WP's network query,
  211. * the network count as an integer if `$this->query_vars['count']` is set,
  212. * or null to allow WP to run its normal queries.
  213. * @param WP_Network_Query $query The WP_Network_Query instance, passed by reference.
  214. */
  215. $network_data = apply_filters_ref_array( 'networks_pre_query', array( $network_data, &$this ) );
  216. if ( null !== $network_data ) {
  217. if ( is_array( $network_data ) && ! $this->query_vars['count'] ) {
  218. $this->networks = $network_data;
  219. }
  220. return $network_data;
  221. }
  222. // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
  223. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
  224. // Ignore the $fields, $update_network_cache arguments as the queried result will be the same regardless.
  225. unset( $_args['fields'], $_args['update_network_cache'] );
  226. $key = md5( serialize( $_args ) );
  227. $last_changed = wp_cache_get_last_changed( 'networks' );
  228. $cache_key = "get_network_ids:$key:$last_changed";
  229. $cache_value = wp_cache_get( $cache_key, 'networks' );
  230. if ( false === $cache_value ) {
  231. $network_ids = $this->get_network_ids();
  232. if ( $network_ids ) {
  233. $this->set_found_networks();
  234. }
  235. $cache_value = array(
  236. 'network_ids' => $network_ids,
  237. 'found_networks' => $this->found_networks,
  238. );
  239. wp_cache_add( $cache_key, $cache_value, 'networks' );
  240. } else {
  241. $network_ids = $cache_value['network_ids'];
  242. $this->found_networks = $cache_value['found_networks'];
  243. }
  244. if ( $this->found_networks && $this->query_vars['number'] ) {
  245. $this->max_num_pages = ceil( $this->found_networks / $this->query_vars['number'] );
  246. }
  247. // If querying for a count only, there's nothing more to do.
  248. if ( $this->query_vars['count'] ) {
  249. // $network_ids is actually a count in this case.
  250. return (int) $network_ids;
  251. }
  252. $network_ids = array_map( 'intval', $network_ids );
  253. if ( 'ids' === $this->query_vars['fields'] ) {
  254. $this->networks = $network_ids;
  255. return $this->networks;
  256. }
  257. if ( $this->query_vars['update_network_cache'] ) {
  258. _prime_network_caches( $network_ids );
  259. }
  260. // Fetch full network objects from the primed cache.
  261. $_networks = array();
  262. foreach ( $network_ids as $network_id ) {
  263. $_network = get_network( $network_id );
  264. if ( $_network ) {
  265. $_networks[] = $_network;
  266. }
  267. }
  268. /**
  269. * Filters the network query results.
  270. *
  271. * @since 4.6.0
  272. *
  273. * @param WP_Network[] $_networks An array of WP_Network objects.
  274. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference).
  275. */
  276. $_networks = apply_filters_ref_array( 'the_networks', array( $_networks, &$this ) );
  277. // Convert to WP_Network instances.
  278. $this->networks = array_map( 'get_network', $_networks );
  279. return $this->networks;
  280. }
  281. /**
  282. * Used internally to get a list of network IDs matching the query vars.
  283. *
  284. * @since 4.6.0
  285. *
  286. * @global wpdb $wpdb WordPress database abstraction object.
  287. *
  288. * @return int|array A single count of network IDs if a count query. An array of network IDs if a full query.
  289. */
  290. protected function get_network_ids() {
  291. global $wpdb;
  292. $order = $this->parse_order( $this->query_vars['order'] );
  293. // Disable ORDER BY with 'none', an empty array, or boolean false.
  294. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  295. $orderby = '';
  296. } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
  297. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  298. $this->query_vars['orderby'] :
  299. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  300. $orderby_array = array();
  301. foreach ( $ordersby as $_key => $_value ) {
  302. if ( ! $_value ) {
  303. continue;
  304. }
  305. if ( is_int( $_key ) ) {
  306. $_orderby = $_value;
  307. $_order = $order;
  308. } else {
  309. $_orderby = $_key;
  310. $_order = $_value;
  311. }
  312. $parsed = $this->parse_orderby( $_orderby );
  313. if ( ! $parsed ) {
  314. continue;
  315. }
  316. if ( 'network__in' === $_orderby ) {
  317. $orderby_array[] = $parsed;
  318. continue;
  319. }
  320. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  321. }
  322. $orderby = implode( ', ', $orderby_array );
  323. } else {
  324. $orderby = "$wpdb->site.id $order";
  325. }
  326. $number = absint( $this->query_vars['number'] );
  327. $offset = absint( $this->query_vars['offset'] );
  328. $limits = '';
  329. if ( ! empty( $number ) ) {
  330. if ( $offset ) {
  331. $limits = 'LIMIT ' . $offset . ',' . $number;
  332. } else {
  333. $limits = 'LIMIT ' . $number;
  334. }
  335. }
  336. if ( $this->query_vars['count'] ) {
  337. $fields = 'COUNT(*)';
  338. } else {
  339. $fields = "$wpdb->site.id";
  340. }
  341. // Parse network IDs for an IN clause.
  342. if ( ! empty( $this->query_vars['network__in'] ) ) {
  343. $this->sql_clauses['where']['network__in'] = "$wpdb->site.id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
  344. }
  345. // Parse network IDs for a NOT IN clause.
  346. if ( ! empty( $this->query_vars['network__not_in'] ) ) {
  347. $this->sql_clauses['where']['network__not_in'] = "$wpdb->site.id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
  348. }
  349. if ( ! empty( $this->query_vars['domain'] ) ) {
  350. $this->sql_clauses['where']['domain'] = $wpdb->prepare( "$wpdb->site.domain = %s", $this->query_vars['domain'] );
  351. }
  352. // Parse network domain for an IN clause.
  353. if ( is_array( $this->query_vars['domain__in'] ) ) {
  354. $this->sql_clauses['where']['domain__in'] = "$wpdb->site.domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
  355. }
  356. // Parse network domain for a NOT IN clause.
  357. if ( is_array( $this->query_vars['domain__not_in'] ) ) {
  358. $this->sql_clauses['where']['domain__not_in'] = "$wpdb->site.domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
  359. }
  360. if ( ! empty( $this->query_vars['path'] ) ) {
  361. $this->sql_clauses['where']['path'] = $wpdb->prepare( "$wpdb->site.path = %s", $this->query_vars['path'] );
  362. }
  363. // Parse network path for an IN clause.
  364. if ( is_array( $this->query_vars['path__in'] ) ) {
  365. $this->sql_clauses['where']['path__in'] = "$wpdb->site.path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
  366. }
  367. // Parse network path for a NOT IN clause.
  368. if ( is_array( $this->query_vars['path__not_in'] ) ) {
  369. $this->sql_clauses['where']['path__not_in'] = "$wpdb->site.path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
  370. }
  371. // Falsey search strings are ignored.
  372. if ( strlen( $this->query_vars['search'] ) ) {
  373. $this->sql_clauses['where']['search'] = $this->get_search_sql(
  374. $this->query_vars['search'],
  375. array( "$wpdb->site.domain", "$wpdb->site.path" )
  376. );
  377. }
  378. $join = '';
  379. $where = implode( ' AND ', $this->sql_clauses['where'] );
  380. $groupby = '';
  381. $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
  382. /**
  383. * Filters the network query clauses.
  384. *
  385. * @since 4.6.0
  386. *
  387. * @param string[] $clauses An associative array of network query clauses.
  388. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference).
  389. */
  390. $clauses = apply_filters_ref_array( 'networks_clauses', array( compact( $pieces ), &$this ) );
  391. $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
  392. $join = isset( $clauses['join'] ) ? $clauses['join'] : '';
  393. $where = isset( $clauses['where'] ) ? $clauses['where'] : '';
  394. $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
  395. $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
  396. $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
  397. if ( $where ) {
  398. $where = 'WHERE ' . $where;
  399. }
  400. if ( $groupby ) {
  401. $groupby = 'GROUP BY ' . $groupby;
  402. }
  403. if ( $orderby ) {
  404. $orderby = "ORDER BY $orderby";
  405. }
  406. $found_rows = '';
  407. if ( ! $this->query_vars['no_found_rows'] ) {
  408. $found_rows = 'SQL_CALC_FOUND_ROWS';
  409. }
  410. $this->sql_clauses['select'] = "SELECT $found_rows $fields";
  411. $this->sql_clauses['from'] = "FROM $wpdb->site $join";
  412. $this->sql_clauses['groupby'] = $groupby;
  413. $this->sql_clauses['orderby'] = $orderby;
  414. $this->sql_clauses['limits'] = $limits;
  415. $this->request = "
  416. {$this->sql_clauses['select']}
  417. {$this->sql_clauses['from']}
  418. {$where}
  419. {$this->sql_clauses['groupby']}
  420. {$this->sql_clauses['orderby']}
  421. {$this->sql_clauses['limits']}
  422. ";
  423. if ( $this->query_vars['count'] ) {
  424. return (int) $wpdb->get_var( $this->request );
  425. }
  426. $network_ids = $wpdb->get_col( $this->request );
  427. return array_map( 'intval', $network_ids );
  428. }
  429. /**
  430. * Populates found_networks and max_num_pages properties for the current query
  431. * if the limit clause was used.
  432. *
  433. * @since 4.6.0
  434. *
  435. * @global wpdb $wpdb WordPress database abstraction object.
  436. */
  437. private function set_found_networks() {
  438. global $wpdb;
  439. if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
  440. /**
  441. * Filters the query used to retrieve found network count.
  442. *
  443. * @since 4.6.0
  444. *
  445. * @param string $found_networks_query SQL query. Default 'SELECT FOUND_ROWS()'.
  446. * @param WP_Network_Query $network_query The `WP_Network_Query` instance.
  447. */
  448. $found_networks_query = apply_filters( 'found_networks_query', 'SELECT FOUND_ROWS()', $this );
  449. $this->found_networks = (int) $wpdb->get_var( $found_networks_query );
  450. }
  451. }
  452. /**
  453. * Used internally to generate an SQL string for searching across multiple columns.
  454. *
  455. * @since 4.6.0
  456. *
  457. * @global wpdb $wpdb WordPress database abstraction object.
  458. *
  459. * @param string $search Search string.
  460. * @param string[] $columns Array of columns to search.
  461. * @return string Search SQL.
  462. */
  463. protected function get_search_sql( $search, $columns ) {
  464. global $wpdb;
  465. $like = '%' . $wpdb->esc_like( $search ) . '%';
  466. $searches = array();
  467. foreach ( $columns as $column ) {
  468. $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
  469. }
  470. return '(' . implode( ' OR ', $searches ) . ')';
  471. }
  472. /**
  473. * Parses and sanitizes 'orderby' keys passed to the network query.
  474. *
  475. * @since 4.6.0
  476. *
  477. * @global wpdb $wpdb WordPress database abstraction object.
  478. *
  479. * @param string $orderby Alias for the field to order by.
  480. * @return string|false Value to used in the ORDER clause. False otherwise.
  481. */
  482. protected function parse_orderby( $orderby ) {
  483. global $wpdb;
  484. $allowed_keys = array(
  485. 'id',
  486. 'domain',
  487. 'path',
  488. );
  489. $parsed = false;
  490. if ( 'network__in' === $orderby ) {
  491. $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
  492. $parsed = "FIELD( {$wpdb->site}.id, $network__in )";
  493. } elseif ( 'domain_length' === $orderby || 'path_length' === $orderby ) {
  494. $field = substr( $orderby, 0, -7 );
  495. $parsed = "CHAR_LENGTH($wpdb->site.$field)";
  496. } elseif ( in_array( $orderby, $allowed_keys, true ) ) {
  497. $parsed = "$wpdb->site.$orderby";
  498. }
  499. return $parsed;
  500. }
  501. /**
  502. * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary.
  503. *
  504. * @since 4.6.0
  505. *
  506. * @param string $order The 'order' query variable.
  507. * @return string The sanitized 'order' query variable.
  508. */
  509. protected function parse_order( $order ) {
  510. if ( ! is_string( $order ) || empty( $order ) ) {
  511. return 'ASC';
  512. }
  513. if ( 'ASC' === strtoupper( $order ) ) {
  514. return 'ASC';
  515. } else {
  516. return 'DESC';
  517. }
  518. }
  519. }