<?php
/**
 * Known-compromise list: BUNDLED ONLY.
 *
 * The list ships inside the plugin as a static data file and is updated only by
 * releasing a new plugin version. There is deliberately no remote feed:
 *
 *  - A security feed is worthless unless it is actively curated. A stale feed is
 *    worse than no feed, because it quietly implies "we checked, you're fine".
 *    This plugin's whole premise is being honest about what it does and does not
 *    know, so it does not ship a channel it cannot promise to maintain.
 *  - It keeps the plugin's external surface to services that already exist, with
 *    no server of our own to run and nothing that can 404 out from under a user.
 *
 * The live signal comes from the provenance engine instead, which reads the
 * WordPress.org API directly: closures (with reasons), ownership changes, new
 * contributors, and abandonment.
 *
 * @package Upgrade_Pilot
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class UPilot_Compromise_List
 */
class UPilot_Compromise_List {

	/**
	 * Loaded list.
	 *
	 * @var array|null
	 */
	private $list = null;

	/**
	 * Check a slug/version pair against the bundled list.
	 *
	 * @param string $slug    Plugin slug.
	 * @param string $version Installed version.
	 * @return string|false Advisory text when listed, false otherwise.
	 */
	public function check( $slug, $version ) {
		$list = $this->get_list();
		if ( ! isset( $list['plugins'][ $slug ] ) ) {
			return false;
		}

		$entry = $list['plugins'][ $slug ];

		// A fixed version means the installed copy may already be safe.
		if ( ! empty( $entry['fixed_in'] ) && is_string( $entry['fixed_in'] ) && version_compare( $version, $entry['fixed_in'], '>=' ) ) {
			return false;
		}
		if ( ! empty( $entry['affected_versions'] ) && is_array( $entry['affected_versions'] ) && ! in_array( $version, $entry['affected_versions'], true ) ) {
			return false;
		}

		return isset( $entry['advisory'] ) && is_string( $entry['advisory'] )
			? $entry['advisory']
			: __( 'This plugin appears on the bundled list of plugins named in public security advisories.', 'upgrade-pilot' );
	}

	/**
	 * Load the bundled list.
	 *
	 * @return array
	 */
	public function get_list() {
		if ( null !== $this->list ) {
			return $this->list;
		}

		$this->list = array(
			'version' => '0',
			'plugins' => array(),
		);

		$file = UPILOT_DIR . 'data/compromise-list.json';
		if ( is_readable( $file ) ) {
			$data = json_decode( (string) file_get_contents( $file ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- reading a data file bundled inside this plugin.
			if ( is_array( $data ) && isset( $data['version'], $data['plugins'] ) && is_array( $data['plugins'] ) ) {
				$this->list = $data;
			}
		}

		return $this->list;
	}
}
