<?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                              |
// +----------------------------------------------------------------------+

// Don't cache
header("Expires: Mon, 18 Sep 2003 13:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

require_once "../include.php";

require_once OCC_COUNTRY_FILE;

printHeader("Nouvelle soumission",3);

// Check whether cfp still open
if (! $OC_statusAR['OC_submissions_open']) {
	print '<b>La période de soumission est close.</b><p />';
	printFooter();
	exit;
}

// Get topics
$topq = "SELECT * FROM `" . OCC_TABLE_TOPIC . "`";
$topr = ocsql_query($topq) or err('unable to retrieve topics');
if (($tnum = mysql_num_rows($topr)) < 1) {
	warn('We are still waiting for the Program Chair to finalize the list of topics before opening up for submissions.  Please check back later.');
} else {
	$half = ceil($tnum / 2);
	$topicAR = array();
	while ($topl = mysql_fetch_assoc($topr)) {
		$topicAR[$topl['topicid']] = $topl['topicname'];
	}
}

// Check whether this is a submission
if (isset($_POST['submit']) && ($_POST['submit'] == "Soumettre")) {
	$err = '';
	$errInc = '';
	// Check title
	if (!preg_match("/\w+/",$_POST['title'])) {
		$err .= "<li>Enter a title for your submission</li>";
	}
	// Check that we have a valid contact author & email
	if (!preg_match("/^[1-5]$/",$_POST['contact'])) {
		$err .= "<li>Contact author invalid</li>";
	} else {
        $contactemail = $_POST['email'.$_POST['contact']];
		if (!preg_match("/\w/",$_POST['name_last'.$_POST['contact']]) || !preg_match("/\w/",$_POST['name_first'.$_POST['contact']])) {
			$err .= "<li>Fill in both the first &amp; last name of the contact author</li>";
		}
		if (!validEmail($contactemail)) {
			$err .= "<li>Contact author email does not seem valid";
		}
	}
	// Check author countries
	for ($c=1; $c<=4; $c++) {
		if ((!isset($_POST['country'.$c]) || empty($_POST['country'.$c])) && isset($_POST['isocountry'.$c]) && !empty($_POST['isocountry'.$c])) {
			$isoUpper = oc_strtoupper($_POST['isocountry'.$c]);
			if (!in_array($isoUpper, array_keys($OC_countryAR))) {
				$err .= "<li>Author #" . $c . " (2-letter) ISO country code is not valid</li>";
			} else {
				$_POST['country'.$c] = $OC_countryAR[$isoUpper];
			}
		}
	}
	// Check that we have alternate contact info for contact author
	if (!validEmail($_POST['contactaltemail']) && !preg_match("/\d/",$_POST['contactphone'])) {
		$err .= "<li>Enter a valid alternate email or phone number for contact author</li>";
	}
	// Check student
	if (!preg_match("/^[FT]$/", $_POST['student'])) {
		$err .= "<li>Student selection invalid</li>";
	}
	// Check topics
	if (empty($_POST['topic'])) {
		$err .= "<li>Select a topic area</li>";
	}

	if (oc_hookSet('author-submit-validate')) {
		foreach ($GLOBALS['OC_hooksAR']['author-submit-validate'] as $hook) {
			require_once $hook;
		}
	}
	
	// Check password
	if (empty($_POST['password1'])) {
		$err .= "<li>Password must be entered</li>";
	} elseif ($_POST['password1'] != $_POST['password2']) {
		$err .= "<li>Passwords entered do not match</li>";
	}

	// errors?
	if ($err) {
        print '<p><span class="err">Please check the following:<ul>' . $err . $errInc . '</ul></span><p /><hr><p />';
	} else {
		// Check that paper hasn't been submitted yet; if it has notify author and bail
		$q = "SELECT " . OCC_TABLE_PAPER . ".paperid FROM " . OCC_TABLE_PAPER . ", " . OCC_TABLE_AUTHOR . " WHERE " . OCC_TABLE_PAPER . ".title='" . safeSQLstr($_POST['title']) . "' AND " . OCC_TABLE_AUTHOR . ".paperid=" . OCC_TABLE_PAPER . ".paperid AND " . OCC_TABLE_AUTHOR . ".position=" . OCC_TABLE_PAPER . ".contactid AND " . OCC_TABLE_AUTHOR . ".name_last='" . safeSQLstr($_POST['name_last'.$_POST['contact']]) . "'";
		$r = ocsql_query($q) or err("Unable to verify whether submission has already been made " . mysql_errno());
		if (mysql_num_rows($r) > 0) {
			print '<p><span class="err">This submission appears to already have been made; please check your email for a confirmation. ';
			if ($OC_statusAR['OC_edit_open']) {
				print 'You may review or edit the submission <a href="edit.php">here</a>. ';
			}
			print 'Please contact the Chair with any questions.</span></p>';
			printFooter();
			exit;
		}
		
		$backupMsg = '';

		// add paper
		$q = "INSERT INTO `" . OCC_TABLE_PAPER . "` (`password`,`title`,`student`,`contactid`,`contactemail`,`contactphone`,`submissiondate`,`lastupdate`,`format`,`otherauthors`,`keywords`,`comments`,`abstract`) VALUES (" .
		"'" . hashPassword(stripslashes($_POST['password1'])) . "'," .
		"'" . safeSQLstr($_POST['title']) . "'," .
		"'" . $_POST['student'] . "'," .
		"'" . $_POST['contact'] . "'," .
		"'" . safeSQLstr(oc_strtolower($_POST['contactaltemail'])) . "'," .
		"'" . safeSQLstr($_POST['contactphone']) . "'," .
		"'" . date("Y-m-d") . "'," .
		"'" . date("Y-m-d") . "'," .
		"NULL," .
		"'" . safeSQLstr($_POST['otherauthors']) . "',".
		"'" . safeSQLstr($_POST['keywords']) . "',".
		"'" . safeSQLstr($_POST['comments']) . "',".
		"'" . safeSQLstr($_POST['abstract']) . "'".
		")";
		$r = ocsql_query($q) or err("unable to process submission ".mysql_errno());

        $backupMsg .= "$q\n\n";

		// get paper ID
		$pid = mysql_insert_id() or err("unable to get submission id ".mysql_errno());
	
	    // add authors
		for ($i=1;$i<=5;$i++) {
		  if (!empty($_POST["name_last$i"])) {
		    $q = "INSERT INTO " . OCC_TABLE_AUTHOR . " (paperid,position,name_last,name_first,organization,country,email) VALUES (".
			"'$pid',".
			"'$i',".
			"'".safeSQLstr($_POST["name_last$i"])."',".
			"'".safeSQLstr($_POST["name_first$i"])."',".
			"'".safeSQLstr($_POST["org$i"])."',".
			"'".safeSQLstr($_POST["country$i"])."',".
			"'".safeSQLstr($_POST["email$i"])."'".
			")";
			$r = ocsql_query($q) or err("unable to add one or more authors, but submission added.  Please edit submission. ".mysql_errno());
			$backupMsg .= "$q\n\n";
		  }
		}
	
	    // add topic(s)
		foreach ($_POST['topic'] as $t) {
	  		if (is_numeric($t)) {
				$q = "INSERT INTO " . OCC_TABLE_PAPERTOPIC . " (paperid,topicid) VALUES ($pid,$t)";
				$r = ocsql_query($q) or err("unable to add paper topic, but paper and authors added ".mysql_errno());
				$backupMsg .= "$q\n\n";
			}
			else { err("invalid submission topic - ..$t.."); }
		}
	
		if (!empty($OC_configAR['OC_subBackupEmail'])) {
			sendEmail($OC_configAR['OC_subBackupEmail'], "Submission ID $pid SQL", $backupMsg);
		}

		if (oc_hookSet('author-submit-save')) {
			foreach ($GLOBALS['OC_hooksAR']['author-submit-save'] as $hook) {
				require_once $hook;
			}
		}
		
		$confirmmsg = '
Soumission n. '.$pid.'

Title: '.stripslashes($_POST['title']).'
';
		if ($OC_configAR['OC_trackStudent'] == 1) {
			$confirmmsg .= 'Student: '.$_POST['student'];
		}
		for ($i=1;$i<=5;$i++) {
			$confirmmsg .= '
Author ' . $i;
			if ($i == $_POST['contact']) { $confirmmsg .= " (CONTACT AUTHOR)"; }
  			$confirmmsg .= '
  Name: '.stripslashes($_POST["name_first$i"] . " " . $_POST["name_last$i"]).'
  Org: '.stripslashes($_POST['org'.$i]).'
  Country: '.$_POST['country'.$i].'
  Email:'.$_POST['email'.$i];
		}

		$confirmmsg .= '
Autres auteurs : '.stripslashes($_POST['otherauthors']).'
Courriel de secours : '.$_POST['contactaltemail'].'
Téléphone : '.$_POST['contactphone'].'
Mots-clefs : '.stripslashes($_POST['keywords']).'
Résumé : '.stripslashes($_POST['abstract']).'
Commentaires : '.stripslashes($_POST['comments']) . '
';

		if (oc_hookSet('author-submit-confirm')) {
			foreach ($GLOBALS['OC_hooksAR']['author-submit-confirm'] as $hook) {
				require_once $hook;
			}
		}
		
		// confirm it
		print '
	<b>Merci pour votre soumission. Son identifiant est le n° ' . $pid . '.
        Notez ce numéro et mentionnez-le dans toute communication avec le commité de la conférence.
<p>Les informations ci-dessous récapitulent votre enregistrement, et une copie de ces informations est également envoyée par courriel à l\'auteur de contact. Si vous remarquez un problème ou si vous <b>ne</b> recevez <b>paq</b> le courriel d\'ici 24 heures, merci de contacter l\' <a href="mailto:' . $OC_configAR['OC_pcemail'] . '?subject=submission problem - ' . $pid . '">Admin.</a>.</b><p><pre>' . safeHTMLstr($confirmmsg) . '</pre>';
	
	    $confirmmsg = "Merci pour votre soumission à " . $OC_configAR['OC_confName'] . ".  Veuillez trouver ci-dessous une copie des informations enregistrées.\n\n" . $confirmmsg;

		sendEmail($contactemail, "Soumission n. $pid", $confirmmsg, $OC_configAR['OC_notifyAuthorSubmit']);
	
		printFooter();

		exit;
	} // else no errors
}

// Print Form
print '
<script language="javascript">
<!--
function showProcessing() {
	if (document.getElementById) {
		var procdiv = document.getElementById("processing");
		procdiv.style.visibility="visible";
	}
}
//-->
</script>

<span class="cat"><i>' . $OC_configAR['OC_paperSubNote'] . '</i></span>
<p><hr><p>

<form method="post" enctype="multipart/form-data" action="' . $_SERVER['PHP_SELF'] . '">
<table border=0 cellspacing=1 cellpadding=5 bgcolor="#dddddd">
<tr><td colspan=3 class="cat">Information générale / General Information</td></tr>
<tr>
<td class="item"><label for="form_title">Titre / Title :</label></td>
<td colspan=2><input name="title" id="form_title" size="75" maxlength="250" value="' . safeHTMLstr(varValue('title', $_POST)) . '"></td>
</tr>
';

if ($OC_configAR['OC_trackStudent'] == 1) {
	print '
<tr>
<td class="item" valign="top">Student?</td>
<td colspan=2>';

$studoptions = '<input name="student" id="form_studentYes" type="radio" value="T"><label for="form_studentYes">Yes</label> &nbsp; &nbsp;  <input name="student" id="form_studentNo" type="radio" value="F"><label for="form_studentNo">No</label>';

	if (isset($_POST['student']) && ($_POST['student'] == "T")) {
		print preg_replace("/(value=\"T\")/","$1 checked", $studoptions);
	}
	else {
		print preg_replace("/(value=\"F\")/","$1 checked", $studoptions);
	}

print '
  <br>
  <span class="note">' . $OC_configAR['OC_studentNote'] . '</span>
</td>
</tr>
	';
} else {
	print '<input type="hidden" name="student" value="F">';
}


if (oc_hookSet('author-submit-general')) {
	foreach ($GLOBALS['OC_hooksAR']['author-submit-general'] as $hook) {
		require_once $hook;
	}
}


print '
<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 class="cat">Auteur(s) / Author(s) Information</td></tr>
';

$colar = array(1,3,5);
for ($i=1;$i<=5;$i++) {
  if (in_array($i,$colar)) { $it = "item2"; } else { $it = "item"; }
  print '
<tr><td class="' . $it . '" rowspan=4>Auteur n°' . $i . '</td>
<td class="' . $it . '">Nom / Name :</td>
<td class="' . $it . '">';
 	if ($i==1) {
	    print '
	<table border=0 cellspacing=0 cellpadding=0>
	<tr><td>
	<input size=33 name="name_first' . $i . '" id="form_name_first' . $i . '" value="' . safeHTMLstr(varValue("name_first$i", $_POST)) . '" maxlength=60><br /><span class="note"><label for="form_name_first' . $i . '">Prénom / First Name</label></span>
	</td><td><nobr> &nbsp; &nbsp; </nobr></td><td>
	<input size=33 name="name_last' . $i . '" id="form_name_last' . $i . '" value="' . safeHTMLstr(varValue("name_last$i", $_POST)) . '" maxlength=40><br /><span class="note"><label for="form_name_last' . $i . '">Nom / Last Name</label></span>
	</td></tr>
	</table>';
  	} else {
		print '
<input size=33 name="name_first' . $i . '" value="' . safeHTMLstr(varValue('name_first'.$i, $_POST)) . '" maxlength=60> &nbsp; &nbsp; <input size=33 name="name_last' . $i . '" value="' . safeHTMLstr(varValue('name_last'.$i, $_POST)) . '" maxlength=40>';
	}
	
	print '
</td>
</tr>
<tr>
<td class="' . $it . '"><label for="form_org' . $i . '">Organisme / Organization :</label></td>
<td class="' . $it . '"><input name="org' . $i . '" id="form_org' . $i . '" size=75 maxlength=255 value="' . safeHTMLstr(varValue("org$i", $_POST)) . '">';

  if ($i==1) {
    print "<br><span class=\"note\">NOTE: L'organisme est votre entreprise, université, ... / Organization should be your company, university, or similar. Please do not use your department or division, unless it is part of your organization's name such as Interior Department.</span>";
  }

  print '</td>
</tr>
<tr>
<td class="' . $it . '" valign="top"><label for="form_country' . $i . '">Pays :</label></td>
<td class="' . $it . '"><input name="isocountry' . $i . '" size="2" id="form_country' . $i . '" title="Code pays de 2 lettres / ISO 2-letter country code" /> <select name="country' . $i . '"><option></option>' . generateSelectOptions($OC_countryAR, varValue("country$i", $_POST), FALSE) . '</select>';
	if ($i == 1) {
		print '<br /><span class="note">Entrez le code-pays (2 lettres), ou sélectionnez le pays dans la liste déroulante / Enter the 2-letter ISO country code above or select country name from drop-down menu.</span>';
	}
	print '</td>
</tr>
<tr>
<td class="' . $it . '"><label for="form_email' . $i . '">Courriel/Email :</label></td>
<td class="' . $it . '"><input name="email' . $i . '" id="form_email' . $i . '" size=75 maxlength=100 value="' . safeHTMLstr(varValue("email$i", $_POST)) . '"></td>
</tr>
';
}

print '
<tr>
<td class="item" valign="top"><label for="form_otherauthors">Auteurs<br />supplémentaires :<br /> / Additional<br />Authors:</label></td>
<td colspan=2>
<span class="note">Pour une soumission signée par plus de cinq auteurs, entrez les informations supplémentaires dans ce cadre<br />If you have more than 5 authors, please enter the additional information here:</span><br>
<textarea rows=4 cols=70 name="otherauthors" id="form_otherauthors">' . safeHTMLstr(varValue('otherauthors', $_POST)) . '</textarea></td>
</tr>
';

if (oc_hookSet('author-submit-authors')) {
	foreach ($GLOBALS['OC_hooksAR']['author-submit-authors'] as $hook) {
		require_once $hook;
	}
}

print '
<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 class="cat">Auteur à contacter / Contact Author</td></tr>
<tr><td colspan=3><span class="note">
Il s\'agit de l\'auteur responsable de la correspondance avec le site de la conférence.
Des informations supplémentaires sont demandées afin d\'assurer une communication rapide et de maintenir un programme exact. Les autres auteurs ne seront contactés que si nous sommes dans l\'incapacité de joindre ce dernier (p.ex. en cas d\'adresse erronée). Merci de nous notifier tout changement  dans les noms, affiliations, etc. de l\'"auteur à contacter".
<p>
NB: Si vous possédez une seconde adresse de courriel, entrez-la ici. Elle sera utilisée seulement en cas de problème avec la première.
<p>
/ The contact author is the person responsible for correspondence with the program chair. We ask for additional information for the contact author, so that we can ensure timely communication and make the program accurate. We will only contact authors other than the contact author if we are unable to reach the contact author (e.g., because of a bad email address). Please notify us of any changes in names, affiliations, etc. in the contact author\'s information.
<p>
Note: If you have more than one email address, please put the second address under "Alternate Email". We will only use that address if there is a problem with the primary email.
</span></td></tr>
<tr>
<td class="item"><label for="form_contact">Auteur à contacter<br />/Contact Author:</label></td>
<td colspan=2><select name="contact" id="form_contact">';

$contactoptions = '<option value="1">Auteur 1</option><option value="2">Auteur 2</option><option value="3">Auteur 3</option><option value="4">Auteur 4</option><option value="5">Auteur 5</option>';
if (isset($_POST['contact']) && is_numeric($_POST['contact'])) {
	print preg_replace("/(value=\"" . $_POST['contact'] . "\")/", "$1 selected", $contactoptions);
} else {
	print $contactoptions;
}

print '
</select></td>
</tr>
<tr>
<td class="item"><label for="form_contactaltemail">Autre courriel<br />/Alternate Email:</label></td>
<td colspan=2><input name="contactaltemail" id="form_contactaltemail" size=50 maxlength=100 value="' . safeHTMLstr(varValue("contactaltemail", $_POST)) . '"> <span class="note">Une seconde addresse de courriel,</span></td>
</tr>
<tr>
<td class="item"><label for="form_contactphone">Téléphone:</label></td>
<td colspan=2><input name="contactphone" id="form_contactphone" size=50 maxlength=30 value="' . safeHTMLstr(varValue("contactphone", $_POST)) . '"> <span class="note">ou un numéro de téléphone est requis</span></td>
</tr>
';


if (oc_hookSet('author-submit-contact')) {
	foreach ($GLOBALS['OC_hooksAR']['author-submit-contact'] as $hook) {
		require_once $hook;
	}
}


print '
<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 class="cat">Thèmes</td></tr>
<tr><td colspan=3><span class="note">
Pour faciliter l\'affectation des soumissions aux relecteurs et aux sessions, sélectionnez ';

if ($OC_configAR['OC_multipleSubmissionTopics']) {
	print 'un ou plusieurs thème(s)';
} else {
	print 'un thème';
}

print ' s\'appliquant au mieux à votre soumission :
</td></tr>
<tr><td colspan=3>
  <table border=0 cellspacing=0 cellpadding=0><tr><td valign="top">
';

$i=1;
if ($OC_configAR['OC_multipleSubmissionTopics']) {
	$type = 'checkbox';
} else {
	$type = 'radio';
}
foreach ($topicAR as $tid => $topic) {
	print '<label><input type="' . $type . '" name="topic[]" value="' . $tid . '"';
	if (isset($_POST['topic']) && in_array($tid, $_POST['topic'])) { print " checked"; }
	print ' />' . safeHTMLstr($topic) . '</label>';
	if (($OC_configAR['OC_topicColumns'] == 2) && ($i++ == $half)) {
		print "</td><td><nobr> &nbsp; &nbsp; &nbsp; &nbsp; </nobr></td><td valign=\"top\">";
	}
	else {
		print "<br />\n";
	}
}

print '
  </td></tr></table>
</td></tr>
';


if (oc_hookSet('author-submit-topics')) {
	foreach ($GLOBALS['OC_hooksAR']['author-submit-topics'] as $hook) {
		require_once $hook;
	}
}


print '
<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 class="cat">Contenu / Content</td></tr>

<tr>
<td class="item"><label for="form_keywords">Mots-clefs / Keywords :</label></td>
<td colspan=2><input name="keywords" id="form_keywords" size="75" maxlength="250" value="' . safeHTMLstr(varValue("keywords", $_POST)) . '"></td>
</tr>

<tr>
<td class="item" valign="top"><label for="form_abstract">Résumé / Abstract</label></td>
<td colspan=2><textarea name="abstract" id="form_abstract" rows="8" cols="70">' . safeHTMLstr(varValue("abstract", $_POST)).'</textarea></td>
</tr>
';

if (oc_hookSet('author-submit-content')) {
	foreach ($GLOBALS['OC_hooksAR']['author-submit-content'] as $hook) {
		require_once $hook;
	}
}


print '
<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 class="cat">Mot de passe / Password</td></tr>

<tr><td colspan=3><span class="note">
A l\'aide de ce mot de passe et du numéro d\'identification de la soumission que vous allez recevoir par courriel, vous pourrez effectuer des modifications de votre soumission / Please enter a password you will remember.  The submission id, which you will receive via email upon submission of this form, along with this password will allow you to make future changes to this submission.
</span></td></tr>

<tr>
<td class="item"><label for="form_password">Mot de passe :</label></td>
<td colspan=2><input type="password" name="password1" id="form_password" size="20" maxlength="30" value="' . safeHTMLstr(varValue("password1", $_POST)) . '"></td>
</tr>

<tr>
<td class="item"><label for="form_password2">Confirmation :</label></td>
<td colspan=2><input type="password" name="password2" id="form_password2" size="20" maxlength="30" value="' . safeHTMLstr(varValue("password2", $_POST)) . '"></td>
</tr>

<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 class="cat">Commentaires / Comments</td></tr>

<tr><td colspan=3><span class="note">(optionnel/optional)</td></tr>

<td valign="top" class="item"><label for="form_comments"></label><br /><span class="note"></span></td>
<td colspan=2><textarea name="comments" id="form_comments" cols="70" rows="4">' . safeHTMLstr(varValue("comments", $_POST)) . '</textarea></td>
</tr>
';


if (oc_hookSet('author-submit-comments')) {
	foreach ($GLOBALS['OC_hooksAR']['author-submit-comments'] as $hook) {
		require_once $hook;
	}
}


print '
<tr><td colspan=3 class="sep">&nbsp;<br>&nbsp;</td></tr>

<tr><td colspan=3 valign="top" class="cat">Confirmation</td></tr>
<tr>
<td colspan=3>
<span class="note">
Après avoir vérifié que tout est bien rempli, cliquez sur le bouton Soumettre, ci-dessous. /
Please check over your entries, making sure everything is filled out.  When ready, click on the Soumettre button below.</span><p>
<input type="submit" name="submit" value="Soumettre" onclick="this.style.visibility=\'hidden\'; showProcessing();" />
<br />
<span id="processing" style="position: relative; visibility: hidden;">Processing...</span>
</td>
</tr>

';

print '
</table>
</form>
';

printFooter();

?>
