PageRenderTime 66ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/sources/controllers/PersonalMessage.controller.php

https://github.com/Arantor/Elkarte
PHP | 2770 lines | 2052 code | 346 blank | 372 comment | 492 complexity | 3a25487873b7ba521b145170ac6f87a0 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file is mainly meant for controlling the actions related to personal
  16. * messages. It allows viewing, sending, deleting, and marking personal
  17. * messages. For compatibility reasons, they are often called "instant messages".
  18. *
  19. */
  20. if (!defined('ELKARTE'))
  21. die('No access...');
  22. /**
  23. * This is the main function of personal messages, called before the action handler.
  24. * It should set the context, load templates and language file(s), as necessary
  25. * for the function that will be called.
  26. *
  27. * @todo this should be a (pre)dispatcher.
  28. */
  29. function action_pm()
  30. {
  31. global $txt, $scripturl, $context, $user_info, $user_settings, $smcFunc, $modSettings;
  32. // No guests!
  33. is_not_guest();
  34. // You're not supposed to be here at all, if you can't even read PMs.
  35. isAllowedTo('pm_read');
  36. // This file contains the our PM functions such as mark, send, delete
  37. require_once(SUBSDIR . '/PersonalMessage.subs.php');
  38. loadLanguage('PersonalMessage+Drafts');
  39. loadJavascriptFile(array('PersonalMessage.js', 'suggest.js'));
  40. if (!isset($_REQUEST['xml']))
  41. loadTemplate('PersonalMessage');
  42. // Load up the members maximum message capacity.
  43. loadMessageLimit();
  44. // Prepare the context for the capacity bar.
  45. if (!empty($context['message_limit']))
  46. {
  47. $bar = ($user_info['messages'] * 100) / $context['message_limit'];
  48. $context['limit_bar'] = array(
  49. 'messages' => $user_info['messages'],
  50. 'allowed' => $context['message_limit'],
  51. 'percent' => $bar,
  52. 'bar' => min(100, (int) $bar),
  53. 'text' => sprintf($txt['pm_currently_using'], $user_info['messages'], round($bar, 1)),
  54. );
  55. }
  56. // a previous message was sent successfully? show a small indication.
  57. if (isset($_GET['done']) && ($_GET['done'] == 'sent'))
  58. $context['pm_sent'] = true;
  59. // Now we have the labels, and assuming we have unsorted mail, apply our rules!
  60. if ($user_settings['new_pm'])
  61. {
  62. $context['labels'] = $user_settings['message_labels'] == '' ? array() : explode(',', $user_settings['message_labels']);
  63. foreach ($context['labels'] as $id_label => $label_name)
  64. $context['labels'][(int) $id_label] = array(
  65. 'id' => $id_label,
  66. 'name' => trim($label_name),
  67. 'messages' => 0,
  68. 'unread_messages' => 0,
  69. );
  70. $context['labels'][-1] = array(
  71. 'id' => -1,
  72. 'name' => $txt['pm_msg_label_inbox'],
  73. 'messages' => 0,
  74. 'unread_messages' => 0,
  75. );
  76. applyRules();
  77. updateMemberData($user_info['id'], array('new_pm' => 0));
  78. $smcFunc['db_query']('', '
  79. UPDATE {db_prefix}pm_recipients
  80. SET is_new = {int:not_new}
  81. WHERE id_member = {int:current_member}',
  82. array(
  83. 'current_member' => $user_info['id'],
  84. 'not_new' => 0,
  85. )
  86. );
  87. }
  88. // Load the label data.
  89. if ($user_settings['new_pm'] || ($context['labels'] = cache_get_data('labelCounts:' . $user_info['id'], 720)) === null)
  90. {
  91. $context['labels'] = $user_settings['message_labels'] == '' ? array() : explode(',', $user_settings['message_labels']);
  92. foreach ($context['labels'] as $id_label => $label_name)
  93. {
  94. $context['labels'][(int) $id_label] = array(
  95. 'id' => $id_label,
  96. 'name' => trim($label_name),
  97. 'messages' => 0,
  98. 'unread_messages' => 0,
  99. );
  100. }
  101. $context['labels'][-1] = array(
  102. 'id' => -1,
  103. 'name' => $txt['pm_msg_label_inbox'],
  104. 'messages' => 0,
  105. 'unread_messages' => 0,
  106. );
  107. loadPMLabels();
  108. }
  109. // This determines if we have more labels than just the standard inbox.
  110. $context['currently_using_labels'] = count($context['labels']) > 1 ? 1 : 0;
  111. // Some stuff for the labels...
  112. $context['current_label_id'] = isset($_REQUEST['l']) && isset($context['labels'][(int) $_REQUEST['l']]) ? (int) $_REQUEST['l'] : -1;
  113. $context['current_label'] = &$context['labels'][(int) $context['current_label_id']]['name'];
  114. $context['folder'] = !isset($_REQUEST['f']) || $_REQUEST['f'] != 'sent' ? 'inbox' : 'sent';
  115. // This is convenient. Do you know how annoying it is to do this every time?!
  116. $context['current_label_redirect'] = 'action=pm;f=' . $context['folder'] . (isset($_GET['start']) ? ';start=' . $_GET['start'] : '') . (isset($_REQUEST['l']) ? ';l=' . $_REQUEST['l'] : '');
  117. $context['can_issue_warning'] = in_array('w', $context['admin_features']) && allowedTo('issue_warning') && $modSettings['warning_settings'][0] == 1;
  118. // Are PM drafts enabled?
  119. $context['drafts_pm_save'] = !empty($modSettings['drafts_enabled']) && !empty($modSettings['drafts_pm_enabled']) && allowedTo('pm_draft');
  120. $context['drafts_autosave'] = !empty($context['drafts_pm_save']) && !empty($modSettings['drafts_autosave_enabled']) && allowedTo('pm_autosave_draft');
  121. // Build the linktree for all the actions...
  122. $context['linktree'][] = array(
  123. 'url' => $scripturl . '?action=pm',
  124. 'name' => $txt['personal_messages']
  125. );
  126. // Preferences...
  127. $context['display_mode'] = $user_settings['pm_prefs'] & 3;
  128. // Finally all the things we know how to do
  129. $subActions = array(
  130. 'manlabels' => 'action_messagelabels',
  131. 'manrules' => 'action_messagerules',
  132. 'pmactions' => 'action_messageactions',
  133. 'prune' => 'action_messageprune',
  134. 'removeall' => 'action_removemessage',
  135. 'removeall2' => 'action_removemessage2',
  136. 'report' => 'action_reportmessage',
  137. 'search' => array('Search.controller.php','MessageSearch'),
  138. 'search2' => array('Search.controller.php','MessageSearch2'),
  139. 'send' => 'action_sendmessage',
  140. 'send2' => 'action_sendmessage2',
  141. 'settings' => 'action_messagesettings',
  142. 'showpmdrafts' => 'action_messagedrafts',
  143. );
  144. // Known action, go to it, otherwise the inbox for you
  145. if (!isset($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
  146. action_messagefolder();
  147. else
  148. {
  149. if (!isset($_REQUEST['xml']))
  150. messageIndexBar($_REQUEST['sa']);
  151. // So it was set - let's go to that action.
  152. if (is_array($subActions[$_REQUEST['sa']]))
  153. {
  154. require_once(CONTROLLERDIR . '/' . $subActions[$_REQUEST['sa']][0]);
  155. $subActions[$_REQUEST['sa']][1]();
  156. }
  157. else
  158. $subActions[$_REQUEST['sa']]();
  159. }
  160. }
  161. /**
  162. * A menu to easily access different areas of the PM section
  163. *
  164. * @param string $area
  165. */
  166. function messageIndexBar($area)
  167. {
  168. global $txt, $context, $scripturl, $sc, $modSettings, $settings, $user_info, $options;
  169. $pm_areas = array(
  170. 'folders' => array(
  171. 'title' => $txt['pm_messages'],
  172. 'areas' => array(
  173. 'send' => array(
  174. 'label' => $txt['new_message'],
  175. 'custom_url' => $scripturl . '?action=pm;sa=send',
  176. 'permission' => allowedTo('pm_send'),
  177. ),
  178. 'inbox' => array(
  179. 'label' => $txt['inbox'],
  180. 'custom_url' => $scripturl . '?action=pm',
  181. ),
  182. 'sent' => array(
  183. 'label' => $txt['sent_items'],
  184. 'custom_url' => $scripturl . '?action=pm;f=sent',
  185. ),
  186. 'drafts' => array(
  187. 'label' => $txt['drafts_show'],
  188. 'custom_url' => $scripturl . '?action=pm;sa=showpmdrafts',
  189. 'permission' => allowedTo('pm_draft'),
  190. 'enabled' => !empty($modSettings['drafts_enabled']) && !empty($modSettings['drafts_pm_enabled']),
  191. ),
  192. ),
  193. ),
  194. 'labels' => array(
  195. 'title' => $txt['pm_labels'],
  196. 'areas' => array(),
  197. ),
  198. 'actions' => array(
  199. 'title' => $txt['pm_actions'],
  200. 'areas' => array(
  201. 'search' => array(
  202. 'label' => $txt['pm_search_bar_title'],
  203. 'custom_url' => $scripturl . '?action=pm;sa=search',
  204. ),
  205. 'prune' => array(
  206. 'label' => $txt['pm_prune'],
  207. 'custom_url' => $scripturl . '?action=pm;sa=prune'
  208. ),
  209. ),
  210. ),
  211. 'pref' => array(
  212. 'title' => $txt['pm_preferences'],
  213. 'areas' => array(
  214. 'manlabels' => array(
  215. 'label' => $txt['pm_manage_labels'],
  216. 'custom_url' => $scripturl . '?action=pm;sa=manlabels',
  217. ),
  218. 'manrules' => array(
  219. 'label' => $txt['pm_manage_rules'],
  220. 'custom_url' => $scripturl . '?action=pm;sa=manrules',
  221. ),
  222. 'settings' => array(
  223. 'label' => $txt['pm_settings'],
  224. 'custom_url' => $scripturl . '?action=pm;sa=settings',
  225. ),
  226. ),
  227. ),
  228. );
  229. // Handle labels.
  230. if (empty($context['currently_using_labels']))
  231. unset($pm_areas['labels']);
  232. else
  233. {
  234. // Note we send labels by id as it will have less problems in the querystring.
  235. $unread_in_labels = 0;
  236. foreach ($context['labels'] as $label)
  237. {
  238. if ($label['id'] == -1)
  239. continue;
  240. // Count the amount of unread items in labels.
  241. $unread_in_labels += $label['unread_messages'];
  242. // Add the label to the menu.
  243. $pm_areas['labels']['areas']['label' . $label['id']] = array(
  244. 'label' => $label['name'] . (!empty($label['unread_messages']) ? ' (<strong>' . $label['unread_messages'] . '</strong>)' : ''),
  245. 'custom_url' => $scripturl . '?action=pm;l=' . $label['id'],
  246. 'unread_messages' => $label['unread_messages'],
  247. 'messages' => $label['messages'],
  248. );
  249. }
  250. if (!empty($unread_in_labels))
  251. $pm_areas['labels']['title'] .= ' (' . $unread_in_labels . ')';
  252. }
  253. $pm_areas['folders']['areas']['inbox']['unread_messages'] = &$context['labels'][-1]['unread_messages'];
  254. $pm_areas['folders']['areas']['inbox']['messages'] = &$context['labels'][-1]['messages'];
  255. // If we have unread messages, make note of the number in the menus
  256. if (!empty($context['labels'][-1]['unread_messages']))
  257. {
  258. $pm_areas['folders']['areas']['inbox']['label'] .= ' (<strong>' . $context['labels'][-1]['unread_messages'] . '</strong>)';
  259. $pm_areas['folders']['title'] .= ' (' . $context['labels'][-1]['unread_messages'] . ')';
  260. }
  261. // Do we have a limit on the amount of messages we can keep?
  262. if (!empty($context['message_limit']))
  263. {
  264. $bar = round(($user_info['messages'] * 100) / $context['message_limit'], 1);
  265. $context['limit_bar'] = array(
  266. 'messages' => $user_info['messages'],
  267. 'allowed' => $context['message_limit'],
  268. 'percent' => $bar,
  269. 'bar' => $bar > 100 ? 100 : (int) $bar,
  270. 'text' => sprintf($txt['pm_currently_using'], $user_info['messages'], $bar)
  271. );
  272. }
  273. require_once(SUBSDIR . '/Menu.subs.php');
  274. // What page is this, again?
  275. $current_page = $scripturl . '?action=pm' . (!empty($_REQUEST['sa']) ? ';sa=' . $_REQUEST['sa'] : '') . (!empty($context['folder']) ? ';f=' . $context['folder'] : '') . (!empty($context['current_label_id']) ? ';l=' . $context['current_label_id'] : '');
  276. // Set a few options for the menu.
  277. $menuOptions = array(
  278. 'current_area' => $area,
  279. 'disable_url_session_check' => true,
  280. );
  281. // Actually create the menu!
  282. $pm_include_data = createMenu($pm_areas, $menuOptions);
  283. unset($pm_areas);
  284. // No menu means no access.
  285. if (!$pm_include_data && (!$user_info['is_guest'] || validateSession()))
  286. fatal_lang_error('no_access', false);
  287. // Make a note of the Unique ID for this menu.
  288. $context['pm_menu_id'] = $context['max_menu_id'];
  289. $context['pm_menu_name'] = 'menu_data_' . $context['pm_menu_id'];
  290. // Set the selected item.
  291. $current_area = $pm_include_data['current_area'];
  292. $context['menu_item_selected'] = $current_area;
  293. // Set the template for this area and add the profile layer.
  294. if (!isset($_REQUEST['xml']))
  295. $context['template_layers'][] = 'pm';
  296. }
  297. /**
  298. * A folder, ie. inbox/sent etc.
  299. */
  300. function action_messagefolder()
  301. {
  302. global $txt, $scripturl, $modSettings, $context, $subjects_request;
  303. global $messages_request, $user_info, $recipients, $options, $smcFunc, $memberContext, $user_settings;
  304. // Changing view?
  305. if (isset($_GET['view']))
  306. {
  307. $context['display_mode'] = $context['display_mode'] > 1 ? 0 : $context['display_mode'] + 1;
  308. updateMemberData($user_info['id'], array('pm_prefs' => ($user_settings['pm_prefs'] & 252) | $context['display_mode']));
  309. }
  310. // Make sure the starting location is valid.
  311. $start = '';
  312. if (isset($_GET['start']) && $_GET['start'] != 'new')
  313. $start = (int) $_GET['start'];
  314. elseif (!isset($_GET['start']) && !empty($options['view_newest_pm_first']))
  315. $start = 0;
  316. else
  317. $start = 'new';
  318. // Set up some basic theme stuff.
  319. $context['from_or_to'] = $context['folder'] != 'sent' ? 'from' : 'to';
  320. $context['get_pmessage'] = 'prepareMessageContext';
  321. $context['signature_enabled'] = substr($modSettings['signature_settings'], 0, 1) == 1;
  322. $context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
  323. $labelQuery = $context['folder'] != 'sent' ? '
  324. AND FIND_IN_SET(' . $context['current_label_id'] . ', pmr.labels) != 0' : '';
  325. // Set the index bar correct!
  326. messageIndexBar($context['current_label_id'] == -1 ? $context['folder'] : 'label' . $context['current_label_id']);
  327. // They didn't pick a sort, use the forum default.
  328. if (!isset($_GET['sort']))
  329. {
  330. $sort_by = 'date';
  331. $descending = !empty($options['view_newest_pm_first']);
  332. }
  333. // Otherwise use the defaults: ascending, by date.
  334. else
  335. {
  336. $sort_by = $_GET['sort'];
  337. $descending = isset($_GET['desc']);
  338. }
  339. // Set our sort by query
  340. switch ($sort_by)
  341. {
  342. case 'date':
  343. $sort_by_query = 'pm.id_pm';
  344. case 'name':
  345. $sort_by_query = 'IFNULL(mem.real_name, \'\')';
  346. case 'subject':
  347. $sort_by_query = 'pm.subject';
  348. default:
  349. $sort_by_query = 'pm.id_pm';
  350. }
  351. // Set the text to resemble the current folder.
  352. $pmbox = $context['folder'] != 'sent' ? $txt['inbox'] : $txt['sent_items'];
  353. $txt['delete_all'] = str_replace('PMBOX', $pmbox, $txt['delete_all']);
  354. // Now, build the link tree!
  355. if ($context['current_label_id'] == -1)
  356. $context['linktree'][] = array(
  357. 'url' => $scripturl . '?action=pm;f=' . $context['folder'],
  358. 'name' => $pmbox
  359. );
  360. // Build it further for a label.
  361. if ($context['current_label_id'] != -1)
  362. $context['linktree'][] = array(
  363. 'url' => $scripturl . '?action=pm;f=' . $context['folder'] . ';l=' . $context['current_label_id'],
  364. 'name' => $txt['pm_current_label'] . ': ' . $context['current_label']
  365. );
  366. // Figure out how many messages there are.
  367. $max_messages = getPMCount(false, null, $labelQuery);
  368. // Only show the button if there are messages to delete.
  369. $context['show_delete'] = $max_messages > 0;
  370. // Start on the last page.
  371. if (!is_numeric($start) || $start >= $max_messages)
  372. $start = ($max_messages - 1) - (($max_messages - 1) % $modSettings['defaultMaxMessages']);
  373. elseif ($start < 0)
  374. $start = 0;
  375. // ... but wait - what if we want to start from a specific message?
  376. if (isset($_GET['pmid']))
  377. {
  378. $pmID = (int) $_GET['pmid'];
  379. // Make sure you have access to this PM.
  380. if (!isAccessiblePM($pmID, $context['folder'] == 'sent' ? 'outbox' : 'inbox'))
  381. fatal_lang_error('no_access', false);
  382. $context['current_pm'] = $pmID;
  383. // With only one page of PM's we're gonna want page 1.
  384. if ($max_messages <= $modSettings['defaultMaxMessages'])
  385. $start = 0;
  386. // If we pass kstart we assume we're in the right place.
  387. elseif (!isset($_GET['kstart']))
  388. {
  389. $start = getPMCount($descending, $pmID, $labelQuery);
  390. // To stop the page index's being abnormal, start the page on the page the message would normally be located on...
  391. $start = $modSettings['defaultMaxMessages'] * (int) ($start / $modSettings['defaultMaxMessages']);
  392. }
  393. }
  394. // Sanitize and validate pmsg variable if set.
  395. if (isset($_GET['pmsg']))
  396. {
  397. $pmsg = (int) $_GET['pmsg'];
  398. if (!isAccessiblePM($pmsg, $context['folder'] == 'sent' ? 'outbox' : 'inbox'))
  399. fatal_lang_error('no_access', false);
  400. }
  401. // Determine the navigation context (especially useful for the wireless template).
  402. $context['links'] = array(
  403. 'first' => $start >= $modSettings['defaultMaxMessages'] ? $scripturl . '?action=pm;start=0' : '',
  404. 'prev' => $start >= $modSettings['defaultMaxMessages'] ? $scripturl . '?action=pm;start=' . ($start - $modSettings['defaultMaxMessages']) : '',
  405. 'next' => $start + $modSettings['defaultMaxMessages'] < $max_messages ? $scripturl . '?action=pm;start=' . ($start + $modSettings['defaultMaxMessages']) : '',
  406. 'last' => $start + $modSettings['defaultMaxMessages'] < $max_messages ? $scripturl . '?action=pm;start=' . (floor(($max_messages - 1) / $modSettings['defaultMaxMessages']) * $modSettings['defaultMaxMessages']) : '',
  407. 'up' => $scripturl,
  408. );
  409. $context['page_info'] = array(
  410. 'current_page' => $start / $modSettings['defaultMaxMessages'] + 1,
  411. 'num_pages' => floor(($max_messages - 1) / $modSettings['defaultMaxMessages']) + 1
  412. );
  413. // First work out what messages we need to see - if grouped is a little trickier...
  414. if ($context['display_mode'] == 2)
  415. {
  416. // On a non-default sort due to PostgreSQL we have to do a harder sort.
  417. if ($smcFunc['db_title'] == 'PostgreSQL' && $sort_by_query != 'pm.id_pm')
  418. {
  419. $sub_request = $smcFunc['db_query']('', '
  420. SELECT MAX({raw:sort}) AS sort_param, pm.id_pm_head
  421. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? ($sort_by == 'name' ? '
  422. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  423. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  424. AND pmr.id_member = {int:current_member}
  425. AND pmr.deleted = {int:not_deleted}
  426. ' . $labelQuery . ')') . ($sort_by == 'name' ? ( '
  427. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:id_member})') : '') . '
  428. WHERE ' . ($context['folder'] == 'sent' ? 'pm.id_member_from = {int:current_member}
  429. AND pm.deleted_by_sender = {int:not_deleted}' : '1=1') . (empty($pmsg) ? '' : '
  430. AND pm.id_pm = {int:id_pm}') . '
  431. GROUP BY pm.id_pm_head
  432. ORDER BY sort_param' . ($descending ? ' DESC' : ' ASC') . (empty($pmsg) ? '
  433. LIMIT ' . $start . ', ' . $modSettings['defaultMaxMessages'] : ''),
  434. array(
  435. 'current_member' => $user_info['id'],
  436. 'not_deleted' => 0,
  437. 'id_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  438. 'id_pm' => isset($pmsg) ? $pmsg : '0',
  439. 'sort' => $sort_by_query,
  440. )
  441. );
  442. $sub_pms = array();
  443. while ($row = $smcFunc['db_fetch_assoc']($sub_request))
  444. $sub_pms[$row['id_pm_head']] = $row['sort_param'];
  445. $smcFunc['db_free_result']($sub_request);
  446. $request = $smcFunc['db_query']('', '
  447. SELECT pm.id_pm AS id_pm, pm.id_pm_head
  448. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? ($sort_by == 'name' ? '
  449. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  450. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  451. AND pmr.id_member = {int:current_member}
  452. AND pmr.deleted = {int:not_deleted}
  453. ' . $labelQuery . ')') . ($sort_by == 'name' ? ( '
  454. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:id_member})') : '') . '
  455. WHERE ' . (empty($sub_pms) ? '0=1' : 'pm.id_pm IN ({array_int:pm_list})') . '
  456. ORDER BY ' . ($sort_by_query == 'pm.id_pm' && $context['folder'] != 'sent' ? 'id_pm' : '{raw:sort}') . ($descending ? ' DESC' : ' ASC') . (empty($pmsg) ? '
  457. LIMIT ' . $start . ', ' . $modSettings['defaultMaxMessages'] : ''),
  458. array(
  459. 'current_member' => $user_info['id'],
  460. 'pm_list' => array_keys($sub_pms),
  461. 'not_deleted' => 0,
  462. 'sort' => $sort_by_query,
  463. 'id_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  464. )
  465. );
  466. }
  467. else
  468. {
  469. $request = $smcFunc['db_query']('pm_conversation_list', '
  470. SELECT MAX(pm.id_pm) AS id_pm, pm.id_pm_head
  471. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? ($sort_by == 'name' ? '
  472. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  473. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  474. AND pmr.id_member = {int:current_member}
  475. AND pmr.deleted = {int:deleted_by}
  476. ' . $labelQuery . ')') . ($sort_by == 'name' ? ( '
  477. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:pm_member})') : '') . '
  478. WHERE ' . ($context['folder'] == 'sent' ? 'pm.id_member_from = {int:current_member}
  479. AND pm.deleted_by_sender = {int:deleted_by}' : '1=1') . (empty($pmsg) ? '' : '
  480. AND pm.id_pm = {int:pmsg}') . '
  481. GROUP BY pm.id_pm_head
  482. ORDER BY ' . ($sort_by_query == 'pm.id_pm' && $context['folder'] != 'sent' ? 'id_pm' : '{raw:sort}') . ($descending ? ' DESC' : ' ASC') . (isset($pmsg) ? '
  483. LIMIT ' . $start . ', ' . $modSettings['defaultMaxMessages'] : ''),
  484. array(
  485. 'current_member' => $user_info['id'],
  486. 'deleted_by' => 0,
  487. 'sort' => $sort_by_query,
  488. 'pm_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  489. 'pmsg' => isset($pmsg) ? (int) $pmsg : 0,
  490. )
  491. );
  492. }
  493. }
  494. // This is kinda simple!
  495. else
  496. {
  497. // @todo SLOW This query uses a filesort. (inbox only.)
  498. $request = $smcFunc['db_query']('', '
  499. SELECT pm.id_pm, pm.id_pm_head, pm.id_member_from
  500. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? '' . ($sort_by == 'name' ? '
  501. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') : '
  502. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm
  503. AND pmr.id_member = {int:current_member}
  504. AND pmr.deleted = {int:is_deleted}
  505. ' . $labelQuery . ')') . ($sort_by == 'name' ? ( '
  506. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:pm_member})') : '') . '
  507. WHERE ' . ($context['folder'] == 'sent' ? 'pm.id_member_from = {raw:current_member}
  508. AND pm.deleted_by_sender = {int:is_deleted}' : '1=1') . (empty($pmsg) ? '' : '
  509. AND pm.id_pm = {int:pmsg}') . '
  510. ORDER BY ' . ($sort_by_query == 'pm.id_pm' && $context['folder'] != 'sent' ? 'pmr.id_pm' : '{raw:sort}') . ($descending ? ' DESC' : ' ASC') . (isset($pmsg) ? '
  511. LIMIT ' . $start . ', ' . $modSettings['defaultMaxMessages'] : ''),
  512. array(
  513. 'current_member' => $user_info['id'],
  514. 'is_deleted' => 0,
  515. 'sort' => $sort_by_query,
  516. 'pm_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  517. 'pmsg' => isset($pmsg) ? (int) $pmsg : 0,
  518. )
  519. );
  520. }
  521. // Load the id_pms and initialize recipients.
  522. $pms = array();
  523. $lastData = array();
  524. $posters = $context['folder'] == 'sent' ? array($user_info['id']) : array();
  525. $recipients = array();
  526. while ($row = $smcFunc['db_fetch_assoc']($request))
  527. {
  528. if (!isset($recipients[$row['id_pm']]))
  529. {
  530. if (isset($row['id_member_from']))
  531. $posters[$row['id_pm']] = $row['id_member_from'];
  532. $pms[$row['id_pm']] = $row['id_pm'];
  533. $recipients[$row['id_pm']] = array(
  534. 'to' => array(),
  535. 'bcc' => array()
  536. );
  537. }
  538. // Keep track of the last message so we know what the head is without another query!
  539. if ((empty($pmID) && (empty($options['view_newest_pm_first']) || !isset($lastData))) || empty($lastData) || (!empty($pmID) && $pmID == $row['id_pm']))
  540. $lastData = array(
  541. 'id' => $row['id_pm'],
  542. 'head' => $row['id_pm_head'],
  543. );
  544. }
  545. $smcFunc['db_free_result']($request);
  546. // Make sure that we have been given a correct head pm id!
  547. if ($context['display_mode'] === 2 && !empty($pmID) && $pmID != $lastData['id'])
  548. fatal_lang_error('no_access', false);
  549. if (!empty($pms))
  550. {
  551. // Select the correct current message.
  552. if (empty($pmID))
  553. $context['current_pm'] = $lastData['id'];
  554. // This is a list of the pm's that are used for "full" display.
  555. if ($context['display_mode'] == 0)
  556. $display_pms = $pms;
  557. else
  558. $display_pms = array($context['current_pm']);
  559. // At this point we know the main id_pm's. But - if we are looking at conversations we need the others!
  560. if ($context['display_mode'] == 2)
  561. {
  562. $request = $smcFunc['db_query']('', '
  563. SELECT pm.id_pm, pm.id_member_from, pm.deleted_by_sender, pmr.id_member, pmr.deleted
  564. FROM {db_prefix}personal_messages AS pm
  565. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
  566. WHERE pm.id_pm_head = {int:id_pm_head}
  567. AND ((pm.id_member_from = {int:current_member} AND pm.deleted_by_sender = {int:not_deleted})
  568. OR (pmr.id_member = {int:current_member} AND pmr.deleted = {int:not_deleted}))
  569. ORDER BY pm.id_pm',
  570. array(
  571. 'current_member' => $user_info['id'],
  572. 'id_pm_head' => $lastData['head'],
  573. 'not_deleted' => 0,
  574. )
  575. );
  576. while ($row = $smcFunc['db_fetch_assoc']($request))
  577. {
  578. // This is, frankly, a joke. We will put in a workaround for people sending to themselves - yawn!
  579. if ($context['folder'] == 'sent' && $row['id_member_from'] == $user_info['id'] && $row['deleted_by_sender'] == 1)
  580. continue;
  581. elseif ($row['id_member'] == $user_info['id'] & $row['deleted'] == 1)
  582. continue;
  583. if (!isset($recipients[$row['id_pm']]))
  584. $recipients[$row['id_pm']] = array(
  585. 'to' => array(),
  586. 'bcc' => array()
  587. );
  588. $display_pms[] = $row['id_pm'];
  589. $posters[$row['id_pm']] = $row['id_member_from'];
  590. }
  591. $smcFunc['db_free_result']($request);
  592. }
  593. // This is pretty much EVERY pm!
  594. $all_pms = array_merge($pms, $display_pms);
  595. $all_pms = array_unique($all_pms);
  596. // Get recipients (don't include bcc-recipients for your inbox, you're not supposed to know :P).
  597. $request = $smcFunc['db_query']('', '
  598. SELECT pmr.id_pm, mem_to.id_member AS id_member_to, mem_to.real_name AS to_name, pmr.bcc, pmr.labels, pmr.is_read
  599. FROM {db_prefix}pm_recipients AS pmr
  600. LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
  601. WHERE pmr.id_pm IN ({array_int:pm_list})',
  602. array(
  603. 'pm_list' => $all_pms,
  604. )
  605. );
  606. $context['message_labels'] = array();
  607. $context['message_replied'] = array();
  608. $context['message_unread'] = array();
  609. while ($row = $smcFunc['db_fetch_assoc']($request))
  610. {
  611. if ($context['folder'] == 'sent' || empty($row['bcc']))
  612. $recipients[$row['id_pm']][empty($row['bcc']) ? 'to' : 'bcc'][] = empty($row['id_member_to']) ? $txt['guest_title'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . '">' . $row['to_name'] . '</a>';
  613. if ($row['id_member_to'] == $user_info['id'] && $context['folder'] != 'sent')
  614. {
  615. $context['message_replied'][$row['id_pm']] = $row['is_read'] & 2;
  616. $context['message_unread'][$row['id_pm']] = $row['is_read'] == 0;
  617. $row['labels'] = $row['labels'] == '' ? array() : explode(',', $row['labels']);
  618. foreach ($row['labels'] as $v)
  619. {
  620. if (isset($context['labels'][(int) $v]))
  621. $context['message_labels'][$row['id_pm']][(int) $v] = array('id' => $v, 'name' => $context['labels'][(int) $v]['name']);
  622. }
  623. }
  624. }
  625. $smcFunc['db_free_result']($request);
  626. // Make sure we don't load unnecessary data.
  627. if ($context['display_mode'] == 1)
  628. {
  629. foreach ($posters as $k => $v)
  630. if (!in_array($k, $display_pms))
  631. unset($posters[$k]);
  632. }
  633. // Load any users....
  634. $posters = array_unique($posters);
  635. if (!empty($posters))
  636. loadMemberData($posters);
  637. // If we're on grouped/restricted view get a restricted list of messages.
  638. if ($context['display_mode'] != 0)
  639. {
  640. // Get the order right.
  641. $orderBy = array();
  642. foreach (array_reverse($pms) as $pm)
  643. $orderBy[] = 'pm.id_pm = ' . $pm;
  644. // Seperate query for these bits!
  645. $subjects_request = $smcFunc['db_query']('', '
  646. SELECT pm.id_pm, pm.subject, pm.id_member_from, pm.msgtime, IFNULL(mem.real_name, pm.from_name) AS from_name,
  647. IFNULL(mem.id_member, 0) AS not_guest
  648. FROM {db_prefix}personal_messages AS pm
  649. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  650. WHERE pm.id_pm IN ({array_int:pm_list})
  651. ORDER BY ' . implode(', ', $orderBy) . '
  652. LIMIT ' . count($pms),
  653. array(
  654. 'pm_list' => $pms,
  655. )
  656. );
  657. }
  658. // Execute the query!
  659. $messages_request = $smcFunc['db_query']('', '
  660. SELECT pm.id_pm, pm.subject, pm.id_member_from, pm.body, pm.msgtime, pm.from_name
  661. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? '
  662. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)' : '') . ($sort_by == 'name' ? '
  663. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = {raw:id_member})' : '') . '
  664. WHERE pm.id_pm IN ({array_int:display_pms})' . ($context['folder'] == 'sent' ? '
  665. GROUP BY pm.id_pm, pm.subject, pm.id_member_from, pm.body, pm.msgtime, pm.from_name' : '') . '
  666. ORDER BY ' . ($context['display_mode'] == 2 ? 'pm.id_pm' : $sort_by_query) . ($descending ? ' DESC' : ' ASC') . '
  667. LIMIT ' . count($display_pms),
  668. array(
  669. 'display_pms' => $display_pms,
  670. 'id_member' => $context['folder'] == 'sent' ? 'pmr.id_member' : 'pm.id_member_from',
  671. )
  672. );
  673. }
  674. else
  675. $messages_request = false;
  676. // prepare some items for the template
  677. $context['can_send_pm'] = allowedTo('pm_send');
  678. $context['can_send_email'] = allowedTo('send_email_to_members');
  679. $context['sub_template'] = 'folder';
  680. $context['page_title'] = $txt['pm_inbox'];
  681. $context['sort_direction'] = $descending ? 'down' : 'up';
  682. $context['sort_by'] = $sort_by;
  683. // Set up the page index.
  684. $context['page_index'] = constructPageIndex($scripturl . '?action=pm;f=' . $context['folder'] . (isset($_REQUEST['l']) ? ';l=' . (int) $_REQUEST['l'] : '') . ';sort=' . $context['sort_by'] . ($descending ? ';desc' : ''), $start, $max_messages, $modSettings['defaultMaxMessages']);
  685. $context['start'] = $start;
  686. // Finally mark the relevant messages as read.
  687. if ($context['folder'] != 'sent' && !empty($context['labels'][(int) $context['current_label_id']]['unread_messages']))
  688. {
  689. // If the display mode is "old sk00l" do them all...
  690. if ($context['display_mode'] == 0)
  691. markMessages(null, $context['current_label_id']);
  692. // Otherwise do just the current one!
  693. elseif (!empty($context['current_pm']))
  694. markMessages($display_pms, $context['current_label_id']);
  695. }
  696. // Build the conversation button array.
  697. if ($context['display_mode'] === 2 && !empty($context['current_pm']))
  698. {
  699. $context['conversation_buttons'] = array(
  700. 'delete' => array('text' => 'delete_conversation', 'image' => 'delete.png', 'lang' => true, 'url' => $scripturl . '?action=pm;sa=pmactions;pm_actions[' . $context['current_pm'] . ']=delete;conversation;f=' . $context['folder'] . ';start=' . $context['start'] . ($context['current_label_id'] != -1 ? ';l=' . $context['current_label_id'] : '') . ';' . $context['session_var'] . '=' . $context['session_id'], 'custom' => 'onclick="return confirm(\'' . addslashes($txt['remove_message']) . '?\');"'),
  701. );
  702. // Allow mods to add additional buttons here
  703. call_integration_hook('integrate_conversation_buttons');
  704. }
  705. }
  706. /**
  707. * Get a personal message for the theme. (used to save memory.)
  708. *
  709. * @param $type
  710. * @param $reset
  711. */
  712. function prepareMessageContext($type = 'subject', $reset = false)
  713. {
  714. global $txt, $scripturl, $modSettings, $settings, $context, $messages_request, $memberContext, $recipients, $smcFunc;
  715. global $user_info, $subjects_request;
  716. // Count the current message number....
  717. static $counter = null;
  718. if ($counter === null || $reset)
  719. $counter = $context['start'];
  720. static $temp_pm_selected = null;
  721. if ($temp_pm_selected === null)
  722. {
  723. $temp_pm_selected = isset($_SESSION['pm_selected']) ? $_SESSION['pm_selected'] : array();
  724. $_SESSION['pm_selected'] = array();
  725. }
  726. // If we're in non-boring view do something exciting!
  727. if ($context['display_mode'] != 0 && $subjects_request && $type == 'subject')
  728. {
  729. $subject = $smcFunc['db_fetch_assoc']($subjects_request);
  730. if (!$subject)
  731. {
  732. $smcFunc['db_free_result']($subjects_request);
  733. return false;
  734. }
  735. $subject['subject'] = $subject['subject'] == '' ? $txt['no_subject'] : $subject['subject'];
  736. censorText($subject['subject']);
  737. $output = array(
  738. 'id' => $subject['id_pm'],
  739. 'member' => array(
  740. 'id' => $subject['id_member_from'],
  741. 'name' => $subject['from_name'],
  742. 'link' => $subject['not_guest'] ? '<a href="' . $scripturl . '?action=profile;u=' . $subject['id_member_from'] . '">' . $subject['from_name'] . '</a>' : $subject['from_name'],
  743. ),
  744. 'recipients' => &$recipients[$subject['id_pm']],
  745. 'subject' => $subject['subject'],
  746. 'time' => timeformat($subject['msgtime']),
  747. 'timestamp' => forum_time(true, $subject['msgtime']),
  748. 'number_recipients' => count($recipients[$subject['id_pm']]['to']),
  749. 'labels' => &$context['message_labels'][$subject['id_pm']],
  750. 'fully_labeled' => count($context['message_labels'][$subject['id_pm']]) == count($context['labels']),
  751. 'is_replied_to' => &$context['message_replied'][$subject['id_pm']],
  752. 'is_unread' => &$context['message_unread'][$subject['id_pm']],
  753. 'is_selected' => !empty($temp_pm_selected) && in_array($subject['id_pm'], $temp_pm_selected),
  754. );
  755. return $output;
  756. }
  757. // Bail if it's false, ie. no messages.
  758. if ($messages_request == false)
  759. return false;
  760. // Reset the data?
  761. if ($reset == true)
  762. return @$smcFunc['db_data_seek']($messages_request, 0);
  763. // Get the next one... bail if anything goes wrong.
  764. $message = $smcFunc['db_fetch_assoc']($messages_request);
  765. if (!$message)
  766. {
  767. if ($type != 'subject')
  768. $smcFunc['db_free_result']($messages_request);
  769. return false;
  770. }
  771. // Use '(no subject)' if none was specified.
  772. $message['subject'] = $message['subject'] == '' ? $txt['no_subject'] : $message['subject'];
  773. // Load the message's information - if it's not there, load the guest information.
  774. if (!loadMemberContext($message['id_member_from'], true))
  775. {
  776. $memberContext[$message['id_member_from']]['name'] = $message['from_name'];
  777. $memberContext[$message['id_member_from']]['id'] = 0;
  778. // Sometimes the forum sends messages itself (Warnings are an example) - in this case don't label it from a guest.
  779. $memberContext[$message['id_member_from']]['group'] = $message['from_name'] == $context['forum_name'] ? '' : $txt['guest_title'];
  780. $memberContext[$message['id_member_from']]['link'] = $message['from_name'];
  781. $memberContext[$message['id_member_from']]['email'] = '';
  782. $memberContext[$message['id_member_from']]['show_email'] = showEmailAddress(true, 0);
  783. $memberContext[$message['id_member_from']]['is_guest'] = true;
  784. }
  785. else
  786. {
  787. $memberContext[$message['id_member_from']]['can_view_profile'] = allowedTo('profile_view_any') || ($message['id_member_from'] == $user_info['id'] && allowedTo('profile_view_own'));
  788. $memberContext[$message['id_member_from']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member_from']]['warning_status'] && ($context['user']['can_mod'] || (!empty($modSettings['warning_show']) && ($modSettings['warning_show'] > 1 || $message['id_member_from'] == $user_info['id'])));
  789. }
  790. $memberContext[$message['id_member_from']]['show_profile_buttons'] = $settings['show_profile_buttons'] && (!empty($memberContext[$message['id_member_from']]['can_view_profile']) || (!empty($memberContext[$message['id_member_from']]['website']['url']) && !isset($context['disabled_fields']['website'])) || (in_array($memberContext[$message['id_member_from']]['show_email'], array('yes', 'yes_permission_override', 'no_through_forum'))) || $context['can_send_pm']);
  791. // Censor all the important text...
  792. censorText($message['body']);
  793. censorText($message['subject']);
  794. // Run UBBC interpreter on the message.
  795. $message['body'] = parse_bbc($message['body'], true, 'pm' . $message['id_pm']);
  796. // Send the array.
  797. $output = array(
  798. 'alternate' => $counter % 2,
  799. 'id' => $message['id_pm'],
  800. 'member' => &$memberContext[$message['id_member_from']],
  801. 'subject' => $message['subject'],
  802. 'time' => timeformat($message['msgtime']),
  803. 'timestamp' => forum_time(true, $message['msgtime']),
  804. 'counter' => $counter,
  805. 'body' => $message['body'],
  806. 'recipients' => &$recipients[$message['id_pm']],
  807. 'number_recipients' => count($recipients[$message['id_pm']]['to']),
  808. 'labels' => &$context['message_labels'][$message['id_pm']],
  809. 'fully_labeled' => count($context['message_labels'][$message['id_pm']]) == count($context['labels']),
  810. 'is_replied_to' => &$context['message_replied'][$message['id_pm']],
  811. 'is_unread' => &$context['message_unread'][$message['id_pm']],
  812. 'is_selected' => !empty($temp_pm_selected) && in_array($message['id_pm'], $temp_pm_selected),
  813. 'is_message_author' => $message['id_member_from'] == $user_info['id'],
  814. 'can_report' => !empty($modSettings['enableReportPM']),
  815. 'can_see_ip' => allowedTo('moderate_forum') || ($message['id_member_from'] == $user_info['id'] && !empty($user_info['id'])),
  816. );
  817. $counter++;
  818. return $output;
  819. }
  820. /**
  821. * Send a new message?
  822. */
  823. function action_sendmessage()
  824. {
  825. global $txt, $scripturl, $modSettings;
  826. global $context, $options, $smcFunc, $language, $user_info;
  827. isAllowedTo('pm_send');
  828. loadLanguage('PersonalMessage');
  829. // Just in case it was loaded from somewhere else.
  830. loadTemplate('PersonalMessage');
  831. $context['sub_template'] = 'send';
  832. // Extract out the spam settings - cause it's neat.
  833. list ($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
  834. // Set the title...
  835. $context['page_title'] = $txt['send_message'];
  836. $context['reply'] = isset($_REQUEST['pmsg']) || isset($_REQUEST['quote']);
  837. // Check whether we've gone over the limit of messages we can send per hour.
  838. if (!empty($modSettings['pm_posts_per_hour']) && !allowedTo(array('admin_forum', 'moderate_forum', 'send_mail')) && $user_info['mod_cache']['bq'] == '0=1' && $user_info['mod_cache']['gq'] == '0=1')
  839. {
  840. // How many messages have they sent this last hour?
  841. $request = $smcFunc['db_query']('', '
  842. SELECT COUNT(pr.id_pm) AS post_count
  843. FROM {db_prefix}personal_messages AS pm
  844. INNER JOIN {db_prefix}pm_recipients AS pr ON (pr.id_pm = pm.id_pm)
  845. WHERE pm.id_member_from = {int:current_member}
  846. AND pm.msgtime > {int:msgtime}',
  847. array(
  848. 'current_member' => $user_info['id'],
  849. 'msgtime' => time() - 3600,
  850. )
  851. );
  852. list ($postCount) = $smcFunc['db_fetch_row']($request);
  853. $smcFunc['db_free_result']($request);
  854. if (!empty($postCount) && $postCount >= $modSettings['pm_posts_per_hour'])
  855. fatal_lang_error('pm_too_many_per_hour', true, array($modSettings['pm_posts_per_hour']));
  856. }
  857. // Quoting/Replying to a message?
  858. if (!empty($_REQUEST['pmsg']))
  859. {
  860. $pmsg = (int) $_REQUEST['pmsg'];
  861. // Make sure this is yours.
  862. if (!isAccessiblePM($pmsg))
  863. fatal_lang_error('no_access', false);
  864. // Work out whether this is one you've received?
  865. $request = $smcFunc['db_query']('', '
  866. SELECT
  867. id_pm
  868. FROM {db_prefix}pm_recipients
  869. WHERE id_pm = {int:id_pm}
  870. AND id_member = {int:current_member}
  871. LIMIT 1',
  872. array(
  873. 'current_member' => $user_info['id'],
  874. 'id_pm' => $pmsg,
  875. )
  876. );
  877. $isReceived = $smcFunc['db_num_rows']($request) != 0;
  878. $smcFunc['db_free_result']($request);
  879. // Get the quoted message (and make sure you're allowed to see this quote!).
  880. $request = $smcFunc['db_query']('', '
  881. SELECT
  882. pm.id_pm, CASE WHEN pm.id_pm_head = {int:id_pm_head_empty} THEN pm.id_pm ELSE pm.id_pm_head END AS pm_head,
  883. pm.body, pm.subject, pm.msgtime, mem.member_name, IFNULL(mem.id_member, 0) AS id_member,
  884. IFNULL(mem.real_name, pm.from_name) AS real_name
  885. FROM {db_prefix}personal_messages AS pm' . (!$isReceived ? '' : '
  886. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = {int:id_pm})') . '
  887. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  888. WHERE pm.id_pm = {int:id_pm}' . (!$isReceived ? '
  889. AND pm.id_member_from = {int:current_member}' : '
  890. AND pmr.id_member = {int:current_member}') . '
  891. LIMIT 1',
  892. array(
  893. 'current_member' => $user_info['id'],
  894. 'id_pm_head_empty' => 0,
  895. 'id_pm' => $pmsg,
  896. )
  897. );
  898. if ($smcFunc['db_num_rows']($request) == 0)
  899. fatal_lang_error('pm_not_yours', false);
  900. $row_quoted = $smcFunc['db_fetch_assoc']($request);
  901. $smcFunc['db_free_result']($request);
  902. // Censor the message.
  903. censorText($row_quoted['subject']);
  904. censorText($row_quoted['body']);
  905. // Add 'Re: ' to it....
  906. if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix')))
  907. {
  908. if ($language === $user_info['language'])
  909. $context['response_prefix'] = $txt['response_prefix'];
  910. else
  911. {
  912. loadLanguage('index', $language, false);
  913. $context['response_prefix'] = $txt['response_prefix'];
  914. loadLanguage('index');
  915. }
  916. cache_put_data('response_prefix', $context['response_prefix'], 600);
  917. }
  918. $form_subject = $row_quoted['subject'];
  919. if ($context['reply'] && trim($context['response_prefix']) != '' && $smcFunc['strpos']($form_subject, trim($context['response_prefix'])) !== 0)
  920. $form_subject = $context['response_prefix'] . $form_subject;
  921. if (isset($_REQUEST['quote']))
  922. {
  923. // Remove any nested quotes and <br />...
  924. $form_message = preg_replace('~<br ?/?' . '>~i', "\n", $row_quoted['body']);
  925. if (!empty($modSettings['removeNestedQuotes']))
  926. $form_message = preg_replace(array('~\n?\[quote.*?\].+?\[/quote\]\n?~is', '~^\n~', '~\[/quote\]~'), '', $form_message);
  927. if (empty($row_quoted['id_member']))
  928. $form_message = '[quote author=&quot;' . $row_quoted['real_name'] . '&quot;]' . "\n" . $form_message . "\n" . '[/quote]';
  929. else
  930. $form_message = '[quote author=' . $row_quoted['real_name'] . ' link=action=profile;u=' . $row_quoted['id_member'] . ' date=' . $row_quoted['msgtime'] . ']' . "\n" . $form_message . "\n" . '[/quote]';
  931. }
  932. else
  933. $form_message = '';
  934. // Do the BBC thang on the message.
  935. $row_quoted['body'] = parse_bbc($row_quoted['body'], true, 'pm' . $row_quoted['id_pm']);
  936. // Set up the quoted message array.
  937. $context['quoted_message'] = array(
  938. 'id' => $row_quoted['id_pm'],
  939. 'pm_head' => $row_quoted['pm_head'],
  940. 'member' => array(
  941. 'name' => $row_quoted['real_name'],
  942. 'username' => $row_quoted['member_name'],
  943. 'id' => $row_quoted['id_member'],
  944. 'href' => !empty($row_quoted['id_member']) ? $scripturl . '?action=profile;u=' . $row_quoted['id_member'] : '',
  945. 'link' => !empty($row_quoted['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row_quoted['id_member'] . '">' . $row_quoted['real_name'] . '</a>' : $row_quoted['real_name'],
  946. ),
  947. 'subject' => $row_quoted['subject'],
  948. 'time' => timeformat($row_quoted['msgtime']),
  949. 'timestamp' => forum_time(true, $row_quoted['msgtime']),
  950. 'body' => $row_quoted['body']
  951. );
  952. }
  953. else
  954. {
  955. $context['quoted_message'] = false;
  956. $form_subject = '';
  957. $form_message = '';
  958. }
  959. $context['recipients'] = array(
  960. 'to' => array(),
  961. 'bcc' => array(),
  962. );
  963. // Sending by ID? Replying to all? Fetch the real_name(s).
  964. if (isset($_REQUEST['u']))
  965. {
  966. // If the user is replying to all, get all the other members this was sent to..
  967. if ($_REQUEST['u'] == 'all' && isset($row_quoted))
  968. {
  969. // Firstly, to reply to all we clearly already have $row_quoted - so have the original member from.
  970. if ($row_quoted['id_member'] != $user_info['id'])
  971. $context['recipients']['to'][] = array(
  972. 'id' => $row_quoted['id_member'],
  973. 'name' => htmlspecialchars($row_quoted['real_name']),
  974. );
  975. // Now to get the others.
  976. $request = $smcFunc['db_query']('', '
  977. SELECT mem.id_member, mem.real_name
  978. FROM {db_prefix}pm_recipients AS pmr
  979. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = pmr.id_member)
  980. WHERE pmr.id_pm = {int:id_pm}
  981. AND pmr.id_member != {int:current_member}
  982. AND pmr.bcc = {int:not_bcc}',
  983. array(
  984. 'current_member' => $user_info['id'],
  985. 'id_pm' => $pmsg,
  986. 'not_bcc' => 0,
  987. )
  988. );
  989. while ($row = $smcFunc['db_fetch_assoc']($request))
  990. $context['recipients']['to'][] = array(
  991. 'id' => $row['id_member'],
  992. 'name' => $row['real_name'],
  993. );
  994. $smcFunc['db_free_result']($request);
  995. }
  996. else
  997. {
  998. $_REQUEST['u'] = explode(',', $_REQUEST['u']);
  999. foreach ($_REQUEST['u'] as $key => $uID)
  1000. $_REQUEST['u'][$key] = (int) $uID;
  1001. $_REQUEST['u'] = array_unique($_REQUEST['u']);
  1002. $request = $smcFunc['db_query']('', '
  1003. SELECT id_member, real_name
  1004. FROM {db_prefix}members
  1005. WHERE id_member IN ({array_int:member_list})
  1006. LIMIT ' . count($_REQUEST['u']),
  1007. array(
  1008. 'member_list' => $_REQUEST['u'],
  1009. )
  1010. );
  1011. while ($row = $smcFunc['db_fetch_assoc']($request))
  1012. $context['recipients']['to'][] = array(
  1013. 'id' => $row['id_member'],
  1014. 'name' => $row['real_name'],
  1015. );
  1016. $smcFunc['db_free_result']($request);
  1017. }
  1018. // Get a literal name list in case the user has JavaScript disabled.
  1019. $names = array();
  1020. foreach ($context['recipients']['to'] as $to)
  1021. $names[] = $to['name'];
  1022. $context['to_value'] = empty($names) ? '' : '&quot;' . implode('&quot;, &quot;', $names) . '&quot;';
  1023. }
  1024. else
  1025. $context['to_value'] = '';
  1026. // Set the defaults...
  1027. $context['subject'] = $form_subject;
  1028. $context['message'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $form_message);
  1029. $context['copy_to_outbox'] = !empty($options['copy_to_outbox']);
  1030. // And build the link tree.
  1031. $context['linktree'][] = array(
  1032. 'url' => $scripturl . '?action=pm;sa=send',
  1033. 'name' => $txt['new_message']
  1034. );
  1035. $modSettings['disable_wysiwyg'] = !empty($modSettings['disable_wysiwyg']) || empty($modSettings['enableBBC']);
  1036. // Generate a list of drafts that they can load in to the editor
  1037. if (!empty($context['drafts_pm_save']))
  1038. {
  1039. require_once(CONTROLLERDIR . '/Drafts.controller.php');
  1040. $pm_seed = isset($_REQUEST['pmsg']) ? $_REQUEST['pmsg'] : (isset($_REQUEST['quote']) ? $_REQUEST['quote'] : 0);
  1041. action_showDrafts($user_info['id'], $pm_seed, 1);
  1042. }
  1043. // Needed for the WYSIWYG editor.
  1044. require_once(SUBSDIR . '/Editor.subs.php');
  1045. // Now create the editor.
  1046. $editorOptions = array(
  1047. 'id' => 'message',
  1048. 'value' => $context['message'],
  1049. 'height' => '250px',
  1050. 'width' => '100%',
  1051. 'labels' => array(
  1052. 'post_button' => $txt['send_message'],
  1053. ),
  1054. 'preview_type' => 2,
  1055. );
  1056. create_control_richedit($editorOptions);
  1057. // Store the ID for old compatibility.
  1058. $context['post_box_name'] = $editorOptions['id'];
  1059. $context['bcc_value'] = '';
  1060. $context['require_verification'] = !$user_info['is_admin'] && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification'];
  1061. if ($context['require_verification'])
  1062. {
  1063. $verificationOptions = array(
  1064. 'id' => 'pm',
  1065. );
  1066. $context['require_verification'] = create_control_verification($verificationOptions);
  1067. $context['visual_verification_id'] = $verificationOptions['id'];
  1068. }
  1069. // Register this form and get a sequence number in $context.
  1070. checkSubmitOnce('register');
  1071. }
  1072. /**
  1073. * This function allows the user to view their PM drafts
  1074. * Accessed by ?action=pm;sa=showpmdrafts
  1075. */
  1076. function action_messagedrafts()
  1077. {
  1078. global $user_info;
  1079. // validate with loadMemberData()
  1080. $memberResult = loadMemberData($user_info['id'], false);
  1081. if (!is_array($memberResult))
  1082. fatal_lang_error('not_a_user', false);
  1083. list ($memID) = $memberResult;
  1084. // drafts is where the functions reside
  1085. require_once(CONTROLLERDIR . '/Drafts.controller.php');
  1086. action_showPMDrafts($memID);
  1087. }
  1088. /**
  1089. * An error in the message...
  1090. *
  1091. * @param $named_recipients
  1092. * @param $recipient_ids
  1093. */
  1094. function messagePostError($named_recipients, $recipient_ids = array())
  1095. {
  1096. global $txt, $context, $scripturl, $modSettings;
  1097. global $smcFunc, $user_info;
  1098. if (!isset($_REQUEST['xml']))
  1099. $context['menu_data_' . $context['pm_menu_id']]['current_area'] = 'send';
  1100. if (!isset($_REQUEST['xml']))
  1101. $context['sub_template'] = 'send';
  1102. elseif (isset($_REQUEST['xml']))
  1103. $context['sub_template'] = 'pm';
  1104. $context['page_title'] = $txt['send_message'];
  1105. $error_types = error_context::context('pm', 1);
  1106. // Got some known members?
  1107. $context['recipients'] = array(
  1108. 'to' => array(),
  1109. 'bcc' => array(),
  1110. );
  1111. if (!empty($recipient_ids['to']) || !empty($recipient_ids['bcc']))
  1112. {
  1113. $allRecipients = array_merge($recipient_ids['to'], $recipient_ids['bcc']);
  1114. $request = $smcFunc['db_query']('', '
  1115. SELECT id_member, real_name
  1116. FROM {db_prefix}members
  1117. WHERE id_member IN ({array_int:member_list})',
  1118. array(
  1119. 'member_list' => $allRecipients,
  1120. )
  1121. );
  1122. while ($row = $smcFunc['db_fetch_assoc']($request))
  1123. {
  1124. $recipientType = in_array($row['id_member'], $recipient_ids['bcc']) ? 'bcc' : 'to';
  1125. $context['recipients'][$recipientType][] = array(
  1126. 'id' => $row['id_member'],
  1127. 'name' => $row['real_name'],
  1128. );
  1129. }
  1130. $smcFunc['db_free_result']($request);
  1131. }
  1132. // Set everything up like before....
  1133. $context['subject'] = isset($_REQUEST['subject']) ? $smcFunc['htmlspecialchars']($_REQUEST['subject']) : '';
  1134. $context['message'] = isset($_REQUEST['message']) ? str_replace(array(' '), array('&nbsp; '), $smcFunc['htmlspecialchars']($_REQUEST['message'])) : '';
  1135. $context['copy_to_outbox'] = !empty($_REQUEST['outbox']);
  1136. $context['reply'] = !empty($_REQUEST['replied_to']);
  1137. if ($context['reply'])
  1138. {
  1139. $_REQUEST['replied_to'] = (int) $_REQUEST['replied_to'];
  1140. $request = $smcFunc['db_query']('', '
  1141. SELECT
  1142. pm.id_pm, CASE WHEN pm.id_pm_head = {int:no_id_pm_head} THEN pm.id_pm ELSE pm.id_pm_head END AS pm_head,
  1143. pm.body, pm.subject, pm.msgtime, mem.member_name, IFNULL(mem.id_member, 0) AS id_member,
  1144. IFNULL(mem.real_name, pm.from_name) AS real_name
  1145. FROM {db_prefix}personal_messages AS pm' . ($context['folder'] == 'sent' ? '' : '
  1146. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = {int:replied_to})') . '
  1147. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  1148. WHERE pm.id_pm = {int:replied_to}' . ($context['folder'] == 'sent' ? '
  1149. AND pm.id_member_from = {int:current_member}' : '
  1150. AND pmr.id_member = {int:current_member}') . '
  1151. LIMIT 1',
  1152. array(
  1153. 'current_member' => $user_info['id'],
  1154. 'no_id_pm_head' => 0,
  1155. 'replied_to' => $_REQUEST['replied_to'],
  1156. )
  1157. );
  1158. if ($smcFunc['db_num_rows']($request) == 0)
  1159. {
  1160. if (!isset($_REQUEST['xml']))
  1161. fatal_lang_error('pm_not_yours', false);
  1162. else
  1163. $error_types->addError('pm_not_yours');
  1164. }
  1165. $row_quoted = $smcFunc['db_fetch_assoc']($request);
  1166. $smcFunc['db_free_result']($request);
  1167. censorText($row_quoted['subject']);
  1168. censorText($row_quoted['body']);
  1169. $context['quoted_message'] = array(
  1170. 'id' => $row_quoted['id_pm'],
  1171. 'pm_head' => $row_quoted['pm_head'],
  1172. 'member' => array(
  1173. 'name' => $row_quoted['real_name'],
  1174. 'username' => $row_quoted['member_name'],
  1175. 'id' => $row_quoted['id_member'],
  1176. 'href' => !empty($row_quoted['id_member']) ? $scripturl . '?action=profile;u=' . $row_quoted['id_member'] : '',
  1177. 'link' => !empty($row_quoted['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row_quoted['id_member'] . '">' . $row_quoted['real_name'] . '</a>' : $row_quoted['real_name'],
  1178. ),
  1179. 'subject' => $row_quoted['subject'],
  1180. 'time' => timeformat($row_quoted['msgtime']),
  1181. 'timestamp' => forum_time(true, $row_quoted['msgtime']),
  1182. 'body' => parse_bbc($row_quoted['body'], true, 'pm' . $row_quoted['id_pm']),
  1183. );
  1184. }
  1185. // Build the link tree....
  1186. $context['linktree'][] = array(
  1187. 'url' => $scripturl . '?action=pm;sa=send',
  1188. 'name' => $txt['new_message']
  1189. );
  1190. // Set each of the errors for the template.
  1191. $context['post_error'] = array(
  1192. 'errors' => $error_types->prepareErrors(),
  1193. 'type' => $error_types->getErrorType() == 0 ? 'minor' : 'serious',
  1194. 'title' => $txt['error_while_submitting'],
  1195. );
  1196. // We need to load the editor once more.
  1197. require_once(SUBSDIR . '/Editor.subs.php');
  1198. // Create it...
  1199. $editorOptions = array(
  1200. 'id' => 'message',
  1201. 'value' => $context['message'],
  1202. 'width' => '90%',
  1203. 'height' => '250px',
  1204. 'labels' => array(
  1205. 'post_button' => $txt['send_message'],
  1206. ),
  1207. 'preview_type' => 2,
  1208. );
  1209. create_control_richedit($editorOptions);
  1210. // ... and store the ID again...
  1211. $context['post_box_name'] = $editorOptions['id'];
  1212. // Check whether we need to show the code again.
  1213. $context['require_verification'] = !$user_info['is_admin'] && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification'];
  1214. if ($context['require_verification'] && !isset($_REQUEST['xml']))
  1215. {
  1216. require_once(SUBSDIR . '/Editor.subs.php');
  1217. $verificationOptions = array(
  1218. 'id' => 'pm',
  1219. );
  1220. $context['require_verification'] = create_control_verification($verificationOptions);
  1221. $context['visual_verification_id'] = $verificationOptions['id'];
  1222. }
  1223. $context['to_value'] = empty($named_recipients['to']) ? '' : '&quot;' . implode('&quot;, &quot;', $named_recipients['to']) . '&quot;';
  1224. $context['bcc_value'] = empty($named_recipients['bcc']) ? '' : '&quot;' . implode('&quot;, &quot;', $named_recipients['bcc']) . '&quot;';
  1225. // No check for the previous submission is needed.
  1226. checkSubmitOnce('free');
  1227. // Acquire a new form sequence number.
  1228. checkSubmitOnce('register');
  1229. }
  1230. /**
  1231. * Send it!
  1232. */
  1233. function action_sendmessage2()
  1234. {
  1235. global $txt, $context;
  1236. global $user_info, $modSettings, $scripturl, $smcFunc;
  1237. isAllowedTo('pm_send');
  1238. require_once(SUBSDIR . '/Auth.subs.php');
  1239. require_once(SUBSDIR . '/Post.subs.php');
  1240. // PM Drafts enabled and needed?
  1241. if ($context['drafts_pm_save'] && (isset($_POST['save_draft']) || isset($_POST['id_pm_draft'])))
  1242. require_once(CONTROLLERDIR . '/Drafts.controller.php');
  1243. loadLanguage('PersonalMessage', '', false);
  1244. // Extract out the spam settings - it saves database space!
  1245. list ($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
  1246. // Initialize the errors we're about to make.
  1247. $post_errors = error_context::context('pm', 1);
  1248. // Check whether we've gone over the limit of messages we can send per hour - fatal error if fails!
  1249. if (!empty($modSettings['pm_posts_per_hour']) && !allowedTo(array('admin_forum', 'moderate_forum', 'send_mail')) && $user_info['mod_cache']['bq'] == '0=1' && $user_info['mod_cache']['gq'] == '0=1')
  1250. {
  1251. // How many have they sent this last hour?
  1252. $request = $smcFunc['db_query']('', '
  1253. SELECT COUNT(pr.id_pm) AS post_count
  1254. FROM {db_prefix}personal_messages AS pm
  1255. INNER JOIN {db_prefix}pm_recipients AS pr ON (pr.id_pm = pm.id_pm)
  1256. WHERE pm.id_member_from = {int:current_member}
  1257. AND pm.msgtime > {int:msgtime}',
  1258. array(
  1259. 'current_member' => $user_info['id'],
  1260. 'msgtime' => time() - 3600,
  1261. )
  1262. );
  1263. list ($postCount) = $smcFunc['db_fetch_row']($request);
  1264. $smcFunc['db_free_result']($request);
  1265. if (!empty($postCount) && $postCount >= $modSettings['pm_posts_per_hour'])
  1266. {
  1267. if (!isset($_REQUEST['xml']))
  1268. fatal_lang_error('pm_too_many_per_hour', true, array($modSettings['pm_posts_per_hour']));
  1269. else
  1270. $post_errors->addError('pm_too_many_per_hour');
  1271. }
  1272. }
  1273. // If your session timed out, show an error, but do allow to re-submit.
  1274. if (!isset($_REQUEST['xml']) && checkSession('post', '', false) != '')
  1275. $post_errors->addError('session_timeout');
  1276. $_REQUEST['subject'] = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : '';
  1277. $_REQUEST['to'] = empty($_POST['to']) ? (empty($_GET['to']) ? '' : $_GET['to']) : $_POST['to'];
  1278. $_REQUEST['bcc'] = empty($_POST['bcc']) ? (empty($_GET['bcc']) ? '' : $_GET['bcc']) : $_POST['bcc'];
  1279. // Route the input from the 'u' parameter to the 'to'-list.
  1280. if (!empty($_POST['u']))
  1281. $_POST['recipient_to'] = explode(',', $_POST['u']);
  1282. // Construct the list of recipients.
  1283. $recipientList = array();
  1284. $namedRecipientList = array();
  1285. $namesNotFound = array();
  1286. foreach (array('to', 'bcc') as $recipientType)
  1287. {
  1288. // First, let's see if there's user ID's given.
  1289. $recipientList[$recipientType] = array();
  1290. if (!empty($_POST['recipient_' . $recipientType]) && is_array($_POST['recipient_' . $recipientType]))
  1291. {
  1292. foreach ($_POST['recipient_' . $recipientType] as $recipient)
  1293. $recipientList[$recipientType][] = (int) $recipient;
  1294. }
  1295. // Are there also literal names set?
  1296. if (!empty($_REQUEST[$recipientType]))
  1297. {
  1298. // We're going to take out the "s anyway ;).
  1299. $recipientString = strtr($_REQUEST[$recipientType], array('\\"' => '"'));
  1300. preg_match_all('~"([^"]+)"~', $recipientString, $matches);
  1301. $namedRecipientList[$recipientType] = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $recipientString))));
  1302. foreach ($namedRecipientList[$recipientType] as $index => $recipient)
  1303. {
  1304. if (strlen(trim($recipient)) > 0)
  1305. $namedRecipientList[$recipientType][$index] = $smcFunc['htmlspecialchars']($smcFunc['strtolower'](trim($recipient)));
  1306. else
  1307. unset($namedRecipientList[$recipientType][$index]);
  1308. }
  1309. if (!empty($namedRecipientList[$recipientType]))
  1310. {
  1311. $foundMembers = findMembers($namedRecipientList[$recipientType]);
  1312. // Assume all are not found, until proven otherwise.
  1313. $namesNotFound[$recipientType] = $namedRecipientList[$recipientType];
  1314. foreach ($foundMembers as $member)
  1315. {
  1316. $testNames = array(
  1317. $smcFunc['strtolower']($member['username']),
  1318. $smcFunc['strtolower']($member['name']),
  1319. $smcFunc['strtolower']($member['email']),
  1320. );
  1321. if (count(array_intersect($testNames, $namedRecipientList[$recipientType])) !== 0)
  1322. {
  1323. $recipientList[$recipientType][] = $member['id'];
  1324. // Get rid of this username, since we found it.
  1325. $namesNotFound[$recipientType] = array_diff($namesNotFound[$recipientType], $testNames);
  1326. }
  1327. }
  1328. }
  1329. }
  1330. // Selected a recipient to be deleted? Remove them now.
  1331. if (!empty($_POST['delete_recipient']))
  1332. $recipientList[$recipientType] = array_diff($recipientList[$recipientType], array((int) $_POST['delete_recipient']));
  1333. // Make sure we don't include the same name twice
  1334. $recipientList[$recipientType] = array_unique($recipientList[$recipientType]);
  1335. }
  1336. // Are we changing the recipients some how?
  1337. $is_recipient_change = !empty($_POST['delete_recipient']) || !empty($_POST['to_submit']) || !empty($_POST['bcc_submit']);
  1338. // Check if there's at least one recipient.
  1339. if (empty($recipientList['to']) && empty($recipientList['bcc']))
  1340. $post_errors->addError('no_to');
  1341. // Make sure that we remove the members who did get it from the screen.
  1342. if (!$is_recipient_change)
  1343. {
  1344. foreach ($recipientList as $recipientType => $dummy)
  1345. {
  1346. if (!empty($namesNotFound[$recipientType]))
  1347. {
  1348. $post_errors->addError('bad_' . $recipientType);
  1349. // Since we already have a post error, remove the previous one.
  1350. $post_errors->removeError('no_to');
  1351. foreach ($namesNotFound[$recipientType] as $name)
  1352. $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
  1353. }
  1354. }
  1355. }
  1356. // Did they make any mistakes?
  1357. if ($_REQUEST['subject'] == '')
  1358. $post_errors->addError('no_subject');
  1359. if (!isset($_REQUEST['message']) || $_REQUEST['message'] == '')
  1360. $post_errors->addError('no_message');
  1361. elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_REQUEST['message']) > $modSettings['max_messageLength'])
  1362. $post_errors->addError('long_message');
  1363. else
  1364. {
  1365. // Preparse the message.
  1366. $message = $_REQUEST['message'];
  1367. preparsecode($message);
  1368. // Make sure there's still some content left without the tags.
  1369. if ($smcFunc['htmltrim'](strip_tags(parse_bbc($smcFunc['htmlspecialchars']($message, ENT_QUOTES), false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($message, '[html]') === false))
  1370. $post_errors->addError('no_message');
  1371. }
  1372. // Wrong verification code?
  1373. if (!$user_info['is_admin'] && !isset($_REQUEST['xml']) && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification'])
  1374. {
  1375. require_once(SUBSDIR . '/Editor.subs.php');
  1376. $verificationOptions = array(
  1377. 'id' => 'pm',
  1378. );
  1379. $context['require_verification'] = create_control_verification($verificationOptions, true);
  1380. if ($context['require_verification'])
  1381. $post_errors->addError('need_qr_verification', 0);
  1382. }
  1383. // If they did, give a chance to make ammends.
  1384. if ($post_errors->hasErrors() && !$is_recipient_change && !isset($_REQUEST['preview']) && !isset($_REQUEST['xml']))
  1385. return messagePostError($namedRecipientList, $recipientList);
  1386. // Want to take a second glance before you send?
  1387. if (isset($_REQUEST['preview']))
  1388. {
  1389. // Set everything up to be displayed.
  1390. $context['preview_subject'] = $smcFunc['htmlspecialchars']($_REQUEST['subject']);
  1391. $context['preview_message'] = $smcFunc['htmlspecialchars']($_REQUEST['message'], ENT_QUOTES);
  1392. preparsecode($context['preview_message'], true);
  1393. // Parse out the BBC if it is enabled.
  1394. $context['preview_message'] = parse_bbc($context['preview_message']);
  1395. // Censor, as always.
  1396. censorText($context['preview_subject']);
  1397. censorText($context['preview_message']);
  1398. // Set a descriptive title.
  1399. $context['page_title'] = $txt['preview'] . ' - ' . $context['preview_subject'];
  1400. // Pretend they messed up but don't ignore if they really did :P.
  1401. return messagePostError($namedRecipientList, $recipientList);
  1402. }
  1403. // Adding a recipient cause javascript ain't working?
  1404. elseif ($is_recipient_change)
  1405. {
  1406. // Maybe we couldn't find one?
  1407. foreach ($namesNotFound as $recipientType => $names)
  1408. {
  1409. $post_errors->addError('bad_' . $recipientType);
  1410. foreach ($names as $name)
  1411. $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
  1412. }
  1413. return messagePostError($namedRecipientList, $recipientList);
  1414. }
  1415. // Want to save this as a draft and think about it some more?
  1416. if ($context['drafts_pm_save'] && isset($_POST['save_draft']))
  1417. {
  1418. savePMDraft($recipientList);
  1419. return messagePostError($namedRecipientList, $recipientList);
  1420. }
  1421. // Before we send the PM, let's make sure we don't have an abuse of numbers.
  1422. elseif (!empty($modSettings['max_pm_recipients']) && count($recipientList['to']) + count($recipientList['bcc']) > $modSettings['max_pm_recipients'] && !allowedTo(array('moderate_forum', 'send_mail', 'admin_forum')))
  1423. {
  1424. $context['send_log'] = array(
  1425. 'sent' => array(),
  1426. 'failed' => array(sprintf($txt['pm_too_many_recipients'], $modSettings['max_pm_recipients'])),
  1427. );
  1428. return messagePostError($namedRecipientList, $recipientList);
  1429. }
  1430. // Protect from message spamming.
  1431. spamProtection('pm');
  1432. // Prevent double submission of this form.
  1433. checkSubmitOnce('check');
  1434. // Do the actual sending of the PM.
  1435. if (!empty($recipientList['to']) || !empty($recipientList['bcc']))
  1436. $context['send_log'] = sendpm($recipientList, $_REQUEST['subject'], $_REQUEST['message'], !empty($_REQUEST['outbox']), null, !empty($_REQUEST['pm_head']) ? (int) $_REQUEST['pm_head'] : 0);
  1437. else
  1438. $context['send_log'] = array(
  1439. 'sent' => array(),
  1440. 'failed' => array()
  1441. );
  1442. // Mark the message as "replied to".
  1443. if (!empty($context['send_log']['sent']) && !empty($_REQUEST['replied_to']) && isset($_REQUEST['f']) && $_REQUEST['f'] == 'inbox')
  1444. {
  1445. $smcFunc['db_query']('', '
  1446. UPDATE {db_prefix}pm_recipients
  1447. SET is_read = is_read | 2
  1448. WHERE id_pm = {int:replied_to}
  1449. AND id_member = {int:current_member}',
  1450. array(
  1451. 'current_member' => $user_info['id'],
  1452. 'replied_to' => (int) $_REQUEST['replied_to'],
  1453. )
  1454. );
  1455. }
  1456. // If one or more of the recipient were invalid, go back to the post screen with the failed usernames.
  1457. if (!empty($context['send_log']['failed']))
  1458. return messagePostError($namesNotFound, array(
  1459. 'to' => array_intersect($recipientList['to'], $context['send_log']['failed']),
  1460. 'bcc' => array_intersect($recipientList['bcc'], $context['send_log']['failed'])
  1461. ));
  1462. // Message sent successfully?
  1463. if (!empty($context['send_log']) && empty($context['send_log']['failed']))
  1464. {
  1465. $context['current_label_redirect'] = $context['current_label_redirect'] . ';done=sent';
  1466. // If we had a PM draft for this one, then its time to remove it since it was just sent
  1467. if ($context['drafts_pm_save'] && !empty($_POST['id_pm_draft']))
  1468. deleteDrafts($_POST['id_pm_draft'], $user_info['id']);
  1469. }
  1470. // Go back to the where they sent from, if possible...
  1471. redirectexit($context['current_label_redirect']);
  1472. }
  1473. /**
  1474. * This function performs all additional stuff...
  1475. */
  1476. function action_messageactions()
  1477. {
  1478. global $txt, $context, $user_info, $options, $smcFunc;
  1479. checkSession('request');
  1480. if (isset($_REQUEST['del_selected']))
  1481. $_REQUEST['pm_action'] = 'delete';
  1482. if (isset($_REQUEST['pm_action']) && $_REQUEST['pm_action'] != '' && !empty($_REQUEST['pms']) && is_array($_REQUEST['pms']))
  1483. {
  1484. foreach ($_REQUEST['pms'] as $pm)
  1485. $_REQUEST['pm_actions'][(int) $pm] = $_REQUEST['pm_action'];
  1486. }
  1487. if (empty($_REQUEST['pm_actions']))
  1488. redirectexit($context['current_label_redirect']);
  1489. // If we are in conversation, we may need to apply this to every message in the conversation.
  1490. if ($context['display_mode'] == 2 && isset($_REQUEST['conversation']))
  1491. {
  1492. $id_pms = array();
  1493. foreach ($_REQUEST['pm_actions'] as $pm => $dummy)
  1494. $id_pms[] = (int) $pm;
  1495. $request = $smcFunc['db_query']('', '
  1496. SELECT id_pm_head, id_pm
  1497. FROM {db_prefix}personal_messages
  1498. WHERE id_pm IN ({array_int:id_pms})',
  1499. array(
  1500. 'id_pms' => $id_pms,
  1501. )
  1502. );
  1503. $pm_heads = array();
  1504. while ($row = $smcFunc['db_fetch_assoc']($request))
  1505. $pm_heads[$row['id_pm_head']] = $row['id_pm'];
  1506. $smcFunc['db_free_result']($request);
  1507. $request = $smcFunc['db_query']('', '
  1508. SELECT id_pm, id_pm_head
  1509. FROM {db_prefix}personal_messages
  1510. WHERE id_pm_head IN ({array_int:pm_heads})',
  1511. array(
  1512. 'pm_heads' => array_keys($pm_heads),
  1513. )
  1514. );
  1515. // Copy the action from the single to PM to the others.
  1516. while ($row = $smcFunc['db_fetch_assoc']($request))
  1517. {
  1518. if (isset($pm_heads[$row['id_pm_head']]) && isset($_REQUEST['pm_actions'][$pm_heads[$row['id_pm_head']]]))
  1519. $_REQUEST['pm_actions'][$row['id_pm']] = $_REQUEST['pm_actions'][$pm_heads[$row['id_pm_head']]];
  1520. }
  1521. $smcFunc['db_free_result']($request);
  1522. }
  1523. $to_delete = array();
  1524. $to_label = array();
  1525. $label_type = array();
  1526. foreach ($_REQUEST['pm_actions'] as $pm => $action)
  1527. {
  1528. if ($action === 'delete')
  1529. $to_delete[] = (int) $pm;
  1530. else
  1531. {
  1532. if (substr($action, 0, 4) == 'add_')
  1533. {
  1534. $type = 'add';
  1535. $action = substr($action, 4);
  1536. }
  1537. elseif (substr($action, 0, 4) == 'rem_')
  1538. {
  1539. $type = 'rem';
  1540. $action = substr($action, 4);
  1541. }
  1542. else
  1543. $type = 'unk';
  1544. if ($action == '-1' || $action == '0' || (int) $action > 0)
  1545. {
  1546. $to_label[(int) $pm] = (int) $action;
  1547. $label_type[(int) $pm] = $type;
  1548. }
  1549. }
  1550. }
  1551. // Deleting, it looks like?
  1552. if (!empty($to_delete))
  1553. deleteMessages($to_delete, $context['display_mode'] == 2 ? null : $context['folder']);
  1554. // Are we labeling anything?
  1555. if (!empty($to_label) && $context['folder'] == 'inbox')
  1556. {
  1557. $updateErrors = 0;
  1558. // Get information about each message...
  1559. $request = $smcFunc['db_query']('', '
  1560. SELECT id_pm, labels
  1561. FROM {db_prefix}pm_recipients
  1562. WHERE id_member = {int:current_member}
  1563. AND id_pm IN ({array_int:to_label})
  1564. LIMIT ' . count($to_label),
  1565. array(
  1566. 'current_member' => $user_info['id'],
  1567. 'to_label' => array_keys($to_label),
  1568. )
  1569. );
  1570. while ($row = $smcFunc['db_fetch_assoc']($request))
  1571. {
  1572. $labels = $row['labels'] == '' ? array('-1') : explode(',', trim($row['labels']));
  1573. // Already exists? Then... unset it!
  1574. $ID_LABEL = array_search($to_label[$row['id_pm']], $labels);
  1575. if ($ID_LABEL !== false && $label_type[$row['id_pm']] !== 'add')
  1576. unset($labels[$ID_LABEL]);
  1577. elseif ($label_type[$row['id_pm']] !== 'rem')
  1578. $labels[] = $to_label[$row['id_pm']];
  1579. if (!empty($options['pm_remove_inbox_label']) && $to_label[$row['id_pm']] != '-1' && ($key = array_search('-1', $labels)) !== false)
  1580. unset($labels[$key]);
  1581. $set = implode(',', array_unique($labels));
  1582. if ($set == '')
  1583. $set = '-1';
  1584. // Check that this string isn't going to be too large for the database.
  1585. if ($set > 60)
  1586. $updateErrors++;
  1587. else
  1588. {
  1589. $smcFunc['db_query']('', '
  1590. UPDATE {db_prefix}pm_recipients
  1591. SET labels = {string:labels}
  1592. WHERE id_pm = {int:id_pm}
  1593. AND id_member = {int:current_member}',
  1594. array(
  1595. 'current_member' => $user_info['id'],
  1596. 'id_pm' => $row['id_pm'],
  1597. 'labels' => $set,
  1598. )
  1599. );
  1600. }
  1601. }
  1602. $smcFunc['db_free_result']($request);
  1603. // Any errors?
  1604. // @todo Separate the sprintf?
  1605. if (!empty($updateErrors))
  1606. fatal_lang_error('labels_too_many', true, array($updateErrors));
  1607. }
  1608. // Back to the folder.
  1609. $_SESSION['pm_selected'] = array_keys($to_label);
  1610. redirectexit($context['current_label_redirect'] . (count($to_label) == 1 ? '#msg' . $_SESSION['pm_selected'][0] : ''), count($to_label) == 1 && isBrowser('ie'));
  1611. }
  1612. /**
  1613. * Are you sure you want to PERMANENTLY (mostly) delete ALL your messages?
  1614. */
  1615. function action_removemessage()
  1616. {
  1617. global $txt, $context;
  1618. // Only have to set up the template....
  1619. $context['sub_template'] = 'ask_delete';
  1620. $context['page_title'] = $txt['delete_all'];
  1621. $context['delete_all'] = $_REQUEST['f'] == 'all';
  1622. // And set the folder name...
  1623. $txt['delete_all'] = str_replace('PMBOX', $context['folder'] != 'sent' ? $txt['inbox'] : $txt['sent_items'], $txt['delete_all']);
  1624. }
  1625. /**
  1626. * Delete ALL the messages!
  1627. */
  1628. function action_removemessage2()
  1629. {
  1630. global $context;
  1631. checkSession('get');
  1632. // If all then delete all messages the user has.
  1633. if ($_REQUEST['f'] == 'all')
  1634. deleteMessages(null, null);
  1635. // Otherwise just the selected folder.
  1636. else
  1637. deleteMessages(null, $_REQUEST['f'] != 'sent' ? 'inbox' : 'sent');
  1638. // Done... all gone.
  1639. redirectexit($context['current_label_redirect']);
  1640. }
  1641. /**
  1642. * This function allows the user to delete all messages older than so many days.
  1643. */
  1644. function action_messageprune()
  1645. {
  1646. global $txt, $context, $user_info, $scripturl, $smcFunc;
  1647. // Actually delete the messages.
  1648. if (isset($_REQUEST['age']))
  1649. {
  1650. checkSession();
  1651. // Calculate the time to delete before.
  1652. $deleteTime = max(0, time() - (86400 * (int) $_REQUEST['age']));
  1653. // Array to store the IDs in.
  1654. $toDelete = array();
  1655. // Select all the messages they have sent older than $deleteTime.
  1656. $request = $smcFunc['db_query']('', '
  1657. SELECT id_pm
  1658. FROM {db_prefix}personal_messages
  1659. WHERE deleted_by_sender = {int:not_deleted}
  1660. AND id_member_from = {int:current_member}
  1661. AND msgtime < {int:msgtime}',
  1662. array(
  1663. 'current_member' => $user_info['id'],
  1664. 'not_deleted' => 0,
  1665. 'msgtime' => $deleteTime,
  1666. )
  1667. );
  1668. while ($row = $smcFunc['db_fetch_row']($request))
  1669. $toDelete[] = $row[0];
  1670. $smcFunc['db_free_result']($request);
  1671. // Select all messages in their inbox older than $deleteTime.
  1672. $request = $smcFunc['db_query']('', '
  1673. SELECT pmr.id_pm
  1674. FROM {db_prefix}pm_recipients AS pmr
  1675. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  1676. WHERE pmr.deleted = {int:not_deleted}
  1677. AND pmr.id_member = {int:current_member}
  1678. AND pm.msgtime < {int:msgtime}',
  1679. array(
  1680. 'current_member' => $user_info['id'],
  1681. 'not_deleted' => 0,
  1682. 'msgtime' => $deleteTime,
  1683. )
  1684. );
  1685. while ($row = $smcFunc['db_fetch_assoc']($request))
  1686. $toDelete[] = $row['id_pm'];
  1687. $smcFunc['db_free_result']($request);
  1688. // Delete the actual messages.
  1689. deleteMessages($toDelete);
  1690. // Go back to their inbox.
  1691. redirectexit($context['current_label_redirect']);
  1692. }
  1693. // Build the link tree elements.
  1694. $context['linktree'][] = array(
  1695. 'url' => $scripturl . '?action=pm;sa=prune',
  1696. 'name' => $txt['pm_prune']
  1697. );
  1698. $context['sub_template'] = 'prune';
  1699. $context['page_title'] = $txt['pm_prune'];
  1700. }
  1701. /**
  1702. * This function handles adding, deleting and editing labels on messages.
  1703. */
  1704. function action_messagelabels()
  1705. {
  1706. global $txt, $context, $user_info, $scripturl, $smcFunc;
  1707. // Build the link tree elements...
  1708. $context['linktree'][] = array(
  1709. 'url' => $scripturl . '?action=pm;sa=manlabels',
  1710. 'name' => $txt['pm_manage_labels']
  1711. );
  1712. $context['page_title'] = $txt['pm_manage_labels'];
  1713. $context['sub_template'] = 'labels';
  1714. $the_labels = array();
  1715. // Add all existing labels to the array to save, slashing them as necessary...
  1716. foreach ($context['labels'] as $label)
  1717. {
  1718. if ($label['id'] != -1)
  1719. $the_labels[$label['id']] = $label['name'];
  1720. }
  1721. if (isset($_POST[$context['session_var']]))
  1722. {
  1723. checkSession('post');
  1724. // This will be for updating messages.
  1725. $message_changes = array();
  1726. $new_labels = array();
  1727. $rule_changes = array();
  1728. // Will most likely need this.
  1729. loadRules();
  1730. // Adding a new label?
  1731. if (isset($_POST['add']))
  1732. {
  1733. $_POST['label'] = strtr($smcFunc['htmlspecialchars'](trim($_POST['label'])), array(',' => '&#044;'));
  1734. if ($smcFunc['strlen']($_POST['label']) > 30)
  1735. $_POST['label'] = $smcFunc['substr']($_POST['label'], 0, 30);
  1736. if ($_POST['label'] != '')
  1737. $the_labels[] = $_POST['label'];
  1738. }
  1739. // Deleting an existing label?
  1740. elseif (isset($_POST['delete'], $_POST['delete_label']))
  1741. {
  1742. $i = 0;
  1743. foreach ($the_labels as $id => $name)
  1744. {
  1745. if (isset($_POST['delete_label'][$id]))
  1746. {
  1747. unset($the_labels[$id]);
  1748. $message_changes[$id] = true;
  1749. }
  1750. else
  1751. $new_labels[$id] = $i++;
  1752. }
  1753. }
  1754. // The hardest one to deal with... changes.
  1755. elseif (isset($_POST['save']) && !empty($_POST['label_name']))
  1756. {
  1757. $i = 0;
  1758. foreach ($the_labels as $id => $name)
  1759. {
  1760. if ($id == -1)
  1761. continue;
  1762. elseif (isset($_POST['label_name'][$id]))
  1763. {
  1764. $_POST['label_name'][$id] = trim(strtr($smcFunc['htmlspecialchars']($_POST['label_name'][$id]), array(',' => '&#044;')));
  1765. if ($smcFunc['strlen']($_POST['label_name'][$id]) > 30)
  1766. $_POST['label_name'][$id] = $smcFunc['substr']($_POST['label_name'][$id], 0, 30);
  1767. if ($_POST['label_name'][$id] != '')
  1768. {
  1769. $the_labels[(int) $id] = $_POST['label_name'][$id];
  1770. $new_labels[$id] = $i++;
  1771. }
  1772. else
  1773. {
  1774. unset($the_labels[(int) $id]);
  1775. $message_changes[(int) $id] = true;
  1776. }
  1777. }
  1778. else
  1779. $new_labels[$id] = $i++;
  1780. }
  1781. }
  1782. // Save the label status.
  1783. updateMemberData($user_info['id'], array('message_labels' => implode(',', $the_labels)));
  1784. // Update all the messages currently with any label changes in them!
  1785. if (!empty($message_changes))
  1786. {
  1787. $searchArray = array_keys($message_changes);
  1788. if (!empty($new_labels))
  1789. {
  1790. for ($i = max($searchArray) + 1, $n = max(array_keys($new_labels)); $i <= $n; $i++)
  1791. $searchArray[] = $i;
  1792. }
  1793. // Now find the messages to change.
  1794. $request = $smcFunc['db_query']('', '
  1795. SELECT id_pm, labels
  1796. FROM {db_prefix}pm_recipients
  1797. WHERE FIND_IN_SET({raw:find_label_implode}, labels) != 0
  1798. AND id_member = {int:current_member}',
  1799. array(
  1800. 'current_member' => $user_info['id'],
  1801. 'find_label_implode' => '\'' . implode('\', labels) != 0 OR FIND_IN_SET(\'', $searchArray) . '\'',
  1802. )
  1803. );
  1804. while ($row = $smcFunc['db_fetch_assoc']($request))
  1805. {
  1806. // Do the long task of updating them...
  1807. $toChange = explode(',', $row['labels']);
  1808. foreach ($toChange as $key => $value)
  1809. if (in_array($value, $searchArray))
  1810. {
  1811. if (isset($new_labels[$value]))
  1812. $toChange[$key] = $new_labels[$value];
  1813. else
  1814. unset($toChange[$key]);
  1815. }
  1816. if (empty($toChange))
  1817. $toChange[] = '-1';
  1818. // Update the message.
  1819. $smcFunc['db_query']('', '
  1820. UPDATE {db_prefix}pm_recipients
  1821. SET labels = {string:new_labels}
  1822. WHERE id_pm = {int:id_pm}
  1823. AND id_member = {int:current_member}',
  1824. array(
  1825. 'current_member' => $user_info['id'],
  1826. 'id_pm' => $row['id_pm'],
  1827. 'new_labels' => implode(',', array_unique($toChange)),
  1828. )
  1829. );
  1830. }
  1831. $smcFunc['db_free_result']($request);
  1832. // Now do the same the rules - check through each rule.
  1833. foreach ($context['rules'] as $k => $rule)
  1834. {
  1835. // Each action...
  1836. foreach ($rule['actions'] as $k2 => $action)
  1837. {
  1838. if ($action['t'] != 'lab' || !in_array($action['v'], $searchArray))
  1839. continue;
  1840. $rule_changes[] = $rule['id'];
  1841. // If we're here we have a label which is either changed or gone...
  1842. if (isset($new_labels[$action['v']]))
  1843. $context['rules'][$k]['actions'][$k2]['v'] = $new_labels[$action['v']];
  1844. else
  1845. unset($context['rules'][$k]['actions'][$k2]);
  1846. }
  1847. }
  1848. }
  1849. // If we have rules to change do so now.
  1850. if (!empty($rule_changes))
  1851. {
  1852. $rule_changes = array_unique($rule_changes);
  1853. // Update/delete as appropriate.
  1854. foreach ($rule_changes as $k => $id)
  1855. if (!empty($context['rules'][$id]['actions']))
  1856. {
  1857. $smcFunc['db_query']('', '
  1858. UPDATE {db_prefix}pm_rules
  1859. SET actions = {string:actions}
  1860. WHERE id_rule = {int:id_rule}
  1861. AND id_member = {int:current_member}',
  1862. array(
  1863. 'current_member' => $user_info['id'],
  1864. 'id_rule' => $id,
  1865. 'actions' => serialize($context['rules'][$id]['actions']),
  1866. )
  1867. );
  1868. unset($rule_changes[$k]);
  1869. }
  1870. // Anything left here means it's lost all actions...
  1871. if (!empty($rule_changes))
  1872. $smcFunc['db_query']('', '
  1873. DELETE FROM {db_prefix}pm_rules
  1874. WHERE id_rule IN ({array_int:rule_list})
  1875. AND id_member = {int:current_member}',
  1876. array(
  1877. 'current_member' => $user_info['id'],
  1878. 'rule_list' => $rule_changes,
  1879. )
  1880. );
  1881. }
  1882. // Make sure we're not caching this!
  1883. cache_put_data('labelCounts:' . $user_info['id'], null, 720);
  1884. // To make the changes appear right away, redirect.
  1885. redirectexit('action=pm;sa=manlabels');
  1886. }
  1887. }
  1888. /**
  1889. * Allows to edit Personal Message Settings.
  1890. *
  1891. * @uses ProfileOptions controller. (@todo refactor this.)
  1892. * @uses Profile template.
  1893. * @uses Profile language file.
  1894. */
  1895. function action_messagesettings()
  1896. {
  1897. global $txt, $user_settings, $user_info, $context, $smcFunc;
  1898. global $scripturl, $profile_vars, $cur_profile, $user_profile;
  1899. // We want them to submit back to here.
  1900. $context['profile_custom_submit_url'] = $scripturl . '?action=pm;sa=settings;save';
  1901. loadMemberData($user_info['id'], false, 'profile');
  1902. $cur_profile = $user_profile[$user_info['id']];
  1903. loadLanguage('Profile');
  1904. loadTemplate('Profile');
  1905. $context['page_title'] = $txt['pm_settings'];
  1906. $context['user']['is_owner'] = true;
  1907. $context['id_member'] = $user_info['id'];
  1908. $context['require_password'] = false;
  1909. $context['menu_item_selected'] = 'settings';
  1910. $context['submit_button_text'] = $txt['pm_settings'];
  1911. $context['profile_header_text'] = $txt['personal_messages'];
  1912. // Add our position to the linktree.
  1913. $context['linktree'][] = array(
  1914. 'url' => $scripturl . '?action=pm;sa=settings',
  1915. 'name' => $txt['pm_settings']
  1916. );
  1917. // Are they saving?
  1918. if (isset($_REQUEST['save']))
  1919. {
  1920. checkSession('post');
  1921. // Mimic what profile would do.
  1922. $_POST = htmltrim__recursive($_POST);
  1923. $_POST = htmlspecialchars__recursive($_POST);
  1924. // Save the fields.
  1925. require_once(SUBSDIR . '/Profile.subs.php');
  1926. saveProfileFields();
  1927. if (!empty($profile_vars))
  1928. updateMemberData($user_info['id'], $profile_vars);
  1929. }
  1930. // Load up the fields.
  1931. require_once(CONTROLLERDIR . '/ProfileOptions.controller.php');
  1932. action_pmprefs($user_info['id']);
  1933. }
  1934. /**
  1935. * Allows the user to report a personal message to an administrator.
  1936. *
  1937. * - In the first instance requires that the ID of the message to report is passed through $_GET.
  1938. * - It allows the user to report to either a particular administrator - or the whole admin team.
  1939. * - It will forward on a copy of the original message without allowing the reporter to make changes.
  1940. *
  1941. * @uses report_message sub-template.
  1942. */
  1943. function action_reportmessage()
  1944. {
  1945. global $txt, $context, $scripturl;
  1946. global $user_info, $language, $modSettings, $smcFunc;
  1947. // Check that this feature is even enabled!
  1948. if (empty($modSettings['enableReportPM']) || empty($_REQUEST['pmsg']))
  1949. fatal_lang_error('no_access', false);
  1950. $pmsg = (int) $_REQUEST['pmsg'];
  1951. if (!isAccessiblePM($pmsg, 'inbox'))
  1952. fatal_lang_error('no_access', false);
  1953. $context['pm_id'] = $pmsg;
  1954. $context['page_title'] = $txt['pm_report_title'];
  1955. // If we're here, just send the user to the template, with a few useful context bits.
  1956. if (!isset($_POST['report']))
  1957. {
  1958. $context['sub_template'] = 'report_message';
  1959. // @todo I don't like being able to pick who to send it to. Favoritism, etc. sucks.
  1960. // Now, get all the administrators.
  1961. $request = $smcFunc['db_query']('', '
  1962. SELECT id_member, real_name
  1963. FROM {db_prefix}members
  1964. WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
  1965. ORDER BY real_name',
  1966. array(
  1967. 'admin_group' => 1,
  1968. )
  1969. );
  1970. $context['admins'] = array();
  1971. while ($row = $smcFunc['db_fetch_assoc']($request))
  1972. $context['admins'][$row['id_member']] = $row['real_name'];
  1973. $smcFunc['db_free_result']($request);
  1974. // How many admins in total?
  1975. $context['admin_count'] = count($context['admins']);
  1976. }
  1977. // Otherwise, let's get down to the sending stuff.
  1978. else
  1979. {
  1980. // Check the session before proceeding any further!
  1981. checkSession('post');
  1982. // First, pull out the message contents, and verify it actually went to them!
  1983. $request = $smcFunc['db_query']('', '
  1984. SELECT pm.subject, pm.body, pm.msgtime, pm.id_member_from, IFNULL(m.real_name, pm.from_name) AS sender_name
  1985. FROM {db_prefix}personal_messages AS pm
  1986. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
  1987. LEFT JOIN {db_prefix}members AS m ON (m.id_member = pm.id_member_from)
  1988. WHERE pm.id_pm = {int:id_pm}
  1989. AND pmr.id_member = {int:current_member}
  1990. AND pmr.deleted = {int:not_deleted}
  1991. LIMIT 1',
  1992. array(
  1993. 'current_member' => $user_info['id'],
  1994. 'id_pm' => $context['pm_id'],
  1995. 'not_deleted' => 0,
  1996. )
  1997. );
  1998. // Can only be a hacker here!
  1999. if ($smcFunc['db_num_rows']($request) == 0)
  2000. fatal_lang_error('no_access', false);
  2001. list ($subject, $body, $time, $memberFromID, $memberFromName) = $smcFunc['db_fetch_row']($request);
  2002. $smcFunc['db_free_result']($request);
  2003. // Remove the line breaks...
  2004. $body = preg_replace('~<br ?/?' . '>~i', "\n", $body);
  2005. // Get any other recipients of the email.
  2006. $request = $smcFunc['db_query']('', '
  2007. SELECT mem_to.id_member AS id_member_to, mem_to.real_name AS to_name, pmr.bcc
  2008. FROM {db_prefix}pm_recipients AS pmr
  2009. LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
  2010. WHERE pmr.id_pm = {int:id_pm}
  2011. AND pmr.id_member != {int:current_member}',
  2012. array(
  2013. 'current_member' => $user_info['id'],
  2014. 'id_pm' => $context['pm_id'],
  2015. )
  2016. );
  2017. $recipients = array();
  2018. $hidden_recipients = 0;
  2019. while ($row = $smcFunc['db_fetch_assoc']($request))
  2020. {
  2021. // If it's hidden still don't reveal their names - privacy after all ;)
  2022. if ($row['bcc'])
  2023. $hidden_recipients++;
  2024. else
  2025. $recipients[] = '[url=' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . ']' . $row['to_name'] . '[/url]';
  2026. }
  2027. $smcFunc['db_free_result']($request);
  2028. if ($hidden_recipients)
  2029. $recipients[] = sprintf($txt['pm_report_pm_hidden'], $hidden_recipients);
  2030. // Now let's get out and loop through the admins.
  2031. $request = $smcFunc['db_query']('', '
  2032. SELECT id_member, real_name, lngfile
  2033. FROM {db_prefix}members
  2034. WHERE (id_group = {int:admin_id} OR FIND_IN_SET({int:admin_id}, additional_groups) != 0)
  2035. ' . (empty($_POST['id_admin']) ? '' : 'AND id_member = {int:specific_admin}') . '
  2036. ORDER BY lngfile',
  2037. array(
  2038. 'admin_id' => 1,
  2039. 'specific_admin' => isset($_POST['id_admin']) ? (int) $_POST['id_admin'] : 0,
  2040. )
  2041. );
  2042. // Maybe we shouldn't advertise this?
  2043. if ($smcFunc['db_num_rows']($request) == 0)
  2044. fatal_lang_error('no_access', false);
  2045. $memberFromName = un_htmlspecialchars($memberFromName);
  2046. // Prepare the message storage array.
  2047. $messagesToSend = array();
  2048. // Loop through each admin, and add them to the right language pile...
  2049. while ($row = $smcFunc['db_fetch_assoc']($request))
  2050. {
  2051. // Need to send in the correct language!
  2052. $cur_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
  2053. if (!isset($messagesToSend[$cur_language]))
  2054. {
  2055. loadLanguage('PersonalMessage', $cur_language, false);
  2056. // Make the body.
  2057. $report_body = str_replace(array('{REPORTER}', '{SENDER}'), array(un_htmlspecialchars($user_info['name']), $memberFromName), $txt['pm_report_pm_user_sent']);
  2058. $report_body .= "\n" . '[b]' . $_POST['reason'] . '[/b]' . "\n\n";
  2059. if (!empty($recipients))
  2060. $report_body .= $txt['pm_report_pm_other_recipients'] . ' ' . implode(', ', $recipients) . "\n\n";
  2061. $report_body .= $txt['pm_report_pm_unedited_below'] . "\n" . '[quote author=' . (empty($memberFromID) ? '&quot;' . $memberFromName . '&quot;' : $memberFromName . ' link=action=profile;u=' . $memberFromID . ' date=' . $time) . ']' . "\n" . un_htmlspecialchars($body) . '[/quote]';
  2062. // Plonk it in the array ;)
  2063. $messagesToSend[$cur_language] = array(
  2064. 'subject' => ($smcFunc['strpos']($subject, $txt['pm_report_pm_subject']) === false ? $txt['pm_report_pm_subject'] : '') . un_htmlspecialchars($subject),
  2065. 'body' => $report_body,
  2066. 'recipients' => array(
  2067. 'to' => array(),
  2068. 'bcc' => array()
  2069. ),
  2070. );
  2071. }
  2072. // Add them to the list.
  2073. $messagesToSend[$cur_language]['recipients']['to'][$row['id_member']] = $row['id_member'];
  2074. }
  2075. $smcFunc['db_free_result']($request);
  2076. // Send a different email for each language.
  2077. foreach ($messagesToSend as $lang => $message)
  2078. sendpm($message['recipients'], $message['subject'], $message['body']);
  2079. // Give the user their own language back!
  2080. if (!empty($modSettings['userLanguage']))
  2081. loadLanguage('PersonalMessage', '', false);
  2082. // Leave them with a template.
  2083. $context['sub_template'] = 'report_message_complete';
  2084. }
  2085. }
  2086. /**
  2087. * List all rules, and allow adding/entering etc...
  2088. */
  2089. function action_messagerules()
  2090. {
  2091. global $txt, $context, $user_info, $scripturl, $smcFunc;
  2092. // The link tree - gotta have this :o
  2093. $context['linktree'][] = array(
  2094. 'url' => $scripturl . '?action=pm;sa=manrules',
  2095. 'name' => $txt['pm_manage_rules']
  2096. );
  2097. $context['page_title'] = $txt['pm_manage_rules'];
  2098. $context['sub_template'] = 'rules';
  2099. // Load them... load them!!
  2100. loadRules();
  2101. // Likely to need all the groups!
  2102. $request = $smcFunc['db_query']('', '
  2103. SELECT mg.id_group, mg.group_name, IFNULL(gm.id_member, 0) AS can_moderate, mg.hidden
  2104. FROM {db_prefix}membergroups AS mg
  2105. LEFT JOIN {db_prefix}group_moderators AS gm ON (gm.id_group = mg.id_group AND gm.id_member = {int:current_member})
  2106. WHERE mg.min_posts = {int:min_posts}
  2107. AND mg.id_group != {int:moderator_group}
  2108. AND mg.hidden = {int:not_hidden}
  2109. ORDER BY mg.group_name',
  2110. array(
  2111. 'current_member' => $user_info['id'],
  2112. 'min_posts' => -1,
  2113. 'moderator_group' => 3,
  2114. 'not_hidden' => 0,
  2115. )
  2116. );
  2117. $context['groups'] = array();
  2118. while ($row = $smcFunc['db_fetch_assoc']($request))
  2119. {
  2120. // Hide hidden groups!
  2121. if ($row['hidden'] && !$row['can_moderate'] && !allowedTo('manage_membergroups'))
  2122. continue;
  2123. $context['groups'][$row['id_group']] = $row['group_name'];
  2124. }
  2125. $smcFunc['db_free_result']($request);
  2126. // Applying all rules?
  2127. if (isset($_GET['apply']))
  2128. {
  2129. checkSession('get');
  2130. applyRules(true);
  2131. redirectexit('action=pm;sa=manrules');
  2132. }
  2133. // Editing a specific one?
  2134. if (isset($_GET['add']))
  2135. {
  2136. $context['rid'] = isset($_GET['rid']) && isset($context['rules'][$_GET['rid']])? (int) $_GET['rid'] : 0;
  2137. $context['sub_template'] = 'add_rule';
  2138. // Current rule information...
  2139. if ($context['rid'])
  2140. {
  2141. $context['rule'] = $context['rules'][$context['rid']];
  2142. $members = array();
  2143. // Need to get member names!
  2144. foreach ($context['rule']['criteria'] as $k => $criteria)
  2145. if ($criteria['t'] == 'mid' && !empty($criteria['v']))
  2146. $members[(int) $criteria['v']] = $k;
  2147. if (!empty($members))
  2148. {
  2149. $request = $smcFunc['db_query']('', '
  2150. SELECT id_member, member_name
  2151. FROM {db_prefix}members
  2152. WHERE id_member IN ({array_int:member_list})',
  2153. array(
  2154. 'member_list' => array_keys($members),
  2155. )
  2156. );
  2157. while ($row = $smcFunc['db_fetch_assoc']($request))
  2158. $context['rule']['criteria'][$members[$row['id_member']]]['v'] = $row['member_name'];
  2159. $smcFunc['db_free_result']($request);
  2160. }
  2161. }
  2162. else
  2163. $context['rule'] = array(
  2164. 'id' => '',
  2165. 'name' => '',
  2166. 'criteria' => array(),
  2167. 'actions' => array(),
  2168. 'logic' => 'and',
  2169. );
  2170. }
  2171. // Saving?
  2172. elseif (isset($_GET['save']))
  2173. {
  2174. checkSession('post');
  2175. $context['rid'] = isset($_GET['rid']) && isset($context['rules'][$_GET['rid']])? (int) $_GET['rid'] : 0;
  2176. // Name is easy!
  2177. $ruleName = $smcFunc['htmlspecialchars'](trim($_POST['rule_name']));
  2178. if (empty($ruleName))
  2179. fatal_lang_error('pm_rule_no_name', false);
  2180. // Sanity check...
  2181. if (empty($_POST['ruletype']) || empty($_POST['acttype']))
  2182. fatal_lang_error('pm_rule_no_criteria', false);
  2183. // Let's do the criteria first - it's also hardest!
  2184. $criteria = array();
  2185. foreach ($_POST['ruletype'] as $ind => $type)
  2186. {
  2187. // Check everything is here...
  2188. if ($type == 'gid' && (!isset($_POST['ruledefgroup'][$ind]) || !isset($context['groups'][$_POST['ruledefgroup'][$ind]])))
  2189. continue;
  2190. elseif ($type != 'bud' && !isset($_POST['ruledef'][$ind]))
  2191. continue;
  2192. // Members need to be found.
  2193. if ($type == 'mid')
  2194. {
  2195. $name = trim($_POST['ruledef'][$ind]);
  2196. $request = $smcFunc['db_query']('', '
  2197. SELECT id_member
  2198. FROM {db_prefix}members
  2199. WHERE real_name = {string:member_name}
  2200. OR member_name = {string:member_name}',
  2201. array(
  2202. 'member_name' => $name,
  2203. )
  2204. );
  2205. if ($smcFunc['db_num_rows']($request) == 0)
  2206. continue;
  2207. list ($memID) = $smcFunc['db_fetch_row']($request);
  2208. $smcFunc['db_free_result']($request);
  2209. $criteria[] = array('t' => 'mid', 'v' => $memID);
  2210. }
  2211. elseif ($type == 'bud')
  2212. $criteria[] = array('t' => 'bud', 'v' => 1);
  2213. elseif ($type == 'gid')
  2214. $criteria[] = array('t' => 'gid', 'v' => (int) $_POST['ruledefgroup'][$ind]);
  2215. elseif (in_array($type, array('sub', 'msg')) && trim($_POST['ruledef'][$ind]) != '')
  2216. $criteria[] = array('t' => $type, 'v' => $smcFunc['htmlspecialchars'](trim($_POST['ruledef'][$ind])));
  2217. }
  2218. // Also do the actions!
  2219. $actions = array();
  2220. $doDelete = 0;
  2221. $isOr = $_POST['rule_logic'] == 'or' ? 1 : 0;
  2222. foreach ($_POST['acttype'] as $ind => $type)
  2223. {
  2224. // Picking a valid label?
  2225. if ($type == 'lab' && (!isset($_POST['labdef'][$ind]) || !isset($context['labels'][$_POST['labdef'][$ind] - 1])))
  2226. continue;
  2227. // Record what we're doing.
  2228. if ($type == 'del')
  2229. $doDelete = 1;
  2230. elseif ($type == 'lab')
  2231. $actions[] = array('t' => 'lab', 'v' => (int) $_POST['labdef'][$ind] - 1);
  2232. }
  2233. if (empty($criteria) || (empty($actions) && !$doDelete))
  2234. fatal_lang_error('pm_rule_no_criteria', false);
  2235. // What are we storing?
  2236. $criteria = serialize($criteria);
  2237. $actions = serialize($actions);
  2238. // Create the rule?
  2239. if (empty($context['rid']))
  2240. $smcFunc['db_insert']('',
  2241. '{db_prefix}pm_rules',
  2242. array(
  2243. 'id_member' => 'int', 'rule_name' => 'string', 'criteria' => 'string', 'actions' => 'string',
  2244. 'delete_pm' => 'int', 'is_or' => 'int',
  2245. ),
  2246. array(
  2247. $user_info['id'], $ruleName, $criteria, $actions, $doDelete, $isOr,
  2248. ),
  2249. array('id_rule')
  2250. );
  2251. else
  2252. $smcFunc['db_query']('', '
  2253. UPDATE {db_prefix}pm_rules
  2254. SET rule_name = {string:rule_name}, criteria = {string:criteria}, actions = {string:actions},
  2255. delete_pm = {int:delete_pm}, is_or = {int:is_or}
  2256. WHERE id_rule = {int:id_rule}
  2257. AND id_member = {int:current_member}',
  2258. array(
  2259. 'current_member' => $user_info['id'],
  2260. 'delete_pm' => $doDelete,
  2261. 'is_or' => $isOr,
  2262. 'id_rule' => $context['rid'],
  2263. 'rule_name' => $ruleName,
  2264. 'criteria' => $criteria,
  2265. 'actions' => $actions,
  2266. )
  2267. );
  2268. redirectexit('action=pm;sa=manrules');
  2269. }
  2270. // Deleting?
  2271. elseif (isset($_POST['delselected']) && !empty($_POST['delrule']))
  2272. {
  2273. checkSession('post');
  2274. $toDelete = array();
  2275. foreach ($_POST['delrule'] as $k => $v)
  2276. $toDelete[] = (int) $k;
  2277. if (!empty($toDelete))
  2278. $smcFunc['db_query']('', '
  2279. DELETE FROM {db_prefix}pm_rules
  2280. WHERE id_rule IN ({array_int:delete_list})
  2281. AND id_member = {int:current_member}',
  2282. array(
  2283. 'current_member' => $user_info['id'],
  2284. 'delete_list' => $toDelete,
  2285. )
  2286. );
  2287. redirectexit('action=pm;sa=manrules');
  2288. }
  2289. }
  2290. /**
  2291. * This will apply rules to all unread messages.
  2292. * If all_messages is set will, clearly, do it to all!
  2293. *
  2294. * @param bool $all_messages = false
  2295. */
  2296. function applyRules($all_messages = false)
  2297. {
  2298. global $user_info, $smcFunc, $context, $options;
  2299. // Want this - duh!
  2300. loadRules();
  2301. // No rules?
  2302. if (empty($context['rules']))
  2303. return;
  2304. // Just unread ones?
  2305. $ruleQuery = $all_messages ? '' : ' AND pmr.is_new = 1';
  2306. // @todo Apply all should have timeout protection!
  2307. // Get all the messages that match this.
  2308. $request = $smcFunc['db_query']('', '
  2309. SELECT
  2310. pmr.id_pm, pm.id_member_from, pm.subject, pm.body, mem.id_group, pmr.labels
  2311. FROM {db_prefix}pm_recipients AS pmr
  2312. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  2313. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = pm.id_member_from)
  2314. WHERE pmr.id_member = {int:current_member}
  2315. AND pmr.deleted = {int:not_deleted}
  2316. ' . $ruleQuery,
  2317. array(
  2318. 'current_member' => $user_info['id'],
  2319. 'not_deleted' => 0,
  2320. )
  2321. );
  2322. $actions = array();
  2323. while ($row = $smcFunc['db_fetch_assoc']($request))
  2324. {
  2325. foreach ($context['rules'] as $rule)
  2326. {
  2327. $match = false;
  2328. // Loop through all the criteria hoping to make a match.
  2329. foreach ($rule['criteria'] as $criterium)
  2330. {
  2331. if (($criterium['t'] == 'mid' && $criterium['v'] == $row['id_member_from']) || ($criterium['t'] == 'gid' && $criterium['v'] == $row['id_group']) || ($criterium['t'] == 'sub' && strpos($row['subject'], $criterium['v']) !== false) || ($criterium['t'] == 'msg' && strpos($row['body'], $criterium['v']) !== false))
  2332. $match = true;
  2333. // If we're adding and one criteria don't match then we stop!
  2334. elseif ($rule['logic'] == 'and')
  2335. {
  2336. $match = false;
  2337. break;
  2338. }
  2339. }
  2340. // If we have a match the rule must be true - act!
  2341. if ($match)
  2342. {
  2343. if ($rule['delete'])
  2344. $actions['deletes'][] = $row['id_pm'];
  2345. else
  2346. {
  2347. foreach ($rule['actions'] as $ruleAction)
  2348. {
  2349. if ($ruleAction['t'] == 'lab')
  2350. {
  2351. // Get a basic pot started!
  2352. if (!isset($actions['labels'][$row['id_pm']]))
  2353. $actions['labels'][$row['id_pm']] = empty($row['labels']) ? array() : explode(',', $row['labels']);
  2354. $actions['labels'][$row['id_pm']][] = $ruleAction['v'];
  2355. }
  2356. }
  2357. }
  2358. }
  2359. }
  2360. }
  2361. $smcFunc['db_free_result']($request);
  2362. // Deletes are easy!
  2363. if (!empty($actions['deletes']))
  2364. deleteMessages($actions['deletes']);
  2365. // Relabel?
  2366. if (!empty($actions['labels']))
  2367. {
  2368. foreach ($actions['labels'] as $pm => $labels)
  2369. {
  2370. // Quickly check each label is valid!
  2371. $realLabels = array();
  2372. foreach ($context['labels'] as $label)
  2373. if (in_array($label['id'], $labels) && ($label['id'] != -1 || empty($options['pm_remove_inbox_label'])))
  2374. $realLabels[] = $label['id'];
  2375. $smcFunc['db_query']('', '
  2376. UPDATE {db_prefix}pm_recipients
  2377. SET labels = {string:new_labels}
  2378. WHERE id_pm = {int:id_pm}
  2379. AND id_member = {int:current_member}',
  2380. array(
  2381. 'current_member' => $user_info['id'],
  2382. 'id_pm' => $pm,
  2383. 'new_labels' => empty($realLabels) ? '' : implode(',', $realLabels),
  2384. )
  2385. );
  2386. }
  2387. }
  2388. }
  2389. /**
  2390. * Load up all the rules for the current user.
  2391. *
  2392. * @param bool $reload = false
  2393. */
  2394. function loadRules($reload = false)
  2395. {
  2396. global $user_info, $context, $smcFunc;
  2397. if (isset($context['rules']) && !$reload)
  2398. return;
  2399. $request = $smcFunc['db_query']('', '
  2400. SELECT
  2401. id_rule, rule_name, criteria, actions, delete_pm, is_or
  2402. FROM {db_prefix}pm_rules
  2403. WHERE id_member = {int:current_member}',
  2404. array(
  2405. 'current_member' => $user_info['id'],
  2406. )
  2407. );
  2408. $context['rules'] = array();
  2409. // Simply fill in the data!
  2410. while ($row = $smcFunc['db_fetch_assoc']($request))
  2411. {
  2412. $context['rules'][$row['id_rule']] = array(
  2413. 'id' => $row['id_rule'],
  2414. 'name' => $row['rule_name'],
  2415. 'criteria' => unserialize($row['criteria']),
  2416. 'actions' => unserialize($row['actions']),
  2417. 'delete' => $row['delete_pm'],
  2418. 'logic' => $row['is_or'] ? 'or' : 'and',
  2419. );
  2420. if ($row['delete_pm'])
  2421. $context['rules'][$row['id_rule']]['actions'][] = array('t' => 'del', 'v' => 1);
  2422. }
  2423. $smcFunc['db_free_result']($request);
  2424. }