hooks(); } return self::$instance; } private function __construct() { } /** * Registers all necessary hooks for the admin side of the module. */ public function hooks(): void { add_filter( 'display_post_states', [ $this, 'mark_auto_ads_post_states' ], 10, 2 ); add_action( 'before_delete_post', [ $this, 'handle_auto_ads_deletion' ] ); ( new AdSenseDeliveryController() )->hooks(); add_action( 'adpresso_register_assets', [ $this, 'register_delivery_reporter' ] ); add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_delivery_reporter' ] ); } /** * Registers the frontend reporter of the delivery counters. * * @param Assets $assets Asset catalogue. * * @return void */ public function register_delivery_reporter( Assets $assets ): void { $assets->register_script( 'adsense-delivery', 'modules/adsense/assets/js/delivery.js', [], true ); } /** * Every page reports whether AdSense delivered; views of users who manage AdPresso are not counted. * * @return void */ public function enqueue_delivery_reporter(): void { wp_enqueue_script( 'adpresso-adsense-delivery' ); wp_localize_script( 'adpresso-adsense-delivery', 'adpressoAdSenseDeliveryConfig', [ 'endpoint' => rest_url( 'adpresso/v1/adsense/delivery' ), 'delay' => 8000, 'skip' => current_user_can( adpresso_get_capability() ), ] ); } /** * Adds an 'AdSense Auto Ad' or 'AdSense Auto Placement' state to the post list table. * * @param array $states * @param WP_Post $post * * @return array */ public function mark_auto_ads_post_states( array $states, WP_Post $post ): array { $ad_id = (int) Settings::get_setting( 'auto_ads_ad_id', 0 ); $placement_id = (int) Settings::get_setting( 'auto_ads_placement_id', 0 ); if ( $post->ID === $ad_id ) { $states['adpresso_adsense_ad'] = __( 'AdSense Auto Ad', 'adpresso' ); } elseif ( $post->ID === $placement_id ) { $states['adpresso_adsense_placement'] = __( 'AdSense Auto Placement', 'adpresso' ); } return $states; } /** * Creates and publishes the necessary Ad and Placement for Auto Ads. * * @return void */ public function create_entities(): void { if ( ! check_ajax_referer( SettingsTab::CREATE_ENTITIES_AJAX_ACTION, '_ajax_nonce', false ) ) { wp_send_json_error( [ 'message' => __( 'Invalid nonce.', 'adpresso' ) ], 403 ); } // Capability check (Admin-only) if ( ! current_user_can( adpresso_get_capability( 'manage_settings' ) ) ) { wp_send_json_error( [ 'message' => __( 'Permission denied.', 'adpresso' ) ], 403 ); } $settings = (array) get_option( 'adpresso_settings_adsense', [] ); $publisher_id = (string) ( $settings['adsense_publisher_id'] ?? '' ); if ( '' === trim( $publisher_id ) ) { wp_send_json_error( [ 'message' => __( 'Please set your Publisher ID first.', 'adpresso' ) ], 403 ); return; } // Whatever part of the setup still exists is reused: only the missing one is created, and the ad gets the // current Publisher ID, so "Regenerate" also updates it after an ID change. $ad_id = self::existing_post( (int) ( $settings['auto_ads_ad_id'] ?? 0 ), Constants::POST_TYPE_AD ); $placement_id = self::existing_post( (int) ( $settings['auto_ads_placement_id'] ?? 0 ), Constants::POST_TYPE_PLACEMENT ); $updated = $ad_id > 0 && $placement_id > 0; if ( $ad_id ) { wp_update_post( [ 'ID' => $ad_id, 'post_content' => $this->get_auto_ads_script_content( $publisher_id ), 'post_status' => 'publish', ] ); } else { $ad_id = $this->create_auto_ads_ad( $publisher_id ); } if ( ! $ad_id ) { RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Failed to create Ad. Skipping creation.' ); wp_send_json_error( [ 'message' => __( 'Failed to create Ad. Skipping creation.', 'adpresso' ) ], 403 ); return; } if ( $placement_id ) { wp_update_post( [ 'ID' => $placement_id, 'post_status' => 'publish', ] ); } else { $placement_id = $this->create_auto_ads_placement(); } if ( ! $placement_id ) { RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Failed to create Placement. Skipping creation.' ); wp_send_json_error( [ 'message' => __( 'Failed to create Placement. Skipping creation.', 'adpresso' ) ], 403 ); return; } $this->assign_ad_to_placement( $placement_id, $ad_id ); RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Placement and Ad are ready.' ); $settings['auto_ads_placement_id'] = $placement_id; $settings['auto_ads_ad_id'] = $ad_id; $settings['adsense_enable_auto_ads'] = true; Settings::update_direct_option( self::OPTION_NAME, $settings ); wp_send_json_success( [ 'message' => $updated ? __( 'Ad and placement are updated.', 'adpresso' ) : __( 'Entities are created successfully!', 'adpresso' ), ] ); } /** * The ID if the post still exists (trashed counts, it is restored) and has the expected type, else 0. * * @param int $post_id Stored ID. * @param string $post_type Expected post type. * * @return int */ private static function existing_post( int $post_id, string $post_type ): int { return $post_id > 0 && get_post_type( $post_id ) === $post_type ? $post_id : 0; } /** * Whether the Auto Ads code is on the site: its ad and placement are published. * * @param array $settings AdSense settings. * * @return bool */ public static function auto_ads_running( array $settings ): bool { $ad_id = (int) ( $settings['auto_ads_ad_id'] ?? 0 ); $placement_id = (int) ( $settings['auto_ads_placement_id'] ?? 0 ); return $ad_id > 0 && 'publish' === get_post_status( $ad_id ) && $placement_id > 0 && 'publish' === get_post_status( $placement_id ); } /** * Published ads other than the Auto Ads one that carry AdSense code (a unit or the loader), newest first. * * The query only narrows down to ads mentioning "adsbygoogle"; contains_adsense_code() decides. * * @param array $settings AdSense settings. * @param int $limit Maximum number of IDs. * * @return int[] */ public static function adsense_ad_ids( array $settings, int $limit = 4 ): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- admin only. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_content FROM {$wpdb->posts} WHERE post_type = %s AND post_status = 'publish' AND post_content LIKE %s AND ID <> %d ORDER BY ID DESC LIMIT 200", Constants::POST_TYPE_AD, '%' . $wpdb->esc_like( 'adsbygoogle' ) . '%', (int) ( $settings['auto_ads_ad_id'] ?? 0 ) ) ); $ids = []; foreach ( (array) $rows as $row ) { if ( self::contains_adsense_code( (string) ( $row->post_content ?? '' ) ) ) { $ids[] = (int) $row->ID; } if ( count( $ids ) >= max( 1, $limit ) ) { break; } } return $ids; } /** * Whether the content delivers AdSense: Google's loader script or an unit with the adsbygoogle class. * The bare word, a comment or a lone push() call deliver nothing. * * @param string $content Ad content. * * @return bool */ public static function contains_adsense_code( string $content ): bool { $content = (string) preg_replace( '##s', '', $content ); return 1 === preg_match( '#]*\bsrc\s*=\s*["\']?[^"\'>\s]*googlesyndication\.com/pagead/js/adsbygoogle\.js#i', $content ) || 1 === preg_match( '#]*\bclass\s*=\s*["\'](?:[^"\']*\s)?adsbygoogle(?=[\s"\'])#i', $content ); } /** * "Embed Auto Ads code" publishes the Auto Ads ad and placement when switched on and drafts them when switched off. * * @param mixed $old_value Previous AdSense settings. * @param mixed $value New AdSense settings. * * @return void */ public static function sync_auto_ads_status( $old_value, $value ): void { $value = (array) $value; $on = ! empty( $value['adsense_enable_auto_ads'] ); if ( ! empty( ( (array) $old_value )['adsense_enable_auto_ads'] ) === $on ) { return; } $targets = [ (int) ( $value['auto_ads_ad_id'] ?? 0 ) => Constants::POST_TYPE_AD, (int) ( $value['auto_ads_placement_id'] ?? 0 ) => Constants::POST_TYPE_PLACEMENT, ]; foreach ( $targets as $post_id => $post_type ) { if ( ! self::existing_post( $post_id, $post_type ) ) { continue; } $status = get_post_status( $post_id ); if ( $on ? in_array( $status, [ 'draft', 'pending', 'private' ], true ) : 'publish' === $status ) { wp_update_post( [ 'ID' => $post_id, 'post_status' => $on ? 'publish' : 'draft', ] ); } } } /** * Create the ad for the Auto Ads script. * * @param string $publisher_id * * @return int */ private function create_auto_ads_ad( string $publisher_id ): int { $script_content = $this->get_auto_ads_script_content( $publisher_id ); $ad_id = wp_insert_post( [ 'post_type' => Constants::POST_TYPE_AD, 'post_title' => 'AdSense Auto Ads Script (Auto-Generated)', 'post_content' => $script_content, 'post_status' => 'publish', ] ); RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Ad ID: ' . $ad_id ); if ( is_wp_error( $ad_id ) ) { RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Ad creation failed.' ); return 0; } RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Ad created successfully.' ); update_post_meta( $ad_id, Constants::META_PREFIX . 'ad_type', 'html' ); return $ad_id; } /** * Creates a new header placement for the Auto Ads script. * * @return int */ private function create_auto_ads_placement(): int { $placement_id = wp_insert_post( [ 'post_type' => Constants::POST_TYPE_PLACEMENT, 'post_title' => 'AdSense Auto Ads Placement (Auto-Generated)', 'post_status' => 'publish', ] ); RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Placement ID: ' . $placement_id ); if ( is_wp_error( $placement_id ) ) { RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Placement creation failed.' ); return 0; } RuntimeDebugger::add_server_error_log_entry( 'Auto Ads: Placement created successfully.' ); update_post_meta( $placement_id, Constants::META_PREFIX . 'placement_type', HeaderPlacement::ID ); return $placement_id; } /** * Assign ad to placement. * * @param int $placement_id * @param int $ad_id * * @return void */ private function assign_ad_to_placement( int $placement_id, int $ad_id ): void { update_post_meta( $placement_id, Constants::META_PREFIX . 'placement_item_id', $ad_id ); } /** * Creates the Auto Ads script content based on the Publisher ID. * * @param string $publisher_id * * @return string */ private function get_auto_ads_script_content( string $publisher_id ): string { $normalized_id = $this->normalize_adsense_publisher_id( $publisher_id ); return sprintf( // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- don't allow any changes on Google AdSense code. '', esc_attr( $normalized_id ) ); } /** * Checks if a permanently deleted post is part of the Auto Ads setup, * clears the IDs, disables the feature and notifies the user. * * @param int $post_id The ID of the post being deleted. */ public static function handle_auto_ads_deletion( int $post_id ): void { $post_type = get_post_type( $post_id ); if ( ! in_array( $post_type, [ 'adpresso_ad', 'adpresso_placement' ], true ) ) { return; } $option_name = 'adpresso_settings_adsense'; $settings = get_option( $option_name, [] ); if ( empty( $settings ) || ! is_array( $settings ) ) { return; } $is_dirty = false; $deleted_type = ''; if ( isset( $settings['auto_ads_ad_id'] ) && (int) $settings['auto_ads_ad_id'] === $post_id ) { $settings['auto_ads_ad_id'] = 0; $deleted_type = __( 'Auto-Ad', 'adpresso' ); $is_dirty = true; } if ( isset( $settings['auto_ads_placement_id'] ) && (int) $settings['auto_ads_placement_id'] === $post_id ) { $settings['auto_ads_placement_id'] = 0; $deleted_type = __( 'Auto-Ad Placement', 'adpresso' ); $is_dirty = true; } if ( $is_dirty ) { $settings['adsense_enable_auto_ads'] = 0; update_option( $option_name, $settings ); NotificationManager::get()->register( 'adsense-autoad-deleted-' . $post_id, sprintf( /* translators: %s is the type of the deleted entity (Auto-Ad or Placement) */ __( 'Your AdSense %s was permanently deleted. The Auto-Ads feature has been automatically disabled to prevent errors.', 'adpresso' ), $deleted_type ), [ 'type' => 'warning', 'location' => 'wp_notice', 'dismissible' => true, 'context' => 'all', ] ); } } /** * Normalizes the AdSense Publisher ID to a standard format. * * @param string $id * * @return string */ private function normalize_adsense_publisher_id( string $id ): string { $id = strtolower( trim( $id ) ); // Removes common prefixes $id = preg_replace( '/^(ca-)?(pub-)?/', '', $id ); // Only digits are allowed $id = preg_replace( '/\D/', '', $id ); // Add the standard prefix if not present return 'ca-pub-' . $id; } }