<?php
//=================================================================
// KOOBI R7 - CMS - PORTALSOFTWARE(c) DREAM4(r) 
// HTTP://WWW.DREAM4.DE
//=================================================================
// ACHTUNG!
// DIESER PROGRAMMCODE IST URHERRECHTLICH GESCHUETZT
// DIE URHEBERRECHTE LIEGEN BEI DEN JEWEILIGEN AUTOREN.
// AENDERUNGEN IN DIESER DATEI ERFOLGEN AUF EIGENE GEFAHR!
// ES IST NICHT GESTATTET, DEN COPYRIGHTHINWEIS ZU AENDERN ODER ZU
// ENTFERNEN. NUR WENN SIE EINE COPYRIGHTHINWEIS-ENTFERNUNG BESTELLT
// HABEN, DUERFEN SIE DIESEN ENTFERNEN.
//================================================================
// BEI FRAGEN WENDEN SIE SICH BITTE AN: KONTAKT@DREAM4.DE
//=================================================================
if(!defined('BASE_DIR')) exit;
if(!get_active('pn'))
{
	notActive();
}

$pnerror       = false;
$sname         = $GLOBALS['config_vars']['PN_PeronalMessages'];
$ok            = 1;
$pnin          = 1;
$dlmessage     = '';
$topic_sel     = '';
$outbox_uid    = '';
$inbox_uid     = '';
$readed_sel    = '';
$notreaded_sel = '';
$disp          = '';
$thisselect    = '';
$thisselect    = '';
$pntime_sel    = '';
$pp_l          = '';
$limit         = getLim(25);

$_REQUEST['action'] = (isset($_REQUEST['action']) && $_REQUEST['action'] != '') ? $_REQUEST['action'] : '';

//=================================================================
// Keine Berechtigung
//=================================================================

if((!permission("canpn")) || (MAXPN==0) || UGROUP==2)
{
	koobi_message('Global_NoPermission', 'Global_NoPermission_t', HOME_PATH . '/index.php');
} else {
	//=================================================================
	// Loeschen
	//=================================================================
	if(isset($_REQUEST['delete_once']) && $_REQUEST['delete_once']==1) 
	{
		$id = abs((int)$_GET['id']);
		
		switch(@$_GET['goto'])
		{
			case 'outbox':
				$check = $GLOBALS['db']->RowQuery("SELECT pnid FROM ".PREFIX."_pn WHERE typ = 'outbox' AND pnid='$id' AND from_uid='".$_SESSION['benutzer_id']."'");
				if(is_object($check))
				{
					$GLOBALS['db']->Query("DELETE FROM ".PREFIX."_pn WHERE pnid='".$check->pnid."'");
				}
			break;
			
			case 'inbox':
				$check = $GLOBALS['db']->RowQuery("SELECT pnid FROM ".PREFIX."_pn WHERE typ = 'inbox' AND pnid='$id' AND to_uid='".$_SESSION['benutzer_id']."'");
				if(is_object($check))
				{
					$GLOBALS['db']->Query("DELETE FROM ".PREFIX."_pn WHERE pnid='".$check->pnid."'");
				}
			break;
		}
		
		
		refer("index.php?p=pn&goto=".$_REQUEST['goto']);
	}
	
	if(isset($_REQUEST['del']) && $_REQUEST['del']!="") 
	{
		reset ($_REQUEST);
		while (list($key, $val) = each($_REQUEST)) 
		{
			if (substr($key,0,3)=="pn_") 
			{
				$aktid = str_replace("pn_","",$key);
				$sql = $GLOBALS['db']->Query("DELETE FROM ".PREFIX."_pn WHERE pnid='".$aktid."'");
			}
		}
		refer("index.php?p=pn&goto=".$_REQUEST['goto']);
		exit;
	}
	
	//=================================================================
	// Uebersicht
	//=================================================================
	if($_REQUEST['action']=="")
	{
		$goto = @$_REQUEST['goto']=="outbox" ? "outbox" : "inbox";
		$tofrom = $goto=="inbox" ? "to_uid" : "from_uid";
		
		$send_recieve_text = $goto=="inbox" ? $GLOBALS['config_vars']['recieve_dt'] : $GLOBALS['config_vars']['send_dt'];
		$text_fromto = $goto=="inbox" ? $GLOBALS['config_vars']['from_t'] : $GLOBALS['config_vars']['to_t'];
		
		
		//=================================================================
		// Aufsteigende + Absteigende Sortierung
		//=================================================================
		$sort = (isset($_REQUEST['sort']) && ($_REQUEST['sort'] == 'ASC' || $_REQUEST['sort'] == 'DESC')) ? $_REQUEST['sort'] : 'DESC';
		
		//=================================================================
		// Sortierung nach Betreff, Autor, Gelesen und Ungelesen
		//=================================================================
		$porder = (isset($_REQUEST['porder']) && ($_REQUEST['porder'] != '') ) ? $_REQUEST['porder'] : 'pntime';
		if(($porder != "pntime") && ($porder != "topic") && ($porder != "uid") && ($porder != "readed") && ($porder != "notreaded")) $porder = "pntime";
		
		
		if(($goto=="inbox") && ($porder=="uid")) 
		{
			$porder = "from_uid";
			$inbox_uid = " selected";
		}
		if(($goto=="outbox") && ($porder=="uid")) 
		{
			$porder = "to_uid";
			$outbox_uid = " selected";
		}
		
		if($porder=="pntime"){
			$porder = "pntime";
			$pntime_sel = " selected";
		}
		
		if($porder=="topic"){
			$porder = "topic";
			$topic_sel = " selected";
		}
		
		if($porder=="readed"){
			$porder = "is_readed='yes'";
			$readed_sel = " selected";
		}
		
		if($porder=="notreaded"){
			$porder = "is_readed='no'";
			$notreaded_sel = " selected";
		}
		
		//=================================================================
		// Sortierungsoptionen dem Template zuweisen...
		//=================================================================
		$sel_topic_read_unread	 = '<option value="pntime" ' . $pntime_sel . '>'.$GLOBALS['config_vars']['bydate'].'</option>';
		$sel_topic_read_unread	.= '<option value="topic" ' . $topic_sel . '>'.$GLOBALS['config_vars']['bytopic'].'</option>';
		$sel_topic_read_unread	.= '<option value="uid" ' . $outbox_uid . $inbox_uid . '>'.$GLOBALS['config_vars']['byauthor'].'</option>';
		$sel_topic_read_unread	.= '<option value="readed" ' . $readed_sel . ' >'.$GLOBALS['config_vars']['byreaded'].'</option>';
		$sel_topic_read_unread	.= '<option value="notreaded" ' . $notreaded_sel . '>'.$GLOBALS['config_vars']['byunreaded'].'</option>';
		
		$GLOBALS['tmpl']->assign('sel_topic_read_unread', $sel_topic_read_unread) ;
		
		$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_pn WHERE $tofrom='".UID."' AND typ='".$goto."' ORDER BY $porder $sort");
		$pnin = $sql->numrows();
		$seiten = ceil($pnin / $limit);
		$a = prepage() * $limit - $limit;
		
		$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_pn WHERE $tofrom='".UID."' AND typ='".$goto."'  ORDER BY $porder $sort limit  $a,$limit");
		
		//=================================================================
		// Normale oder Katalogisierte Ansicht
		//=================================================================
		if(@isset($_COOKIE['listpn']) && (@$_COOKIE['listpn']=="katalog" ) || (@!$_COOKIE['listpn']))
		{
			$LISTPN = 1;
			setcookie("listpn", "katalog", time()+(365*24*3600));
		}
		
		if(isset($_REQUEST['switchto']) && $_REQUEST['switchto']!="")
		{
			if($_REQUEST['switchto'] == "katalog")
			{
				$LISTPN = 1;
				setcookie("listpn", "katalog", time()+(365*24*3600));
				$switchto = "katalog";
			}
			if(isset($_REQUEST['switchto']) && $_REQUEST['switchto']=="norm")
			{
				$LISTPN = -1;
				setcookie("listpn", "norm", time()+(365*24*3600));
				$switchto = "norm";
			}
		}
		
		
		$entry_array = array();
		$table_data = array();
		if(@$LISTPN==1)
		{
			while ($row = $sql->fetchrow()) 
			{
				$sql2 = $GLOBALS['db']->Query("SELECT Benutzername as uname, Id as uid FROM ".PREFIX."_benutzer WHERE Id='".$row->from_uid."' ");
				$row2 = $sql2->fetchrow();
				$sql2->close();
				
				if(is_object($row2))
				{
					if($goto=="inbox")
					{
						$theuserid = $row2->uid;
						$theusername = $row2->uname;
					} else {
						$sql_emp = $GLOBALS['db']->Query("SELECT Benutzername as uname, Id as uid FROM ".PREFIX."_benutzer WHERE Id='".$row->to_uid."' ");
						$row_emp = $sql_emp->fetchrow();
						if(is_object($row_emp))
						{
							$theuserid = $row->to_uid;
							$theusername = $row_emp->uname;
						} else {
							$theuserid = '';
							$theusername = $GLOBALS['config_vars']['PN_undefined'];
						}
					}
				} else {
					$theuserid = '';
					$theusername = $GLOBALS['config_vars']['PN_undefined'];
				}
				
				$entry_array[] = array(
					'timestamp' => $row->pntime,
					'data'      => array(
					'title'	=> stripslashes($row->topic),
					'pntime' => $row->pntime,
					'pnday' => $row->pntime,
					'von'	=> $theusername,
					'goto'	=> $goto,
					'pnid'	=> $row->pnid,
					'icon' => isreaded($row->pnid),
					'uid' => $theuserid,
					'toid' => "index.php?p=user&amp;id=".$theuserid,
					'mlink'	=> "index.php?p=pn&amp;action=message&amp;id=".$row->pnid."&amp;goto=".$goto
				)
				);
			}
			
			$last = 0;
			
			$ts = array();
			$ts[0] = array('anfang' => mktime(0,0,0,date("m"),date("d"),date("Y")),'ende'	 => mktime(23,59,59,date("m"),date("d"),date("Y")));
			$last = mktime(0,0,0,date("m"),date("d"),date("Y"));
			$wochentag = date("w") + 1;
			
			for ($i = 1; $i < $wochentag; $i++)
			{
				$a = $wochentag - $i;
				if (date("d")-$i > 0)
				{
					$last -= 86400;
					$ts[$a] = array('anfang' => $last,'ende' => $last+86399);
				}
			}
			
			$ts[-2] = array('anfang' => $last-(7 * 86400),'ende'		=> $last);
			$last -= 7 * 86400;
			$ts[-1] = array('anfang' => 0,'ende'		=> $last);
			$wochentage = explode(",",$GLOBALS['config_vars']['days_name']);
			
			while(list($key,$val)=each($ts))
			{
				if ($key==0)
				{
					$t = $GLOBALS['config_vars']['pn_today'];
					$d = ", " . date("d.m.Y", $val['anfang']);
				} elseif ($key==-1) {
					$t = $GLOBALS['config_vars']['later'];
					$d = "";
				} elseif ($key==-2) {
					$t = $GLOBALS['config_vars']['lastweek'];
					$d = "";
				} else {
					$t = $wochentage[$key-1];
					$d = ", " . date("d.m.Y", $val['anfang']);
				}
				
				$mys = 0;
				
				reset($entry_array);
				while(list($k,$v) = each($entry_array))
				{
					if($v['timestamp'] > $val['anfang'] && $v['timestamp'] < $val['ende'])
					{
						$mys++;
					}
				}
				
				if($mys > 0)
				{
					$a = 0;
					reset($entry_array);
					while(list($k,$v) = each($entry_array))
					{
						if($v['timestamp'] > $val['anfang'] && $v['timestamp'] < $val['ende']) 
						{
							$a++;
							if($a==1) 
							{
								unset($position,$plusminus,$disp);
								$position = strpos(@$_COOKIE["pn"], "pn" . $goto.$key);
								
								if ( is_numeric($position) )
								{
									$disp= "none";
									$plusminus = "plus.png";
								} else {
									$plusminus = "minus.png";
								}
								$toggle = "<img hspace=\"2\" class=\"absmiddle\" border=\"0\" id=\"pn_".$goto.$key."\" src=\"theme/".$GLOBALS['theme']."/images/forums/".$plusminus."\" 
								onmouseover=\"this.style.cursor = 'pointer'\"
								onclick=\"MWJ_changeDisplay('pn".$goto.$key."', MWJ_getStyle( 'pn".$goto.$key."', 'display' ) ? '' : 'none');
								koobi_toggleImage('pn_".$goto.$key."', this.src);
								koobi_setCookie('pn', 'pn".$goto.$key."');\"
								alt=\"\" />";
								
								$v['data']['tbody_start'] = "<tr><td class=\"forum_header\" colspan=\"4\">".$toggle.$t.$d."</td></tr><tbody id='pn".$goto.$key."' name='pn".$goto.$key."' style=\"display: ".@$disp.";\">";
							}
							if($a==$mys)
							{
								$v['data']['tbody_end'] = "</tbody>";
							}
							
							array_push($table_data, $v['data']);
						}
					}
				}
			}
			
		} else {
			while ($row = $sql->fetchrow())
			{
				$sql2 = $GLOBALS['db']->Query("SELECT Benutzername as uname, Id as uid FROM ".PREFIX."_benutzer WHERE Id='".$row->from_uid."' ");
				$row2 = $sql2->fetchrow();
				$sql2->close();
				
				if ($goto=="inbox")
				{
					$theuserid = @$row2->uid;
					$theusername = @$row2->uname;
				} else {
					$sql_emp = $GLOBALS['db']->Query("SELECT Benutzername as uname, Id as uid FROM ".PREFIX."_benutzer WHERE Id='".$row->to_uid."' ");
					$row_emp = $sql_emp->fetchrow();
					$theuserid = @$row->to_uid;
					$theusername = @$row_emp->uname;
				}
				array_push($table_data, array(
					'timestamp' => $row->pntime,
					'title'	=> stripslashes($row->topic),
					'pntime' => $row->pntime,
					'pnday' => $row->pntime,
					'von'	=> $theusername,
					'pnid'	=> $row->pnid,
					'goto'	=> $goto,
					'icon' => isreaded($row->pnid),
					'toid' => "index.php?p=user&amp;id=".$theuserid,
					'mlink'	=> "index.php?p=pn&amp;action=message&amp;id=".$row->pnid."&amp;goto=".$goto
					)
				);
			}
		}
		
		//=================================================================
		// Selektion für gelesene und ungelesene Nachrichten wieder aendern
		//=================================================================
		if (isset($_REQUEST['porder']) && $_REQUEST['porder']=="readed") {
			$porder = "readed";
		}
		if (isset($_REQUEST['porder']) && $_REQUEST['porder']=="notreaded") {
			$porder = "notreaded";
		}
		if (isset($_REQUEST['porder']) && $_REQUEST['porder']=="uid") {
			$porder = "uid";
		}
		
		//=================================================================
		// Navigation erzeugen
		//=================================================================
		if($pnin > $limit)
		{
			$nav = pagenav($seiten, $GLOBALS['config_vars']['aktpos'], " <a class=\"page_navigation\" href=\"index.php?switchto=".$switchto."&p=pn&goto=".$goto."&sort=".$sort."&porder=".$porder."&pp=".$limit."&page={s}\">{t}</a> ");
			$GLOBALS['tmpl']->assign("nav", $nav) ;
		}
		
		//=================================================================
		// Anzahlwahl + Auf oder Absteigend
		//=================================================================
		for ($i = 10; $i <= 50; $i+=10) 
		{
			unset($thisselect);
			if (isset($_REQUEST['pp']) && $_REQUEST['pp']==$i) 
			{
				$thisselect = "selected";
			}
			@$pp_l .= '<option value="'.$i.'" '.@$thisselect.'>'.$i.' '.$GLOBALS['config_vars']['eachpage'].'</option>';
		}
		$GLOBALS['tmpl']->assign('pp_l', $pp_l) ;
		$page = $_REQUEST['page'];
		
		if(isset($_REQUEST['sort']) && $_REQUEST['sort']=="DESC")
		{   // ABSTEIGEND
			$GLOBALS['tmpl']->assign('sel1', "selected");
			$GLOBALS['tmpl']->assign('sel2', "");
		}
		if(isset($_REQUEST['sort']) && $_REQUEST['sort']=="ASC")
		{   // AUFSTEIGEND
			$GLOBALS['tmpl']->assign('sel2', "selected");
			$GLOBALS['tmpl']->assign('sel1', "");
		}
		$GLOBALS['tmpl']->assign('page', $page);
		
		
		$link_the_normmodus = "index.php?switchto=norm&p=pn&goto=".$goto."&sort=".$sort."&porder=".$porder."&pp=".$limit."&page=".$page;
		$link_the_katmodus = "index.php?switchto=katalog&p=pn&goto=".$goto."&sort=".$sort."&porder=".$porder."&pp=".$limit."&page=".$page;
		$GLOBALS['tmpl']->assign('normmodus_link', $link_the_normmodus) ;
		$GLOBALS['tmpl']->assign('katmodus_link', $link_the_katmodus) ;
		//$GLOBALS['tmpl']->assign('lang', $lang);
		
		//=================================================================
		// PROZENT EINGANG / AUSGANG
		//=================================================================
		$onepn = 100 / MAXPN;
		$allpn = $onepn * $pnin;
		$inoutwidth = round($allpn/1.005, 3);
		$inoutpercent = round($allpn, 0);
		
		$warningpnfull = ($pnin>=MAXPN) ? $GLOBALS['config_vars']['PN_warningpnfull'] : '';
		
		if($goto=="inbox") 
		{
			$GLOBALS['tmpl']->assign('selin', "selected");
			$GLOBALS['tmpl']->assign("view", "inbox");
		}
		
		if($goto=="outbox") 
		{
			$GLOBALS['tmpl']->assign('selout', "selected");
			$GLOBALS['tmpl']->assign("view", "outbox");
		}
	}
	
	if($_REQUEST['action']=="")
	{
		$desclink = "index.php?p=pn&goto=".$goto."&sort=DESC&pp=".$_REQUEST['pp']."&page=".prepage();
		$asclink = "index.php?p=pn&goto=".$goto."&sort=ASC&pp=".$_REQUEST['pp']."&page=".prepage();
		
		$GLOBALS['tmpl']->assign('send_recieve_text', $send_recieve_text);
		$GLOBALS['tmpl']->assign('title_t', $GLOBALS['config_vars']['title_t']);
		$GLOBALS['tmpl']->assign('from_t', $text_fromto);
		$GLOBALS['tmpl']->assign('action', $GLOBALS['config_vars']['Global_Action']);
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['PN_PeronalMessages']);
		$GLOBALS['tmpl']->assign('delmarked', $GLOBALS['config_vars']['PN_delmarked']);
		$GLOBALS['tmpl']->assign('goto', $goto);
		$GLOBALS['tmpl']->assign('pndel_confirm', $GLOBALS['config_vars']['pndel_confirm']);
		$GLOBALS['tmpl']->assign('inoutwidth', $inoutwidth);
		$GLOBALS['tmpl']->assign('inoutpercent', $inoutpercent);
		$GLOBALS['tmpl']->assign('pnioutnall', $pnin);
		$GLOBALS['tmpl']->assign('pnmax', str_replace("__MAXPN__",MAXPN,$GLOBALS['config_vars']['pninoutstatus']));
		$GLOBALS['tmpl']->assign('warningpnfull', $warningpnfull);
		$GLOBALS['tmpl']->assign('sortdesc', $desclink);
		$GLOBALS['tmpl']->assign('sortasc', $asclink);
		$GLOBALS['tmpl']->assign('dlpnas', $GLOBALS['config_vars']['PN_downloadas']);
		$GLOBALS['tmpl']->assign('pndl_text', "index.php?type=text&p=pn&goto=".$goto."&download=1");
		$GLOBALS['tmpl']->assign('pndl_html', "index.php?type=html&p=pn&goto=".$goto."&download=1");
		$GLOBALS['tmpl']->assign('pndl_text_link', $GLOBALS['config_vars']['PN_dlText']);
		$GLOBALS['tmpl']->assign('pndl_html_link', $GLOBALS['config_vars']['PN_dlHTML']);
		$GLOBALS['tmpl']->assign('outin', 1);
		$GLOBALS['tmpl']->assign('neu', 0);
		
		//=================================================================
		// Wenn keine PN...
		//=================================================================
		if($pnin) 
		{
			$GLOBALS['tmpl']->assign('table_data', $table_data);
		} else {
			$GLOBALS['tmpl']->assign('nopns', $GLOBALS['config_vars']['PN_nopns']);
			$GLOBALS['tmpl']->assign('nomessages', 1);
			$GLOBALS['tmpl']->assign('outin', 0);
		}
		
		//=================================================================
		// PN herunterladen
		//=================================================================
		if(isset($_REQUEST['download']) && $_REQUEST['download']==1)
		{
			$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_pn WHERE $tofrom='".UID."' AND typ='".$goto."'  ORDER BY pntime ".$sort."");
			while ($row = $sql->fetchrow())
			{
				$message = str_replace("\n", "\r\n", $row->message);
				
				if($goto=="inbox")
				{
					$pninout = $GLOBALS['config_vars']['PN_inbox'];
					$fname = $theusername;
					$tname = UNAME;
				} else {
					$pninout = $GLOBALS['config_vars']['PN_outbox'];
					$fname = UNAME;
					$tname = $theusername;
				}
				
				if($_REQUEST['type']=="text") 
				{
					$dlmessage .= "===============================================================================\r\n";
					$dlmessage .= "".$GLOBALS['config_vars']['from_t'].":\t" . $fname ."\r\n";
					$dlmessage .= "".$GLOBALS['config_vars']['to_t'].":\t" . $tname . "\r\n";
					$dlmessage .= "".$GLOBALS['config_vars']['PN_date'].":\t" . date('d-m-Y H:i', $row->pntime) . "\r\n";
					$dlmessage .= "".$GLOBALS['config_vars']['PN_Subject'].":\t" . $row->topic . "\r\n";
					$dlmessage .= "-------------------------------------------------------------------------------\r\n";
					$dlmessage .=  wordwrap( $message, 90, "\r\n", 1) . "\r\n\r\n";
					$end = ".txt";
					
				} else {
					
					$dlmessage = '<style><!-- TD{FONT-SIZE: 11px;FONT-FAMILY:   Verdana, Arial, Helvetica, sans-serif;} --></style>';
					$dlmessage .= '<table width="100%"  border="1" cellpadding="3" cellspacing="0" bordercolor="#333333"><tr><td bgcolor="#F4F4F4">';
					$dlmessage .= "<B>".$GLOBALS['config_vars']['from_t']."</B>:\t" . $fname ."\r<br>";
					$dlmessage .= "<B>".$GLOBALS['config_vars']['to_t']."</B>:\t" . $tname . "\r<br>";
					$dlmessage .= "<B>".$GLOBALS['config_vars']['PN_date']."</B>:\t" . date('d-m-Y H:i', $row->pntime) . "\r<br>";
					$dlmessage .= "<B>".$GLOBALS['config_vars']['PN_Subject']."</B>:\t" . $row->topic . "\r<br>";
					$dlmessage .= '</td></tr><tr><td>';
					$dlmessage .=  nl2br(koobispecialchars(wordwrap( $message, 90, "\r\n", 1))) ."";
					$dlmessage .= '</td></tr></table><br>';
					$end = ".html";
				}
			}
			downloadfile($dlmessage, $pninout ."-". $GLOBALS['config_vars']['PN_PeronalMessages'].date("d-m-Y") . $end, 'text/plain');
		}
		
	}
	
	//=================================================================
	// NACHRICHT ANSEHEN
	//=================================================================
	if(isset($_REQUEST['action']) && $_REQUEST['action']=="message")
	{
		$goto = $_REQUEST['goto']=="inbox" ? "inbox" : "outbox";
		$tofrom = $goto=="inbox" ? "to_uid" : "from_uid";
		$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_pn WHERE pnid='".$_REQUEST['id']."' AND $tofrom='".UID."' AND typ='".$goto."'");
		$num = $sql->numrows();
		$row = $sql->fetchrow();
		$sql->close();
		
		//=================================================================
		// WENN UNGUELTIGE ID ODER PN NICHT == USER-ID
		//=================================================================
		if(!$num)
		{
			refer("index.php?p=pn&goto=" . @$_REQUEST['goto']);
			exit;
		}
		
		if($ok==1):
		$pn_id = $_REQUEST['id'];
		if(isset($_REQUEST['do']) && $_REQUEST['do']=="del")
		{
			$sql = $GLOBALS['db']->Query("DELETE FROM ".PREFIX."_pn WHERE pnid='".$pn_id."'");
			refer("index.php?p=pn&goto=".$_REQUEST['goto']);
			
		}
		
		if($goto == "inbox")
		{
			$sql = $GLOBALS['db']->Query("UPDATE ".PREFIX."_pn SET is_readed='yes' WHERE pnid='".$_REQUEST['id']."'");
			$sql = $GLOBALS['db']->Query("SELECT pntime,topic FROM ".PREFIX."_pn WHERE pnid='".$_REQUEST['id']."'");
			$row_subid = $sql->fetchrow();
			$sql = $GLOBALS['db']->Query("UPDATE ".PREFIX."_pn SET is_readed='yes' WHERE pntime='".$row_subid->pntime."' AND topic='".$row_subid->topic."'");
		}
		
		if($_REQUEST['goto'] == "inbox")
		{
			$sqlid = $row->from_uid;
			$tfrlink = "index.php?p=user&amp;id=" . UID;
		}elseif($_REQUEST['goto'] == "outbox"){
			$sqlid = $row->to_uid;
			$tfrlink = "index.php?p=user&amp;id=".$row->to_uid;
		}else{
			$sqlid = $row->from_uid;
		}
		
		if(!isset($_REQUEST['goto']) && ($_REQUEST['goto']=="")):
		$goto = "inbox";
		else: $goto = $_REQUEST['goto']; endif;
		
		$text_fromto = $goto=="inbox" ? $GLOBALS['config_vars']['from_t'] : $GLOBALS['config_vars']['to_t'];
		
		$message = $row->message;
		$message = ($row->smilies=="yes") ? dosmilies(kcodes($message)) : kcodes($message);
		$GLOBALS['tmpl']->assign('message', $message);
		
		$sql = $GLOBALS['db']->Query("SELECT Id as uid, Benutzername as uname, Regdatum as user_regdate, Beitraege as user_posts, Gruppe as ugroup FROM ".PREFIX."_benutzer WHERE Id='".$sqlid."'");
		$row_u = $sql->fetchrow();
		$sql->close();
		
		if(is_object($row_u)) $row1 = $GLOBALS['db']->RowQuery("SELECT * From " . PREFIX . "_benutzer WHERE Id = '" . $row_u->uid . "'");
		if(isset($row1) && is_object($row1)) $row_u2 = $GLOBALS['db']->RowQuery("SELECT * From " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $row1->Gruppe . "'");
			
		@$pnlink_del = "index.php?delete_once=1&p=pn&action=message&id=".$pn_id."&goto=".$goto;
		@$pnlink = "index.php?del=1&p=pn&action=message&id=".$pn_id."&goto=".$goto;
		@$forwardlink = "index.php?p=pn&action=new&forward=1&id=".$pn_id."&subject=".base64_encode($row->topic)."&aut=".base64_encode($row_u->uname)."&date=".base64_encode($row->pntime)."&goto=".$goto;
		@$relink = "index.php?p=pn&action=new&forward=2&id=".$pn_id."&subject=".base64_encode($row->topic)."&aut=".base64_encode($row_u->uname)."&date=".base64_encode($row->pntime)."&goto=".$goto;
		
		if($_REQUEST['goto'] == "inbox")
		{
			@$tfrlink = "index.php?p=user&amp;id=".$row_u->uid."";
			@$group = fetchgroupname($row_u->ugroup);
		} else {
			@$tfrlink = "index.php?p=user&amp;id=".$row_u->uid."";
			@$group = fetchgroupname($row_u2->Id);
		}
		
		if($goto=="inbox") {
			$GLOBALS['tmpl']->assign('answerok', 1);
		}
		
		$GLOBALS['tmpl']->assign('forward', 2);
		$GLOBALS['tmpl']->assign('pn_id', $pn_id);
		$GLOBALS['tmpl']->assign('pn_subject', @base64_encode($row->topic));
		$GLOBALS['tmpl']->assign('pn_aut', @base64_encode($row_u->uname));
		$GLOBALS['tmpl']->assign('pn_date', @base64_encode($row->pntime));
		$GLOBALS['tmpl']->assign('pn_goto', @$goto);
		$GLOBALS['tmpl']->assign('pn_text', @$row->message);
		
		$GLOBALS['tmpl']->assign('delpn', $pnlink_del);
		$GLOBALS['tmpl']->assign('forwardlink', $forwardlink);
		$GLOBALS['tmpl']->assign('relink', @$relink);
		$GLOBALS['tmpl']->assign('delpn_t', @$GLOBALS['config_vars']['delpn_t']);
		$GLOBALS['tmpl']->assign('membersince_date', @$row_u->user_regdate);
		$GLOBALS['tmpl']->assign('membersince', @$GLOBALS['config_vars']['Forums_Field_membersince']);
		$GLOBALS['tmpl']->assign('posts_num', @$row_u->user_posts);
		$GLOBALS['tmpl']->assign('groupname', @$group);
		$GLOBALS['tmpl']->assign('posts', $GLOBALS['config_vars']['Forums_Postings']);
		
		$GLOBALS['tmpl']->assign('pntitle', oform($row->topic));
		$GLOBALS['tmpl']->assign('send_dt', $GLOBALS['config_vars']['send_dt']);
		$GLOBALS['tmpl']->assign('pntime', $row->pntime);
		$GLOBALS['tmpl']->assign('pn_t_once',$GLOBALS['config_vars']['pn_t_once']);
		$GLOBALS['tmpl']->assign('tofromname', @$row_u->uname);
		$GLOBALS['tmpl']->assign('tofromname_link', @$tfrlink);
		$GLOBALS['tmpl']->assign('PN_sendtime_t', $GLOBALS['config_vars']['PN_sendtime_t']);
		$GLOBALS['tmpl']->assign('pndate', $row->pntime);
		$GLOBALS['tmpl']->assign('to_t', $text_fromto);
		$GLOBALS['tmpl']->assign('showmessage', 1);
		endif;
	}
	
	//=================================================================
	// NEUE NACHRICHT
	//=================================================================
	if(isset($_REQUEST['action']) && $_REQUEST['action'] == "new") 
	{
		$sql = $GLOBALS['db']->Query("SELECT typ FROM ".PREFIX."_pn WHERE typ='outbox' and from_uid='".UID."'");
		$num = $sql->numrows();
		
		if($num == MAXPN || $num >= MAXPN)
		{
			koobi_message('Global_error', 'PN_warningpnfull2', HOME_PATH . '/index.php?p=pn&goto=inbox');
		}
		
		//=================================================================
		// Vorschau
		//=================================================================
		if(isset($_REQUEST['send']) && $_REQUEST['send']=="1")
		{
			$message = $_REQUEST['text'];
			
			if($_REQUEST['parseurl']=="yes") 
			{
				$message = parseurl($message);
			}
			
			if($_REQUEST['use_smilies'] == "yes") 
			{
				$GLOBALS['tmpl']->assign('preview_text', dosmilies(kcodes($message)));
			} else {
				$GLOBALS['tmpl']->assign('preview_text', kcodes($message));
			}
			
			$text = "";
			$GLOBALS['tmpl']->assign('tofromname', oform($_REQUEST['tofromname']));
			$GLOBALS['tmpl']->assign('title', oform($_REQUEST['title']));
			$GLOBALS['tmpl']->assign('text', koobispecialchars($_REQUEST['text']));
			$GLOBALS['tmpl']->assign('preview', 1);
			
		}
		
		if(isset($_REQUEST['send']) && $_REQUEST['send']=="2")
		{
			$error = "";
			if(empty($_REQUEST['tofromname'])) $pnerror .= emsg('PN_error_selUser');
			if(empty($_REQUEST['title'])) $pnerror .= emsg('PN_error_notopic');
			if(empty($_REQUEST['text'])) $pnerror .= emsg('PN_error_notext');
			if(strlen($_REQUEST['text']) > MAXPNLENGTH) $pnerror .= emsg('PN_error_tomuchtext');
			
			$GLOBALS['tmpl']->assign('tofromname', oform($_REQUEST['tofromname']));
			$GLOBALS['tmpl']->assign('title', oform($_REQUEST['title']));
			$GLOBALS['tmpl']->assign('text', oform($_REQUEST['text']));
			
			//=================================================================
			// CHECK OB USER EXISTIERT
			//=================================================================
			$sql = $GLOBALS['db']->Query("SELECT Benutzername as uname, Id as uid, Pnempfang as user_canpn FROM ".PREFIX."_benutzer WHERE Benutzername='".trim($_REQUEST['tofromname'])."' AND Aktiv='1' AND Geloescht!='1'");
			$num = $sql->numrows();
			$row = $sql->fetchrow();
			
			if(!$pnerror)if(!$num)$pnerror .= emsg('PN_error_usernotindb');
			if(!$pnerror)if($_REQUEST['tofromname']==UNAME) $pnerror .= emsg('PN_error_usersameasuname');
			
			
			//=================================================================
			// CHECK OB ABSENDER IN IGNORIERLISTE DES EMPFÄNGERS STEHT
			//=================================================================
			if(is_object($row)) 
			{
				$sql_ignore = $GLOBALS['db']->Query("SELECT IgnorierId, BenutzerId  FROM ".PREFIX."_ignorierliste WHERE BenutzerId='".$row->uid."' AND IgnorierId='".UID."'");
				$num_ignore = $sql_ignore->numrows();
			}
			
			//=================================================================
			// CHECK OB NACHRICHTENBOX VOLL IST
			//=================================================================
			if(!$pnerror)
			{
				if($num_ignore) $pnerror .= emsg('PN_error_blocked');
				if(!$pnerror)
				{
					$row1 = $GLOBALS['db']->RowQuery("SELECT * From " . PREFIX . "_benutzer WHERE Id = '" . $row->uid . "'");
					$row2 = $GLOBALS['db']->RowQuery("SELECT * From " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $row1->Gruppe . "'");
					
					$USERARRAY2 = $row2;
					$usermaxpn = $row2->MaxPn;
					
					$sql3 = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_pn WHERE to_uid='".$row->uid."' AND typ='inbox'");
					$numuserpn = $sql3->numrows();
					
					if($numuserpn >= $usermaxpn) $pnerror .= emsg('PN_error_mailbox_user_full');
				}
			}
			
			//=================================================================
			// CHECK OB USER PN'S EMPFANGEN MOECHTE
			//=================================================================
			if(!$pnerror)
			{
				if($row->user_canpn!=1) $pnerror .= emsg('PN_error_wants_no_pn');
			}
			
			//=================================================================
			// CHECK OB USER DIE GRUPPENRECHTE BESITZT, PN'S ZU EMPFANGEN
			//=================================================================
			if(!$pnerror)
			{
				if(!permission("canpn")) $pnerror .= emsg('PN_error_wants_no_pn');
			}
			
			
			$text = phpdecode(substr($_REQUEST['text'],0, MAXPNLENGTH));
			
			if($_REQUEST['parseurl']=="yes")
			{
				$text = parseurl($text);
			}
			
			if(!$pnerror)
			{
				$sql = $GLOBALS['db']->Query("INSERT INTO ".PREFIX."_pn (smilies,pnid,to_uid,from_uid,topic,message,is_readed,pntime,typ) VALUES ('".$_REQUEST['use_smilies']."','','".$row->uid."','".UID."','".$_REQUEST['title']."','".$text."','no','".time()."','inbox')");
				
				if(isset($_REQUEST['savecopy']) && $_REQUEST['savecopy']=="yes")
				{
					$sql = $GLOBALS['db']->Query("INSERT INTO ".PREFIX."_pn (smilies,pnid,to_uid,from_uid,topic,message,is_readed,pntime,typ) VALUES ('".$_REQUEST['use_smilies']."','','".$row->uid."','".UID."','".$_REQUEST['title']."','".$text."','no','".time()."','outbox')");
				}
				
				// MAILBENACHRICHTIGUNG
				if($row1->Pnempfang==1 && $row1->PnEmail==1)
				{
					$body = $GLOBALS['config_vars']['PN_new_pn_emailbody'];
					$body = str_replace("__USER__", $row1->Benutzername, $body);
					$body = str_replace("__AUTOR__", UNAME, $body);
					$body = str_replace("__LINK__", "http://" . $_SERVER['HTTP_HOST'].str_replace("/index.php","",$_SERVER['PHP_SELF'])."/index.php?p=pn&goto=inbox", $body);
					
					$koobi = new Koobi;
					$koobi->koobi_mail($row1->Email, stripslashes($body), $GLOBALS['config_vars']['PN_subjectnewpnemail'], STANDARDMAIL, STANDARDMAIL, 'text', 'attach', '');
				}
				koobi_message('PN_PeronalMessages', 'PN_PeronalMessages_ok_t', HOME_PATH . '/index.php?p=pn&goto=outbox');
			}
		}
		
		
		if($pnerror) 
		{
			$GLOBALS['tmpl']->assign('title_error', $GLOBALS['config_vars']['Global_error']);
			$GLOBALS['tmpl']->assign('iserror', 1);
			$GLOBALS['tmpl']->assign('error', $pnerror);
		}
		
		$GLOBALS['tmpl']->assign('listfonts',  fontdropdown());
		$GLOBALS['tmpl']->assign('sizedropdown',  sizedropdown());
		$GLOBALS['tmpl']->assign('colordropdown',  colordropdown());
		$GLOBALS['tmpl']->assign('max_post_length', MAXPNLENGTH);
		$GLOBALS['tmpl']->assign('listemos', listsmilies(0,1,1));
		$GLOBALS['tmpl']->assign('newpn_t', str_replace("__ZEICHEN__", MAXPNLENGTH ,$GLOBALS['config_vars']['PN_newpn_t']));
		$GLOBALS['tmpl']->assign('newpn_error', $pnerror);
		
		if(isset($_REQUEST['to']) && $_REQUEST['to']!="")
		{
			$GLOBALS['tmpl']->assign('tofromname', base64_decode($_REQUEST['to']));
		}
		
		
		if(isset($_REQUEST['forward']) && $_REQUEST['forward']!="")
		{
			$fwre = $_REQUEST['forward']=="1" ? "Fw: " : "Re: ";
			$qtext = stripslashes(koobispecialchars($_REQUEST['text']));
			
			$qtext = "\r\n\r\n----------------------------------------\r\n" 
			. $GLOBALS['config_vars']['PN_originalmessage'] 
			. "\r\n" 
			. $GLOBALS['config_vars']['from_t']
			. ": " . base64_decode($_REQUEST['aut']) . "\n" 
			. $GLOBALS['config_vars']['PN_Subject'] 
			. ": ".base64_decode($_REQUEST['subject'])
			. "\r\n" . $GLOBALS['config_vars']['PN_date']
			. ": " . date('d.m.Y, H:i',base64_decode($_REQUEST['date']))
			. "\r\n\r\n" . $qtext;
			
			$GLOBALS['tmpl']->assign('tofromname', base64_decode($_REQUEST['aut']));
			$GLOBALS['tmpl']->assign('title', $fwre.base64_decode($_REQUEST['subject']));
			$GLOBALS['tmpl']->assign('text', $qtext);
		}
		
		if(SMILIES == 1) $GLOBALS['tmpl']->assign('smilie', 1);
		
		$GLOBALS['tmpl']->assign('outin', 0);
		$GLOBALS['tmpl']->assign('neu', 1);
		
	}
	$GLOBALS['tmpl']->assign('pagetitle_html', $sname);
	$GLOBALS['tmpl']->assign('SearchPop', popSearch());
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/pn.tpl')); 
}
?>