<?php
require_once("init.php");

$incdir = dirname(__FILE__);
define("INC", $incdir);

$area = ((!isset($area)) || ($_REQUEST['area']=="")) ? 1 : $_REQUEST['area'];
$limit = (isset($_REQUEST['pp']) && $_REQUEST['pp']!="") ? $_REQUEST['pp'] : 10;

$tmpl = new Koobi("templates/".ADMINTHEME."/newsletter/");
$tmpl->assign("theme", ADMINTHEME);
$tmpl->assign("langadmin", $langadmin);
$tmpl->assign("area", $area);
$tmpl->assign("kversion", KVERSION);
$tmpl->assign("rmode", $_REQUEST['mode']);
$tmpl->register_function("permission", "permission");
$tmpl->assign('uid', UID);
$tmpl->assign('pref', $pref);

if( (!permission('newsletter_abodel')) && (!permission('newsletter_archive')) && (!permission('newsletter_categ')) && (!permission('newsletter_compose')) ) { echo error($langadmin['noperms']); exit(); }


switch($_REQUEST['donow']){
	// ============================================================================
	// <<-- ARCHIV -->>
	// ============================================================================
	case "archive" :
	if(!permission('newsletter_archive')) { echo error($langadmin['noperms']); exit(); }
	
	if($_REQUEST['show']==1){
		$sql = new dbc("SELECT * FROM ".PREFIX."_newsletter_archiv WHERE area='$_REQUEST[area]' AND id = '$_REQUEST[id]' ");
		$row = $sql->fetchrow();
		$row->htmlv = htmlspecialchars(stripslashes($row->htmlv));
		$row->textv = htmlspecialchars(stripslashes($row->textv));
		$tmpl->assign('row', $row);
	}
	
	if($_POST['sel']>1){
		foreach ($_POST['sel'] as $id => $sel) {
			if( $sel != "")  {
				$sql = new dbc("DELETE FROM ".PREFIX."_newsletter_archiv  WHERE id = '$id'");
			}
		}
	}
	
	$items = array();
	
	switch($_REQUEST['order']){
		case "" :
		case "ctime" :
		$order = "ctime";
		break;
		
		case "absmail" :
		$order = "absmail";
		break;
		
		case "absname" :
		$order = "absname";
		break;
	}
	
	switch($_REQUEST['ascdesc']){
		case "":
		case "desc" :
		$ascdesc = "desc";
		break;
		
		case "asc" :
		$ascdesc = "asc";
		break;
	}
	
	switch($_REQUEST['gselect']){
		case "" :
		case "all" :
		$gs = " AND (type='groups' OR type='abos')";
		break;
		
		case "abos" :
		$gs = " AND (type='abos')";
		$gselect = "abos";
		break;
		
		case "groups" :
		$gs = " AND (type='groups')";
		$gselect = "groups";
		break;
		
	}
	
	$sql = new dbc("SELECT id FROM ".PREFIX."_newsletter_archiv WHERE area='$_REQUEST[area]' $gs order by $order $ascdesc ");
	$num = $sql->numrows();
	
	$seiten = ceil($num / $limit);
	$a = prepage() * $limit - $limit;
	
	$sql = new dbc("SELECT * FROM ".PREFIX."_newsletter_archiv WHERE area='$_REQUEST[area]' $gs order by  $order $ascdesc limit $a,$limit ");
	
	while($row = $sql->fetchrow()){
		$row->title = stripslashes($row->title);
		$row->htmlv = stripslashes($row->htmlv);
		$row->textv = stripslashes($row->textv);
		$row->ctime = mygmt($row->ctime);
		$row->author_id = $row->author;
		$row->author = fetchusername($row->author);
		
		$groups = $row->groups;
		$groups_a = explode(",", $groups);
		$groups_all = array();
		
		if($row->type == "abos") {
			foreach($groups_a as $gval){
				$sql_g = new dbc("SELECT name FROM ".PREFIX."_newsletter WHERE id = '$gval'");
				$row_g = $sql_g->fetchrow();
				$groups_all[] = $row_g->name;
			}
			$row->reciever = $langadmin['newsletter_abos'];
		} else {
			foreach($groups_a as $gval){
				$sql_g = new dbc("SELECT groupname FROM ".PREFIX."_usergroup WHERE ugroup = '$gval'");
				$row_g = $sql_g->fetchrow();
				$groups_all[] = $row_g->groupname;
			}
			$row->reciever = $langadmin['systemuser'];
		}
		
		$groups = implode(", ", $groups_all);
		$row->groups = $groups;
		array_push($items,$row);
	}
	
	if($num > $limit) $tmpl->assign('navi', pagenav($seiten, $lang['aktpos'], " <a class=\"pnav\" href=\"newsletter.php?gselect=$gselect&ascdesc=$ascdesc&order=$order&donow=archive&area=$area&pp=$limit&page={s}\">{t}</a> "));
	
	$tmpl->assign('items', $items);
	$tmpl->display("archive.tpl");
	break;
	
	
	
	// ============================================================================
	// <<-- KATEGORIEN -->>
	// ============================================================================
	case "categs" :
	if(!permission('newsletter_abodel'))  { echo error($langadmin['noperms']); exit(); }
	
	if($_REQUEST['newcat']==1){
		if($_POST['name']!=""){
			$sql = new dbc("INSERT INTO ".PREFIX."_newsletter (id,name,area) VALUES ('','$_POST[name]','$_REQUEST[area]')");
		}
	}
	
	if($_POST['sel']>1){
		foreach ($_POST['sel'] as $id => $sel) {
			if( $sel != "")  {
				$sql1 = new dbc("DELETE FROM ".PREFIX."_newsletter  WHERE id = '$id'");
				$sql2 = new dbc("DELETE FROM ".PREFIX."_newsletter_abos  WHERE newsletter = '$id'");
				
			}
		}
	}
	
	if($_POST['name']>1){
		foreach ($_POST['name'] as $id => $name) {
			if( $name != "")  {
				$sql1 = new dbc("UPDATE ".PREFIX."_newsletter set name='$name' WHERE id = '$id'");
				
			}
		}
	}
	
	if($_POST['posi']>1){
		foreach ($_POST['posi'] as $id => $posi) {
			if( ($posi != "") && (is_numeric($posi) ) )  {
				$sql1 = new dbc("UPDATE ".PREFIX."_newsletter set posi='$posi' WHERE id = '$id'");
				
			}
		}
	}
	$sql = new dbc("SELECT * FROM ".PREFIX."_newsletter  WHERE area='$_REQUEST[area]' order by posi ASC");
	$items = array();
	while($row = $sql->fetchrow()){
		array_push($items,$row);
	}
	$tmpl->assign('items', $items);
	$tmpl->display("categs.tpl");
	break;
	
	// ============================================================================
	// <<-- ABO LOESCHEN -->>
	// ============================================================================
	case "delabo" :
	if(!permission('newsletter_abodel'))  { echo error($langadmin['noperms']); exit(); }
	$sql = new dbc("DELETE FROM ".PREFIX."_newsletter_abos WHERE email='$_REQUEST[id]' AND area='$_REQUEST[area]'");
	header("Location:newsletter.php?area=$_REQUEST[area]&donow=showabos");
	break;
	
	
	// ============================================================================
	// <<-- DETAILS -->>
	// ============================================================================
	case "detail" :
	if($_REQUEST['del']==1){
		if(!permission('newsletter_abodel'))  { echo error($langadmin['noperms']); exit(); }
		$sql = new dbc("DELETE FROM ".PREFIX."_newsletter_abos WHERE id='$_REQUEST[delid]'");
	}
	
	$sql1 = new dbc("SELECT email FROM ".PREFIX."_newsletter_abos  WHERE email='$_REQUEST[id]'");
	$row1 = $sql1->fetchrow();
	
	$sql = new dbc("SELECT * FROM ".PREFIX."_newsletter_abos  WHERE email='$_REQUEST[id]'");
	$abos = array();
	while($row = $sql->fetchrow()){
		
		$sql_nl = new dbc("SELECT name FROM ".PREFIX."_newsletter  WHERE id='$row->newsletter'");
		$row_nl = $sql_nl->fetchrow();
		$row->newsletter = $row_nl->name;
		
		$row->ctime = mygmt($row->ctime);
		array_push($abos,$row);
	}
	$nl =array();
	$sql = new dbc("SELECT * FROM ".PREFIX."_newsletter  WHERE area='$_REQUEST[area]'");
	while ($row = $sql->FetchRow()) {
		$row->id = $row->id;
		$row->name = stripslashes($row->name);
		array_push($nl, $row);
	}
	
	$tmpl->assign('nl', $nl);
	$tmpl->assign('abos', $abos);
	$tmpl->display("abos.tpl");
	break;
	
	
	// ============================================================================
	// <<-- ABONNENTEN- UBERSICHT -->>
	// ============================================================================
	case "showabos" :
	$where = ($_REQUEST['newsletter']!="") ? " AND newsletter='$_REQUEST[newsletter]'" : "";
	$sort = ($_REQUEST['sort']=="ctime") ? "order by ctime desc" : "order by name asc";
	if($_REQUEST['email']!="") $extra = " and email like '%$_REQUEST[email]%'";
	
	// ============================================================================
	// <<-- DATENSAETZE -->>
	// ============================================================================
	$sql = new dbc("SELECT distinct email  FROM ".PREFIX."_newsletter_abos  WHERE area='$_REQUEST[area]' $where $extra");
	$num = $sql->numrows();
	
	$seiten = ceil($num / $limit);
	$a = prepage() * $limit - $limit;
	
	$sql = new dbc("SELECT distinct email  FROM ".PREFIX."_newsletter_abos  WHERE area='$_REQUEST[area]' $where $extra $sort limit $a,$limit");
	
	// ============================================================================
	// <<-- SEITEN -->>
	// ============================================================================
	if($num > $limit) $tmpl->assign('navi', pagenav($seiten, $lang['aktpos'], " <a class=\"pnav\" href=\"newsletter.php?newsletter=".$_REQUEST[newsletter]."&donow=showabos&area=$area&pp=$limit&page={s}\">{t}</a> "));
	
	
	
	$items = array();
	while($row = $sql->fetchrow()){
		
		$sql3 = new dbc("SELECT newsletter,id FROM ".PREFIX."_newsletter_abos  WHERE email='$row->email'");
		$erg = $sql3->numrows();
		$row3 = $sql3->fetchrow();
		
		$sql2 = new dbc("SELECT name FROM ".PREFIX."_newsletter  WHERE id='$row->newsletter'");
		
		$row2 = $sql2->fetchrow();
		$row->newsletter = $row2->name;
		$row->overall = $erg;
		$row->id = $row3->id;
		
		array_push($items,$row);
	}
	
	$nl = array();
	$sql = new dbc("SELECT * FROM ".PREFIX."_newsletter  WHERE area='$_REQUEST[area]'");
	while ($row = $sql->FetchRow()) {
		$row->id = $row->id;
		$row->name = stripslashes($row->name);
		array_push($nl, $row);
	}
	
	$tmpl->assign('nl', $nl);
	$tmpl->assign('items', $items);
	$tmpl->display("abos.tpl");
	break;
	
	
	// ============================================================================
	// <<-- HIER ERFOLGT DER VERSAND... -->>
	// ============================================================================
	case "" :
	if(!permission('newsletter_compose'))  { echo error($langadmin['noperms']); exit(); }
	if ($_REQUEST['action']=="send") {
		$path = "../uploads/newsletter_attachments/";
		$delattach = $_REQUEST['delattach'];
		$area = $_REQUEST['area'];
		
		$attach = array();
		$db_attachments = array();
		$db_groups = array();
		
		for($i=0;$i<count($_FILES['files']['tmp_name']);$i++){	
			if(filesize($_FILES['files']['tmp_name'][$i]) >2 ){
				
				// ============================================================================
				// <<-- ANHAENGE ZWISCHENSPEICHERN (SAFE_MODE- SICHER) -->>
				// ============================================================================
				if(file_exists($path . $_FILES['files']['name'][$i])){
					$_FILES['files']['name'][$i] = time().mt_rand(0, 1000000000) . $_FILES['files']['name'][$i];
				}
				
				@move_uploaded_file($_FILES['files']['tmp_name'][$i], $path . $_FILES['files']['name'][$i]);
				
				// ============================================================================
				// <<-- ATTACHMENT- ARRAY FUER ARCHIV -->>
				// ============================================================================
				$db_attachments[] = $_FILES['files']['name'][$i];
				
				// ============================================================================
				// <<-- DATEI OEFFNEN UND AUSLESEN -->>
				// ============================================================================
				$fp = @fopen($path . $_FILES['files']['name'][$i], "r");
				$cnt = @fread($fp, filesize($path . $_FILES['files']['name'][$i]));
				
				@array_push($attach, array(
				'filename' => $_FILES['files']['name'][$i],
				'content' => $cnt,
				'type' => $_FILES['files']['type'][$i]
				)
				);
				@fclose($fp);
			}
		}		
		
		
		
		$textv = stripslashes($_REQUEST['textversion']);
		$htmlv = stripslashes($_REQUEST['htmlversion']);
		$betreff = stripslashes($_REQUEST['betreff']);
		$from_name = $_REQUEST['absname'];
		$from_mail = $_REQUEST['absmail'];
		$nltype = $_REQUEST['nltype'];
		
		
		
		$start = (!isset($_REQUEST['start'])) ? 0 : $_REQUEST['start'];
		$count = $start;
		
		$listcond = "";
		@reset($_REQUEST);
		while(list($key,$val)=each($_REQUEST)) {
			if(substr($key,0,3)=="ml_") {
				$liste = str_replace("ml_", "", $key);
				if($nltype=="groups"){
					$db_groups[] = $liste;
					$listcond .= "ugroup='$liste' OR ";
				} else {
					$listcond .= "newsletter='$liste' OR ";
					$db_groups[] = $liste;
				}
			}
		}
		
		$listcond = ereg_replace("OR $", "", $listcond);
		
		// ============================================================================
		// <<-- GRUPPEN -->>
		// ============================================================================
		if($nltype=="groups"){
			$sql = new dbc("SELECT * FROM " . PREFIX . "_user WHERE ($listcond) AND recieve_newsletter='1' AND status='1'");
			$gesamt = $sql->numrows();
			$sql = new dbc("SELECT * FROM " . PREFIX . "_user WHERE ($listcond) AND recieve_newsletter='1' AND status='1' ORDER BY uid ASC LIMIT $start,50");
		} else {
		
			// ============================================================================
			// <<-- NUR EMPAENGER DER NEWSLETTER- LISTEN -->>
			// ============================================================================
			$sql = new dbc("SELECT * FROM " . PREFIX . "_newsletter_abos WHERE ($listcond) AND  active='1'");
			$gesamt = $sql->numrows();
			$qf = "SELECT * FROM " . PREFIX . "_newsletter_abos WHERE ($listcond) AND  active='1' ORDER BY id ASC LIMIT $start,50";
			
			$sql = new dbc($qf);
		
		
		
		
		}
		
		while ($row = $sql->FetchRow()) {
			
			if($nltype=="groups"){
				
				$an = $row->email;
				$name = $row->uname;
				if ($row->format == "html") {
					$a = true;
					$text = $htmlv;
				} else {
					$a = false;
					$text = $textv;
				}
				
				$text = str_replace("%%EMAIL%%", $an, $text);
				$text = str_replace("%%NAME%%", $name, $text);
				
				$thismail = new MIMEMail();
				$thismail->from_name = $from_name;
				$thismail->from_email = $from_mail;
				$thismail->subject = $betreff;
				$thismail->cc = "";
				$thismail->bcc = "";
				$thismail->to = $an;
				$thismail->headers();
				$thismail->addtextpart($a, $text);
				
			} else {
			
				$an = $row->email;
				$name = $row->name;
				$area = $row->area;
				$code = $row->securecode;
				
				if ($row->format == "html") {
					$a = true;
					$text = $htmlv;
				} else {
					$a = false;
					$text = $textv;
				}
				$unsubscribe = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/admin/newsletter.php","",$_SERVER['PHP_SELF']) . "/index.php?p=newsletter&action=unsubscribe&area=$area&email=$an&code=$code";
				$text = str_replace("%%EMAIL%%", $an, $text);
				$text = str_replace("%%NAME%%", $name, $text);
				$text = str_replace("%%AUSTRAGEN%%", $unsubscribe, $text);
				
				
				$thismail = new MIMEMail();
				$thismail->from_name = $from_name;
				$thismail->from_email = $from_mail;
				$thismail->subject = $betreff;
				$thismail->cc = "";
				$thismail->bcc = "";
				$thismail->to = $an;
				$thismail->headers();
				$thismail->addtextpart($a, $text);
				
			}
			
			// ============================================================================
			// <<-- DATEIEN ANHAENGEN UND WIEDER LOESCHEN -->>
			// ===========================================================================
			reset($attach);
			foreach($attach as $att_item){
				$thismail->AddAttachment($att_item['content'], $att_item['filename'], $att_item['type']);
				
				// ============================================================================
				// <<-- DATEIEN WIEDER LOESCHEN -->>
				// ============================================================================
				if($_REQUEST['delattach']==1){
					@unlink($path . $att_item['filename'] );
				}
			}
			
			
			$thismail->finish();
			$thismail->send();
			
			$count++;
		}
		$sql->Close();
		
		
		// ===========================================================================
		// <<-- UBERGABEFORM NACH REFRESH -->>
		// ===========================================================================
		if ($count < $gesamt) {
			$forms .= '<form action="newsletter.php?area='.$_REQUEST['area'].'" method="post" name="nextform" id="nextform">';
			$forms .=  '<input type="hidden" name="action" value="send" />';
			$forms .=  '<input type="hidden" name="start" value="'.$count.'" />';
			$forms .=  '<input type="hidden" name="betreff" value="'.$betreff.'" />';
			$forms .=  '<input type="hidden" name="absname" value="'.$from_name.'" />';
			$forms .=  '<input type="hidden" name="an" value="'.$an.'" />';
			$forms .=  '<input type="hidden" name="absmail" value="'.$from_mail.'" />';
			$forms .=  '<input type="hidden" name="nltype" value="'.$nltype.'" />';
			$forms .=  '<input type="hidden" name="delattach" value="'.$delattach.'" />';
			
			reset($_REQUEST);
			while(list($key,$val)=each($_REQUEST)) {
				if(substr($key,0,3)=="ml_") {
					$forms .=  "<input type=\"hidden\" name=\"$key\" value=\"true\">\n";
				}
			}
			
			$forms .=  '<textarea style="width:1;height:1;visibility:hidden;" name="textversion">'.htmlspecialchars($textv).'</textarea>';
			$forms .=  '<textarea style="width:1;height:1;visibility:hidden;" name="htmlversion">'.htmlspecialchars($htmlv).'</textarea>';
			$forms .= '</form>';
			$tmpl->assign('forms', $forms);
			$einprozent = $gesamt / 100;
			$prozent = $count / $einprozent;
			$tmpl->assign('done', (round($prozent)) );
			
			$jsdata ='<script language="JavaScript" type="text/javascript">
			<!--
			function nexts() {
				document.nextform.submit();
			}
			setTimeout("nexts();", 1000);
			//-->
			</script>
			';
			$tmpl->assign('jsdata', $jsdata);
			$tmpl->display("status.tpl");
		} else {
			$tmpl->assign('done', 100);
			$tmpl->display("status.tpl");
			
		}
		
		// <<-- ARCHIVIEREN -->>
		$datas = @implode(",", $db_attachments);
		$groups = @implode(",", $db_groups);
		
		$type = ($_REQUEST['nltype']=="groups") ? "groups" : "abos" ;
		$sql = new dbc("INSERT INTO ".PREFIX."_newsletter_archiv 
		(
		id,
		ctime,
		attachments,
		type,
		title,
		htmlv,
		textv,
		absmail,
		absname,
		author,
		groups,
		area
		) VALUES (
		'',
		'".time()."',
		'$datas',
		'$type',
		'$_REQUEST[betreff]',
		'$_REQUEST[htmlversion]',
		'$_REQUEST[textversion]',
		'$_REQUEST[absmail]',
		'$_REQUEST[absname]',
		'".UID."',
		'$groups',
		'$area'
		
		)
		");
		exit;
		
		
	}
	
	
	break;
	
	// ===========================================================================
	// <<-- NEUER NEWSLETTER -->>
	// ===========================================================================
	case "new":
	if(!permission('newsletter_compose'))  { echo error($langadmin['noperms']); exit(); }
	$items = array();
	if($_REQUEST['nltype']=="groups"){
		$sql = new dbc("SELECT * FROM " . PREFIX . "_usergroup ORDER BY  groupname ASC");
		while ($row = $sql->FetchRow()) {
			$row->id = $row->ugroup;
			$row->name = stripslashes($row->groupname);
			array_push($items, $row);
		}
	}else{
		$sql = new dbc("SELECT * FROM " . PREFIX . "_newsletter  WHERE area='$_REQUEST[area]'  ORDER BY name ASC");
		while ($row = $sql->FetchRow()) {
			$row->id = $row->id;
			$row->name = stripslashes($row->name);
			array_push($items, $row);
		}
	}
	$tmpl->assign('items', $items);
	$tmpl->display("new.tpl");
	break;
}
?>