Request-Cache for Group-instances. */ private static array $request_cache = []; private ?array $ads_for_select = null; /** * Gets an ad by its ID. * Everytime an ad is requested, it is processed and stored in the request cache. * * @param int $id * @param bool $process_data * * @return Ad|null */ public function get( int $id, bool $process_data = true ): ?Ad { if ( array_key_exists( $id, self::$request_cache ) ) { return self::$request_cache[ $id ]; } $ad = AdFactory::make( $id ); if ( $ad instanceof Ad ) { if ( $process_data ) { $ad->processBackendData(); self::$request_cache[ $id ] = $ad; } return $ad; } else { if ( $process_data ) { self::$request_cache[ $id ] = null; } return null; } } /** * Get all published ads. If ad is not cached yet, it will be processed and cached. * * @param string[] $post_status * @param bool $process_data * @param bool $only_ids * @param int[]|null $ids_override Fetch exactly these IDs instead of querying by * $post_status - used by the clipboard exporter * to scope a selection instead of "all ads". * * @return Ad[] */ public function get_all( array $post_status = [ 'publish', 'draft' ], bool $process_data = true, bool $only_ids = false, ?array $ids_override = null ): array { if ( $process_data && $only_ids ) { $process_data = false; } $posts = $ids_override ?? get_posts( [ 'post_type' => Constants::POST_TYPE_AD, 'post_status' => $post_status, 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'cache_results' => false, ] ); if ( empty( $posts ) ) { return []; } if ( $only_ids ) { return $posts; } // Two IN() queries for all post + meta rows. _prime_post_caches( $posts, false, true ); $ads = []; foreach ( $posts as $post_id ) { $ads[] = $this->get( $post_id, $process_data ); } return array_filter( $ads ); } /** * Prepares the data for Ads, Groups, and Manual Placements for the select field in the block editor and placement item select. * * @return array */ public function get_ads_for_select(): array { if ( null !== $this->ads_for_select ) { return $this->ads_for_select; } $ads = $this->get_all( [ 'publish', 'draft' ], false ); $options = []; foreach ( $ads as $ad ) { if ( $ad instanceof Ad ) { /* translators: %d is the ad id */ $options[] = [ 'value' => $ad->get_id(), 'label' => $ad->get_title() ?: sprintf( __( 'Ad #%d', 'adpresso' ), $ad->get_id() ) ]; } } $this->ads_for_select = $options; return $options; } /** * Get all ads by type. If an ad is not cached yet, it will be processed and cached. * * @param string|string[] $types * * @return Ad[] */ public function get_by_type( string|array $types ): array { $query = new WP_Query( [ 'post_type' => Constants::POST_TYPE_AD, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_query' => [ [ 'key' => Constants::META_PREFIX . 'ad_type', 'value' => (array) $types, 'compare' => 'IN', ], ], ] ); if ( empty( $query->posts ) ) { return []; } $ads = array_map( [ $this, 'get' ], $query->posts ); return array_filter( $ads ); } /** * Count ads for multiple ad_types in one query. * * @param array $types Ad type IDs. * @param string|string[] $status One status or several. * * @return array Map: ad_type => count */ public function counts_by_type( array $types, string|array $status = 'publish' ): array { global $wpdb; $types = array_values( array_unique( array_map( 'strval', array_filter( $types, 'strlen' ) ) ) ); if ( empty( $types ) ) { return []; } $statuses = array_values( array_map( 'strval', (array) $status ) ); $placeholders = implode( ',', array_fill( 0, count( $types ), '%s' ) ); $status_placeholders = implode( ',', array_fill( 0, count( $statuses ), '%s' ) ); $params = array_merge( [ Constants::META_PREFIX . 'ad_type', Constants::POST_TYPE_AD ], $statuses, $types ); // Sniff can't count placeholders passed via ...$params (2 fixed + one %s per status + one per type); both lists are only literal "%s,%s,...". // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $sql = $wpdb->prepare( " SELECT pm.meta_value AS type, COUNT(DISTINCT p.ID) AS cnt FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key = %s WHERE p.post_type = %s AND p.post_status IN ($status_placeholders) AND pm.meta_value IN ($placeholders) GROUP BY pm.meta_value ", ...$params ); // phpcs:enable // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query prepared above using dynamic placeholders. $rows = $wpdb->get_results( $sql, ARRAY_A ); $out = array_fill_keys( $types, 0 ); foreach ( $rows as $r ) { $out[ (string) $r['type'] ] = (int) $r['cnt']; } return $out; } /** * Saves or updates an Ad entity. * This method orchestrates the save process by handling core post data * and delegating metadata saving to the Metabox_Ad orchestrator. * * @param Ad $ad The Ad entity object. * @param array $data The raw, validated data from the REST request. * * @return Ad|null The saved and re-fetched Ad object, or null on failure. */ public function save( Ad $ad, array $data ): ?Ad { // REST params arrive unslashed; ParamsHandler and the boxes expect slashed input like $_POST. $params = new ParamsHandler( wp_slash( $data ) ); $ad_id = $ad->get_id(); // Detect a change und unmark it. $previous_image_id = ( is_int( $ad_id ) && $ad_id > 0 ) ? (int) get_post_meta( $ad_id, Constants::META_PREFIX . 'image_id', true ) : 0; $post_args = [ 'post_type' => Constants::POST_TYPE_AD, 'post_status' => $params->getKey( 'status', 'draft' ), 'post_title' => $params->getString( 'title' ), ]; if ( is_int( $ad_id ) && $ad_id > 0 ) { $post_args['ID'] = $ad_id; } if ( isset( $data['content'] ) ) { $raw_content = $data['content']; if ( Util::can_user_unfiltered_html() ) { $post_args['post_content'] = $raw_content; } else { $post_args['post_content'] = wp_kses_post( $raw_content ); } } $post_id = wp_insert_post( wp_slash( $post_args ), true ); if ( is_wp_error( $post_id ) ) { RuntimeDebugger::add_server_error_log_entry( 'AdRepository Save Error: ' . $post_id->get_error_message() ); return null; } // Deliberately NOT sanitize_text_field() (getArray()'s own default) - that would blanket-strip every string value in meta_data, including // HTML/scripts in fields like custom_ad_code that are SUPPOSED to preserve them for trusted users. $meta_data = $params->getArray( 'meta_data', fn( $value ) => $value ); if ( ! empty( $meta_data ) ) { $metabox_orchestrator = new Ad_Metaboxes_Orchestrator(); $metabox_orchestrator->process_save( $post_id, wp_slash( $meta_data ) ); } /** * Fires once an ad's post AND its meta_data are both fully persisted for this save * * @param int $post_id The ad's post ID. * @param int $previous_image_id The ad's image_id meta value before this save (0 if none/new ad). */ do_action( 'adpresso_ad_saved', $post_id, $previous_image_id ); $this->clear_request_cache_for( $post_id ); adpresso_get_placement_repository()->clear_request_cache(); adpresso_get_group_repository()->clear_request_cache(); return $this->get( $post_id ); } /** * Deletes an Ad entity from the database. * * @param Ad $ad The Ad entity object to delete. * @param bool $force Whether to bypass the trash and delete permanently. * * @return bool True on success, false on failure. */ public function delete( Ad $ad, bool $force = false ): bool { $post_id = $ad->get_id(); if ( $post_id <= 0 ) { return false; } // wp_delete_post() only auto-routes to wp_trash_post() for the core 'post'/'page' types $result = $force ? wp_delete_post( $post_id, true ) : wp_trash_post( $post_id ); if ( $result !== false && $result !== null ) { $this->clear_request_cache_for( $post_id ); return true; } return false; } /** * Helper to clear the internal request cache for a specific ID. * * @param int $post_id * * @return void */ public function clear_request_cache_for( int $post_id ): void { unset( self::$request_cache[ $post_id ] ); } }