<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class ASA_Permission_Scan {

	public function run() {
		$results = array();
		$paths = array( ABSPATH, WP_CONTENT_DIR, WP_CONTENT_DIR . '/uploads', WP_CONTENT_DIR . '/plugins' );
		foreach ( $paths as $path ) {
			if ( ! file_exists( $path ) ) {
				continue;
			}
			$perms = substr( sprintf( '%o', fileperms( $path ) ), -4 );
			$world_writable = in_array( $perms, array( '0777', '0666' ), true );
			$results[] = array(
				'severity' => $world_writable ? 'high' : 'passed',
				'category' => 'permissions',
				'title'    => 'Path permission review',
				'details'  => $path . ' uses permissions ' . $perms,
			);
		}

		$recent_php = $this->find_recent_php_files();
		foreach ( $recent_php as $path ) {
			$results[] = array( 'severity' => 'info', 'category' => 'recent-files', 'title' => 'Recently modified PHP file', 'details' => $path );
		}
		return $results;
	}

	private function find_recent_php_files() {
		$recent = array();
		$cutoff = time() - DAY_IN_SECONDS * 7;
		$iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( WP_CONTENT_DIR, FilesystemIterator::SKIP_DOTS ) );
		foreach ( $iterator as $file ) {
			if ( ! $file->isFile() || 'php' !== strtolower( $file->getExtension() ) ) {
				continue;
			}
			if ( $file->getMTime() >= $cutoff ) {
				$recent[] = $file->getPathname();
				if ( count( $recent ) >= 25 ) {
					break;
				}
			}
		}
		return $recent;
	}
}
