Bez popisu

class-wp-network-query.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 int[] $network__in Array of network IDs to include. Default empty.
  84. * @type int[] $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 string[] $domain__in Array of domains to include affiliated networks for. Default empty.
  99. * @type string[] $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 string[] $path__in Array of paths to include affiliated networks for. Default empty.
  102. * @type string[] $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. * Filters the network data before the query takes place.
  186. *
  187. * Return a non-null value to bypass WordPress' default network queries.
  188. *
  189. * The expected return type from this filter depends on the value passed
  190. * in the request query vars:
  191. * - When `$this->query_vars['count']` is set, the filter should return
  192. * the network count as an integer.
  193. * - When `'ids' === $this->query_vars['fields']`, the filter should return
  194. * an array of network IDs.
  195. * - Otherwise the filter should return an array of WP_Network objects.
  196. *
  197. * Note that if the filter returns an array of network data, it will be assigned
  198. * to the `networks` property of the current WP_Network_Query instance.
  199. *
  200. * Filtering functions that require pagination information are encouraged to set
  201. * the `found_networks` and `max_num_pages` properties of the WP_Network_Query object,
  202. * passed to the filter by reference. If WP_Network_Query does not perform a database
  203. * query, it will not have enough information to generate these values itself.
  204. *
  205. * @since 5.2.0
  206. * @since 5.6.0 The returned array of network data is assigned to the `networks` property
  207. * of the current WP_Network_Query instance.
  208. *
  209. * @param array|int|null $network_data Return an array of network data to short-circuit WP's network query,
  210. * the network count as an integer if `$this->query_vars['count']` is set,
  211. * or null to allow WP to run its normal queries.
  212. * @param WP_Network_Query $query The WP_Network_Query instance, passed by reference.
  213. */
  214. $network_data = apply_filters_ref_array( 'networks_pre_query', array( $network_data, &$this ) );
  215. if ( null !== $network_data ) {
  216. if ( is_array( $network_data ) && ! $this->query_vars['count'] ) {
  217. $this->networks = $network_data;
  218. }
  219. return $network_data;
  220. }
  221. // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
  222. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
  223. // Ignore the $fields argument as the queried result will be the same regardless.
  224. unset( $_args['fields'] );
  225. $key = md5( serialize( $_args ) );
  226. $last_changed = wp_cache_get_last_changed( 'networks' );
  227. $cache_key = "get_network_ids:$key:$last_changed";
  228. $cache_value = wp_cache_get( $cache_key, 'networks' );
  229. if ( false === $cache_value ) {
  230. $network_ids = $this->get_network_ids();
  231. if ( $network_ids ) {
  232. $this->set_found_networks();
  233. }
  234. $cache_value = array(
  235. 'network_ids' => $network_ids,
  236. 'found_networks' => $this->found_networks,
  237. );
  238. wp_cache_add( $cache_key, $cache_value, 'networks' );
  239. } else {
  240. $network_ids = $cache_value['network_ids'];
  241. $this->found_networks = $cache_value['found_networks'];
  242. }
  243. if ( $this->found_networks && $this->query_vars['number'] ) {
  244. $this->max_num_pages = ceil( $this->found_networks / $this->query_vars['number'] );
  245. }
  246. // If querying for a count only, there's nothing more to do.
  247. if ( $this->query_vars['count'] ) {
  248. // $network_ids is actually a count in this case.
  249. return (int) $network_ids;
  250. }
  251. $network_ids = array_map( 'intval', $network_ids );
  252. if ( 'ids' === $this->query_vars['fields'] ) {
  253. $this->networks = $network_ids;
  254. return $this->networks;
  255. }
  256. if ( $this->query_vars['update_network_cache'] ) {
  257. _prime_network_caches( $network_ids );
  258. }
  259. // Fetch full network objects from the primed cache.
  260. $_networks = array();
  261. foreach ( $network_ids as $network_id ) {
  262. $_network = get_network( $network_id );
  263. if ( $_network ) {
  264. $_networks[] = $_network;
  265. }
  266. }
  267. /**
  268. * Filters the network query results.
  269. *
  270. * @since 4.6.0
  271. *
  272. * @param WP_Network[] $_networks An array of WP_Network objects.
  273. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference).
  274. */
  275. $_networks = apply_filters_ref_array( 'the_networks', array( $_networks, &$this ) );
  276. // Convert to WP_Network instances.
  277. $this->networks = array_map( 'get_network', $_networks );
  278. return $this->networks;
  279. }
  280. /**
  281. * Used internally to get a list of network IDs matching the query vars.
  282. *
  283. * @since 4.6.0
  284. *
  285. * @global wpdb $wpdb WordPress database abstraction object.
  286. *
  287. * @return int|array A single count of network IDs if a count query. An array of network IDs if a full query.
  288. */
  289. protected function get_network_ids() {
  290. global $wpdb;
  291. $order = $this->parse_order( $this->query_vars['order'] );
  292. // Disable ORDER BY with 'none', an empty array, or boolean false.
  293. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  294. $orderby = '';
  295. } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
  296. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  297. $this->query_vars['orderby'] :
  298. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  299. $orderby_array = array();
  300. foreach ( $ordersby as $_key => $_value ) {
  301. if ( ! $_value ) {
  302. continue;
  303. }
  304. if ( is_int( $_key ) ) {
  305. $_orderby = $_value;
  306. $_order = $order;
  307. } else {
  308. $_orderby = $_key;
  309. $_order = $_value;
  310. }
  311. $parsed = $this->parse_orderby( $_orderby );
  312. if ( ! $parsed ) {
  313. continue;
  314. }
  315. if ( 'network__in' === $_orderby ) {
  316. $orderby_array[] = $parsed;
  317. continue;
  318. }
  319. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  320. }
  321. $orderby = implode( ', ', $orderby_array );
  322. } else {
  323. $orderby = "$wpdb->site.id $order";
  324. }
  325. $number = absint( $this->query_vars['number'] );
  326. $offset = absint( $this->query_vars['offset'] );
  327. $limits = '';
  328. if ( ! empty( $number ) ) {
  329. if ( $offset ) {
  330. $limits = 'LIMIT ' . $offset . ',' . $number;
  331. } else {
  332. $limits = 'LIMIT ' . $number;
  333. }
  334. }
  335. if ( $this->query_vars['count'] ) {
  336. $fields = 'COUNT(*)';
  337. } else {
  338. $fields = "$wpdb->site.id";
  339. }
  340. // Parse network IDs for an IN clause.
  341. if ( ! empty( $this->query_vars['network__in'] ) ) {
  342. $this->sql_clauses['where']['network__in'] = "$wpdb->site.id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
  343. }
  344. // Parse network IDs for a NOT IN clause.
  345. if ( ! empty( $this->query_vars['network__not_in'] ) ) {
  346. $this->sql_clauses['where']['network__not_in'] = "$wpdb->site.id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
  347. }
  348. if ( ! empty( $this->query_vars['domain'] ) ) {
  349. $this->sql_clauses['where']['domain'] = $wpdb->prepare( "$wpdb->site.domain = %s", $this->query_vars['domain'] );
  350. }
  351. // Parse network domain for an IN clause.
  352. if ( is_array( $this->query_vars['domain__in'] ) ) {
  353. $this->sql_clauses['where']['domain__in'] = "$wpdb->site.domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
  354. }
  355. // Parse network domain for a NOT IN clause.
  356. if ( is_array( $this->query_vars['domain__not_in'] ) ) {
  357. $this->sql_clauses['where']['domain__not_in'] = "$wpdb->site.domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
  358. }
  359. if ( ! empty( $this->query_vars['path'] ) ) {
  360. $this->sql_clauses['where']['path'] = $wpdb->prepare( "$wpdb->site.path = %s", $this->query_vars['path'] );
  361. }
  362. // Parse network path for an IN clause.
  363. if ( is_array( $this->query_vars['path__in'] ) ) {
  364. $this->sql_clauses['where']['path__in'] = "$wpdb->site.path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
  365. }
  366. // Parse network path for a NOT IN clause.
  367. if ( is_array( $this->query_vars['path__not_in'] ) ) {
  368. $this->sql_clauses['where']['path__not_in'] = "$wpdb->site.path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
  369. }
  370. // Falsey search strings are ignored.
  371. if ( strlen( $this->query_vars['search'] ) ) {
  372. $this->sql_clauses['where']['search'] = $this->get_search_sql(
  373. $this->query_vars['search'],
  374. array( "$wpdb->site.domain", "$wpdb->site.path" )
  375. );
  376. }
  377. $join = '';
  378. $where = implode( ' AND ', $this->sql_clauses['where'] );
  379. $groupby = '';
  380. $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
  381. /**
  382. * Filters the network query clauses.
  383. *
  384. * @since 4.6.0
  385. *
  386. * @param string[] $pieces An associative array of network query clauses.
  387. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference).
  388. */
  389. $clauses = apply_filters_ref_array( 'networks_clauses', array( compact( $pieces ), &$this ) );
  390. $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
  391. $join = isset( $clauses['join'] ) ? $clauses['join'] : '';
  392. $where = isset( $clauses['where'] ) ? $clauses['where'] : '';
  393. $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
  394. $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
  395. $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
  396. if ( $where ) {
  397. $where = 'WHERE ' . $where;
  398. }
  399. if ( $groupby ) {
  400. $groupby = 'GROUP BY ' . $groupby;
  401. }
  402. if ( $orderby ) {
  403. $orderby = "ORDER BY $orderby";
  404. }
  405. $found_rows = '';
  406. if ( ! $this->query_vars['no_found_rows'] ) {
  407. $found_rows = 'SQL_CALC_FOUND_ROWS';
  408. }
  409. $this->sql_clauses['select'] = "SELECT $found_rows $fields";
  410. $this->sql_clauses['from'] = "FROM $wpdb->site $join";
  411. $this->sql_clauses['groupby'] = $groupby;
  412. $this->sql_clauses['orderby'] = $orderby;
  413. $this->sql_clauses['limits'] = $limits;
  414. $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
  415. if ( $this->query_vars['count'] ) {
  416. return (int) $wpdb->get_var( $this->request );
  417. }
  418. $network_ids = $wpdb->get_col( $this->request );
  419. return array_map( 'intval', $network_ids );
  420. }
  421. /**
  422. * Populates found_networks and max_num_pages properties for the current query
  423. * if the limit clause was used.
  424. *
  425. * @since 4.6.0
  426. *
  427. * @global wpdb $wpdb WordPress database abstraction object.
  428. */
  429. private function set_found_networks() {
  430. global $wpdb;
  431. if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
  432. /**
  433. * Filters the query used to retrieve found network count.
  434. *
  435. * @since 4.6.0
  436. *
  437. * @param string $found_networks_query SQL query. Default 'SELECT FOUND_ROWS()'.
  438. * @param WP_Network_Query $network_query The `WP_Network_Query` instance.
  439. */
  440. $found_networks_query = apply_filters( 'found_networks_query', 'SELECT FOUND_ROWS()', $this );
  441. $this->found_networks = (int) $wpdb->get_var( $found_networks_query );
  442. }
  443. }
  444. /**
  445. * Used internally to generate an SQL string for searching across multiple columns.
  446. *
  447. * @since 4.6.0
  448. *
  449. * @global wpdb $wpdb WordPress database abstraction object.
  450. *
  451. * @param string $string Search string.
  452. * @param string[] $columns Array of columns to search.
  453. * @return string Search SQL.
  454. */
  455. protected function get_search_sql( $string, $columns ) {
  456. global $wpdb;
  457. $like = '%' . $wpdb->esc_like( $string ) . '%';
  458. $searches = array();
  459. foreach ( $columns as $column ) {
  460. $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
  461. }
  462. return '(' . implode( ' OR ', $searches ) . ')';
  463. }
  464. /**
  465. * Parses and sanitizes 'orderby' keys passed to the network query.
  466. *
  467. * @since 4.6.0
  468. *
  469. * @global wpdb $wpdb WordPress database abstraction object.
  470. *
  471. * @param string $orderby Alias for the field to order by.
  472. * @return string|false Value to used in the ORDER clause. False otherwise.
  473. */
  474. protected function parse_orderby( $orderby ) {
  475. global $wpdb;
  476. $allowed_keys = array(
  477. 'id',
  478. 'domain',
  479. 'path',
  480. );
  481. $parsed = false;
  482. if ( 'network__in' === $orderby ) {
  483. $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
  484. $parsed = "FIELD( {$wpdb->site}.id, $network__in )";
  485. } elseif ( 'domain_length' === $orderby || 'path_length' === $orderby ) {
  486. $field = substr( $orderby, 0, -7 );
  487. $parsed = "CHAR_LENGTH($wpdb->site.$field)";
  488. } elseif ( in_array( $orderby, $allowed_keys, true ) ) {
  489. $parsed = "$wpdb->site.$orderby";
  490. }
  491. return $parsed;
  492. }
  493. /**
  494. * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary.
  495. *
  496. * @since 4.6.0
  497. *
  498. * @param string $order The 'order' query variable.
  499. * @return string The sanitized 'order' query variable.
  500. */
  501. protected function parse_order( $order ) {
  502. if ( ! is_string( $order ) || empty( $order ) ) {
  503. return 'ASC';
  504. }
  505. if ( 'ASC' === strtoupper( $order ) ) {
  506. return 'ASC';
  507. } else {
  508. return 'DESC';
  509. }
  510. }
  511. }