<?php

// +----------------------------------------------------------------------+
// | OpenConf                                                             |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2012 Zakon Group LLC.  All Rights Reserved.       |
// +----------------------------------------------------------------------+
// | This source file is subject to the OpenConf License, available on    |
// | the OpenConf web site: www.OpenConf.com                              |
// +----------------------------------------------------------------------+

require_once "../include.php";

$dir = $OC_configAR['OC_paperDir'];

if (isset($_GET['c']) && ($_GET['c'] == 1)) {
	beginChairSession();
	$printHeaderFunction = 1;   // chair
} else {    // not chair
	beginSession();
	$printHeaderFunction = 2;   //reviewer
}

// Check for valid file name
if (!preg_match("/^(\d+)\.(\w+)$/",$_GET['p'],$matches)) {
	printHeader(oc_('File Retrieval'), $printHeaderFunction);
	//T: %s = filename (e.g., 1.pdf)
	warn(sprintf(oc_('Invalid submission file: %s'), safeHTMLstr($_GET['p'])));
}

// Extract paper ID
$pid = $matches[1];

// Permission checks for reviewers
if ($printHeaderFunction == 2) {
	// Check for conflict
	$conflictAR = getConflicts($_SESSION[OCC_SESSION_VAR_NAME]['acreviewerid']);
	if (in_array($pid.'-'.$_SESSION[OCC_SESSION_VAR_NAME]['acreviewerid'],$conflictAR)) {
		printHeader(oc_('File Retrieval'), 2);
		warn(oc_('You appear to have a conflict with this submission'));
	}

	$ok = 0;
	// Check that reviewer has permission
	if ($OC_configAR['OC_reviewerReadPapers']) {
		$ok = 1;
	} else {    // make sure reviewer is assigned
		$q = "SELECT paperid FROM " . OCC_TABLE_PAPERREVIEWER . " WHERE paperid=" . $pid . " AND reviewerid=" . $_SESSION[OCC_SESSION_VAR_NAME]['acreviewerid'];
		$r = ocsql_query($q) or err("Unable to check reviewer permissions " . mysql_errno());
		if (mysql_num_rows($r) == 1) {
 			$ok = 1;
		}
	}
	// If not ok, check if advocate & has permission
	if (!$ok && ($_SESSION[OCC_SESSION_VAR_NAME]['acpc'] == "T")) {
		if ($OC_configAR['OC_advocateReadPapers']) {
			$ok = 1;
		} else { // make sure advocate is assigned
			$q = "SELECT paperid FROM " . OCC_TABLE_PAPERADVOCATE . " WHERE paperid=" . $pid . " AND advocateid=" . $_SESSION[OCC_SESSION_VAR_NAME]['acreviewerid'];
			$r = ocsql_query($q) or err("Unable to check advocate permissions " . mysql_errno());
			if (mysql_num_rows($r) == 1) {
	  			$ok = 1;
	  		}
		}
	}
	
	// If still not ok, show error
	if (!$ok) {
		printHeader(oc_('File Retrieval'), 2);
		warn(oc_('You do not have permission to retrieve this submission'));
	}
} // reviewer

if (oc_hookSet('committee-paper-predisplay')) {
	foreach ($OC_hooksAR['committee-paper-predisplay'] as $v) {
		require_once $v;
	}
}

if (! oc_displayFile($dir . $_GET['p'], $matches[2])) {
	printHeader(oc_('File Retrieval'), $printHeaderFunction);
	warn(oc_('File does not exist'));
}

exit;
?>