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


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

if (isset($_POST['form_sent']))
{

	// Flood protection
	if(USER_ID){
		$result = cpg_db_query("SELECT posted FROM {$CONFIG['TABLE_PMS']} where sender_id='".(USER_ID)."' ORDER BY posted DESC LIMIT 1");
		if(list($last) = mysql_fetch_row($result)){
			if(((localised_timestamp(-1)) - $last) < $CONFIG['pms_post_flood'])
				//echo $lang_pms['Flood start'].' '.$CONFIG['pms_post_flood'].' '.$lang_pms['Flood end'];
				cpg_die(ERROR, $lang_pms['Flood start'].' '.$CONFIG['pms_post_flood'].' '.$lang_pms['Flood end'], __FILE__, __LINE__);
		}
		
	}
	// Smileys
	if (isset($_POST['hide_smilies']))
		$smilies = 0;
	else
		$smilies = 1;

	// Check subject
	$subject = copper_trim($_POST['req_subject']);
	if ($subject == '')
		echo $lang_pms['No subject'];
	else if (copper_strlen($subject) > 70)
		echo $lang_pms['Too long subject'];

	// Clean up message from POST
	$message = copper_linebreaks(copper_trim($_POST['message']));

	// Check message
	if ($message == '')
		echo $lang_pms['No message'];
	else if (strlen($message) > 65535)
		echo $lang_pms['Too long message'];


	// Validate BBCode syntax
	if ($CONFIG['pms_message_bbcode'] == '1' && strpos($message, '[') !== false && strpos($message, ']') !== false)
	{
		//require 'include/pms_parser.inc.php';
		$message = preparse_bbcode($message, $errors);
	}
	if (isset($errors))
		echo ($errors[0]);

	// Get userid
	$result = cpg_db_query("SELECT user_id, user_name, user_group, user_pmsmail, user_email FROM {$CONFIG['TABLE_USERS']} WHERE user_name='".addslashes($_POST['req_username'])."'");

	// Send message
	if(list($user_id, $user_name, $user_group, $user_pmsmail, $user_email) = mysql_fetch_row($result)){
		// Check inbox status
		if($CONFIG['pms_messages'] != 0 && (USER_ID))
		{
			$result = cpg_db_query("SELECT count(*) FROM {$CONFIG['TABLE_PMS']} WHERE owner=".$user_id);
			
			list($count) = mysql_fetch_row($result);
			if($count >= $CONFIG['pms_messages']) {
				cpg_die(ERROR, $lang_pms['Inbox full'], __FILE__, __LINE__);
			}
								
			// Also check users own box
			if(isset($_POST['savemessage']) && intval($_POST['savemessage']) == 1)
			{
				$result = cpg_db_query("SELECT count(*) FROM {$CONFIG['TABLE_PMS']} WHERE owner=".(USER_ID)) ;
				list($count) = mysql_fetch_row($result);
				if($count >= $CONFIG['pms_messages'])
					cpg_die(ERROR, $lang_pms['Sent full'], __FILE__, __LINE__);
			}
		}

		// "Send" message
		cpg_db_query("INSERT INTO {$CONFIG['TABLE_PMS']} (owner, subject, message, sender, sender_id, sender_ip, smileys, posted) VALUES(
			'".$user_id."',
			'".addslashes($subject)."',
			'".addslashes($message)."',
			'".addslashes((USER_NAME))."',
			'".(USER_ID)."',
			'".get_remote_address()."',
			'".$smilies."',
			'".localised_timestamp(-1)."'
		)");
		//mark replied
		if(isset($_POST['replied']) && $_POST['replied']>0){
			cpg_db_query("UPDATE  {$CONFIG['TABLE_PMS']} SET replied=1 WHERE id ='".$_POST['replied']."' AND owner='".USER_ID."'");		
		}
		
		// Save an own copy of the message
		if(isset($_POST['savemessage'])){
			cpg_db_query("INSERT INTO {$CONFIG['TABLE_PMS']} (owner, subject, message, sender, sender_id, sender_ip, smileys, showed, status, posted) VALUES(
			'".(USER_ID)."',
			'".addslashes($subject)."',
			'".addslashes($message)."',
			'".addslashes($_POST['req_username'])."',
			'".$user_id."',
			'".get_remote_address()."',
			'".$smilies."',
				'1',
				'1',
				'".localised_timestamp(-1)."'
			)");
		}
		if ($CONFIG['pms_enable_email'] && $user_pmsmail==1 && $user_email)
		{
			include_once('include/mailer.inc.php');
			$gallery_url_prefix = $CONFIG['ecards_more_pic_target']. (substr($CONFIG['ecards_more_pic_target'], -1) == '/' ? '' : '/');			
        	$template_vars = array('{SITE_NAME}' => $CONFIG['gallery_name'],
            '{USER_NAME}' => $user_name,
            '{SENDER_NAME}' => (USER_NAME),
            '{LINK}' => "{$gallery_url_prefix}pms.php"
            );
			
			$mail_body=strtr($lang_pms_notify_email, $template_vars);
			$subject="New private message at ".$CONFIG['gallery_name'];
			cpg_mail($user_email, $subject, $mail_body, 'text/plain', $CONFIG['gallery_name'], $CONFIG['gallery_admin_email'] );
		}
		
	}
	else{
		cpg_die(ERROR, "User doesn't exist", __FILE__, __LINE__);
	}
	
	header('Location: '.str_replace('&amp;', '&', "pms.php"));
}
else
{
if (isset($_GET['id']))
	$id = intval($_GET['id']);
else
	$id = 0;

	if($id > 0){
		$result = cpg_db_query("SELECT user_name FROM {$CONFIG['TABLE_USERS']} WHERE user_id=".$id) or error('Unable to fetch message info', __FILE__, __LINE__, $db->error());
		if (!mysql_num_rows($result))
			echo $lang_common['Bad request'];
		list($username) = mysql_fetch_row($result);
	}

	if(isset($_GET['reply']) || isset($_GET['quote'])){
		$r = isset($_GET['reply']) ? intval($_GET['reply']) : 0;
		$q = isset($_GET['quote']) ? intval($_GET['quote']) : 0;
		// Get message info
		empty($r) ? $id = $q : $id = $r;
		$result = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_PMS']} WHERE id=".$id);
		if (!mysql_num_rows($result))
			echo $lang_common['Bad request'];
		$message = mysql_fetch_assoc($result);

		// Quote the message
		if(isset($_GET['quote']))
			$quote = '[quote='.$message['sender'].']'.stripslashes($message['message']).'[/quote]';

		// Add subject
		$subject = "RE: " . stripslashes($message['subject']);
	}

	$action = $lang_pms['Send a message'];
	$form = '<form name="pmsform" method="post" id="post" action="'.$PHP_SELF.'?action=send"  onSubmit="return checkForm(this)">';

	$page_title = copper_htmlspecialchars($lang_pms['o_board_title']).' / '.$action;
	$form_name = 'post';

	$cur_index = 1;
	if (!isset($username))
		$username = '';
	if (!isset($quote))
		$quote = '';
	if (!isset($subject))
		$subject = '';

pageheader($lang_pms['o_board_title']);
starttable('100%', $action, 2);
echo $form;
?>

<script language="JavaScript" type="text/javascript">
<!--
// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
b_help = "Bold text: [b]text[/b]  (alt+b)";
i_help = "Italic text: [i]text[/i]  (alt+i)";
u_help = "Underline text: [u]text[/u]  (alt+u)";
q_help = "Quote text: [quote]text[/quote]  (alt+q)";
c_help = "Code display: [code]code[/code]  (alt+c)";
l_help = "List: [list]text[/list] (alt+l)";
o_help = "Ordered list: [list=]text[/list]  (alt+o)";
p_help = "Insert image: [img]http://image_url[/img]  (alt+p)";
w_help = "Insert URL: [url]http://url[/url] or [url=http://url]URL text[/url]  (alt+w)";
a_help = "Close all open bbCode tags";
s_help = "Font color: [color=red]text[/color]  Tip: you can also use color=#FF0000";
f_help = "Font size: [size=x-small]small text[/size]";
smilies_help = "Add smilies";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// Shows the help messages in the helpline window
function helpline(help) {
	document.pmsform.helpbox.value = eval(help + "_help");
}


// Replacement for arrayname.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}


function checkForm() {

	formErrors = false;
	if (document.pmsform.message.value.length < 2) {
		formErrors = "You must enter a message when posting.";
	}
	if (document.pmsform.req_subject.value.length < 2) {
		formErrors = "You must enter a subject when posting.";
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	var txtarea = document.pmsform.message;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	var txtarea = document.pmsform.message;

	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			txtarea.value += bbopen + bbclose;
			txtarea.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		txtarea.focus();
		return;
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbopen, bbclose);
		return;
	}
	else
	{
		txtarea.value += bbopen + bbclose;
		txtarea.focus();
	}
	storeCaret(txtarea);
}


function bbstyle(bbnumber) {
	var txtarea = document.pmsform.message;

	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.post.addbbcode' + butnumber + '.value');
			eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('document.post.addbbcode' + butnumber + '.value');
				eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.pmsform.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.post.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

//-->
</script>
<style type="text/css">

TEXTAREA, .bginput {
	FONT-SIZE: 12px;
	FONT-FAMILY: Verdana,Arial,Helvetica,sans-serif;
	COLOR: #000000;
	BACKGROUND-COLOR: #f8f8f8
}
	
genmed {
color:black; 
background-color: #FAFAFA";
}
	
</style>

<table cellpadding="0" cellspacing="0" border="0" bgcolor="#969696" width="100%" align="center"><tr><td>
<table cellpadding="4" cellspacing="0" border="0"  width="100%">
<input type="hidden" name="form_sent" value="1" />
<input type="hidden" name="topic_redirect" value="<?php echo isset($_GET['tid']) ? $_GET['tid'] : '' ?>" />
<input type="hidden" name="topic_redirect" value="<?php echo isset($_POST['from_profile']) ? $_POST['from_profile'] : '' ?>" />
<input type="hidden" name="replied" value="<?php echo $id; ?>" />
<input type="hidden" name="form_user" value="<?php echo (USER_ID); ?>" />

<tr><td class='pms_send_a'><strong><?php echo $lang_pms['Send to'] ?>: </strong></td>
<td class='pms_send_a'><?php echo '<input type="text" class="bginput" name="req_username" size="25" maxlength="25" value="'.copper_htmlspecialchars($username).'" tabindex="'.($cur_index++).'" />'; ?></td></tr>
<tr><td class='pms_send_b'><strong><?php echo $lang_pms['Subject'] ?>: </strong></td>
<td class='pms_send_b'><input class="bginput" type='text' name='req_subject' value="<?php echo $subject ?>" size="80" maxlength="70" tabindex='<?php echo $cur_index++ ?>' /></td></tr>
<tr><td class='pms_send_a' valign=top><strong><?php echo $lang_pms['BBCode'] ?></strong>: 
</td>


</td>
<td class='pms_send_a'>



	<table cellpadding="0" cellspacing="0" border="0">
	<tr>
		<td><font face="verdana,arial,helvetica" size="1" >
			  <input type="button" class="bginput" accesskey="b" name="addbbcode0" value=" B " style="font-weight:bold; width: 30px" onClick="bbstyle(0)" onMouseOver="helpline('b')" />
			  <input type="button" class="bginput" accesskey="i" name="addbbcode2" value=" i " style="font-style:italic; width: 30px" onClick="bbstyle(2)" onMouseOver="helpline('i')" />
			  <input type="button" class="bginput" accesskey="u" name="addbbcode4" value=" u " style="text-decoration: underline; width: 30px" onClick="bbstyle(4)" onMouseOver="helpline('u')" />
				&nbsp;
				<select name="addbbcode18" onChange="bbfontstyle('[color=' + this.form.addbbcode18.options[this.form.addbbcode18.selectedIndex].value + ']', '[/color]');this.selectedIndex=0;" onMouseOver="helpline('s')">
				  <option style="color:black; background-color: #FAFAFA" value="#444444">Default</option>
				  <option style="color:darkred; background-color: #FAFAFA" value="darkred" class="genmed">Dark Red</option>
				  <option style="color:red; background-color: #FAFAFA" value="red" class="genmed">Red</option>
				  <option style="color:orange; background-color: #FAFAFA" value="orange" class="genmed">Orange</option>
				  <option style="color:brown; background-color: #FAFAFA" value="brown" class="genmed">Brown</option>
				  <option style="color:yellow; background-color: #FAFAFA" value="yellow" class="genmed">Yellow</option>
				  <option style="color:green; background-color: #FAFAFA" value="green" class="genmed">Green</option>
				  <option style="color:olive; background-color: #FAFAFA" value="olive" class="genmed">Olive</option>
				  <option style="color:cyan; background-color: #FAFAFA" value="cyan" class="genmed">Cyan</option>
				  <option style="color:blue; background-color: #FAFAFA" value="blue" class="genmed">Blue</option>
				  <option style="color:darkblue; background-color: #FAFAFA" value="darkblue" class="genmed">Dark Blue</option>
				  <option style="color:indigo; background-color: #FAFAFA" value="indigo" class="genmed">Indigo</option>
				  <option style="color:violet; background-color: #FAFAFA" value="violet" class="genmed">Violet</option>
				  <option style="color:white; background-color: #FAFAFA" value="white" class="genmed">White</option>
				  <option style="color:black; background-color: #FAFAFA" value="black" class="genmed">Black</option>
				</select> &nbsp;
				<br />
			  <input type="button" class="bginput" accesskey="q" name="addbbcode6" value="Quote" style="width: 50px" onClick="bbstyle(6)" onMouseOver="helpline('q')" />
			  <input type="button" class="bginput" accesskey="c" name="addbbcode8" value="Code" style="width: 40px" onClick="bbstyle(8)" onMouseOver="helpline('c')" />
			  <input type="button" class="bginput" accesskey="p" name="addbbcode14" value="Img" style="width: 40px"  onClick="bbstyle(14)" onMouseOver="helpline('p')" />
			  <input type="button" class="bginput" accesskey="w" name="addbbcode16" value="URL" style="text-decoration: underline; width: 40px" onClick="bbstyle(16)" onMouseOver="helpline('w')" />
				&nbsp;
			  <input type="button" class="bginput" value="Smilies" title="Smilies" onclick="window.open('pms_smilies.php', 'shoutBoxSmilies', 'width=370,height=400,toolbar=0,location=0,menubar=0,directories=0,scrollbars=1');" onmouseover="helpline('smilies')"
				<input type="text" class="bginput" name="status" style="font-size:7pt" size="50" value="Use these controls to insert BBcode">

		</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span><a href="javascript:bbstyle(-1)" onMouseOver="helpline('a')">Close Tags</a></span>

		<br /><input type="text" name="helpbox" size="45" maxlength="100" style="width:450px; font-size:10px" class="helpline" value="Tip: Styles can be applied quickly to selected text." />
		</td></tr>
	</table>



</td></tr>
<tr><td class='pms_send_b' valign=top><strong><?php echo $lang_pms['Message'] ?></strong>: </td>
<td class='pms_send_b'>





<textarea name="message" rows="20" cols="70" wrap="virtual" tabindex="<?php echo $cur_index++ ?>"><?php echo $quote ?></textarea><br /></label></td></tr>
<tr><td class='pms_send_a'><strong><?php echo $lang_pms['Settings'] ?>: </strong><br />
<font size=1>
&nbsp;&nbsp;<?php echo $lang_pms['BBCode'] ?>: <?php echo ($CONFIG['pms_message_bbcode'] == '1') ? $lang_pms['on'] : $lang_pms['off']; ?><br />
&nbsp;&nbsp;<?php echo $lang_pms['img tag'] ?>: <?php echo ($CONFIG['pms_message_img_tag'] == '1') ? $lang_pms['on'] : $lang_pms['off']; ?><br />
&nbsp;&nbsp;<?php echo $lang_pms['Smilies'] ?>: <?php echo ($CONFIG['pms_smilies'] == '1') ? $lang_pms['on'] : $lang_pms['off']; ?><br />
</font>

</td>
<td class='pms_send_a' valign=top>
<?php
	$checkboxes = array();

	//if ($CONFIG['pms_smilies'] == '1') $checkboxes[] = '<input type="checkbox" name="hide_smilies" value="1" tabindex="'.($cur_index++).'"'.(isset($_POST['hide_smilies']) ? ' checked="checked"' : '').' />'.$lang_pms['Hide smilies'];

	$checkboxes[] = '<input type="checkbox" name="savemessage" value="1" checked tabindex="'.($cur_index++).'" />'.$lang_pms['Save message'];

	if (!empty($checkboxes))
	{
?>
<?php echo implode('<br /></label>'."\n\t\t\t\t", $checkboxes).'<br /></label>'."\n" ?></td></tr>
<tr><td class='pms_send_b' colspan=2 align=center>
<input class="shoutboxbutton" type="submit" name="submit" value="<?php echo $lang_pms['Send'] ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="s" />
</form>
</td></tr></table>
<?php
}
endtable();
pagefooter();
ob_end_flush();
}
?>