<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否
/**
 * Name: ATPU_Plugin
 * Description:
 * Version: 1.4 (Object Injection Safety Fixed)
 * Author: Hima Art
 * Author URI: https://habone.biz
 * Created : March 29, 2026
 * Modified: May 6, 2026
 * Package: HA Automatic Theme Plugin Update
 *
 * License: GPLv2
 */
class ATPU_Plugin {
	private $api_url;
	private $plugin_slug;

	public function __construct( $api_url = '', $plugin_slug = '' ) {
		if ( !$api_url ) {
			die( 'Please set $api_url.' );
		}
		$this->api_url = esc_url( $api_url );

		if ( !$plugin_slug ) {
			die( 'Please set $plugin_slug.' );
		}
		$this->plugin_slug = $plugin_slug;

		add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'check_for_plugin_update' ) );
		add_filter( 'plugins_api', array( $this, 'plugin_api_call' ), 10, 3 );
	}

	public function check_for_plugin_update( $checked_data ) {
		// 万が一、受け取ったデータがオブジェクトでなければ、そのまま返す（クラッシュ防止）
		if ( ! is_object( $checked_data ) ) {
			return $checked_data;
		}

		global $wp_version;
		$plugin_name = $this->plugin_slug . '/' . $this->plugin_slug . '.php';

		if ( ! empty( $checked_data->checked ) &&
			 is_array( $checked_data->checked ) &&
			 isset( $checked_data->checked[$plugin_name] ) ) {

			$current_version = $checked_data->checked[$plugin_name];

			$args = array(
				'slug' => $this->plugin_slug,
				'version' => $current_version,
			);
			$request_string = array(
				'body' => array(
					'action' => 'basic_check',
					'request' => serialize( $args ),
					'api-key' => md5( home_url() ),
				),
				'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url(),
			);

			$raw_response = wp_remote_post( $this->api_url, $request_string );
			$response = null;

			if ( ! is_wp_error( $raw_response ) && $raw_response['response']['code'] == 200 && is_serialized( $raw_response['body'] ) ) {
				$response = unserialize( $raw_response['body'] );
			}

			// 元データを破壊しないよう、レスポンスの配列を初期化して準備
			if ( ! isset( $checked_data->response ) || ! is_array( $checked_data->response ) ) {
				$checked_data->response = array();
			}

			if ( isset( $response ) && is_object( $response ) && ! empty( $response ) ) {
				
				// 🔴 既存オブジェクトを書き換えるのではなく、新規にWordPress標準互換の stdClass を組み立てる
				$matched_response = new stdClass();
				
				// 配信サーバーから取得したデータ
				$matched_response->id          = 'local/' . $this->plugin_slug;
				$matched_response->slug        = $this->plugin_slug;
				$matched_response->plugin      = $plugin_name;
				$matched_response->new_version = isset( $response->version ) ? $response->version : ( isset( $response->new_version ) ? $response->new_version : $current_version );
				$matched_response->url         = isset( $response->homepage ) ? $response->homepage : $this->api_url;
				$matched_response->package     = isset( $response->package ) ? $response->package : '';
				
				// アイコンやバナーなどの追加情報（あればコピー）
				if ( isset( $response->icons ) ) {
					$matched_response->icons = $response->icons;
				}
				if ( isset( $response->banners ) ) {
					$matched_response->banners = $response->banners;
				}
				if ( isset( $response->requires ) ) {
					$matched_response->requires = $response->requires;
				}
				if ( isset( $response->tested ) ) {
					$matched_response->tested = $response->tested;
				}

				// 安全に「response」配列へインジェクション
				$checked_data->response[$plugin_name] = $matched_response;

			} else {
				// 更新がない、あるいは通信失敗時は安全にunsetのみ行う
				if ( isset( $checked_data->response[$plugin_name] ) ) {
					unset( $checked_data->response[$plugin_name] );
				}
			}
		}

		return $checked_data;
	}

	public function plugin_api_call( $def, $action, $args ) {
		global $wp_version;
		if ( !is_object( $args ) || !isset( $args->slug ) || $args->slug != $this->plugin_slug )
			return false;

		$plugin_name = $this->plugin_slug . '/' . $this->plugin_slug . '.php';
		$plugin_info = get_site_transient( 'update_plugins' );
		
		$current_version = '0.0.0';
		if ( is_object( $plugin_info ) && isset( $plugin_info->checked ) && is_array( $plugin_info->checked ) ) {
			if ( isset( $plugin_info->checked[$plugin_name] ) ) {
				$current_version = $plugin_info->checked[$plugin_name];
			}
		}
		
		$args->version = $current_version;

		$request_string = array(
			'body' => array(
				'action' => $action,
				'request' => serialize( $args ),
				'api-key' => md5( home_url() ),
			),
			'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url(),
		);
		$request = wp_remote_post( $this->api_url, $request_string );

		if ( is_wp_error( $request ) ) {
			$error_message = __( 'An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>' );
			$res = new WP_Error( 'plugins_api_failed', $error_message, $request->get_error_message() );
		} else {
			$res = unserialize( $request['body'] );
			if ( $res === false ) {
				$res = new WP_Error( 'plugins_api_failed', __( 'An unknown error occurred' ), $request['body'] );
			}
		}

		return $res;
	}
}