isset( $c['daily'] ) && is_array( $c['daily'] ) ? $c['daily'] : array(), 'lifetime' => isset( $c['lifetime'] ) ? (float) $c['lifetime'] : 0.0, ); } public static function table() { global $wpdb; return $wpdb->prefix . 'aieo_social_boosts'; } public static function boost( array $args ) { $platform = sanitize_key( (string) ( $args['platform'] ?? '' ) ); $budget = round( (float) ( $args['budget'] ?? 0 ), 2 ); $wf_id = (int) ( $args['wf_id'] ?? 0 ); $proposal_id = (int) ( $args['proposal_id'] ?? 0 ); $story = (string) ( $args['object_story_id'] ?? '' ); $campaign = (string) ( $args['campaign_name'] ?? ( $wf_id > 0 ? 'wf_' . $wf_id : '' ) ); if ( self::killed() ) { return self::fail( 'kill_switch', 'The boost kill-switch is engaged.' ); } if ( ! self::enabled() ) { return self::fail( 'disabled', 'Paid boosting is off. Enable it in Social → Boost governance.' ); } if ( $proposal_id <= 0 ) { return self::fail( 'not_accepted', 'A boost must originate from an accepted proposal.' ); } if ( ! in_array( $platform, array( 'meta', 'google' ), true ) ) { return self::fail( 'bad_platform', 'Boost platform must be meta or google.' ); } if ( $budget <= 0 ) { return self::fail( 'bad_budget', 'Boost budget must be positive.' ); } $caps = self::caps(); if ( $caps['lifetime'] <= 0 ) { return self::fail( 'no_cap', 'Set a per-campaign lifetime budget cap before boosting.' ); } if ( $budget > $caps['lifetime'] ) { return self::fail( 'over_lifetime_cap', sprintf( 'Budget exceeds the per-campaign cap (%.2f).', $caps['lifetime'] ) ); } if ( 'meta' === $platform && '' === $story ) { return self::fail( 'no_story', 'Meta boost needs the organic post id (object_story_id).' ); } $idem = hash( 'sha256', $wf_id . '|' . $proposal_id . '|' . $platform . '|' . $story . '|' . gmdate( 'Ymd' ) ); $creds = class_exists( 'AIEO_DMM_Ad_Connectors' ) ? AIEO_DMM_Ad_Connectors::credentials( $platform ) : array(); if ( empty( $creds ) ) { return self::fail( 'no_ad_account', sprintf( 'No %s ad account is connected.', $platform ) ); } $sandbox = self::sandbox(); global $wpdb; $lock = AIEO_Lock_Name::for_shop( 'aieo_boost_' . $platform ); $got = (bool) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $lock ) ); $existing = self::find_by_idem( $idem ); if ( $existing ) { if ( $got ) { $wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } return array( 'ok' => true, 'status' => (string) $existing['status'], 'sandbox' => (bool) $existing['sandbox'], 'boost_id' => (int) $existing['id'] ); } $daily_cap = isset( $caps['daily'][ $platform ] ) ? (float) $caps['daily'][ $platform ] : 0.0; if ( $daily_cap > 0 && ( self::spent_today( $platform ) + $budget ) > $daily_cap ) { if ( $got ) { $wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } return self::fail( 'over_daily_cap', sprintf( 'Would exceed the %s daily cap (%.2f).', $platform, $daily_cap ) ); } $row_id = self::journal( array( 'wf_id' => $wf_id, 'proposal_id' => $proposal_id, 'platform' => $platform, 'object_story_id'=> $story, 'campaign_name' => $campaign, 'budget' => $budget, 'currency' => substr( (string) ( $args['currency'] ?? ( function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'EUR' ) ), 0, 3 ), 'idempotency_key'=> $idem, 'sandbox' => $sandbox ? 1 : 0, 'status' => $sandbox ? 'sandbox_ok' : 'pending', ) ); if ( $got ) { $wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } if ( ! $row_id ) { return self::fail( 'journal_failed', 'Could not record the boost.' ); } if ( $sandbox ) { return array( 'ok' => true, 'status' => 'sandbox_ok', 'sandbox' => true, 'boost_id' => $row_id ); } $res = ( 'meta' === $platform ) ? self::meta_boost( $creds, $story, $campaign, $budget, $idem, (array) $args ) : self::google_boost( $creds, $campaign, $budget, $idem, (array) $args ); if ( empty( $res['ok'] ) ) { self::update_row( $row_id, array( 'status' => 'failed', 'error' => (string) ( $res['error'] ?? 'mutate failed' ) ) ); return self::fail( 'mutate_failed', (string) ( $res['error'] ?? 'The ad platform rejected the mutate.' ), $row_id ); } self::update_row( $row_id, array( 'status' => 'live', 'external_campaign_id' => (string) ( $res['external_campaign_id'] ?? '' ) ) ); if ( class_exists( 'AIEO_DMM_Campaigns' ) && method_exists( 'AIEO_DMM_Campaigns', 'touch' ) ) { AIEO_DMM_Campaigns::touch( $campaign, 'paid_social' ); } return array( 'ok' => true, 'status' => 'live', 'sandbox' => false, 'boost_id' => $row_id ); } public static function kill_switch() { update_option( self::OPT_KILL, '1', false ); if ( ! self::sandbox() && class_exists( 'AIEO_DMM_Ad_Connectors' ) ) { global $wpdb; $t = self::table(); if ( self::table_exists( $t ) ) { $live = $wpdb->get_results( "SELECT id, platform, external_campaign_id FROM `{$t}` WHERE status = 'live' AND external_campaign_id <> ''", ARRAY_A ); foreach ( (array) $live as $b ) { $creds = AIEO_DMM_Ad_Connectors::credentials( (string) $b['platform'] ); if ( 'meta' === $b['platform'] ) { self::meta_pause( $creds, (string) $b['external_campaign_id'] ); } elseif ( 'google' === $b['platform'] ) { self::google_pause( $creds, (string) $b['external_campaign_id'] ); } self::update_row( (int) $b['id'], array( 'status' => 'killed' ) ); } } } return true; } private static function meta_boost( $creds, $story, $campaign, $budget, $idem, $args ) { $token = (string) ( $creds['access_token'] ?? '' ); $acct = 'act_' . ltrim( (string) ( $creds['ad_account_id'] ?? '' ), 'act_' ); if ( '' === $token || 'act_' === $acct ) { return array( 'ok' => false, 'error' => 'Meta ad account not fully configured.' ); } $v = 'v21.0'; $cents = (int) round( $budget * 100 ); $camp = self::meta_post( "https://graph.facebook.com/{$v}/{$acct}/campaigns", $token, array( 'name' => $campaign, 'objective' => 'OUTCOME_ENGAGEMENT', 'status' => 'PAUSED', 'special_ad_categories'=> '[]', ), $idem . '-c' ); if ( empty( $camp['id'] ) ) { return array( 'ok' => false, 'error' => self::meta_err( $camp, 'campaign create' ) ); } $adset = self::meta_post( "https://graph.facebook.com/{$v}/{$acct}/adsets", $token, array( 'name' => $campaign . ' — set', 'campaign_id' => (string) $camp['id'], 'lifetime_budget' => (string) $cents, 'billing_event' => 'IMPRESSIONS', 'optimization_goal' => 'POST_ENGAGEMENT', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP', 'start_time' => gmdate( 'c' ), 'end_time' => gmdate( 'c', time() + 30 * DAY_IN_SECONDS ), 'targeting' => wp_json_encode( array( 'geo_locations' => array( 'countries' => array( 'GR' ) ) ) ), 'status' => 'PAUSED', ), $idem . '-s' ); if ( empty( $adset['id'] ) ) { return array( 'ok' => false, 'error' => self::meta_err( $adset, 'adset create' ) ); } $ad = self::meta_post( "https://graph.facebook.com/{$v}/{$acct}/ads", $token, array( 'name' => $campaign . ' — ad', 'adset_id' => (string) $adset['id'], 'creative' => wp_json_encode( array( 'object_story_id' => $story ) ), 'status' => 'PAUSED', ), $idem . '-a' ); if ( empty( $ad['id'] ) ) { return array( 'ok' => false, 'error' => self::meta_err( $ad, 'ad create' ) ); } return array( 'ok' => true, 'external_campaign_id' => (string) $camp['id'] ); } private static function meta_post( $url, $token, array $body, $idem ) { $r = wp_remote_post( $url, array( 'timeout' => 30, 'headers' => array( 'Authorization' => 'Bearer ' . $token ), 'body' => array_merge( $body, array( 'idempotency_key' => $idem ) ), ) ); if ( is_wp_error( $r ) ) { return array( 'error' => array( 'message' => $r->get_error_message() ) ); } return (array) json_decode( wp_remote_retrieve_body( $r ), true ); } private static function meta_err( $resp, $stage ) { $msg = is_array( $resp ) && isset( $resp['error']['message'] ) ? (string) $resp['error']['message'] : 'unknown error'; return $stage . ': ' . $msg; } private static function meta_pause( $creds, $campaign_id ) { $token = (string) ( $creds['access_token'] ?? '' ); if ( '' === $token || '' === $campaign_id ) { return; } wp_remote_post( "https://graph.facebook.com/v21.0/{$campaign_id}", array( 'timeout' => 20, 'headers' => array( 'Authorization' => 'Bearer ' . $token ), 'body' => array( 'status' => 'PAUSED' ), ) ); } private static function google_boost( $creds, $campaign, $budget, $idem, $args ) { $cid = preg_replace( '/\D/', '', (string) ( $creds['customer_id'] ?? '' ) ); $dev = (string) ( $creds['developer_token'] ?? '' ); $gcid = (string) ( $args['google_campaign_id'] ?? '' ); if ( '' === $cid || '' === $dev || '' === $gcid ) { return array( 'ok' => false, 'error' => 'Google boost needs a connected account + a target campaign id.' ); } $token = self::google_token( $creds ); if ( '' === $token ) { return array( 'ok' => false, 'error' => 'Could not obtain a Google access token.' ); } $micros = (int) round( $budget * 1000000 ); $url = "https://googleads.googleapis.com/v17/customers/{$cid}/campaignBudgets:mutate"; $headers = array( 'Authorization' => 'Bearer ' . $token, 'developer-token' => $dev, 'Content-Type' => 'application/json', ); if ( ! empty( $creds['login_customer_id'] ) ) { $headers['login-customer-id'] = preg_replace( '/\D/', '', (string) $creds['login_customer_id'] ); } $r = wp_remote_post( $url, array( 'timeout' => 30, 'headers' => $headers, 'body' => wp_json_encode( array( 'operations' => array( array( 'update' => array( 'resourceName' => (string) $args['google_budget_resource'] ?? '', 'amountMicros' => (string) $micros ), 'updateMask' => 'amount_micros', ) ) ) ), ) ); if ( is_wp_error( $r ) ) { return array( 'ok' => false, 'error' => $r->get_error_message() ); } $code = (int) wp_remote_retrieve_response_code( $r ); if ( $code < 200 || $code >= 300 ) { $b = json_decode( wp_remote_retrieve_body( $r ), true ); return array( 'ok' => false, 'error' => 'Google Ads HTTP ' . $code . ': ' . ( is_array( $b ) && isset( $b['error']['message'] ) ? $b['error']['message'] : '' ) ); } return array( 'ok' => true, 'external_campaign_id' => $gcid ); } private static function google_token( $creds ) { $r = wp_remote_post( 'https://oauth2.googleapis.com/token', array( 'timeout' => 20, 'body' => array( 'client_id' => (string) ( $creds['client_id'] ?? '' ), 'client_secret' => (string) ( $creds['client_secret'] ?? '' ), 'refresh_token' => (string) ( $creds['refresh_token'] ?? '' ), 'grant_type' => 'refresh_token', ), ) ); if ( is_wp_error( $r ) ) { return ''; } $b = json_decode( wp_remote_retrieve_body( $r ), true ); return is_array( $b ) && ! empty( $b['access_token'] ) ? (string) $b['access_token'] : ''; } private static function google_pause( $creds, $campaign_id ) { $cid = preg_replace( '/\D/', '', (string) ( $creds['customer_id'] ?? '' ) ); $dev = (string) ( $creds['developer_token'] ?? '' ); if ( '' === $cid || '' === $dev || '' === $campaign_id ) { return; } $token = self::google_token( $creds ); if ( '' === $token ) { return; } $headers = array( 'Authorization' => 'Bearer ' . $token, 'developer-token' => $dev, 'Content-Type' => 'application/json', ); if ( ! empty( $creds['login_customer_id'] ) ) { $headers['login-customer-id'] = preg_replace( '/\D/', '', (string) $creds['login_customer_id'] ); } wp_remote_post( "https://googleads.googleapis.com/v17/customers/{$cid}/campaigns:mutate", array( 'timeout' => 20, 'headers' => $headers, 'body' => wp_json_encode( array( 'operations' => array( array( 'update' => array( 'resourceName' => "customers/{$cid}/campaigns/{$campaign_id}", 'status' => 'PAUSED' ), 'updateMask' => 'status', ) ) ) ), ) ); } private static function spent_today( $platform ) { global $wpdb; $t = self::table(); if ( ! self::table_exists( $t ) ) { return 0.0; } return (float) $wpdb->get_var( $wpdb->prepare( "SELECT COALESCE(SUM(budget),0) FROM `{$t}` WHERE platform = %s AND sandbox = 0 AND status IN ('live','pending') AND created_at >= %s", $platform, gmdate( 'Y-m-d 00:00:00' ) ) ); } private static function find_by_idem( $idem ) { global $wpdb; $t = self::table(); if ( ! self::table_exists( $t ) ) { return null; } return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$t}` WHERE idempotency_key = %s LIMIT 1", $idem ), ARRAY_A ); } private static function journal( array $row ) { global $wpdb; if ( ! self::ensure_table() ) { return 0; } $row['created_at'] = current_time( 'mysql', true ); $ok = $wpdb->insert( self::table(), $row ); return $ok ? (int) $wpdb->insert_id : 0; } private static function update_row( $id, array $fields ) { global $wpdb; if ( self::table_exists( self::table() ) ) { $wpdb->update( self::table(), $fields, array( 'id' => (int) $id ) ); } } private static function fail( $code, $message, $boost_id = 0 ) { $out = array( 'ok' => false, 'status' => $code, 'sandbox' => self::sandbox(), 'error' => $message ); if ( $boost_id ) { $out['boost_id'] = (int) $boost_id; } return $out; } private static function table_exists( $t ) { global $wpdb; return (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t; } public static function ensure_table() { global $wpdb; $t = self::table(); if ( self::table_exists( $t ) ) { return true; } $charset = function_exists( 'aieo_get_charset_collate' ) ? aieo_get_charset_collate() : $wpdb->get_charset_collate(); $def_cur = function_exists( 'get_woocommerce_currency' ) ? substr( (string) get_woocommerce_currency(), 0, 3 ) : 'EUR'; $def_cur = esc_sql( $def_cur ); $wpdb->query( "CREATE TABLE IF NOT EXISTS `{$t}` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT, `wf_id` bigint unsigned NOT NULL DEFAULT 0, `proposal_id` bigint unsigned NOT NULL DEFAULT 0, `platform` varchar(20) NOT NULL DEFAULT '', `object_story_id` varchar(191) NOT NULL DEFAULT '', `campaign_name` varchar(120) NOT NULL DEFAULT '', `budget` decimal(12,2) NOT NULL DEFAULT 0, `currency` varchar(3) NOT NULL DEFAULT '{$def_cur}', `external_campaign_id` varchar(191) NOT NULL DEFAULT '', `status` varchar(20) NOT NULL DEFAULT 'pending', `sandbox` tinyint(1) NOT NULL DEFAULT 1, `idempotency_key` varchar(64) NOT NULL DEFAULT '', `error` text, `created_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `idem` (`idempotency_key`), KEY `platform_day` (`platform`,`created_at`), KEY `wf` (`wf_id`) ) {$charset};" ); return self::table_exists( $t ); } }