<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Job.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/MyMember.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/AdminUser.inc.php" );

	class JobAttachmentPane extends Widget {
		protected $jm = null;
		protected $mmm = null;
		protected $job_attachment_id = 0;
		protected $job_attachment = array();

		public function __construct( $id = "JobPane" , $parent = null ) {
			parent::__construct( $id , $parent );
		}

		public function modifyGetPost( &$g , &$p ) {
			parent::modifyGetPost( $g , $p );
			if (isset( $this->aG["job_attachment_id"] )) $this->job_attachment_id = $this->aG["job_attachment_id"];
		}

		protected function isJobAttachmentAvailable() {
			if (!$this->job_attachment_id) return false;
			if (!isset( $this->job_attachment["job_id"] )) return false;

			if (AdminUserModel::isAdminLoggedIn()) return true;	// admin mindenkepp latja
			if (!$this->mmm->isUserLoggedin()) return false;

			$user_id = $this->mmm->getLoggedinUserId();
			if (!$this->jm->isJobAvailableForUser( $this->job_attachment["job_id"] , $user_id )) return false;
			// SL1110 - a visszavontakat nem erheti el mas, ha url hackel
			$job = $this->jm->getJobFromId( $this->job_attachment["job_id"] );
			if ($job["is_revoked"]=="t") return false;
			if ($job["is_closed"]=="t") return false;
			return true;
		}

		protected function sendJobAttachment() {
			header( "Content-Type: " . $this->job_attachment["attachment_mimetype"] );
			header( sprintf( "Content-Disposition: attachment; filename=\"%s\"",$this->job_attachment["attachment_original_filename"] ) );
			$filename = $GLOBALS["site_root"].$this->job_attachment["attachment_path"]."/".$this->job_attachment["attachment_filename"];
			header( "Content-length: ".$this->job_attachment["attachment_filesize"] );
			// TODO bufferelt kikuldes illene a nagy fileok miatt
			echo file_get_contents( $filename );
			exit();
		}

		public function handleEvents() {
			if (!$this->job_attachment_id) return parent::handleEvents();
			$this->jm = new JobModel();
			$this->mmm = new MyMemberModel();

			$this->job_attachment = $this->jm->getJobAttachment( $this->job_attachment_id );
			if ($this->isJobAttachmentAvailable()) $this->sendJobAttachment();
			return parent::handleEvents();
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->setParam( "bLoggedIn" , $this->mmm->isUserLoggedin() );
			$this->setParam( "bActiveSubscriber" , $this->mmm->isLoggedinMemberActiveSubscriber() );
			return parent::render();
		}
	}

?>
