$kept, 'error' => null, 'stale' => false ); } } $fetched = $connected ? self::fetch_overview( $lang ) : self::fetch_catalog( $lang ); if ( is_array( $fetched ) ) { set_transient( $key, $fetched, $connected ? 5 * MINUTE_IN_SECONDS : HOUR_IN_SECONDS ); if ( $connected ) { update_option( self::LAST_GOOD, array( 'lang' => $lang, 'data' => $fetched ), false ); } return array( 'data' => $fetched, 'error' => null, 'stale' => false ); } // The platform could not be reached: show the last good view (when it is in this language) and say so $last = $connected ? get_option( self::LAST_GOOD ) : null; if ( is_array( $last ) && ( $last['lang'] ?? '' ) === $lang && is_array( $last['data'] ?? null ) ) { return array( 'data' => $last['data'], 'error' => $fetched, 'stale' => true ); } return array( 'data' => null, 'error' => $fetched, 'stale' => false ); } /** Forget what is kept: the next read asks the platform. */ public static function forget() { foreach ( array( 'c', 'p' ) as $kind ) { foreach ( array( 'en', 'ar', 'fr' ) as $lang ) { delete_transient( 'winnyplus_connect_overview_' . $kind . '_' . $lang ); } } } /** @return array|string The overview, or the reason it could not be read. */ private static function fetch_overview( $lang ) { $connection = WinnyPlus_Connect_Connection::get(); $token = WinnyPlus_Connect_Connection::get_token(); if ( '' === $token ) { return __( 'Invalid connection token.', 'winnyplus' ); } $url = trailingslashit( $connection['site_url'] ) . 'v1/integrations/installations/' . rawurlencode( $connection['installation_id'] ) . '/overview?lang=' . rawurlencode( $lang ); return self::request( $url, array( 'Authorization' => 'Bearer ' . $token ) ); } /** @return array|string */ private static function fetch_catalog( $lang ) { return self::request( trailingslashit( WinnyPlus_Connect_Links::api() ) . 'v1/integrations/plugin/services?lang=' . rawurlencode( $lang ), array() ); } /** @return array|string */ private static function request( $url, $headers ) { $response = wp_remote_get( $url, array( 'timeout' => 6, 'headers' => $headers + array( 'Accept' => 'application/json' ) ) ); if ( is_wp_error( $response ) ) { return $response->get_error_message(); } $code = wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code < 200 || $code >= 300 || ! is_array( $body ) || ! isset( $body['data']['services'] ) || ! is_array( $body['data']['services'] ) ) { return ! empty( $body['error']['message'] ) ? (string) $body['error']['message'] : sprintf( /* translators: %d: HTTP status code */ __( 'WinnyPlus answered with an unexpected response (%d).', 'winnyplus' ), $code ); } return $body['data']; } }