class-wp-network-query.php 17 KB

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