auth = new Agents24x7_Auth();
require_once __DIR__ . '/class-notifications.php';
$this->notifications = new Agents24x7_Notifications( $this->auth );
$this->integration = new Agents24x7_Integration();
$this->api_proxy = new Agents24x7_API_Proxy( $this->auth );
$this->abilities = new Agents24x7_Abilities( $this->api_proxy, $this->integration );
add_action( 'save_post', array( $this, 'queue_content_change' ), 100, 2 );
foreach ( array( 'post', 'page', 'product' ) as $post_type ) {
add_action( 'rest_after_insert_' . $post_type, array( $this, 'queue_rest_content_change' ), 100, 1 );
}
add_action( 'deleted_post', array( $this, 'queue_content_change' ), 100, 2 );
add_action( 'agents24x7_content_change', array( $this, 'notify_content_change' ) );
add_action( 'added_post_meta', array( $this, 'queue_content_meta_change' ), 100, 3 );
add_action( 'updated_post_meta', array( $this, 'queue_content_meta_change' ), 100, 3 );
add_action( 'deleted_post_meta', array( $this, 'queue_content_meta_change' ), 100, 3 );
add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
add_action( 'admin_init', array( $this, 'sync_support_settings_on_admin_page' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'wp_footer', array( $this, 'render_support_widget' ) );
add_action( 'wp_loaded', array( $this, 'capture_support_sale_session' ), 20 );
add_action( 'woocommerce_checkout_create_order', array( $this, 'add_support_sale_session_to_order' ) );
add_action( 'woocommerce_store_api_checkout_update_order_meta', array( $this, 'add_support_sale_session_to_order' ) );
add_action( 'init', array( $this, 'schedule_support_settings_sync' ) );
add_action( 'agents24x7_sync_support_settings', array( $this, 'sync_support_settings' ) );
// AJAX handlers
add_action( 'wp_ajax_agents24x7_get_wp_credentials', array( $this, 'ajax_get_wp_credentials' ) );
add_action( 'wp_ajax_agents24x7_confirm_wp_password_rotation', array( $this, 'ajax_confirm_wp_password_rotation' ) );
add_action( 'wp_ajax_agents24x7_cancel_wp_password_rotation', array( $this, 'ajax_cancel_wp_password_rotation' ) );
add_action( 'wp_ajax_agents24x7_release_wp_password_rotation_lock', array( $this, 'ajax_release_wp_password_rotation_lock' ) );
add_action( 'wp_ajax_agents24x7_disconnect', array( $this, 'ajax_disconnect' ) );
add_action( 'wp_ajax_agents24x7_get_auth_status', array( $this, 'ajax_get_auth_status' ) );
add_action( 'wp_ajax_agents24x7_search_catalog', array( $this, 'ajax_search_catalog' ) );
add_action( 'wp_ajax_agents24x7_set_support_enabled', array( $this, 'ajax_set_support_enabled' ) );
}
/**
* Add admin menu
*/
public function add_admin_menu() {
add_menu_page(
'Agents24x7',
$this->notifications->menu_title(),
'edit_posts',
'agents24x7',
array( $this, 'admin_page' ),
'dashicons-lightbulb',
25
);
// The plugin ships no .mo files, so Hebrew menu labels are selected here like the admin app's own copy.
$home_label = $this->admin_menu_label( __( 'Home', 'agents24x7' ), 'בית' );
add_submenu_page(
'agents24x7',
$home_label,
$home_label,
'edit_posts',
'agents24x7-home',
array( $this, 'admin_page' )
);
$plan_label = $this->admin_menu_label( __( 'Plan', 'agents24x7' ), 'תוכנית' );
add_submenu_page( 'agents24x7', $plan_label, $plan_label, 'edit_posts', 'agents24x7-plan', array( $this, 'admin_page' ) );
$team_label = $this->admin_menu_label( __( 'Team', 'agents24x7' ), 'הצוות' );
$work_label = $this->admin_menu_label( __( 'Work items', 'agents24x7' ), 'משימות' );
$channels_label = $this->admin_menu_label( __( 'Communication Channels', 'agents24x7' ), 'ערוצי תקשורת' );
$settings_label = $this->admin_menu_label( __( 'Settings', 'agents24x7' ), 'הגדרות' );
$seo_previews_label = $this->admin_menu_label( __( 'SEO Page Previews', 'agents24x7' ), 'תצוגות מקדימות של דפי SEO' );
add_submenu_page( 'agents24x7', $team_label, $team_label, 'edit_posts', 'agents24x7-team', array( $this, 'admin_page' ) );
add_submenu_page( 'agents24x7', $work_label, $work_label, 'edit_posts', 'agents24x7-work', array( $this, 'admin_page' ) );
add_submenu_page( 'agents24x7', $channels_label, $channels_label, 'edit_posts', 'agents24x7-channels', array( $this, 'admin_page' ) );
add_submenu_page( 'agents24x7', $settings_label, $settings_label, 'edit_posts', 'agents24x7-settings', array( $this, 'admin_page' ) );
add_submenu_page( 'agents24x7', $seo_previews_label, $seo_previews_label, 'manage_options', 'agents24x7-seo-pages', array( $this, 'seo_page_previews' ) );
remove_submenu_page( 'agents24x7', 'agents24x7' );
}
/** Literal strings stay at the call site so translation tools can still extract them. */
private function admin_menu_label( $translated, $hebrew ) {
return 0 === strpos( get_user_locale(), 'he' ) ? $hebrew : $translated;
}
/** Show page proposal previews while keeping approval on the portal card. */
public function seo_page_previews() {
if ( ! current_user_can( 'manage_options' ) || ! $this->auth->is_authenticated() ) {
return;
}
echo '
';
$this->notifications->admin_notice( true );
echo '
';
$hebrew = 0 === strpos( get_user_locale(), 'he' );
$labels = $hebrew
? array( 'home' => 'בית', 'team' => 'צוות', 'work' => 'פריטי עבודה', 'channels' => 'ערוצי תקשורת', 'settings' => 'הגדרות', 'seo-pages' => 'תצוגות מקדימות של דפי SEO' )
: array( 'home' => 'Home', 'team' => 'Team', 'work' => 'Work items', 'channels' => 'Communication Channels', 'settings' => 'Settings', 'seo-pages' => 'SEO Page Previews' );
$host = wp_parse_url( home_url(), PHP_URL_HOST );
$port = wp_parse_url( home_url(), PHP_URL_PORT );
$site_label = $host . ( $port ? ':' . $port : '' );
echo '';
echo '
';
foreach ( $labels as $slug => $label ) {
echo '' . esc_html( $label ) . ' ';
}
echo ' ' . esc_html( $hebrew ? 'שינויים בעמודי האתר' : 'Store page changes' ) . ' ';
echo '' . esc_html( $hebrew ? 'כאן מופיעים שינויים שהסוכן מציע לעמודי החנות: תיאורים, כותרות ועמודים חדשים. שום דבר לא עולה לאתר לפני שתאשרו.' : 'Review changes your agent suggests for store pages: descriptions, titles and new pages. Nothing goes live until you approve it.' ) . '
';
echo '' . esc_html( $hebrew ? 'כל האישורים והיסטוריית השינויים' : 'All approvals and history' ) . '
';
$site_url = home_url();
$response = wp_remote_get(
rtrim( AGENTS24X7_APP_URL, '/' ) . '/wordpress/page-proposals?siteUrl=' . rawurlencode( $site_url ),
array( 'headers' => $this->auth->get_auth_headers(), 'timeout' => 15 )
);
$payload = ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response )
? json_decode( wp_remote_retrieve_body( $response ), true ) : null;
if ( ! is_array( $payload ) || ! isset( $payload['proposals'] ) || ! is_array( $payload['proposals'] ) ) {
echo ' ';
return;
}
$proposals = $payload['proposals'];
if ( empty( $proposals ) ) {
echo '';
return;
}
foreach ( $proposals as $proposal ) {
if ( empty( $proposal['decisionUrl'] ) || empty( $proposal['title'] ) ) {
continue;
}
echo '';
echo '' . esc_html( $proposal['title'] ) . ' ';
echo '' . esc_html( $hebrew ? 'לפני' : 'Before' ) . ' ' . esc_html( $hebrew ? 'העמוד הזה עדיין לא קיים.' : 'This page does not exist yet.' ) . '
' . esc_html( $hebrew ? 'אחרי' : 'After' ) . ' ';
if ( ! empty( $proposal['metaTitle'] ) ) {
echo '' . esc_html( $proposal['metaTitle'] ) . '
';
}
if ( ! empty( $proposal['metaDescription'] ) ) {
echo '' . esc_html( $proposal['metaDescription'] ) . '
';
}
echo '' . esc_html( $hebrew ? 'איך זה עוזר' : 'Why it helps' ) . ' ' . esc_html( $hebrew ? 'נותן למבקרים עמוד ייעודי למציאת המידע שהם צריכים.' : 'Gives visitors a dedicated page to find the information they need.' ) . '
';
if ( ! empty( $proposal['previewUrl'] ) ) {
echo '';
}
echo '' . esc_html( $hebrew ? 'בדיקה ב-Agents24x7' : 'Review in Agents24x7' ) . '
';
}
echo '';
}
/**
* Enqueue scripts
*
* @param string $hook Current admin page
*/
public function enqueue_scripts( $hook ) {
$plugin_pages = array(
'agents24x7',
'agents24x7-home',
'agents24x7-plan',
'agents24x7-team',
'agents24x7-work',
'agents24x7-channels',
'agents24x7-settings',
'agents24x7-seo-pages',
);
// WordPress derives submenu hooks from the parent title, including its notification badge.
$plugin_hooks = array_map(
static function ( $page ) {
return get_plugin_page_hookname( $page, 'agents24x7' );
},
$plugin_pages
);
if ( ! in_array( $hook, $plugin_hooks, true ) ) {
return;
}
wp_enqueue_style( 'agents24x7-team-calendar', AGENTS24X7_PLUGIN_URL . 'admin/css/team-calendar.css', array(), AGENTS24X7_VERSION );
// Check if development mode is active (webpack dev server running)
$dev_server_url = 'http://localhost:3001/admin.js';
$is_dev_mode = defined( 'WP_DEBUG' ) && WP_DEBUG && $this->is_dev_server_running();
if ( $is_dev_mode ) {
// Development mode - load from webpack dev server
wp_enqueue_script(
'agents24x7-admin',
$dev_server_url,
array( 'wp-element', 'wp-i18n' ),
time(), // Use timestamp to prevent caching
true
);
} else {
// Production mode - load built assets
wp_enqueue_script(
'agents24x7-admin',
AGENTS24X7_PLUGIN_URL . 'admin/js/dist/admin.js',
array( 'wp-element', 'wp-i18n' ),
$this->asset_version( 'admin/js/dist/admin.js' ),
true
);
}
wp_set_script_translations( 'agents24x7-admin', 'agents24x7', AGENTS24X7_PLUGIN_DIR . 'languages' );
wp_enqueue_style(
'agents24x7-admin',
AGENTS24X7_PLUGIN_URL . 'admin/css/admin.css',
array(),
$this->asset_version( 'admin/css/admin.css' )
);
// Localize script with data
wp_localize_script( 'agents24x7-admin', 'agents24x7_data', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'restUrl' => rest_url( 'agents24x7/v1' ),
'nonce' => wp_create_nonce( 'agents24x7_nonce' ),
'wpNonce' => wp_create_nonce( 'wp_rest' ),
'isAuthenticated' => $this->auth->is_authenticated(),
'adminView' => isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : 'agents24x7-home',
'logoUrl' => AGENTS24X7_PLUGIN_URL . 'admin/images/agents24x7-mark.svg',
'pluginUrl' => AGENTS24X7_PLUGIN_URL,
'supportEnabled' => (bool) get_option( 'agents24x7_support_enabled', $this->is_support_agent_bound() ? 1 : 0 ),
'supportAvailable' => $this->is_support_agent_bound(),
// Nested so it stays a boolean: wp_localize_script casts
// top-level values to strings, which turns false into "".
'service' => array(
'available' => Agents24x7_Service_Status::is_available(),
),
'connectUrl' => $this->auth->get_connect_url(),
'convexCloudUrl' => $this->get_convex_cloud_url(),
'apiUrl' => Agents24x7_Config::get_api_url(),
'convexSiteUrl' => Agents24x7_Config::get_api_url(),
'appUrl' => $this->get_app_url(),
'wpSiteInfo' => array(
'name' => get_bloginfo( 'name' ),
'url' => home_url(),
'description' => get_bloginfo( 'description' ),
'locale' => get_locale(),
),
'adminLocale' => get_user_locale( get_current_user_id() ),
'woocommerceInfo' => $this->integration->get_woocommerce_info(),
'userId' => get_current_user_id(),
) );
}
/** Use the built file timestamp so updated plugin assets bypass browser caches. */
private function asset_version( $relative_path ) {
$asset_path = AGENTS24X7_PLUGIN_DIR . $relative_path;
$modified = file_exists( $asset_path ) ? filemtime( $asset_path ) : false;
return false !== $modified ? (string) $modified : AGENTS24X7_VERSION;
}
/**
* The platform writes these values after confirming a hired agent binding.
*/
private function is_support_agent_bound() {
$agent_id = get_option( 'agents24x7_support_agent_id', '' );
$site_key = get_option( 'agents24x7_support_site_key', '' );
return is_string( $agent_id ) && $agent_id !== '' && is_string( $site_key ) && preg_match( '/^[a-zA-Z0-9_-]{1,200}$/', $site_key );
}
/** Keep only the first-party chat key, never shopper details. Works for classic and block checkout. */
public function capture_support_sale_session() {
if ( ! $this->is_support_agent_bound() || ! get_option( 'agents24x7_support_enabled', 1 ) || ! get_option( 'agents24x7_support_site_enabled', 0 ) || ! function_exists( 'WC' ) || ! WC()->session ) {
return;
}
$session_id = isset( $_GET['a24x7_support_session'] ) && is_string( $_GET['a24x7_support_session'] ) ? sanitize_text_field( wp_unslash( $_GET['a24x7_support_session'] ) ) : '';
if ( ! preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $session_id ) ) {
return;
}
WC()->session->set( 'a24x7_support_session', array( 'id' => $session_id, 'at' => time() ) );
WC()->session->set_customer_session_cookie( true );
wc_setcookie( 'a24x7_support_session', $session_id . '.' . time(), time() + 7 * DAY_IN_SECONDS, is_ssl(), true );
}
public function add_support_sale_session_to_order( $order ) {
if ( ! function_exists( 'WC' ) || ! WC()->session ) {
return;
}
$match = WC()->session->get( 'a24x7_support_session' );
// Woo sessions can expire before seven days; the HTTP-only first-party key covers a later visit.
if ( ! is_array( $match ) && isset( $_COOKIE['a24x7_support_session'] ) && is_string( $_COOKIE['a24x7_support_session'] ) ) {
$parts = explode( '.', sanitize_text_field( wp_unslash( $_COOKIE['a24x7_support_session'] ) ) );
if ( 2 === count( $parts ) && preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $parts[0] ) && ctype_digit( $parts[1] ) ) {
$match = array( 'id' => $parts[0], 'at' => (int) $parts[1] );
}
}
if ( is_array( $match ) && isset( $match['id'], $match['at'] ) && time() >= $match['at'] && time() - $match['at'] <= 7 * DAY_IN_SECONDS ) {
$order->update_meta_data( 'a24x7_support_session', $match['id'] );
}
}
public function render_support_widget() {
if ( ! get_option( 'agents24x7_support_enabled', 1 ) || ! get_option( 'agents24x7_support_site_enabled', 0 ) || ! $this->is_support_agent_bound() ) {
return;
}
$site_key = get_option( 'agents24x7_support_site_key', '' );
echo '';
}
/** Core post hooks run for editor, REST, CLI, cron and wp_update_post writes. */
public function queue_content_change( $post_id, $post = null ) {
if ( ! $this->auth->is_authenticated() || wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
return;
}
if ( ! $post || ! in_array( $post->post_type, array( 'post', 'page', 'product' ), true ) ) {
return;
}
if ( ! wp_next_scheduled( 'agents24x7_content_change' ) ) {
wp_schedule_single_event( time() + 30, 'agents24x7_content_change' );
}
// A pending cron retry must not suppress this request's final editor save.
if ( ! $this->content_change_queued ) {
$this->content_change_queued = true;
add_action( 'shutdown', array( $this, 'notify_content_change' ) );
}
}
/** REST metadata and additional fields are complete at this hook. */
public function queue_rest_content_change( $post ) {
$this->queue_content_change( $post->ID, $post );
}
/** Builders can store their rendered content in post metadata. */
public function queue_content_meta_change( $meta_id, $post_id, $meta_key ) {
if ( in_array( $meta_key, array( '_edit_lock', '_edit_last' ), true ) ) {
return;
}
$this->queue_content_change( $post_id, get_post( $post_id ) );
}
public function notify_content_change() {
if ( ! $this->auth->is_authenticated() || get_transient( 'agents24x7_content_change_lock' ) ) {
return;
}
set_transient( 'agents24x7_content_change_lock', 1, 15 );
$response = wp_remote_post(
$this->get_platform_app_url() . '/wordpress/content-change',
array(
'headers' => array_merge( $this->auth->get_auth_headers(), array( 'X-WordPress-Site' => home_url() ) ),
'timeout' => 10,
)
);
delete_transient( 'agents24x7_content_change_lock' );
if ( ! is_wp_error( $response ) && 202 === wp_remote_retrieve_response_code( $response ) ) {
wp_clear_scheduled_hook( 'agents24x7_content_change' );
} elseif ( ! wp_next_scheduled( 'agents24x7_content_change' ) ) {
wp_schedule_single_event( time() + 60, 'agents24x7_content_change' );
}
}
/** Refresh the support settings owned by this connected WordPress site. */
public function sync_support_settings( $force = false ) {
if ( ! $this->auth->is_authenticated() ) {
return;
}
$lock_key = 'agents24x7_support_settings_refresh_lock';
$refresh_key = 'agents24x7_support_settings_refreshed_at';
if ( ! $force && ( get_transient( $lock_key ) || get_transient( $refresh_key ) ) ) {
return;
}
set_transient( $lock_key, 1, 15 );
set_transient( $refresh_key, time(), self::SUPPORT_SETTINGS_REFRESH_INTERVAL );
$response = wp_remote_get(
$this->get_platform_app_url() . '/wordpress/support-settings',
array(
'headers' => array_merge( $this->auth->get_auth_headers(), array( 'X-WordPress-Site' => home_url(), 'X-WordPress-WooCommerce' => class_exists( 'WooCommerce' ) ? '1' : '0' ) ),
'timeout' => 10,
)
);
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return;
}
$settings = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $settings ) || ! array_key_exists( 'enabled', $settings ) ) {
return;
}
$site_key = isset( $settings['publicSiteKeyId'] ) && is_string( $settings['publicSiteKeyId'] )
&& preg_match( '/^[a-zA-Z0-9_-]{1,200}$/', $settings['publicSiteKeyId'] )
? $settings['publicSiteKeyId']
: '';
$agent_id = isset( $settings['agentId'] ) && is_string( $settings['agentId'] )
&& preg_match( '/^[0-9a-f-]{36}$/i', $settings['agentId'] )
? $settings['agentId']
: '';
update_option( 'agents24x7_support_site_enabled', ! empty( $settings['enabled'] ) ? 1 : 0 );
if ( '' !== $site_key ) {
update_option( 'agents24x7_support_site_key', $site_key );
if ( '' !== $agent_id ) {
update_option( 'agents24x7_support_agent_id', $agent_id );
} else {
delete_option( 'agents24x7_support_agent_id' );
}
if ( ! get_option( 'agents24x7_support_toggle_set', 0 ) ) {
update_option( 'agents24x7_support_enabled', 1 );
}
} else {
delete_option( 'agents24x7_support_site_key' );
delete_option( 'agents24x7_support_agent_id' );
update_option( 'agents24x7_support_site_enabled', 0 );
}
}
/** Schedule stale settings to refresh in a separate WP-Cron request. */
public function schedule_support_settings_sync() {
if ( get_transient( 'agents24x7_support_settings_refreshed_at' ) ) {
return;
}
$next_refresh = wp_next_scheduled( 'agents24x7_sync_support_settings' );
if ( ! $next_refresh || $next_refresh > time() + 5 ) {
wp_schedule_single_event( time() + 1, 'agents24x7_sync_support_settings' );
}
}
/** Refresh settings before admin assets are localised on the plugin page. */
public function sync_support_settings_on_admin_page() {
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
$plugin_pages = array( 'agents24x7', 'agents24x7-home', 'agents24x7-team', 'agents24x7-work', 'agents24x7-channels', 'agents24x7-settings', 'agents24x7-seo-pages' );
if ( in_array( $page, $plugin_pages, true ) && current_user_can( 'manage_options' ) ) {
$this->sync_support_settings( true );
}
}
private function get_support_status_text() {
if ( ! $this->auth->is_authenticated() ) {
return '';
}
$audience = class_exists( 'WooCommerce' ) ? 'customer' : 'visitor';
if ( ! $this->is_support_agent_bound() ) {
return ucfirst( $audience ) . ' support chat is not set up for this site.';
}
if ( ! get_option( 'agents24x7_support_site_enabled', 0 ) ) {
return ucfirst( $audience ) . ' support chat is switched off in Agents24x7.';
}
return get_option( 'agents24x7_support_enabled', 1 )
? ''
: ucfirst( $audience ) . ' support chat is switched off in WordPress.';
}
private function get_platform_app_url() {
require_once AGENTS24X7_PLUGIN_DIR . 'config.php';
$url = defined( 'AGENTS24X7_APP_URL' ) && AGENTS24X7_APP_URL
? AGENTS24X7_APP_URL
: 'https://app.agents24x7.com';
return untrailingslashit( $url );
}
public function ajax_set_support_enabled() {
check_ajax_referer( 'agents24x7_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'You need administrative access to update Support Agent settings.' );
return;
}
$enabled = isset( $_POST['enabled'] ) && sanitize_text_field( wp_unslash( $_POST['enabled'] ) ) === '1';
if ( $enabled ) {
$this->sync_support_settings( true );
}
if ( $enabled && ! $this->is_support_agent_bound() ) {
update_option( 'agents24x7_support_enabled', 0 );
wp_send_json_error( 'Hire a Support Agent before enabling chat.' );
return;
}
update_option( 'agents24x7_support_enabled', $enabled ? 1 : 0 );
update_option( 'agents24x7_support_toggle_set', 1 );
wp_send_json_success( array( 'enabled' => $enabled ) );
}
/**
* Check if webpack dev server is running
*
* @return bool
*/
private function is_dev_server_running() {
$dev_server_url = 'http://localhost:3001';
$context = stream_context_create( array(
'http' => array(
'timeout' => 1,
'ignore_errors' => true,
),
) );
$result = @file_get_contents( $dev_server_url, false, $context );
return $result !== false;
}
/**
* Admin page output
*/
public function admin_page() {
// admin.css hides every direct child of #wpbody-content except the app
// root and this container, so notices must be printed inside it.
echo '';
$this->notifications->admin_notice( true );
if ( ! Agents24x7_Service_Status::is_available() ) {
echo '
' .
esc_html( Agents24x7_Service_Status::unavailable_message() ) .
'
';
}
// Check for OAuth success/error messages from transient storage
$message = get_transient( 'agents24x7_message' );
if ( $message ) {
// Delete transient after reading (single-use message)
delete_transient( 'agents24x7_message' );
if ( $message['type'] === 'success' ) {
echo '
' .
esc_html( $message['text'] ) .
'
';
} elseif ( $message['type'] === 'error' ) {
$error_message = $message['text'];
$error_parts = explode( ' | Details: ', $error_message );
$main_error = $error_parts[0];
$details = isset( $error_parts[1] ) ? $error_parts[1] : '';
echo '
';
echo '
⚠️ OAuth Connection Failed ';
echo '
' . esc_html( $main_error ) . '
';
if ( $details ) {
echo '
';
echo 'Technical Details (click to expand) ';
echo '';
echo esc_html( str_replace( ' | ', "\n", $details ) );
echo '
';
echo ' ';
}
echo '
Next Steps:
';
echo '
';
echo 'Check your site\'s error logs for more details ';
echo 'Try the connection again in a few minutes ';
echo 'Contact support if the issue persists ';
echo ' ';
echo '
';
}
}
$support_status = $this->get_support_status_text();
if ( $support_status ) {
echo '
' . esc_html( $support_status ) . '
';
}
echo '
';
?>
integration->get_wordpress_credentials();
if ( is_wp_error( $credentials ) ) {
wp_send_json_error( $credentials->get_error_message() );
return;
}
wp_send_json_success( $credentials );
}
public function ajax_confirm_wp_password_rotation() {
$this->ajax_finish_wp_password_rotation( true );
}
public function ajax_cancel_wp_password_rotation() {
$this->ajax_finish_wp_password_rotation( false );
}
public function ajax_release_wp_password_rotation_lock() {
check_ajax_referer( 'agents24x7_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'You need administrative access to update WordPress credentials.' );
return;
}
$rotation_id = isset( $_POST['rotationId'] ) ? sanitize_text_field( wp_unslash( $_POST['rotationId'] ) ) : '';
if ( ! preg_match( '/^[a-f0-9-]{36}$/i', $rotation_id ) ) {
wp_send_json_error( 'Invalid credential rotation request.' );
return;
}
$result = $this->integration->release_password_rotation_lock( $rotation_id );
if ( is_wp_error( $result ) ) {
wp_send_json_error( $result->get_error_message() );
return;
}
wp_send_json_success( array( 'released' => true ) );
}
private function ajax_finish_wp_password_rotation( $keep_new ) {
check_ajax_referer( 'agents24x7_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'You need administrative access to update WordPress credentials.' );
return;
}
$rotation_id = isset( $_POST['rotationId'] ) ? sanitize_text_field( wp_unslash( $_POST['rotationId'] ) ) : '';
if ( ! preg_match( '/^[a-f0-9-]{36}$/i', $rotation_id ) ) {
wp_send_json_error( 'Invalid credential rotation request.' );
return;
}
$result = $this->integration->finish_password_rotation( $rotation_id, $keep_new );
if ( is_wp_error( $result ) ) {
wp_send_json_error( $result->get_error_message() );
return;
}
wp_send_json_success( array( 'confirmed' => (bool) $keep_new ) );
}
/**
* AJAX handler for disconnecting site
*/
public function ajax_disconnect() {
check_ajax_referer( 'agents24x7_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'Insufficient permissions' );
return;
}
// Tell Agents24x7 first, while the token still exists. If that fails
// the local cleanup still runs: removing the Application Passwords
// below revokes the platform's access regardless, and a site owner
// must always be able to disconnect, outage or not.
$site_url = home_url();
$convex_result = $this->api_proxy->disconnect_from_plugin( $site_url );
$message = 'Site disconnected successfully';
if ( is_wp_error( $convex_result ) ) {
Agents24x7_Logger::error( 'Remote disconnect failed, disconnecting locally: ' . $convex_result->get_error_message() );
$message = __( 'Site disconnected. Agents24x7 could not be reached, but its access to this site has been removed.', 'agents24x7' );
}
// Then disconnect OAuth and clean up local data
$this->auth->disconnect();
delete_option( 'agents24x7_support_site_enabled' );
delete_option( 'agents24x7_support_site_key' );
delete_option( 'agents24x7_support_agent_id' );
// Clean up WordPress integration
$result = $this->integration->disconnect_site();
if ( is_wp_error( $result ) ) {
// Log the error but don't fail the disconnect process
Agents24x7_Logger::error( 'Failed to clean up WordPress integration: ' . $result->get_error_message() );
}
wp_send_json_success( array(
'message' => $message,
'refresh' => true
) );
}
/**
* AJAX handler for getting auth status
*/
public function ajax_get_auth_status() {
check_ajax_referer( 'agents24x7_nonce', 'nonce' );
wp_send_json_success( array(
'isAuthenticated' => $this->auth->is_authenticated(),
'hasToken' => ! is_null( $this->auth->get_token() ),
) );
}
/**
* AJAX handler for local catalog search: WordPress posts, WooCommerce
* products and product categories. The article forms use this to pick
* content by title (Ruling R2); it never reaches the platform.
*
* Returns items as { id: string, title: string, handle: string }.
*/
public function ajax_search_catalog() {
check_ajax_referer( 'agents24x7_nonce', 'nonce' );
if ( ! current_user_can( 'edit_posts' ) ) {
wp_send_json_error( 'You do not have permission to search content.' );
return;
}
$type = isset( $_POST['type'] ) ? sanitize_key( wp_unslash( $_POST['type'] ) ) : '';
$query = isset( $_POST['q'] ) ? sanitize_text_field( wp_unslash( $_POST['q'] ) ) : '';
$items = array();
if ( 'posts' === $type ) {
$posts = get_posts( array(
'post_type' => 'post',
'post_status' => array( 'publish', 'draft', 'private' ),
's' => $query,
'posts_per_page' => 20,
'orderby' => 'date',
'order' => 'DESC',
'suppress_filters' => true,
) );
foreach ( $posts as $post ) {
$post_id = (int) $post->ID;
if ( 'draft' === $post->post_status && ! current_user_can( 'edit_post', $post_id ) ) {
continue;
}
if ( 'private' === $post->post_status && ! current_user_can( 'read_post', $post_id ) ) {
continue;
}
$items[] = array(
'id' => (string) $post_id,
'title' => $post->post_title,
'handle' => $post->post_name,
);
}
} elseif ( 'products' === $type && post_type_exists( 'product' ) ) {
$products = get_posts( array(
'post_type' => 'product',
'post_status' => 'publish',
's' => $query,
'posts_per_page' => 20,
'orderby' => 'date',
'order' => 'DESC',
'suppress_filters' => true,
) );
foreach ( $products as $product ) {
$items[] = array(
'id' => (string) $product->ID,
'title' => $product->post_title,
'handle' => $product->post_name,
);
}
} elseif ( 'product_cats' === $type && taxonomy_exists( 'product_cat' ) ) {
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'search' => $query,
'number' => 20,
'hide_empty' => false,
'orderby' => 'name',
) );
if ( ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
$items[] = array(
'id' => (string) $term->term_id,
'title' => $term->name,
'handle' => $term->slug,
);
}
}
}
wp_send_json_success( $items );
}
/**
* Get the configured platform URL, retaining the legacy setting for upgrades.
*
* @return string
*/
private function get_convex_cloud_url() {
// Load constants from config file
require_once AGENTS24X7_PLUGIN_DIR . 'config.php';
return defined( 'AGENTS24X7_CONVEX_CLOUD_URL' ) && AGENTS24X7_CONVEX_CLOUD_URL
? AGENTS24X7_CONVEX_CLOUD_URL
: $this->get_app_url();
}
/**
* Get Convex site URL
*
* @return string
*/
private function get_convex_site_url() {
return Agents24x7_Config::get_api_url();
}
/**
* Get app URL
*
* @return string
*/
private function get_app_url() {
// Load constants from config file
require_once AGENTS24X7_PLUGIN_DIR . 'config.php';
return defined( 'AGENTS24X7_APP_URL' )
? AGENTS24X7_APP_URL
: '';
}
}