class-wp-network-query.php 18 KB

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