prefix . 'aieo_gsc_daily'; } public static function table_exists() { global $wpdb; $t = self::table(); return (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t; } public static function ensure_schema() { if ( self::table_exists() ) { return; } $schema = AIEO_DIR . 'includes/dmm/sql/gsc-history-schema.php'; if ( file_exists( $schema ) ) { require_once $schema; if ( function_exists( 'aieo_gsc_history_install_schema' ) ) { aieo_gsc_history_install_schema(); } } } public static function retention_days() { return max( 90, (int) apply_filters( 'aieo_gsc_history_retention_days', 400 ) ); } public static function maybe_sync( $force = false ) { if ( ! AIEO_GSC::is_connected() || '' === (string) AIEO_GSC::property() ) { return 'not_connected'; } if ( false !== get_transient( self::SYNC_LOCK ) ) { return 'running'; } $wait = $force ? '' : self::throttle_reason(); if ( '' !== $wait ) { return $wait; } set_transient( self::SYNC_LOCK, time(), self::SYNC_LOCK_TTL ); $end = gmdate( 'Y-m-d', time() - 2 * DAY_IN_SECONDS ); $start = gmdate( 'Y-m-d', strtotime( $end ) - ( self::REFRESH_DAYS - 1 ) * DAY_IN_SECONDS ); $res = self::sync( $start, $end ); self::record_outcome( $res, true ); $res['pruned'] = self::prune(); return $res; } public static function queue_sync( $force = false ) { if ( ! AIEO_GSC::is_connected() || '' === (string) AIEO_GSC::property() ) { return 'not_connected'; } if ( false !== get_transient( self::SYNC_LOCK ) ) { return 'running'; } $has_as = function_exists( 'as_enqueue_async_action' ) && function_exists( 'as_has_scheduled_action' ); if ( self::sync_waiting() ) { return 'queued'; } $wait = $force ? '' : self::throttle_reason(); if ( '' !== $wait ) { return $wait; } $args = array( (bool) $force ); if ( $has_as ) { return as_enqueue_async_action( self::SYNC_HOOK, $args, self::AS_GROUP ) ? 'queued' : 'not_queued'; } return true === wp_schedule_single_event( time(), self::SYNC_HOOK, $args ) ? 'queued' : 'not_queued'; } public static function sync_state() { if ( false !== get_transient( self::SYNC_LOCK ) ) { return 'running'; } return self::sync_waiting() ? 'queued' : ''; } private static function sync_waiting() { if ( function_exists( 'as_enqueue_async_action' ) && function_exists( 'as_has_scheduled_action' ) ) { return (bool) as_has_scheduled_action( self::SYNC_HOOK, null, self::AS_GROUP ); } return false !== wp_next_scheduled( self::SYNC_HOOK, array( false ) ) || false !== wp_next_scheduled( self::SYNC_HOOK, array( true ) ); } public static function run_queued_sync( $force = false ) { if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 300 ); } self::maybe_sync( (bool) $force ); } private static function throttle_reason() { $last = (int) get_option( self::LAST_SYNC_OPT, 0 ); if ( $last && ( time() - $last ) < self::MIN_INTERVAL ) { return 'throttled'; } $err = AIEO_GSC::last_error(); if ( $err && ( time() - $err['at'] ) < self::RETRY_INTERVAL ) { return 'backoff'; } return ''; } public static function sync( $start, $end ) { self::ensure_schema(); $out = array( 'written' => 0, 'rows' => 0, 'errors' => array(), 'calls_ok' => 0 ); if ( ! self::table_exists() ) { $out['errors'][] = 'table_missing'; $out['last_error'] = array( 'code' => 'table_missing', 'message' => __( 'The Search Console history table is missing.', 'ai-eshop-optimizer' ), ); return $out; } foreach ( self::DIMENSIONS as $dim ) { $row_start = 0; for ( $page = 0; $page < self::MAX_PAGES; $page++ ) { $resp = AIEO_GSC::query( array( 'start_date' => $start, 'end_date' => $end, 'dimensions' => array( 'date', $dim ), 'row_limit' => self::PAGE_SIZE, 'start_row' => $row_start, ) ); if ( is_wp_error( $resp ) ) { $out['errors'][] = $dim . ': ' . $resp->get_error_message(); $out['last_error'] = array( 'code' => AIEO_GSC::error_reason( $resp ), 'message' => $resp->get_error_message(), ); if ( AIEO_GSC::needs_reconnect( $resp ) || in_array( $resp->get_error_code(), array( 'aieo_gsc_disconnected', 'aieo_gsc_noprop' ), true ) ) { break 2; } break; } $out['calls_ok']++; $rows = isset( $resp['rows'] ) ? (array) $resp['rows'] : array(); if ( empty( $rows ) ) { break; } $out['rows'] += count( $rows ); $out['written'] += self::store( $dim, $rows ); if ( count( $rows ) < self::PAGE_SIZE ) { break; } $row_start += self::PAGE_SIZE; } } return $out; } private static function record_outcome( array $res, $stamp ) { $failed = ! empty( $res['errors'] ); if ( $stamp && ( ! $failed || ! empty( $res['calls_ok'] ) ) ) { update_option( self::LAST_SYNC_OPT, time(), false ); } if ( ! $failed ) { AIEO_GSC::clear_error(); } elseif ( ! empty( $res['last_error']['message'] ) ) { AIEO_GSC::record_error( $res['last_error']['code'], $res['last_error']['message'] ); } if ( $stamp ) { delete_transient( self::SYNC_LOCK ); } } public static function backfill( $months = self::BACKFILL_MONTHS ) { if ( ! AIEO_GSC::is_connected() || '' === (string) AIEO_GSC::property() ) { return 'not_connected'; } if ( self::backfill_pending() > 0 ) { return 'already_queued'; } $to = gmdate( 'Y-m-d', time() - 2 * DAY_IN_SECONDS ); $from = gmdate( 'Y-m-d', strtotime( gmdate( 'Y-m-01', strtotime( $to ) ) . ' -' . max( 1, (int) $months ) . ' months' ) ); $floor = gmdate( 'Y-m-d', time() - self::retention_days() * DAY_IN_SECONDS ); if ( $from < $floor ) { $from = $floor; } $chunks = self::month_chunks( $from, $to ); if ( empty( $chunks ) ) { return 0; } if ( function_exists( 'as_enqueue_async_action' ) && function_exists( 'as_has_scheduled_action' ) ) { $queued = 0; foreach ( $chunks as $chunk ) { if ( ! as_has_scheduled_action( self::BACKFILL_HOOK, $chunk, self::AS_GROUP ) && as_enqueue_async_action( self::BACKFILL_HOOK, $chunk, self::AS_GROUP ) ) { $queued++; } } return $queued; } $booked = wp_schedule_single_event( time(), self::BACKFILL_HOOK, array( $chunks[0][0], $chunks[0][1], $from ) ); return true === $booked ? count( $chunks ) : 0; } public static function maybe_backfill() { $cov = self::coverage(); if ( (int) $cov['days'] >= self::THIN_DAYS ) { return 'covered'; } return self::backfill(); } public static function run_backfill_month( $start, $end, $chain_from = '' ) { $start = (string) $start; $end = (string) $end; $chain_from = (string) $chain_from; $ymd = '/^\d{4}-\d{2}-\d{2}$/'; if ( ! preg_match( $ymd, $start ) || ! preg_match( $ymd, $end ) ) { return; } if ( ! AIEO_GSC::is_connected() || '' === (string) AIEO_GSC::property() ) { return; } if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 300 ); } $res = self::sync( $start, $end ); self::record_outcome( $res, false ); if ( ! empty( $res['last_error']['code'] ) && AIEO_GSC::needs_reconnect( $res['last_error']['code'] ) ) { if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( self::BACKFILL_HOOK, null, self::AS_GROUP ); } return; } if ( '' !== $chain_from && preg_match( $ymd, $chain_from ) ) { $prev_end = gmdate( 'Y-m-d', strtotime( $start ) - DAY_IN_SECONDS ); if ( $prev_end >= $chain_from ) { $prev_start = max( $chain_from, gmdate( 'Y-m-01', strtotime( $prev_end ) ) ); wp_schedule_single_event( time() + MINUTE_IN_SECONDS, self::BACKFILL_HOOK, array( $prev_start, $prev_end, $chain_from ) ); } } } public static function backfill_pending() { if ( class_exists( 'ActionScheduler' ) && function_exists( 'as_get_scheduled_actions' ) ) { return (int) ActionScheduler::store()->query_actions( array( 'hook' => self::BACKFILL_HOOK, 'group' => self::AS_GROUP, 'status' => array( ActionScheduler_Store::STATUS_PENDING, ActionScheduler_Store::STATUS_RUNNING ), ), 'count' ); } $n = 0; foreach ( (array) _get_cron_array() as $hooks ) { if ( empty( $hooks[ self::BACKFILL_HOOK ] ) ) { continue; } foreach ( (array) $hooks[ self::BACKFILL_HOOK ] as $event ) { $a = isset( $event['args'] ) ? array_values( (array) $event['args'] ) : array(); $n += ( isset( $a[1], $a[2] ) && '' !== (string) $a[2] ) ? max( 1, count( self::month_chunks( (string) $a[2], (string) $a[1] ) ) ) : 1; } } return $n; } private static function month_chunks( $from, $to ) { $out = array(); $floor = strtotime( $from ); $end = strtotime( $to ); if ( false === $floor || false === $end ) { return $out; } while ( $end >= $floor ) { $start = max( $floor, strtotime( gmdate( 'Y-m-01', $end ) ) ); $out[] = array( gmdate( 'Y-m-d', $start ), gmdate( 'Y-m-d', $end ) ); $end = $start - DAY_IN_SECONDS; } return $out; } private static function store( $dim, array $rows ) { global $wpdb; $table = self::table(); $now = gmdate( 'Y-m-d H:i:s' ); $objects = array(); if ( 'page' === $dim ) { if ( ! class_exists( 'AIEO_Path_Resolver' ) ) { require_once AIEO_DIR . 'includes/seo/class-aieo-path-resolver.php'; } $urls = array(); foreach ( $rows as $r ) { $urls[] = (string) ( $r['keys'][1] ?? '' ); } $objects = AIEO_Path_Resolver::resolve_many( $urls ); } $written = 0; foreach ( $rows as $r ) { $date = (string) ( $r['keys'][0] ?? '' ); $value = (string) ( $r['keys'][1] ?? '' ); if ( '' === $date || '' === $value ) { continue; } $otype = ''; $oid = 0; if ( 'page' === $dim ) { $key = AIEO_Path_Resolver::normalise( $value ); if ( isset( $objects[ $key ] ) ) { $otype = (string) $objects[ $key ]['type']; $oid = (int) $objects[ $key ]['id']; } } $wpdb->query( $wpdb->prepare( "INSERT INTO `{$table}` (`date`, dim_type, dim_hash, dim_value, clicks, impressions, ctr, position, object_type, object_id, created_at) VALUES (%s, %s, %s, %s, %d, %d, %f, %f, %s, %d, %s) ON DUPLICATE KEY UPDATE dim_value = VALUES(dim_value), clicks = VALUES(clicks), impressions = VALUES(impressions), ctr = VALUES(ctr), position = VALUES(position), object_type = VALUES(object_type), object_id = VALUES(object_id), created_at = VALUES(created_at)", $date, $dim, md5( $value ), mb_substr( $value, 0, 191 ), (int) ( $r['clicks'] ?? 0 ), (int) ( $r['impressions'] ?? 0 ), (float) ( $r['ctr'] ?? 0 ), (float) ( $r['position'] ?? 0 ), $otype, $oid, $now ) ); $written++; } return $written; } public static function prune() { global $wpdb; if ( ! self::table_exists() ) { return 0; } $cut = gmdate( 'Y-m-d', time() - self::retention_days() * DAY_IN_SECONDS ); $table = self::table(); return (int) $wpdb->query( $wpdb->prepare( "DELETE FROM `{$table}` WHERE `date` < %s", $cut ) ); } public static function series( $dim, $value, $from, $to ) { global $wpdb; if ( ! self::table_exists() ) { return array(); } $table = self::table(); return (array) $wpdb->get_results( $wpdb->prepare( "SELECT `date`, clicks, impressions, ctr, position FROM `{$table}` WHERE dim_type = %s AND dim_hash = %s AND `date` BETWEEN %s AND %s ORDER BY `date`", $dim, md5( (string) $value ), $from, $to ), ARRAY_A ); } public static function year_on_year( $dim, $from, $to, $limit = 50 ) { global $wpdb; if ( ! self::table_exists() ) { return array( 'rows' => array(), 'have_last_year' => false ); } $table = self::table(); $py_from = gmdate( 'Y-m-d', strtotime( $from . ' -1 year' ) ); $py_to = gmdate( 'Y-m-d', strtotime( $to . ' -1 year' ) ); $oldest = (string) $wpdb->get_var( "SELECT MIN(`date`) FROM `{$table}`" ); $have = ( '' !== $oldest && strtotime( $oldest ) <= strtotime( $py_from ) ); $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT n.dim_value, n.clicks AS clicks, n.impressions AS impressions, n.position AS position, p.clicks AS ly_clicks, p.impressions AS ly_impressions, p.position AS ly_position FROM ( SELECT dim_hash, MAX(dim_value) dim_value, SUM(clicks) clicks, SUM(impressions) impressions, ROUND(AVG(position),1) position FROM `{$table}` WHERE dim_type = %s AND `date` BETWEEN %s AND %s GROUP BY dim_hash ) n LEFT JOIN ( SELECT dim_hash, SUM(clicks) clicks, SUM(impressions) impressions, ROUND(AVG(position),1) position FROM `{$table}` WHERE dim_type = %s AND `date` BETWEEN %s AND %s GROUP BY dim_hash ) p ON p.dim_hash = n.dim_hash ORDER BY n.impressions DESC LIMIT %d", $dim, $from, $to, $dim, $py_from, $py_to, (int) $limit ), ARRAY_A ); return array( 'rows' => $rows, 'have_last_year' => $have, 'window' => array( 'from' => $from, 'to' => $to ), 'last_year' => array( 'from' => $py_from, 'to' => $py_to ), ); } public static function coverage() { global $wpdb; if ( ! self::table_exists() ) { return array( 'rows' => 0, 'days' => 0, 'first' => '', 'last' => '' ); } $table = self::table(); $r = $wpdb->get_row( "SELECT COUNT(*) rows_n, COUNT(DISTINCT `date`) days, MIN(`date`) first_d, MAX(`date`) last_d FROM `{$table}`", ARRAY_A ); return array( 'rows' => (int) ( $r['rows_n'] ?? 0 ), 'days' => (int) ( $r['days'] ?? 0 ), 'first' => (string) ( $r['first_d'] ?? '' ), 'last' => (string) ( $r['last_d'] ?? '' ), ); } }