<?php
/*
+===========================================+
|      ArabPortal V2.2.x Copyright © 2009   |
|   -------------------------------------   |
|                     BY                    |
|              Arab Portal Team             |
|   -------------------------------------   |
|      Web: http://www.ArabPortal.Info      |
|   -------------------------------------   |
|  Last Updated: 25/08/2008 Time: 03:35 AM  |
+===========================================+
*/

require_once('global.php');
unset($ads_head,$ads_foot);

$apt->GroupAllow('view_site');
checkcookie();


$apt->ifpm = 0;
$upload_pm_file = 1;
$menu = new menu;

$menu->menuid =  $apt->getsettings("index_menuid");

$right_menu   = $menu->_menu(1);

if ($apt->get['action']==""){
$box = (int)$apt->get[box];
if(!$box)$box = 1;
if (($apt->get['box']=="") or ($apt->get['box']=="1") ){
    $box_title = "صندوق الوارد";
    $apt->head(LANG_TITLE_PRIVATE_MESSAGES . " -> $box_title");
    $member_lang_head = LANG_TITLE_PRIVATE_MESSAGES;
    $tofrom = "من قبل";
    eval("\$index_middle = \" " . $apt->gettemplate ( 'members_pm_link' ) . "\";");
    $total =  $apt->getsettings("maxpmuser");
    $nummsg = $apt->dbnumquery("rafia_messages","msgbox='1' and userbox='".$apt->cookie['cid']."'");
    $resultc = @(($nummsg / $total)* 100);
    $width = number_format($resultc);
    $resultnew = $apt->query("SELECT * FROM rafia_messages WHERE
                                           msgbox='1' and userbox='".$apt->cookie['cid']."'
                                           and msgisread='1'
                                           ORDER BY  msgid DESC");
    if ($apt->dbnumrows($resultnew) > 0)
    {
        while($row = $apt->dbarray($resultnew))
        {
            @extract($row);
            $msgisread     = "<img border=\"0\" src=\"themes/$themepath/pm_unread.gif\" width=\"18\" height=\"12\">";
            $fromusername  = $fromname;
            $msgdate       = $apt->Hijri ("$msgdate")." ".$apt->gettime($msgdate);
            $apt->color($color);
           eval ("\$pm_msg_list .= \" ".$apt->gettemplate("pm_msg_list")."\";");
        }
     }
    $resultold = $apt->query("SELECT * FROM rafia_messages WHERE
                                         msgbox='1' and userbox='".$apt->cookie['cid']."'
                                         and msgisread='2'
                                         ORDER BY  msgid DESC");
    if ($apt->dbnumrows($resultold) > 0)
    {
        while($row = $apt->dbarray($resultold))
        {
            @extract($row);
            $msgisread     = "<img border=\"0\" src=\"themes/$themepath/pm_read.gif\" width=\"18\" height=\"12\">";
            $fromusername  = $fromname;
            $msgdate       = $apt->Hijri ("$msgdate")." ".$apt->gettime($msgdate);
            $apt->color($color);
           eval ("\$pm_msg_list .= \" ".$apt->gettemplate("pm_msg_list")."\";");
         }
     }
     if (($apt->dbnumrows($resultold) == 0) and ($apt->dbnumrows($resultnew) == 0))
     {
         eval("\$index_middle .= \" " . $apt->gettemplate ( 'pm_list_table' ) . "\";");
     }
     else
     {
           eval("\$index_middle .= \" " . $apt->gettemplate ( 'pm_list_table' ) . "\";");

     }
    echo $apt->script->post_java();
    $apt->html_Output($left_menu);

}elseif ($apt->get['box']=="2"){
    $box_title = "صندوق الصادر";
    $apt->head(LANG_TITLE_PRIVATE_MESSAGES . " -> $box_title");
    $member_lang_head = LANG_TITLE_PRIVATE_MESSAGES;
    $tofrom = "الى";
    eval("\$index_middle = \" " . $apt->gettemplate ( 'members_pm_link' ) . "\";");
    $total =  $apt->getsettings("maxpmuser");
    $nummsg = $apt->dbnumquery("rafia_messages","msgbox='2' and userbox='".$apt->cookie['cid']."'");
    $resultc = @(($nummsg / $total)* 100);
    $width = number_format($resultc);
    $resultnew = $apt->query("SELECT * FROM rafia_messages WHERE
    msgbox='2' and userbox='".$apt->cookie['cid']."'
    and msgisread='1' ORDER BY  msgid DESC");
    if ($apt->dbnumrows($resultnew) > 0)
    {
        while($row = $apt->dbarray($resultnew))
        {
            @extract($row);
            $msgisread     = "<img border=\"0\" src=\"themes/$themepath/pm_unread.gif\" width=\"18\" height=\"12\">";
            $fromusername  = $toname;
            $msgdate       = $apt->Hijri ("$msgdate")." ".$apt->gettime($msgdate);
            $apt->color($color);
           eval ("\$pm_msg_list .= \" ".$apt->gettemplate("pm_msg_list")."\";");
        }
     }
    $resultold = $apt->query("SELECT * FROM rafia_messages WHERE
                                         msgbox='2' and userbox='".$apt->cookie['cid']."'
                                         and msgisread='2'
                                         ORDER BY  msgid DESC");
    if ($apt->dbnumrows($resultold) > 0)
    {
        while($row = $apt->dbarray($resultold))
        {
            @extract($row);
            $msgisread     = "<img border=\"0\" src=\"themes/$themepath/pm_read.gif\" width=\"18\" height=\"12\">";
            $fromusername  = $toname;
            $msgdate       = $apt->Hijri ("$msgdate")." ".$apt->gettime($msgdate);
            $apt->color($color);
           eval ("\$pm_msg_list .= \" ".$apt->gettemplate("pm_msg_list")."\";");
         }
     }
     if (($apt->dbnumrows($resultold) == 0) and ($apt->dbnumrows($resultnew) == 0))
     {
         eval("\$index_middle .= \" " . $apt->gettemplate ( 'pm_list_table' ) . "\";");
     }
     else
     {
           eval("\$index_middle .= \" " . $apt->gettemplate ( 'pm_list_table' ) . "\";");

     }
    echo $apt->script->post_java();
    $apt->html_Output($left_menu);

}elseif ($apt->get['box']=="3"){
    $box_title = "صندوق الحفظ";
    $apt->head(LANG_TITLE_PRIVATE_MESSAGES . " -> $box_title");
    $member_lang_head = LANG_TITLE_PRIVATE_MESSAGES;
    $tofrom = "من قبل";
    eval("\$index_middle = \" " . $apt->gettemplate ( 'members_pm_link' ) . "\";");
    $total =  $apt->getsettings("maxpmuser");
    $nummsg = $apt->dbnumquery("rafia_messages","msgbox='3' and userbox='".$apt->cookie['cid']."'");
    $resultc = @(($nummsg / $total)* 100);
    $width = number_format($resultc);
    $resultnew = $apt->query("SELECT * FROM rafia_messages WHERE
                                           msgbox='3' and userbox='".$apt->cookie['cid']."'
                                           and msgisread='1'
                                           ORDER BY  msgid DESC");
    if ($apt->dbnumrows($resultnew) > 0)
    {
        while($row = $apt->dbarray($resultnew))
        {
            @extract($row);
            $msgisread     = "<img border=\"0\" src=\"themes/$themepath/pm_unread.gif\">";
            $fromusername  = $fromname;
            $msgdate       = $apt->Hijri ("$msgdate")." ".$apt->gettime($msgdate);
            $apt->color($color);
           eval ("\$pm_msg_list .= \" ".$apt->gettemplate("pm_msg_list")."\";");
        }
     }
    $resultold = $apt->query("SELECT * FROM rafia_messages WHERE
                                         msgbox='3' and userbox='".$apt->cookie['cid']."'
                                         and msgisread='2'
                                         ORDER BY  msgid DESC");
    if ($apt->dbnumrows($resultold) > 0)
    {
        while($row = $apt->dbarray($resultold))
        {
            @extract($row);
            $msgisread     = "<img border=\"0\" src=\"themes/$themepath/pm_read.gif\">";
            $fromusername  = $fromname;
            $msgdate       = $apt->Hijri ("$msgdate")." ".$apt->gettime($msgdate);
            $apt->color($color);
           eval ("\$pm_msg_list .= \" ".$apt->gettemplate("pm_msg_list")."\";");
         }
     }
     if (($apt->dbnumrows($resultold) == 0) and ($apt->dbnumrows($resultnew) == 0))
     {
         eval("\$index_middle .= \" " . $apt->gettemplate ( 'pm_list_table' ) . "\";");
     }
     else
     {
           eval("\$index_middle .= \" " . $apt->gettemplate ( 'pm_list_table' ) . "\";");

     }
    echo $apt->script->post_java();
    $apt->html_Output($left_menu);

}
}
if ($apt->get['action']=="view")
{
    checkcookie();
    $msgid = intval($apt->get[msgid]);
    $box = intval($apt->get[box]);
    if(!$box)$box = 1;

    if($box == 2){
    $result = $apt->query("SELECT * FROM rafia_messages WHERE
    msgid='$msgid' and msgbox='2' and userbox='".$apt->cookie['cid']."' limit 1");
    }else{
    $result = $apt->query("SELECT * FROM rafia_messages WHERE
    msgid='$msgid' and userbox='".$apt->cookie['cid']."' limit 1");
    }
    $row = $apt->dbarray($result);
    if(empty($row)) $apt->errmsg(LANG_ERROR_PM_URL);
    @extract($row);
    
    if($msgisread == "1") $apt->query("UPDATE rafia_messages SET msgisread ='2' WHERE msgid='$msgid'");

    $apt->head(LANG_TITLE_PRIVATE_MESSAGES." -> ".$msgtitle);

    eval("\$index_middle .= \" " . $apt->gettemplate ( 'members_pm_link' ) . "\";");
     $rows           =  $apt->getuser($ufromid);
     $userid   	  =  $ufromid;
     $usertitles    =  explode("-", $apt->userRating($rows->usertitles));
     $usertitle     =  $usertitles[1];
     $userimgtitle  =  $usertitles[0];
     $username =  $apt->format_data_out($rows->username);
     $allpost =  $apt->format_data_out($rows->allposts);
     $homepage =  $apt->addToURL ($rows->homepage);
     $date     =  $apt->Hijri($rows->datetime);
     $message       =  $apt->rafia_code($message);
     $homepage =  $apt->addToURL ($rows->homepage);
     $msgdate       =  $apt->Hijri($msgdate)." ".$apt->gettime($msgdate);
     eval ("\$index_middle .= \" " . $apt->gettemplate ( 'pm_msg_table' ) . "\";");

     $apt->html_Output($left_menu);
}
else if ($apt->get['action']=="manag"){

if($apt->get['case']){
$box = (int)$apt->get[box];

$id = $apt->get['id'];
if($apt->get['case'] == 'save'){
$result = $apt->query("update rafia_messages set msgbox='3'
WHERE msgid='$id' and userbox='".$apt->cookie['cid']."'");
$apt->bodymsg("تم حفظ الرسالة بنجاح","$PHP_SELF?box=$box");
}elseif($apt->get['case'] == 'del'){
$result = $apt->query("delete from rafia_messages
WHERE msgid='$id' and userbox='".$apt->cookie['cid']."'");
$apt->bodymsg("تم حذف الرسالة بنجاح","$PHP_SELF?box=$box");
}
die();
}

$box = $apt->post[box];
$do = $apt->post['do'];
if ($do == 'save'){
    $count = count($apt->post['msgsid']);
    $nummsg    = $apt->dbnumquery("rafia_messages","userbox='".$apt->cookie['cid']."' and msgbox='3'");
    $maxpmuser = $apt->getsettings('maxpmuser');
    $nummsg    = $nummsg + $count;
    if ($nummsg > $maxpmuser)
    {
       $apt->errmsg(LANG_ERROR_PM_FULL."".$apt->cookie['cname']);
    }

    if (!count($apt->post['msgsid'])>0)
    {
            $apt->bodymsg("عفوا .. انت لم تقم بإختيار اي رسائل لحفظها","$apt->refe");
	}else{

        foreach($apt->post['msgsid'] as $id)
        {
		if($box == 2){
		
             $result = $apt->query("update rafia_messages set msgbox='3'
                       WHERE msgid='$id' and userbox='".$apt->cookie['cid']."'");
                          }elseif($box == 3){
           			  $apt->bodymsg("عفوا .. الرسائل التي اخترت حفظها محفوظه مسبقا","$PHP_SELF?box=3");
                          }else{
             $result = $apt->query("update rafia_messages set msgbox='3'
                       WHERE msgid='$id' and userbox='".$apt->cookie['cid']."'");
				}            
         }
     }

      if ($result)
      {
            $apt->bodymsg("تم حفظ الرسائل التي اخترتها بنجاح","$PHP_SELF?box=3");
     }
}
else if ($do == 'del')
{
    checkcookie();
    if (!count($apt->post['msgsid'])>0)
    {
            $apt->bodymsg("عفوا .. انت لم تقم بإختيار اي رسائل لحذفها","$apt->refe");
	}else{
        foreach($apt->post['msgsid'] as $id)
        {
             $result = $apt->query("delete from rafia_messages
                                      WHERE msgid='$id'
                                      and userbox='".$apt->cookie['cid']."'");
                                      
         }
     }

      if ($result)
      {

            header("Refresh: 1;url=$PHP_SELF");

            $apt->bodymsg(LANG_MSG_SELECTED_MESSAGE_HAS_DELETED,"$PHP_SELF");

     }
}else if ($do == 'read'){
    if (!count($apt->post['msgsid'])>0)
    {
            $apt->bodymsg("عفوا .. انت لم تقم بإختيار اي رسائل لجعلها مقروءة","$apt->refe");
	}else{
        foreach($apt->post['msgsid'] as $id)
        {
             $result = $apt->query("update rafia_messages set msgisread='2'
                                      WHERE msgid='$id'
                                      and userbox='".$apt->cookie['cid']."'");
                                      
         }
     }

      if ($result)
      {

            header("Refresh: 1;url=$PHP_SELF");

            $apt->bodymsg("تم جعل الرسائل المختارة مقروءه","$PHP_SELF");

     }

}else if ($do == 'unread'){
    if (!count($apt->post['msgsid'])>0)
    {
            $apt->bodymsg("عفوا .. انت لم تقم بإختيار اي رسائل لجعلها غير مقروءه","$apt->refe");
	}else{
        foreach($apt->post['msgsid'] as $id)
        {
             $result = $apt->query("update rafia_messages set msgisread='1'
                                      WHERE msgid='$id'
                                      and userbox='".$apt->cookie['cid']."'");
                                      
         }
     }

      if ($result)
      {

            header("Refresh: 1;url=$PHP_SELF");

            $apt->bodymsg("تم جعل الرسائل المختارة غير مقروءه","$PHP_SELF");

     }

}else if ($do == 'export'){
$text = '';
    if (!count($apt->post['msgsid'])>0){
            $apt->bodymsg("عفوا .. انت لم تقم بإختيار اي رسائل لتصديرها","$apt->refe");
	}else{
        foreach($apt->post['msgsid'] as $id)
        {
             $result = $apt->query("select * from rafia_messages WHERE msgid='$id'
                                    and userbox='".$apt->cookie['cid']."'");
                 $row    = $apt->dbarray($result);
		     @extract($row);
		     $row           =  $apt->getuser($ufromid);
 		     $usertitles    =  explode("-", $apt->userRating($row->usertitles));
		     $usertitle     =  $usertitles[1];
 		     $userimgtitle  =  $usertitles[0];
		     $row->username =  $apt->format_data_out($row->username);
		     $row->homepage =  $apt->addToURL ($row->homepage);
		     $row->date     =  $apt->Hijri($row->datetime);
		     $message       =  $apt->rafia_code($message);
		     $row->homepage =  $apt->addToURL ($row->homepage);
		     $msgdate       =  $apt->Hijri ($msgdate)." ".$apt->gettime($msgdate);
		     $text .= "<table border='0' width='95%' id='table4' cellspacing='1' cellpadding='0'>
			<tr>
				<td width='100%' class='forum_alt1' style='text-align: right'>
				  <p style='text-align: center'>» $msgtitle</td>
			</tr>
			<tr>
				<td width='100%' class='forum_alt3'>
<table border='0' width='100%' id='table16' >
					
			<tr>
				<td width='100%' class='forum_alt3'>
				<table border='0' width='100%' id='table16' >
					<tr>
						<td width='20%' class='forum_alt1' valign='top'>

<span class=small>
الكاتب: $row->username</span></td>


	<td width='80%' valign='top' class='forum_alt2'><span class=small>
						 حرر في    </font>&nbsp;$msgdate</span><hr color='#7394B6' size='1'>
                  
                 <span class=small>$message<br>
      <hr color='#7394B6' size='1'>
        </td>
					</tr>
					</table>
               </td>
				</tr>
			</table>
			    </td>
				</tr>
			</table><br>";
         }
     }

      if ($result)
      {
		header("Content-Type: application/x-ms-download");
		header("Content-disposition: attachment; filename=الرسائل الخاصة.html");
		header("Pragma: no-cache");
		header("Expires: 0");
		$apt->head('');
            echo "<style>
.forum_alt1{
    font:bold 12pt arial;
    color: #34597D;
    background: #DFE9F4;
    padding: 0px;
}
.forum_alt3{
    font:bold 12pt arial;
    color: #34597D;
    background: #FFFFFF;
    padding: 0px;
    border-bottom: solid 3px #8CA7C3;
    border-left: solid 1px #8CA7C3;
    border-right: solid 1px #8CA7C3;
    border-top: solid 1px #8CA7C3;
}
.small{
    font: 13px tahoma;
}
</style>";
            echo "$text";
		exit;
     }
}
}
if ($apt->get['action']=="reply")
{
    checkcookie();
    if($apt->getUser($apt->cookie['cid'])->statpm == 0)$apt->errmsg("عفوا .. لا يسمح لك بإرسال رسائل خاصه");
    $id = (int)$apt->get[id];
    $box = (int)$apt->get[box];
    $apt->head(LANG_TITLE_PRIVATE_MESSAGES);

    eval("\$index_middle = \" " . $apt->gettemplate ( 'members_pm_link' ) . "\";");
    $result = $apt->query("SELECT * FROM rafia_messages WHERE msgid='$id' and userbox='".$apt->cookie['cid']."'");

    $row    = $apt->dbarray($result);
    @extract($row);
    
    if(!strstr($msgtitle,LANG_MSG_REPLY))
    {
         $msgtitle   = LANG_MSG_REPLY.":".$msgtitle;
    }
    if($box == 2){
    $row		= $apt->getuser($utoid);
    $resend		= 'إعادة ';
    }else{
    $row		= $apt->getuser($ufromid);
    $resend		= '';
    }
    $fo = new form;
    $form .= $fo->inputform   ($resend . $apt->lang_form['30'],"text","username","*",$row->username);
    $form .= $fo->hiddenform  ("touserid", $row->userid);
    $form .= $fo->inputform   ($apt->lang_form['22'],"text","msgtitle","*",$msgtitle,"30");
    eval("\$fo->form_code = \"" . $apt->gettemplate ( 'form_code' ) . "\";");

    $fo->countpost    = $apt->getsettings('txtcount8');
    $form .= $fo->txtcount    ();
    $form .= $fo->textarea    ($apt->lang_form['23'],"post","\n\n\n[QUOTE]".$message."[/QUOTE]","10");
    if ($upload_pm_file == 1)
    $form .= $fo->inputform  ($apt->lang_form['29'],"file","phpfile","");

    $image = "themes/".$GLOBALS[themepath]."/do.gif";

     $output = array("action"      => "$PHP_SELF?action=sendreply",
                     "title"      => LANG_TITLE_PRIVATE_MESSAGES,
                     "method"     => '',
                     "name"       => '',
                     "content"    => $form,
                     "image"      => $image
                      );
     $index_middle  .= $fo->formtable($output);
     
    $apt->html_Output($left_menu);
}
if ($apt->get['action']=="sendmsg")
{
    checkcookie();
    if($apt->getUser($apt->cookie['cid'])->statpm == 0)$apt->errmsg("عفوا .. لا يسمح لك بإرسال رسائل خاصه");
    $id = (int) $apt->get[id];
    $apt->head(LANG_TITLE_PRIVATE_MESSAGES);

    eval("\$index_middle = \" " . $apt->gettemplate ( 'members_pm_link' ) . "\";");
    if(isset($id))
    {
        $result      = $apt->query("SELECT username FROM rafia_users where userid='$id'");
        $row         = $apt->dbarray($result);
        $tousername  = $row[username];
    }

     $fo = new form;
     $fo->countpost = $apt->getsettings('txtcount8');

     $form .= $fo->inputform   ($apt->lang_form['30'],"text","username","*",$tousername);
     $form .= $fo->inputform   ($apt->lang_form['22'],"text","msgtitle","*","","30");
     eval("\$fo->form_code = \"" . $apt->gettemplate ( 'form_code' ) . "\";");
     $form .= $fo->txtcount    ();
     $form .= $fo->textarea    ($apt->lang_form['23'],"post","","10");

     $image = "themes/".$GLOBALS[themepath]."/do.gif";

     $output = array("action"      => "$PHP_SELF?action=sendnew",
                     "title"      => LANG_TITLE_PRIVATE_MESSAGES,
                     "method"     => '',
                     "name"       => '',
                     "content"    => $form,
                     "image"      => $image
                      );
         $index_middle  .= $fo->formtable($output);
     $apt->html_Output($left_menu);

}
else if ($apt->get['action']=="sendreply")
{
    checkcookie();
    @extract($HTTP_POST_VARS);

     $arr_post_vars = array($msgtitle,
                            $username,
                            $post);
                            
    if (!$apt->full($arr_post_vars))
    {
        $apt->errmsg(LANG_ERROR_VALIDATE);
    }

    $result    = $apt->query("SELECT email,username,userid FROM rafia_users where username='$username' and userid != '$apt->Guestid'");

    if ($apt->dbnumrows($result) == 0){
       $apt->errmsg(LANG_ERROR_USERNAME_NOT_EXIST);
    }

    $row       = $apt->dbarray($result);
    if(isset($touserid))
    {
        $touserid  = $row[userid];
    }
    $email     = $row[email];
    
    $nummsg    = $apt->dbnumquery("rafia_messages","userbox='$touserid' and msgbox='1'");
    $maxpmuser = $apt->getsettings('maxpmuser');

    if ($nummsg >= $maxpmuser)
    {
       $apt->errmsg(LANG_ERROR_PM_FULL."".$username);
    }

    $nummsg = $apt->dbnumquery("rafia_messages","userbox='".$apt->cookie['cid']."' and msgbox='2'");

    if ($nummsg >= $maxpmuser)
    {
       $apt->errmsg(LANG_ERROR_PM_COUNT_MORE);
    }

    $msgtitle  = $apt->format_post($msgtitle);
    $ufromid   = $apt->format_data($apt->cookie['cid']);
    $fromname  = $apt->format_data($apt->cookie['cname']);
    $message   = $apt->format_post($post);
    $msgdate   = time();
    $result    = $apt->query("INSERT INTO rafia_messages (msgbox,userbox,msgdate,msgisread,msgtitle,message,
                                                            ufromid,fromname,utoid,toname)
                                                      VALUES
                                                            ('1','$touserid','$msgdate','1','$msgtitle','$message',
                                                            '$ufromid','$fromname','$touserid','$username')");
    if ($result){
    $result_box = $apt->query("INSERT INTO rafia_messages (msgbox,userbox,msgdate,msgisread,msgtitle,message,
                                                            ufromid,fromname,utoid,toname)
                                                      VALUES
                                                            ('2','$ufromid','$msgdate','1','$msgtitle','$message',
                                                            '$ufromid','$fromname','$touserid','$username')");
	}
    if ($result)
    {
        $id        = $apt->insertid();
        $id        = $id - 1;
        $name      = $apt->cookie['cname'];
        $sitetitle = $apt->getsettings("sitetitle");
        $sitemail  = $apt->getsettings("sitemail");
        $url       = $apt->getsettings("siteURL")."/pm.php?action=view&msgid=$id&box=1";
         
        $replace   =  array( "{name}"  => $name ,
                             "{sitetitle}" => $sitetitle,
                             "{url}"       => $url);
                             
        $mail    = new email;
        
        $message = $apt->getmessage('msg_alertpm',$html_msg,$replace);
        
        $mail->send($email,
        $apt->getsettings('alert_pm'),
        $message,
        $sitetitle,
        $sitemail,
        $html_msg);

           header("Refresh: 1;url=$PHP_SELF?");
        $apt->bodymsg(LANG_MSG_MESSAGE_HAS_SENT." ".$username,"$PHP_SELF?");
    }
    else
    {
        header("Refresh: 1;url=$PHP_SELF?");

        $apt->bodymsg(LANG_ERROR_ADD_DB,"$PHP_SELF?");
    }
}
else if ($apt->get['action']=="sendnew")
{
    checkcookie();
    
    @extract($HTTP_POST_VARS);
    $username = $apt->format_data(trim($username));
    if(!$username) $username = $s_username;
     $arr_post_vars = array($msgtitle,
                            $username,
                            $post);
                            
    if (!$apt->full($arr_post_vars))
    {
        $apt->errmsg(LANG_ERROR_VALIDATE);
    }
    
    $result    = $apt->query("SELECT email,username,userid FROM rafia_users where username='$username' and userid != '$apt->Guestid'");

    if ($apt->dbnumrows($result) == 0){
       $apt->errmsg(LANG_ERROR_USERNAME_NOT_EXIST);
    }

    $row       = $apt->dbarray($result);
    $touserid  = $row[userid];
    $email     = $row[email];

    $nummsg    = $apt->dbnumquery("rafia_messages","userbox='$touserid' and msgbox='1'");
    $maxpmuser = $apt->getsettings('maxpmuser');
    
    if ($nummsg >= $maxpmuser)
    {
       $apt->errmsg(LANG_ERROR_PM_FULL."".$username);
    }
    
    $nummsg = $apt->dbnumquery("rafia_messages","utoid='".$apt->cookie['cid']."' and msgbox='2'");

    if ($nummsg >= $maxpmuser)
    {
       $apt->errmsg(LANG_ERROR_PM_COUNT_MORE);
    }
    
    $msgtitle  = $apt->format_post($msgtitle);
    $ufromid   = $apt->format_data($apt->cookie['cid']);
    $message   = $apt->format_post($post);
    $fromname  = $apt->format_data($apt->cookie['cname']);
    $msgdate   = time();
    $result    = $apt->query("INSERT INTO rafia_messages (msgbox,userbox,msgdate,
                                                            msgisread,
                                                            msgtitle,
                                                            message,
                                                            ufromid,
                                                            fromname,
                                                            utoid,toname)
                                                      VALUES
                                                            ('1','$touserid','$msgdate',
                                                            '1',
                                                            '$msgtitle',
                                                            '$message',
                                                            '$ufromid',
                                                            '$fromname',
                                                            '$touserid','$username')");
    if ($result){
    $result_box    = $apt->query("INSERT INTO rafia_messages (msgbox,userbox,msgdate,
                                                            msgisread,
                                                            msgtitle,
                                                            message,
                                                            ufromid,
                                                            fromname,
                                                            utoid,toname)
                                                      VALUES
                                                            ('2','$ufromid','$msgdate',
                                                            '1',
                                                            '$msgtitle',
                                                            '$message',
                                                            '$ufromid',
                                                            '$fromname',
                                                            '$touserid','$username')");
	}
    if ($result)
    {
        $id        = $apt->insertid();
        $id        = $id - 1;
        $name      = $apt->cookie['cname'];
        $sitetitle = $apt->getsettings("sitetitle");
        $sitemail  = $apt->getsettings("sitemail");
        $url       = $apt->getsettings("siteURL")."/pm.php?action=view&msgid=$id&box=1";

        $replace   =  array( "{name}"  => $name ,
                             "{sitetitle}" => $sitetitle,
                             "{url}"       => $url);

        $mail = new email;
        $message = $apt->getmessage('msg_alertpm',$html_msg,$replace);
        $mail->send($email,
        $apt->getsettings('alert_pm'),
        $message,
        $sitetitle,
        $sitemail,
        $html_msg);

        header("Refresh: 1;url=$PHP_SELF?");
        $apt->bodymsg(LANG_MSG_MESSAGE_HAS_SENT." ".$username,"$PHP_SELF?");
    }
    else
    {
        header("Refresh: 1;url=$PHP_SELF?");
        $apt->bodymsg($apt->rafia->lang_error['10'],"$PHP_SELF?");
    }
}
if(isset($fo))
{
    print $apt->script->post_java();
}
$apt->foot($pageft);

?>