1<?php
2/**
3 * MyBB 1.8
4 * Copyright 2014 MyBB Group, All Rights Reserved
5 *
6 * Website: http://www.mybb.com
7 * License: http://www.mybb.com/about/license
8 *
9 */
10
11define("IN_MYBB", 1);
12define("IGNORE_CLEAN_VARS", "sid");
13define('THIS_SCRIPT', 'private.php');
14
15$templatelist = "private_send,private_send_buddyselect,private_tracking,private_tracking_readmessage,private_tracking_unreadmessage,usercp_nav_attachments,usercp_nav_messenger_compose,private_tracking_readmessage_stop";
16$templatelist .= ",private_folders,private_folders_folder,private_folders_folder_unremovable,private,usercp_nav,private_empty_folder,private_archive_txt,private_archive_csv,private_archive_html,private_tracking_unreadmessage_stop";
17$templatelist .= ",usercp_nav_messenger,usercp_nav_changename,multipage,multipage_end,multipage_jump_page,multipage_nextpage,multipage_page,multipage_page_current,multipage_page_link_current,multipage_prevpage,multipage_start";
18$templatelist .= ",private_messagebit,codebuttons,posticons,private_send_autocomplete,private_messagebit_denyreceipt,postbit_warninglevel_formatted,private_emptyexportlink,postbit_purgespammer,postbit_gotopost,private_read";
19$templatelist .= ",postbit_delete_pm,postbit,private_tracking_nomessage,private_nomessages,postbit_author_guest,private_multiple_recipients_user,private_multiple_recipients_bcc,private_multiple_recipients,usercp_nav_messenger_folder";
20$templatelist .= ",private_search_messagebit,private_search_results_nomessages,private_search_results,private_advanced_search,previewpost,private_send_tracking,private_send_signature,private_read_bcc,private_composelink";
21$templatelist .= ",private_archive,private_quickreply,private_pmspace,private_limitwarning,postbit_groupimage,postbit_offline,postbit_www,postbit_replyall_pm,postbit_signature,postbit_classic,postbit_reputation_formatted_link";
22$templatelist .= ",private_archive_folders_folder,private_archive_folders,postbit_warninglevel,postbit_author_user,postbit_forward_pm,private_messagebit_icon,private_jump_folders_folder,private_advanced_search_folders,usercp_nav_home";
23$templatelist .= ",private_jump_folders,postbit_avatar,postbit_warn,postbit_rep_button,postbit_email,postbit_reputation,private_move,private_read_action,postbit_away,postbit_pm,usercp_nav_messenger_tracking,postbit_find";
24$templatelist .= ",usercp_nav_editsignature,posticons_icon,postbit_icon,postbit_iplogged_hiden,usercp_nav_profile,usercp_nav_misc,postbit_userstar,private_read_to,postbit_online,private_empty,private_orderarrow,postbit_reply_pm";
25
26require_once "./global.php";
27require_once MYBB_ROOT."inc/functions_post.php";
28require_once MYBB_ROOT."inc/functions_user.php";
29require_once MYBB_ROOT."inc/class_parser.php";
30$parser = new postParser;
31
32// Load global language phrases
33$lang->load("private");
34
35if($mybb->settings['enablepms'] == 0)
36{
37	error($lang->pms_disabled);
38}
39
40if($mybb->user['uid'] == '/' || $mybb->user['uid'] == 0 || $mybb->usergroup['canusepms'] == 0)
41{
42	error_no_permission();
43}
44
45$mybb->input['fid'] = $mybb->get_input('fid', MyBB::INPUT_INT);
46
47$folder_id = $folder_name = $folderjump_folder = $folderoplist_folder = $foldersearch_folder ='';
48
49$foldernames = array();
50$foldersexploded = explode("$%%$", $mybb->user['pmfolders']);
51foreach($foldersexploded as $key => $folders)
52{
53	$folderinfo = explode("**", $folders, 2);
54	if($mybb->input['fid'] == $folderinfo[0])
55	{
56		$sel = ' selected="selected"';
57	}
58	else
59	{
60		$sel = '';
61	}
62	$folderinfo[1] = get_pm_folder_name($folderinfo[0], $folderinfo[1]);
63	$foldernames[$folderinfo[0]] = $folderinfo[1];
64
65	$folder_id = $folderinfo[0];
66	$folder_name = $folderinfo[1];
67
68	eval("\$folderjump_folder .= \"".$templates->get("private_jump_folders_folder")."\";");
69
70	// Manipulate search folder selection & move selector to omit "Unread"
71	if($folder_id != 1)
72	{
73		if($folder_id == 0)
74		{
75			$folder_id = 1;
76		}
77		eval("\$folderoplist_folder .= \"".$templates->get("private_jump_folders_folder")."\";");
78		eval("\$foldersearch_folder .= \"".$templates->get("private_jump_folders_folder")."\";");
79	}
80}
81
82$from_fid = $mybb->input['fid'];
83
84eval("\$folderjump = \"".$templates->get("private_jump_folders")."\";");
85eval("\$folderoplist = \"".$templates->get("private_move")."\";");
86eval("\$foldersearch = \"".$templates->get("private_advanced_search_folders")."\";");
87
88usercp_menu();
89
90$plugins->run_hooks("private_start");
91
92// Make navigation
93add_breadcrumb($lang->nav_pms, "private.php");
94
95$mybb->input['action'] = $mybb->get_input('action');
96switch($mybb->input['action'])
97{
98	case "send":
99		add_breadcrumb($lang->nav_send);
100		break;
101	case "tracking":
102		add_breadcrumb($lang->nav_tracking);
103		break;
104	case "folders":
105		add_breadcrumb($lang->nav_folders);
106		break;
107	case "empty":
108		add_breadcrumb($lang->nav_empty);
109		break;
110	case "export":
111		add_breadcrumb($lang->nav_export);
112		break;
113	case "advanced_search":
114		add_breadcrumb($lang->nav_search);
115		break;
116	case "results":
117		add_breadcrumb($lang->nav_results);
118		break;
119}
120
121if(!empty($mybb->input['preview']))
122{
123	$mybb->input['action'] = "send";
124}
125
126if(($mybb->input['action'] == "do_search" || $mybb->input['action'] == "do_stuff" && ($mybb->get_input('quick_search') || !$mybb->get_input('hop') && !$mybb->get_input('moveto') && !$mybb->get_input('delete'))) && $mybb->request_method == "post")
127{
128	$plugins->run_hooks("private_do_search_start");
129
130	// Simulate coming from our advanced search form with some preset options
131	if($mybb->get_input('quick_search'))
132	{
133		$mybb->input['action'] = "do_search";
134		$mybb->input['subject'] = 1;
135		$mybb->input['message'] = 1;
136		$mybb->input['folder'] = $mybb->input['fid'];
137		unset($mybb->input['jumpto']);
138		unset($mybb->input['fromfid']);
139	}
140
141	// Check if search flood checking is enabled and user is not admin
142	if($mybb->settings['searchfloodtime'] > 0 && $mybb->usergroup['cancp'] != 1)
143	{
144		// Fetch the time this user last searched
145		$timecut = TIME_NOW-$mybb->settings['searchfloodtime'];
146		$query = $db->simple_select("searchlog", "*", "uid='{$mybb->user['uid']}' AND dateline > '$timecut'", array('order_by' => "dateline", 'order_dir' => "DESC"));
147		$last_search = $db->fetch_array($query);
148		// Users last search was within the flood time, show the error
149		if($last_search['sid'])
150		{
151			$remaining_time = $mybb->settings['searchfloodtime']-(TIME_NOW-$last_search['dateline']);
152			if($remaining_time == 1)
153			{
154				$lang->error_searchflooding = $lang->sprintf($lang->error_searchflooding_1, $mybb->settings['searchfloodtime']);
155			}
156			else
157			{
158				$lang->error_searchflooding = $lang->sprintf($lang->error_searchflooding, $mybb->settings['searchfloodtime'], $remaining_time);
159			}
160			error($lang->error_searchflooding);
161		}
162	}
163
164	if($mybb->get_input('subject', MyBB::INPUT_INT) != 1 && $mybb->get_input('message', MyBB::INPUT_INT) != 1)
165	{
166		error($lang->error_nosearchresults);
167	}
168
169	if($mybb->get_input('message', MyBB::INPUT_INT) == 1)
170	{
171		$resulttype = "pmmessages";
172	}
173	else
174	{
175		$resulttype = "pmsubjects";
176	}
177
178	$search_data = array(
179		"keywords" => $mybb->get_input('keywords'),
180		"subject" => $mybb->get_input('subject', MyBB::INPUT_INT),
181		"message" => $mybb->get_input('message', MyBB::INPUT_INT),
182		"sender" => $mybb->get_input('sender'),
183		"status" => $mybb->get_input('status', MyBB::INPUT_ARRAY),
184		"folder" => $mybb->get_input('folder', MyBB::INPUT_ARRAY)
185	);
186
187	if($db->can_search == true)
188	{
189		require_once MYBB_ROOT."inc/functions_search.php";
190
191		$search_results = privatemessage_perform_search_mysql($search_data);
192	}
193	else
194	{
195		error($lang->error_no_search_support);
196	}
197	$sid = md5(uniqid(microtime(), true));
198	$searcharray = array(
199		"sid" => $db->escape_string($sid),
200		"uid" => $mybb->user['uid'],
201		"dateline" => TIME_NOW,
202		"ipaddress" => $db->escape_binary($session->packedip),
203		"threads" => '',
204		"posts" => '',
205		"resulttype" => $resulttype,
206		"querycache" => $search_results['querycache'],
207		"keywords" => $db->escape_string($mybb->get_input('keywords')),
208	);
209	$plugins->run_hooks("private_do_search_process");
210
211	$db->insert_query("searchlog", $searcharray);
212
213	// Sender sort won't work yet
214	$sortby = array('subject', 'sender', 'dateline');
215
216	if(in_array($mybb->get_input('sort'), $sortby))
217	{
218		$sortby = $mybb->get_input('sort');
219	}
220	else
221	{
222		$sortby = "dateline";
223	}
224
225	if(my_strtolower($mybb->get_input('sortordr')) == "asc")
226	{
227		$sortorder = "asc";
228	}
229	else
230	{
231		$sortorder = "desc";
232	}
233
234	$plugins->run_hooks("private_do_search_end");
235	redirect("private.php?action=results&sid=".$sid."&sortby=".$sortby."&order=".$sortorder, $lang->redirect_searchresults);
236}
237
238if($mybb->input['action'] == "results")
239{
240	$sid = $mybb->get_input('sid');
241	$query = $db->simple_select("searchlog", "*", "sid='".$db->escape_string($sid)."' AND uid='{$mybb->user['uid']}'");
242	$search = $db->fetch_array($query);
243
244	if(!$search)
245	{
246		error($lang->error_invalidsearch);
247	}
248
249	$plugins->run_hooks("private_results_start");
250
251	// Decide on our sorting fields and sorting order.
252	$order = my_strtolower($mybb->get_input('order'));
253	$sortby = my_strtolower($mybb->get_input('sortby'));
254
255	$sortby_accepted = array('subject', 'username', 'dateline');
256
257	if(in_array($sortby, $sortby_accepted))
258	{
259		$query_sortby = $sortby;
260
261		if($query_sortby == "username")
262		{
263			$query_sortby = "fromusername";
264		}
265	}
266	else
267	{
268		$sortby = $query_sortby = "dateline";
269	}
270
271	if($order != "asc")
272	{
273		$order = "desc";
274	}
275
276	if(!$mybb->settings['threadsperpage'] || (int)$mybb->settings['threadsperpage'] < 1)
277	{
278		$mybb->settings['threadsperpage'] = 20;
279	}
280
281	$query = $db->simple_select("privatemessages", "COUNT(*) AS total", "pmid IN(".$db->escape_string($search['querycache']).")");
282	$pmscount = $db->fetch_field($query, "total");
283
284	// Work out pagination, which page we're at, as well as the limits.
285	$perpage = $mybb->settings['threadsperpage'];
286	$page = $mybb->get_input('page', MyBB::INPUT_INT);
287	if($page > 0)
288	{
289		$start = ($page-1) * $perpage;
290		$pages = ceil($pmscount / $perpage);
291		if($page > $pages)
292		{
293			$start = 0;
294			$page = 1;
295		}
296	}
297	else
298	{
299		$start = 0;
300		$page = 1;
301	}
302	$end = $start + $perpage;
303	$lower = $start+1;
304	$upper = $end;
305
306	// Work out if we have terms to highlight
307	$highlight = "";
308	if($search['keywords'])
309	{
310		$highlight = "&amp;highlight=".urlencode($search['keywords']);
311	}
312
313	// Do Multi Pages
314	if($upper > $pmscount)
315	{
316		$upper = $pmscount;
317	}
318	$multipage = multipage($pmscount, $perpage, $page, "private.php?action=results&amp;sid=".htmlspecialchars_uni($mybb->get_input('sid'))."&amp;sortby={$sortby}&amp;order={$order}");
319	$messagelist = '';
320
321	$icon_cache = $cache->read("posticons");
322
323	// Cache users in multiple recipients for sent & drafts folder
324	// Get all recipients into an array
325	$cached_users = $get_users = array();
326	$users_query = $db->simple_select("privatemessages", "recipients", "pmid IN(".$db->escape_string($search['querycache']).")", array('limit_start' => $start, 'limit' => $perpage, 'order_by' => $query_sortby, 'order_dir' => $order));
327	while($row = $db->fetch_array($users_query))
328	{
329		$recipients = my_unserialize($row['recipients']);
330		if(isset($recipients['to']) && is_array($recipients['to']) && count($recipients['to']))
331		{
332			$get_users = array_merge($get_users, $recipients['to']);
333		}
334
335		if(isset($recipients['bcc']) && is_array($recipients['bcc']) && count($recipients['bcc']))
336		{
337			$get_users = array_merge($get_users, $recipients['bcc']);
338		}
339	}
340
341	$get_users = implode(',', array_unique($get_users));
342
343	// Grab info
344	if($get_users)
345	{
346		$users_query = $db->simple_select("users", "uid, username, usergroup, displaygroup", "uid IN ({$get_users})");
347		while($user = $db->fetch_array($users_query))
348		{
349			$cached_users[$user['uid']] = $user;
350		}
351	}
352
353	$query = $db->query("
354		SELECT pm.*, fu.username AS fromusername, tu.username as tousername
355		FROM ".TABLE_PREFIX."privatemessages pm
356		LEFT JOIN ".TABLE_PREFIX."users fu ON (fu.uid=pm.fromid)
357		LEFT JOIN ".TABLE_PREFIX."users tu ON (tu.uid=pm.toid)
358		WHERE pm.pmid IN(".$db->escape_string($search['querycache']).") AND pm.uid='{$mybb->user['uid']}'
359		ORDER BY pm.{$query_sortby} {$order}
360		LIMIT {$start}, {$perpage}
361	");
362	while($message = $db->fetch_array($query))
363	{
364		$msgalt = $msgstatus = '';
365
366		// Determine Folder Icon
367		if($message['status'] == 0)
368		{
369			$msgstatus = 'new_pm';
370			$msgalt = $lang->new_pm;
371		}
372		else if($message['status'] == 1)
373		{
374			$msgstatus = 'old_pm';
375			$msgalt = $lang->old_pm;
376		}
377		else if($message['status'] == 3)
378		{
379			$msgstatus = 're_pm';
380			$msgalt = $lang->reply_pm;
381		}
382		else if($message['status'] == 4)
383		{
384			$msgstatus = 'fw_pm';
385			$msgalt = $lang->fwd_pm;
386		}
387
388		$folder = $message['folder'];
389
390		$tofromuid = 0;
391		if($folder == 2 || $folder == 3)
392		{
393			// Sent Items or Drafts Folder Check
394			$recipients = my_unserialize($message['recipients']);
395			$to_users = $bcc_users = '';
396			if(
397				isset($recipients['to']) &&
398				(count($recipients['to']) > 1 || (count($recipients['to']) == 1 && isset($recipients['bcc']) && count($recipients['bcc']) > 0))
399			)
400			{
401				foreach($recipients['to'] as $uid)
402				{
403					$profilelink = get_profile_link($uid);
404					$user = $cached_users[$uid];
405					$user['username'] = htmlspecialchars_uni($user['username']);
406					$username = format_name($user['username'], $user['usergroup'], $user['displaygroup']);
407					eval("\$to_users .= \"".$templates->get("private_multiple_recipients_user")."\";");
408				}
409				if(isset($recipients['bcc']) && is_array($recipients['bcc']) && count($recipients['bcc']))
410				{
411					eval("\$bcc_users = \"".$templates->get("private_multiple_recipients_bcc")."\";");
412					foreach($recipients['bcc'] as $uid)
413					{
414						$profilelink = get_profile_link($uid);
415						$user = $cached_users[$uid];
416						$user['username'] = htmlspecialchars_uni($user['username']);
417						$username = format_name($user['username'], $user['usergroup'], $user['displaygroup']);
418						eval("\$bcc_users .= \"".$templates->get("private_multiple_recipients_user")."\";");
419					}
420				}
421
422				eval("\$tofromusername = \"".$templates->get("private_multiple_recipients")."\";");
423			}
424			else if($message['toid'])
425			{
426				$tofromusername = htmlspecialchars_uni($message['tousername']);
427				$tofromuid = $message['toid'];
428			}
429			else
430			{
431				$tofromusername = $lang->not_sent;
432			}
433		}
434		else
435		{
436			$tofromusername = htmlspecialchars_uni($message['fromusername']);
437			$tofromuid = $message['fromid'];
438			if($tofromuid == 0)
439			{
440				$tofromusername = $lang->mybb_engine;
441			}
442		}
443
444		$tofromusername = build_profile_link($tofromusername, $tofromuid);
445
446		$denyreceipt = '';
447
448		if($message['icon'] > 0 && $icon_cache[$message['icon']])
449		{
450			$icon = $icon_cache[$message['icon']];
451			$icon['path'] = str_replace("{theme}", $theme['imgdir'], $icon['path']);
452			$icon['path'] = htmlspecialchars_uni($icon['path']);
453			$icon['name'] = htmlspecialchars_uni($icon['name']);
454			eval("\$icon = \"".$templates->get("private_messagebit_icon")."\";");
455		}
456		else
457		{
458			$icon = '&#009;';
459		}
460
461		if(!trim($message['subject']))
462		{
463			$message['subject'] = $lang->pm_no_subject;
464		}
465
466		$message['subject'] = $parser->parse_badwords($message['subject']);
467
468		if(my_strlen($message['subject']) > 50)
469		{
470			$message['subject'] = htmlspecialchars_uni(my_substr($message['subject'], 0, 50)."...");
471		}
472		else
473		{
474			$message['subject'] = htmlspecialchars_uni($message['subject']);
475		}
476
477		if($message['folder'] != "3")
478		{
479			$senddate = my_date('relative', $message['dateline']);
480		}
481		else
482		{
483			$senddate = $lang->not_sent;
484		}
485
486		$fid = "0";
487		if((int)$message['folder'] > 1)
488		{
489			$fid = $message['folder'];
490		}
491		$foldername = $foldernames[$fid];
492
493		// What we do here is parse the post using our post parser, then strip the tags from it
494		$parser_options = array(
495			'allow_html' => 0,
496			'allow_mycode' => 1,
497			'allow_smilies' => 0,
498			'allow_imgcode' => 0,
499			'filter_badwords' => 1
500		);
501		$message['message'] = strip_tags($parser->parse_message($message['message'], $parser_options));
502		if(my_strlen($message['message']) > 200)
503		{
504			$message['message'] = my_substr($message['message'], 0, 200)."...";
505		}
506
507		eval("\$messagelist .= \"".$templates->get("private_search_messagebit")."\";");
508	}
509
510	if($db->num_rows($query) == 0)
511	{
512		eval("\$messagelist = \"".$templates->get("private_search_results_nomessages")."\";");
513	}
514
515	$plugins->run_hooks("private_results_end");
516
517	eval("\$results = \"".$templates->get("private_search_results")."\";");
518	output_page($results);
519}
520
521if($mybb->input['action'] == "advanced_search")
522{
523	$plugins->run_hooks("private_advanced_search");
524
525	eval("\$advanced_search = \"".$templates->get("private_advanced_search")."\";");
526
527	output_page($advanced_search);
528}
529
530// Dismissing a new/unread PM notice
531if($mybb->input['action'] == "dismiss_notice")
532{
533	if($mybb->user['pmnotice'] != 2)
534	{
535		exit;
536	}
537
538	// Verify incoming POST request
539	verify_post_check($mybb->get_input('my_post_key'));
540
541	$updated_user = array(
542		"pmnotice" => 1
543	);
544	$db->update_query("users", $updated_user, "uid='{$mybb->user['uid']}'");
545
546	if(!empty($mybb->input['ajax']))
547	{
548		echo 1;
549		exit;
550	}
551	else
552	{
553		header("Location: index.php");
554		exit;
555	}
556}
557
558$send_errors = '';
559
560if($mybb->input['action'] == "do_send" && $mybb->request_method == "post")
561{
562	if($mybb->usergroup['cansendpms'] == 0)
563	{
564		error_no_permission();
565	}
566
567	// Verify incoming POST request
568	verify_post_check($mybb->get_input('my_post_key'));
569
570	$plugins->run_hooks("private_send_do_send");
571
572	// Attempt to see if this PM is a duplicate or not
573	$to = array_map("trim", explode(",", $mybb->get_input('to')));
574	$to = array_unique($to); // Filter out any duplicates
575	$to_escaped = implode("','", array_map(array($db, 'escape_string'), array_map('my_strtolower', $to)));
576	$time_cutoff = TIME_NOW - (5 * 60 * 60);
577	$query = $db->query("
578		SELECT pm.pmid
579		FROM ".TABLE_PREFIX."privatemessages pm
580		LEFT JOIN ".TABLE_PREFIX."users u ON(u.uid=pm.toid)
581		WHERE LOWER(u.username) IN ('{$to_escaped}') AND pm.dateline > {$time_cutoff} AND pm.fromid='{$mybb->user['uid']}' AND pm.subject='".$db->escape_string($mybb->get_input('subject'))."' AND pm.message='".$db->escape_string($mybb->get_input('message'))."' AND pm.folder!='3'
582		LIMIT 0, 1
583	");
584	if($db->num_rows($query) > 0)
585	{
586		error($lang->error_pm_already_submitted);
587	}
588
589	require_once MYBB_ROOT."inc/datahandlers/pm.php";
590	$pmhandler = new PMDataHandler();
591
592	$pm = array(
593		"subject" => $mybb->get_input('subject'),
594		"message" => $mybb->get_input('message'),
595		"icon" => $mybb->get_input('icon', MyBB::INPUT_INT),
596		"fromid" => $mybb->user['uid'],
597		"do" => $mybb->get_input('do'),
598		"pmid" => $mybb->get_input('pmid', MyBB::INPUT_INT),
599		"ipaddress" => $session->packedip
600	);
601
602	// Split up any recipients we have
603	$pm['to'] = $to;
604	if(!empty($mybb->input['bcc']))
605	{
606		$pm['bcc'] = explode(",", $mybb->get_input('bcc'));
607		$pm['bcc'] = array_map("trim", $pm['bcc']);
608	}
609
610	$mybb->input['options'] = $mybb->get_input('options', MyBB::INPUT_ARRAY);
611
612	if(!$mybb->usergroup['cantrackpms'])
613	{
614		$mybb->input['options']['readreceipt'] = false;
615	}
616
617	$pm['options'] = array();
618	if(isset($mybb->input['options']['signature']) && $mybb->input['options']['signature'] == 1)
619	{
620		$pm['options']['signature'] = 1;
621	}
622	else
623	{
624		$pm['options']['signature'] = 0;
625	}
626	if(isset($mybb->input['options']['disablesmilies']))
627	{
628		$pm['options']['disablesmilies'] = $mybb->input['options']['disablesmilies'];
629	}
630	if(isset($mybb->input['options']['savecopy']) && $mybb->input['options']['savecopy'] == 1)
631	{
632		$pm['options']['savecopy'] = 1;
633	}
634	else
635	{
636		$pm['options']['savecopy'] = 0;
637	}
638	if(isset($mybb->input['options']['readreceipt']))
639	{
640		$pm['options']['readreceipt'] = $mybb->input['options']['readreceipt'];
641	}
642
643	if(!empty($mybb->input['saveasdraft']))
644	{
645		$pm['saveasdraft'] = 1;
646	}
647	$pmhandler->set_data($pm);
648
649	// Now let the pm handler do all the hard work.
650	if(!$pmhandler->validate_pm())
651	{
652		$pm_errors = $pmhandler->get_friendly_errors();
653		$send_errors = inline_error($pm_errors);
654		$mybb->input['action'] = "send";
655	}
656	else
657	{
658		$pminfo = $pmhandler->insert_pm();
659		$plugins->run_hooks("private_do_send_end");
660
661		if(isset($pminfo['draftsaved']))
662		{
663			redirect("private.php", $lang->redirect_pmsaved);
664		}
665		else
666		{
667			redirect("private.php", $lang->redirect_pmsent);
668		}
669	}
670}
671
672if($mybb->input['action'] == "send")
673{
674	if($mybb->usergroup['cansendpms'] == 0)
675	{
676		error_no_permission();
677	}
678
679	$plugins->run_hooks("private_send_start");
680
681	$smilieinserter = $codebuttons = '';
682
683	if($mybb->settings['bbcodeinserter'] != 0 && $mybb->settings['pmsallowmycode'] != 0 && $mybb->user['showcodebuttons'] != 0)
684	{
685		$codebuttons = build_mycode_inserter("message", $mybb->settings['pmsallowsmilies']);
686		if($mybb->settings['pmsallowsmilies'] != 0)
687		{
688			$smilieinserter = build_clickable_smilies();
689		}
690	}
691
692	$lang->post_icon = $lang->message_icon;
693
694	$posticons = get_post_icons();
695	$message = htmlspecialchars_uni($parser->parse_badwords($mybb->get_input('message')));
696	$subject = htmlspecialchars_uni($parser->parse_badwords($mybb->get_input('subject')));
697
698	$optionschecked = array('signature' => '', 'disablesmilies' => '', 'savecopy' => '', 'readreceipt' => '');
699	$to = $bcc = '';
700
701	if(!empty($mybb->input['preview']) || $send_errors)
702	{
703		$options = $mybb->get_input('options', MyBB::INPUT_ARRAY);
704		if(isset($options['signature']) && $options['signature'] == 1)
705		{
706			$optionschecked['signature'] = 'checked="checked"';
707		}
708		if(isset($options['disablesmilies']) && $options['disablesmilies'] == 1)
709		{
710			$optionschecked['disablesmilies'] = 'checked="checked"';
711		}
712		if(isset($options['savecopy']) && $options['savecopy'] != 0)
713		{
714			$optionschecked['savecopy'] = 'checked="checked"';
715		}
716		if(isset($options['readreceipt']) && $options['readreceipt'] != 0)
717		{
718			$optionschecked['readreceipt'] = 'checked="checked"';
719		}
720		$to = htmlspecialchars_uni(implode(', ', array_unique(array_map('trim', explode(',', $mybb->get_input('to'))))));
721		$bcc = htmlspecialchars_uni(implode(', ', array_unique(array_map('trim', explode(',', $mybb->get_input('bcc'))))));
722	}
723
724	$preview = '';
725	// Preview
726	if(!empty($mybb->input['preview']))
727	{
728		$options = $mybb->get_input('options', MyBB::INPUT_ARRAY);
729		$query = $db->query("
730			SELECT u.username AS userusername, u.*, f.*
731			FROM ".TABLE_PREFIX."users u
732			LEFT JOIN ".TABLE_PREFIX."userfields f ON (f.ufid=u.uid)
733			WHERE u.uid='".$mybb->user['uid']."'
734		");
735
736		$post = $db->fetch_array($query);
737
738		$post['userusername'] = $mybb->user['username'];
739		$post['postusername'] = $mybb->user['username'];
740		$post['message'] = $mybb->get_input('message');
741		$post['subject'] = htmlspecialchars_uni($mybb->get_input('subject'));
742		$post['icon'] = $mybb->get_input('icon', MyBB::INPUT_INT);
743		if(!isset($options['disablesmilies']))
744		{
745			$options['disablesmilies'] = 0;
746		}
747		$post['smilieoff'] = $options['disablesmilies'];
748		$post['dateline'] = TIME_NOW;
749
750		if(!isset($options['signature']))
751		{
752			$post['includesig'] = 0;
753		}
754		else
755		{
756			$post['includesig'] = 1;
757		}
758
759		// Merge usergroup data from the cache
760		$data_key = array(
761			'title' => 'grouptitle',
762			'usertitle' => 'groupusertitle',
763			'stars' => 'groupstars',
764			'starimage' => 'groupstarimage',
765			'image' => 'groupimage',
766			'namestyle' => 'namestyle',
767			'usereputationsystem' => 'usereputationsystem'
768		);
769
770		foreach($data_key as $field => $key)
771		{
772			$post[$key] = $groupscache[$post['usergroup']][$field];
773		}
774
775		$postbit = build_postbit($post, 2);
776		eval("\$preview = \"".$templates->get("previewpost")."\";");
777	}
778	else if(!$send_errors)
779	{
780		// New PM, so load default settings
781		if($mybb->user['signature'] != '')
782		{
783			$optionschecked['signature'] = 'checked="checked"';
784		}
785		if($mybb->usergroup['cantrackpms'] == 1)
786		{
787			$optionschecked['readreceipt'] = 'checked="checked"';
788		}
789		$optionschecked['savecopy'] = 'checked="checked"';
790	}
791
792	// Draft, reply, forward
793	if($mybb->get_input('pmid') && empty($mybb->input['preview']) && !$send_errors)
794	{
795		$query = $db->query("
796			SELECT pm.*, u.username AS quotename
797			FROM ".TABLE_PREFIX."privatemessages pm
798			LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=pm.fromid)
799			WHERE pm.pmid='".$mybb->get_input('pmid', MyBB::INPUT_INT)."' AND pm.uid='{$mybb->user['uid']}'
800		");
801
802		$pm = $db->fetch_array($query);
803		$message = htmlspecialchars_uni($parser->parse_badwords($pm['message']));
804		$subject = htmlspecialchars_uni($parser->parse_badwords($pm['subject']));
805
806		if($pm['folder'] == "3")
807		{
808			// message saved in drafts
809			$mybb->input['uid'] = $pm['toid'];
810
811			if($pm['includesig'] == 1)
812			{
813				$optionschecked['signature'] = 'checked="checked"';
814			}
815			if($pm['smilieoff'] == 1)
816			{
817				$optionschecked['disablesmilies'] = 'checked="checked"';
818			}
819			if($pm['receipt'])
820			{
821				$optionschecked['readreceipt'] = 'checked="checked"';
822			}
823
824			// Get list of recipients
825			$recipients = my_unserialize($pm['recipients']);
826			$comma = $recipientids = '';
827			if(isset($recipients['to']) && is_array($recipients['to']))
828			{
829				foreach($recipients['to'] as $recipient)
830				{
831					$recipient_list['to'][] = $recipient;
832					$recipientids .= $comma.$recipient;
833					$comma = ',';
834				}
835			}
836
837			if(isset($recipients['bcc']) && is_array($recipients['bcc']))
838			{
839				foreach($recipients['bcc'] as $recipient)
840				{
841					$recipient_list['bcc'][] = $recipient;
842					$recipientids .= $comma.$recipient;
843					$comma = ',';
844				}
845			}
846
847			if(!empty($recipientids))
848			{
849				$query = $db->simple_select("users", "uid, username", "uid IN ({$recipientids})");
850				while($user = $db->fetch_array($query))
851				{
852					if(isset($recipients['bcc']) && is_array($recipients['bcc']) && in_array($user['uid'], $recipient_list['bcc']))
853					{
854						$bcc .= htmlspecialchars_uni($user['username']).', ';
855					}
856					else
857					{
858						$to .= htmlspecialchars_uni($user['username']).', ';
859					}
860				}
861			}
862		}
863		else
864		{
865			// forward/reply
866			$subject = preg_replace("#(FW|RE):( *)#is", '', $subject);
867			$message = "[quote='{$pm['quotename']}']\n$message\n[/quote]";
868			$message = preg_replace('#^/me (.*)$#im', "* ".$pm['quotename']." \\1", $message);
869
870			require_once MYBB_ROOT."inc/functions_posting.php";
871
872			if($mybb->settings['maxpmquotedepth'] != '0')
873			{
874				$message = remove_message_quotes($message, $mybb->settings['maxpmquotedepth']);
875			}
876
877			if($mybb->input['do'] == 'forward')
878			{
879				$subject = "Fw: $subject";
880			}
881			elseif($mybb->input['do'] == 'reply')
882			{
883				$subject = "Re: $subject";
884				$uid = $pm['fromid'];
885				if($mybb->user['uid'] == $uid)
886				{
887					$to = $mybb->user['username'];
888				}
889				else
890				{
891					$query = $db->simple_select('users', 'username', "uid='{$uid}'");
892					$to = $db->fetch_field($query, 'username');
893				}
894				$to = htmlspecialchars_uni($to);
895			}
896			else if($mybb->input['do'] == 'replyall')
897			{
898				$subject = "Re: $subject";
899
900				// Get list of recipients
901				$recipients = my_unserialize($pm['recipients']);
902				$recipientids = $pm['fromid'];
903				if(isset($recipients['to']) && is_array($recipients['to']))
904				{
905					foreach($recipients['to'] as $recipient)
906					{
907						if($recipient == $mybb->user['uid'])
908						{
909							continue;
910						}
911						$recipientids .= ','.$recipient;
912					}
913				}
914				$comma = '';
915				$query = $db->simple_select('users', 'uid, username', "uid IN ({$recipientids})");
916				while($user = $db->fetch_array($query))
917				{
918					$to .= $comma.htmlspecialchars_uni($user['username']);
919					$comma = $lang->comma;
920				}
921			}
922		}
923	}
924
925	// New PM with recipient preset
926	if($mybb->get_input('uid', MyBB::INPUT_INT) && empty($mybb->input['preview']))
927	{
928		$query = $db->simple_select('users', 'username', "uid='".$mybb->get_input('uid', MyBB::INPUT_INT)."'");
929		$to = htmlspecialchars_uni($db->fetch_field($query, 'username')).', ';
930	}
931
932	$max_recipients = '';
933	if($mybb->usergroup['maxpmrecipients'] > 0)
934	{
935		$max_recipients = $lang->sprintf($lang->max_recipients, $mybb->usergroup['maxpmrecipients']);
936	}
937
938	if($send_errors)
939	{
940		$to = htmlspecialchars_uni(implode(', ', array_unique(array_map('trim', explode(',', $mybb->get_input('to'))))));
941		$bcc = htmlspecialchars_uni(implode(', ', array_unique(array_map('trim', explode(',', $mybb->get_input('bcc'))))));
942	}
943
944	// Load the auto complete javascript if it is enabled.
945	eval("\$autocompletejs = \"".$templates->get("private_send_autocomplete")."\";");
946
947	$pmid = $mybb->get_input('pmid', MyBB::INPUT_INT);
948	$do = $mybb->get_input('do');
949	if($do != "forward" && $do != "reply" && $do != "replyall")
950	{
951		$do = '';
952	}
953
954	$buddy_select_to = $buddy_select_bcc = '';
955	// See if it's actually worth showing the buddylist icon.
956	if($mybb->user['buddylist'] != '' && $mybb->settings['use_xmlhttprequest'] == 1)
957	{
958		$buddy_select = 'to';
959		eval("\$buddy_select_to = \"".$templates->get("private_send_buddyselect")."\";");
960		$buddy_select = 'bcc';
961		eval("\$buddy_select_bcc = \"".$templates->get("private_send_buddyselect")."\";");
962	}
963
964	// Hide tracking option if no permission
965	$private_send_tracking = '';
966	if($mybb->usergroup['cantrackpms'])
967	{
968		eval("\$private_send_tracking = \"".$templates->get("private_send_tracking")."\";");
969	}
970
971	$plugins->run_hooks("private_send_end");
972
973	eval("\$send = \"".$templates->get("private_send")."\";");
974	output_page($send);
975}
976
977if($mybb->input['action'] == "read")
978{
979	$plugins->run_hooks("private_read");
980
981	$pmid = $mybb->get_input('pmid', MyBB::INPUT_INT);
982
983	$query = $db->query("
984		SELECT pm.*, u.*, f.*
985		FROM ".TABLE_PREFIX."privatemessages pm
986		LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=pm.fromid)
987		LEFT JOIN ".TABLE_PREFIX."userfields f ON (f.ufid=u.uid)
988		WHERE pm.pmid='{$pmid}' AND pm.uid='".$mybb->user['uid']."'
989	");
990	$pm = $db->fetch_array($query);
991
992	if(!$pm)
993	{
994		error($lang->error_invalidpm);
995	}
996
997	if($pm['folder'] == 3)
998	{
999		header("Location: private.php?action=send&pmid={$pm['pmid']}");
1000		exit;
1001	}
1002
1003	// If we've gotten a PM, attach the group info
1004	$data_key = array(
1005		'title' => 'grouptitle',
1006		'usertitle' => 'groupusertitle',
1007		'stars' => 'groupstars',
1008		'starimage' => 'groupstarimage',
1009		'image' => 'groupimage',
1010		'namestyle' => 'namestyle'
1011	);
1012
1013	foreach($data_key as $field => $key)
1014	{
1015		$pm[$key] = $groupscache[$pm['usergroup']][$field];
1016	}
1017
1018	if($pm['receipt'] == 1)
1019	{
1020		if($mybb->usergroup['candenypmreceipts'] == 1 && $mybb->get_input('denyreceipt', MyBB::INPUT_INT) == 1)
1021		{
1022			$receiptadd = 0;
1023		}
1024		else
1025		{
1026			$receiptadd = 2;
1027		}
1028	}
1029
1030	$action_time = '';
1031	if($pm['status'] == 0)
1032	{
1033		$time = TIME_NOW;
1034		$updatearray = array(
1035			'status' => 1,
1036			'readtime' => $time
1037		);
1038
1039		if(isset($receiptadd))
1040		{
1041			$updatearray['receipt'] = $receiptadd;
1042		}
1043
1044		$db->update_query('privatemessages', $updatearray, "pmid='{$pmid}'");
1045
1046		// Update the unread count - it has now changed.
1047		update_pm_count($mybb->user['uid'], 6);
1048
1049		// Update PM notice value if this is our last unread PM
1050		if($mybb->user['unreadpms']-1 <= 0 && $mybb->user['pmnotice'] == 2)
1051		{
1052			$updated_user = array(
1053				"pmnotice" => 1
1054			);
1055			$db->update_query("users", $updated_user, "uid='{$mybb->user['uid']}'");
1056		}
1057	}
1058	// Replied PM?
1059	else if($pm['status'] == 3 && $pm['statustime'])
1060	{
1061		$reply_string = $lang->you_replied_on;
1062		$reply_date = my_date('relative', $pm['statustime']);
1063
1064		if((TIME_NOW - $pm['statustime']) < 3600)
1065		{
1066			// Relative string for the first hour
1067			$reply_string = $lang->you_replied;
1068		}
1069
1070		$actioned_on = $lang->sprintf($reply_string, $reply_date);
1071		eval("\$action_time = \"".$templates->get("private_read_action")."\";");
1072	}
1073	else if($pm['status'] == 4 && $pm['statustime'])
1074	{
1075		$forward_string = $lang->you_forwarded_on;
1076		$forward_date = my_date('relative', $pm['statustime']);
1077
1078		if((TIME_NOW - $pm['statustime']) < 3600)
1079		{
1080			$forward_string = $lang->you_forwarded;
1081		}
1082
1083		$actioned_on = $lang->sprintf($forward_string, $forward_date);
1084		eval("\$action_time = \"".$templates->get("private_read_action")."\";");
1085	}
1086
1087	$pm['userusername'] = $pm['username'];
1088	$pm['subject'] = htmlspecialchars_uni($parser->parse_badwords($pm['subject']));
1089
1090	if($pm['fromid'] == 0)
1091	{
1092		$pm['username'] = $lang->mybb_engine;
1093	}
1094
1095	if(!$pm['username'])
1096	{
1097		$pm['username'] = $lang->na;
1098	}
1099
1100	// Fetch the recipients for this message
1101	$pm['recipients'] = my_unserialize($pm['recipients']);
1102
1103	if(isset($pm['recipients']['to']) && is_array($pm['recipients']['to']))
1104	{
1105		$uid_sql = implode(',', $pm['recipients']['to']);
1106	}
1107	else
1108	{
1109		$uid_sql = $pm['toid'];
1110		$pm['recipients']['to'] = array($pm['toid']);
1111	}
1112
1113	$show_bcc = 0;
1114
1115	// If we have any BCC recipients and this user is an Administrator, add them on to the query
1116	if(isset($pm['recipients']['bcc']) && count($pm['recipients']['bcc']) > 0 && $mybb->usergroup['cancp'] == 1)
1117	{
1118		$show_bcc = 1;
1119		$uid_sql .= ','.implode(',', $pm['recipients']['bcc']);
1120	}
1121
1122	// Fetch recipient names from the database
1123	$bcc_recipients = $to_recipients = $bcc_form_val = array();
1124	$query = $db->simple_select('users', 'uid, username', "uid IN ({$uid_sql})");
1125	while($recipient = $db->fetch_array($query))
1126	{
1127		// User is a BCC recipient
1128		$recipient['username'] = htmlspecialchars_uni($recipient['username']);
1129		if($show_bcc && in_array($recipient['uid'], $pm['recipients']['bcc']))
1130		{
1131			$bcc_recipients[] = build_profile_link($recipient['username'], $recipient['uid']);
1132			$bcc_form_val[] = $recipient['username'];
1133		}
1134		// User is a normal recipient
1135		else if(in_array($recipient['uid'], $pm['recipients']['to']))
1136		{
1137			$to_recipients[] = build_profile_link($recipient['username'], $recipient['uid']);
1138		}
1139	}
1140
1141	$bcc = '';
1142	if(count($bcc_recipients) > 0)
1143	{
1144		$bcc_recipients = implode(', ', $bcc_recipients);
1145		$bcc_form_val = implode(',', $bcc_form_val);
1146		eval("\$bcc = \"".$templates->get("private_read_bcc")."\";");
1147	}
1148	else
1149	{
1150		$bcc_form_val = '';
1151	}
1152
1153	$replyall = false;
1154	if(count($to_recipients) > 1)
1155	{
1156		$replyall = true;
1157	}
1158
1159	if(count($to_recipients) > 0)
1160	{
1161		$to_recipients = implode($lang->comma, $to_recipients);
1162	}
1163	else
1164	{
1165		$to_recipients = $lang->nobody;
1166	}
1167
1168	eval("\$pm['subject_extra'] = \"".$templates->get("private_read_to")."\";");
1169
1170	add_breadcrumb($pm['subject']);
1171	$message = build_postbit($pm, 2);
1172
1173	// Decide whether or not to show quick reply.
1174	$quickreply = '';
1175	if($mybb->settings['pmquickreply'] != 0 && $mybb->user['showquickreply'] != 0 && $mybb->usergroup['cansendpms'] != 0 && $pm['fromid'] != 0 && $pm['folder'] != 3)
1176	{
1177		$trow = alt_trow();
1178
1179		$optionschecked = array('savecopy' => 'checked="checked"', 'signature' => '', 'disablesmilies' => '');
1180		if(!empty($mybb->user['signature']))
1181		{
1182			$optionschecked['signature'] = 'checked="checked"';
1183		}
1184		if($mybb->usergroup['cantrackpms'] == 1)
1185		{
1186			$optionschecked['readreceipt'] = 'checked="checked"';
1187		}
1188
1189		require_once MYBB_ROOT.'inc/functions_posting.php';
1190
1191		$quoted_message = array(
1192			'message' => htmlspecialchars_uni($parser->parse_badwords($pm['message'])),
1193			'username' => $pm['username'],
1194			'quote_is_pm' => true
1195		);
1196		$quoted_message = parse_quoted_message($quoted_message);
1197
1198		if($mybb->settings['maxpmquotedepth'] != '0')
1199		{
1200			$quoted_message = remove_message_quotes($quoted_message, $mybb->settings['maxpmquotedepth']);
1201		}
1202
1203		$subject = preg_replace("#(FW|RE):( *)#is", '', $pm['subject']);
1204
1205		if($mybb->user['uid'] == $pm['fromid'])
1206		{
1207			$to = htmlspecialchars_uni($mybb->user['username']);
1208		}
1209		else
1210		{
1211			$query = $db->simple_select('users', 'username', "uid='{$pm['fromid']}'");
1212			$to = htmlspecialchars_uni($db->fetch_field($query, 'username'));
1213		}
1214
1215		$private_send_tracking = '';
1216		if($mybb->usergroup['cantrackpms'])
1217		{
1218			$lang->options_read_receipt = $lang->quickreply_read_receipt;
1219
1220			eval("\$private_send_tracking = \"".$templates->get("private_send_tracking")."\";");
1221		}
1222
1223		$postoptionschecked = $optionschecked; // Backwards compatability instead of correcting variable used in template
1224
1225		if(!isset($collapsedthead['quickreply']))
1226		{
1227			$collapsedthead['quickreply'] = '';
1228		}
1229		if(!isset($collapsedimg['quickreply']))
1230		{
1231			$collapsedimg['quickreply'] = '';
1232		}
1233		if(!isset($collapsed['quickreply_e']))
1234		{
1235			$collapsed['quickreply_e'] = '';
1236		}
1237
1238		$expaltext = (in_array("quickreply", $collapse)) ? $lang->expcol_expand : $lang->expcol_collapse;
1239		eval("\$quickreply = \"".$templates->get("private_quickreply")."\";");
1240	}
1241
1242	$plugins->run_hooks("private_read_end");
1243
1244	eval("\$read = \"".$templates->get("private_read")."\";");
1245	output_page($read);
1246}
1247
1248if($mybb->input['action'] == "tracking")
1249{
1250	if(!$mybb->usergroup['cantrackpms'])
1251	{
1252		error_no_permission();
1253	}
1254
1255	$plugins->run_hooks("private_tracking_start");
1256	$readmessages = '';
1257	$unreadmessages = '';
1258
1259	if(!$mybb->settings['postsperpage'] || (int)$mybb->settings['postsperpage'] < 1)
1260	{
1261		$mybb->settings['postsperpage'] = 20;
1262	}
1263
1264	// Figure out if we need to display multiple pages.
1265	$perpage = $mybb->settings['postsperpage'];
1266
1267	$query = $db->simple_select("privatemessages", "COUNT(pmid) as readpms", "receipt='2' AND folder!='3' AND status!='0' AND fromid='".$mybb->user['uid']."'");
1268	$postcount = $db->fetch_field($query, "readpms");
1269
1270	$page = $mybb->get_input('read_page', MyBB::INPUT_INT);
1271	$pages = $postcount / $perpage;
1272	$pages = ceil($pages);
1273
1274	if($mybb->get_input('read_page') == "last")
1275	{
1276		$page = $pages;
1277	}
1278
1279	if($page > $pages || $page <= 0)
1280	{
1281		$page = 1;
1282	}
1283
1284	if($page)
1285	{
1286		$start = ($page-1) * $perpage;
1287	}
1288	else
1289	{
1290		$start = 0;
1291		$page = 1;
1292	}
1293
1294	$read_multipage = multipage($postcount, $perpage, $page, "private.php?action=tracking&amp;read_page={page}");
1295
1296	$query = $db->query("
1297		SELECT pm.pmid, pm.subject, pm.toid, pm.readtime, u.username as tousername
1298		FROM ".TABLE_PREFIX."privatemessages pm
1299		LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=pm.toid)
1300		WHERE pm.receipt='2' AND pm.folder!='3'  AND pm.status!='0' AND pm.fromid='".$mybb->user['uid']."'
1301		ORDER BY pm.readtime DESC
1302		LIMIT {$start}, {$perpage}
1303	");
1304	while($readmessage = $db->fetch_array($query))
1305	{
1306		$readmessage['subject'] = htmlspecialchars_uni($parser->parse_badwords($readmessage['subject']));
1307		$readmessage['tousername'] = htmlspecialchars_uni($readmessage['tousername']);
1308		$readmessage['profilelink'] = build_profile_link($readmessage['tousername'], $readmessage['toid']);
1309		$readdate = my_date('relative', $readmessage['readtime']);
1310		eval("\$readmessages .= \"".$templates->get("private_tracking_readmessage")."\";");
1311	}
1312
1313	$stoptrackingread = '';
1314	if(!empty($readmessages))
1315	{
1316		eval("\$stoptrackingread = \"".$templates->get("private_tracking_readmessage_stop")."\";");
1317	}
1318
1319	if(!$readmessages)
1320	{
1321		eval("\$readmessages = \"".$templates->get("private_tracking_nomessage")."\";");
1322	}
1323
1324	$query = $db->simple_select("privatemessages", "COUNT(pmid) as unreadpms", "receipt='1' AND folder!='3' AND status='0' AND fromid='".$mybb->user['uid']."'");
1325	$postcount = $db->fetch_field($query, "unreadpms");
1326
1327	$page = $mybb->get_input('unread_page', MyBB::INPUT_INT);
1328	$pages = $postcount / $perpage;
1329	$pages = ceil($pages);
1330
1331	if($mybb->get_input('unread_page') == "last")
1332	{
1333		$page = $pages;
1334	}
1335
1336	if($page > $pages || $page <= 0)
1337	{
1338		$page = 1;
1339	}
1340
1341	if($page)
1342	{
1343		$start = ($page-1) * $perpage;
1344	}
1345	else
1346	{
1347		$start = 0;
1348		$page = 1;
1349	}
1350
1351	$unread_multipage = multipage($postcount, $perpage, $page, "private.php?action=tracking&amp;unread_page={page}");
1352
1353	$query = $db->query("
1354		SELECT pm.pmid, pm.subject, pm.toid, pm.dateline, u.username as tousername
1355		FROM ".TABLE_PREFIX."privatemessages pm
1356		LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=pm.toid)
1357		WHERE pm.receipt='1' AND pm.folder!='3' AND pm.status='0' AND pm.fromid='".$mybb->user['uid']."'
1358		ORDER BY pm.dateline DESC
1359		LIMIT {$start}, {$perpage}
1360	");
1361	while($unreadmessage = $db->fetch_array($query))
1362	{
1363		$unreadmessage['subject'] = htmlspecialchars_uni($parser->parse_badwords($unreadmessage['subject']));
1364		$unreadmessage['tousername'] = htmlspecialchars_uni($unreadmessage['tousername']);
1365		$unreadmessage['profilelink'] = build_profile_link($unreadmessage['tousername'], $unreadmessage['toid']);
1366		$senddate = my_date('relative', $unreadmessage['dateline']);
1367		eval("\$unreadmessages .= \"".$templates->get("private_tracking_unreadmessage")."\";");
1368	}
1369
1370	$stoptrackingunread = '';
1371	if(!empty($unreadmessages))
1372	{
1373		eval("\$stoptrackingunread = \"".$templates->get("private_tracking_unreadmessage_stop")."\";");
1374	}
1375
1376	if(!$unreadmessages)
1377	{
1378		$lang->no_readmessages = $lang->no_unreadmessages;
1379		eval("\$unreadmessages = \"".$templates->get("private_tracking_nomessage")."\";");
1380	}
1381
1382	$plugins->run_hooks("private_tracking_end");
1383
1384	eval("\$tracking = \"".$templates->get("private_tracking")."\";");
1385	output_page($tracking);
1386}
1387
1388if($mybb->input['action'] == "do_tracking" && $mybb->request_method == "post")
1389{
1390	// Verify incoming POST request
1391	verify_post_check($mybb->get_input('my_post_key'));
1392
1393	$plugins->run_hooks("private_do_tracking_start");
1394
1395	if(!empty($mybb->input['stoptracking']))
1396	{
1397		$mybb->input['readcheck'] = $mybb->get_input('readcheck', MyBB::INPUT_ARRAY);
1398		if(!empty($mybb->input['readcheck']))
1399		{
1400			foreach($mybb->input['readcheck'] as $key => $val)
1401			{
1402				$sql_array = array(
1403					"receipt" => 0
1404				);
1405				$db->update_query("privatemessages", $sql_array, "pmid=".(int)$key." AND fromid=".$mybb->user['uid']);
1406			}
1407		}
1408		$plugins->run_hooks("private_do_tracking_end");
1409		redirect("private.php?action=tracking", $lang->redirect_pmstrackingstopped);
1410	}
1411	elseif(!empty($mybb->input['stoptrackingunread']))
1412	{
1413		$mybb->input['unreadcheck'] = $mybb->get_input('unreadcheck', MyBB::INPUT_ARRAY);
1414		if(!empty($mybb->input['unreadcheck']))
1415		{
1416			foreach($mybb->input['unreadcheck'] as $key => $val)
1417			{
1418				$sql_array = array(
1419					"receipt" => 0
1420				);
1421				$db->update_query("privatemessages", $sql_array, "pmid=".(int)$key." AND fromid=".$mybb->user['uid']);
1422			}
1423		}
1424		$plugins->run_hooks("private_do_tracking_end");
1425		redirect("private.php?action=tracking", $lang->redirect_pmstrackingstopped);
1426	}
1427	elseif(!empty($mybb->input['cancel']))
1428	{
1429		$mybb->input['unreadcheck'] = $mybb->get_input('unreadcheck', MyBB::INPUT_ARRAY);
1430		if(!empty($mybb->input['unreadcheck']))
1431		{
1432			foreach($mybb->input['unreadcheck'] as $pmid => $val)
1433			{
1434				$pmids[$pmid] = (int)$pmid;
1435			}
1436
1437			$pmids = implode(",", $pmids);
1438			$query = $db->simple_select("privatemessages", "uid", "pmid IN ($pmids) AND fromid='".$mybb->user['uid']."'");
1439			while($pm = $db->fetch_array($query))
1440			{
1441				$pmuids[$pm['uid']] = $pm['uid'];
1442			}
1443
1444			$db->delete_query("privatemessages", "pmid IN ($pmids) AND receipt='1' AND status='0' AND fromid='".$mybb->user['uid']."'");
1445			foreach($pmuids as $uid)
1446			{
1447				// Message is canceled, update PM count for this user
1448				update_pm_count($uid);
1449			}
1450		}
1451		$plugins->run_hooks("private_do_tracking_end");
1452		redirect("private.php?action=tracking", $lang->redirect_pmstrackingcanceled);
1453	}
1454}
1455
1456if($mybb->input['action'] == "stopalltracking")
1457{
1458	// Verify incoming POST request
1459	verify_post_check($mybb->get_input('my_post_key'));
1460
1461	$plugins->run_hooks("private_stopalltracking_start");
1462
1463	$sql_array = array(
1464		"receipt" => 0
1465	);
1466	$db->update_query("privatemessages", $sql_array, "receipt='2' AND folder!='3' AND status!='0' AND fromid=".$mybb->user['uid']);
1467
1468	$plugins->run_hooks("private_stopalltracking_end");
1469	redirect("private.php?action=tracking", $lang->redirect_allpmstrackingstopped);
1470}
1471
1472if($mybb->input['action'] == "folders")
1473{
1474	$plugins->run_hooks("private_folders_start");
1475
1476	$folderlist = '';
1477	$foldersexploded = explode("$%%$", $mybb->user['pmfolders']);
1478	foreach($foldersexploded as $key => $folders)
1479	{
1480		$folderinfo = explode("**", $folders, 2);
1481		$foldername = $folderinfo[1];
1482		$fid = $folderinfo[0];
1483		$foldername = get_pm_folder_name($fid, $foldername);
1484
1485		if((int)$folderinfo[0] < 5)
1486		{
1487			$foldername2 = get_pm_folder_name($fid);
1488			eval("\$folderlist .= \"".$templates->get("private_folders_folder_unremovable")."\";");
1489			unset($name);
1490		}
1491		else
1492		{
1493			eval("\$folderlist .= \"".$templates->get("private_folders_folder")."\";");
1494		}
1495	}
1496
1497	$newfolders = '';
1498	for($i = 1; $i <= 5; ++$i)
1499	{
1500		$fid = "new$i";
1501		$foldername = '';
1502		eval("\$newfolders .= \"".$templates->get("private_folders_folder")."\";");
1503	}
1504
1505	$plugins->run_hooks("private_folders_end");
1506
1507	eval("\$folders = \"".$templates->get("private_folders")."\";");
1508	output_page($folders);
1509}
1510
1511if($mybb->input['action'] == "do_folders" && $mybb->request_method == "post")
1512{
1513	// Verify incoming POST request
1514	verify_post_check($mybb->get_input('my_post_key'));
1515
1516	$plugins->run_hooks("private_do_folders_start");
1517
1518	$highestid = 2;
1519	$folders = '';
1520	$donefolders = array();
1521	$mybb->input['folder'] = $mybb->get_input('folder', MyBB::INPUT_ARRAY);
1522	foreach($mybb->input['folder'] as $key => $val)
1523	{
1524		if(empty($donefolders[$val]) )// Probably was a check for duplicate folder names, but doesn't seem to be used now
1525		{
1526			if(my_substr($key, 0, 3) == "new") // Create a new folder
1527			{
1528				++$highestid;
1529				$fid = (int)$highestid;
1530			}
1531			else // Editing an existing folder
1532			{
1533				if($key > $highestid)
1534				{
1535					$highestid = $key;
1536				}
1537
1538				$fid = (int)$key;
1539				// Use default language strings if empty or value is language string
1540				if($val == get_pm_folder_name($fid) || trim($val) == '')
1541				{
1542					$val = '';
1543				}
1544			}
1545
1546			if($val != '' && trim($val) == '' && !(is_numeric($key) && $key <= 4))
1547			{
1548				// If the name only contains whitespace and it's not a default folder, print an error
1549				error($lang->error_emptypmfoldername);
1550			}
1551
1552			if($val != '' || (is_numeric($key) && $key <= 4))
1553			{
1554				// If there is a name or if this is a default folder, save it
1555				$foldername = $db->escape_string(htmlspecialchars_uni($val));
1556
1557				if(my_strpos($foldername, "$%%$") === false)
1558				{
1559					if($folders != '')
1560					{
1561						$folders .= "$%%$";
1562					}
1563					$folders .= "$fid**$foldername";
1564				}
1565				else
1566				{
1567					error($lang->error_invalidpmfoldername);
1568				}
1569			}
1570			else
1571			{
1572				// Delete PMs from the folder
1573				$db->delete_query("privatemessages", "folder='$fid' AND uid='".$mybb->user['uid']."'");
1574			}
1575		}
1576	}
1577
1578	$sql_array = array(
1579		"pmfolders" => $folders
1580	);
1581	$db->update_query("users", $sql_array, "uid='".$mybb->user['uid']."'");
1582
1583	// Update PM count
1584	update_pm_count();
1585
1586	$plugins->run_hooks("private_do_folders_end");
1587
1588	redirect("private.php", $lang->redirect_pmfoldersupdated);
1589}
1590
1591if($mybb->input['action'] == "empty")
1592{
1593	if($mybb->user['totalpms'] == 0)
1594	{
1595		error($lang->error_nopms);
1596	}
1597
1598	$plugins->run_hooks("private_empty_start");
1599
1600	$foldersexploded = explode("$%%$", $mybb->user['pmfolders']);
1601	$folderlist = '';
1602	foreach($foldersexploded as $key => $folders)
1603	{
1604		$folderinfo = explode("**", $folders, 2);
1605		$unread = '';
1606		$fid = $folderinfo[0];
1607		if($folderinfo[0] == "1")
1608		{
1609			$fid = "1";
1610			$unread = " AND status='0'";
1611		}
1612		if($folderinfo[0] == "0")
1613		{
1614			$fid = "1";
1615		}
1616		$foldername = get_pm_folder_name($folderinfo[0], $folderinfo[1]);
1617		$query = $db->simple_select("privatemessages", "COUNT(*) AS pmsinfolder", " folder='$fid'$unread AND uid='".$mybb->user['uid']."'");
1618		$thing = $db->fetch_array($query);
1619		$foldercount = my_number_format($thing['pmsinfolder']);
1620		eval("\$folderlist .= \"".$templates->get("private_empty_folder")."\";");
1621	}
1622
1623	$plugins->run_hooks("private_empty_end");
1624
1625	eval("\$folders = \"".$templates->get("private_empty")."\";");
1626	output_page($folders);
1627}
1628
1629if($mybb->input['action'] == "do_empty" && $mybb->request_method == "post")
1630{
1631	// Verify incoming POST request
1632	verify_post_check($mybb->get_input('my_post_key'));
1633
1634	$plugins->run_hooks("private_do_empty_start");
1635
1636	$emptyq = '';
1637	$mybb->input['empty'] = $mybb->get_input('empty', MyBB::INPUT_ARRAY);
1638	$keepunreadq = '';
1639	if($mybb->get_input('keepunread', MyBB::INPUT_INT) == 1)
1640	{
1641		$keepunreadq = " AND status!='0'";
1642	}
1643	if(!empty($mybb->input['empty']))
1644	{
1645		foreach($mybb->input['empty'] as $key => $val)
1646		{
1647			if($val == 1)
1648			{
1649				$key = (int)$key;
1650				if($emptyq)
1651				{
1652					$emptyq .= " OR ";
1653				}
1654				$emptyq .= "folder='$key'";
1655			}
1656		}
1657
1658		if($emptyq != '')
1659		{
1660			$db->delete_query("privatemessages", "($emptyq) AND uid='".$mybb->user['uid']."'{$keepunreadq}");
1661		}
1662	}
1663
1664	// Update PM count
1665	update_pm_count();
1666
1667	$plugins->run_hooks("private_do_empty_end");
1668	redirect("private.php", $lang->redirect_pmfoldersemptied);
1669}
1670
1671if($mybb->input['action'] == "do_stuff" && $mybb->request_method == "post")
1672{
1673	// Verify incoming POST request
1674	verify_post_check($mybb->get_input('my_post_key'));
1675
1676	$plugins->run_hooks("private_do_stuff");
1677
1678	if(!empty($mybb->input['hop']))
1679	{
1680		header("Location: private.php?fid=".$mybb->get_input('jumpto'));
1681	}
1682	elseif(!empty($mybb->input['moveto']))
1683	{
1684		$pms = array_map('intval', array_keys($mybb->get_input('check', MyBB::INPUT_ARRAY)));
1685		if(!empty($pms))
1686		{
1687			if(!$mybb->input['fid'])
1688			{
1689				$mybb->input['fid'] = 1;
1690			}
1691
1692			if(array_key_exists($mybb->input['fid'], $foldernames))
1693			{
1694				$db->update_query("privatemessages", array("folder" => $mybb->input['fid']), "pmid IN (".implode(",", $pms).") AND uid='".$mybb->user['uid']."'");
1695				update_pm_count();
1696			}
1697			else
1698			{
1699				error($lang->error_invalidmovefid);
1700			}
1701		}
1702
1703		if(!empty($mybb->input['fromfid']))
1704		{
1705			redirect("private.php?fid=".$mybb->get_input('fromfid', MyBB::INPUT_INT), $lang->redirect_pmsmoved);
1706		}
1707		else
1708		{
1709			redirect("private.php", $lang->redirect_pmsmoved);
1710		}
1711	}
1712	elseif(!empty($mybb->input['delete']))
1713	{
1714		$mybb->input['check'] = $mybb->get_input('check', MyBB::INPUT_ARRAY);
1715		if(!empty($mybb->input['check']))
1716		{
1717			$pmssql = '';
1718			foreach($mybb->input['check'] as $key => $val)
1719			{
1720				if($pmssql)
1721				{
1722					$pmssql .= ",";
1723				}
1724				$pmssql .= "'".(int)$key."'";
1725			}
1726
1727			$deletepms = array();
1728			$query = $db->simple_select("privatemessages", "pmid, folder", "pmid IN ($pmssql) AND uid='".$mybb->user['uid']."' AND folder='4'", array('order_by' => 'pmid'));
1729			while($delpm = $db->fetch_array($query))
1730			{
1731				$deletepms[$delpm['pmid']] = 1;
1732			}
1733
1734			foreach($mybb->input['check'] as $key => $val)
1735			{
1736				$key = (int)$key;
1737				if(!empty($deletepms[$key]))
1738				{
1739					$db->delete_query("privatemessages", "pmid='$key' AND uid='".$mybb->user['uid']."'");
1740				}
1741				else
1742				{
1743					$sql_array = array(
1744						"folder" => 4,
1745						"deletetime" => TIME_NOW
1746					);
1747					$db->update_query("privatemessages", $sql_array, "pmid='".$key."' AND uid='".$mybb->user['uid']."'");
1748				}
1749			}
1750		}
1751		// Update PM count
1752		update_pm_count();
1753
1754		if(!empty($mybb->input['fromfid']))
1755		{
1756			redirect("private.php?fid=".$mybb->get_input('fromfid', MyBB::INPUT_INT), $lang->redirect_pmsdeleted);
1757		}
1758		else
1759		{
1760			redirect("private.php", $lang->redirect_pmsdeleted);
1761		}
1762	}
1763}
1764
1765if($mybb->input['action'] == "delete")
1766{
1767	// Verify incoming POST request
1768	verify_post_check($mybb->get_input('my_post_key'));
1769
1770	$plugins->run_hooks("private_delete_start");
1771
1772	$query = $db->simple_select("privatemessages", "*", "pmid='".$mybb->get_input('pmid', MyBB::INPUT_INT)."' AND uid='".$mybb->user['uid']."' AND folder='4'", array('order_by' => 'pmid'));
1773	if($db->num_rows($query) == 1)
1774	{
1775		$db->delete_query("privatemessages", "pmid='".$mybb->get_input('pmid', MyBB::INPUT_INT)."'");
1776	}
1777	else
1778	{
1779		$sql_array = array(
1780			"folder" => 4,
1781			"deletetime" => TIME_NOW
1782		);
1783		$db->update_query("privatemessages", $sql_array, "pmid='".$mybb->get_input('pmid', MyBB::INPUT_INT)."' AND uid='".$mybb->user['uid']."'");
1784	}
1785
1786	// Update PM count
1787	update_pm_count();
1788
1789	$plugins->run_hooks("private_delete_end");
1790	redirect("private.php", $lang->redirect_pmsdeleted);
1791}
1792
1793if($mybb->input['action'] == "export")
1794{
1795	if($mybb->user['totalpms'] == 0)
1796	{
1797		error($lang->error_nopms);
1798	}
1799
1800	$plugins->run_hooks("private_export_start");
1801
1802	$foldersexploded = explode("$%%$", $mybb->user['pmfolders']);
1803	$folder_name = $folder_id = '';
1804	foreach($foldersexploded as $key => $folders)
1805	{
1806		$folderinfo = explode("**", $folders, 2);
1807		$folderinfo[1] = get_pm_folder_name($folderinfo[0], $folderinfo[1]);
1808
1809		$folder_id = $folderinfo[0];
1810		$folder_name = $folderinfo[1];
1811
1812		eval("\$folderlist_folder .= \"".$templates->get("private_archive_folders_folder")."\";");
1813	}
1814
1815	eval("\$folderlist = \"".$templates->get("private_archive_folders")."\";");
1816
1817	$plugins->run_hooks("private_export_end");
1818
1819	eval("\$archive = \"".$templates->get("private_archive")."\";");
1820
1821	output_page($archive);
1822}
1823
1824if($mybb->input['action'] == "do_export" && $mybb->request_method == "post")
1825{
1826	// Verify incoming POST request
1827	verify_post_check($mybb->get_input('my_post_key'));
1828
1829	$plugins->run_hooks("private_do_export_start");
1830
1831	$lang->private_messages_for = $lang->sprintf($lang->private_messages_for, htmlspecialchars_uni($mybb->user['username']));
1832	$exdate = my_date($mybb->settings['dateformat'], TIME_NOW, 0, 0);
1833	$extime = my_date($mybb->settings['timeformat'], TIME_NOW, 0, 0);
1834	$lang->exported_date = $lang->sprintf($lang->exported_date, $exdate, $extime);
1835	$foldersexploded = explode("$%%$", $mybb->user['pmfolders']);
1836	foreach($foldersexploded as $key => $folders)
1837	{
1838		$folderinfo = explode("**", $folders, 2);
1839		$folderinfo[1] = get_pm_folder_name($folderinfo[0], $folderinfo[1]);
1840		$foldersexploded[$key] = implode("**", $folderinfo);
1841	}
1842
1843	if($mybb->get_input('pmid', MyBB::INPUT_INT))
1844	{
1845		$wsql = "pmid='".$mybb->get_input('pmid', MyBB::INPUT_INT)."' AND uid='".$mybb->user['uid']."'";
1846	}
1847	else
1848	{
1849		if($mybb->get_input('daycut', MyBB::INPUT_INT) && ($mybb->get_input('dayway') != "disregard"))
1850		{
1851			$datecut = TIME_NOW-($mybb->get_input('daycut', MyBB::INPUT_INT) * 86400);
1852			$wsql = "pm.dateline";
1853			if($mybb->get_input('dayway') == "older")
1854			{
1855				$wsql .= "<=";
1856			}
1857			else
1858			{
1859				$wsql .= ">=";
1860			}
1861			$wsql .= "'$datecut'";
1862		}
1863		else
1864		{
1865			$wsql = "1=1";
1866		}
1867
1868		$mybb->input['exportfolders'] = $mybb->get_input('exportfolders', MyBB::INPUT_ARRAY);
1869		if(!empty($mybb->input['exportfolders']))
1870		{
1871			$folderlst = '';
1872			foreach($mybb->input['exportfolders'] as $key => $val)
1873			{
1874				$val = $db->escape_string($val);
1875				if($val == "all")
1876				{
1877					$folderlst = '';
1878					break;
1879				}
1880				else
1881				{
1882					if(!$folderlst)
1883					{
1884						$folderlst = " AND pm.folder IN ('$val'";
1885					}
1886					else
1887					{
1888						$folderlst .= ",'$val'";
1889					}
1890				}
1891			}
1892			if($folderlst)
1893			{
1894				$folderlst .= ")";
1895			}
1896			$wsql .= "$folderlst";
1897		}
1898		else
1899		{
1900			error($lang->error_pmnoarchivefolders);
1901		}
1902
1903		if($mybb->get_input('exportunread', MyBB::INPUT_INT) != 1)
1904		{
1905			$wsql .= " AND pm.status!='0'";
1906		}
1907	}
1908	$query = $db->query("
1909		SELECT pm.*, fu.username AS fromusername, tu.username AS tousername
1910		FROM ".TABLE_PREFIX."privatemessages pm
1911		LEFT JOIN ".TABLE_PREFIX."users fu ON (fu.uid=pm.fromid)
1912		LEFT JOIN ".TABLE_PREFIX."users tu ON (tu.uid=pm.toid)
1913		WHERE $wsql AND pm.uid='".$mybb->user['uid']."'
1914		ORDER BY pm.folder ASC, pm.dateline DESC
1915	");
1916	$numpms = $db->num_rows($query);
1917	if(!$numpms)
1918	{
1919		error($lang->error_nopmsarchive);
1920	}
1921
1922	$mybb->input['exporttype'] = $mybb->get_input('exporttype');
1923
1924	$pmsdownload = $ids = '';
1925	while($message = $db->fetch_array($query))
1926	{
1927		if($message['folder'] == 2 || $message['folder'] == 3)
1928		{ // Sent Items or Drafts Folder Check
1929			if($message['toid'])
1930			{
1931				$tofromuid = $message['toid'];
1932				if($mybb->input['exporttype'] == "txt")
1933				{
1934					$tofromusername = $message['tousername'];
1935				}
1936				else
1937				{
1938					$tofromusername = build_profile_link($message['tousername'], $tofromuid);
1939				}
1940			}
1941			else
1942			{
1943				$tofromusername = $lang->not_sent;
1944			}
1945			$tofrom = $lang->to;
1946		}
1947		else
1948		{
1949			$tofromuid = $message['fromid'];
1950			if($mybb->input['exporttype'] == "txt")
1951			{
1952				$tofromusername = $message['fromusername'];
1953			}
1954			else
1955			{
1956				$tofromusername = build_profile_link($message['fromusername'], $tofromuid);
1957			}
1958
1959			if($tofromuid == 0)
1960			{
1961				$tofromusername = $lang->mybb_engine;
1962			}
1963			$tofrom = $lang->from;
1964		}
1965
1966		if($tofromuid == 0)
1967		{
1968			$message['fromusername'] = $lang->mybb_engine;
1969		}
1970
1971		if(!$message['toid'] && $message['folder'] == 3)
1972		{
1973			$message['tousername'] = $lang->not_sent;
1974		}
1975
1976		$message['subject'] = $parser->parse_badwords($message['subject']);
1977		if($message['folder'] != "3")
1978		{
1979			$senddate = my_date($mybb->settings['dateformat'], $message['dateline'], "", false);
1980			$sendtime = my_date($mybb->settings['timeformat'], $message['dateline'], "", false);
1981			$senddate .= " $lang->at $sendtime";
1982		}
1983		else
1984		{
1985			$senddate = $lang->not_sent;
1986		}
1987
1988		if($mybb->input['exporttype'] == "html")
1989		{
1990			$parser_options = array(
1991				"allow_html" => $mybb->settings['pmsallowhtml'],
1992				"allow_mycode" => $mybb->settings['pmsallowmycode'],
1993				"allow_smilies" => 0,
1994				"allow_imgcode" => $mybb->settings['pmsallowimgcode'],
1995				"allow_videocode" => $mybb->settings['pmsallowvideocode'],
1996				"me_username" => $mybb->user['username'],
1997				"filter_badwords" => 1
1998			);
1999
2000			$message['message'] = $parser->parse_message($message['message'], $parser_options);
2001			$message['subject'] = htmlspecialchars_uni($message['subject']);
2002		}
2003
2004		if($mybb->input['exporttype'] == "txt" || $mybb->input['exporttype'] == "csv")
2005		{
2006			$message['message'] = str_replace("\r\n", "\n", $message['message']);
2007			$message['message'] = str_replace("\n", "\r\n", $message['message']);
2008		}
2009
2010		if($mybb->input['exporttype'] == "csv")
2011		{
2012			$message['message'] = my_escape_csv($message['message']);
2013			$message['subject'] = my_escape_csv($message['subject']);
2014			$message['tousername'] = my_escape_csv($message['tousername']);
2015			$message['fromusername'] = my_escape_csv($message['fromusername']);
2016		}
2017
2018		if(empty($donefolder[$message['folder']]))
2019		{
2020			reset($foldersexploded);
2021			foreach($foldersexploded as $key => $val)
2022			{
2023				$folderinfo = explode("**", $val, 2);
2024				if($folderinfo[0] == $message['folder'])
2025				{
2026					$foldername = $folderinfo[1];
2027					if($mybb->input['exporttype'] != "csv")
2028					{
2029						if($mybb->input['exporttype'] != "html")
2030						{
2031							$mybb->input['exporttype'] == "txt";
2032						}
2033						eval("\$pmsdownload .= \"".$templates->get("private_archive_".$mybb->input['exporttype']."_folderhead", 1, 0)."\";");
2034					}
2035					else
2036					{
2037						$foldername = my_escape_csv($folderinfo[1]);
2038					}
2039					$donefolder[$message['folder']] = 1;
2040				}
2041			}
2042		}
2043
2044		eval("\$pmsdownload .= \"".$templates->get("private_archive_".$mybb->input['exporttype']."_message", 1, 0)."\";");
2045		$ids .= ",'{$message['pmid']}'";
2046	}
2047
2048	if($mybb->input['exporttype'] == "html")
2049	{
2050		// Gather global stylesheet for HTML
2051		$css_tid = empty($theme['tid']) ? '' : "'". (int)$theme['tid'] ."',";
2052		$query = $db->simple_select("themestylesheets", "stylesheet", "tid in ({$css_tid}'2','1') AND name = 'global.css'", array('order_by' => 'tid', 'order_dir' => 'DESC', 'limit' => 1));
2053		$css = $db->fetch_field($query, "stylesheet");
2054	}
2055
2056	$plugins->run_hooks("private_do_export_end");
2057
2058	eval("\$archived = \"".$templates->get("private_archive_".$mybb->input['exporttype'], 1, 0)."\";");
2059	if($mybb->get_input('deletepms', MyBB::INPUT_INT) == 1)
2060	{ // delete the archived pms
2061		$db->delete_query("privatemessages", "pmid IN ('0'$ids)");
2062		// Update PM count
2063		update_pm_count();
2064	}
2065
2066	if($mybb->input['exporttype'] == "html")
2067	{
2068		$filename = "pm-archive.html";
2069		$contenttype = "text/html";
2070	}
2071	elseif($mybb->input['exporttype'] == "csv")
2072	{
2073		$filename = "pm-archive.csv";
2074		$contenttype = "application/octet-stream";
2075	}
2076	else
2077	{
2078		$filename = "pm-archive.txt";
2079		$contenttype = "text/plain";
2080	}
2081
2082	$archived = str_replace("\\\'","'",$archived);
2083	header("Content-disposition: filename=$filename");
2084	header("Content-type: ".$contenttype);
2085
2086	if($mybb->input['exporttype'] == "html")
2087	{
2088		output_page($archived);
2089	}
2090	else
2091	{
2092		echo "\xEF\xBB\xBF"; // UTF-8 BOM
2093		echo $archived;
2094	}
2095}
2096
2097if(!$mybb->input['action'])
2098{
2099	$plugins->run_hooks("private_inbox");
2100
2101	if(!$mybb->input['fid'] || !array_key_exists($mybb->input['fid'], $foldernames))
2102	{
2103		$mybb->input['fid'] = 0;
2104	}
2105
2106	$fid = (int)$mybb->input['fid'];
2107	$folder = !$fid ? 1 : $fid;
2108	$foldername = $foldernames[$fid];
2109
2110	if($folder == 2 || $folder == 3)
2111	{ // Sent Items Folder
2112		$sender = $lang->sentto;
2113	}
2114	else
2115	{
2116		$sender = $lang->sender;
2117	}
2118
2119	$mybb->input['order'] = htmlspecialchars_uni($mybb->get_input('order'));
2120	$ordersel = array('asc' => '', 'desc');
2121	switch(my_strtolower($mybb->input['order']))
2122	{
2123		case "asc":
2124			$sortordernow = "asc";
2125			$ordersel['asc'] = "selected=\"selected\"";
2126			$oppsort = $lang->desc;
2127			$oppsortnext = "desc";
2128			break;
2129		default:
2130			$sortordernow = "desc";
2131			$ordersel['desc'] = "selected=\"selected\"";
2132			$oppsort = $lang->asc;
2133			$oppsortnext = "asc";
2134			break;
2135	}
2136
2137	// Sort by which field?
2138	$sortby = htmlspecialchars_uni($mybb->get_input('sortby'));
2139	switch($mybb->get_input('sortby'))
2140	{
2141		case "subject":
2142			$sortfield = "subject";
2143			break;
2144		case "username":
2145			$sortfield = "username";
2146			break;
2147		default:
2148			$sortby = "dateline";
2149			$sortfield = "dateline";
2150			$mybb->input['sortby'] = "dateline";
2151			break;
2152	}
2153	$orderarrow = $sortsel = array('subject' => '', 'username' => '', 'dateline' => '');
2154	$sortsel[$sortby] = "selected=\"selected\"";
2155
2156	eval("\$orderarrow['$sortby'] = \"".$templates->get("private_orderarrow")."\";");
2157
2158	// Do Multi Pages
2159	$selective = "";
2160	if($fid == 1)
2161	{
2162		$selective = " AND status='0'";
2163	}
2164
2165	$query = $db->simple_select("privatemessages", "COUNT(*) AS total", "uid='".$mybb->user['uid']."' AND folder='$folder'$selective");
2166	$pmscount = $db->fetch_field($query, "total");
2167
2168	if(!$mybb->settings['threadsperpage'] || (int)$mybb->settings['threadsperpage'] < 1)
2169	{
2170		$mybb->settings['threadsperpage'] = 20;
2171	}
2172
2173	$perpage = $mybb->settings['threadsperpage'];
2174	$page = $mybb->get_input('page', MyBB::INPUT_INT);
2175
2176	if($page > 0)
2177	{
2178		$start = ($page-1) *$perpage;
2179		$pages = ceil($pmscount / $perpage);
2180		if($page > $pages)
2181		{
2182			$start = 0;
2183			$page = 1;
2184		}
2185	}
2186	else
2187	{
2188		$start = 0;
2189		$page = 1;
2190	}
2191
2192	$end = $start + $perpage;
2193	$lower = $start+1;
2194	$upper = $end;
2195
2196	if($upper > $pmscount)
2197	{
2198		$upper = $pmscount;
2199	}
2200
2201	if($mybb->input['order'] || ($sortby && $sortby != "dateline"))
2202	{
2203		$page_url = "private.php?fid={$fid}&sortby={$sortby}&order={$sortordernow}";
2204	}
2205	else
2206	{
2207		$page_url = "private.php?fid={$fid}";
2208	}
2209
2210	$multipage = multipage($pmscount, $perpage, $page, $page_url);
2211	$selective = $messagelist = '';
2212
2213	$icon_cache = $cache->read("posticons");
2214
2215	// Cache users in multiple recipients for sent & drafts folder
2216	if($folder == 2 || $folder == 3)
2217	{
2218		if($sortfield == "username")
2219		{
2220			$u = "u.";
2221		}
2222		else
2223		{
2224			$u = "pm.";
2225		}
2226
2227		// Get all recipients into an array
2228		$cached_users = $get_users = array();
2229		$users_query = $db->query("
2230			SELECT pm.recipients
2231			FROM ".TABLE_PREFIX."privatemessages pm
2232			LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=pm.toid)
2233			WHERE pm.folder='{$folder}' AND pm.uid='{$mybb->user['uid']}'
2234			ORDER BY {$u}{$sortfield} {$sortordernow}
2235			LIMIT {$start}, {$perpage}
2236		");
2237		while($row = $db->fetch_array($users_query))
2238		{
2239			$recipients = my_unserialize($row['recipients']);
2240			if(is_array($recipients['to']) && count($recipients['to']))
2241			{
2242				$get_users = array_merge($get_users, $recipients['to']);
2243			}
2244
2245			if(isset($recipients['bcc']) && is_array($recipients['bcc']) && count($recipients['bcc']))
2246			{
2247				$get_users = array_merge($get_users, $recipients['bcc']);
2248			}
2249		}
2250
2251		$get_users = implode(',', array_unique($get_users));
2252
2253		// Grab info
2254		if($get_users)
2255		{
2256			$users_query = $db->simple_select("users", "uid, username, usergroup, displaygroup", "uid IN ({$get_users})");
2257			while($user = $db->fetch_array($users_query))
2258			{
2259				$cached_users[$user['uid']] = $user;
2260			}
2261		}
2262	}
2263
2264	if($folder == 2 || $folder == 3)
2265	{
2266		if($sortfield == "username")
2267		{
2268			$pm = "tu.";
2269		}
2270		else
2271		{
2272			$pm = "pm.";
2273		}
2274	}
2275	else
2276	{
2277		if($fid == 1)
2278		{
2279			$selective = " AND pm.status='0'";
2280		}
2281
2282		if($sortfield == "username")
2283		{
2284			$pm = "fu.";
2285		}
2286		else
2287		{
2288			$pm = "pm.";
2289		}
2290	}
2291
2292	$query = $db->query("
2293		SELECT pm.*, fu.username AS fromusername, tu.username as tousername
2294		FROM ".TABLE_PREFIX."privatemessages pm
2295		LEFT JOIN ".TABLE_PREFIX."users fu ON (fu.uid=pm.fromid)
2296		LEFT JOIN ".TABLE_PREFIX."users tu ON (tu.uid=pm.toid)
2297		WHERE pm.folder='$folder' AND pm.uid='".$mybb->user['uid']."'{$selective}
2298		ORDER BY {$pm}{$sortfield} {$sortordernow}
2299		LIMIT $start, $perpage
2300	");
2301
2302	if($db->num_rows($query) > 0)
2303	{
2304		$bgcolor = alt_trow(true);
2305		while($message = $db->fetch_array($query))
2306		{
2307			$msgalt = $msgstatus = '';
2308
2309			// Determine Folder Icon
2310			if($message['status'] == 0)
2311			{
2312				$msgstatus = 'new_pm';
2313				$msgalt = $lang->new_pm;
2314			}
2315			else if($message['status'] == 1)
2316			{
2317				$msgstatus = 'old_pm';
2318				$msgalt = $lang->old_pm;
2319			}
2320			else if($message['status'] == 3)
2321			{
2322				$msgstatus = 're_pm';
2323				$msgalt = $lang->reply_pm;
2324			}
2325			else if($message['status'] == 4)
2326			{
2327				$msgstatus = 'fw_pm';
2328				$msgalt = $lang->fwd_pm;
2329			}
2330
2331			$tofromuid = 0;
2332			if($folder == 2 || $folder == 3)
2333			{ // Sent Items or Drafts Folder Check
2334				$recipients = my_unserialize($message['recipients']);
2335				$to_users = $bcc_users = '';
2336				if(isset($recipients['to']) && count($recipients['to']) > 1 || (isset($recipients['to']) && count($recipients['to']) == 1 && isset($recipients['bcc']) && count($recipients['bcc']) > 0))
2337				{
2338					foreach($recipients['to'] as $uid)
2339					{
2340						$profilelink = get_profile_link($uid);
2341						$user = $cached_users[$uid];
2342						$user['username'] = htmlspecialchars_uni($user['username']);
2343						$username = format_name($user['username'], $user['usergroup'], $user['displaygroup']);
2344						if(!$user['username'])
2345						{
2346							$username = $lang->na;
2347						}
2348						eval("\$to_users .= \"".$templates->get("private_multiple_recipients_user")."\";");
2349					}
2350					if(isset($recipients['bcc']) && is_array($recipients['bcc']) && count($recipients['bcc']))
2351					{
2352						eval("\$bcc_users = \"".$templates->get("private_multiple_recipients_bcc")."\";");
2353						foreach($recipients['bcc'] as $uid)
2354						{
2355							$profilelink = get_profile_link($uid);
2356							$user = $cached_users[$uid];
2357							$user['username'] = htmlspecialchars_uni($user['username']);
2358							$username = format_name($user['username'], $user['usergroup'], $user['displaygroup']);
2359							if(!$user['username'])
2360							{
2361								$username = $lang->na;
2362							}
2363							eval("\$bcc_users .= \"".$templates->get("private_multiple_recipients_user")."\";");
2364						}
2365					}
2366
2367					eval("\$tofromusername = \"".$templates->get("private_multiple_recipients")."\";");
2368				}
2369				else if($message['toid'])
2370				{
2371					$tofromusername = htmlspecialchars_uni($message['tousername']);
2372					$tofromuid = $message['toid'];
2373				}
2374				else
2375				{
2376					$tofromusername = $lang->not_sent;
2377				}
2378			}
2379			else
2380			{
2381				$tofromusername = htmlspecialchars_uni($message['fromusername']);
2382				$tofromuid = $message['fromid'];
2383				if($tofromuid == 0)
2384				{
2385					$tofromusername = $lang->mybb_engine;
2386				}
2387
2388				if(!$tofromusername)
2389				{
2390					$tofromuid = 0;
2391					$tofromusername = $lang->na;
2392				}
2393			}
2394
2395			$tofromusername = build_profile_link($tofromusername, $tofromuid);
2396
2397			if($mybb->usergroup['candenypmreceipts'] == 1 && $message['receipt'] == '1' && $message['folder'] != '3' && $message['folder'] != 2)
2398			{
2399				eval("\$denyreceipt = \"".$templates->get("private_messagebit_denyreceipt")."\";");
2400			}
2401			else
2402			{
2403				$denyreceipt = '';
2404			}
2405
2406			if($message['icon'] > 0 && $icon_cache[$message['icon']])
2407			{
2408				$icon = $icon_cache[$message['icon']];
2409				$icon['path'] = str_replace("{theme}", $theme['imgdir'], $icon['path']);
2410				$icon['path'] = htmlspecialchars_uni($icon['path']);
2411				$icon['name'] = htmlspecialchars_uni($icon['name']);
2412				eval("\$icon = \"".$templates->get("private_messagebit_icon")."\";");
2413			}
2414			else
2415			{
2416				$icon = '&#009;';
2417			}
2418
2419			if(!trim($message['subject']))
2420			{
2421				$message['subject'] = $lang->pm_no_subject;
2422			}
2423
2424			$message['subject'] = htmlspecialchars_uni($parser->parse_badwords($message['subject']));
2425			if($message['folder'] != "3")
2426			{
2427				$senddate = my_date('relative', $message['dateline']);
2428			}
2429			else
2430			{
2431				$senddate = $lang->not_sent;
2432			}
2433
2434			$plugins->run_hooks("private_message");
2435
2436			eval("\$messagelist .= \"".$templates->get("private_messagebit")."\";");
2437			$bgcolor = alt_trow();
2438		}
2439	}
2440	else
2441	{
2442		eval("\$messagelist .= \"".$templates->get("private_nomessages")."\";");
2443	}
2444
2445	$pmspacebar = '';
2446	if($mybb->usergroup['pmquota'] != 0)
2447	{
2448		$query = $db->simple_select("privatemessages", "COUNT(*) AS total", "uid='".$mybb->user['uid']."'");
2449		$pmscount = $db->fetch_array($query);
2450		if($pmscount['total'] == 0)
2451		{
2452			$spaceused = 0;
2453		}
2454		else
2455		{
2456			$spaceused = $pmscount['total'] / $mybb->usergroup['pmquota'] * 100;
2457		}
2458		$spaceused2 = 100 - $spaceused;
2459		$belowhalf = $overhalf = '';
2460		if($spaceused <= "50")
2461		{
2462			$spaceused_severity = "low";
2463			$belowhalf = round($spaceused, 0)."%";
2464			if((int)$belowhalf > 100)
2465			{
2466				$belowhalf = "100%";
2467			}
2468		}
2469		else
2470		{
2471			if($spaceused <= "75")
2472			{
2473				$spaceused_severity = "medium";
2474			}
2475
2476			else
2477			{
2478				$spaceused_severity = "high";
2479			}
2480
2481			$overhalf = round($spaceused, 0)."%";
2482			if((int)$overhalf > 100)
2483			{
2484				$overhalf = "100%";
2485			}
2486		}
2487
2488		if($spaceused > 100)
2489		{
2490			$spaceused = 100;
2491			$spaceused2 = 0;
2492		}
2493
2494		eval("\$pmspacebar = \"".$templates->get("private_pmspace")."\";");
2495	}
2496
2497	$composelink = '';
2498	if($mybb->usergroup['cansendpms'] == 1)
2499	{
2500		eval("\$composelink = \"".$templates->get("private_composelink")."\";");
2501	}
2502
2503	$emptyexportlink = '';
2504	if($mybb->user['totalpms'] > 0)
2505	{
2506		eval("\$emptyexportlink = \"".$templates->get("private_emptyexportlink")."\";");
2507	}
2508
2509	$limitwarning = '';
2510	if($mybb->usergroup['pmquota'] != 0 && $pmscount['total'] >= $mybb->usergroup['pmquota'])
2511	{
2512		eval("\$limitwarning = \"".$templates->get("private_limitwarning")."\";");
2513	}
2514
2515	$plugins->run_hooks("private_end");
2516
2517	eval("\$folder = \"".$templates->get("private")."\";");
2518	output_page($folder);
2519}
2520