get_var( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the table name comes from $wpdb->prefix and cannot come from a visitor, and `prepare` cannot bind a table name. $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE form_id = %d AND status = %s", $form_id, 'published' ) ); wp_cache_set( $key, $count, 'ranq_forms', MINUTE_IN_SECONDS ); return $count; } /** * The entries of one form. * * @param int $form_id The form id. * @param int $limit How many of them. * @param int $offset From which row. * * @return array */ public static function get_for_form( $form_id, $limit = 25, $offset = 0 ) { global $wpdb; $table = Ranq_Forms_Install::entries_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the table name comes from $wpdb->prefix and cannot come from a visitor, and `prepare` cannot bind a table name. $wpdb->prepare( "SELECT * FROM {$table} WHERE form_id = %d AND status = %s ORDER BY id DESC LIMIT %d OFFSET %d", absint( $form_id ), 'published', absint( $limit ), absint( $offset ) ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * The number of entries for every form at once. * * The entries screen needs a figure next to each form in the picker. Asking * form by form means one query per form, which on a site with a hundred forms * is a hundred queries for a number that fits in one. * * @return array The form id as the key, the number of entries as the value. */ public static function counts_by_form() { global $wpdb; $cached = wp_cache_get( 'ranq_forms_counts', 'ranq_forms' ); if ( is_array( $cached ) ) { return $cached; } $table = Ranq_Forms_Install::entries_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the table name comes from $wpdb->prefix and cannot come from a visitor, and `prepare` cannot bind a table name. $wpdb->prepare( "SELECT form_id, COUNT(*) AS broj FROM {$table} WHERE status = %s GROUP BY form_id", 'published' ), ARRAY_A ); $counts = array(); foreach ( is_array( $rows ) ? $rows : array() as $row ) { $counts[ (int) $row['form_id'] ] = (int) $row['broj']; } wp_cache_set( 'ranq_forms_counts', $counts, 'ranq_forms', MINUTE_IN_SECONDS ); return $counts; } /** * Clears the remembered count when a new entry arrives. * * @param int $entry_id The entry id. * @param int $form_id The form id. * * @return void */ public static function flush_count( $entry_id, $form_id ) { unset( $entry_id ); wp_cache_delete( 'ranq_forms_count_' . absint( $form_id ), 'ranq_forms' ); wp_cache_delete( 'ranq_forms_counts', 'ranq_forms' ); } }