<?php
define('IN_COPPERMINE', true);
define('PMS_PHP', true);
require('include/init.inc.php');
require('include/pms.inc.php');
require('include/smilies.inc.php');
require('include/mailer.inc.php');

if (!USER_ID) cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);


// Inbox or Sent?
(int)$box = isset($_REQUEST['box']) ? $_REQUEST['box'] : 0;

$box != 1 ? $box = 0 : $box = 1;
$box != 1 ? $status = 0 : null;
$box == 0 ? $name = $lang_pms['Inbox'] : $name = $lang_pms['Outbox'];
//$name plus the link to the other box
$page_name = $name.' (<a href="?box='.(int)(!$box).'">'.$lang_pms['Box'.(int)$box].'</a>)';


// Delete and mark as read/unread
if( isset($_POST['dowhat']) && isset($_POST['messages']))
{

	switch ($_POST['dowhat']) {
	case "delete_messages_comply":
		$mark_list=$_POST['messages'];
		while(list($key, $value) = each($mark_list)) 
			{
			cpg_db_query("DELETE FROM {$CONFIG['TABLE_PMS']} WHERE id ='".$key."' AND owner='".(USER_ID)."'");
			}
			header('Location: '.str_replace('&amp;', '&', $PHP_SELF."?box=".$_REQUEST['box']));
	   break;
	case "delete_message":
		$mark_list=$_POST['messages'];
		
		list($key, $value) = each($mark_list); 
			if ($value) 
			{
			cpg_db_query("DELETE FROM {$CONFIG['TABLE_PMS']} WHERE id ='".$key."' AND owner='".(USER_ID)."'");
			}
			header('Location: '.str_replace('&amp;', '&', $PHP_SELF."?box=".$_REQUEST['box']));
	   break;
	case "markall_read":
		$mark_list=$_POST['messages'];
		while(list($key) = each($mark_list)) 
		{
			cpg_db_query("UPDATE  {$CONFIG['TABLE_PMS']} SET showed=1 WHERE id ='".$key."' AND owner='".(USER_ID)."'");
		}
		header('Location: '.str_replace('&amp;', '&', $PHP_SELF."?box=".$_REQUEST['box']));
	   break;
	case "markall_unread":
		$mark_list=$_POST['messages'];
		while(list($key) = each($mark_list)) 
		{
			cpg_db_query("UPDATE  {$CONFIG['TABLE_PMS']} SET showed=0 WHERE id ='".$key."' AND owner='".(USER_ID)."'");
		}
		header('Location: '.str_replace('&amp;', '&', $PHP_SELF."?box=".$_REQUEST['box']));
	   break;
	case 3:
	   break;
	case 4:
	   break;
	}

}// end dowhat


// Get total message count (inbox+sent)
$result = cpg_db_query("SELECT count(*) FROM  {$CONFIG['TABLE_PMS']} WHERE status=".$box." AND owner=".(USER_ID));
list($num_messages) = @mysql_fetch_row($result);
mysql_free_result($result);


//Are we viewing a PM?
if(isset($_GET['id'])){

	//Yes! Lets get the details	
	$id = intval($_GET['id']);
	// Set user
	$result = cpg_db_query("SELECT status,owner FROM  {$CONFIG['TABLE_PMS']} WHERE id=".$id);
	list($status, $owner) = mysql_fetch_row($result);
	mysql_free_result($result);
	$status == 0 ? $where = 'u.user_id=sender_id' : $where = 'u.user_id=owner';

	$sql = 	"SELECT id , subject, sender_id, sender_ip, message, smileys, posted, showed, sender,".
				"u.user_id,u.user_group as g_id,u.user_name,u.user_email, u.avatar_url".
		" FROM {$CONFIG['TABLE_PMS']} LEFT JOIN {$CONFIG['TABLE_USERS']} AS u ON sender_id=u.user_id WHERE  id=".$id;

	$result = cpg_db_query($sql);
	$cur_post = mysql_fetch_array($result);
	mysql_free_result($result);

	if ($owner != (USER_ID))
		cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);
	if ($cur_post['showed'] == 0)
		cpg_db_query("UPDATE  {$CONFIG['TABLE_PMS']} SET showed=1 WHERE id=".$id);

		if(!$status) // if not in sent box then create quote link
			$post_actions = "<a href=\"".(PM_LINK).$cur_post['user_id']."&amp;quote=".$cur_post['id']."\"><img src='".$THEME_DIR."images/pm_reply_small.gif' border=0></a>";

	// Perform the main parsing of the message (BBCode, smilies, censor words etc)
	$cur_post['smileys'] = isset($cur_post['smileys']);

	$cur_post['message'] = stripslashes(parse_message($cur_post['message'], (int)(!$cur_post['smileys'])));
	if ($CONFIG['enable_avatar']){
       	($cur_post['avatar_url'] != "") ? $avatar_url= "<br /><br /><img src='".$cur_post["avatar_url"]."' class='image' width='".$CONFIG['mini_thumb_width']."' height='".$CONFIG['mini_thumb_height']."'>" : $avatar_url = '';
	}

$link_pms_index="<a href='?box=".(int)($box)."' style='color:black'>".$lang_pms['Box'.(int)(!$box)]."</a>";	

pageheader($lang_pms['o_board_title']);


$time=format_time($cur_post['posted']);
$disp_subject=stripslashes($cur_post['subject']);
echo <<<EOT
<form action="pms.php" method="post">


<table class="maintable" cellpadding="6" cellspacing="1" border="0" width="100%" align="center">
	<tr>
	<td class="tableh1" colspan="2" style="padding: 6px 0 6px 6px"><strong>$lang_pms[PrivateMessage]</strong><span class="normal">: $disp_subject</span>
	</td>
</tr>
</table>
<table class="maintable" cellpadding="6" cellspacing="0" border="0" width="100%" align="center">
<tr>
		<td class="alt3" style="font-weight:normal" colspan=2>		
			<span style="float:left"><img src="{$THEME_DIR}images/pm_post_old.gif" border="0" /> $time</span>
			
			<span style="float:right">&nbsp;$link_pms_index</span>
		</td>
</tr>
<tr valign="top">
	<td class="alt2" width="20%" rowspan=2>
			<div>
				<a style="font-size: 12pt; font-weight: bold;" href="profile.php?uid=$cur_post[sender_id]">$cur_post[sender]$avatar_url</a>
			</div>
	</td>
	<td class="alt1" width="75%">
	
		
			<!-- icon and title -->
			<div class="smallfont">
				<img class="inlineimg" src="{$THEME_DIR}images/pm_icon1.gif" alt="Standard" border="0" />
				<strong>$disp_subject</strong>
			</div>
			<hr size="1" style="color:#707070;" />
			<!-- / icon and title -->
		
		
		<!-- message -->
		<div style="padding-right: 10px;">
		{$cur_post['message']}
		</div>
		<!-- / message -->

	
	</td>
</tr>
<tr>
	<td class="alt1" align="right">
			$post_actions
	</td>
</tr>
</table>

<br />



<table class="maintable" cellpadding="6" cellspacing="1" border="0" width="100%" align="center">
<thead>
	<tr>
		<td class="tableh1" colspan="2" style="padding: 6px 0 6px 6px">
			<strong>$lang_pms[Deletemessage]</strong>
		</td>
	</tr>
</thead>
	<tr>
		<td class="panelsurround" align="center">
		<div class="panel">
			<div style="width:380px" align="left">
			
			<fieldset class="fieldset">
				<legend>$lang_pms[Deletemessage]</legend>
				<table cellpadding="0" cellspacing="3" border="0">
				<tr>
					<td>To delete this message mark the checkbox and hit 'Delete'.</td>
				</tr>
				<tr>
					<td><label for="deletepm"><input type="checkbox" name="messages[$cur_post[id]]" id="messages[$cur_post[id]]" value="true" />$lang_pms[Deletemessage]</label></td>
				</tr>
				</table>
			</fieldset>
			
			</div>
		</div>
		
		<div style="margin-top:6px">
			<input type="hidden" name="box" value="$_REQUEST[box]" />
			<input type="hidden" name="dowhat" value="delete_message" />
			<input type="submit" class="button" value="Delete this message" accesskey="s" />
		</div>
		</td>
	</tr>
</table>

</form>


EOT;

//endtable();
pagefooter();
ob_end_flush();

}

if(!isset($_GET['id'])){
	


			// Get total inbox count
			$result = cpg_db_query("SELECT count(*) FROM  {$CONFIG['TABLE_PMS']} WHERE owner=".(USER_ID)." AND STATUS='0'");
			list($tot_box[0]) = @mysql_fetch_array($result);
			mysql_free_result($result);
			// Get total sent count
			$result = cpg_db_query("SELECT count(*) FROM  {$CONFIG['TABLE_PMS']} WHERE owner=".(USER_ID)." AND STATUS='1'");
			list($tot_box[1]) = @mysql_fetch_array($result);
			mysql_free_result($result);
			$tot_messages=$tot_box[0]+$tot_box[1];
			$proc[1] = ceil($tot_box[1] / $CONFIG['pms_messages'] * 100);
			$proc[0] = ceil($tot_box[0] / $CONFIG['pms_messages'] * 100);
			$proc_free = 100-($proc[1]+$proc[0]);
			$proc_all_td=($proc[1]+$proc[0])-$proc[$box];
			if ($box=="1") 
				$thisfolder=$proc[1];
			else
				$thisfolder=$proc[0];
			$allfolder=$proc[0]+$proc[1];
				
			//$status = ' - '.$lang_pms['Status'].' '.$proc.'%';
				$selected_in=' selected="selected"';
				$selected_out='';

			if ($box=="1")
				{
				$selected_out=' selected="selected"';
				$selected_in='';
				}
			
		
if($CONFIG['pms_messages'] != 0 && (USER_ID)){
		    $sort_codes = array(
		        'posted_d' => 'posted DESC',
				'posted_a' => 'posted ASC',
				'sender_a' => 'sender ASC',
		        'sender_d' => 'sender DESC',
		        );
		
		    $sort = (!isset($_GET['sort']) || !isset($sort_codes[$_GET['sort']])) ? 'posted_d' : $_GET['sort'];
		
		    $tab_tmpl = array('left_text' => '<td width="100%%" align="left" valign="middle" class="tableh1_compact" style="white-space: nowrap"><b>' . $lang_pms['u_messages_on_p_pages'] . '</b></td>' . "\n",
		        'tab_header' => '',
		        'tab_trailer' => '',
		        'active_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="tableb_compact"><b>%d</b></td>',
		        'inactive_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="navmenu"><a href="' . $PHP_SELF . '?page=%d&box=' . $box . '&sort=' . $sort . '"<b>%d</b></a></td>' . "\n",
				'active_next_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="tableb_compact"><b>%s</b></td>',
				'inactive_next_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="navmenu"><a href="' . $PHP_SELF . '?page=%s&box=' . $box . '&sort=' . $sort . '"<b>Next</b></a></td>',
				'active_prev_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="tableb_compact"><b>%s</b></td>',
				'inactive_prev_tab' => '<td><img src="images/spacer.gif" width="1" height="1"></td>' . "\n" . '<td align="center" valign="middle" class="navmenu"><a href="' . $PHP_SELF . '?page=%s&box=' . $box . '&sort=' . $sort . '"<b>Prev</b></a></td>'
				);
		    $users_per_page = 25;
		    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
		    $lower_limit = ($page-1) * $users_per_page;
		    $total_pages = ceil($tot_box[$box] / $users_per_page);
		




// Fetch messages
$result = cpg_db_query("SELECT id, owner, subject, sender, sender_id, posted, status, showed, replied FROM {$CONFIG['TABLE_PMS']} WHERE owner=".(USER_ID)." AND status=".$box." ORDER BY ". $sort_codes[$sort] ." LIMIT $lower_limit, $users_per_page;");
$new_messages = false;
$total= @mysql_num_rows($result);

if ($total>0) $tabs = create_tabs($total, $page, $total_pages, $tab_tmpl);
$lb = "<select name=\"album_listbox\" class=\"listbox\" onChange=\"if(this.options[this.selectedIndex].value) window.location.href='$PHP_SELF?page=$page&box=$box&sort='+this.options[this.selectedIndex].value;\">\n";
	foreach($sort_codes as $key => $value) {
		  $selected = ($key == $sort) ? "SELECTED" : "";
		  $lb .= "        <option value=\"" . $key . "\" $selected>" . $lang_pms[$key] . "</option>\n";
	}
$lb .= "</select>\n";

pageheader($lang_pms['o_board_title']);

?>


<script type="text/javascript" language="javascript">
<!--
function checkBoxes (form, check) {
  for (var c = 0; c < form.elements.length; c++)
    if (form.elements[c].type == 'checkbox')
      form.elements[c].checked = check;
}
-->
</script>


<?php
echo <<<EOT
<form action="pms.php" method="post">
<table class="maintable" cellpadding="6" cellspacing="1" border="0" width="100%" align="center">
<thead>
	<tr>
		<td class="tableh1" colspan="4" style="padding: 6px 0 6px 6px">
			<strong>$lang_pms[PrivMesIn]</strong><span>: <span>$name</span></span>
		</td>
	</tr>
</thead>
<tbody>
	<tr>
		<td class="panelsurround" align="center">
		<div class="panel">
			<div style="width:480px" align="center">
				<fieldset class="fieldset">
					<legend>$lang_pms[managefolder]</legend>
					<table cellpadding="0" cellspacing="3" border="0" width="100%">
					<tr>
						<td><strong>$name</strong> contains $tot_box[$box] messages.<br />In total there are $tot_messages from a maximum of $CONFIG[pms_messages] messages stored.</td>
					</tr>
					<tr>
						<td>
							<table style="border:2px groove" cellpadding="0" cellspacing="1" border="0" width="100%">
							<tr>
								<td width="$proc[$box]%" class="pms_linecolor1" title="Stored messages in this folder: $tot_box[$box]">&nbsp;</td>
								<td width="$proc_all_td%" class="pms_linecolor2" title="Total messages: $tot_messages">&nbsp;</td>
								<td width="$proc_free%" class="pms_linecolor3" title="$lang_pms[maxmsg]: $CONFIG[pms_messages]">&nbsp;</td>
							</tr>		
							</table>
						</td>
					</tr>
					<tr>
						<td>
							$lang_pms[switch]:<br />
							<select name="box" style="width: 200px;" onchange="this.form.submit();">
							<option value="0" $selected_in>$lang_pms[Inbox] ($tot_box[0] $lang_pms[Messages])</option>
							<option value="1" $selected_out>$lang_pms[Outbox] ($tot_box[1] $lang_pms[Messages])</option>

							</select><!-- go button -->
<input type="submit" class="button" value="$lang_pms[go]"  />
						</td>
					</tr>
					</table>
				</fieldset>
			</div>
		</div>
		</td>
	</tr>
</tbody>
</table>
</form>

<br />





<form action="pms.php" method="post" name="form">
<table class="maintable" cellpadding="0" cellspacing="1" border="0" width="100%" align="center">
<thead>
	<tr>
		<td class="tableh1" colspan="4" style="padding: 6px 0 6px 6px">
			<span class="smallfont" style="float:right">
				<label for="checkall_all">
				$lang_pms[Messages]: <strong>$total</strong>
				<input type="checkbox" name="allbox" id="checkall_all" title="$lang_pms[markmessages_all]" onclick="checkBoxes(this.form, this.checked)" />
				</label>			
			</span>
			<strong>$lang_pms[PrivMesIn]</strong><span>: <span>$name ($tot_box[0])</span></span>			
		</td>
	</tr>
</thead>
<tr><td>
<table class="tborder" cellpadding="6" cellspacing="1" border="0" width="100%" align="center">
EOT;


if ($total>0){
	//get all the message data
	$id = array();
	while($i=mysql_fetch_array($result))
	{
		$id[] = $i['id']; 
		$owner[] = $i['owner']; 
		$subject[] = $i['subject']; 
		$sender[] = $i['sender']; 
		$sender_id[] = $i['sender_id']; 
		$posted[] = $i['posted']; 
		$stat[] = $i['status']; 
		$showed[] = $i['showed']; 
		$replied[] = $i['replied']; 
	}
	//check how many unread messages there are
	$unread_messages = count((array_keys($showed, "0")));
	
	//process date grouping and icons
	$date_group = array();
	$icon_type = array();
	for ($i=0;$i<count($id);$i++)
	{
		$dategroup[$i]=check_date($posted[$i]);
		$icon_type[$i] = $THEME_DIR.'images/pm_old.gif';
		if ($showed[$i] == '0') $icon_type[$i] = $THEME_DIR.'images/pm_new.gif';
		if ($replied[$i] == '1') $icon_type[$i] = $THEME_DIR.'images/pm_replied.gif';
		
	}
	//now read the cookie
	
	for ($i=0;$i<5;$i++)
	{	
		$pms_day_count=count(array_keys($dategroup, $i));
		if($pms_day_count>0)
		{
			$collapse="";
			switch ($i) {
			case 0:
			   $day_name="Today";
			   display_messages_td($day_name,$pms_day_count,$collapse,0);
			   break;
			case 1:
			   $day_name="Yesterday";
			   display_messages_td($day_name,$pms_day_count,$collapse,1);
			   break;
			case 2:
			   $day_name="This week";
			   display_messages_td($day_name,$pms_day_count,$collapse,2);
			   break;
			case 3:
			   $day_name="This month";
			   display_messages_td($day_name,$pms_day_count,$collapse,3);
			   break;
			case 4:
			   $day_name="Older than a month";
			   display_messages_td($day_name,$pms_day_count,$collapse,4);
			   break;
			}
		}
	}
mysql_free_result($result);
}


else // if there are no messages to display
{
	echo '<tr><td class="alt1">'.$lang_pms['No messages'].'</td></tr>'."\n";
}

echo <<<EOT
<input type="hidden" name=box value="((int)($box));">

			
<table class=" " cellpadding="0" cellspacing="0" border="0" width="100%" align="center">
<thead>
	<tr>
		<td class="tablef" align="left">
			<div class="smallfont">
				Sort by $lb
			</div>		
		</td>
		<td class="tablef" align="right" colspan="4">			
			<div class="smallfont">
				$lang_pms[selectedmessages]
				<select name="dowhat">
					<option value="markall_read">$lang_pms[markread]</option>
					<option value="markall_unread">$lang_pms[markunread]</option>
					<option value="delete_messages_comply">$lang_pms[delete]</option>
				</select>
				<input type="hidden" name="box" value="$box" />
				<input type="submit" class="button" value="$lang_pms[go]" />
			</div>		
		</td>
	</tr>
    <tr>
              <td colspan="5" style="padding: 0px;">
                      <table width="100%" cellspacing="0" cellpadding="0">
                              <tr>
                                      $tabs
                              </tr>
                      </table>
              </td>
    </tr>
</form></thead></table>
</tr></td></table>


<table class="pms_legend" cellpadding="0" cellspacing="0" border="0" width="100%" align="center">
<tr><td><img src="{$THEME_DIR}images/pm_new.gif" border=0></td><td class="smallfont">&nbsp;&nbsp;$lang_pms[unreadmsg]</td></tr>
<tr><td><img src="{$THEME_DIR}images/pm_old.gif" border=0></td><td class="smallfont">&nbsp;&nbsp;$lang_pms[readmsg]</td></tr>
<tr><td><img src="{$THEME_DIR}images/pm_replied.gif" border=0></td><td class="smallfont">&nbsp;&nbsp;$lang_pms[reapliedmsg]</td></tr>

	
EOT;
endtable();
pagefooter();
ob_end_flush();
}
}
?>