<?php
class Newsletter
{
	var $_sendlimit = 50;
	
	function getHomeLink()
	{
		$p = 'http://' . $_SERVER['HTTP_HOST'] . str_replace('admin/index.php','',$_SERVER['PHP_SELF']);
		return $p;
	}
	
	function getMediaStart()
	{
		$start = str_replace('admin/index.php','',$_SERVER['PHP_SELF']);
		return $start;
	}
	
	function DelCateg($id)
	{
		$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_newsletter WHERE Id='{$id}'");
		$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_newsletter_abos WHERE Newsletter_Id='{$id}'");
		echo '<script>window.opener.location.reload(); window.close();</script>';
	}
	
	//============================================================================
	// Anlage herunterladen
	//============================================================================
	function GetAttachment($att)
	{
		$att = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9._]*)/', '', $_REQUEST['att']);
		ob_start();
		header("Cache-control: private");
		header("Content-type: application/octet-stream"); 
		header("Content-disposition:attachment; filename=" . str_replace(array(' '), '', $att));
		@KoobiReadFile(BASE_DIR . 'attachments/' . $att);
		exit;
	}
	
	
	function ShowAbos()
	{
		// Speichern
		if(isset($_POST['save']) && $_POST['save']==1)
		{
			foreach($_POST['Format'] as $format => $nid)
			{
				
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_newsletter_abos SET 
					Format = '".$_POST['Format'][$format]."',
					Aktiv = '".$_POST['Aktiv'][$format]."'
				WHERE 
					Id = '$format'
				");
				if(!empty($_POST['del'][$format]) && $_POST['del'][$format]==1) $GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_newsletter_abos WHERE Id='$format'");
			}
			header('Location:index.php?do=newsletter&sub=showabos');
			exit;
		}
		
		
		$def_search = '';
		$def_order_n = '';
		$def_search_n = '';
		$def_order    = ' ORDER BY Datum DESC';
		
		if(isset($_REQUEST['q']) && $_REQUEST['q']!='')
		{
			$def_search = " AND Email='".addslashes(trim($_REQUEST['q']))."'";
			$def_search_n = "&amp;q=".addslashes(trim($_REQUEST['q']));
		}
		
		// Sortierungen
		if(isset($_REQUEST['sort']))
		{
			$curr_page = ((isset($_REQUEST['page'])) ? '&page=' . abs((int)($_REQUEST['page'])) : '&amp;page=1');
			
			switch($_REQUEST['sort'])
			{
				case '':
				case 'email_asc' : 
					$def_order    = ' ORDER BY Email ASC';
					$def_order_n  = '&sort=email_asc' . $curr_page;
					$def_order_ns = '&sort=email_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('email_s',$def_order_ns);
				break;
				
				case 'email_desc' : 
					$def_order    = ' ORDER BY Email DESC';
					$def_order_n  = '&sort=email_desc' . $curr_page;
					$def_order_ns = '&sort=email_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('email_s',$def_order_ns);
				break;
				
				case 'format_asc' : 
					$def_order    = ' ORDER BY Format ASC';
					$def_order_n  = '&sort=format_asc' . $curr_page;
					$def_order_ns = '&sort=format_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('format_s',$def_order_ns);
				break;
				
				case 'format_desc' : 
					$def_order    = ' ORDER BY Format DESC';
					$def_order_n  = '&sort=format_desc' . $curr_page;
					$def_order_ns = '&sort=format_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('format_s',$def_order_ns);
				break;
				
				case 'date_asc' : 
					$def_order    = ' ORDER BY Datum ASC';
					$def_order_n  = '&sort=datum_asc' . $curr_page;
					$def_order_ns = '&sort=datum_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('date_s',$def_order_ns);
				break;
				
				case 'date_desc' : 
					$def_order    = ' ORDER BY Datum DESC';
					$def_order_n  = '&sort=datum_desc' . $curr_page;
					$def_order_ns = '&sort=datum_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('date_s',$def_order_ns);
				break;
				
				case 'active_asc' : 
					$def_order    = ' ORDER BY Aktiv ASC';
					$def_order_n  = '&sort=active_asc' . $curr_page;
					$def_order_ns = '&sort=active_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('active_s',$def_order_ns);
				break;
				
				case 'active_desc' : 
					$def_order    = ' ORDER BY Aktiv DESC';
					$def_order_n  = '&sort=active_desc' . $curr_page;
					$def_order_ns = '&sort=active_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('active_s',$def_order_ns);
				break;
				
				case 'newsletter_asc' : 
					$def_order    = ' ORDER BY Newsletter_Id ASC';
					$def_order_n  = '&sort=newsletter_asc' . $curr_page;
					$def_order_ns = '&sort=newsletter_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('newsletter_s',$def_order_ns);
				break;
				
				case 'newsletter_desc' : 
					$def_order    = ' ORDER BY Newsletter_Id DESC';
					$def_order_n  = '&sort=newsletter_desc' . $curr_page;
					$def_order_ns = '&sort=newsletter_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('newsletter_s',$def_order_ns);
				break;
				
			}
		}
		// ============================================================================
		// <<-- DATENSAETZE -->>
		// ============================================================================
		$sql = $GLOBALS['db']->Query("SELECT DISTINCT Email  FROM ".PREFIX."_newsletter_abos  WHERE Sektion='".$_SESSION['a_area']."' $def_search");
		$num = $sql->numrows();
		
		$limit = getLimit(15);
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
		
		$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_newsletter_abos  WHERE Sektion='".$_SESSION['a_area']."' $def_search $def_order limit $a,$limit");
		
		$items = array();
		while($row = $sql->fetchrow())
		{
			$sql2 = $GLOBALS['db']->Query("SELECT Name FROM ".PREFIX."_newsletter  WHERE Id='$row->Newsletter_Id'");
			$row2 = $sql2->fetchrow();
			$row->newsletter = $row2->Name;
			
			array_push($items,$row);
		}
		
		$nl = array();
		$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_newsletter  WHERE Sektion='".$_SESSION['a_area']."'");
		while ($row = $sql->FetchRow()) 
		{
			$row->id = $row->Id;
			$row->name = stripslashes($row->Name);
			array_push($nl, $row);
		}
		
		$ordstr = "index.php?do=newsletter&sub=showabos{$def_search_n}&amp;pp={$limit}";
		$nastr = "{$def_order_n}{$def_search_n}&amp;pp={$limit}";
		if($num>$limit)$GLOBALS['tmpl']->assign('Navi', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"{$ordstr}&page={s}\">{t}</a> "));
		
		
		$GLOBALS['tmpl']->assign('ordstr',$ordstr);
		$GLOBALS['tmpl']->assign('nl', $nl);
		$GLOBALS['tmpl']->assign('limit', $limit);
		$GLOBALS['tmpl']->assign('items', $items);
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Newsletter_Categs']); 
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/abos.tpl'));
	}
	
	//============================================================================
	// Kategorien
	//============================================================================
	function GetCatgs()
	{
		// Aktualisieren
		if(isset($_POST['save']) && $_POST['save']==1)
		{
			foreach($_POST['Name'] as $Nname => $nid)
			{
				if(!empty($_POST['Name'][$Nname])) $GLOBALS['db']->Query("UPDATE " . PREFIX . "_newsletter SET Name='" . $_POST['Name'][$Nname] . "', Info='" . $_POST['Info'][$Nname] . "' WHERE Id='{$Nname}'");
			}
		}
		
		// Neu
		if(isset($_POST['new']) && $_POST['new']==1)
		{
			if(!empty($_POST['Name']))
			{
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_newsletter VALUES ('','" . $_POST['Name'] . "','" . @$_POST['Info'] . "','" . AREA . "')");
			}
		}
		
		$GLOBALS['tmpl']->assign('Categs', $this->getNewsletterCategs());
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Newsletter_Categs']); 
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/categs.tpl'));
	}
	
	//============================================================================
	// Archiv anzeigen
	//============================================================================
	function GetArchive()
	{
		if(isset($_POST['delete']) && $_POST['delete']==1 && perm('newsletter'))
		{
			if(isset($_POST['del']))
			{
				foreach(@$_POST['del'] as $did => $x)
				{
					$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_newsletter_archiv WHERE Id='{$did}'");
				}
			}
		}
		
		switch(@$_REQUEST['typ'])
		{
			case '':
			default:
				$db_where = '';
				$nav = '';
			break;
			
			case 'groups':
				$db_where = " AND Typ='groups'";
				$nav = "&amp;typ=groups";
			break;
			
			case 'abos':
				$db_where = " AND Typ='abos'";
				$nav = "&amp;typ=abos";
			break;
		}
		
		$items = array();
		
		$sql = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_newsletter_archiv  WHERE Sektion='" . AREA . "' {$db_where} ORDER BY Id DESC");
		$num = $sql->numrows();
		
		$limit = GetLimit();
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
		
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_newsletter_archiv  WHERE Sektion='" . AREA . "' {$db_where} ORDER BY Id DESC LIMIT $a,$limit");
		while ($row = $sql->FetchRow())
		{
			array_push($items, $row);
		}
		
		if($num>$limit)$GLOBALS['tmpl']->assign('Navi', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"index.php?do=newsletter&sub=archive&amp;page={s}{$nav}&pp={$limit}\">{t}</a> "));
		
		$GLOBALS['tmpl']->assign('limit',$limit); 
		$GLOBALS['tmpl']->assign('items',$items); 
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Newsletter_archive']); 
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/archive.tpl'));
	}
	
	//============================================================================
	// Newsletter anzeigen (Details)
	//============================================================================
	function ShowNewsletter($id)
	{	
		$id = abs((int)$id);
		$sett = $GLOBALS['db']->RowQuery("SELECT Mail_Header FROM " . PREFIX . "_einstellungen");
		$res  = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_newsletter_archiv  WHERE Sektion='" . AREA . "' AND Id='{$id}'");
		
		switch(@$_REQUEST['type'])
		{
			case 'abos':
				$groups = explode(',', $res->Gruppen);
				foreach($groups as $group)
				{
					$name = $GLOBALS['db']->RowQuery("SELECT Name AS Name_Intern FROM " . PREFIX . "_newsletter WHERE Id='{$group}'");
					$names[] = $name->Name_Intern;
				}
				$GLOBALS['tmpl']->assign('names',$names);
			break;
			
			case 'groups':
				$groups = explode(',', $res->Gruppen);
				foreach($groups as $group)
				{
					$name = $GLOBALS['db']->RowQuery("SELECT Name_Intern FROM " . PREFIX . "_benutzer_gruppen WHERE Id='{$group}'");
					$names[] = $name->Name_Intern;
				}
				$GLOBALS['tmpl']->assign('names',$names);
			break;
		}
		
		if(@$_REQUEST['noout']==1)
		{
			echo $sett->Mail_Header;
			echo $res->Newsletter;
		} else {
		
			$att = '';
			
			if($res->Anlagen!='')
			{
				$att = explode(',', $res->Anlagen);
			}
			
			$GLOBALS['tmpl']->assign('att',$att);
			$GLOBALS['tmpl']->assign('HtmlV', fckInit($res->Code, 'htmlversion', 550, 'Nothing'));
			$GLOBALS['tmpl']->assign('sett',$sett);
			$GLOBALS['tmpl']->assign('res',$res);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Newsletter_NlView']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/view.tpl'));
		}
	}
	
	//============================================================================
	// Newsletter senden
	//============================================================================
	function NewNewsletter($to='abos')
	{
		$path_to_media = $this->getHomeLink();
		$start_media = $this->getMediaStart();
		
		$Koobi = new Koobi;
		
		if(isset($_REQUEST['send']) && $_REQUEST['send']==1)
		{
			if(empty($_REQUEST['htmlversion']) || strlen($_REQUEST['htmlversion']) < 5 || @!$_REQUEST['ToCateg'])
			{
				header('Location:index.php?do=newsletter&sub=new&to=' . $_REQUEST['to'] . '&area=' . AREA . '&noframes=1');
				exit;
			}
			
			$path = BASE_DIR . 'attachments/';
			$delattach = $_REQUEST['delattach'];
			$area = $_REQUEST['area'];
			if(isset($_REQUEST['delattach']) && $_REQUEST['delattach'] == 1)
			{
				$_SESSION['delattach'] = 1;
			}
			
			$attach = array();
			$db_attachments = array();
			$db_groups = array();
			
			if(isset($_REQUEST['start']) && $_REQUEST['start'] >= 1)
			{
				$Anlagen = explode(',', $_SESSION['datas']);
				foreach($Anlagen as $Anlage)
				{
					$fp = @fopen($path . $Anlage, "r");
					$cnt = @fread($fp, filesize($path . $Anlage));
				
					$db_attachments[] = $Anlage;
					
					array_push($attach, array(
						'filename' => $Anlage,
						'content' => $cnt,
						'type' => ''));
				}
			} else {
				for($i=0;$i<count($_FILES['files']['tmp_name']);$i++)
				{	
					if(filesize($_FILES['files']['tmp_name'][$i]) >2 )
					{
						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]);
						@chmod($path . $_FILES['files']['name'][$i], 0777);
						$db_attachments[] = $_FILES['files']['name'][$i];
					}
				}
				
				$_SESSION['datas'] = @implode(",", $db_attachments);
			}		
			
			
			$htmlv = stripslashes($_REQUEST['htmlversion']);
			$textv = $htmlv;
			$betreff = stripslashes($_REQUEST['betreff']);
			$from_name = $_REQUEST['absname'];
			$from_mail = $_REQUEST['absmail'];
			$nltype = $_REQUEST['to'];
			
			$start = (!isset($_REQUEST['start'])) ? 0 : $_REQUEST['start'];
			$count = $start;
			
			$listcond = "";
			
			
			if($nltype=='abos')
			{
				foreach($_POST['ToCateg'] as $ToC => $tcid)
				{
					$listcond .= "Newsletter_Id='$ToC' OR ";
					$db_groups[] = $ToC;
				}
			} else {
				foreach($_POST['ToCateg'] as $ToC => $tcid)
				{
					$listcond .= "Gruppe='$ToC' OR ";
					$db_groups[] = $ToC;
				}
			}
			
			$listcond = ereg_replace("OR $", "", $listcond);
			
			
			
			
			
			//============================================================================
			// GRUPPEN
			//============================================================================
			if($nltype=='abos')
			{
				$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_newsletter_abos WHERE ($listcond) AND  Aktiv='1' ORDER BY Id ASC");
				$gesamt = $sql->numrows();
				$qf = "SELECT * FROM " . PREFIX . "_newsletter_abos WHERE ($listcond) AND  Aktiv='1' ORDER BY Id ASC LIMIT $start,".$this->_sendlimit;
				$sql = $GLOBALS['db']->Query($qf);
			//============================================================================
			// NUR EMPAENGER DER NEWSLETTER- LISTEN
			//============================================================================
			} else {
				$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_benutzer WHERE ($listcond) AND Newsletter='1' AND Aktiv='1'");
				$gesamt = $sql->numrows();
				$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_benutzer WHERE ($listcond) AND Newsletter='1' AND Aktiv='1' ORDER BY Id ASC LIMIT $start,".$this->_sendlimit);
			}
			
			while ($row = $sql->FetchRow())
			{
				// Benutzergruppen
				if($nltype=="groups")
				{
					$an = $row->Email;
					$name = $row->Benutzername;
					$row->Format = 'html';
				} else {
					// Abonnenten
					$an = $row->Email;
					$area = $row->Sektion;
					$code = $row->Code;
				}
				
				if ($row->Format == 'html')
				{
					$a = true;
					$v = 'html';
					$text = $htmlv;
					$sethtml = 1;
				} else {
					$a = false;
					$v = 'text';
					$text = $htmlv;//$textv;
					$sethtml = '';
				}
				
				$text = str_replace("src=\"{$start_media}uploads/", "src=\"{$path_to_media}uploads/", $text);
				$inf = '';
				$header = '';
				
				//===========================================================================
				// Newsletter an Abonnenten
				//===========================================================================
				if($nltype=='abos')
				{
					if($sethtml==1)
					{
						$header = $GLOBALS['settings']['Mail_Header'];
						$inf = $GLOBALS['config_vars']['Newsletter_UnsubscribeInf_html'];
						$inf = str_replace('__WEBSEITE__', '<a href="' . $this->getHomeLink() . '">' . $this->getHomeLink() . '</a>', $inf);
						$inf = str_replace('__LINK__', '<a href="' . $this->getHomeLink() . 'index.php?p=newsletter&action=unsubscribe&email=' . $an . '&code=' . $row->Code. '&area=' . $row->Sektion . '">' . $this->getHomeLink() . 'index.php?p=newsletter&action=unsubscribe&email=' . $an . '&code=' . $row->Code. '&area=' . $row->Sektion . '</a>', $inf);
						$inf .= '</a><hr noshade="noshade" size="1" /><br />';
						$text = preg_replace("!\[NEWS:([0-9]*)\]!Uise", "getLastNews('$1')", $text);
						$text = preg_replace("!\[SHOP:([0-9]*)\]!Uise", "getLastShopArticles('$1')", $text);
						$text = preg_replace("!\[GALLERY:([0-9]*)\]!Uise", "getLastGalleries('$1')", $text);
						$insert = $text;
					} else {
						$text = $this->html2text($text);
						$inf =  $this->cleanUmlaut(strip_tags($GLOBALS['config_vars']['Newsletter_UnsubscribeInf_html']));
						$inf = str_replace('__WEBSEITE__', $this->getHomeLink(), $inf);
						$inf = str_replace('__LINK__',  $this->getHomeLink() . 'index.php?p=newsletter&action=unsubscribe&email=' . $an . '&code=' . $row->Code. '&area=' . $row->Sektion, $inf);
						$inf .= "\r\n-----------------------------------------\r\n\r\n";
						$text = $this->html2text(preg_replace("!\[NEWS:([0-9]*)\]!Uise", "getLastNews('$1','text')", $text));
						$text = preg_replace("!\[SHOP:([0-9]*)\]!Uise", "getLastShopArticles('$1','text')", $text);
						$text = preg_replace("!\[GALLERY:([0-9]*)\]!Uise", "getLastGalleries('$1','text')", $text);
					}
				} else {
					//===========================================================================
					// Newsletter an Benutzergruppen
					//===========================================================================
					$header = $GLOBALS['settings']['Mail_Header'];
					$inf = $GLOBALS['config_vars']['Newsletter_UnsubscribeInf_html2'];
					$inf = str_replace('__WEBSEITE__', '<a href="' . $this->getHomeLink() . '">' . $this->getHomeLink() . '</a>', $inf);
					$inf = str_replace('__BENUTZER__', '<strong>' . $name . '</strong>', $inf);
					$inf .= '</a><hr noshade="noshade" size="1" /><br />';
					$text = preg_replace("!\[NEWS:([0-9]*)\]!Uise", "getLastNews('$1')", $text);
					$text = preg_replace("!\[SHOP:([0-9]*)\]!Uise", "getLastShopArticles('$1')", $text);
					$text = preg_replace("!\[GALLERY:([0-9]*)\]!Uise", "getLastGalleries('$1')", $text);
					$insert = $text;
				}
				
				// Mail versenden
				$Koobi->koobi_mail($an, $header . $inf . stripslashes($text), $betreff, $from_mail, $from_name, 'text', @$db_attachments, $sethtml);	
				
				$count++;
			}
			$sql->Close();
		
			//============================================================================
			// Uebergabe nach Refresh
			//============================================================================
			if ($count < $gesamt)
			{
				$forms = '';
				$forms .= '<form action="index.php?do=newsletter&amp;sub=new&amp;to=' . $nltype .  '&amp;area='.$_REQUEST['area'].'&amp;noframes=1" method="post" name="nextform" id="nextform">';
				$forms .=  '<input type="hidden" name="send" value="1" />';
				$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.'" />';
				$forms .=  '<input type="hidden" name="Anhang" value="'.@$Anhang.'" />';
	
				if(isset($_REQUEST['delattach']) && $_REQUEST['delattach']==1) $_SESSION['delattach'] = 1;
				
				foreach($_POST['ToCateg'] as $ToC => $tcid)
				{
					$forms .=  "<input type=\"hidden\" name=\"ToCateg[".$ToC."]\" value=\"true\">\n";
				}
				
				
				$forms .=  '<textarea style="width:1;height:1;visibility:hidden;" name="textversion">'.htmlentities($textv).'</textarea>';
				$forms .=  '<textarea style="width:1;height:1;visibility:hidden;" name="htmlversion">'.htmlentities($htmlv).'</textarea>';
				$forms .= '</form>';
				$GLOBALS['tmpl']->assign('forms', $forms);
				$einprozent = $gesamt / 100;
				$prozent = $count / $einprozent;
				$GLOBALS['tmpl']->assign('done_nl', (round($prozent)) );
				
				$jsdata ='<script language="JavaScript" type="text/javascript">
				<!--
				function nexts() {
					document.nextform.submit();
				}
				setTimeout("nexts();", 1000);
				//-->
				</script>
				';
				$GLOBALS['tmpl']->assign('jsdata', $jsdata);
				$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/status.tpl'));
			} else {
				if(@$insert=='') 
				{
					$_SESSION['Newsletter_text'] = @$_REQUEST['htmlversion'];
					$GLOBALS['tmpl']->assign('not_send', 1);
				} else {
					$_SESSION['Newsletter_text'] = '';
				}
				
				$GLOBALS['tmpl']->assign('done', 100);
				$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/status.tpl'));
				
				//DB-EINTRAG
				$datas = @implode(",", $db_attachments);
				$groups = @implode(",", $db_groups);
			
				if(@$insert!='')
				{
					 $GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_newsletter_archiv 
					 VALUES 
					 (
						'',
						'" . stime() . "',
						'" . $_REQUEST['nltype'] . "',
						'" . $betreff . "',
						'" . $insert . "',
						'" . $from_mail . "',
						'" . $from_name . "',
						'" . $_SESSION['benutzer_id'] . "',
						'" . $datas . "',
						'" . $groups . "',
						'" . AREA . "',
						'"  . $htmlv .  "'
					 )");
					
					$iid = $GLOBALS['db']->InsertId();
					
					Logger('User ' . $_SESSION['user_name'] . ' send Newsletter (' . $betreff . ')', '3', $_SESSION['benutzer_id']);
					
					if(@$_SESSION['delattach']==1)
					{
					
						$row = $GLOBALS['db']->RowQuery("SELECT Anlagen FROM  " . PREFIX . "_newsletter_archiv WHERE Id = '$iid'");
						if(is_object($row))
						{
							$del_att = @explode(',', chop($row->Anlagen));
							foreach($del_att as $del)
							{
								@unlink($path .$del);
								
							}
							$_SESSION['delattach'] = '';
						}
					}
				}
			}
			
		} else {
			$GLOBALS['tmpl']->assign('UserGroups', UserGroups());
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['NewsletterNew']); 
			$GLOBALS['tmpl']->assign('DefSubject', $GLOBALS['config_vars']['NewsletterDefS'] . $GLOBALS['settings']['Seitenname']);
			$GLOBALS['tmpl']->assign('NewsletterCategs', $this->getNewsletterCategs());
			$GLOBALS['tmpl']->assign('HtmlV', fckInit(' ' . @$_SESSION['Newsletter_text'], 'htmlversion', 400, 'Content'));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/newsletter/new.tpl'));
		}
		
	}
	
	
	
	function getNewsletterCategs()
	{
		$items = array();
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_newsletter  WHERE Sektion='" . AREA . "'  ORDER BY Name ASC");
		while ($row = $sql->FetchRow())
		{
			array_push($items, $row);
		}
		return $items;
	}
	
	
	function html2text($text)
	{
		$text = strip_tags($text);
		$text = $this->cleanUmlaut($text);
		return $text;
	}
	
	function cleanUmlaut($text)
	{
		$text = str_replace(
			array('&auml;','&Auml;','&ouml;','&Ouml;','&uuml;','&uuml;','&amp;','&quot;','&szlig;','&copy;','&euro;','&reg;'),
			array('ä','Ä','ö','Ö','ü','Ü','&','"','ß','©','€','®'), 
		$text);
		return $text;
	}

}
?>