<?php

// +----------------------------------------------------------------------+
// | OpenConf                                                             |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2008 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";

if (OCC_CHAIR_PWD_TRUMPS && isset($_REQUEST['c']) && ($_REQUEST['c'] == 1)) {
	$hdrfn = 1;
	beginChairSession();
	$chair = TRUE;
} else {
	$hdrfn = 3;
	$chair = FALSE;
}

// Print appropriate header
printHeader("Envoyer un fichier", $hdrfn);

if ($chair) { // display back links
	print '<p style="text-align: center"><a href="../chair/show_paper.php?pid=' . $_REQUEST['pid'] . '">View This Submission</a> | <a href="../chair/list_papers.php">View All Submissions</a></p><br />';
} elseif (! $OC_statusAR['OC_upload_open']) { // Check that we're still open
	warn('Files are no longer being accepted');
}

// Check whether this is a submission
if (isset($_POST['submit']) && ($_POST['submit'] == "Envoyer le fichier")) {
	if ($chair && !validToken('chair')) {
		warn('Invalid submission');
	}

	// Check inputs
	if (!preg_match("/^\d+$/",$_POST['pid'])
		|| (! $chair && empty($_POST['pwd'])) 
		|| empty($_FILES['paper']['name'])
		|| ! in_array($_POST['format'], $OC_configAR['OC_extar'])
	) {
		warn('Please go back and fill in all fields.');
	}

	// Set PID to intval in case of leading 0's
	$usepid = intval($_POST['pid']);

	// Retrieve pwd & format
	$pq = "SELECT `format`, `password` FROM `" . OCC_TABLE_PAPER . "` WHERE `paperid`='".$usepid."'";
	$pr = ocsql_query($pq) or err("Unable to upload file (" . mysql_errno() . ")");
	if (mysql_num_rows($pr) != 1) {
		warn("Unable to find submission ID ".$usepid);
	}
	$pl = mysql_fetch_array($pr);

	// Valid pid/pwd?; check for chair pwd first to save db call
	if (! $chair
		&& (! OCC_CHAIR_PWD_TRUMPS || (hashPassword($_POST['pwd'], $OC_configAR['OC_chair_pwd']) != $OC_configAR['OC_chair_pwd']))
		&& (! defined('OCC_SUPERCHAIR_PASSWORD') || (hashPassword($_POST['pwd'], OCC_SUPERCHAIR_PASSWORD) != OCC_SUPERCHAIR_PASSWORD))
		&& (hashPassword($_POST['pwd'], $pl['password']) != $pl['password'])
		&& (md5($_POST['pwd']) != $pl['password'])
	) {
		warn('Password entered is not valid for submission ID '.$usepid);
	}
	
	// Was a paper successfully loaded & filesize > 0?
	if (!isset($_FILES['paper']['error']) || $_FILES['paper']['error'] || ! is_uploaded_file($_FILES['paper']['tmp_name']) || ($_FILES['paper']['size'] <= 0)) {
		warn('The file failed to load.  Please go back and try again.  If the problem persists, contact the <a href="mailto:' . $OC_configAR['OC_pcemail'] . '?subject=File Upload failed">Program Chair</a>');
	}

	if (oc_hookSet('author-upload-validate')) {
		foreach ($GLOBALS['OC_hooksAR']['author-upload-validate'] as $hook) {
			require_once $hook;
		}
	}
	
	// Delete old file?
	$oldFileName = $OC_configAR['OC_paperDir'] . $usepid . '.' . $pl['format'];
	if (is_file($oldFileName)) {
		unlink($oldFileName);
	}

	// Move new file
	$err = 0;
	$newFileName = $OC_configAR['OC_paperDir'] . $usepid . '.' . $_POST['format'];
	
    // Check whether file uploaded
    if (is_uploaded_file($_FILES['paper']['tmp_name'])
		&& move_uploaded_file($_FILES['paper']['tmp_name'],$newFileName)
	) {
		// Update file permissions
		chmod($newFileName, 0666);

		$confirmmsg = 'La soumission n° ' . $usepid . ' a été transmise.';

		// Set lastupdate date, and format if needed
		$eq = "UPDATE " . OCC_TABLE_PAPER . " SET lastupdate='" . date("Y-m-d") . "'";
		// also update format if changed
		if ($_POST['format'] != $pl['format']) {
			$eq .= ", format='".$_POST['format']."'";
		}
		$eq .= " WHERE paperid='".$usepid."'";
		if (!ocsql_query($eq)) {
			$confirmmsg .= "However, we were unable to update the database (" . mysql_errno() . ").\n";
			$err = 1;
		}

		// Send email confirmation
   		sendEmail(NULL, "Soumission n. " . $usepid . " file uploaded", $confirmmsg, $OC_configAR['OC_notifyAuthorUpload']);

		if (!$err) {
			print $confirmmsg;
		} else {
			err($confirmmsg);
		}
	} else { // file failed to upload or move properly
		print '<span class="err">The file failed to load properly.  Please email it directly to the <a href="mailto:' . $OC_configAR['OC_pcemail'] . '?subject=' . $OC_configAR['OC_confName'] . ' File failed - submission ID ' . $usepid . '">Program Chair</a></span><p><hr><p>';
	}

	printFooter();
	exit;
}

print '
<form method="POST" enctype="multipart/form-data" action="upload.php">
';

if ($chair) {
	print '
<input type="hidden" name="c" value="1">
<input type="hidden" name="token" value="' . $_SESSION[OCC_SESSION_VAR_NAME]['chairtoken'] . '" />
<input type="hidden" name="pid" value="' . $_REQUEST['pid'] . '" />
';
}

print '<table border=0 cellspacing=0 cellpadding=5>';

if (! $chair) {
	print '
<tr><td><b>Soumission n°</b></td><td><input name="pid" size="5" tabindex="1"> ( <a href="email_papers.php">Id. oublié ?</a> )</td></tr>
<tr><td><b>Mot de passe :</b></td><td><input name="pwd" type="password" size="20" maxlength="255" tabindex="2"> ( <a href="reset.php">Mot de passe oublié ?</a> )</td></tr>
';
}

print '
<tr><td valign="top"><b>Fichier :</b></td><td><input type="file" name="paper" size="30" tabindex="3"> &nbsp; &nbsp; <b>Format:</b>
';

if (count($OC_configAR['OC_extar']) == 1) {        # Only accept one format?
    print $OC_formatAR[$OC_configAR['OC_extar'][0]] . ' seulement <input type="hidden" name="format" value="' . $OC_configAR['OC_extar'][0] . '"><p />';
} else {
	print '<select name="format">';
	$formatoptions = "";
	foreach ($OC_configAR['OC_extar'] as $fval) {
		$formatoptions .= '<option value="'.$fval.'"> ' . $OC_formatAR[$fval];
	}
	print $formatoptions;
	print "</select><p />\n";
}

print '
<span class="note3">' . $OC_configAR['OC_paperFldNote'] . '</span><br />
<span class="note">Taille limite de ' . $OC_maxFileSize . '. Si votre fichier est plus volumineux que ' . $OC_maxFileSize . ', laissez le champ Fichier vide et contactez l\'<a href="mailto:' . urlencode($OC_configAR['OC_pcemail']) . '?subject=' . urlencode($OC_configAR['OC_confName']) . ' File Upload - large file">Administrateur</a>.</span>
</td></tr></table>
<p>
<input type="submit" name="submit" value="Envoyer le fichier" tabindex="4">
</form>
<p>
<script language="javascript">
<!--
document.forms[0].elements[1].focus();
// -->
</script>
';

printFooter();

?>
