render(); } ); } /** * Enqueue Connect styles on the Connect screen. * * @param string $hook_suffix Current admin hook suffix. * @return void */ public function enqueue_assets( $hook_suffix ) { if ( 'woocommerce_page_' . self::PAGE_SLUG === $hook_suffix ) { wp_enqueue_style( 'aha-is-for-woocommerce-connect-admin', plugins_url( 'assets/css/aha-connect-admin.css', AHA_IS_WOOCOMMERCE_PLUGIN_FILE ), array(), $this->asset_version( 'assets/css/aha-connect-admin.css' ) ); wp_enqueue_script( 'aha-is-for-woocommerce-connect-admin', plugins_url( 'assets/js/aha-connect-admin.js', AHA_IS_WOOCOMMERCE_PLUGIN_FILE ), array(), $this->asset_version( 'assets/js/aha-connect-admin.js' ), true ); } } /** * Version string that changes whenever the asset file changes (browser cache busting). * * @param string $relative_path Asset path relative to the plugin root. * @return string */ private function asset_version( $relative_path ) { $mtime = @filemtime( dirname( AHA_IS_WOOCOMMERCE_PLUGIN_FILE ) . '/' . $relative_path ); return $mtime ? AHA_IS_WOOCOMMERCE_PLUGIN_VERSION . '.' . $mtime : AHA_IS_WOOCOMMERCE_PLUGIN_VERSION; } /** * Validate a tab name against the whitelist. * * @param mixed $tab Candidate tab. * @return string Tab name, or '' when unknown. */ public static function sanitize_tab( $tab ) { return is_string( $tab ) && in_array( $tab, self::TABS, true ) ? $tab : ''; } /** * Build the first-install display model. * * @param mixed $website Website URL. * @return array */ public static function first_install_model( $website ) { return array( 'website' => (string) $website, 'account_status' => 'not linked', 'steps' => array( array( 'title' => __( 'Sign in to Aha', 'aha-is-for-woocommerce' ), 'body' => __( 'On aha.is. Sign in, or create an account.', 'aha-is-for-woocommerce' ) ), array( 'title' => __( 'Tell Aha about your store', 'aha-is-for-woocommerce' ), 'body' => __( 'Store type, name, address and phone. These create the connection only; no service is enabled.', 'aha-is-for-woocommerce' ) ), array( 'title' => __( 'Aha reviews your request', 'aha-is-for-woocommerce' ), 'body' => __( 'Catalog selling turns on after Aha review.', 'aha-is-for-woocommerce' ) ), ), ); } /** * Render a supplied state for validation errors, or load the current state. * * @param array|null $view_state View state. * @param array $errors Validation errors. * @return void */ /** @var bool Show the edit-details form on the waiting screen (set by a re-render after a failed edit). */ private $editing = false; /** @var string Notice code to show when the request URL carries none. */ private $notice_override = ''; public function render( $view_state = null, array $errors = array() ) { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( esc_html__( 'You cannot connect this website to Aha.', 'aha-is-for-woocommerce' ) ); } if ( 0 === func_num_args() ) { try { $view_state = Aha_Is_Woocommerce_Connect_Flow::view_state(); } catch ( Throwable $error ) { $view_state = null; if ( 'connect_attempt_bound_to_other_user' === $error->getMessage() ) { try { $view_state = Aha_Is_Woocommerce_Connect_Flow::view_state_for_other_admin(); } catch ( Throwable $other ) { $view_state = null; } } if ( null === $view_state ) { $view_state = array( 'phase' => Aha_Is_Woocommerce_Connect_Credentials::state_unreadable() ? 'state_unreadable' : 'not_connected', 'values' => array(), ); } } if ( empty( $view_state['read_only'] ) && 'origin_verified' === $view_state['phase'] ) { $view_state['login_used'] = Aha_Is_Woocommerce_Connect_Start::login_used(); } if ( empty( $view_state['read_only'] ) && in_array( $view_state['phase'], array( 'pending_review', 'reconnect_approved' ), true ) ) { try { Aha_Is_Woocommerce_Connect_Credentials::poll_request(); $view_state = Aha_Is_Woocommerce_Connect_Flow::view_state(); } catch ( Throwable $error ) { // Keep the readable waiting state. The scheduler will retry. } } } if ( ! is_array( $view_state ) || ! isset( $view_state['phase'] ) ) { $view_state = array( 'phase' => 'not_connected', 'values' => array() ); } $model = self::first_install_model( home_url() ); $phase = $view_state['phase']; $values = isset( $view_state['values'] ) && is_array( $view_state['values'] ) ? $view_state['values'] : array(); $statuses = array( 'not_connected' => __( 'not linked', 'aha-is-for-woocommerce' ), 'prepared' => __( 'waiting for sign-in', 'aha-is-for-woocommerce' ), 'proof_ready' => __( 'waiting for sign-in', 'aha-is-for-woocommerce' ), 'origin_verified' => __( 'waiting for sign-in', 'aha-is-for-woocommerce' ), 'consented' => __( 'details required', 'aha-is-for-woocommerce' ), 'pending_review' => __( 'waiting for review', 'aha-is-for-woocommerce' ), 'reconnect_available' => __( 'reconnecting', 'aha-is-for-woocommerce' ), 'returning_pending_review' => __( 'waiting for review', 'aha-is-for-woocommerce' ), 'site_bound_to_other_account' => __( 'linked to another account', 'aha-is-for-woocommerce' ), 'reconnect_approved' => __( 'reconnected', 'aha-is-for-woocommerce' ), 'connected' => __( 'connected', 'aha-is-for-woocommerce' ), 'rejected' => __( 'rejected', 'aha-is-for-woocommerce' ), 'access_revoked' => __( 'not linked', 'aha-is-for-woocommerce' ), 'connection_lost' => __( 'not linked', 'aha-is-for-woocommerce' ), 'state_unreadable' => __( 'setup needs attention', 'aha-is-for-woocommerce' ), 'expired_unresolved' => __( 'setup needs attention', 'aha-is-for-woocommerce' ), ); $model['account_status'] = isset( $statuses[ $phase ] ) ? $statuses[ $phase ] : __( 'not linked', 'aha-is-for-woocommerce' ); $notice_code = isset( $_GET['aha_is_woocommerce_notice'] ) && is_string( $_GET['aha_is_woocommerce_notice'] ) // phpcs:ignore WordPress.Security.NonceVerification -- read-only display value, mapped to a fixed message by a whitelist of codes; unknown values render nothing ? sanitize_text_field( wp_unslash( $_GET['aha_is_woocommerce_notice'] ) ) // phpcs:ignore WordPress.Security.NonceVerification -- read-only display value, mapped to a fixed message by a whitelist of codes; unknown values render nothing : $this->notice_override; $notices = array( 'setup_unavailable' => __( 'Connection setup is not available yet. No data was sent.', 'aha-is-for-woocommerce' ), 'safe_mode' => __( 'Safe mode is on. This site is not a production site or its address changed, so nothing was sent to Aha.', 'aha-is-for-woocommerce' ), 'setup_retry' => __( 'Connection setup could not finish. Retry Connect or start over.', 'aha-is-for-woocommerce' ), 'proof_pending' => __( 'Aha is verifying this website. Continue to check the result.', 'aha-is-for-woocommerce' ), 'callback_invalid' => __( 'The return from Aha could not be verified. No connection state was changed.', 'aha-is-for-woocommerce' ), 'callback_pending' => __( 'Aha has not recorded consent yet. Try the Aha sign-in step again.', 'aha-is-for-woocommerce' ), 'callback_failed' => __( 'Aha could not verify this connection attempt. Start over to try again.', 'aha-is-for-woocommerce' ), 'callback_review' => __( 'Aha reports that this request is waiting for review.', 'aha-is-for-woocommerce' ), 'attempt_expired' => __( 'This connection attempt can no longer continue. Start over to create a fresh attempt.', 'aha-is-for-woocommerce' ), 'login_used' => __( 'This connection attempt was already used on Aha. Start over to try again.', 'aha-is-for-woocommerce' ), 'reset_done' => __( 'The connection attempt was cleared. You can start again.', 'aha-is-for-woocommerce' ), 'send_retry' => __( 'Request could not be sent. Your details are kept. Try again.', 'aha-is-for-woocommerce' ), 'reconnect_retry' => __( 'Aha could not be reached. Try again.', 'aha-is-for-woocommerce' ), 'details_edited' => __( 'Details updated. Aha will review the new details.', 'aha-is-for-woocommerce' ), 'not_reviewable' => __( 'This request is no longer waiting for review.', 'aha-is-for-woocommerce' ), 'neutral_error' => __( 'The connection could not be updated. No sensitive details were displayed.', 'aha-is-for-woocommerce' ), 'retry_sync_started' => __( 'Product sync retry scheduled.', 'aha-is-for-woocommerce' ), 'product_sync_started' => __( 'Product sync started. Your products will update on aha.is shortly.', 'aha-is-for-woocommerce' ), 'product_sync_cooldown' => $this->cooldown_message(), 'product_sync_unavailable' => __( 'Product sync is not available right now. It will still run automatically every day.', 'aha-is-for-woocommerce' ), 'product_sync_paused' => __( 'Connection paused by Aha. Product sync is on hold; your connection and keys are kept.', 'aha-is-for-woocommerce' ), 'product_sync_failed' => __( 'Product sync could not be started. Try again later.', 'aha-is-for-woocommerce' ), ); $notice = isset( $notices[ $notice_code ] ) ? $notices[ $notice_code ] : ''; $error_codes = array( 'setup_retry', 'send_retry', 'reconnect_retry', 'callback_failed', 'callback_invalid', 'neutral_error', 'attempt_expired', 'login_used', 'setup_unavailable', 'safe_mode', 'product_sync_failed', 'product_sync_cooldown' ); $success_codes = array( 'details_edited', 'reset_done', 'retry_sync_started', 'product_sync_started' ); $notice_type = in_array( $notice_code, $error_codes, true ) ? 'error' : ( in_array( $notice_code, $success_codes, true ) ? 'success' : 'info' ); if ( 'connected' === $phase && empty( $view_state['read_only'] ) && 0 === func_num_args() && function_exists( 'get_transient' ) && function_exists( 'set_transient' ) ) { $transient = 'aha_is_woocommerce_connect_status_' . get_current_blog_id(); if ( false === get_transient( $transient ) ) { set_transient( $transient, 1, MINUTE_IN_SECONDS ); try { $checked = Aha_Is_Woocommerce_Connect_Credentials::connection_status(); if ( 'revoked' === $checked ) { $view_state = Aha_Is_Woocommerce_Connect_Flow::view_state(); $phase = $view_state['phase']; $model['account_status'] = __( 'not linked', 'aha-is-for-woocommerce' ); } elseif ( 'unavailable' === $checked ) { $notice = __( 'Could not check the connection right now.', 'aha-is-for-woocommerce' ); $notice_type = 'warning'; } } catch ( Throwable $error ) { $notice = __( 'Could not check the connection right now.', 'aha-is-for-woocommerce' ); $notice_type = 'warning'; } } } if ( 'access_revoked' === $phase ) { $notice = __( 'Aha access was removed. Connect again.', 'aha-is-for-woocommerce' ); $notice_type = 'warning'; } if ( 'connection_lost' === $phase ) { $notice = __( 'The connection to Aha was lost. Connect again to resume.', 'aha-is-for-woocommerce' ); $notice_type = 'warning'; } // Safe mode from a changed site address shows the state_unreadable screen; give it its own copy. $address_changed = 'state_unreadable' === $phase && Aha_Is_Woocommerce_Site_Identity::is_safe_mode() && 'site_url_changed' === Aha_Is_Woocommerce_Site_Identity::safe_mode_reason(); if ( 'state_unreadable' === $phase ) { $notice = $address_changed ? __( 'This website\'s address changed. The connection is paused.', 'aha-is-for-woocommerce' ) : __( 'Connect state could not be read.', 'aha-is-for-woocommerce' ); $notice_type = 'error'; } if ( 'expired_unresolved' === $phase && '' === $notice ) { $notice = $notices['attempt_expired']; $notice_type = 'error'; } $login_used = 'origin_verified' === $phase && ! empty( $view_state['login_used'] ); if ( $login_used ) { $notice = $notices['login_used']; $notice_type = 'error'; } $cleanup_pending = in_array( $phase, array( 'not_connected', 'access_revoked' ), true ) && Aha_Is_Woocommerce_Connect_Credentials::catalog_key_cleanup_pending(); $entry_phases = array( 'not_connected', 'prepared', 'proof_ready', 'origin_verified' ); $recovery_phases = array( 'access_revoked', 'connection_lost', 'expired_unresolved', 'state_unreadable' ); // A send failure gets its own screen only where a safe retry action exists. $retry_screen = ( 'send_retry' === $notice_code && 'consented' === $phase ) || ( 'reconnect_retry' === $notice_code && 'reconnect_available' === $phase ); if ( $retry_screen || in_array( $phase, $recovery_phases, true ) ) { $notice = ''; // Recovery screens carry their own warning callout. } echo '
'; echo '
' . esc_html__( 'WooCommerce · Plugins / Aha', 'aha-is-for-woocommerce' ) . '
'; echo '
'; if ( '' !== $notice ) { $notice_role = 'error' === $notice_type ? 'alert' : 'status'; // Own markup, not ".notice": WordPress moves ".notice" elements to after the first h2, into the store card. echo '

' . esc_html( $notice ) . '

'; } if ( ! empty( $view_state['read_only'] ) ) { $this->render_read_only( $view_state, $model['website'], $model['account_status'] ); echo '
'; return; } if ( 'connected' === $phase ) { $this->render_connected( isset( $view_state['connected'] ) && is_array( $view_state['connected'] ) ? $view_state['connected'] : array(), $model['website'], '' !== $notice ); echo ''; return; } $self_url = admin_url( 'admin.php?page=' . self::PAGE_SLUG ); if ( $retry_screen ) { $reconnect = 'reconnect_available' === $phase; $this->render_screen_open( __( 'Request could not be sent', 'aha-is-for-woocommerce' ), $reconnect ? __( 'The connector could not reach Aha, so the reconnect request was not confirmed. Your saved request was kept, so you can try again.', 'aha-is-for-woocommerce' ) : __( 'The connector could not reach Aha, so nothing was submitted and no store was created. Your store details were kept, so you can send the request again.', 'aha-is-for-woocommerce' ), true ); echo '
'; if ( $reconnect ) { $this->render_action_form( self::ACTION_RECONNECT, self::NONCE_RECONNECT, __( 'Try again', 'aha-is-for-woocommerce' ), 'aha-connect__primary' ); } else { $hidden = array(); foreach ( array( 'requested_target_kind', 'display_name', 'street_address', 'postcode', 'city', 'phone', 'description' ) as $field ) { $hidden[ $field ] = isset( $values[ $field ] ) && is_string( $values[ $field ] ) ? $values[ $field ] : ''; } $this->render_action_form( self::ACTION_DETAILS, self::NONCE_DETAILS, __( 'Try again', 'aha-is-for-woocommerce' ), 'aha-connect__primary', '', $hidden ); echo '' . esc_html__( 'Back to store details', 'aha-is-for-woocommerce' ) . ''; } echo '
'; } elseif ( in_array( $phase, $entry_phases, true ) ) { echo '
'; echo '

' . esc_html__( 'Aha connector', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Connect your website to Aha', 'aha-is-for-woocommerce' ) . '

'; printf( '

%1$s %2$s %3$s %4$s

', esc_html__( 'Website:', 'aha-is-for-woocommerce' ), esc_html( $model['website'] ), esc_html__( 'Aha account:', 'aha-is-for-woocommerce' ), esc_html( $model['account_status'] ) ); $this->render_cleanup_notice( $cleanup_pending ); echo '
    '; foreach ( $model['steps'] as $step ) { printf( '
  1. %1$s

    %2$s

  2. ', esc_html( $step['title'] ), esc_html( $step['body'] ) ); } echo '
'; // Aha may need a moment to verify; re-submit the Connect form up to MAX_AUTO_RECHECK times. $recheck = 0; // Only the server-side one-shot marker set by the Connect POST may trigger this; a GET param never does. if ( 'proof_pending' === $notice_code && function_exists( 'get_transient' ) ) { $marker = 'aha_is_woocommerce_connect_recheck_' . get_current_user_id(); $recheck = absint( get_transient( $marker ) ); delete_transient( $marker ); } $auto_recheck = $recheck >= 1 && $recheck <= self::MAX_AUTO_RECHECK; if ( $auto_recheck ) { echo ''; } echo '
'; if ( ! $login_used ) { $this->render_action_form( self::ACTION_CONNECT, self::NONCE_CONNECT, __( 'Connect with Aha', 'aha-is-for-woocommerce' ), 'aha-connect__primary', '', $auto_recheck ? array( 'aha_is_woocommerce_recheck' => (string) $recheck ) : array() ); } if ( in_array( $phase, array( 'prepared', 'proof_ready', 'origin_verified' ), true ) ) { $this->render_action_form( self::ACTION_RESET, self::NONCE_RESET, __( 'Start over', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); } echo '
'; } elseif ( in_array( $phase, $recovery_phases, true ) ) { $recovery = array( 'access_revoked' => array( __( 'Aha access was removed', 'aha-is-for-woocommerce' ), __( 'Connection removed', 'aha-is-for-woocommerce' ), __( 'Catalog selling is paused. Your store, settings and mapped orders are kept; connect again to resume.', 'aha-is-for-woocommerce' ) ), 'connection_lost' => array( __( 'Connection to Aha was lost', 'aha-is-for-woocommerce' ), __( 'Disconnected', 'aha-is-for-woocommerce' ), __( 'Aha could not confirm this website\'s link. Connect again to resume, or start over.', 'aha-is-for-woocommerce' ) ), 'expired_unresolved' => array( __( 'Connection attempt expired', 'aha-is-for-woocommerce' ), __( 'This attempt can no longer continue', 'aha-is-for-woocommerce' ), $notices['attempt_expired'] ), 'state_unreadable' => array( __( 'Connect state could not be read', 'aha-is-for-woocommerce' ), __( 'Saved state is unreadable', 'aha-is-for-woocommerce' ), __( 'Aha cannot read the saved connection state. Start over to connect again.', 'aha-is-for-woocommerce' ) ), ); if ( $address_changed ) { $recovery['state_unreadable'] = array( __( 'This website\'s address changed', 'aha-is-for-woocommerce' ), __( 'Connected at another address', 'aha-is-for-woocommerce' ), __( 'This site\'s address is different from the one that was connected to Aha, so the connection is paused. Start over to connect this address.', 'aha-is-for-woocommerce' ) ); } $ref = $address_changed ? 'REF-SITE-URL-CHANGED' : 'REF-' . strtoupper( str_replace( '_', '-', $phase ) ); echo '
'; echo '

' . esc_html__( 'WooCommerce · recovery', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html( $recovery[ $phase ][0] ) . '

'; echo '
' . esc_html( $recovery[ $phase ][1] ) . '

' . esc_html( $recovery[ $phase ][2] ) . '

' . esc_html( $ref ) . '
'; $this->render_cleanup_notice( $cleanup_pending ); echo '
'; if ( 'state_unreadable' === $phase ) { $this->render_action_form( self::ACTION_DISCARD, self::NONCE_DISCARD, __( 'Start over', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); echo '

' . esc_html__( 'Start over removes the saved Aha connection from this site. The site must connect again.', 'aha-is-for-woocommerce' ) . '

'; } else { if ( 'expired_unresolved' !== $phase ) { $this->render_action_form( self::ACTION_CONNECT, self::NONCE_CONNECT, __( 'Connect with Aha', 'aha-is-for-woocommerce' ), 'aha-connect__primary' ); } if ( in_array( $phase, array( 'connection_lost', 'expired_unresolved' ), true ) ) { $this->render_action_form( self::ACTION_RESET, self::NONCE_RESET, __( 'Start over', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); } } echo '
'; } elseif ( 'consented' === $phase ) { echo '
'; echo '

' . esc_html__( 'Step 2 of 3', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Tell Aha about your store', 'aha-is-for-woocommerce' ) . '

'; /* translators: %s: website URL. */ echo '

' . esc_html( sprintf( __( 'Website %s is verified. These details appear on your Aha store page. Nothing is published and no service is enabled yet.', 'aha-is-for-woocommerce' ), $model['website'] ) ) . '

'; $this->render_details_form( $values, $errors ); echo '
'; } elseif ( in_array( $phase, array( 'pending_review', 'returning_pending_review' ), true ) ) { $name = ''; if ( 'pending_review' === $phase && ! empty( $view_state['connected']['name'] ) ) { $name = $view_state['connected']['name']; } elseif ( ! empty( $view_state['returning']['display_name'] ) && is_string( $view_state['returning']['display_name'] ) ) { $name = $view_state['returning']['display_name']; } echo '
'; $this->render_store_card( $name, (string) wp_parse_url( (string) $model['website'], PHP_URL_HOST ), __( 'Waiting for Aha review', 'aha-is-for-woocommerce' ), 'aha-connect__pill--warn', __( 'Store awaiting review', 'aha-is-for-woocommerce' ) ); // The page polls Aha on every load, so a re-check is a plain reload. if ( 'pending_review' === $phase && empty( $view_state['read_only'] ) && ( $this->editing || ! empty( $_GET['aha_is_woocommerce_edit'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification -- read-only toggle, only tested for emptiness echo '

' . esc_html__( 'Edit your store details', 'aha-is-for-woocommerce' ) . '

'; $this->render_details_form( $values, $errors, self::ACTION_EDIT_DETAILS, self::NONCE_EDIT_DETAILS, __( 'Save changes', 'aha-is-for-woocommerce' ), $self_url ); echo '
'; } elseif ( 'pending_review' === $phase ) { $this->render_review_panel( '' . esc_html__( 'Check review status', 'aha-is-for-woocommerce' ) . ' ' . esc_html__( 'Edit details', 'aha-is-for-woocommerce' ) . '', isset( $view_state['submitted_at'] ) ? (int) $view_state['submitted_at'] : 0 ); } else { ob_start(); $this->render_action_form( self::ACTION_RECONNECT, self::NONCE_RECONNECT, __( 'Check review status', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); $this->render_review_panel( ob_get_clean() ); } echo '
'; } elseif ( 'reconnect_available' === $phase ) { $display_name = isset( $view_state['returning']['display_name'] ) && is_string( $view_state['returning']['display_name'] ) ? $view_state['returning']['display_name'] : ''; $sku = isset( $view_state['returning']['sku'] ) && is_string( $view_state['returning']['sku'] ) ? $view_state['returning']['sku'] : ''; echo '
'; echo '

' . esc_html__( 'WooCommerce · existing binding', 'aha-is-for-woocommerce' ) . '

'; /* translators: %s: store name. */ echo '

' . esc_html( sprintf( __( 'Reconnect %s', 'aha-is-for-woocommerce' ), $display_name ) ) . '

'; echo '

' . esc_html__( 'Catalog selling is paused while disconnected.', 'aha-is-for-woocommerce' ) . ' ' . esc_html( '' !== $sku /* translators: %s: store SKU. */ ? sprintf( __( 'Your store %s, settings and mapped orders are kept. Reconnecting resumes the same store; it never creates another.', 'aha-is-for-woocommerce' ), $sku ) : __( 'Your store, settings and mapped orders are kept. Reconnecting resumes the same store; it never creates another.', 'aha-is-for-woocommerce' ) ) . '

'; echo '
'; $this->render_action_form( self::ACTION_RECONNECT, self::NONCE_RECONNECT, __( 'Reconnect existing store', 'aha-is-for-woocommerce' ), 'aha-connect__primary' ); echo '
'; } elseif ( 'site_bound_to_other_account' === $phase ) { $this->render_screen_open( __( 'Website linked to another account', 'aha-is-for-woocommerce' ), __( 'This website is already linked to a different Aha account. Contact Aha support.', 'aha-is-for-woocommerce' ), true, true ); echo '
'; $this->render_action_form( self::ACTION_RESET, self::NONCE_RESET, __( 'Start over', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); echo '
'; } elseif ( 'reconnect_approved' === $phase ) { $this->render_screen_open( __( 'Reconnected to Aha', 'aha-is-for-woocommerce' ), __( 'Reconnected to Aha. Finishing setup…', 'aha-is-for-woocommerce' ), false, true ); echo ''; } elseif ( 'rejected' === $phase ) { $reason = isset( $view_state['reason'] ) && is_string( $view_state['reason'] ) && '' !== trim( $view_state['reason'] ) ? $view_state['reason'] : __( 'Aha did not approve this connection request.', 'aha-is-for-woocommerce' ); $this->render_screen_open( __( 'Connect request rejected', 'aha-is-for-woocommerce' ), $reason, true, true ); echo '
'; $this->render_action_form( self::ACTION_CONNECT, self::NONCE_CONNECT, __( 'Connect with Aha', 'aha-is-for-woocommerce' ), 'aha-connect__primary' ); echo '
'; } echo ''; } /** * Render the read-only status for a WordPress admin who does not own the connection. * No forms, no links that change state. * * @param array $view_state Read-only view state. * @param string $website Website URL. * @param string $status Status label. * @return void */ private function render_read_only( array $view_state, $website, $status ) { $connected = isset( $view_state['connected'] ) && is_array( $view_state['connected'] ) ? $view_state['connected'] : array(); echo '
'; echo '

' . esc_html__( 'WooCommerce · Aha connector', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Aha connection', 'aha-is-for-woocommerce' ) . '

'; printf( '

%1$s %2$s %3$s %4$s

', esc_html__( 'Website:', 'aha-is-for-woocommerce' ), esc_html( $website ), esc_html__( 'Aha account:', 'aha-is-for-woocommerce' ), esc_html( $status ) ); if ( 'connected' === $view_state['phase'] ) { $meta = array_filter( array( isset( $connected['name'] ) ? $connected['name'] : '', isset( $connected['sku'] ) ? $connected['sku'] : '' ) ); if ( $meta ) { echo '

' . esc_html( implode( ' · ', $meta ) ) . '

'; } } echo '

' . esc_html__( 'This connection is managed by another WordPress admin. Only that admin can change it.', 'aha-is-for-woocommerce' ) . '

'; echo '
'; } /** * Render the managed-key cleanup callout and its retry action. * * @param bool $cleanup_pending Whether a catalog key cleanup is pending. * @return void */ private function render_cleanup_notice( $cleanup_pending ) { if ( $cleanup_pending && Aha_Is_Woocommerce_Connect_Automation::catalog_key_paused() ) { echo '

' . esc_html__( 'Product sync cleanup paused', 'aha-is-for-woocommerce' ) . ' ' . esc_html__( 'The Aha-managed WooCommerce key was not removed. Retry to remove it.', 'aha-is-for-woocommerce' ) . '

'; $this->render_action_form( self::ACTION_RETRY_SYNC, self::NONCE_RETRY_SYNC, __( 'Retry product sync', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); } elseif ( $cleanup_pending ) { echo '

' . esc_html__( 'Product sync cleanup', 'aha-is-for-woocommerce' ) . ' ' . esc_html__( 'Removing the Aha-managed WooCommerce key. Cleanup will retry automatically.', 'aha-is-for-woocommerce' ) . '

'; } } /** * Open a centred status screen: optional icon, eyebrow, title and message. * The caller prints the actions and closes the container div. * * @param string $title Title. * @param string $message Plain-text message. * @param bool $icon Show the red "!" icon. * @param bool $status Announce the message as a status. * @return void */ private function render_screen_open( $title, $message, $icon = false, $status = false ) { echo '
'; if ( $icon ) { echo ''; } echo '

' . esc_html__( 'WooCommerce · Aha connector', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html( $title ) . '

'; echo '

' . esc_html( $message ) . '

'; } /** * Render the store card shared by the waiting and connected screens. * * @param string $name Store name, may be empty. * @param string $meta Meta line. * @param string $pill Pill text. * @param string $pill_class Pill modifier class. * @param string $eyebrow Eyebrow text. * @param string $last Optional last-contact text. * @param string $note Optional extra line under the meta. * @return void */ private function pill( $text, $class = '' ) { return '' . esc_html( $text ) . ''; } private function render_store_card( $name, $meta, $pill, $pill_class, $eyebrow, $last = '', $note = '', $url = '' ) { echo '

' . esc_html( $eyebrow ) . '

'; if ( '' !== $name ) { echo '

' . esc_html( $name ) . '

'; } echo '

' . esc_html( $meta ) . '

'; if ( '' !== $note ) { echo '

' . esc_html( $note ) . '

'; } echo '
'; echo '
' . $this->pill( $pill, $pill_class ); // phpcs:ignore WordPress.Security.EscapeOutput -- pill() escapes its text and class if ( '' !== $last ) { echo '

' . esc_html( $last ) . '

'; } if ( '' !== $url ) { echo '' . esc_html__( 'View store on aha.is', 'aha-is-for-woocommerce' ) . ' ' . esc_html__( '(opens in a new tab)', 'aha-is-for-woocommerce' ) . ''; } echo '
'; } /** * Count mapped Aha orders from the plugin order map. Returns null when unreadable. * * @return array|null Keys: mapped, pending, failed. */ private function order_counts() { global $wpdb; if ( ! class_exists( 'Aha_Is_Woocommerce_Order_Map' ) || ! isset( $wpdb ) || ! is_object( $wpdb ) || ! method_exists( $wpdb, 'get_results' ) ) { return null; } $rows = $wpdb->get_results( 'SELECT status, COUNT(*) AS total FROM `' . esc_sql( Aha_Is_Woocommerce_Order_Map::table_name() ) . '` GROUP BY status', ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- own table, esc_sql'd, no user input; admin counts must be live. if ( ! is_array( $rows ) ) { return null; } $by_status = array(); foreach ( $rows as $row ) { if ( isset( $row['status'], $row['total'] ) ) { $by_status[ $row['status'] ] = (int) $row['total']; } } $get = function ( $status ) use ( $by_status ) { return isset( $by_status[ $status ] ) ? $by_status[ $status ] : 0; }; return array( 'mapped' => $get( Aha_Is_Woocommerce_Order_Map::STATUS_CREATED ), 'pending' => $get( Aha_Is_Woocommerce_Order_Map::STATUS_CLAIMED ), 'failed' => $get( Aha_Is_Woocommerce_Order_Map::STATUS_FAILED ), ); } /** * URL of a tab on this page. * * @param string $tab Tab name. * @return string */ private static function tab_url( $tab ) { return admin_url( 'admin.php?page=' . self::PAGE_SLUG . '&tab=' . $tab ); } /** * Render the Mapped/Pending/Failed counts, when the order map is readable. * * @param bool $link Add the link to the Orders tab. * @return void */ private function render_order_counts( $link ) { $counts = $this->order_counts(); if ( null === $counts ) { return; } echo '

' . esc_html__( 'Orders', 'aha-is-for-woocommerce' ) . '

'; echo '
'; foreach ( array( 'mapped' => __( 'Mapped orders', 'aha-is-for-woocommerce' ), 'pending' => __( 'Pending sync', 'aha-is-for-woocommerce' ), 'failed' => __( 'Failed', 'aha-is-for-woocommerce' ), ) as $key => $label ) { echo '
' . esc_html( (string) $counts[ $key ] ) . '' . esc_html( $label ) . '
'; } if ( $link ) { echo '' . esc_html__( 'View orders →', 'aha-is-for-woocommerce' ) . ''; } echo '
'; } /** * Format a time like "10 September 2026 at 12:44" or "10 Sep, 12:44". */ private static function when( $time, $format = 'j M, H:i' ) { return function_exists( 'wp_date' ) ? wp_date( $format, $time ) : gmdate( $format, $time ); } /** * Render a sketch facts grid. * * @param array $facts Label => value. * @return void */ private function render_facts( array $facts ) { echo '
'; foreach ( $facts as $label => $value ) { echo '
' . esc_html( $label ) . '
' . esc_html( $value ) . '
'; } echo '
'; } /** * Render the Orders tab: facts grid and the 20 most recently updated mapped orders. * * @param string $sku Store SKU, empty when unknown. * @param string $name Store name, empty when unknown. * @return void */ private function render_orders_tab( $sku = '', $name = '' ) { echo '

' . esc_html__( 'Order sync', 'aha-is-for-woocommerce' ) . '

'; $this->render_orders_refresh(); echo '

' . ( '' !== $sku /* translators: %s: store SKU. */ ? sprintf( esc_html__( 'Each WooCommerce order maps to exactly one Aha order on stable store %s.', 'aha-is-for-woocommerce' ), '' . esc_html( $sku ) . '' ) : esc_html__( 'Each WooCommerce order maps to exactly one Aha order.', 'aha-is-for-woocommerce' ) ) . '

'; $counts = $this->order_counts(); $last = (int) get_option( 'aha_is_woocommerce_connect_last_contact', 0 ); $this->render_facts( array( __( 'Order sync', 'aha-is-for-woocommerce' ) => null === $counts ? __( 'Unknown', 'aha-is-for-woocommerce' ) /* translators: %d: number of orders. */ : ( $counts['failed'] > 0 /* translators: %d: number of failed orders. */ ? sprintf( __( '%d failed', 'aha-is-for-woocommerce' ), $counts['failed'] ) : ( $counts['pending'] > 0 /* translators: %d: number of pending orders. */ ? sprintf( __( '%d pending', 'aha-is-for-woocommerce' ), $counts['pending'] ) : __( 'All synced', 'aha-is-for-woocommerce' ) ) ), __( 'Last checked', 'aha-is-for-woocommerce' ) => $last > 0 ? self::when( $last ) : __( 'Not checked yet', 'aha-is-for-woocommerce' ), __( 'Mapped orders', 'aha-is-for-woocommerce' ) => null === $counts ? '—' : (string) $counts['mapped'], __( 'Failed', 'aha-is-for-woocommerce' ) => null === $counts ? '—' : (string) $counts['failed'], ) ); // No "Sync pending orders" button: the plugin has no order-retry handler (only product sync). // Whitelist: only "failed" is accepted. The filter queries failed rows directly, still capped at 20. $failed_only = isset( $_GET['aha_is_woocommerce_status'] ) && is_string( $_GET['aha_is_woocommerce_status'] ) && 'failed' === wp_unslash( $_GET['aha_is_woocommerce_status'] ); // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- read-only view filter, compared to the literal failed $rows = ( class_exists( 'Aha_Is_Woocommerce_Order_Map' ) && null !== $counts ) ? Aha_Is_Woocommerce_Order_Map::recent( 20, $failed_only ? Aha_Is_Woocommerce_Order_Map::STATUS_FAILED : '' ) : array(); if ( $failed_only ) { echo '

' . esc_html__( 'Showing failed orders only', 'aha-is-for-woocommerce' ) . ' · ' . esc_html__( 'Show all', 'aha-is-for-woocommerce' ) . '

'; } if ( ! $rows ) { echo '

' . esc_html( $failed_only ? __( 'No failed orders.', 'aha-is-for-woocommerce' ) : __( 'No Aha orders have reached this store yet.', 'aha-is-for-woocommerce' ) ) . '

'; return; } $statuses = array( Aha_Is_Woocommerce_Order_Map::STATUS_CREATED => array( __( 'Synced', 'aha-is-for-woocommerce' ), '' ), Aha_Is_Woocommerce_Order_Map::STATUS_CLAIMED => array( __( 'Pending', 'aha-is-for-woocommerce' ), 'aha-connect__pill--warn' ), Aha_Is_Woocommerce_Order_Map::STATUS_FAILED => array( __( 'Failed', 'aha-is-for-woocommerce' ), 'aha-connect__pill--error' ), ); $hpos = Aha_Is_Woocommerce_Order_Map::hpos_enabled(); echo '
'; foreach ( array( __( 'Order ID', 'aha-is-for-woocommerce' ), __( 'Aha order', 'aha-is-for-woocommerce' ), __( 'Sync', 'aha-is-for-woocommerce' ), __( 'Updated', 'aha-is-for-woocommerce' ) ) as $heading ) { echo ''; } echo ''; foreach ( $rows as $row ) { $wc_id = isset( $row['wc_order_id'] ) ? (int) $row['wc_order_id'] : 0; $status = isset( $row['status'], $statuses[ $row['status'] ] ) ? $statuses[ $row['status'] ] : array( __( 'Pending', 'aha-is-for-woocommerce' ), 'aha-connect__pill--warn' ); $when = ''; $time = isset( $row['updated_at'] ) ? strtotime( (string) $row['updated_at'] . ' UTC' ) : false; if ( $time ) { $when = self::when( $time ); } $aha_is_woocommerce_id = isset( $row['aha_order_id'] ) ? (string) $row['aha_order_id'] : ''; $shown = $this->customer_order_number( $wc_id, $aha_is_woocommerce_id ); // One wc_get_order per displayed row; recent() caps the list at 20. $edit_url = $wc_id > 0 ? admin_url( $hpos ? 'admin.php?page=wc-orders&action=edit&id=' . $wc_id : 'post.php?post=' . $wc_id . '&action=edit' ) : ''; $label = $wc_id > 0 /* translators: %d: WooCommerce order number. */ ? sprintf( __( 'Open order #%d detail', 'aha-is-for-woocommerce' ), $wc_id ) : __( 'Open order detail', 'aha-is-for-woocommerce' ); echo ''; echo ''; // phpcs:ignore WordPress.Security.EscapeOutput -- pill() escapes its text and class echo ''; } echo '
' . esc_html( $heading ) . '
'; if ( $wc_id > 0 ) { echo '#' . esc_html( (string) $wc_id ) . ''; } else { echo '—'; } echo ''; $this->render_order_detail( $row, $wc_id, $aha_is_woocommerce_id, $shown, $status, $when, $sku, $name ); echo '' . esc_html( $shown ) . '' . $this->pill( $status[0], $status[1] ) . '' . esc_html( $when ) . '
'; echo ''; } /** * Customer-facing Aha order number from the WooCommerce order meta, falling back to the internal id. * * @param int $wc_id WooCommerce order ID, 0 when unmapped. * @param string $aha_is_woocommerce_id Internal Aha order id. * @return string */ private function failed_order_ref( array $row ) { $wc_id = ! empty( $row['wc_order_id'] ) ? (int) $row['wc_order_id'] : 0; if ( $wc_id > 0 ) { /* translators: %d: order number. */ return sprintf( __( 'Order #%d', 'aha-is-for-woocommerce' ), $wc_id ); } $aha_is_woocommerce_id = isset( $row['aha_order_id'] ) ? (string) $row['aha_order_id'] : ''; /* translators: %s: Aha order reference. */ return '' !== $aha_is_woocommerce_id ? sprintf( __( 'Aha order %s', 'aha-is-for-woocommerce' ), $aha_is_woocommerce_id ) : __( 'Order', 'aha-is-for-woocommerce' ); } private function customer_order_number( $wc_id, $aha_is_woocommerce_id ) { if ( $wc_id > 0 && function_exists( 'wc_get_order' ) && class_exists( 'Aha_Is_Woocommerce_Order_Factory' ) ) { $order = wc_get_order( $wc_id ); if ( is_object( $order ) && method_exists( $order, 'get_meta' ) ) { $number = $order->get_meta( Aha_Is_Woocommerce_Order_Factory::META_INCREMENT_ID ); if ( is_scalar( $number ) && '' !== trim( (string) $number ) ) { return (string) $number; } } } return $aha_is_woocommerce_id; } /** * Render the Refresh link. It only reloads the Orders tab; it never retries or resends anything. * * @return void */ private function render_orders_refresh() { echo '' . esc_html__( 'Refresh', 'aha-is-for-woocommerce' ) . ''; } /** * Render one hidden per-row template; the page script copies it into the shared dialog. * * @param array $row Order map row. * @param int $wc_id WooCommerce order ID, 0 when unmapped. * @param string $aha_is_woocommerce_id Internal Aha order id. * @param string $shown Customer-facing Aha order number. * @param array $status Pill text and class. * @param string $when Formatted updated time. * @param string $sku Store SKU. * @param string $name Store name. * @return void */ private function render_order_detail( array $row, $wc_id, $aha_is_woocommerce_id, $shown, array $status, $when, $sku, $name ) { $state = isset( $row['status'] ) ? (string) $row['status'] : ''; $error = ( Aha_Is_Woocommerce_Order_Map::STATUS_FAILED === $state && ! empty( $row['error_code'] ) ) ? (string) $row['error_code'] : ''; $ref = $wc_id > 0 ? '#' . $wc_id : '—'; $sub = trim( $name . ( '' !== $name && '' !== $sku ? ' · ' : '' ) . $sku ); $steps = array( array( 'done', __( 'Order received from Aha', 'aha-is-for-woocommerce' ), '' ) ); if ( Aha_Is_Woocommerce_Order_Map::STATUS_CREATED === $state ) { /* translators: %s: WooCommerce order number. */ $steps[] = array( 'done', sprintf( __( 'Mapped to WooCommerce order %s', 'aha-is-for-woocommerce' ), $ref ), __( 'One-to-one, idempotent', 'aha-is-for-woocommerce' ) ); $steps[] = array( 'done', __( 'Synced', 'aha-is-for-woocommerce' ), $when ); } elseif ( Aha_Is_Woocommerce_Order_Map::STATUS_FAILED === $state ) { if ( $wc_id > 0 ) { /* translators: %s: WooCommerce order number. */ $steps[] = array( 'done', sprintf( __( 'Mapped to WooCommerce order %s', 'aha-is-for-woocommerce' ), $ref ), __( 'One-to-one, idempotent', 'aha-is-for-woocommerce' ) ); } /* translators: %s: error reference code. */ $steps[] = array( 'now', __( 'Sync failed', 'aha-is-for-woocommerce' ), '' !== $error ? sprintf( __( 'Error reference: %s', 'aha-is-for-woocommerce' ), $error ) : '' ); } else { $steps[] = array( 'now', __( 'Waiting to sync', 'aha-is-for-woocommerce' ), '' ); } $facts = array( __( 'Order ID', 'aha-is-for-woocommerce' ) => esc_html( $ref ), __( 'Aha order', 'aha-is-for-woocommerce' ) => esc_html( $shown ), __( 'Sync', 'aha-is-for-woocommerce' ) => $this->pill( $status[0], $status[1] ), __( 'Updated', 'aha-is-for-woocommerce' ) => esc_html( $when ), ); if ( $shown !== $aha_is_woocommerce_id && '' !== $aha_is_woocommerce_id ) { $facts[ __( 'Aha internal id', 'aha-is-for-woocommerce' ) ] = esc_html( $aha_is_woocommerce_id ); } if ( '' !== $error ) { $facts[ __( 'Error reference', 'aha-is-for-woocommerce' ) ] = esc_html( $error ); } echo ''; } /** * Render the Diagnostics tab: facts, connection check and sanitized export. * * @param array $connected Connected store name and SKU. * @return void */ private function render_diagnostics_tab( array $connected, $has_notice = false ) { $queue = Aha_Is_Woocommerce_Health::queue(); $last = (int) get_option( 'aha_is_woocommerce_connect_last_contact', 0 ); $cron = defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON; $as = (bool) $queue['action_scheduler_available']; $wc = function_exists( 'WC' ) && is_object( WC() ) && isset( WC()->version ) ? (string) WC()->version : ( defined( 'WC_VERSION' ) ? WC_VERSION : '' ); $counts = $this->order_counts(); $failed_orders = ( class_exists( 'Aha_Is_Woocommerce_Order_Map' ) && null !== $counts ) ? Aha_Is_Woocommerce_Order_Map::recent( 5, Aha_Is_Woocommerce_Order_Map::STATUS_FAILED ) : array(); $error = ''; foreach ( $failed_orders as $row ) { if ( ! empty( $row['error_code'] ) ) { $error = (string) $row['error_code']; break; } } $jobs = $this->failed_jobs( 5 ); $lag_limit = 900; // Seconds. A due job waiting longer than 15 minutes means the queue is not being run. $lagging = (int) $queue['lag_seconds'] > $lag_limit; // Each check: state (true ok, false problem, null informational), label, detail, optional link array( text, url ). $checks = array(); $checks[] = array( $last > 0 ? true : null, __( 'Connection to Aha', 'aha-is-for-woocommerce' ), /* translators: %s: date and time. */ $last > 0 ? sprintf( __( 'Last checked %s', 'aha-is-for-woocommerce' ), self::when( $last ) ) : __( 'Not checked yet', 'aha-is-for-woocommerce' ), null, ); if ( null === $counts ) { $checks[] = array( null, __( 'Orders from Aha', 'aha-is-for-woocommerce' ), __( 'Order counts cannot be read.', 'aha-is-for-woocommerce' ), null ); } elseif ( $counts['failed'] > 0 ) { $newest = $failed_orders ? $failed_orders[0] : array(); $ref = ''; if ( $newest ) { $ref = ' ' . $this->failed_order_ref( $newest ) . ( ! empty( $newest['error_code'] ) ? ' ' . $newest['error_code'] : '' ); } $checks[] = array( false, __( 'Orders from Aha', 'aha-is-for-woocommerce' ), /* translators: %d: number of failed orders. */ sprintf( _n( '%d order failed to sync.', '%d orders failed to sync.', $counts['failed'], 'aha-is-for-woocommerce' ), $counts['failed'] ) /* translators: %s: order number and error reference. */ . ( '' !== trim( $ref ) ? ' ' . sprintf( __( 'Newest:%s', 'aha-is-for-woocommerce' ), $ref ) : '' ), array( __( 'View in Orders', 'aha-is-for-woocommerce' ), self::tab_url( 'orders' ) . '&aha_is_woocommerce_status=failed' ), ); } else { $checks[] = array( true, __( 'Orders from Aha', 'aha-is-for-woocommerce' ), __( 'No failed orders.', 'aha-is-for-woocommerce' ), null ); } if ( ! $as ) { $checks[] = array( null, __( 'Updates to Aha', 'aha-is-for-woocommerce' ), __( 'Not available without Action Scheduler.', 'aha-is-for-woocommerce' ), null ); } else { $detail = sprintf( /* translators: 1: failed jobs, 2: pending jobs. */ __( '%1$d failed, %2$d waiting.', 'aha-is-for-woocommerce' ), (int) $queue['failed'], (int) $queue['pending'] ); if ( $lagging ) { /* translators: %d: minutes. */ $detail .= ' ' . sprintf( __( 'The oldest due update has waited %d min.', 'aha-is-for-woocommerce' ), (int) floor( $queue['lag_seconds'] / 60 ) ); } $checks[] = array( ( $queue['failed'] > 0 || $lagging ) ? false : true, __( 'Updates to Aha', 'aha-is-for-woocommerce' ), $detail, $queue['failed'] > 0 ? array( __( 'View failed jobs', 'aha-is-for-woocommerce' ), admin_url( 'admin.php?page=wc-status&tab=action-scheduler&status=failed&s=aha_is_woocommerce_push' ) ) : null, ); } // Judge real job health, not DISABLE_WP_CRON: without a server cron WP-Cron still runs jobs on site visits. $jobs_link = null; if ( ! $as ) { $jobs_ok = false; $jobs_detail = __( 'Action Scheduler is missing.', 'aha-is-for-woocommerce' ) . ' ' . __( 'Aha order and stock updates cannot be queued without it.', 'aha-is-for-woocommerce' ); } elseif ( $lagging ) { $jobs_ok = false; /* translators: %d: minutes. */ $jobs_detail = sprintf( __( 'Aha background jobs are waiting (oldest %d min). Ask your host to run WP-Cron from the server.', 'aha-is-for-woocommerce' ), (int) floor( $queue['lag_seconds'] / 60 ) ); $jobs_link = array( __( 'View pending jobs', 'aha-is-for-woocommerce' ), admin_url( 'admin.php?page=wc-status&tab=action-scheduler&status=pending&s=aha' ) ); } else { $jobs_ok = true; $jobs_detail = __( 'Background jobs are running.', 'aha-is-for-woocommerce' ); if ( ! $cron ) { $jobs_detail .= ' ' . __( 'Jobs run when the site gets visits. On a quiet site, ask your host to run WP-Cron every minute.', 'aha-is-for-woocommerce' ); } } $checks[] = array( $jobs_ok, __( 'Background jobs', 'aha-is-for-woocommerce' ), $jobs_detail, $jobs_link ); $checks[] = array( null, __( 'Versions', 'aha-is-for-woocommerce' ), /* translators: 1: plugin version, 2: WooCommerce version, 3: contract version. */ sprintf( __( 'Plugin %1$s · WooCommerce %2$s · Contract %3$s', 'aha-is-for-woocommerce' ), AHA_IS_WOOCOMMERCE_PLUGIN_VERSION, '' !== $wc ? $wc : __( 'unknown', 'aha-is-for-woocommerce' ), Aha_Is_Woocommerce_Contract::VERSION ), null, ); $problems = 0; foreach ( $checks as $check ) { if ( false === $check[0] ) { ++$problems; } } echo '

' . esc_html__( 'Diagnostics', 'aha-is-for-woocommerce' ) . '

'; Aha_Is_Woocommerce_Admin_Page::render_test_button( 'diagnostics' ); echo '

' . esc_html__( 'Version, compatibility and connection details for support. No secrets are shown.', 'aha-is-for-woocommerce' ) . '

'; if ( ! $has_notice ) { Aha_Is_Woocommerce_Admin_Page::render_notice( true ); } echo '

' . ( 0 === $problems ? $this->pill( __( 'All checks passed', 'aha-is-for-woocommerce' ), '' ) // phpcs:ignore WordPress.Security.EscapeOutput -- pill() escapes its text and class /* translators: %d: number of problems. */ : $this->pill( sprintf( _n( '%d problem needs attention', '%d problems need attention', $problems, 'aha-is-for-woocommerce' ), $problems ), 'aha-connect__pill--error' ) ) . '

'; // phpcs:ignore WordPress.Security.EscapeOutput -- pill() escapes its text and class echo ''; // Recent problems: failed mapped orders and failed Aha jobs, newest first, max 5. References only. $problem_rows = array(); foreach ( $failed_orders as $row ) { $ts = isset( $row['updated_at'] ) ? strtotime( (string) $row['updated_at'] . ' UTC' ) : false; $problem_rows[] = array( 'time' => $ts ? (int) $ts : 0, 'text' => $this->failed_order_ref( $row ) . ( ! empty( $row['error_code'] ) ? ' · ' . $row['error_code'] : '' ), ); } foreach ( $jobs as $job ) { $problem_rows[] = array( 'time' => $job['time'], 'text' => $job['label'] . ( '' !== $job['message'] ? ' · ' . $job['message'] : '' ), ); } if ( $problem_rows ) { usort( $problem_rows, function ( $a, $b ) { return $b['time'] <=> $a['time']; } ); echo '

' . esc_html__( 'Recent problems', 'aha-is-for-woocommerce' ) . '

'; } echo ''; // Sanitized: no tokens, keys or secrets are ever added to this array. $export = array( 'plugin_version' => AHA_IS_WOOCOMMERCE_PLUGIN_VERSION, 'woocommerce_version' => $wc, 'site_url' => Aha_Is_Woocommerce_Site_Identity::site_url_for_payload(), 'site_url_at_install' => Aha_Is_Woocommerce_Site_Identity::stored_site_url(), 'install_uuid' => Aha_Is_Woocommerce_Site_Identity::install_uuid(), 'environment' => Aha_Is_Woocommerce_Site_Identity::environment_type(), 'contract_version' => Aha_Is_Woocommerce_Contract::VERSION, 'action_scheduler' => $as ? 'available' : 'missing', 'queue_pending' => (int) $queue['pending'], 'queue_failed' => (int) $queue['failed'], 'queue_lag_seconds' => (int) $queue['lag_seconds'], 'real_server_cron' => $cron ? 'configured' : 'not configured', 'product_sync_enabled' => (bool) Aha_Is_Woocommerce_Settings::is_product_sync_enabled(), 'store_sku' => isset( $connected['sku'] ) ? (string) $connected['sku'] : '', 'store_name' => isset( $connected['name'] ) ? (string) $connected['name'] : '', 'last_contact' => $last > 0 ? gmdate( 'c', $last ) : null, 'last_product_sync' => ! empty( $connected['last_product_sync'] ) ? gmdate( 'c', (int) $connected['last_product_sync'] ) : null, 'safe_error_reference' => '' !== $error ? $error : null, ); $json = wp_json_encode( $export, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ); echo '
' . esc_html__( 'Support export (JSON)', 'aha-is-for-woocommerce' ) . ''; echo '
' . esc_html( $json ) . '
'; echo '

' . esc_html__( 'Download JSON', 'aha-is-for-woocommerce' ) . ' ' . '

'; } /** * Newest failed Aha Action Scheduler jobs, with a short sanitized failure note. One bounded query. * * @param int $limit Maximum jobs. * @return array[] Each: time (int), label (string), message (string, max ~120 chars, no URLs). */ private function failed_jobs( $limit ) { if ( ! function_exists( 'as_get_scheduled_actions' ) || ! class_exists( 'Aha_Is_Woocommerce_Connect_Automation' ) ) { return array(); } $labels = array( Aha_Is_Woocommerce_Connect_Automation::HOOK_POLL => __( 'Connection check', 'aha-is-for-woocommerce' ), Aha_Is_Woocommerce_Connect_Automation::HOOK_POLL_RETRY => __( 'Connection check', 'aha-is-for-woocommerce' ), Aha_Is_Woocommerce_Connect_Automation::HOOK_REFRESH => __( 'Connection refresh', 'aha-is-for-woocommerce' ), Aha_Is_Woocommerce_Connect_Automation::HOOK_REFRESH_RETRY => __( 'Connection refresh', 'aha-is-for-woocommerce' ), Aha_Is_Woocommerce_Connect_Automation::HOOK_CATALOG_KEY => __( 'Catalog access setup', 'aha-is-for-woocommerce' ), ); $actions = as_get_scheduled_actions( array( 'group' => Aha_Is_Woocommerce_Connect_Automation::GROUP, 'status' => 'failed', 'per_page' => max( 1, (int) $limit ), 'orderby' => 'date', 'order' => 'DESC', ) ); $out = array(); if ( ! is_array( $actions ) ) { return $out; } foreach ( $actions as $id => $action ) { if ( ! is_object( $action ) ) { continue; } $hook = method_exists( $action, 'get_hook' ) ? (string) $action->get_hook() : ''; $time = 0; $text = ''; try { if ( class_exists( 'ActionScheduler' ) && method_exists( 'ActionScheduler', 'logger' ) ) { $logs = ActionScheduler::logger()->get_logs( $id ); $log = is_array( $logs ) ? end( $logs ) : false; if ( is_object( $log ) ) { $text = method_exists( $log, 'get_message' ) ? (string) $log->get_message() : ''; $date = method_exists( $log, 'get_date' ) ? $log->get_date() : null; $time = $date instanceof DateTimeInterface ? $date->getTimestamp() : 0; } } if ( ! $time && method_exists( $action, 'get_schedule' ) ) { $schedule = $action->get_schedule(); $date = $schedule && method_exists( $schedule, 'get_date' ) ? $schedule->get_date() : null; $time = $date instanceof DateTimeInterface ? $date->getTimestamp() : 0; } } catch ( Throwable $error ) { $text = ''; } $text = preg_replace( '#https?://\S+#i', '[link]', $text ); $text = trim( preg_replace( '/[\x00-\x1F\x7F\s]+/', ' ', (string) $text ) ); $text = function_exists( 'mb_substr' ) ? mb_substr( $text, 0, 120 ) : substr( $text, 0, 120 ); $out[] = array( 'time' => (int) $time, 'label' => isset( $labels[ $hook ] ) ? $labels[ $hook ] : __( 'Aha update', 'aha-is-for-woocommerce' ), 'message' => $text, ); } return $out; } /** * Render the connected-store card, tabs, services and order counts. * * @param array $connected Connected store name and SKU. * @param string $website Website URL. * @param bool $has_notice Whether the Connect notice already showed above. * @return void */ private function render_connected( array $connected, $website, $has_notice = false ) { $tab = isset( $_GET['tab'] ) ? self::sanitize_tab( wp_unslash( $_GET['tab'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- read-only view parameter, whitelisted by sanitize_tab() $tab = '' === $tab ? 'overview' : $tab; $host = (string) wp_parse_url( (string) $website, PHP_URL_HOST ); $meta = array_filter( array( __( 'Store', 'aha-is-for-woocommerce' ), $host, isset( $connected['sku'] ) ? $connected['sku'] : '' ) ); $sync_paused = false; $sync_ready = false; $sync_on = false; $sync_class = 'aha-connect__pill--warn'; if ( Aha_Is_Woocommerce_Connect_Credentials::catalog_key_registered() ) { $store_state = isset( $connected['state'] ) ? $connected['state'] : 'waiting'; if ( 'live' === $store_state ) { $product_sync = __( 'Your store is live on Aha.', 'aha-is-for-woocommerce' ); $sync_pill = __( 'On', 'aha-is-for-woocommerce' ); $sync_on = true; $sync_ready = true; $sync_class = ''; } elseif ( 'needs_attention' === $store_state ) { $reason = 'no_products' === ( isset( $connected['attention'] ) ? $connected['attention'] : '' ) ? __( 'no products were found', 'aha-is-for-woocommerce' ) : __( 'the import failed', 'aha-is-for-woocommerce' ); /* translators: %s: reason the import failed. */ $product_sync = sprintf( __( 'Your products could not be imported: %s. Fix the problem and press Retry.', 'aha-is-for-woocommerce' ), $reason ); $sync_pill = __( 'Needs attention', 'aha-is-for-woocommerce' ); $sync_ready = true; } else { $product_sync = __( 'Approved. Aha is setting up your store and importing your products. Your store goes live when Aha finishes the setup.', 'aha-is-for-woocommerce' ); $sync_pill = __( 'Setting up', 'aha-is-for-woocommerce' ); $sync_class = 'aha-connect__pill--neutral'; } } elseif ( Aha_Is_Woocommerce_Connect_Credentials::catalog_key_owner_lost() ) { $product_sync = __( 'Product sync: paused — the WordPress admin who connected this store no longer has access. Open Settings, choose Disconnect from Aha, then connect again to resume product sync.', 'aha-is-for-woocommerce' ); $sync_pill = __( 'Paused', 'aha-is-for-woocommerce' ); } elseif ( Aha_Is_Woocommerce_Connect_Automation::catalog_key_paused() ) { $product_sync = __( 'Product sync: repair paused', 'aha-is-for-woocommerce' ); $sync_pill = __( 'Paused', 'aha-is-for-woocommerce' ); $sync_paused = true; } elseif ( Aha_Is_Woocommerce_Connect_Credentials::catalog_key_repairing() ) { $product_sync = __( 'Product sync: repairing', 'aha-is-for-woocommerce' ); $sync_pill = __( 'Repairing', 'aha-is-for-woocommerce' ); } else { $product_sync = __( 'Product sync: not set up yet', 'aha-is-for-woocommerce' ); $sync_pill = __( 'Not set up', 'aha-is-for-woocommerce' ); $sync_class = 'aha-connect__pill--neutral'; } $aha_is_woocommerce_paused = Aha_Is_Woocommerce_Connect_Credentials::paused_at(); // "Last synced" shows only while the card is On or Paused by Aha. $show_synced = false !== $aha_is_woocommerce_paused || $sync_on; if ( false !== $aha_is_woocommerce_paused ) { $sync_ready = false; $sync_paused = false; $sync_pill = __( 'Paused', 'aha-is-for-woocommerce' ); $sync_class = 'aha-connect__pill--warn'; $product_sync = __( 'Connection paused by Aha', 'aha-is-for-woocommerce' ); if ( $aha_is_woocommerce_paused > 0 ) { /* translators: %s: date and time. */ $product_sync = sprintf( __( 'Connection paused by Aha since %s', 'aha-is-for-woocommerce' ), self::when( $aha_is_woocommerce_paused ) ); } } $last_synced = ''; if ( $show_synced ) { $last_synced = ! empty( $connected['last_product_sync'] ) /* translators: %s: date and time. */ ? sprintf( __( 'Last synced %s', 'aha-is-for-woocommerce' ), self::when( (int) $connected['last_product_sync'] ) ) : __( 'Not synced yet', 'aha-is-for-woocommerce' ); } $last_contact = ''; $last = (int) get_option( 'aha_is_woocommerce_connect_last_contact', 0 ); if ( $last > 0 ) { $when = self::when( $last ); /* translators: %s: date and time. */ $last_contact = sprintf( __( 'Last checked %s', 'aha-is-for-woocommerce' ), $when ); } echo '
'; echo ''; $sku = isset( $connected['sku'] ) ? (string) $connected['sku'] : ''; if ( 'orders' === $tab ) { $this->render_orders_tab( $sku, isset( $connected['name'] ) ? (string) $connected['name'] : '' ); echo '
'; return; } if ( 'settings' === $tab || 'diagnostics' === $tab ) { if ( 'settings' === $tab ) { echo '

' . esc_html__( 'Sync', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Choose what this store sends to Aha.', 'aha-is-for-woocommerce' ) . '

'; if ( ! $has_notice ) { Aha_Is_Woocommerce_Admin_Page::render_notice( true ); } Aha_Is_Woocommerce_Admin_Page::render_settings( $tab ); $this->render_danger_zone( $sku ); } else { $this->render_diagnostics_tab( $connected, $has_notice ); } echo '
'; return; } $this->render_store_card( isset( $connected['name'] ) ? (string) $connected['name'] : '', implode( ' · ', $meta ), __( 'Linked', 'aha-is-for-woocommerce' ), '', __( 'Connected store', 'aha-is-for-woocommerce' ), $last_contact, __( 'Orders placed on Aha sync to this store.', 'aha-is-for-woocommerce' ), isset( $connected['url'] ) && is_string( $connected['url'] ) ? $connected['url'] : '' ); echo '

' . esc_html__( 'Services', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Catalog selling', 'aha-is-for-woocommerce' ) . '

' . $this->pill( $sync_pill, $sync_class ) . '
' // phpcs:ignore WordPress.Security.EscapeOutput -- pill() escapes its text and class . '

' . esc_html( $product_sync ) . '

' . ( '' !== $last_synced ? '

' . esc_html( $last_synced ) . '

' : '' ) . ( $sync_ready && ! Aha_Is_Woocommerce_Settings::is_product_sync_enabled() ? '

' . esc_html__( 'Automatic sync is off.', 'aha-is-for-woocommerce' ) . '

' : '' ); if ( $sync_paused || $sync_ready ) { $this->render_action_form( self::ACTION_RETRY_SYNC, self::NONCE_RETRY_SYNC, $sync_ready ? __( 'Sync products now', 'aha-is-for-woocommerce' ) : __( 'Retry product sync', 'aha-is-for-woocommerce' ), 'aha-connect__secondary' ); } echo '
'; $this->render_order_counts( true ); echo ''; } /** * Render the Disconnect danger zone (Settings tab only). * * @param string $sku Store SKU, empty when unknown. * @return void */ private function render_danger_zone( $sku ) { $kept = '' !== $sku /* translators: %s: store SKU. */ ? sprintf( __( 'Store %s, your settings, mapped orders and audit history are kept, so reconnecting resumes the same store.', 'aha-is-for-woocommerce' ), $sku ) : __( 'Your store, settings, mapped orders and audit history are kept, so reconnecting resumes the same store.', 'aha-is-for-woocommerce' ); echo '
' . esc_html__( 'Disconnect from Aha', 'aha-is-for-woocommerce' ) . '

' . esc_html( __( 'Catalog selling stops and Aha orders no longer reach this store.', 'aha-is-for-woocommerce' ) . ' ' . $kept ) . '

'; $this->render_action_form( self::ACTION_DISCONNECT, self::NONCE_DISCONNECT, __( 'Disconnect from Aha', 'aha-is-for-woocommerce' ), 'aha-connect__danger', __( 'Disconnect this store from Aha? Product sync stops and Aha orders no longer reach this store until you connect again.', 'aha-is-for-woocommerce' ) ); echo '
'; } /** * Render the amber waiting-for-review panel with a truthful timeline. * * @param string $check_html Pre-escaped check-status control. * @param int $submitted_at Unix time the request was submitted, 0 when unknown. * @return void */ private function render_review_panel( $check_html, $submitted_at = 0 ) { echo '

' . esc_html__( 'Waiting for Aha review', 'aha-is-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Aha staff review the store and account before the connection becomes active. Nothing is published in the meantime.', 'aha-is-for-woocommerce' ) . '

'; echo '
    '; $sent = __( 'Your store details were sent to Aha.', 'aha-is-for-woocommerce' ); if ( $submitted_at > 0 ) { $sent .= ' ' . self::when( $submitted_at, /* translators: Date format, e.g. "10 September 2026 at 12:44". Keep the PHP date escapes. */ __( 'j F Y \\a\\t H:i', 'aha-is-for-woocommerce' ) ); } $points = array( array( 'done', __( 'Request submitted', 'aha-is-for-woocommerce' ), $sent ), array( 'active', __( 'Aha review in progress', 'aha-is-for-woocommerce' ), __( 'Typical response 1–2 business days. No action needed from you.', 'aha-is-for-woocommerce' ) ), array( 'todo', __( 'Approval recorded', 'aha-is-for-woocommerce' ), __( 'Catalog selling turns on after Aha approves.', 'aha-is-for-woocommerce' ) ), ); foreach ( $points as $point ) { echo '
  1. ' . esc_html( $point[1] ) . '' . esc_html( $point[2] ) . '
  2. '; } echo '
' . $check_html . '
'; // phpcs:ignore WordPress.Security.EscapeOutput -- built from escaped markup above. } /** * Handle a Connect action. * * @return void */ public function handle_connect() { $this->assert_post( self::NONCE_CONNECT ); $this->assert_not_safe_mode(); $notice = 'setup_unavailable'; try { $result = Aha_Is_Woocommerce_Connect_Start::run(); if ( 'origin_verified' === $result['status'] ) { $profile = Aha_Is_Woocommerce_Connect_Profile::from_operator_config(); $destination = Aha_Is_Woocommerce_Connect_Start::login_redirect( $result['login_uri'], $result['local_state'], $profile ); self::safe_redirect_to_aha( $destination, $profile ); } if ( 'pending' === $result['status'] ) { $this->redirect_proof_pending(); } $notice = 'expired_unresolved' === $result['status'] ? 'attempt_expired' : ( 'login_used' === $result['status'] ? 'login_used' : 'setup_retry' ); } catch ( Throwable $error ) { $preflight = array( 'connect_admin_required', 'connect_https_public_origin_required' ); $notice = in_array( $error->getMessage(), $preflight, true ) ? 'setup_unavailable' : 'setup_retry'; } $this->redirect_local( $notice ); } /** * Redirect back with the proof_pending notice. The page stops auto re-checking after MAX_AUTO_RECHECK. * * @return void */ private function redirect_proof_pending() { $count = isset( $_POST['aha_is_woocommerce_recheck'] ) ? absint( wp_unslash( $_POST['aha_is_woocommerce_recheck'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification -- checked in assert_post(). set_transient( 'aha_is_woocommerce_connect_recheck_' . get_current_user_id(), min( $count, self::MAX_AUTO_RECHECK ) + 1, 60 ); $this->redirect_local( 'proof_pending' ); } /** * Handle the Connect callback. * * @return void */ public function handle_callback() { $this->assert_capability(); if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'GET' !== $_SERVER['REQUEST_METHOD'] ) { wp_die( esc_html__( 'Invalid request method.', 'aha-is-for-woocommerce' ) ); } $this->assert_not_safe_mode(); $state = isset( $_GET['state'] ) && is_string( $_GET['state'] ) ? wp_unslash( $_GET['state'] ) : null; // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- callback arrives from Aha without a nonce; Aha_Is_Woocommerce_Connect_Flow::handle_callback() validates the state value $notice = ''; try { $status = Aha_Is_Woocommerce_Connect_Flow::handle_callback( $state ); $notice_map = array( 'callback_invalid' => 'callback_invalid', 'pending' => 'callback_pending', 'proof_failed' => 'callback_failed', 'attempt_expired' => 'attempt_expired', 'pending_review' => 'callback_review', 'origin_verified' => 'callback_pending', 'send_retry' => 'reconnect_retry', 'returning_pending_review' => '', 'site_bound_to_other_account' => '', 'reconnect_approved' => '' ); $notice = isset( $notice_map[ $status ] ) ? $notice_map[ $status ] : ( 'consented' === $status ? '' : 'neutral_error' ); } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** * Handle a Connect reset action. * * @return void */ public function handle_reset() { $this->assert_post( self::NONCE_RESET ); try { $notice = Aha_Is_Woocommerce_Connect_Flow::reset() ? 'reset_done' : 'neutral_error'; } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** * Discard Connect state that cannot be decrypted (any manage_woocommerce user; no owner exists to check). * * @return void */ public function handle_discard() { $this->assert_post( self::NONCE_DISCARD ); try { $notice = Aha_Is_Woocommerce_Connect_Flow::discard_unreadable() ? 'reset_done' : 'neutral_error'; } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** * Handle a merchant request to retry paused product sync. * * @return void */ public function handle_retry_sync() { $this->assert_post( self::NONCE_RETRY_SYNC ); $this->assert_connect_owner(); $this->assert_not_safe_mode(); // A paused or missing catalog key is repaired first, as before; otherwise start a product fetch. if ( Aha_Is_Woocommerce_Connect_Automation::catalog_key_paused() && ! Aha_Is_Woocommerce_Connect_Credentials::catalog_key_registered() && ! Aha_Is_Woocommerce_Connect_Credentials::catalog_key_owner_lost() ) { Aha_Is_Woocommerce_Connect_Automation::retry_catalog_key(); $this->redirect_local( 'retry_sync_started' ); } if ( Aha_Is_Woocommerce_Connect_Credentials::is_paused() ) { $this->redirect_local( 'product_sync_paused' ); } try { $result = Aha_Is_Woocommerce_Connect_Credentials::request_product_sync(); } catch ( Throwable $error ) { $result = array( 'status' => 'retry' ); } if ( 'paused' === $result['status'] ) { $this->redirect_local( 'product_sync_paused' ); } if ( 'queued' === $result['status'] ) { $this->redirect_local( 'product_sync_started' ); } if ( 'cooldown' === $result['status'] ) { $this->redirect_local( 'product_sync_cooldown', array( 'aha_is_woocommerce_minutes' => max( 1, (int) ceil( $result['retry_after_seconds'] / 60 ) ) ) ); } $this->redirect_local( 'unavailable' === $result['status'] ? 'product_sync_unavailable' : 'product_sync_failed' ); } /** * Cooldown notice text with the remaining whole minutes from the redirect. * * @return string */ private function cooldown_message() { $minutes = isset( $_GET['aha_is_woocommerce_minutes'] ) ? max( 1, min( 10, (int) $_GET['aha_is_woocommerce_minutes'] ) ) : 10; // phpcs:ignore WordPress.Security.NonceVerification -- read-only display value, cast to int and clamped if ( 1 === $minutes ) { return __( 'A product sync was started recently. Try again in 1 minute.', 'aha-is-for-woocommerce' ); } /* translators: %d: minutes until the next product sync is allowed. */ return sprintf( __( 'A product sync was started recently. Try again in %d minutes.', 'aha-is-for-woocommerce' ), $minutes ); } /** * Handle a Connect details submission. * * @return void */ public function handle_details() { $this->assert_post( self::NONCE_DETAILS ); $this->assert_not_safe_mode(); $input = array(); foreach ( array( 'requested_target_kind', 'display_name', 'street_address', 'postcode', 'city', 'phone', 'description' ) as $field ) { $input[ $field ] = isset( $_POST[ $field ] ) && is_string( $_POST[ $field ] ) ? wp_unslash( $_POST[ $field ] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- nonce checked in assert_post(); value validated by Aha_Is_Woocommerce_Connect_Flow::validate_details() } $result = Aha_Is_Woocommerce_Connect_Flow::validate_details( $input ); if ( $result['errors'] ) { $this->render( array( 'phase' => 'consented', 'values' => $result['values'] ), $result['errors'] ); return; } try { $submitted = Aha_Is_Woocommerce_Connect_Flow::submit_details( $result['values'] ); if ( 'validation_error' === $submitted['status'] ) { $this->render( array( 'phase' => 'consented', 'values' => $submitted['values'] ), $submitted['errors'] ); return; } $notice = in_array( $submitted['status'], array( 'send_retry', 'neutral_error' ), true ) ? $submitted['status'] : ( 'expired_unresolved' === $submitted['status'] ? 'attempt_expired' : '' ); } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** * Handle an edit of the details while the request waits for review. * * @return void */ public function handle_edit_details() { $this->assert_post( self::NONCE_EDIT_DETAILS ); $this->assert_not_safe_mode(); $input = array(); foreach ( array( 'requested_target_kind', 'display_name', 'street_address', 'postcode', 'city', 'phone', 'description' ) as $field ) { $input[ $field ] = isset( $_POST[ $field ] ) && is_string( $_POST[ $field ] ) ? wp_unslash( $_POST[ $field ] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- nonce checked in assert_post(); value validated by Aha_Is_Woocommerce_Connect_Flow::validate_details() } $notice = 'neutral_error'; try { $result = Aha_Is_Woocommerce_Connect_Flow::edit_details( $input ); if ( 'validation_error' === $result['status'] ) { $this->editing = true; $this->render( array( 'phase' => 'pending_review', 'values' => $result['values'] ), $result['errors'] ); return; } if ( 'send_retry' === $result['status'] ) { $this->editing = true; $this->notice_override = 'send_retry'; $this->render( array( 'phase' => 'pending_review', 'values' => $result['values'] ) ); return; } if ( 'edited' === $result['status'] ) { $notice = 'details_edited'; } elseif ( 'neutral_error' !== $result['status'] ) { $notice = 'not_reviewable'; } } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** * Retry a failed automatic reconnect submission. * * @return void */ public function handle_reconnect() { $this->assert_post( self::NONCE_RECONNECT ); $this->assert_not_safe_mode(); try { $submitted = Aha_Is_Woocommerce_Connect_Flow::submit_reconnect(); $notice = in_array( $submitted['status'], array( 'send_retry', 'neutral_error' ), true ) ? ( 'send_retry' === $submitted['status'] ? 'reconnect_retry' : 'neutral_error' ) : ( 'expired_unresolved' === $submitted['status'] ? 'attempt_expired' : '' ); } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** Handle a protected Disconnect action. */ public function handle_disconnect() { $this->assert_post( self::NONCE_DISCONNECT ); $this->assert_connect_owner(); $this->assert_not_safe_mode(); try { $result = Aha_Is_Woocommerce_Connect_Credentials::disconnect(); $notice = 'retry' === $result ? 'neutral_error' : ''; } catch ( Throwable $error ) { $notice = 'neutral_error'; } $this->redirect_local( $notice ); } /** * Render the merchant details form. * * @param array $values Field values. * @param array $errors Validation errors. * @return void */ private function render_details_form( array $values, array $errors, $action = self::ACTION_DETAILS, $nonce = self::NONCE_DETAILS, $button = '', $cancel_url = '' ) { if ( '' === $button ) { $button = __( 'Send integration request to Aha', 'aha-is-for-woocommerce' ); } $defaults = array( 'requested_target_kind' => 'store', 'display_name' => '', 'street_address' => '', 'postcode' => '', 'city' => '', 'phone' => '', 'description' => '' ); $values = array_merge( $defaults, $values ); if ( ! in_array( $values['requested_target_kind'], array( 'store', 'restaurant' ), true ) ) { $values['requested_target_kind'] = 'store'; } echo '
'; wp_nonce_field( $nonce ); echo ''; echo '
' . esc_html__( 'Store type', 'aha-is-for-woocommerce' ) . ''; foreach ( array( 'store' => __( 'Store', 'aha-is-for-woocommerce' ), 'restaurant' => __( 'Restaurant', 'aha-is-for-woocommerce' ) ) as $kind => $label ) { $checked = $values['requested_target_kind'] === $kind ? ' checked="checked"' : ''; echo ''; } $this->render_error( 'requested_target_kind', $errors ); echo '
'; $labels = array( 'display_name' => '' . esc_html__( 'Store name', 'aha-is-for-woocommerce' ) . '' . esc_html__( 'Restaurant name', 'aha-is-for-woocommerce' ) . '', 'street_address' => __( 'Street address', 'aha-is-for-woocommerce' ), 'postcode' => __( 'Postcode', 'aha-is-for-woocommerce' ), 'city' => __( 'City', 'aha-is-for-woocommerce' ), 'phone' => __( 'Phone', 'aha-is-for-woocommerce' ), 'description' => __( 'Description', 'aha-is-for-woocommerce' ) ); $hints = array( 'display_name' => ' maxlength="120" autocomplete="organization"', 'street_address' => ' maxlength="200" autocomplete="street-address"', 'postcode' => ' maxlength="16" autocomplete="postal-code"', 'city' => ' maxlength="100" autocomplete="address-level2"', 'phone' => ' maxlength="32" pattern="\+([ \(\)\-]*[0-9]){8,15}[ \(\)\-]*|([ \(\)\-]*[0-9]){7}[ \(\)\-]*" title="' . esc_attr__( 'Enter a 7-digit Icelandic number, or an international number that starts with + (8–15 digits).', 'aha-is-for-woocommerce' ) . '" inputmode="tel" autocomplete="tel"', 'description' => ' maxlength="1000"', ); foreach ( $labels as $field => $label ) { echo ''; // phpcs:ignore WordPress.Security.EscapeOutput -- display_name label is escaped where defined. if ( 'description' === $field ) { echo ''; $this->render_error( $field, $errors ); continue; } echo ''; $this->render_error( $field, $errors ); } if ( '' !== $cancel_url ) { echo '
'; } echo ''; if ( '' !== $cancel_url ) { echo ' ' . esc_html__( 'Cancel', 'aha-is-for-woocommerce' ) . '
'; } echo '
'; } /** * Render a field error when present. * * @param string $field Field name. * @param array $errors Validation errors. * @return void */ private function render_error( $field, array $errors ) { if ( isset( $errors[ $field ] ) ) { echo ''; } } /** * Render an admin action form. * * @param string $action Admin action. * @param string $nonce Nonce action. * @param string $label Button label. * @param string $class_name Button class. * @param string $confirm Optional confirmation message. * @param array $hidden Optional extra hidden fields, name => value. * @return void */ private function render_action_form( $action, $nonce, $label, $class_name, $confirm = '', array $hidden = array() ) { $onsubmit = '' !== $confirm ? 'if(!confirm(' . wp_json_encode( $confirm ) . ')){return false;}this.querySelector(\'button\').disabled=true;' : 'this.querySelector(\'button\').disabled=true;'; echo '
'; wp_nonce_field( $nonce ); echo ''; foreach ( $hidden as $name => $value ) { echo ''; } echo '
'; } /** * Require the WooCommerce management capability. * * @return void */ private function assert_capability() { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( esc_html__( 'You cannot connect this website to Aha.', 'aha-is-for-woocommerce' ) ); } } /** * Stop with the safe_mode notice when the plugin is in safe mode. * * @return void */ private function assert_not_safe_mode() { if ( Aha_Is_Woocommerce_Site_Identity::is_safe_mode() ) { $this->redirect_local( 'safe_mode' ); } } /** * Only the admin who owns the connection may change it; others get the neutral error. * * @return void */ private function assert_connect_owner() { if ( ! Aha_Is_Woocommerce_Connect_Flow::current_user_owns_state() ) { $this->redirect_local( 'neutral_error' ); } } /** * Require a valid admin POST request. * * @param string $nonce Nonce action. * @return void */ private function assert_post( $nonce ) { $this->assert_capability(); if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) { wp_die( esc_html__( 'Invalid request method.', 'aha-is-for-woocommerce' ) ); } check_admin_referer( $nonce ); } /** * Send the browser to the Aha login. Only the host of the operator-owned * Aha authority is allowed as a redirect target. * * @param string $destination Validated login URL. * @param array $profile Operator profile. * @return void */ public static function safe_redirect_to_aha( $destination, array $profile ) { $aha_is_woocommerce_host = wp_parse_url( $profile['authority'], PHP_URL_HOST ); add_filter( 'allowed_redirect_hosts', function ( $hosts ) use ( $aha_is_woocommerce_host ) { $hosts = is_array( $hosts ) ? $hosts : array(); $hosts[] = $aha_is_woocommerce_host; return $hosts; } ); wp_safe_redirect( $destination, 303, 'Aha Connect' ); exit; } /** * Redirect to the local Connect screen. * * @param string $notice Notice code. * @return void */ private function redirect_local( $notice, array $extra = array() ) { $args = array( 'page' => self::PAGE_SLUG ) + $extra; if ( '' !== $notice ) { $args['aha_is_woocommerce_notice'] = $notice; } wp_safe_redirect( add_query_arg( $args, admin_url( 'admin.php' ) ), 303 ); exit; } }