Request-Cache for placement instances */ private static array $request_cache = []; /** * Fetches a Placement instance by ID. * Uses a request cache and triggers backend processing. * * @param int $id Post ID of the Placement to fetch. * * @return Placement|null The processed Placement instance, or null if not found. */ public function get( int $id, bool $process_data = true ): ?Placement { if ( array_key_exists( $id, self::$request_cache ) ) { return self::$request_cache[ $id ]; } $placement = PlacementFactory::make( $id ); if ( $placement instanceof Placement ) { if ( $process_data ) { $placement->processBackendData(); self::$request_cache[ $id ] = $placement; } return $placement; } else { if ( $process_data ) { self::$request_cache[ $id ] = null; } return null; } } /** * Empties the request cache. */ public static function clear_request_cache(): void { self::$request_cache = []; } /** * Get all Placements. * * @param string[] $post_status * @param bool $process_data * @param bool $only_ids * @param int[]|null $ids_override Skips the ID query entirely and uses this list instead. * * @return array Array of processed Placement objects. */ public function get_all( array $post_status = [ 'any' ], 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_PLACEMENT, '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; } // Bulk-load the post + meta rows for every placement in two IN() queries instead. _prime_post_caches( $posts, false, true ); $placements = []; foreach ( $posts as $post_id ) { $placements[] = $this->get( $post_id, $process_data ); } // Removes null values from the array. return array_filter( $placements ); } /** * Count placements for multiple placement types in one query. * * @param array $types Placement type IDs. * @param string|string[] $status One status or several. * * @return array Map: placement_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 . 'placement_type', Constants::POST_TYPE_PLACEMENT ], $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; } /** * Prepares the data for Placements for the select field in the Used In filter. * * @return array */ public function get_placements_for_select(): array { $placements = $this->get_all( [ 'any' ], false ); $options = []; foreach ( $placements as $placement ) { if ( $placement instanceof Placement ) { /* translators: %d is the ad id */ $options[] = [ 'value' => 'placement_' . $placement->get_id(), 'label' => $placement->get_title() ?: sprintf( __( 'Placement #%d', 'adpresso' ), $placement->get_id() ), ]; } } return $options; } /** * Returns a basic array with ID, name and type of all placements. * * @return array */ public function get_all_basic(): array { $placements = get_posts( [ 'post_type' => Constants::POST_TYPE_PLACEMENT, 'post_status' => 'publish', 'numberposts' => -1, 'fields' => 'ids', ] ); if ( empty( $placements ) ) { return []; } $info = []; foreach ( $placements as $id ) { $post = get_post( $id ); if ( $post ) { $info[] = [ 'id' => $id, 'name' => $post->post_title ?: __( '(No Title)', 'adpresso' ), 'type' => get_post_meta( $id, Constants::META_PREFIX . 'placement_type', true ) ?: 'unknown', ]; } } return $info; } /** * Get all placements by type. * * @param string|string[] $types One or multiple placement types to filter by. * @param bool $process_data Whether to run full backend processing (conditions, scheduling, ...) on each match. * * @return Placement[] Array of Placement objects that match the specified types. */ public function get_by_type( string|array $types, bool $process_data = true ): array { $query = new WP_Query( [ 'post_type' => Constants::POST_TYPE_PLACEMENT, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'cache_results' => false, 'meta_query' => [ [ 'key' => Constants::META_PREFIX . 'placement_type', 'value' => $types, 'compare' => 'IN', ], ], ] ); if ( empty( $query->posts ) ) { return []; } $placements = array_map( fn( $id ) => $this->get( $id, $process_data ), $query->posts ); return array_filter( $placements ); } /** * Find all placements that are using a specific ad. * * @param int $item_id * @param string $type * @param array $post_status * @param bool $process_data * @param bool $only_ids * * @return array */ public function get_by_using_item( int $item_id, string $type = 'ad', array $post_status = [ 'any' ], bool $process_data = true, bool $only_ids = false ): array { $query = new WP_Query( [ 'post_type' => 'adpresso_placement', 'post_status' => $post_status, 'posts_per_page' => -1, 'no_found_rows' => true, 'cache_results' => false, 'meta_query' => [ [ 'key' => 'adpresso_placement_item_id', 'value' => (string) $item_id, ], ], 'fields' => 'ids', ] ); $placement_ids = $query->posts; if ( empty( $placement_ids ) ) { return []; } if ( $only_ids ) { return $placement_ids; } $placements = []; foreach ( $placement_ids as $post_id ) { $placements[] = $this->get( $post_id, $process_data ); } // Removes null values from the array. return array_filter( $placements ); } /** * Bulk version of get_by_using_item() - one query for every item ID's placements instead of one query per item. * * @param int[] $item_ids The item (ad) IDs to look up. * @param string $type Unused - kept for parity with get_by_using_item(). * @param array $post_status Placement post statuses to include. * * @return array Item ID => the Placements that reference it. */ public function get_used_in_map( array $item_ids, string $type = 'ad', array $post_status = [ 'any' ] ): array { $item_ids = array_values( array_unique( array_filter( $item_ids ) ) ); if ( empty( $item_ids ) ) { return []; } $query = new WP_Query( [ 'post_type' => Constants::POST_TYPE_PLACEMENT, 'post_status' => $post_status, 'posts_per_page' => -1, 'no_found_rows' => true, 'cache_results' => false, 'fields' => 'ids', 'meta_query' => [ [ 'key' => Constants::META_PREFIX . 'placement_item_id', 'value' => array_map( 'strval', $item_ids ), 'compare' => 'IN', ], ], ] ); $placement_ids = $query->posts; if ( empty( $placement_ids ) ) { return []; } _prime_post_caches( $placement_ids, false, true ); $wanted = array_flip( $item_ids ); $map = []; foreach ( $placement_ids as $post_id ) { $placement = $this->get( $post_id, false ); if ( ! $placement ) { continue; } $item_id = absint( $placement->get_meta( 'placement_item_id', 0 ) ); if ( isset( $wanted[ $item_id ] ) ) { $map[ $item_id ][] = $placement; } } return $map; } /** * Saves or updates a Placement entity. * This method handles core post data and delegates metadata saving * to the Metabox_Placement orchestrator for consistency and reuse. * * @param Placement $placement The Placement entity object. * @param array $data The raw, validated data from the REST request. * * @return Placement|null The saved and re-fetched Placement object, or null on failure. */ public function save( Placement $placement, array $data ): ?Placement { // REST params arrive unslashed; ParamsHandler and the boxes expect slashed input like $_POST. $params = new ParamsHandler( wp_slash( $data ) ); $placement_id = $placement->get_id(); $post_args = [ 'post_type' => Constants::POST_TYPE_PLACEMENT, 'post_status' => $params->getKey( 'status', 'draft' ), 'post_title' => $params->getString( 'title' ), ]; if ( is_int( $placement_id ) && $placement_id > 0 ) { $post_args['ID'] = $placement_id; } // Insert or Update the Post, but Placements do not have post_content. $post_id = wp_insert_post( wp_slash( $post_args ), true ); if ( is_wp_error( $post_id ) ) { RuntimeDebugger::add_server_error_log_entry( 'PlacementRepository Save Error: ' . $post_id->get_error_message() ); return null; } // Delegate metadata Saving to the Orchestrator. Deliberately NOT sanitize_text_field() - that would blanket-strip every string value // in meta_data, including HTML/scripts in fields like custom_placement_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 Placement_Metaboxes_Orchestrator(); $metabox_orchestrator->process_save( $post_id, wp_slash( $meta_data ) ); } // Clear Caches and Return the fresh, fully processed object. $this->clear_request_cache_for( $post_id ); return $this->get( $post_id ); } /** * Assign a specific item (ad or group) to a placement. * * This method operates atomically. Either the meta field was successful or it tries to revert the old state. * * @param int $placement_id The ID of the placement to be updated. * @param int $item_id The ID of the item that should be assigned (Ad or Group). * * @return bool */ public function assign_item_to_placement( int $placement_id, int $item_id ): bool { if ( $placement_id <= 0 || $item_id <= 0 ) { return false; } $meta_key_id = Constants::META_PREFIX . 'placement_item_id'; $old_id = get_post_meta( $placement_id, $meta_key_id, true ); update_post_meta( $placement_id, $meta_key_id, $item_id ); // Since update_post_meta delivers false for not changed values, we need to verify that the update has worked. $new_id_in_db = get_post_meta( $placement_id, $meta_key_id, true ); if ( (int) $new_id_in_db !== $item_id ) { update_post_meta( $placement_id, $meta_key_id, $old_id ); return false; } $this->clear_request_cache_for( $placement_id ); return true; } /** * Removes the assignment of an item to a placement. * * Deletes the meta fields for the placement_item_id. * * @param int $placement_id The id of the placement that assigned item should be removed. * * @return bool True when success, false when invalid ID. */ public function unassign_item_from_placement( int $placement_id ): bool { if ( $placement_id <= 0 ) { return false; } $meta_key_id = Constants::META_PREFIX . 'placement_item_id'; $result_id = delete_post_meta( $placement_id, $meta_key_id ); if ( $result_id ) { $this->clear_request_cache_for( $placement_id ); } return $result_id; } /** * Deletes a Placement entity from the database. * * @param Placement $placement The Placement 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( Placement $placement, bool $force = false ): bool { $post_id = $placement->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 the post was successfully deleted, clear it from our request cache. 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 */ public function clear_request_cache_for( int $post_id ): void { unset( self::$request_cache[ $post_id ] ); } }