92 lines
2.7 KiB
PHP
92 lines
2.7 KiB
PHP
<?php
|
|
/**
|
|
* HSSM API Client Class
|
|
*
|
|
* Handles fetching slides from the remote Manager site API
|
|
*
|
|
* @package Hi_School_Slide_Manager
|
|
* @since 1.1.0
|
|
*/
|
|
|
|
// Prevent direct access
|
|
if ( ! defined( 'ABSPATH' ) ) {
|
|
exit( 'Direct access forbidden.' );
|
|
}
|
|
|
|
class HSSM_API_Client {
|
|
|
|
/**
|
|
* Get slides for this site
|
|
*
|
|
* @since 1.1.0
|
|
* @return array|WP_Error Array of slides or WP_Error on failure
|
|
*/
|
|
public function get_slides() {
|
|
$api_url = get_option( 'hssm_api_url' );
|
|
$site_slug = get_option( 'hssm_client_site_slug' );
|
|
$api_key = 'HI_SCHOOL_FIXED_API_KEY'; // Hardcoded fixed API key
|
|
$cache_duration = get_option( 'hssm_cache_duration', 3600 );
|
|
|
|
if ( empty( $api_url ) || empty( $site_slug ) || empty( $api_key ) ) { // Added $api_key check here
|
|
return new WP_Error( 'missing_config', __( 'API URL, Site Slug, or API Key not configured.', 'hi-school-slide-manager' ) ); // Updated error message
|
|
}
|
|
|
|
// Check cache first
|
|
$cache_key = 'hssm_remote_slides_' . $site_slug;
|
|
$cached_slides = get_transient( $cache_key );
|
|
if ( false !== $cached_slides ) {
|
|
return $cached_slides;
|
|
}
|
|
|
|
// Build the request URL
|
|
// Ensure trailing slash on API URL and remove leading slash from endpoint
|
|
$endpoint = sprintf( 'hssm/v1/slides/%s', $site_slug );
|
|
$full_url = trailingslashit( $api_url ) . $endpoint;
|
|
|
|
$args = array(
|
|
'timeout' => 15,
|
|
'headers' => array(
|
|
'X-HSSM-API-Key' => $api_key,
|
|
'Accept' => 'application/json',
|
|
),
|
|
);
|
|
|
|
$response = wp_remote_get( $full_url, $args );
|
|
|
|
if ( is_wp_error( $response ) ) {
|
|
return $response;
|
|
}
|
|
|
|
$code = wp_remote_retrieve_response_code( $response );
|
|
$body = wp_remote_retrieve_body( $response );
|
|
|
|
if ( 200 !== $code ) {
|
|
return new WP_Error( 'api_error', sprintf( __( 'API returned code %d: %s', 'hi-school-slide-manager' ), $code, $body ) );
|
|
}
|
|
|
|
$data = json_decode( $body, true );
|
|
if ( ! is_array( $data ) || ! isset( $data['slides'] ) ) {
|
|
return new WP_Error( 'invalid_response', __( 'Invalid API response format.', 'hi-school-slide-manager' ) );
|
|
}
|
|
|
|
$slides = $data['slides'];
|
|
|
|
// Cache the results
|
|
set_transient( $cache_key, $slides, $cache_duration );
|
|
|
|
return $slides;
|
|
}
|
|
|
|
/**
|
|
* Clear the slides cache
|
|
*
|
|
* @since 1.1.0
|
|
*/
|
|
public function clear_cache() {
|
|
$site_slug = get_option( 'hssm_client_site_slug' );
|
|
if ( ! empty( $site_slug ) ) {
|
|
delete_transient( 'hssm_remote_slides_' . $site_slug );
|
|
}
|
|
}
|
|
}
|