<?php 
session_start();
require 'authenticate.user.php';

require 'configuration.php';
require_once 'includes/common.functions.php';
require_once ('classes/database.php');
require_once ('classes/functions.php');
$sqlObj = new mysqlClass;
$funcObj = new funcClass;
$table = "##smtp";
$ACTION				= 'add';
$TITLE				= NULL;
$HOST				= NULL;
$PORT 				= NULL;
$USER				= NULL;
$PASSWORD			= NULL;
$AUTHENTICATION		= NULL;
$AUTHENTICATION_CHECKED=NULL;
$DEFAULT_CHECKED=NULL;
$BOUNCE_EMAIL		= NULL;
$DEFAULT 			= NULL;
$ID					= NULL;
require_once ('includes/validate.managesmtp.php');

//ADD RECORD
if ((isset($_POST['formaction']) && $_POST['formaction'] == 'add') && (empty($error)))
{
	
	
	# check for duplicate record entry
	$query = "SELECT COUNT(*) FROM $table WHERE TITLE = '$TITLE'";
	$query_count=$funcObj->CustomQueryCount($query)['0']['COUNT(*)'];
	if ($query_count == 0)
	{
		$PASSWORD = base64_encode(base64_encode($PASSWORD));
		$query = "INSERT INTO $table SET MAILER_TYPE='smtp', TITLE='$TITLE', HOST='$HOST', PORT='$PORT', USER='$USER', PASSWORD='$PASSWORD', 
		BOUNCE_EMAIL = '$BOUNCE_EMAIL', AUTHENTICATION='$AUTHENTICATION',LAST_UPDATED=NOW()";
		
		$insertId = $funcObj->insertQuery($query);
		/*
		If it is the default SMTP then remove
		DEFAULT from all other records and
		update this record with a default = 1
		*/
		
		if ($DEFAULT)
		{
			$query = "UPDATE $table SET `DEFAULT`=0"; 
			$funcObj->updateQuery($query);
			
			$query = "UPDATE $table SET `DEFAULT`='1' WHERE ID = '$insertId'"; 
			$funcObj->updateQuery($query);
		}
		
		if ($insertId > 0)
		{
			$message = "Record has been added successfully";
		}
		## RESET THE FORM SO THAT 
		## NO VALUES SHOULD BE SHOWN
		## IF THE FORM IS IN THE ADD
		## MODE
	}
	else
	{
		$message = "Same SMTP title already available. Please try another title.";
	}
}

//EDIT RECORD
if ((isset($_POST['formaction']) && $_POST['formaction'] == 'edit') && (empty($error)))
{
	
	
	# check for duplicate record entry
	$query = "SELECT COUNT(*) FROM $table WHERE TITLE = '$TITLE'";
	$countRecords = $funcObj->CustomQueryCount($query)[0]['COUNT(*)'];
	
	if ($countRecords < 2)
	{
		
		$query = "UPDATE $table SET MAILER_TYPE='smtp', TITLE='$TITLE', HOST='$HOST', PORT='$PORT', USER='$USER',";
		if (!empty($PASSWORD))
		{
			$PASSWORD = base64_encode(base64_encode($PASSWORD));
			$query .= " PASSWORD='$PASSWORD', ";
		}
		$query .= "BOUNCE_EMAIL='$BOUNCE_EMAIL', AUTHENTICATION='$AUTHENTICATION', LAST_UPDATED=NOW()";
		$query .= " WHERE ID = {$ID}";
		
		$updateId = $funcObj->updateQuery($query);
		
		/*
		If it is the default SMTP then remove
		DEFAULT from all other records and
		update this record with a default = 1
		*/
		
		if ($DEFAULT)
		{
			$query = "UPDATE $table SET `DEFAULT`=0"; 
			$funcObj->updateQuery($query);
			
			$query = "UPDATE $table SET `DEFAULT`='1' WHERE ID = '$ID'"; 
			$funcObj->updateQuery($query);
		}
		
		if ($updateId == 1)
		{
			$message = "Record has been successfully updated.";
		}
		
		## RESET THE FORM SO THAT 
		## NO VALUES SHOULD BE SHOWN
		## IF THE FORM IS IN THE ADD
		## MODE
		
	}
	else
	{
		$message = "User already registered with same e-mail. Please try another e-mail address.";
	}
}

## if edit is EDIT
# then load values into the form

if (isset($_GET['action']) && $_GET['action'] == 'edit')
{
	$ID = $_GET['id'];
	$whereFields['ID'] = $ID;
	$resultSet = $funcObj->getRecordDetails($table,$whereFields);
	$ID					= trim($funcObj->AppendSlashes($resultSet[0]['ID']));
	$TITLE				= trim($funcObj->AppendSlashes($resultSet[0]['TITLE']));	
	$HOST				= trim($funcObj->AppendSlashes($resultSet[0]['HOST']));
	$PORT				= trim($funcObj->AppendSlashes($resultSet[0]['PORT']));
	$USER				= trim($funcObj->AppendSlashes($resultSet[0]['USER']));
	$AUTHENTICATION		= $resultSet[0]['AUTHENTICATION'];
	$BOUNCE_EMAIL		= trim($funcObj->AppendSlashes($resultSet[0]['BOUNCE_EMAIL']));
	$DEFAULT			= $resultSet[0]['DEFAULT'];

	$ACTION				= 'edit';
	
	$AUTHENTICATION_CHECKED = ($AUTHENTICATION == 1) ? 'checked="checked"' : '';
	$DEFAULT_CHECKED = ($DEFAULT == 1) ? 'checked="checked" disabled="disabled"' : '';
}

$superID = 1;
$searchbox=isset($_REQUEST['searchbox']) ? $_REQUEST['searchbox']: '';
$searchTxt = trim($funcObj->AppendSlashes($searchbox));
$searchArray = 'ID,TITLE,USER,BOUNCE_EMAIL,HOST,MAILER_TYPE,PORT';
$status=isset($_REQUEST['status']) ? $_REQUEST['status']: '';
$ID=isset($_REQUEST['id']) ? $_REQUEST['id']: '';
if(isset($_GET['action']) && $_GET['action']=='default')
{
	/*
	If it is the default SMTP then remove
	DEFAULT from all other records and
	update this record with a default = 1
	*/
	$query = "UPDATE $table SET `DEFAULT`=0"; 
	$funcObj->updateQuery($query);
	
	$query = "UPDATE $table SET `DEFAULT`='1' WHERE ID = '$ID'"; 
	$funcObj->updateQuery($query);
}	

if(isset($_GET['action']) && $_GET['action']=='del')
{
	$whereField = "ID";
	$whereValue = $ID;
	$funcObj->DeleteRecord($table,$whereField,$whereValue);
	$message = "Mailer has been deleted successfully";
}
$resultSet = $funcObj->CountAllRecords("$table",$searchTxt,$searchArray);

$records	= $funcObj->fetchParameterValue('SHOW_RECORDS_PER_PAGE')[0]['FIELDVALUE'];
if($records > 0)
{
	$limit = intval($records);
}
else
{
	$limit = $configAdminPaging;
}

if(isset($_REQUEST['start']))
	$start = $_REQUEST['start'];
else
	$start = 0;
	


$proCount = $resultSet;
$link = 'managesmtp.php?searchbox='.$searchbox;

require_once('classes/paging.class.php');

$pageObj = new Paging( $proCount, $start , $limit);

/* ACTIVATE THE TAB */
$activeTab = 'Administration';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Segnant Mailer - Manage Mailers (SMTP)</title>
<link rel="stylesheet" type="text/css" href="includes/css/segnantmailer.css" />
<link rel="stylesheet" href="includes/css/themes/blue/style.css" type="text/css"  media="print, projection, screen" />
<link rel="stylesheet" type="text/css" href="includes/css/paging.css"  />
<link rel="stylesheet" type="text/css" href="./includes/css/jquery.fancybox-1.3.0.css" media="screen" />
<script type="text/javascript" src="includes/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="./includes/js/jquery.fancybox-1.3.0.pack.js"></script>
<script type="text/javascript" src="http://fancybox.net/js/fancybox/jquery.easing-1.3.pack.js"></script>
<script type="text/javascript" src="includes/js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="includes/js/common.jquery.js"></script>
<script type="text/javascript" src="includes/js/managesmtp.jquery.js"></script>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td height="79" class="headerbg"><?php require_once 'includes/inc.header.php' ?>    
    </td>
  </tr>

  <tr>
    <td class="canvas" height="300" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="4">
      <tr>
        <td colspan="2" class="heading" height="50" valign="top">Manage Mailers</td>
        </tr>
      <tr>
        <td colspan="2" bgcolor="#eaeaea" style="padding:10px;">
        <table cellspacing="0" cellpadding="0" class="tabtable" >
<tr>
<?php
$file = basename($_SERVER['PHP_SELF']);

## ADD EXCEPTIONS

$tabArray = array("<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='managesmtp.php'\"> Manage Mailers </td>",
		"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='settings.php'\"> General Settings </td>",
		"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='db_dump.php'\"> Export Database </td>"
		);
foreach ($tabArray as $key => $val)
{
	$strpos = strpos($val, $file);

	if ($strpos > 0)
	{
		$newString = str_replace('style="cursor:pointer;"','style="cursor:pointer;" class="active" ',$val);
		echo $newString;
	}
	else
	{
		echo $val;
	}	
}
?>
</tr>
</table>
        <table width="100%" border="0" cellspacing="0" cellpadding="4">
                <tr>
                  <td height="405" bgcolor="#FFFFFF" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="1">
                      <tr>
                        <td class="pageHeading">Manage Mailers</td>
                      </tr>
                      <tr>
                        <td height="55" valign="top" align="right"><form name="formsearch" method="get" style="margin: 0;" action="">
                            <table border="0" cellspacing="2" cellpadding="2" align="right">
                              <tr>
                                <td nowrap="nowrap"><strong>Search</strong></td>
                                <td><input type="text" placeholder="search" name="searchbox" class="textbox" value="<?=$funcObj->RemoveSlashes($searchbox)?>" style="margin-bottom: 2px;" size="20" /></td>
                                <td><input type="submit" name="submit" value="Search" class="button size2" /></td>
                              </tr>
                            </table>
                          </form></td>
                      </tr>
                      <?php if (!empty($message))
					  echo "
                      <tr>
                        <td class='message'>$message</td>
                      </tr>
					  ";
					  ?>
                      <tr>
                        <td><table cellspacing="1" class="tablesorter">
                        <thead>
                            <tr>
                              <th width="35" align="center">ID</th>
                              <th align="left" width="10%">Mailer Type</th>
                              <th align="left">Title</th>
                              <th width="17%" align="left">Host</th>
                              <th width="20%" align="left">User</th>
							  <th width="20%" align="left">Bounce Email</th>
                              <th width="50" align="center">Port</th>
                              <th width="70" align="center">Default</th>
                              <th width="100">Action</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
					$resultSet = $funcObj->FetchRecords("$table",$searchTxt,$searchArray,'ID DESC', $pageObj->start, $pageObj->limit);
					$i=1;
					if(count($resultSet)!=0)
					{
					foreach ($resultSet as $row)
					{
						$i++;
						$inActive = ($row['MAILER_TYPE'] == 'smtp') ? '' : 'inactive';
						$className="$inActive";
						echo "<tr $className>";
						
						echo "
						<td align='center'>{$row['ID']} </td>
						<td align='left'>{$row['MAILER_TYPE']}</td>
						<td align='left'>{$row['TITLE']} &nbsp;</td>
						<td align='left'>{$row['HOST']} &nbsp;</td>
						<td align='left'>{$row['USER']} &nbsp;</td>
						<td align='left'>{$row['BOUNCE_EMAIL']} &nbsp;</td>
						<td align='center'>{$row['PORT']} &nbsp;</td>
						<td align='center'>";
						echo ($row['DEFAULT'] == '1') ? "<img src='images/tick.png' alt='' />" : "<a href='managesmtp.php?action=default&amp;id={$row["ID"]}'><img src='images/tick0.png' border='0' alt='' /></a>" ;
						echo "</td>
						
						<td align='center'>";
						if (!$inActive)
						{
							echo "
							<a class='smtptest' href='./smtp.test.php?id={$row["ID"]}'><img src='images/config.gif' title='Test SMTP' border='0' alt='' /></a>&nbsp;&nbsp;&nbsp;
							<a href='managesmtp.php?action=edit&amp;id={$row["ID"]}'><img src='images/edit.gif' alt='Edit' title='Edit' border='0' /></a>&nbsp;&nbsp;&nbsp;";
							echo "<a href='javascript:confirmAction(\"Are you sure you want to delete this mailer?\",\"managesmtp.php?action=del&amp;id={$row['ID']}\")'><img src='images/delete.gif' alt='Delete' title='Delete' border='0' /></a>";
						}
						else
						{
							echo "
							<a class='smtptest' href='./smtp.test.php?id={$row["ID"]}'><img src='images/config.gif' title='Test SMTP' border='0' /></a>&nbsp;&nbsp;&nbsp;
							<img src='images/edit0.png' alt='Editing unauthorized' title='Editing unauthorized' border='0' />&nbsp;&nbsp;&nbsp;";
							echo "<img src='images/deletenotallowed.gif' alt='Deletion unauthorized' title='Deletion unauthorized' border='0' />";	
						}
						
						echo "</td></tr>";
						}
						
					}
					else
					echo "<tr><td colspan='6' align='center' height='30' valign='middle' class='row0'>No Record Found... </td></tr>";
					?>
                          </tbody>
                          </table></td>
                      </tr>
                      <tr>
                        <td class="pagingTD"><table cellspacing='0' cellpadding='0'  width='100%'>
                            <tr>
                              <td style="text-align:left" class="form_base_header"><span class="pagenav">
                                <?=$pageObj->ShowPageInfo()?>
                                </span></td>
                              <td style="text-align:right" class="form_base_header"><span class="pagenav">
                                <?=$pageObj->Show($link)?>
                                </span></td>
                            </tr>
                          </table></td>
                      </tr>
                      <tr>
                      <td><strong>Note: </strong>Click on the tick symbol (<img src='images/tick0.png' border='0' alt='' />) under <em>Default</em> column to make that as the default mailer for sending mails.</td>
                      </tr>
                    </table></td>
                  <td valign="top" align="left" width="240">                  
                  <form name="formsuperuser" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" style="margin: 0;">
                  <table width="100%" border="0" cellspacing="1" cellpadding="1" class="inputformtable">
                      <tr>
                        <td class="pageHeadingRt"><?php echo ucwords($ACTION) ?> SMTP  
                        <?php if ($ACTION == 'edit') { echo "&nbsp;&nbsp;<small>(<a href='{$_SERVER["PHP_SELF"]}'>Cancel Edit</a>)</small>"; } ?>
                        </td>
                      </tr>
                      <tr>
					  <?php
						if(!empty($errorMsg)){
					  ?>
                        <td height="25" valign="top" <?= (! empty ($errorMsg)) ? 'class="error"' : '' ?>><?php
				   errorMessage($errorMsg);
				   ?></td>
						<?php }?>
                      </tr>
                      <tr>
                        <td class="inputlabel">Title /Name *</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txttitle" class="textbox" value="<?=$funcObj->RemoveSlashes($TITLE)?>" maxlength="40" size="30" />
                        <br /><small>Any name or label</small>
                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel">SMTP Host *</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txthost" class="textbox" value="<?=$funcObj->RemoveSlashes($HOST)?>" maxlength="40" size="30" />
                        <br /><small>Example: mail.yourdomain.com</small>
                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel">SMTP Port *</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtport" class="textbox" value="<?=$funcObj->RemoveSlashes($PORT)?>" maxlength="4" size="4" />
                        <br /><small>Default 25</small>
                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel">User *</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtuser" class="textbox" value="<?=$funcObj->RemoveSlashes($USER)?>" maxlength="35" size="30" />
                        <br /><small>Exmaple: user@yourdomain.com</small>
                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel">Password *</td>
                      </tr>
                      <tr>
                        <td><input type="password" name="txtpassword" class="textbox" value="" size="35" maxlength="20" />
                        <br /><small>Access password to login into your mail server</small>
                        </td>
                      </tr>
						<tr>
                        <td class="inputlabel" style="height: 36px">Authentication Required <input type="checkbox" name="chkauthentication" <?=$AUTHENTICATION_CHECKED?> value="1"  />
                        <br /><small style="font-weight:normal">Check if your server requires Authentication</small>
                        </td>
                      </tr>
					  <tr>
                        <td class="inputlabel">Bounce Email</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtbounce" class="textbox" value="<?=$funcObj->RemoveSlashes($BOUNCE_EMAIL)?>" maxlength="35" size="30" />
                        <br /><small>All bounce emails will be sent to this email address.</small>
                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel"  style="height: 36px">Set as default <input type="checkbox" name="chkdefault" <?=$DEFAULT_CHECKED?> value="1"  />
                         <br /><small style="font-weight:normal">Use this SMTP for sending mails</small>
                        </td>
                      </tr>
                      <tr>
                        <td height="35"><input type="submit" name="submit" value="Save" class="button size1" /></td>
                      </tr>
                      <tr>
                        <td height="45">Fields marked with * are mandatory.</td>
                      </tr>
                    </table>
                    <input type="hidden" name="ID" value="<?php echo isset($_GET['id']) ? $_GET['id'] : ''  ?>" />
                    <input type="hidden" name="formaction" value="<?php echo $ACTION?>" />
                    </form>
                    </td>
                </tr>
              </table></td>
      </tr>
    </table></td>
  </tr>
<?php require_once 'includes/inc.footer.php' ?>
</table>
</body>
</html>
