namespace, '/admin/stats', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'permission_manage' ), ), ) ); } /** * Returns totals, cached for ten minutes. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function get_items( $request ) { unset( $request ); $stats = get_transient( self::CACHE_KEY ); if ( ! is_array( $stats ) ) { $stats = array( 'members' => self::count_members(), 'spaces' => self::count_spaces(), 'posts' => self::count( 'posts', 'status', 'published' ), 'comments' => self::count( 'comments', 'status', 'published' ), 'reports' => \SpaceBay\Moderation\Reports::open_count(), 'pending' => count( \SpaceBay\Members\Profiles::ids_with_status( 'pending' ) ), ); set_transient( self::CACHE_KEY, $stats, 10 * MINUTE_IN_SECONDS ); } return rest_ensure_response( $stats ); } /** * Counts rows in a SpaceBay table with a given status. * * @param string $short_name Short table name. * @param string $column Status column name, from a fixed list. * @param string $value Status value. * @return int */ private static function count( $short_name, $column, $value ) { global $wpdb; $table = Tables::name( $short_name ); if ( '' === $table || 'status' !== $column ) { return 0; } return (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table; result cached in a transient by the caller. $wpdb->prepare( 'SELECT COUNT(id) FROM %i WHERE status = %s', $table, $value ) ); } /** * Counts published spaces, not space groups. * * @return int */ private static function count_spaces() { global $wpdb; return (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table; result cached in a transient by the caller. $wpdb->prepare( 'SELECT COUNT(id) FROM %i WHERE type = %s AND status = %s', Tables::name( 'spaces' ), 'space', 'published' ) ); } /** * Counts registered members of the site. * * @return int */ private static function count_members() { $counts = count_users(); return isset( $counts['total_users'] ) ? (int) $counts['total_users'] : 0; } }