array('label' => __( 'Queries', 'ai-eshop-optimizer' ), 'icon' => 'list'), 'pages' => array('label' => __( 'Pages', 'ai-eshop-optimizer' ), 'icon' => 'file-pen-line'), 'content' => array('label' => __( 'By content type', 'ai-eshop-optimizer' ), 'icon' => 'folders'), 'archive' => array('label' => __( 'Full archive', 'ai-eshop-optimizer' ), 'icon' => 'calendar-days'), ); if ( $has_dfs ) { $tabs['dfs'] = array('label' => __( 'Ranked keywords', 'ai-eshop-optimizer' ), 'icon' => 'target'); } return $tabs; } public function get_tab_arg() { return 'gscq_tab'; } public function register_hooks() { add_action( 'admin_post_aieo_gsc_oauth', array( $this, 'oauth_callback' ) ); add_action( 'wp_ajax_aieo_gsc_save_settings', array( $this, 'ajax_save_settings' ) ); add_action( 'wp_ajax_aieo_gsc_archive_rows', array( $this, 'ajax_archive_rows' ) ); add_action( 'wp_ajax_aieo_gsc_authorize', array( $this, 'ajax_authorize' ) ); add_action( 'wp_ajax_aieo_gsc_set_property', array( $this, 'ajax_set_property' ) ); add_action( 'wp_ajax_aieo_gsc_load_sites', array( $this, 'ajax_load_sites' ) ); add_action( 'wp_ajax_aieo_gsc_disconnect', array( $this, 'ajax_disconnect' ) ); add_action( 'wp_ajax_aieo_gsc_refresh', array( $this, 'ajax_refresh' ) ); add_action( 'wp_ajax_aieo_gsc_backfill', array( $this, 'ajax_backfill' ) ); add_action( AIEO_GSC_History::BACKFILL_HOOK, array( 'AIEO_GSC_History', 'run_backfill_month' ), 10, 3 ); add_action( AIEO_GSC_History::SYNC_HOOK, array( 'AIEO_GSC_History', 'run_queued_sync' ) ); add_filter( 'aieo_dmm_admin_navigator_cards', array( $this, 'navigator_cards' ) ); } public function navigator_cards( $cards ) { $slug = AIEO_DMM::MENU_SLUG; foreach ( AIEO_DMM_UI::normalise_tabs( $this->get_tabs() ) as $key => $tab ) { $cards[] = array( 'label' => sprintf( __( 'Search Queries — %s', 'ai-eshop-optimizer' ), $tab['label'] ), 'page_slug' => $slug, 'dmm_tab' => 'seo_search_queries', 'query' => array( 'gscq_tab' => $key ), ); } return $cards; } private function guard() { AIEO_DMM::verify_ajax_request(); if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ) ); } } public function oauth_callback() { if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ); } $back = admin_url( 'admin.php?page=ai-eshop-dmm&dmm_tab=seo_search_queries' ); $err = isset( $_GET['error'] ) ? sanitize_text_field( wp_unslash( $_GET['error'] ) ) : ''; if ( '' !== $err ) { wp_safe_redirect( add_query_arg( 'gsc_error', rawurlencode( $err ), $back ) ); exit; } $code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : ''; $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; $res = AIEO_GSC::handle_callback( $code, $state ); if ( is_wp_error( $res ) ) { wp_safe_redirect( add_query_arg( 'gsc_error', rawurlencode( $res->get_error_message() ), $back ) ); exit; } delete_transient( self::CACHE ); self::load_sites(); wp_safe_redirect( add_query_arg( 'gsc_connected', '1', $back ) ); exit; } private static function load_sites() { $sites = AIEO_GSC::list_sites(); if ( ! is_wp_error( $sites ) ) { self::adopt_only_property( $sites ); } return $sites; } private static function adopt_only_property( array $sites ) { if ( '' !== AIEO_GSC::property() ) { return; } $verified = array_values( array_filter( $sites, static function ( $e ) { return 'siteUnverifiedUser' !== ( $e['permissionLevel'] ?? '' ); } ) ); if ( 1 !== count( $verified ) ) { return; } $only = isset( $verified[0]['siteUrl'] ) ? (string) $verified[0]['siteUrl'] : ''; if ( '' !== $only && AIEO_GSC::set_property( $only ) ) { AIEO_GSC_History::maybe_backfill(); AIEO_GSC_History::queue_sync(); } } public function ajax_load_sites() { $this->guard(); if ( ! AIEO_GSC::is_connected() ) { wp_send_json_error( array( 'message' => __( 'Google Search Console is not connected.', 'ai-eshop-optimizer' ) ) ); } $sites = self::load_sites(); if ( is_wp_error( $sites ) ) { wp_send_json_error( array( 'message' => sprintf( __( 'Google did not return your properties: %s', 'ai-eshop-optimizer' ), $sites->get_error_message() ), 'reconnect' => AIEO_GSC::needs_reconnect( $sites ), ) ); } wp_send_json_success( array( 'count' => count( $sites ) ) ); } public function ajax_save_settings() { $this->guard(); $cid = isset( $_POST['client_id'] ) ? sanitize_text_field( wp_unslash( $_POST['client_id'] ) ) : ''; $cs = isset( $_POST['client_secret'] ) ? sanitize_text_field( wp_unslash( $_POST['client_secret'] ) ) : ''; if ( '' === trim( str_replace( "\u{2022}", '', $cs ) ) ) { $cs = (string) ( AIEO_GSC::settings()['client_secret'] ?? '' ); } if ( '' === $cid || '' === $cs ) { wp_send_json_error( array( 'message' => __( 'Paste both the Client ID and Client secret.', 'ai-eshop-optimizer' ) ) ); } AIEO_GSC::save_settings( $cid, $cs ); wp_send_json_success( array( 'auth_url' => AIEO_GSC::auth_url() ) ); } public function ajax_authorize() { $this->guard(); $url = AIEO_GSC::auth_url(); if ( '' === $url ) { wp_send_json_error( array( 'message' => __( 'Save the Client ID and Client secret first.', 'ai-eshop-optimizer' ) ) ); } wp_send_json_success( array( 'auth_url' => $url ) ); } public function ajax_set_property() { $this->guard(); $p = isset( $_POST['property'] ) ? sanitize_text_field( wp_unslash( $_POST['property'] ) ) : ''; if ( '' === $p ) { wp_send_json_error( array( 'message' => __( 'Pick a property.', 'ai-eshop-optimizer' ) ) ); } if ( AIEO_GSC::set_property( $p ) ) { AIEO_GSC_History::maybe_backfill(); AIEO_GSC_History::queue_sync(); } delete_transient( self::CACHE ); wp_send_json_success(); } public function ajax_disconnect() { $this->guard(); $revoke = ! isset( $_POST['revoke'] ) || '0' !== sanitize_text_field( wp_unslash( $_POST['revoke'] ) ); AIEO_GSC::disconnect( $revoke ); delete_transient( self::CACHE ); wp_send_json_success(); } public function ajax_refresh() { $this->guard(); delete_transient( self::CACHE ); $res = AIEO_GSC_History::queue_sync( true ); if ( 'not_connected' === $res ) { wp_send_json_error( array( 'message' => AIEO_GSC::is_connected() ? __( 'No Search Console property is selected.', 'ai-eshop-optimizer' ) : __( 'Google Search Console is not connected.', 'ai-eshop-optimizer' ), 'code' => $res, ) ); } if ( 'running' === $res ) { wp_send_json_success( array( 'message' => __( 'A sync is already running. Reload in a few minutes to see its result.', 'ai-eshop-optimizer' ), 'code' => $res, ) ); } if ( 'queued' !== $res ) { wp_send_json_error( array( 'message' => __( 'Nothing could be queued. Try again in a minute.', 'ai-eshop-optimizer' ), 'code' => $res, ) ); } wp_send_json_success( array( 'message' => __( 'Sync queued. The history refreshes in the background; reload in a few minutes.', 'ai-eshop-optimizer' ), 'code' => $res, ) ); } public function ajax_backfill() { $this->guard(); $res = AIEO_GSC_History::backfill(); if ( 'not_connected' === $res ) { wp_send_json_error( array( 'message' => __( 'Connect Search Console and save a property first.', 'ai-eshop-optimizer' ) ) ); } if ( 'already_queued' === $res ) { $left = AIEO_GSC_History::backfill_pending(); wp_send_json_error( array( 'message' => sprintf( _n( 'A backfill is already running: %s month left.', 'A backfill is already running: %s months left.', $left, 'ai-eshop-optimizer' ), number_format_i18n( $left ) ), ) ); } $n = (int) $res; if ( $n < 1 ) { wp_send_json_error( array( 'message' => __( 'Nothing could be queued. Try again in a minute.', 'ai-eshop-optimizer' ) ) ); } wp_send_json_success( array( 'queued' => $n, 'message' => sprintf( _n( 'Queued %s monthly job. The history fills in the background; reload in a few minutes.', 'Queued %s monthly jobs. The history fills in the background; reload in a few minutes.', $n, 'ai-eshop-optimizer' ), number_format_i18n( $n ) ), ) ); } const PAGE_ROWS = 1000; const QUERY_ROWS = 250; private function history_report() { global $wpdb; $table = $wpdb->prefix . 'aieo_gsc_daily'; if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { return null; } $cutoff = gmdate( 'Y-m-d', time() - 90 * DAY_IN_SECONDS ); $range = $wpdb->get_row( $wpdb->prepare( "SELECT MIN(`date`) a, MAX(`date`) b, COUNT(*) n FROM `{$table}` WHERE `date` >= %s", $cutoff ), ARRAY_A ); if ( empty( $range['n'] ) ) { return null; } $shape = static function ( $rows ) { $out = array(); foreach ( (array) $rows as $r ) { $imp = (int) $r['impressions']; $out[] = array( 'keys' => array( (string) $r['dim_value'] ), 'clicks' => (int) $r['clicks'], 'impressions' => $imp, 'ctr' => $imp > 0 ? ( (int) $r['clicks'] ) / $imp : 0, 'position' => (float) $r['position'], ); } return $out; }; $queries = $wpdb->get_results( $wpdb->prepare( "SELECT dim_value, SUM(clicks) clicks, SUM(impressions) impressions, SUM(position * impressions) / NULLIF(SUM(impressions), 0) position FROM `{$table}` WHERE dim_type = 'query' AND `date` >= %s GROUP BY dim_value ORDER BY impressions DESC LIMIT %d", $cutoff, self::QUERY_ROWS ), ARRAY_A ); $pages = $wpdb->get_results( $wpdb->prepare( "SELECT dim_value, SUM(clicks) clicks, SUM(impressions) impressions, SUM(position * impressions) / NULLIF(SUM(impressions), 0) position FROM `{$table}` WHERE dim_type = 'page' AND `date` >= %s GROUP BY dim_value ORDER BY impressions DESC LIMIT %d", $cutoff, self::PAGE_ROWS ), ARRAY_A ); $out = array( 'queries' => array( 'rows' => $shape( $queries ) ), 'pages' => array( 'rows' => $shape( $pages ) ), 'source' => 'history', 'range' => array( 'from' => (string) $range['a'], 'to' => (string) $range['b'] ), ); $out += self::attach_content( $out['pages'] ); return $out; } private function report() { $c = get_transient( self::CACHE ); if ( is_array( $c ) ) { return $c; } $queries = AIEO_GSC::top_queries( 90, self::QUERY_ROWS, array( 'query' ) ); $pages = AIEO_GSC::top_queries( 90, self::PAGE_ROWS, array( 'page' ) ); $out = array( 'queries' => is_wp_error( $queries ) ? array( 'error' => $queries->get_error_message() ) : $queries, 'pages' => is_wp_error( $pages ) ? array( 'error' => $pages->get_error_message() ) : $pages, ); if ( ! is_wp_error( $pages ) ) { $out += self::attach_content( $pages ); } if ( ! is_wp_error( $queries ) ) { set_transient( self::CACHE, $out, HOUR_IN_SECONDS ); } return $out; } private static function attach_content( array $pages ) { if ( ! class_exists( 'AIEO_Path_Resolver' ) ) { require_once AIEO_DIR . 'includes/seo/class-aieo-path-resolver.php'; } $rows = isset( $pages['rows'] ) && is_array( $pages['rows'] ) ? $pages['rows'] : array(); if ( empty( $rows ) ) { return array( 'pages_content' => array(), 'pages_by_type' => array() ); } $urls = array(); foreach ( $rows as $r ) { $u = (string) ( $r['keys'][0] ?? '' ); if ( '' !== $u ) { $urls[] = $u; } } $map = AIEO_Path_Resolver::resolve_many( $urls ); $content = array(); $by_type = array(); foreach ( $rows as $r ) { $u = (string) ( $r['keys'][0] ?? '' ); if ( '' === $u ) { continue; } $key = AIEO_Path_Resolver::normalise( $u ); $hit = isset( $map[ $key ] ) ? $map[ $key ] : null; $type = $hit ? $hit['type'] : 'not_a_single_page'; if ( $hit ) { $content[ $u ] = array( 'type' => $hit['type'], 'id' => $hit['id'], 'title' => (string) get_the_title( $hit['id'] ), 'edit' => (string) get_edit_post_link( $hit['id'], '' ), ); } if ( ! isset( $by_type[ $type ] ) ) { $by_type[ $type ] = array( 'pages' => 0, 'clicks' => 0, 'impressions' => 0 ); } $by_type[ $type ]['pages']++; $by_type[ $type ]['clicks'] += (int) ( $r['clicks'] ?? 0 ); $by_type[ $type ]['impressions'] += (int) ( $r['impressions'] ?? 0 ); } uasort( $by_type, static function ( $a, $b ) { return $b['impressions'] - $a['impressions']; } ); return array( 'pages_content' => $content, 'pages_by_type' => $by_type ); } private static function order_clause( $sort, $dir, array $allowed, $fallback ) { $dir = ( 'asc' === strtolower( (string) $dir ) ) ? 'ASC' : 'DESC'; if ( isset( $allowed[ $sort ] ) ) { return $allowed[ $sort ] . ' ' . $dir; } return $fallback; } private function history_list( $dim, $window, $q, $page, $per = 50, $sort = '', $dir = 'desc' ) { global $wpdb; $t = $wpdb->prefix . 'aieo_gsc_daily'; $out = array( 'rows' => array(), 'total' => 0, 'range' => array( 'from' => '', 'to' => '' ) ); if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) { return $out; } $where = "dim_type = %s"; $args = array( $dim ); if ( $window > 0 ) { $where .= " AND `date` >= %s"; $args[] = gmdate( 'Y-m-d', time() - $window * DAY_IN_SECONDS ); } if ( '' !== $q ) { $where .= " AND dim_value LIKE %s"; $args[] = '%' . $wpdb->esc_like( $q ) . '%'; } $out['total'] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT dim_hash) FROM `{$t}` WHERE {$where}", $args ) ); $range = $wpdb->get_row( $wpdb->prepare( "SELECT MIN(`date`) a, MAX(`date`) b FROM `{$t}` WHERE {$where}", $args ), ARRAY_A ); $out['range'] = array( 'from' => (string) ( $range['a'] ?? '' ), 'to' => (string) ( $range['b'] ?? '' ) ); $offset = max( 0, ( $page - 1 ) * $per ); $order = self::order_clause( $sort, $dir, array( 'term' => 'dim_value', 'clicks' => 'clicks', 'impressions' => 'impressions', 'ctr' => 'ctr', 'position' => 'position', ), 'impressions DESC' ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT dim_value, SUM(clicks) clicks, SUM(impressions) impressions, SUM(clicks) / NULLIF(SUM(impressions), 0) ctr, SUM(position * impressions) / NULLIF(SUM(impressions), 0) position, MAX(object_type) object_type, MAX(object_id) object_id FROM `{$t}` WHERE {$where} GROUP BY dim_hash ORDER BY {$order} LIMIT %d OFFSET %d", array_merge( $args, array( $per, $offset ) ) ), ARRAY_A ); foreach ( (array) $rows as $r ) { $imp = (int) $r['impressions']; $out['rows'][] = array( 'keys' => array( (string) $r['dim_value'] ), 'clicks' => (int) $r['clicks'], 'impressions' => $imp, 'ctr' => $imp > 0 ? ( (int) $r['clicks'] ) / $imp : 0, 'position' => (float) $r['position'], 'object_type' => (string) $r['object_type'], 'object_id' => (int) $r['object_id'], ); } return $out; } private function history_range( $dim, $window ) { global $wpdb; $t = $wpdb->prefix . 'aieo_gsc_daily'; if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) { return array( 'from' => '', 'to' => '' ); } $where = 'dim_type = %s'; $args = array( $dim ); if ( $window > 0 ) { $where .= ' AND `date` >= %s'; $args[] = gmdate( 'Y-m-d', time() - $window * DAY_IN_SECONDS ); } $row = $wpdb->get_row( $wpdb->prepare( "SELECT MIN(`date`) a, MAX(`date`) b FROM `{$t}` WHERE {$where}", $args ), ARRAY_A ); return array( 'from' => (string) ( $row['a'] ?? '' ), 'to' => (string) ( $row['b'] ?? '' ), ); } private function history_by_type( $window, $sort = '', $dir = 'desc' ) { global $wpdb; $t = $wpdb->prefix . 'aieo_gsc_daily'; if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) { return array(); } $where = "dim_type = 'page'"; $args = array(); if ( $window > 0 ) { $where .= " AND `date` >= %s"; $args[] = gmdate( 'Y-m-d', time() - $window * DAY_IN_SECONDS ); } $order = self::order_clause( $sort, $dir, array( 'type' => 'ctype', 'pages' => 'pages', 'clicks' => 'clicks', 'impressions' => 'impressions', ), 'impressions DESC' ); $sql = "SELECT IF(object_id > 0, object_type, 'not_a_single_page') ctype, COUNT(DISTINCT dim_hash) pages, SUM(clicks) clicks, SUM(impressions) impressions FROM `{$t}` WHERE {$where} GROUP BY ctype ORDER BY {$order}"; $rows = $args ? $wpdb->get_results( $wpdb->prepare( $sql, $args ), ARRAY_A ) : $wpdb->get_results( $sql, ARRAY_A ); $out = array(); foreach ( (array) $rows as $r ) { $out[ (string) $r['ctype'] ] = array( 'pages' => (int) $r['pages'], 'clicks' => (int) $r['clicks'], 'impressions' => (int) $r['impressions'], ); } return $out; } private function history_archive( $dim, $window, $q, $page, $per = 50, $sort = '', $dir = 'desc' ) { global $wpdb; $t = $wpdb->prefix . 'aieo_gsc_daily'; $out = array( 'rows' => array(), 'total' => 0 ); if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) { return $out; } $where = "dim_type = %s"; $args = array( $dim ); if ( $window > 0 ) { $where .= " AND `date` >= %s"; $args[] = gmdate( 'Y-m-d', time() - $window * DAY_IN_SECONDS ); } if ( '' !== $q ) { $where .= " AND dim_value LIKE %s"; $args[] = '%' . $wpdb->esc_like( $q ) . '%'; } $out['total'] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `{$t}` WHERE {$where}", $args ) ); $offset = max( 0, ( $page - 1 ) * $per ); $order = self::order_clause( $sort, $dir, array( 'date' => '`date`', 'term' => 'dim_value', 'clicks' => 'clicks', 'impressions' => 'impressions', 'ctr' => 'ctr', 'position' => 'position', ), '`date` DESC, impressions DESC' ); $out['rows'] = (array) $wpdb->get_results( $wpdb->prepare( "SELECT `date`, dim_value, clicks, impressions, ctr, position, object_type, object_id FROM `{$t}` WHERE {$where} ORDER BY {$order} LIMIT %d OFFSET %d", array_merge( $args, array( $per, $offset ) ) ), ARRAY_A ); return $out; } public static function archive_table( array $list, array $view ) { $per = max( 1, (int) ( $view['per_page'] ?? 50 ) ); $page = max( 1, (int) ( $view['page'] ?? 1 ) ); $total = (int) ( $list['total'] ?? 0 ); return \Rooster\Admin\Ui::table( self::archive_columns( (string) ( $view['dim'] ?? 'query' ), (string) ( $view['sort'] ?? '' ), (string) ( $view['dir'] ?? 'desc' ) ), self::archive_cells( (array) ( $list['rows'] ?? array() ) ), array( 'id' => 'aieo-gsc-archive', 'caption' => __( 'Full archive — day by day', 'ai-eshop-optimizer' ), 'remote' => array( 'url' => add_query_arg( 'action', 'aieo_gsc_archive_rows', admin_url( 'admin-ajax.php' ) ), 'nonce' => wp_create_nonce( AIEO_DMM::NONCE_ACTION ), 'context' => 'admin', 'scope' => array( 'gsc_dim' => (string) ( $view['dim'] ?? 'query' ), 'gsc_window' => (string) (int) ( $view['window'] ?? 90 ), 'gsc_q' => (string) ( $view['q'] ?? '' ), ), 'size' => $per, 'sizes' => array( 25, 50, 100 ), 'total' => $total, 'paged' => $page, 'sort' => array( 'key' => 'date', 'dir' => 'desc' ), 'keys' => array( 'orderby' => 'gsc_sort', 'order' => 'gsc_dir', 'paged' => 'sem_page', 'per_page' => 'gsc_per_page' ), ), 'footer' => $total > $per ? \Rooster\Admin\Ui::pager( $page, (int) ceil( $total / $per ), static function ( $n ) { return add_query_arg( 'sem_page', $n > 1 ? $n : false ); }, array( 'total' => $total ) ) : '', ) ); } public function ajax_archive_rows() { if ( ! check_ajax_referer( AIEO_DMM::NONCE_ACTION, '_wpnonce', false ) || ! current_user_can( AIEO_CAPABILITY ) ) { wp_send_json( array( 'message' => __( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ), 403 ); } if ( ! class_exists( '\Rooster\Admin\Ui' ) && ( ! function_exists( 'rooster_admin_builders' ) || ! rooster_admin_builders() ) ) { wp_send_json( array( 'message' => __( 'That report could not be run.', 'ai-eshop-optimizer' ) ), 500 ); } $dim = isset( $_GET['gsc_dim'] ) && 'page' === $_GET['gsc_dim'] ? 'page' : 'query'; $window = isset( $_GET['gsc_window'] ) ? max( 0, min( 480, (int) $_GET['gsc_window'] ) ) : 90; $q = isset( $_GET['gsc_q'] ) ? sanitize_text_field( wp_unslash( $_GET['gsc_q'] ) ) : ''; $page = isset( $_GET['page'] ) ? max( 1, absint( $_GET['page'] ) ) : 1; $per = isset( $_GET['per_page'] ) ? max( 1, min( 200, absint( $_GET['per_page'] ) ) ) : 50; $sort = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : ''; $dir = isset( $_GET['order'] ) && 'asc' === $_GET['order'] ? 'asc' : 'desc'; $list = $this->history_archive( $dim, $window, $q, $page, $per, $sort, $dir ); wp_send_json( \Rooster\Admin\Ui::answer( self::archive_columns( $dim, $sort, $dir ), self::archive_cells( (array) $list['rows'] ), array( 'filtered' => (int) $list['total'], 'page' => $page, 'per_page' => $per, 'orderby' => $sort, 'order' => $dir, ) ) ); } private static function archive_columns( $dim, $sort, $dir ) { $col = static function ( $key, $label, $type ) use ( $sort, $dir ) { $on = $sort === $key; return array( 'key' => $key, 'label' => $label, 'type' => $type, 'sort' => $on ? $dir : 'none', 'sort_type' => 'num' === $type ? 'number' : ( 'date' === $type ? 'date' : 'text' ), 'sort_url' => add_query_arg( array( 'gsc_sort' => $key, 'gsc_dir' => ( $on && 'desc' === $dir ) ? 'asc' : 'desc', 'sem_page' => false ) ), ); }; return array( $col( 'date', __( 'Date', 'ai-eshop-optimizer' ), 'date' ), $col( 'term', 'page' === $dim ? __( 'Page', 'ai-eshop-optimizer' ) : __( 'Query', 'ai-eshop-optimizer' ), 'text' ), $col( 'clicks', __( 'Clicks', 'ai-eshop-optimizer' ), 'num' ), $col( 'impressions', __( 'Impressions', 'ai-eshop-optimizer' ), 'num' ), $col( 'ctr', __( 'CTR', 'ai-eshop-optimizer' ), 'num' ), $col( 'position', __( 'Position', 'ai-eshop-optimizer' ), 'num' ), ); } private static function archive_cells( array $rows ) { $out = array(); foreach ( $rows as $r ) { $out[] = array( 'date' => (string) $r['date'], 'term' => (string) $r['dim_value'], 'clicks' => number_format_i18n( (int) $r['clicks'] ), 'impressions' => number_format_i18n( (int) $r['impressions'] ), 'ctr' => number_format_i18n( (float) $r['ctr'] * 100, 1 ) . '%', 'position' => number_format_i18n( (float) $r['position'], 1 ), ); } return $out; } public function render_subtab() { $connected = AIEO_GSC::is_connected(); $sites = array(); $sites_error = ''; $reconnect = false; $suggested = ''; $syncing = false; $unloaded = false; if ( $connected ) { $s = AIEO_GSC::cached_sites(); $unloaded = ! is_array( $s ); if ( null === $s ) { $s = array(); } if ( is_wp_error( $s ) ) { $sites_error = $s->get_error_message(); $reconnect = AIEO_GSC::needs_reconnect( $s ); } else { $sites = $s; } if ( ! $reconnect ) { $aieo_gsc_last = AIEO_GSC::last_error(); $reconnect = ! empty( $aieo_gsc_last['code'] ) && AIEO_GSC::needs_reconnect( (string) $aieo_gsc_last['code'] ); } $verified = array_values( array_filter( $sites, static function ( $e ) { return 'siteUnverifiedUser' !== ( $e['permissionLevel'] ?? '' ); } ) ); if ( '' === AIEO_GSC::property() && count( $verified ) > 1 ) { $host = preg_replace( '/^www\./', '', strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ) ); foreach ( $verified as $e ) { if ( '' !== $host && 'sc-domain:' . $host === strtolower( (string) ( $e['siteUrl'] ?? '' ) ) ) { $suggested = (string) $e['siteUrl']; break; } } } $syncing = in_array( AIEO_GSC_History::sync_state(), array( 'queued', 'running' ), true ); } $dfs = array(); if ( class_exists( 'AIEO_DFS_Rankings' ) && method_exists( 'AIEO_DFS_Rankings', 'striking_distance' ) ) { $dfs = AIEO_DFS_Rankings::striking_distance( 40 ); } $tabs = $this->get_tabs(); $tab = isset( $_GET['gscq_tab'] ) ? sanitize_key( wp_unslash( $_GET['gscq_tab'] ) ) : 'queries'; if ( ! isset( $tabs[ $tab ] ) ) { $tab = 'queries'; } $window = isset( $_GET['gsc_window'] ) ? max( 0, min( 480, (int) $_GET['gsc_window'] ) ) : 90; $gsc_q = isset( $_GET['gsc_q'] ) ? sanitize_text_field( wp_unslash( $_GET['gsc_q'] ) ) : ''; $pageno = isset( $_GET['sem_page'] ) ? max( 1, (int) $_GET['sem_page'] ) : 1; $aper = isset( $_GET['gsc_per_page'] ) && in_array( (int) $_GET['gsc_per_page'], array( 25, 50, 100 ), true ) ? (int) $_GET['gsc_per_page'] : 50; $adim = ( isset( $_GET['gsc_dim'] ) && 'page' === $_GET['gsc_dim'] ) ? 'page' : 'query'; $sort = isset( $_GET['gsc_sort'] ) ? sanitize_key( wp_unslash( $_GET['gsc_sort'] ) ) : ''; $sdir = ( isset( $_GET['gsc_dir'] ) && 'asc' === $_GET['gsc_dir'] ) ? 'asc' : 'desc'; $list = null; $by_type = array(); $pages_content = array(); if ( 'archive' === $tab ) { $list = $this->history_archive( $adim, $window, $gsc_q, $pageno, $aper, $sort, $sdir ); } elseif ( 'dfs' === $tab && ! empty( $dfs ) && '' !== $sort ) { $map = array( 'term' => 'keyword', 'position' => 'position', 'impressions' => 'volume' ); if ( isset( $map[ $sort ] ) ) { $col = $map[ $sort ]; usort( $dfs, static function ( $a, $b ) use ( $col, $sdir ) { $av = $a[ $col ] ?? ( 'keyword' === $col ? '' : 0 ); $bv = $b[ $col ] ?? ( 'keyword' === $col ? '' : 0 ); $c = is_string( $av ) ? strcasecmp( (string) $av, (string) $bv ) : ( $av <=> $bv ); return 'asc' === $sdir ? $c : -$c; } ); } } $this->render_template( 'seo/search-queries.php', array( 'configured' => AIEO_GSC::is_configured(), 'connected' => $connected, 'settings' => AIEO_GSC::settings(), 'redirect_uri' => AIEO_GSC::redirect_uri(), 'property' => AIEO_GSC::property(), 'sites' => $sites, 'sites_unloaded' => $unloaded, 'sites_error' => $sites_error, 'reconnect' => $reconnect, 'suggested' => $suggested, 'last_error' => AIEO_GSC::last_error(), 'last_sync' => (int) get_option( AIEO_GSC::LAST_SYNC_OPT, 0 ), 'syncing' => $syncing, 'backfilling' => $connected ? AIEO_GSC_History::backfill_pending() : 0, 'gsc_tabs' => $tabs, 'gsc_tab' => $tab, 'gsc_window' => $window, 'gsc_q' => $gsc_q, 'gsc_dim' => $adim, 'gsc_page' => $pageno, 'gsc_list' => $list, 'gsc_range' => $this->history_range( 'pages' === $tab ? 'page' : ( 'archive' === $tab ? $adim : 'query' ), $window ), 'gsc_by_type' => $by_type, 'gsc_content' => $pages_content, 'gsc_sort' => $sort, 'gsc_dir' => $sdir, 'gsc_per_page' => $aper, 'dfs' => is_array( $dfs ) ? $dfs : array(), 'nonce' => wp_create_nonce( AIEO_DMM::NONCE_ACTION ), 'ajax' => admin_url( 'admin-ajax.php' ), ) ); } }