+/**
+ * WordPress User Query class.
+ *
+ * @since 3.1.0
+ */
+class WP_User_Query {
+
+ /**
+ * Query vars, after parsing
+ *
+ * @since 3.5.0
+ * @access public
+ * @var array
+ */
+ public $query_vars = array();
+
+ /**
+ * List of found user ids
+ *
+ * @since 3.1.0
+ * @access private
+ * @var array
+ */
+ private $results;
+
+ /**
+ * Total number of found users for the current query
+ *
+ * @since 3.1.0
+ * @access private
+ * @var int
+ */
+ private $total_users = 0;
+
+ // SQL clauses
+ public $query_fields;
+ public $query_from;
+ public $query_where;
+ public $query_orderby;
+ public $query_limit;
+
+ /**
+ * PHP5 constructor.
+ *
+ * @since 3.1.0
+ *
+ * @param string|array $args Optional. The query variables.
+ * @return WP_User_Query
+ */
+ public function __construct( $query = null ) {
+ if ( ! empty( $query ) ) {
+ $this->prepare_query( $query );
+ $this->query();
+ }
+ }
+
+ /**
+ * Prepare the query variables.
+ *
+ * @since 3.1.0
+ *
+ * @param string|array $args Optional. The query variables.
+ */
+ public function prepare_query( $query = array() ) {
+ global $wpdb;
+
+ if ( empty( $this->query_vars ) || ! empty( $query ) ) {
+ $this->query_limit = null;
+ $this->query_vars = wp_parse_args( $query, array(
+ 'blog_id' => $GLOBALS['blog_id'],
+ 'role' => '',
+ 'meta_key' => '',
+ 'meta_value' => '',
+ 'meta_compare' => '',
+ 'include' => array(),
+ 'exclude' => array(),
+ 'search' => '',
+ 'search_columns' => array(),
+ 'orderby' => 'login',
+ 'order' => 'ASC',
+ 'offset' => '',
+ 'number' => '',
+ 'count_total' => true,
+ 'fields' => 'all',
+ 'who' => ''
+ ) );
+ }
+
+ /**
+ * Fires before the WP_User_Query has been parsed.
+ *
+ * The passed WP_User_Query object contains the query variables, not
+ * yet passed into SQL.
+ *
+ * @since 4.0.0
+ *
+ * @param WP_User_Query $this The current WP_User_Query instance,
+ * passed by reference.
+ */
+ do_action( 'pre_get_users', $this );
+
+ $qv =& $this->query_vars;
+
+ if ( is_array( $qv['fields'] ) ) {
+ $qv['fields'] = array_unique( $qv['fields'] );
+
+ $this->query_fields = array();
+ foreach ( $qv['fields'] as $field ) {
+ $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
+ $this->query_fields[] = "$wpdb->users.$field";
+ }
+ $this->query_fields = implode( ',', $this->query_fields );
+ } elseif ( 'all' == $qv['fields'] ) {
+ $this->query_fields = "$wpdb->users.*";
+ } else {
+ $this->query_fields = "$wpdb->users.ID";
+ }
+
+ if ( isset( $qv['count_total'] ) && $qv['count_total'] )
+ $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
+
+ $this->query_from = "FROM $wpdb->users";
+ $this->query_where = "WHERE 1=1";
+
+ // sorting
+ if ( isset( $qv['orderby'] ) ) {
+ if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
+ $orderby = 'user_' . $qv['orderby'];
+ } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
+ $orderby = $qv['orderby'];
+ } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
+ $orderby = 'display_name';
+ } elseif ( 'post_count' == $qv['orderby'] ) {
+ // todo: avoid the JOIN
+ $where = get_posts_by_author_sql('post');
+ $this->query_from .= " LEFT OUTER JOIN (
+ SELECT post_author, COUNT(*) as post_count
+ FROM $wpdb->posts
+ $where
+ GROUP BY post_author
+ ) p ON ({$wpdb->users}.ID = p.post_author)
+ ";
+ $orderby = 'post_count';
+ } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
+ $orderby = 'ID';
+ } elseif ( 'meta_value' == $qv['orderby'] ) {
+ $orderby = "$wpdb->usermeta.meta_value";
+ } else {
+ $orderby = 'user_login';
+ }
+ }
+
+ if ( empty( $orderby ) )
+ $orderby = 'user_login';
+
+ $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
+ if ( 'ASC' == $qv['order'] )
+ $order = 'ASC';
+ else
+ $order = 'DESC';
+ $this->query_orderby = "ORDER BY $orderby $order";
+
+ // limit
+ if ( isset( $qv['number'] ) && $qv['number'] ) {
+ if ( $qv['offset'] )
+ $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
+ else
+ $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
+ }
+
+ $search = '';
+ if ( isset( $qv['search'] ) )
+ $search = trim( $qv['search'] );
+
+ if ( $search ) {
+ $leading_wild = ( ltrim($search, '*') != $search );
+ $trailing_wild = ( rtrim($search, '*') != $search );
+ if ( $leading_wild && $trailing_wild )
+ $wild = 'both';
+ elseif ( $leading_wild )
+ $wild = 'leading';
+ elseif ( $trailing_wild )
+ $wild = 'trailing';
+ else
+ $wild = false;
+ if ( $wild )
+ $search = trim($search, '*');
+
+ $search_columns = array();
+ if ( $qv['search_columns'] )
+ $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
+ if ( ! $search_columns ) {
+ if ( false !== strpos( $search, '@') )
+ $search_columns = array('user_email');
+ elseif ( is_numeric($search) )
+ $search_columns = array('user_login', 'ID');
+ elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
+ $search_columns = array('user_url');
+ else
+ $search_columns = array('user_login', 'user_nicename');
+ }
+
+ /**
+ * Filter the columns to search in a WP_User_Query search.
+ *
+ * The default columns depend on the search term, and include 'user_email',
+ * 'user_login', 'ID', 'user_url', and 'user_nicename'.
+ *
+ * @since 3.6.0
+ *
+ * @param array $search_columns Array of column names to be searched.
+ * @param string $search Text being searched.
+ * @param WP_User_Query $this The current WP_User_Query instance.
+ */
+ $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
+
+ $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
+ }
+
+ $blog_id = 0;
+ if ( isset( $qv['blog_id'] ) )
+ $blog_id = absint( $qv['blog_id'] );
+
+ if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
+ $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
+ $qv['meta_value'] = 0;
+ $qv['meta_compare'] = '!=';
+ $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
+ }
+
+ $role = '';
+ if ( isset( $qv['role'] ) )
+ $role = trim( $qv['role'] );
+
+ if ( $blog_id && ( $role || is_multisite() ) ) {
+ $cap_meta_query = array();
+ $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
+
+ if ( $role ) {
+ $cap_meta_query['value'] = '"' . $role . '"';
+ $cap_meta_query['compare'] = 'like';
+ }
+
+ if ( empty( $qv['meta_query'] ) || ! in_array( $cap_meta_query, $qv['meta_query'], true ) ) {
+ $qv['meta_query'][] = $cap_meta_query;
+ }
+ }
+
+ $meta_query = new WP_Meta_Query();
+ $meta_query->parse_query_vars( $qv );
+
+ if ( !empty( $meta_query->queries ) ) {
+ $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
+ $this->query_from .= $clauses['join'];
+ $this->query_where .= $clauses['where'];
+
+ if ( 'OR' == $meta_query->relation )
+ $this->query_fields = 'DISTINCT ' . $this->query_fields;
+ }
+
+ if ( ! empty( $qv['include'] ) ) {
+ $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
+ $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
+ } elseif ( ! empty( $qv['exclude'] ) ) {
+ $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
+ $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
+ }
+
+ /**
+ * Fires after the WP_User_Query has been parsed, and before
+ * the query is executed.
+ *
+ * The passed WP_User_Query object contains SQL parts formed
+ * from parsing the given query.
+ *
+ * @since 3.1.0
+ *
+ * @param WP_User_Query $this The current WP_User_Query instance,
+ * passed by reference.
+ */
+ do_action_ref_array( 'pre_user_query', array( &$this ) );
+ }
+
+ /**
+ * Execute the query, with the current variables.
+ *
+ * @since 3.1.0
+ *
+ * @global wpdb $wpdb WordPress database object for queries.
+ */
+ public function query() {
+ global $wpdb;
+
+ $qv =& $this->query_vars;
+
+ $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
+
+ if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
+ $this->results = $wpdb->get_results( $query );
+ } else {
+ $this->results = $wpdb->get_col( $query );
+ }
+
+ /**
+ * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
+ *
+ * @since 3.2.0
+ *
+ * @global wpdb $wpdb WordPress database object.
+ *
+ * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
+ */
+ if ( isset( $qv['count_total'] ) && $qv['count_total'] )
+ $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
+
+ if ( !$this->results )
+ return;
+
+ if ( 'all_with_meta' == $qv['fields'] ) {
+ cache_users( $this->results );
+
+ $r = array();
+ foreach ( $this->results as $userid )
+ $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
+
+ $this->results = $r;
+ } elseif ( 'all' == $qv['fields'] ) {
+ foreach ( $this->results as $key => $user ) {
+ $this->results[ $key ] = new WP_User( $user );
+ }
+ }
+ }
+
+ /**
+ * Retrieve query variable.
+ *
+ * @since 3.5.0
+ * @access public
+ *
+ * @param string $query_var Query variable key.
+ * @return mixed
+ */
+ public function get( $query_var ) {
+ if ( isset( $this->query_vars[$query_var] ) )
+ return $this->query_vars[$query_var];
+
+ return null;
+ }
+
+ /**
+ * Set query variable.
+ *
+ * @since 3.5.0
+ * @access public
+ *
+ * @param string $query_var Query variable key.
+ * @param mixed $value Query variable value.
+ */
+ public function set( $query_var, $value ) {
+ $this->query_vars[$query_var] = $value;
+ }
+
+ /**
+ * Used internally to generate an SQL string for searching across multiple columns
+ *
+ * @access protected
+ * @since 3.1.0
+ *
+ * @param string $string
+ * @param array $cols
+ * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
+ * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
+ * @return string
+ */
+ protected function get_search_sql( $string, $cols, $wild = false ) {
+ global $wpdb;
+
+ $searches = array();
+ $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
+ $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
+ $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
+
+ foreach ( $cols as $col ) {
+ if ( 'ID' == $col ) {
+ $searches[] = $wpdb->prepare( "$col = %s", $string );
+ } else {
+ $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
+ }
+ }
+
+ return ' AND (' . implode(' OR ', $searches) . ')';
+ }
+
+ /**
+ * Return the list of users.
+ *
+ * @since 3.1.0
+ * @access public
+ *
+ * @return array Array of results.
+ */
+ public function get_results() {
+ return $this->results;
+ }
+
+ /**
+ * Return the total number of users for the current query.
+ *
+ * @since 3.1.0
+ * @access public
+ *
+ * @return array Array of total users.
+ */
+ public function get_total() {
+ return $this->total_users;
+ }
+
+ /**
+ * Make private properties readable for backwards compatibility.
+ *
+ * @since 4.0.0
+ * @access public
+ *
+ * @param string $name Property to get.
+ * @return mixed Property.
+ */
+ public function __get( $name ) {
+ return $this->$name;
+ }
+
+ /**
+ * Make private properties settable for backwards compatibility.
+ *
+ * @since 4.0.0
+ * @access public
+ *
+ * @param string $name Property to set.
+ * @param mixed $value Property value.
+ * @return mixed Newly-set property.
+ */
+ public function __set( $name, $value ) {
+ return $this->$name = $value;
+ }
+
+ /**
+ * Make private properties checkable for backwards compatibility.
+ *
+ * @since 4.0.0
+ * @access public
+ *
+ * @param string $name Property to check if set.
+ * @return bool Whether the property is set.
+ */
+ public function __isset( $name ) {
+ return isset( $this->$name );
+ }
+
+ /**
+ * Make private properties un-settable for backwards compatibility.
+ *
+ * @since 4.0.0
+ * @access public
+ *
+ * @param string $name Property to unset.
+ */
+ public function __unset( $name ) {
+ unset( $this->$name );
+ }
+
+ /**
+ * Make private/protected methods readable for backwards compatibility.
+ *
+ * @since 4.0.0
+ * @access public
+ *
+ * @param callable $name Method to call.
+ * @param array $arguments Arguments to pass when calling.
+ * @return mixed|bool Return value of the callback, false otherwise.
+ */
+ public function __call( $name, $arguments ) {
+ return call_user_func_array( array( $this, $name ), $arguments );
+ }
+}