<?php
/**
 * Autoload option anomaly detector.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Detection\Database;

use LocalGuardScanner\Domain\Detection\Detector;
use LocalGuardScanner\Domain\Detection\Evidence;
use LocalGuardScanner\Domain\Detection\ScannableObject;

/**
 * Detects large or executable-looking autoloaded options.
 */
final class AutoloadOptionDetector implements Detector {
	/** @return string */
	public function id() {
		return 'database.autoload_options';
	}

	/** @inheritDoc */
	public function inspect( ScannableObject $scanned_object ) {
		if ( 'db_option' !== $scanned_object->type() ) {
			return array();
		}
		$data = $scanned_object->attributes();
		if ( empty( $data['autoload'] ) ) {
			return array();
		}
		$value    = isset( $data['value'] ) && is_string( $data['value'] ) ? $data['value'] : '';
		$evidence = array();
		if ( isset( $data['size'] ) && (int) $data['size'] > 524288 ) {
			$evidence[] = new Evidence( 'database.large_autoload', 25, 96, 'large_autoloaded_option', 'size>512KiB' );
		}
		if ( preg_match( '/<\?php|\beval\s*\(|\bbase64_decode\s*\(/i', $value ) ) {
			$evidence[] = new Evidence( 'database.executable_autoload', 62, 88, 'executable_content_in_autoloaded_option', 'executable-pattern' );
		}
		return $evidence;
	}
}
