report-expiry.php 1.48 KB
Newer Older
Erick Hitter's avatar
Erick Hitter committed
1
<?php
Erick Hitter's avatar
Erick Hitter committed
2 3 4 5 6
/**
 * Report certificate details.
 *
 * @package PHP_Cert_Reporter
 */
Erick Hitter's avatar
Erick Hitter committed
7

Erick Hitter's avatar
Erick Hitter committed
8 9 10 11 12 13
namespace PHP_Cert_Reporter;

/**
 * Load table renderer.
 */
require_once __DIR__ . '/vendor/autoload.php';
Erick Hitter's avatar
Erick Hitter committed
14

Erick Hitter's avatar
Erick Hitter committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/**
 * Display certificate details in a table.
 *
 * Suitable for use in CI.
 *
 * @param bool $exit Exit with status code indicating if expired certificates were found.
 */
function report( $exit = true ): void {
	$data = [
		[
			'Filename',
			'CN',
			'Expires',
			'Days Left',
		],
Erick Hitter's avatar
Erick Hitter committed
30 31
	];

Erick Hitter's avatar
Erick Hitter committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
	$dir_includes_expired = false;

	printf( 'RESULTS FOR `%1$s`%2$s', getcwd(), "\n" );

	foreach ( glob( '*.crt', GLOB_NOSORT ) as $cert ) {
		$path = getcwd() . '/' . $cert;
		$x509 = openssl_x509_parse( file_get_contents( $path ) );

		if ( ! is_array( $x509 ) ) {
			printf( 'Failed to parse certificate from `%1$s`%2$s', $path, "\n\n" );
			continue;
		}

		$cert_data = [
			0 => $cert,
			1 => $x509['subject']['CN'],
			2 => date( 'Y-m-d H:i:s T', $x509['validTo_time_t'] ),
			3 => (int) round( ( $x509['validTo_time_t'] - time() ) / 86400 ),
		];
Erick Hitter's avatar
Erick Hitter committed
51

52 53
		// Alert if any expire within the next 30 days.
		if ( ! $dir_includes_expired && $cert_data[3] - 30 <= 0 ) {
Erick Hitter's avatar
Erick Hitter committed
54
			$dir_includes_expired = true;
Erick Hitter's avatar
Erick Hitter committed
55 56
		}

Erick Hitter's avatar
Erick Hitter committed
57
		$data[] = $cert_data;
Erick Hitter's avatar
Erick Hitter committed
58 59
	}

Erick Hitter's avatar
Erick Hitter committed
60
	$table = new \cli\Table( array_shift( $data ), $data );
61
	$table->setRenderer( new \cli\table\Ascii() );
Erick Hitter's avatar
Erick Hitter committed
62 63
	$table->sort( 2 );
	$table->display();
Erick Hitter's avatar
Erick Hitter committed
64

65 66 67 68
	if ( $dir_includes_expired ) {
		echo "EXPIRING CERTIFICATES FOUND!\n";
	}

Erick Hitter's avatar
Erick Hitter committed
69 70 71 72 73
	if ( $exit ) {
		exit( $dir_includes_expired ? 1 : 0 );
	}
}
report();