<?php

/********************************************************************************
	- MemHT Portal -
	
	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com
	
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your opinion) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.
		
********************************************************************************/

if (!defined("_LOAD_PAGE_")) {
	die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Error:</b> This file cannot be opened directly!</td></tr></table>");
}

if (isset($_GET['op'])) { $op = inCode($_GET['op']); } else { $op = ""; }
if (isset($_GET['id'])) { $id = inCode($_GET['id']); } else { $id = ""; }
if (isset($_GET['ok'])) { $ok = inCode($_GET['ok']); } else { $ok = false; }
if (isset($_POST['email'])) { $email = inCode($_POST['email']); } else { $email = ""; }
if (isset($_POST['sender_mail'])) { $sender_mail = inCode($_POST['sender_mail']); } else { $sender_mail = ""; }
if (isset($_POST['mailorsmtp'])) { $mailorsmtp = intval($_POST['mailorsmtp']); } else { $mailorsmtp = ""; }
if (isset($_POST['smtp'])) { $smtp = inCode($_POST['smtp']); } else { $smtp = ""; }
if (isset($_POST['useauth'])) { $useauth = intval($_POST['useauth']); } else { $useauth = ""; }
if (isset($_POST['smtpuser'])) { $smtpuser = inCode($_POST['smtpuser']); } else { $smtpuser = ""; }
if (isset($_POST['smtppass'])) { $smtppass = inCode($_POST['smtppass']); } else { $smtppass = ""; }
if (isset($_POST['aut_mail_per_session'])) { $aut_mail_per_session = inCode($_POST['aut_mail_per_session']); } else { $aut_mail_per_session = ""; }
if (isset($_POST['aut_mail_pause'])) { $aut_mail_pause = inCode($_POST['aut_mail_pause']); } else { $aut_mail_pause = ""; }
if (isset($_POST['name'])) { $name = outCode($_POST['name']); } else { $name = ""; }
if (isset($_POST['text'])) { $text = outCode($_POST['text']); } else { $text = ""; }
if (isset($_POST['operation'])) { $operation = inCode($_POST['operation']); } else { $operation = ""; }

if (isset($_GET['pg'])) { $pg = inCode($_GET['pg']); } else { $pg = 1; }
$ofsppg = 50; //Items per page
$ofsbgn = ($pg*$ofsppg)-$ofsppg;

require("inc/class/class.phpmailer.php");

function members($ofsbgn,$ofsppg,$pg) {
	global $dblink;
	
	$n = 0;
	echo "<table width='100%' border='0' cellspacing='1' cellpadding='0' class='std_nicetable'>\n";
	echo "<thead>\n";
	echo "<tr><td>"._EMAIL_."</td><td width='15%'>"._IP_."</td><td width='1%'>&nbsp;</td></tr>\n";
	echo "</thead>\n";
	echo "<tbody>\n";
	if ($result = $dblink->get_list("SELECT * FROM memht_newsletter ORDER BY id LIMIT $ofsbgn,$ofsppg")) {
		foreach ($result as $row) {
			$id = intval($row['id']);
			$email = outCode($row['email']);
			$ip = outCode($row['ip']);
			
			$class = (($n++%2)!=0) ? "hlight" : "clean" ;
			echo "<tr><td class='$class'><b>$email</b></td><td class='$class'>$ip</td><td class='$class'><a href='admin.php?page=newsletter&op=deleteEmail&id=$id' title='"._DELETE_."'><img src='images/delete.gif' alt='Delete' border='0'></a></td></tr>\n";
		}
	} else {
		echo "<tr><td align='center' id='errorText' class='clean' colspan='3'><b>"._EMPTY_."</b></td></tr>";
	}
	echo "</tbody>\n";
	echo "</table>\n";
	
	//Pages
	include_once("inc/class/paginationSystem.class.php");
	$ps = new paginationSystem();
	$ps->items = $ofsppg;
	$ps->actpg = $pg;
	$ps->query = "SELECT id FROM memht_newsletter";
	$ps->url = "admin.php?page=newsletter&op=subscribed&pg={{N}}";
	$ps->show();
}

function searchEmail($email,$ok) {
	global $dblink;
	
	if ($ok) {
		if (validEmail($email)) {
			$search = $dblink->get_row("SELECT * FROM memht_newsletter WHERE email='$email'");
			$num = $dblink->get_num("SELECT * FROM memht_newsletter WHERE email='$email'");
			if ($search) {	
				$id = intval($search['id']);
				
				echo "<table width='100%' cellspacing='1' cellpadding='0' class='std_nicetable'>\n";
				echo "<thead>\n";
				echo "<tr><td>"._EMAIL_."</td><td width='1%'>&nbsp;</td></tr>\n";
				echo "</thead>\n";
				echo "<tbody>\n";
				echo "<tr><td class='clean'>$email ($num)</td><td class='clean' align='right'><a href='admin.php?page=newsletter&op=deleteEmail&id=$id' title='"._DELETE_."'><img src='images/delete.gif' alt='Delete' border='0'></a></td></tr>\n";
				echo "</tbody>\n";
				echo "</table>\n";
			} else {
				echo "<div align='center' id='errorText'><b>"._EMAILNOTFOUND_."</b></div>";
			}
		} else {
			echo "<div align='center' id='errorText'><b>"._FIELDINVALID_."</b></div>";
		}
	} else {
		echo "<table align='center'>";	
		echo "<form name='admin_nl' method='post' action='admin.php?page=newsletter&op=findEmail&ok=true'>\n";
		echo "<tr><td><input type='text' name='email' size='20' maxlength='255'></td><td><input type='submit' name='Submit' value='"._FINDEMAIL_."'></td></tr>\n";
		echo "</form>\n";
		echo "</table>";
	}
}

function sentMail() {
	global $dblink,$siteConfig;
	
	$n = 0;
	echo "<table width='100%' cellspacing='1' cellpadding='0' class='std_nicetable'>\n";
	echo "<thead>\n";
	echo "<tr><td>"._TITLE_."</td><td width='20%' align='center'>"._SENTEMAILS_."</td><td width='20%'>"._DATE_."</td></tr>\n";
	echo "</thead>\n";
	echo "<tbody>\n";
	if ($result = $dblink->get_list("SELECT *,DATE_FORMAT(date, '".$siteConfig['timestamp']."') as date FROM memht_newsletter_sent ORDER BY id DESC")) {
		foreach ($result as $row) {
			$id = intval($row['id']);
			$title = outCode($row['title']);
			$date = $row['date'];
			$numemails = intval($row['numemails']);
			
			$class = (($n++%2)!=0) ? "hlight" : "clean" ;
			
			echo "<tr><td class='$class'><a href='admin.php?page=newsletter&op=showNewsletter&id=$id' title=\"$title\"><b>$title</b></a></td><td class='$class' align='center'>$numemails</td><td class='$class'>$date</td></tr>\n";
		}
	} else {
		echo "<tr><td align='center' id='errorText' class='clean' colspan='3'><b>"._EMPTY_."</b></td></tr>";
	}
	echo "</tbody>\n";
	echo "</table>\n";
}

function deleteEmail($id,$ok=false) {
	global $dblink;
	if ($ok) {
		adminLog("[page:Newsletter][op:deleteEmail()][id:$id][query:".getenv('QUERY_STRING')."][END]");
		$row = $dblink->get_row("SELECT email FROM memht_newsletter WHERE id=$id");
		$email = outCode($row['email']);
		
		if (memRunHooks('RemoveEmailFromNewsletter',array($email))) {
			$dblink->query("DELETE FROM memht_newsletter WHERE email='$email'");
			
			memRunHooks('RemoveEmailFromNewsletterEnd',array($email));
		}
		echo "<meta http-equiv='refresh' content='0;URL=admin.php?page=newsletter&op=subscribed'>";		
	} else {
		echo "<div align='center'><b>"._SUREDELETEEMAIL_."</b><br><a href='admin.php?page=newsletter&op=deleteEmail&id=$id&ok=true' title='"._YES_."'>"._YES_."</a> - <a href='admin.php?page=newsletter' title='"._NO_."'>"._NO_."</a></div>";
	}
}

function config($sender_mail,$mailorsmtp,$smtp,$useauth,$smtpuser,$smtppass,$aut_mail_per_session,$aut_mail_pause,$ok=false) {
	global $dblink;
	if (!$ok) {
		$row = $dblink->get_row("SELECT * FROM memht_newsletter_config");
		$sender_mail = outCode($row['email_mittente']);
		$mailorsmtp = intval($row['mailorsmtp']);
		$smtp = outCode($row['smtp']);
		$useauth = intval($row['useauth']);
		$smtpuser = outCode($row['smtpuser']);
		$smtppass = outCode($row['smtppass']);
		$aut_mail_per_session = intval($row['aut_mailpersession']);
		$aut_mail_pause = intval($row['aut_mailpause']); //minutes
		
		echo "<table width='100%' cellspacing='0' cellpadding='1'>\n";
		echo "<form name='admin_nlcfg' method='post' action='admin.php?page=newsletter&op=configuration&ok=true'>\n";
		echo "<tr><td width='30%'><b>"._SENDERMAIL_."</b></td><td><input type='text' name='sender_mail' value=\"$sender_mail\" size='30' maxlength='255'></td></tr>\n";
		echo "<tr><td><b>"._TYPE_."</b></td><td>";
			echo "<select name='mailorsmtp'>\n";
			if ($mailorsmtp==1) {
				echo "<option value='1' selected>SMTP</option>\n";
				echo "<option value='0'>Mail (Standard)</option>\n";
			} else {
				echo "<option value='1'>SMTP</option>\n";
				echo "<option value='0' selected>Mail (Standard)</option>\n";
			}
			echo "</select>";	
		echo "</td></tr>\n";
		echo "<tr><td><b>"._SMTP_."</b></td><td><input type='text' name='smtp' value=\"$smtp\" size='30' maxlength='255'></td></tr>\n";
		
		echo "<tr><td><b>"._USEAUTH_."</b></td><td>";
			echo "<select name='useauth'>\n";
			if ($useauth==1) {
				echo "<option value='1' selected>"._YES_."</option>\n";
				echo "<option value='0'>"._NO_."</option>\n";
			} else {
				echo "<option value='1'>"._YES_."</option>\n";
				echo "<option value='0' selected>"._NO_."</option>\n";
			}
			echo "</select>";	
		echo "</td></tr>\n";
		echo "<tr><td><b>"._USERNAME_."</b></td><td><input type='text' name='smtpuser' value=\"$smtpuser\" size='30' maxlength='255'></td></tr>\n";
		echo "<tr><td><b>"._PASSWORD_."</b></td><td><input type='text' name='smtppass' value=\"$smtppass\" size='30' maxlength='255'></td></tr>\n";
		echo "<tr><td><b>"._MAILPERSESSION_."</b></td><td><input type='text' name='aut_mail_per_session' value=\"$aut_mail_per_session\" size='15' maxlength='255'></td></tr>\n";
		echo "<tr><td><b>"._MAILPAUSE_."</b></td><td><input type='text' name='aut_mail_pause' value=\"$aut_mail_pause\" size='15' maxlength='255'></td></tr>\n";
		echo "<tr><td colspan='2'><input type='submit' name='Submit' value='"._SAVE_."'></td></tr>";
		echo "</table>\n";
	} else {
		$dblink->query("UPDATE memht_newsletter_config SET email_mittente='$sender_mail',mailorsmtp='$mailorsmtp',smtp='$smtp',useauth='$useauth',smtpuser='$smtpuser',smtppass='$smtppass',aut_mailpersession='$aut_mail_per_session',aut_mailpause='$aut_mail_pause'");
		echo "<meta http-equiv='refresh' content='0;URL=admin.php?page=newsletter&op=configuration'>";
	}
}

function sendMail($name,$text,$operation,$ok=false) {
	global $dblink,$visitorInfo,$siteConfig,$tzNOW;
	
	$row = $dblink->get_row("SELECT * FROM memht_newsletter_config");
	$sender_mail = outCode($row['email_mittente']);
	$mailorsmtp = intval($row['mailorsmtp']);
	$smtp = outCode($row['smtp']);
	$useauth = intval($row['useauth']);
	$smtpuser = outCode($row['smtpuser']);
	$smtppass = outCode($row['smtppass']);
	
	switch($operation) {
		case "0":
			//Anteprima
			echo "<div style='border:1px solid #DDD; padding:6px;'>".outCode(generateNewsletter($name,$text))."</div>";
		break;
		case "1":
			adminLog("[page:Newsletter][op:sendMail()][operation:1(test)][query:".getenv('QUERY_STRING')."][END]");
			//Test
			$content = outCode(generateNewsletter($name,$text));
			
			$mail = new PHPMailer();
			$mail->From = $sender_mail;
			$mail->FromName = $siteConfig['site_name'];
			$mail->Subject = $name;
			if ($mailorsmtp==0) {
				$mail->Mailer = "mail";
			} else {
				$mail->Host = $smtp;
				$mail->Mailer = "smtp";
				if ($useauth==1) {
					$mail->SMTPAuth = true;
					$mail->Username = $smtpuser;
					$mail->Password = $smtppass;
				}
			}
			$mail->IsHTML(true);
			$mail->Body = $content;
			$mail->AddAddress($siteConfig['webmaster_mail']);
			
			if($mail->Send()) {
				$dblink->query("INSERT INTO memht_newsletter_inviate (id,nome,contenuto,data)
								VALUES (null,'Test','".inCode($content)."',$tzNOW)");
				echo "<center><b>"._TESTMAILSENT_."</b>";
			} else {
				echo "<div align='center' id='errorText'><b>"._NEWSLETTERNOTSENT_."</b></div>";
			}
			
			$mail->ClearAddresses();
		break;
		case "2":
			if (memRunHooks('CreateNewsletter',array($name,$text))) {
				adminLog("[page:Newsletter][op:sendMail()][operation:2(send)][query:".getenv('QUERY_STRING')."][END]");
				
				if ($dblink->get_num("SELECT date FROM memht_newsletter_status")>0) {
					echo "<div align='center' id='errorText'><b>"._THERES_UNFINISHED_NEWSLETTER_SESSION_."</b></div>";
				} else {
					echo "<div align='center'>". _CREATINGNEWSLETTERSESSION_."</div>";
					
					//Initialize newsletter session
					$dblink->query("TRUNCATE memht_newsletter_busy");
					$dblink->query("INSERT INTO memht_newsletter_busy (busy,date) VALUES (0,$tzNOW)");
					$dblink->query("UPDATE memht_newsletter SET sent=0");
					
					//Create newsletter
					$content = outCode(generateNewsletter($name,$text));
					
					$dblink->query("INSERT INTO memht_newsletter_status (date,title,content)
									VALUES ($tzNOW,'".inCode($name)."','".inCode($content)."')");
					
					echo "<div align='center'><b>"._DONE_."</b></div>";
				}	
				
				memRunHooks('CreateNewsletterEnd',array($name,$text));
			}
		break;
		default:
			echo "<table width='100%'>\n";
			echo "<form name='form_nlinvia' method='post' action='admin.php?page=newsletter&op=sendNewsletter&ok=true'>";

				$name = $siteConfig['site_name']." - Newsletter";
				echo "<tr><td width='15%'>"._NAME_."<td><input type='text' name='name' value='$name' size='40' maxlength='255'>\n";
		
				echo "<tr><td valign='top'>"._TEXT_."</td><td>\n";
				
					textarea("text","100%","500px",1,"fulladmin");
					
				echo "<tr><td valign='top'>"._INCLUDE_."</td><td>\n";
					echo "<input type='checkbox' name='articles' value='1'> Articles<br>\n";
					echo "<input type='checkbox' name='download' value='1'> Downloads<br>\n";
					echo "<input type='checkbox' name='guide' value='1'> Guides<br>\n";
					echo "<input type='checkbox' name='news' value='1'> News<br>\n";
				echo "</td></tr>";
				echo "<tr><td>"._OPERATION_."</td><td>\n";
					echo "<select name='operation'>\n";
						echo "<option value='0' selected>"._PREVIEW_."</option>\n";
						echo "<option value='1'>"._TEST_SENDTOWEBMASTER_."</option>\n";
						echo "<option value='2'>"._SENDNEWSLETTER_."</option>\n";
					echo "</select> <input type='submit' name='Submit' value='"._OK_."'></td></tr>\n";
		
			echo "</form>\n";
			echo "</table>\n";
		break;
	}	
}

function generateNewsletter($myname,$mytext) {
	global $dblink,$siteConfig;

	if (file_exists("templates/".$siteConfig['template']."/newsletter.php")) {
		require_once("templates/".$siteConfig['template']."/newsletter.php");
	} else {
		require_once("newsletter.php");
	}
	
	$other = "";

	//News
	if (isset($_POST['news']) AND $_POST['news']==1) {
		$other .= "<b>News</b><br>";
		$result = $dblink->get_list("SELECT * FROM memht_news WHERE enabled=1 ORDER BY id DESC LIMIT 10");
		foreach ($result as $row) {
			$nid = intval($row['id']);
			$nnome = $row['nome'];
			
			$other .= "- <a href=\"".$siteConfig['site_url']."/index.php?page=news&op=readNews&id=$nid&title=".mem_urlencode($nnome)."\" title=\"$nnome\" target=\"_blank\">$nnome</a><br>";
		}
	}
	
	//Articles
	if (isset($_POST['articles']) AND $_POST['articles']==1) {
		$other .= "<br><b>Articles</b><br>";
		$result = $dblink->get_list("SELECT * FROM memht_articoli WHERE enabled=1 ORDER BY id DESC LIMIT 10");
		foreach ($result as $row) {
			$aid = intval($row['id']);
			$anome = $row['nome'];
			
			$other .= "- <a href=\"".$siteConfig['site_url']."/index.php?page=articles&op=readArticle&id=$aid&title=".mem_urlencode($anome)."\" title=\"$anome\" target=\"_blank\">$anome</a><br>";
		}
	}
	
	//Guide
	if (isset($_POST['guide']) AND $_POST['guide']==1) {
		$other .= "<br><b>Guide</b><br>";
		$result = $dblink->get_list("SELECT * FROM memht_guide WHERE enabled=1 ORDER BY id DESC LIMIT 10");
		foreach ($result as $row) {
			$gid = intval($row['id']);
			$gnome = $row['nome'];
			
			$other .= "- <a href=\"".$siteConfig['site_url']."/index.php?page=guides&op=readGuide&id=$gid&title=".mem_urlencode($gnome)."\" title=\"$gnome\" target=\"_blank\">$gnome</a><br>";
		}
	}
	
	//Download
	if (isset($_POST['download']) AND $_POST['download']==1) {
		$other .= "<br><b>Downloads</b><br>";
		$result = $dblink->get_list("SELECT * FROM memht_download ORDER BY id DESC LIMIT 10");
		foreach ($result as $row) {
			$did = intval($row['id']);
			$dnome = $row['nome'];
	
			$other .= "- <a href=\"".$siteConfig['site_url']."/index.php?page=download&op=getFile&id=$did&title=".mem_urlencode($dnome)."\" title=\"$dnome\" target=\"_blank\">$dnome</a><br>";
		}
	}
	
	$mycontent = newsletter_template($myname,$mytext,$other);
		
	return $mycontent;
}

function showSentNewsletter($id) {
	global $dblink;

	$row = $dblink->get_row("SELECT content FROM memht_newsletter_sent WHERE id=$id");
	echo "<div style='border:1px solid #DDD; padding:6px;'>".outCode($row['content'])."</div>";
}

require_once("admin/inc/inc_header.php");
	admin_page_title($page);
										
	openTable();
		echo "<div align='center' class='box'>";
			echo "<a href='admin.php?page=newsletter&op=subscribed' title='"._SUBSCRIBERS_."'><img src='admin/icons/newsletter.png' border='0' title='"._SUBSCRIBERS_."' align='top'> "._SUBSCRIBERS_."</a>";
			echo " - <a href='admin.php?page=newsletter&op=findEmail' title='"._FIND_EMAIL_."'><img src='admin/icons/search.png' border='0' title='"._FIND_EMAIL_."' align='top'> "._FIND_EMAIL_."</a>";
			echo " - <a href='admin.php?page=newsletter&op=sentNewsletter' title='"._SENT_NEWSLETTER_."'><img src='admin/icons/sent.png' border='0' title='"._SENT_NEWSLETTER_."' align='top'> "._SENT_NEWSLETTER_."</a>";
			echo " - <a href='admin.php?page=newsletter&op=sendNewsletter' title='"._CREATE_NEWSLETTER_."'><img src='admin/icons/send.png' border='0' title='"._CREATE_NEWSLETTER_."' align='top'> "._CREATE_NEWSLETTER_."</a>";
			echo " - <a href='admin.php?page=newsletter&op=configuration' title='"._CONFIGURATION_."'><img src='admin/icons/config.png' border='0' title='"._CONFIGURATION_."' align='top'> "._CONFIGURATION_."</a>";
		echo "</div>";
	closeTable();
	
	openTable();
	
		switch($op) {	
			case "sentNewsletter":
				sentMail();
			break;
			
			case "sendNewsletter":
				sendMail($name,$text,$operation,$ok);
			break;
			
			case "configuration":
				config($sender_mail,$mailorsmtp,$smtp,$useauth,$smtpuser,$smtppass,$aut_mail_per_session,$aut_mail_pause,$ok);
			break;
			
			case "findEmail":
				searchEmail($email,$ok);
			break;
			
			case "deleteEmail":
				deleteEmail($id,$ok);
			break;
			
			case "showNewsletter":
				showSentNewsletter($id);
			break;
			
			case "subscribed":
			default:
				members($ofsbgn,$ofsppg,$pg);
			break;
		}
	
	closeTable();
require_once("admin/inc/inc_footer.php");

?>