placement_repo = adpresso_get_placement_repository(); } /** * Main method: Fetches all processed Placements and prepares the final output structure. * Structure (SSR or JS-Config) for all valid placements. * * @param int[]|null $ids_override Passed straight through to PlacementRepository::get_all() - see its docblock. * * @return array Array [placement_id => ['output_mode'=>..., 'content'=>..., 'config'=>...]] */ public function process_context( ?array $ids_override = null ): array { $output = []; $placements = $this->placement_repo->get_all( [ 'publish' ], true, false, $ids_override ); // The repository already bulk-primed the placement rows. // Do the same for the posts the loop is about to resolve on its own: assigned Ads/Groups, group child ads, and the image attachments behind image ads. $this->warm_assigned_item_caches( $placements ); foreach ( $placements as $placement ) { /** @var Placement $placement */ $placement_id = $placement->get_id(); // Only build the initial log payload when debugging is on. if ( RuntimeDebugger::is_active( 1 ) ) { RuntimeDebugger::add_log_entry( $placement_id, [ 'id' => $placement_id, 'data' => $placement, 'edit_url' => Util::get_entity_edit_url( 'placements', $placement_id, 'placements' ), 'name' => $placement->get_title(), 'type' => $placement->get_type() ?? 'unknown', 'hook_fired' => false, 'backend_checks' => [], 'output_mode' => 'not_processed', 'item' => null, 'skip_reason' => null, 'public_id' => $placement->get_public_id(), ] ); } if ( $placement->get_type() === 'post_lists' ) { $context = Plugin::get()->context; // Post-list placements only runs on archive/search/home pages. $is_feed = ! empty( $context['is_archive'] ) || ! empty( $context['is_search'] ) || ! empty( $context['is_home'] ); if ( ! $is_feed ) { $reason = __( 'Context Hard-Block: Post List placements only run on feed/archive pages.', 'adpresso' ); RuntimeDebugger::add_log_entry( $placement_id, [ 'id' => $placement_id, 'execution' => [ 'status' => 'skipped', 'skip_reason' => $reason, ], 'payload' => [ 'skip_reason' => $reason, ], ] ); continue; } } // Prepare output data for this placement. $placement_data = $this->_prepare_placement_output( $placement ); if ( $placement_data !== null ) { $output[ $placement_id ] = $placement_data; } } return $output; } /** * Bulk-primes the post + meta caches for everything the render loop resolves per placement. * The assigned Ad/Group, a Group's child ads, and image-ad attachments. * * @param Placement[] $placements */ private function warm_assigned_item_caches( array $placements ): void { $item_ids = []; foreach ( $placements as $placement ) { // A placement that already failed backend validation never resolves its item. if ( ! $placement->is_backend_valid ) { continue; } $item_id = (int) $placement->get_meta( 'placement_item_id', 0 ); if ( $item_id > 0 ) { $item_ids[] = $item_id; } } $item_ids = array_values( array_unique( $item_ids ) ); if ( empty( $item_ids ) ) { return; } _prime_post_caches( $item_ids, false, true ); // Group children - ads_with_weights is warm now for any group in $item_ids. $child_ids = []; foreach ( $item_ids as $item_id ) { if ( get_post_type( $item_id ) !== Constants::POST_TYPE_GROUP ) { continue; } $weights = get_post_meta( $item_id, Constants::META_PREFIX . 'ads_with_weights', true ); if ( is_array( $weights ) ) { foreach ( array_keys( $weights ) as $child_id ) { if ( (int) $child_id > 0 ) { $child_ids[] = (int) $child_id; } } } } $child_ids = array_values( array_unique( $child_ids ) ); if ( ! empty( $child_ids ) ) { _prime_post_caches( $child_ids, false, true ); } // Image attachments referenced by any ad we're about to render. $attachment_ids = []; foreach ( array_merge( $item_ids, $child_ids ) as $ad_id ) { if ( get_post_type( $ad_id ) !== Constants::POST_TYPE_AD ) { continue; } $image_id = (int) get_post_meta( $ad_id, Constants::META_PREFIX . 'image_id', true ); if ( $image_id > 0 ) { $attachment_ids[] = $image_id; } } $attachment_ids = array_values( array_unique( $attachment_ids ) ); if ( ! empty( $attachment_ids ) ) { _prime_post_caches( $attachment_ids, false, true ); } } /** * Prepares the final output structure for a SINGLE processed placement. * Checks validity from placement & item and decides about the output path SSR/JS. * * @param Placement $placement The already processed placement object. * * @return array|null Output data or null if there is nothing to output. */ private function _prepare_placement_output( Placement $placement ): ?array { $placement_id = $placement->get_id(); // Check, if the placement passed the backend checks. if ( ! $placement->is_backend_valid ) { $snapshot = RuntimeDebugger::build_snapshot( $placement ); $snapshot['execution']['status'] = 'skipped'; $snapshot['execution']['hook_fired'] = false; $snapshot['execution']['skip_reason'] = $placement->skip_reason; if ( $snapshot['payload'] ) { $snapshot['payload']['skip_reason'] = $placement->skip_reason; } RuntimeDebugger::add_log_entry( $placement_id, $snapshot ); RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Skipping - Placement itself is not backend valid. Reason: " . $placement->skip_reason ); return null; } // Fetch the assigned item (Ad or Group). $item = $placement->get_item(); if ( ! $item instanceof Ad && ! $item instanceof Group ) { return null; } if ( ! $item->can_be_displayed() ) { $item->is_backend_valid = false; if ( empty( $item->skip_reason ) ) { $item->skip_reason = __( 'Display limit reached or item invalid.', 'adpresso' ); } RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Item #{$item->get_id()} blocked by can_be_displayed(). Reason: {$item->skip_reason}" ); } $is_item_valid = ( $item->is_backend_valid ); $placement_needs_js = $placement->requires_frontend_logic; $item_needs_js = $is_item_valid && $item->requires_frontend_logic; $needs_js = $placement_needs_js || $item_needs_js; if ( ! $needs_js ) { $general_fallback = Util::get_effective_general_fallback_entity( $placement, ! $is_item_valid ); // SSR can't evaluate the fallback's browser-side conditions (device, schedule, ...). $needs_js = $general_fallback && $general_fallback->requires_frontend_logic; } $needs_js_before_filter = $needs_js; // Gather reasons, why an item is forced into the JS rendering path. $js_reasons = []; if ( RuntimeDebugger::is_active( 1 ) ) { $js_reasons = self::collect_js_reasons( $placement, $item, $is_item_valid ); RuntimeDebugger::set_current_placement( $placement_id ); } $needs_js = apply_filters( 'adpresso_requires_frontend_logic', $needs_js, $placement, $item ); if ( RuntimeDebugger::is_active( 1 ) ) { RuntimeDebugger::set_current_placement( null ); // Module reasons: from this filter, or noted earlier while the placement loaded (e.g. Lazy Loading). $js_reasons = array_values( array_unique( array_merge( $js_reasons, RuntimeDebugger::get_placement_js_reasons( $placement_id ) ) ) ); } RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Checking frontend logic needs: Placement needs JS? " . ( $placement_needs_js ? 'Yes' : 'No' ) . ' | Item needs JS? ' . ( $item_needs_js ? 'Yes' : 'No' ) ); if ( $needs_js !== $needs_js_before_filter ) { RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Filter 'adpresso_requires_frontend_logic' changed \$needs_js to: " . ( $needs_js ? 'true' : 'false' ) ); } else { RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Final \$needs_js = " . ( $needs_js ? 'true' : 'false' ) ); } // Prepares the final output structure. $dom_injected_types = [ 'content', 'post_lists' ]; $dom_injected_types = apply_filters( 'adpresso_dom_injectable_types', $dom_injected_types ); $output_data = [ 'output_mode' => null, 'content' => null, 'config' => null, 'injection_rules' => in_array( $placement->get_type(), $dom_injected_types, true ) ? $this->_get_injection_rules( $placement ) : null, ]; if ( $needs_js ) { $output_data['output_mode'] = 'js'; $config = self::build_js_config( $placement, $item, $is_item_valid, $output_data['injection_rules'] ); // Above-the-fold LCP image: preload from so the browser starts the download before the JS chain runs. if ( $config && $is_item_valid && $item instanceof Ad && ! empty( $config['item']['imageUrl'] ) && ! ConditionHelper::tree_contains_frontend_conditions( $placement->conditions_json ) && ! ConditionHelper::tree_contains_frontend_conditions( $item->conditions_json ) && apply_filters( 'adpresso_placement_prioritise_lcp', false, $placement, $item ) ) { PerformanceOptimizer::add_preload_url( $config['item']['imageUrl'] ); } if ( $config === null ) { $reason = $item->skip_reason ?: 'Item invalid and no fallback.'; $placement->skip_reason = $reason; $snapshot = RuntimeDebugger::build_snapshot( $placement, $item ); $snapshot['execution']['status'] = 'skipped'; $snapshot['execution']['hook_fired'] = false; $snapshot['execution']['skip_reason'] = $reason; if ( $snapshot['payload'] ) { $snapshot['payload']['skip_reason'] = $reason; } RuntimeDebugger::add_log_entry( $placement_id, $snapshot ); return null; } $output_data['config'] = $config; if ( empty( $output_data['config'] ) ) { RuntimeDebugger::add_server_error_log_entry( "AdPresso WARNING [P#{$placement_id}]: JS Config is empty after processing!" ); } if ( RuntimeDebugger::is_active( 1 ) ) { $snapshot = RuntimeDebugger::build_snapshot( $placement, $item ); $snapshot['execution']['status'] = 'success'; $snapshot['execution']['output_mode'] = 'js'; $snapshot['execution']['hook_fired'] = false; $snapshot['execution']['js_reasons'] = $js_reasons; RuntimeDebugger::add_log_entry( $placement_id, $snapshot ); } } else { // SSR path [ 'content' => $inner_ssr_content, 'entity' => $rendered_entity ] = self::render_ssr_with_fallback( $placement, $item, $is_item_valid ); if ( ! empty( $inner_ssr_content ) ) { $output_data['output_mode'] = 'ssr'; $output_data['content'] = $inner_ssr_content; // Lets a shortcode re-render it inline (see FrontendHooks::render_manual_placement()). $output_data['rendered_entity'] = $rendered_entity; if ( RuntimeDebugger::is_active( 1 ) ) { $snapshot = RuntimeDebugger::build_snapshot( $placement, $item ); $snapshot['execution']['status'] = 'success'; $snapshot['execution']['output_mode'] = 'ssr'; // Explizit SSR $snapshot['execution']['hook_fired'] = false; RuntimeDebugger::add_log_entry( $placement_id, $snapshot ); } } else { if ( RuntimeDebugger::is_active( 1 ) ) { // Prefer the item's own, more specific reason over the generic message. $reason = ( ! $is_item_valid && ! empty( $item->skip_reason ) ) ? $item->skip_reason : __( 'SSR rendering failed. Empty content.', 'adpresso' ); $placement->skip_reason = $reason; $snapshot = RuntimeDebugger::build_snapshot( $placement, $item ); $snapshot['execution']['status'] = 'skipped'; $snapshot['execution']['output_mode'] = 'ssr'; $snapshot['execution']['hook_fired'] = false; $snapshot['execution']['skip_reason'] = $reason; if ( $snapshot['payload'] ) { $snapshot['payload']['skip_reason'] = $reason; } RuntimeDebugger::add_log_entry( $placement_id, $snapshot ); } return null; } } $item->mark_as_rendered( $output_data['output_mode'] === 'js' ); return $output_data; } /** * Server-side output of a placement: its item, else the placement's general fallback, else the global one. * Shared by the pipeline and manual placements rendered without it (REST, AJAX). * * @param Placement $placement * @param mixed $item The assigned Ad/Group. * @param bool $is_item_valid Whether $item may be displayed. * * @return array{content: string, entity: ?Entity} The HTML and the entity that produced it. */ public static function render_ssr_with_fallback( Placement $placement, $item, bool $is_item_valid ): array { $placement_id = $placement->get_id(); $inner_ssr_content = ''; $render_context = [ 'placement_id' => $placement_id, 'placement' => $placement, 'is_raw_output' => $placement->outputs_raw_items(), 'is_inline_output' => $placement->is_inline_override, ]; $rendered_entity = $is_item_valid ? $item : null; if ( $is_item_valid ) { $inner_ssr_content = $item->render_ssr( $render_context ); } if ( empty( $inner_ssr_content ) ) { // An invalid placement fallback (expired, draft) falls through to the global one, as on the JS path. $fallback_entity = Util::get_placement_general_fallback_entity( $placement ); if ( ! $fallback_entity ) { $fallback_entity = Util::get_global_fallback_entity( 'general_fallback', $is_item_valid ? $item->get_id() : 0 ); // Its browser-side conditions can't be checked here; the JS path handles it via globalFallbacks. if ( $fallback_entity && $fallback_entity->requires_frontend_logic ) { RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Global fallback #{$fallback_entity->get_id()} needs frontend logic, not rendered via SSR." ); $fallback_entity = null; } } // render_ssr() only exists on Ad/Group, not the base Entity type if ( $fallback_entity instanceof Ad || $fallback_entity instanceof Group ) { RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Primary item produced no output. Attempting Fallback Ad #{$fallback_entity->get_id()}." ); // Marks the ads as a fallback (FrontendAttributes), so the SSR scan of tracking.js can count it. $inner_ssr_content = $fallback_entity->render_ssr( array_merge( $render_context, [ 'fallback' => 'general' ] ) ); if ( ! empty( $inner_ssr_content ) ) { $rendered_entity = $fallback_entity; RuntimeDebugger::update_log_entry( $placement_id, [ 'fallback_used' => true, 'fallback_id' => $fallback_entity->get_id(), ] ); } } } // The wrapper's label belongs to what was rendered, not to the primary a fallback replaced. $placement->label_item = '' !== $inner_ssr_content ? $rendered_entity : null; return [ 'content' => (string) $inner_ssr_content, 'entity' => $inner_ssr_content !== '' ? $rendered_entity : null, ]; } /** * List of reasons this specific placement ended up on the JS-rendering path. * * @param Placement $placement * @param Ad|Group $item * @param bool $is_item_valid * * @return string[] */ public static function collect_js_reasons( Placement $placement, $item, bool $is_item_valid ): array { $reasons = []; // Debug-only strings for the frontend admin bar - not translated on purpose. if ( ConditionHelper::tree_contains_frontend_conditions( $placement->conditions_json ) ) { $reasons[] = 'Placement has a frontend-only targeting condition (e.g. Device, Browser Language).'; } $placement_type_object = $placement->get_type_object(); if ( $placement_type_object && $placement_type_object->requires_js_rendering() ) { $reasons[] = sprintf( 'Placement type "%s" always renders via JS.', $placement_type_object->get_title() ); } if ( $is_item_valid ) { if ( ConditionHelper::tree_contains_frontend_conditions( $item->conditions_json ) ) { $reasons[] = 'The assigned Ad/Group has a frontend-only targeting condition (e.g. Device, Max Impressions).'; } $item_type_object = method_exists( $item, 'get_type_object' ) ? $item->get_type_object() : null; if ( $item_type_object && method_exists( $item_type_object, 'requires_js_rendering' ) && $item_type_object->requires_js_rendering() ) { $reasons[] = sprintf( 'Ad type "%s" always renders via JS.', $item_type_object->get_title() ); } if ( $item instanceof Ad && ScheduleValidator::get()->is_scheduling_enabled( $item ) ) { $reasons[] = 'Scheduling is enabled on this ad - the live show/hide decision has to happen in the visitor\'s own browser.'; } // A Group's reason for JS-rendering if ( $item instanceof Group ) { if ( (bool) $item->get_meta( 'refresh', false ) ) { $reasons[] = 'The assigned Group has "Refresh" enabled, which always needs JS.'; } foreach ( $item->get_valid_ads() as $child_ad ) { if ( ! $child_ad->requires_frontend_logic ) { continue; } foreach ( self::_collect_ad_js_reasons( $child_ad ) as $ad_reason ) { $reasons[] = sprintf( 'Ad #%1$d "%2$s": %3$s', $child_ad->get_id(), $child_ad->get_title(), $ad_reason ); } } } } return $reasons; } /** * A single ad's own reasons for needing JS. * * @param Ad $ad * * @return string[] */ private static function _collect_ad_js_reasons( Ad $ad ): array { $reasons = []; // Debug-only strings for the frontend admin bar - not translated on purpose. if ( ConditionHelper::tree_contains_frontend_conditions( $ad->conditions_json ) ) { $reasons[] = 'Has a frontend-only targeting condition (e.g. Device, Max Impressions).'; } $ad_type_object = $ad->get_type_object(); if ( $ad_type_object && $ad_type_object->requires_js_rendering() ) { $reasons[] = sprintf( 'Ad type "%s" always renders via JS.', $ad_type_object->get_title() ); } if ( ScheduleValidator::get()->is_scheduling_enabled( $ad ) ) { $reasons[] = 'Scheduling is enabled - the live show/hide decision has to happen in the visitor\'s own browser.'; } return $reasons; } /** * Fetches injection rules for a content placement. * * @param Placement $placement * * @return array|null */ private function _get_injection_rules( Placement $placement ): ?array { $type = $placement->get_type(); $rules = [ 'position_after' => max( 1, (int) $placement->get_meta( 'position_after', 1 ) ), 'placement_method' => $placement->get_meta( 'injection_method', 'after' ), 'from_bottom' => (bool) $placement->get_meta( 'from_bottom', 0 ), 'is_custom_position' => false, ]; if ( $type === 'post_lists' || $type === 'custom_position' ) { $rules['is_custom_position'] = true; // Build selector $element = $placement->get_meta( 'position_element', 'article' ); $rules['selector'] = ( $element === 'custom' ) ? $placement->get_meta( 'custom_selector', '' ) : $element; // Fallback, if empty. if ( empty( $rules['selector'] ) ) { $rules['selector'] = 'article'; } } else { $target_element = $placement->get_meta( 'position_element', 'p' ); if ( empty( $target_element ) ) { return null; } $rules['target_element'] = $target_element; } $repeat_mode = $placement->get_meta( 'repeat_mode', 'off' ); $repeat_config = [ 'repeat_mode' => $repeat_mode, 'offset' => $rules['position_after'] - 1, // -1, since arrays are 0-based. ]; if ( ! Util::is_pro_active() ) { $repeat_config['enabled'] = false; $repeat_config['limit'] = 1; } else { $repeat_config['enabled'] = $repeat_mode !== 'off'; if ( $repeat_config['enabled'] ) { $repeat_config['every'] = $placement->get_meta( 'repeat_every', 1 ); // If the limit is 0, we expect unlimited repetitions. $saved_limit = (int) $placement->get_meta( 'repeat_limit', 0 ); if ( $repeat_mode === 'auto' ) { // For auto density the limit will be ignored. $repeat_config['limit'] = 0; } else { $repeat_config['limit'] = $saved_limit > 0 ? $saved_limit + 1 : 0; } $repeat_config['min_words'] = $placement->get_meta( 'repeat_min_words', 0 ); $repeat_config['density'] = $placement->get_meta( 'repeat_density', 'mid' ); } } $rules['repeat_config'] = $repeat_config; return $rules; } /** * Tries to load the global fallback entity. * TODO: Need to rework this method. Call it 'get_entity_fallback_entity' or something. * * @param int $current_item_id The ID of the item that couldn't be loaded. * * @return Entity|null * */ private function get_global_fallback_entity( int $current_item_id ): ?Entity { $fallback_id = absint( Settings::get_setting( 'general_fallback', 0 ) ); if ( $fallback_id === 0 ) { return null; } if ( $fallback_id === $current_item_id ) { NotificationManager::get()->register( 'adpresso-fallback-misconfiguration', sprintf( /* translators: %s is the title of the ad or group */ __( 'The fallback item you registered for %s is the same as the item that could not be loaded.', 'adpresso' ), esc_html( get_the_title( $current_item_id ) ) ), [ 'location' => 'dashboard', 'context' => 'adpresso-conditional-root', ] ); return null; } $entity = Util::get_entity_from_post( $fallback_id ); if ( ! $entity || ! $entity->is_backend_valid ) { return null; } return $entity; } /** * The JS config of a placement in JS mode - the one place both the pipeline and manual placements build it. * Returns null when nothing could ever show: the item is invalid and there is no fallback. * * @param Placement $placement * @param Entity|null $item * @param bool $is_item_valid * @param array|null $injection_rules * * @return array|null */ public static function build_js_config( Placement $placement, ?Entity $item, bool $is_item_valid, ?array $injection_rules = null ): ?array { $placement_id = $placement->get_id(); $config = $placement->frontend_config_data; $config['item'] = $is_item_valid && $item ? array_merge( $item->frontend_config_data, $placement->frontend_config_data['item'] ?? [] ) : null; if ( $injection_rules !== null ) { $config['injection_rules'] = $injection_rules; } // Guard at the call site so print_r() only runs when verbose debugging is active. if ( RuntimeDebugger::is_active( 2 ) ) { /* phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r Error logging is intended for debugging.*/ RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: JS Path - Initial Config (Placement+Item): " . print_r( $config, true ) ); } // General fallback: primary item produced nothing. Privacy fallback: consent rejected (placement-controller.js). // Invalid item: only a shipped fallback keeps the placement alive, so the global one ships here too. $general_fallback = Util::get_effective_general_fallback_entity( $placement, ! $is_item_valid ); $privacy_fallback = Util::get_placement_privacy_fallback_entity( $placement ); if ( $general_fallback ) { $config['fallback_item'] = Util::get_fallback_frontend_config( $general_fallback, $placement, true ); RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Added JS Config for General Fallback Entity #{$general_fallback->get_id()}" ); } if ( $privacy_fallback ) { $config['privacy_fallback_item'] = Util::get_fallback_frontend_config( $privacy_fallback ); RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Added JS Config for Privacy Fallback Entity #{$privacy_fallback->get_id()}" ); } if ( ! $is_item_valid && empty( $config['fallback_item'] ) && empty( $config['privacy_fallback_item'] ) ) { return null; } // Add Condition-JSON, if placement or item contain Frontend-Conditions if ( ConditionHelper::tree_contains_frontend_conditions( $placement->conditions_json ) ) { $config['placement_conditions_json'] = $placement->get_frontend_conditions_json(); RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Added Placement Frontend Conditions JSON." ); } if ( $item && ConditionHelper::tree_contains_frontend_conditions( $item->conditions_json ) ) { $config['item_conditions_json'] = $item->get_frontend_conditions_json(); RuntimeDebugger::add_server_error_log_entry( "[P#{$placement_id}]: Added Item Frontend Conditions JSON." ); } /** * Filter to modify the JS configuration for placements. */ return apply_filters( 'adpresso_placement_js_config', $config, $placement, $item ); } }