<?php

# Domain validated cert

$plugin_name='dv';

class dv
{
	public static $order=5;

	public static $filename_key="{host}.{domain}-key.pem";
	public static $filename_cert="{host}.{domain}-cert.pem";

	public static function generate($ssldir, $ssl_all, $ini)
	{
		//sanity check
		if (!($openssl_bin=find_shell_command('openssl')))
		{
			logme('SSL error: openssl binary not found');
			return false;
		}

		foreach($ssl_all as $ssl)
		{
			$hn=$ssl['host'].'.'.$ssl['domain'];

			$key_path=$ssldir."/$hn-key.pem";
			$csr_path=$ssldir."/$hn.csr";
			$cert_path=$ssldir."/$hn-cert.pem";

			if (!(file_exists($key_path)))
			{
				if (file_exists($cert_path.'.bck'))
				{
					unlink($cert_path.'.bck');
				}
				if (file_exists($cert_path))
				{
					rename($cert_path, $cert_path.'.bck');
				}

				exec_as_err($openssl_bin." req -nodes -newkey rsa:2048 -nodes -keyout ".$key_path." -out ".$csr_path." -subj '/C=HU/ST=Budapest/L=Budapest/O=".$ini['global']['name']."/OU=internet/CN=".$hn."'", $ini['ssl']['user'], false);

				if (file_exists($csr_path))
				{
					//send CSR to admin in e-mail
					mailsend($ini['global']['name'], $ini['global']['email'], $ini['global']['email'], "CSR: $hn", "$hn\n\n".file_get_contents($csr_path));
					sleep(1);
				}
			}
		}
	}
}
