<?php
defined('MAXIMUS') or Header("Location: ../../index.php");

$module_name = "ePetitions";
get_lang($module_name);
$pagetitle = "- "._NEP_PETITION."";
$index = 1;

include_once("includes/ePetitions.php");

define("_NEP_TIME_OK",0);
define("_NEP_TIME_NOTSTARTED",1);
define("_NEP_TIME_FINISHED",2);

function NSNInTime($timestart,$timeend)
{
	$iNowTime=time();
	ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $timestart, $datetimestart);
	ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $timeend, $datetimeend);
	$iTimeStart=mktime(intval($datetimestart[4]), intval($datetimestart[5]),intval($datetimestart[6]),intval($datetimestart[2]),intval($datetimestart[3]),intval($datetimestart[1]));
	$iTimeEnd=mktime(intval($datetimeend[4]), intval($datetimeend[5]),intval($datetimeend[6]),intval($datetimeend[2]),intval($datetimeend[3]),intval($datetimeend[1]));
	if($timestart=="0000-00-00 00:00:00") $iTimeStart=$iNowTime;
	if($timeend=="0000-00-00 00:00:00") $iTimeEnd=$iNowTime;

	$ret=_NEP_TIME_OK;
	if($iNowTime<$iTimeStart) $ret=_NEP_TIME_NOTSTARTED;
	else if($iNowTime>$iTimeEnd) $ret=_NEP_TIME_FINISHED;

	return $ret;

}

function validate_signer($check_num)
{
	global $db, $prefix;
	incoh();

	if($row = $db->sql_fetchrow($db->sql_query("SELECT ePetitionId,mailinglist,eMailAddress FROM ".$prefix."_nsngrept_signers WHERE validationString='$check_num'")))
	{
		$ePetitionId=intval($row['ePetitionId']);
		$mailinglist=intval($row['mailinglist']);
		$user_email=$row['eMailAddress'];
		if($row = $db->sql_fetchrow($db->sql_query("SELECT enabled,timestart,timeend,mailinglist FROM ".$prefix."_nsngrept_petitions WHERE ePetitionId='$ePetitionId'")))
		{
			$enabled=intval($row['enabled']);
			$timestart=intval($row['timestart']);
			$timeend=intval($row['timeend']);
			$mailinglistnumber=intval($row['mailinglist']);

			if($enabled==0 || NSNInTime($timestart,$timeend)!=_NEP_TIME_OK)
			{
				Max_OpenTable();
					echo "<center>"
						."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSCLOSED."<br />"
						."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
					."</center>";
				Max_CloseTable();
			}
			else
			{
				if($db->sql_query("UPDATE ".$prefix."_nsngrept_signers set validationString='' WHERE validationString='$check_num'"))
				{
					$db->sql_query("UPDATE ".$prefix."_nsngrept_petitions set voters=voters+1 WHERE ePetitionId='$ePetitionId'");
     Max_OpenTable();
						echo "<center>"
							."<b>"._NEP_EPETITIONSOK."</b><br />";
						if(file_exists("includes/nsnml_func.php") && $mailinglist==1 && $mailinglistnumber>0)
						{
							if(NSNePetitionsSuscribeMailingList($user_email,$mailinglistnumber)==1)
								echo _NEP_EPETITIONSOKML."<br />";
						}
						echo _NEP_EPETITIONSTHANK."<br />"
							."<input type=\"button\" onClick=\"window.location.href('index.php')\" value=\""._NEP_EPETITIONSHOME."\">"
						."</center>";
     Max_CloseTable();
				}
				else
				{
     Max_OpenTable();
						echo "<center>"
							."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSINVALIDCONFIRM."<br />"
							."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
						."</center>";
     Max_CloseTable();
				}
			}
		}
		else
		{
   Max_OpenTable();
				echo "<center>"
					."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSNOTASSIGNED."<br />"
					."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
				."</center>";
   Max_CloseTable();
		}
	}
	else
	{
  Max_OpenTable();
			echo "<center>"
				."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSINVALIDCONFIRM."<br />"
				."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
			."</center>";
  Max_CloseTable();
	}

	incof();
}

function new_signer($user,$ePetitionId,$user_name,$user_email,$user_from,$user_comment,$mailinglist)
{
	global $adminmail,$nukeurl,$module_name,$db,$prefix;
 incoh();
	title(""._NEP_EPETITIONSTITLESIGNED."");
	if($row = $db->sql_fetchrow($db->sql_query("SELECT ePetitionId,name,hidesigner,view,enabled,voters,timestart,timeend,validation,mailinglist FROM ".$prefix."_nsngrept_petitions WHERE ePetitionId='$ePetitionId'")))
	{
		$hidesigner=intval($row['hidesigner']);
		$view=intval($row['view']);
		$voters=intval($row['voters']);
		$enabled=intval($row['enabled']);
		$timestart=intval($row['timestart']);
		$timeend=intval($row['timeend']);
		$validation=intval($row['validation']);
		$name=$row['name'];
		$mailinglistnumber=$row['mailinglist'];

		if($view!=0) $user_groups_cache=load_usergroups_cache($user);
		if($view!=0 && cached_is_visible_for_user($user_groups_cache,$view,$user,$admin)!=1)
		{
			// acces interdit au niveau sécurité nsn groupes
   Max_OpenTable();
				echo "<center><b>"._NEP_EPETITIONSFORBIDDEN."</b></center>";
   Max_CloseTable();
		}
		else
		{
			// la pétition a été desactivée ou le créneau de saisie a été dépassé
			if($enabled!=1 || NSNInTime($timestart,$timeend)!=_NEP_TIME_OK)
			{
    Max_OpenTable();
						echo "<center><b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSCLOSED."</center>";
    Max_CloseTable();
			}
			else // enfin ! c'est ici que nous pouvons vérifier la signature...
			{
				if(!isset($user_email) || $user_email=="" || !check_email($user_email)) // mais l'utilisateur n'a pas mis d'adresse email
				{
     Max_OpenTable();
						echo "<center>"
							."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSEMAILNEEDED."<br />"
							."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
						."</center>";
     Max_CloseTable();

				}
				else // l'adresse email est présente mais elle ne doit pas djéà avoir été utilisée
				{
					if($row = $db->sql_fetchrow($db->sql_query("SELECT ePetitionSignerId FROM ".$prefix."_nsngrept_signers WHERE ePetitionId='$ePetitionId' AND eMailAddress='$user_email'")))
					{
      Max_OpenTable();
							echo "<center>"
								."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSALREADYSIGNED."<br />"
								."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
							."</center>";
      Max_CloseTable();
					}
					else // nous voici à l'endroit où nous allons créer l'enregistrement
					{
						mt_srand ((double)microtime()*1000000);
						$maxran = 1000000;
						$check_num = mt_rand(0, $maxran);
						$check_num = md5($check_num);
						if($validation==0) $check_num="";
						if($db->sql_query("INSERT INTO ".$prefix."_nsngrept_signers (`ePetitionId` ,`userName`, `city`, `eMailAddress`,`comment`,`timesigned`,`validationString`,`mailinglist`)  VALUES ($ePetitionId, '$user_name', '$user_from', '$user_email', '$user_comment',now(),'$check_num','$mailinglist')"))
						{
							if($validation==0) // no validation needed... inserer la signature
							{
								$db->sql_query("UPDATE ".$prefix."_nsngrept_petitions set voters=voters+1 WHERE ePetitionId='$ePetitionId'");
        Max_OpenTable();
									echo "<center>"
										."<b>"._NEP_EPETITIONSOK."</b><br />";
									if(file_exists("includes/nsnml_func.php") && $mailinglist==1 && $mailinglistnumber>0)
									{
										if(NSNePetitionsSuscribeMailingList($user_email,$mailinglistnumber)==1)
											echo _NEP_EPETITIONSOKML."<br />";
									}
									echo _NEP_EPETITIONSTHANK."<br />"
										."<input type=\"button\" onClick=\"window.location.href('index.php')\" value=\""._NEP_EPETITIONSHOME."\">"
									."</center>";
        Max_CloseTable();
							}
							else // une validation a été demandée, envoyons un mail de confirmation mais insérons tout de meme l'enregistrment..
							{
								NSNePetitionsSendMail($module_name,$check_num,$user_email,$name);
        Max_OpenTable();
									echo "<center>"
										."<b>"._NEP_EPETITIONSTAKEN."</b><br />"._NEP_FINISHUSERSIGN."<br />"
										."<input type=\"button\" onClick=\"window.location.href('index.php')\" value=\""._NEP_EPETITIONSHOME."\">"
									."</center>";
        Max_CloseTable();
							}
						}
						else
						{
       Max_OpenTable();
								echo "<center>"
									."<b>"._NEP_EPETITIONSNOTSIGNED."</b><br />"._NEP_EPETITIONSRECORDERROR."<br />"
									."<input type=\"button\" onClick=\"history.go(-1)\" value=\""._NEP_EPETITIONSBACK."\">"
								."</center>";
       Max_CloseTable();
						}
					}
				}
			}
		}
	}
	else
	{
  Max_OpenTable();
			echo "<b>"._NEP_EPETITIONSDOESNOTEXIST."</b>";
  Max_CloseTable();
	}
 incof();
}
function more_info($pid,$Action,$show_signers)
{
	global $db, $prefix, $user, $admin, $module_name;
 incoh();

	switch($Action)
	{
		case "editNotes":
			$titleText=_NEP_MOREINFOTITLE_NOTES;
			break;
		default:
			$titleText=_NEP_MOREINFOTITLE;
			break;
	}

	echo "<table width=\"100%\" border=\"0\"><tr><td valign=\"top\" width=\"100%\">\n";

  Max_OpenTable();
			echo "<center><font class='title'><b>".$titleText."</b></font></center>";
  Max_CloseTable();

		if($row = $db->sql_fetchrow($db->sql_query("SELECT ePetitionId,name,hidesigner,view,enabled,voters,timestart,timeend,hideemail,modifynotes,notestext,mailinglist FROM ".$prefix."_nsngrept_petitions WHERE ePetitionId='$pid'")))
		{
			$hidesigner=intval($row['hidesigner']);
			$view=intval($row['view']);
			$voters=intval($row['voters']);
			$enabled=intval($row['enabled']);
			$timestart=intval($row['timestart']);
			$timeend=intval($row['timeend']);
			$hideemail=intval($row['hideemail']);
			$modifynotes=intval($row['modifynotes']);
			$notestext=$row['notestext'];
			$mailinglist=$row['mailinglist'];
			$modifynotesLink="";

			$user_groups_cache=load_usergroups_cache($user);
			if($view==0 || cached_is_visible_for_user($user_groups_cache,$view,$user,$admin)==1)
			{
				echo "<br />";
    Max_OpenTable();
				if($Action=="" && cached_is_visible_for_user($user_groups_cache,$modifynotes,$user,$admin)==1) $modifynotesLink="modules.php?name=ePetitions&op=more_info&ePetitionId=".$pid."&Action=editNotes#editNotesBox";

				NSNePetitionsView($pid,$modifynotesLink);
				if($Action=="editNotes" && cached_is_visible_for_user($user_groups_cache,$modifynotes,$user,$admin)==1)
				{
					echo "<a name=editNotesBox></a><form method=post action=\"modules.php?name=ePetitions&op=validate_notes\">\n";
						echo "<input type=\"hidden\" name=\"gid\" value=\"".$pid."\">\n";
						echo "<b>"._NEP_NOTES."</b><br />"
							."<textarea wrap=\"virtual\" cols=\"50\" rows=\"4\" name=\"notestext\">$notestext</textarea><br /><br />";
						echo "<INPUT TYPE=SUBMIT VALUE=\""._NEP_OK."\"><INPUT TYPE=BUTTON VALUE=\""._NEP_CANCEL."\" onClick=\"history.go(-1)\">\n";
					echo "</form>\n";

				}

				if($enabled==1 && NSNInTime($timestart,$timeend)==_NEP_TIME_OK)
				{
					echo "<hr>";
					$myContent=NSNePetitionsSign($pid,$row['name'],$voters,1,0,$mailinglist);
					echo $myContent;
				}
    Max_CloseTable();
				if($hidesigner==0 || cached_is_visible_for_user($user_groups_cache,$hidesigner,$user,$admin)==1)
				{
					echo "<br />";
					if( $show_signers==1)
					{
      Max_OpenTable();
							echo "<a name=shownOrNotSigners></a><a href=\"modules.php?name=ePetitions&op=more_info&ePetitionId=$pid&show_signers=0#shownOrNotSigners\"><b><img src=\"images/epetitions/delete.png\" height=\"16\" width=\"16\" border=\"0\" alt=\""._NEP_HIDEWHOALREADYSIGNED."\" title=\""._NEP_HIDEWHOALREADYSIGNED."\">"._NEP_HIDEWHOALREADYSIGNED."</b></a><br />";
							NSNePetitionsShowSigners($pid, "", "AND validationString=''",cached_is_visible_for_user($user_groups_cache,$hideemail,$user,$admin));
      Max_CloseTable();
					}
					else
					{
      Max_OpenTable();
						echo "<a name=shownOrNotSigners></a><a href=\"modules.php?name=ePetitions&op=more_info&ePetitionId=$pid&show_signers=1#shownOrNotSigners\"><b><img src=\"images/epetitions/view.gif\" height=\"16\" width=\"16\" border=\"0\" alt=\""._NEP_WHOALREADYSIGNED."\" title=\""._NEP_WHOALREADYSIGNED."\">"._NEP_WHOALREADYSIGNED."</b></a>";
      Max_CloseTable();
					}
				}
			}
			else
			{
    Max_OpenTable();
					echo "<center><b>"._NEP_EPETITIONSFORBIDDEN."</b></center>";
    Max_CloseTable();
			}
		}
		else
		{
   Max_OpenTable();
				echo "<center><b>"._NEP_EPETITIONSDOESNOTEXIST."</b></center>";
   Max_CloseTable();
		}

	echo "</td><td>&nbsp;</td><td valign=\"top\">\n";

	$optiontitle = ""._OPTIONS."";
	$optionbox = "<br />";
	$optionbox .= "&nbsp;<img src='images/print.gif' border='0' alt='"._PRINTER."' title='"._PRINTER."'> <a href=\"modules.php?name=$module_name&amp;file=print&amp;pid=$pid\">"._PRINTER."</a><br /><br />";
	$optionbox .= "&nbsp;<img src='images/friend.gif' border='0' alt='"._FRIEND."' title='"._FRIEND."'> <a href=\"modules.php?name=$module_name&amp;file=friend&amp;op=FriendSend&amp;sid=$pid\">"._FRIEND."</a><br /><br /></center>\n";
	themesidebox($optiontitle, $optionbox);

	echo "</td></tr></table>\n";

 incof();
}

function show_all() {
    global $prefix, $db, $bgcolor1, $bgcolor2, $user, $admin;
    incoh();
    title(""._NEP_EPETITIONSTITLE."");
    Max_OpenTable();
		echo "<table width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"1\"><tr>"
			."<td bgcolor=\"$bgcolor2\" align=\"left\" width=\"30%\"><b>"._NEP_SIGNERDATE."</b></td>"
			."<td bgcolor=\"$bgcolor2\" align=\"center\" width=\"45%\"><b>"._NEP_EPETITIONNAME."</b></td>"
			."<td bgcolor=\"$bgcolor2\" align=\"center\" width=\"5%\"><b>"._NEP_SIGNERS."</b></td>"
			."<td bgcolor=\"$bgcolor2\" align=\"right\" width=\"15%\"><b>"._NEP_EPETITIONSTATUS."</b></td>"
			."<td bgcolor=\"$bgcolor2\" align=\"center\" width=\"5%\"><b>"._NEP_EPETITIONSACTIONS."</b></td>"
			."</tr>";

        $result = $db->sql_query("SELECT createdtime, ePetitionId, name, enabled, view, voters, timestart, timeend FROM ".$prefix."_nsngrept_petitions ORDER BY createdtime DESC, name ASC");

		$user_groups_cache=load_usergroups_cache($user);
        while(list($createdtime, $ePetitionId,$name,$enabled, $view,$voters,$timestart,$timeend) = $db->sql_fetchrow($result))
		{
			if($view==0 || cached_is_visible_for_user($user_groups_cache,$view,$user,$admin)==1)
			{
				if($enabled==1)
				{
					$timeStatus=NSNInTime($timestart,$timeend);
					switch($timeStatus)
					{
						case _NEP_TIME_NOTSTARTED:
							$enabledText=_NEP_EPETITIONSNOTSTARTED;
							break;
						case _NEP_TIME_FINISHED:
							$enabledText=_NEP_EPETITIONSTATUSCLOSED;
							break;
						case _NEP_TIME_OK;
						default:
							$enabledText="<b>"._NEP_EPETITIONSTATUSOPENED."</br>";
							break;
					}
				}
				else $enabledText=_NEP_EPETITIONSTATUSCLOSED;
				echo "<tr><td bgcolor=\"$bgcolor1\" align=\"left\" nowrap>$createdtime</td>"
					."<td bgcolor=\"$bgcolor1\" align=\"center\"><a href=\"modules.php?name=ePetitions&amp;op=more_info&amp;ePetitionId=$ePetitionId\">$name</a></td>"
					."<td bgcolor=\"$bgcolor1\" align=\"center\">$voters</td>"
					."<td bgcolor=\"$bgcolor1\" align=\"right\">$enabledText</td>"
					."<td bgcolor=\"$bgcolor1\" align=\"center\"><a href=\"modules.php?name=ePetitions&amp;file=print&amp;pid=$ePetitionId\"><img src=\"images/print.gif\" border=0 alt=\""._NEP_EPETITIONPRINTER."\" title=\""._NEP_EPETITIONPRINTER."\" width=\"16\" height=\"11\"></a>&nbsp;<a href=\"modules.php?name=ePetitions&amp;file=friend&amp;op=FriendSend&amp;sid=$ePetitionId\"><img src=\"images/friend.gif\" border=0 alt=\""._FRIEND."\" title=\""._FRIEND."\" width=\"15\" height=\"11\"></a></td>"
					."</tr>";
			}
		}
		echo "</table>";
 Max_CloseTable();
 incof();
}

switch($op) {


    case "activate":
		validate_signer($check_num);
		break;

	case "new_signer";
		new_signer($user,$ePetitionId,$user_name,$user_email,$user_from,$user_comment,$mailinglist);
	    break;

    case "more_info";
		$index = 0;
		more_info($ePetitionId,$Action,intval($show_signers));
	    break;

    case "validate_notes":
		if($row = $db->sql_fetchrow($db->sql_query("SELECT ePetitionId,modifynotes FROM ".$prefix."_nsngrept_petitions WHERE ePetitionId='$gid'")))
		{
			$modifynotes=stripslashes(FixQuotes(intval($row['modifynotes'])));
			$user_groups_cache=load_usergroups_cache($user);
			if(cached_is_visible_for_user($user_groups_cache,$modifynotes,$user,$admin)==1)
				$db->sql_query("UPDATE ".$prefix."_nsngrept_petitions set notestext='$notestext' WHERE ePetitionId='$gid'");
		}
	    Header("Location: modules.php?name=ePetitions&op=more_info&ePetitionId=$gid");
		break;

	default:
		show_all();
		break;


}