<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides User SSL functions
 *
 * @package    OSB
 * @subpackage SSL
 * @category   Controllers/Admin
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_User_SSL extends Controller_TemplateDefault_User {
	protected $secure_actions = array(
		'download'=>FALSE,
	);

	public function action_download() {
		$id = $_POST['sid'];
		$so = ORM::factory('service',$id);

		if (! $so->loaded())
			Request::current()->redirect('welcome/index');

		$passwd = $_POST['passwd'];
		if (strlen($passwd) < Kohana::config('ssl.minpass_length')) {
			SystemMessage::add(array(
				'title'=>_('Validation failed'), 
				'type'=>'error',
				'body'=>_('Your requested password is too short.'),
			));

			Request::current()->redirect('user/service/view/'.$so->id);
		}

		if (! $so->loaded() OR ! Auth::instance()->authorised($so->account_id,$so->affiliate_id)) {
			$this->template->content = 'Unauthorised or doesnt exist?';
			return FALSE;
		}

		$file = Kohana::config('config.tmpdir').'/'.$so->name().'.pkcs12';
		openssl_pkcs12_export_to_file($so->plugin()->cert,$file,$so->plugin()->pk,$passwd,array('extracerts'=>$so->plugin()->cacerts()));
		$x = file_get_contents($file);
		unlink($file);
		$this->response->headers('Content-Type','application/pks12');
		$this->response->headers('Content-Disposition','attachment; filename="'.basename($file).'"');
		$this->response->body($x);
		$this->auto_render = FALSE;
	}
}
?>
