PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/sources/controllers/MergeTopics.controller.php

https://github.com/Arantor/Elkarte
PHP | 826 lines | 636 code | 77 blank | 113 comment | 78 complexity | 9cf62f17b85ad6b3b8ce4cca5f1d825f 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. * Handle merging of topics
  16. *
  17. * Original module by Mach8 - We'll never forget you.
  18. */
  19. if (!defined('ELKARTE'))
  20. die('No access...');
  21. /**
  22. * Merges two or more topics into one topic.
  23. * delegates to the other functions (based on the URL parameter sa).
  24. * loads the MergeTopics template.
  25. * requires the merge_any permission.
  26. * is accessed with ?action=mergetopics.
  27. */
  28. function action_mergetopics()
  29. {
  30. // Load the template....
  31. loadTemplate('MergeTopics');
  32. $subActions = array(
  33. 'done' => 'action_mergeDone',
  34. 'execute' => 'action_mergeExecute',
  35. 'index' => 'action_mergeIndex',
  36. 'options' => 'action_mergeExecute',
  37. );
  38. // ?action=mergetopics;sa=LETSBREAKIT won't work, sorry.
  39. if (empty($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
  40. action_mergeIndex();
  41. else
  42. $subActions[$_REQUEST['sa']]();
  43. }
  44. /**
  45. * Allows to pick a topic to merge the current topic with.
  46. * is accessed with ?action=mergetopics;sa=index
  47. * default sub action for ?action=mergetopics.
  48. * uses 'merge' sub template of the MergeTopics template.
  49. * allows to set a different target board.
  50. */
  51. function action_mergeIndex()
  52. {
  53. global $txt, $board, $context, $smcFunc;
  54. global $scripturl, $topic, $user_info, $modSettings;
  55. if (!isset($_GET['from']))
  56. fatal_lang_error('no_access', false);
  57. $_GET['from'] = (int) $_GET['from'];
  58. $_REQUEST['targetboard'] = isset($_REQUEST['targetboard']) ? (int) $_REQUEST['targetboard'] : $board;
  59. $context['target_board'] = $_REQUEST['targetboard'];
  60. // Prepare a handy query bit for approval...
  61. if ($modSettings['postmod_active'])
  62. {
  63. $can_approve_boards = boardsAllowedTo('approve_posts');
  64. $onlyApproved = $can_approve_boards !== array(0) && !in_array($_REQUEST['targetboard'], $can_approve_boards);
  65. }
  66. else
  67. $onlyApproved = false;
  68. // How many topics are on this board? (used for paging.)
  69. $request = $smcFunc['db_query']('', '
  70. SELECT COUNT(*)
  71. FROM {db_prefix}topics AS t
  72. WHERE t.id_board = {int:id_board}' . ($onlyApproved ? '
  73. AND t.approved = {int:is_approved}' : ''),
  74. array(
  75. 'id_board' => $_REQUEST['targetboard'],
  76. 'is_approved' => 1,
  77. )
  78. );
  79. list ($topiccount) = $smcFunc['db_fetch_row']($request);
  80. $smcFunc['db_free_result']($request);
  81. // Make the page list.
  82. $context['page_index'] = constructPageIndex($scripturl . '?action=mergetopics;from=' . $_GET['from'] . ';targetboard=' . $_REQUEST['targetboard'] . ';board=' . $board . '.%1$d', $_REQUEST['start'], $topiccount, $modSettings['defaultMaxTopics'], true);
  83. // Get the topic's subject.
  84. $request = $smcFunc['db_query']('', '
  85. SELECT m.subject
  86. FROM {db_prefix}topics AS t
  87. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  88. WHERE t.id_topic = {int:id_topic}
  89. AND t.id_board = {int:current_board}' . ($onlyApproved ? '
  90. AND t.approved = {int:is_approved}' : '') . '
  91. LIMIT 1',
  92. array(
  93. 'current_board' => $board,
  94. 'id_topic' => $_GET['from'],
  95. 'is_approved' => 1,
  96. )
  97. );
  98. if ($smcFunc['db_num_rows']($request) == 0)
  99. fatal_lang_error('no_board');
  100. list ($subject) = $smcFunc['db_fetch_row']($request);
  101. $smcFunc['db_free_result']($request);
  102. // Tell the template a few things..
  103. $context['origin_topic'] = $_GET['from'];
  104. $context['origin_subject'] = $subject;
  105. $context['origin_js_subject'] = addcslashes(addslashes($subject), '/');
  106. $context['page_title'] = $txt['merge'];
  107. // Check which boards you have merge permissions on.
  108. $merge_boards = boardsAllowedTo('merge_any');
  109. if (empty($merge_boards))
  110. fatal_lang_error('cannot_merge_any', 'user');
  111. // Get a list of boards they can navigate to to merge.
  112. $request = $smcFunc['db_query']('order_by_board_order', '
  113. SELECT b.id_board, b.name AS board_name, c.name AS cat_name
  114. FROM {db_prefix}boards AS b
  115. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  116. WHERE {query_see_board}' . (!in_array(0, $merge_boards) ? '
  117. AND b.id_board IN ({array_int:merge_boards})' : ''),
  118. array(
  119. 'merge_boards' => $merge_boards,
  120. )
  121. );
  122. $context['boards'] = array();
  123. while ($row = $smcFunc['db_fetch_assoc']($request))
  124. $context['boards'][] = array(
  125. 'id' => $row['id_board'],
  126. 'name' => $row['board_name'],
  127. 'category' => $row['cat_name']
  128. );
  129. $smcFunc['db_free_result']($request);
  130. // Get some topics to merge it with.
  131. $request = $smcFunc['db_query']('', '
  132. SELECT t.id_topic, m.subject, m.id_member, IFNULL(mem.real_name, m.poster_name) AS poster_name
  133. FROM {db_prefix}topics AS t
  134. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  135. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  136. WHERE t.id_board = {int:id_board}
  137. AND t.id_topic != {int:id_topic}' . ($onlyApproved ? '
  138. AND t.approved = {int:is_approved}' : '') . '
  139. ORDER BY {raw:sort}
  140. LIMIT {int:offset}, {int:limit}',
  141. array(
  142. 'id_board' => $_REQUEST['targetboard'],
  143. 'id_topic' => $_GET['from'],
  144. 'sort' => (!empty($modSettings['enableStickyTopics']) ? 't.is_sticky DESC, ' : '') . 't.id_last_msg DESC',
  145. 'offset' => $_REQUEST['start'],
  146. 'limit' => $modSettings['defaultMaxTopics'],
  147. 'is_approved' => 1,
  148. )
  149. );
  150. $context['topics'] = array();
  151. while ($row = $smcFunc['db_fetch_assoc']($request))
  152. {
  153. censorText($row['subject']);
  154. $context['topics'][] = array(
  155. 'id' => $row['id_topic'],
  156. 'poster' => array(
  157. 'id' => $row['id_member'],
  158. 'name' => $row['poster_name'],
  159. 'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
  160. 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" target="_blank" class="new_win">' . $row['poster_name'] . '</a>'
  161. ),
  162. 'subject' => $row['subject'],
  163. 'js_subject' => addcslashes(addslashes($row['subject']), '/')
  164. );
  165. }
  166. $smcFunc['db_free_result']($request);
  167. if (empty($context['topics']) && count($context['boards']) <= 1)
  168. fatal_lang_error('merge_need_more_topics');
  169. $context['sub_template'] = 'merge';
  170. }
  171. /**
  172. * Set merge options and do the actual merge of two or more topics.
  173. *
  174. * the merge options screen:
  175. * * shows topics to be merged and allows to set some merge options.
  176. * * is accessed by ?action=mergetopics;sa=options.and can also internally be called by action_quickmod().
  177. * * uses 'merge_extra_options' sub template of the MergeTopics template.
  178. *
  179. * the actual merge:
  180. * * is accessed with ?action=mergetopics;sa=execute.
  181. * * updates the statistics to reflect the merge.
  182. * * logs the action in the moderation log.
  183. * * sends a notification is sent to all users monitoring this topic.
  184. * * redirects to ?action=mergetopics;sa=done.
  185. * @param array $topics = array()
  186. */
  187. function action_mergeExecute($topics = array())
  188. {
  189. global $user_info, $txt, $context, $scripturl;
  190. global $smcFunc, $language, $modSettings;
  191. // Check the session.
  192. checkSession('request');
  193. // Handle URLs from action_mergeIndex.
  194. if (!empty($_GET['from']) && !empty($_GET['to']))
  195. $topics = array((int) $_GET['from'], (int) $_GET['to']);
  196. // If we came from a form, the topic IDs came by post.
  197. if (!empty($_POST['topics']) && is_array($_POST['topics']))
  198. $topics = $_POST['topics'];
  199. // There's nothing to merge with just one topic...
  200. if (empty($topics) || !is_array($topics) || count($topics) == 1)
  201. fatal_lang_error('merge_need_more_topics');
  202. // Make sure every topic is numeric, or some nasty things could be done with the DB.
  203. foreach ($topics as $id => $topic)
  204. $topics[$id] = (int) $topic;
  205. // Joy of all joys, make sure they're not pi**ing about with unapproved topics they can't see :P
  206. if ($modSettings['postmod_active'])
  207. $can_approve_boards = boardsAllowedTo('approve_posts');
  208. // Get info about the topics and polls that will be merged.
  209. $request = $smcFunc['db_query']('', '
  210. SELECT
  211. t.id_topic, t.id_board, t.id_poll, t.num_views, t.is_sticky, t.approved, t.num_replies, t.unapproved_posts,
  212. m1.subject, m1.poster_time AS time_started, IFNULL(mem1.id_member, 0) AS id_member_started, IFNULL(mem1.real_name, m1.poster_name) AS name_started,
  213. m2.poster_time AS time_updated, IFNULL(mem2.id_member, 0) AS id_member_updated, IFNULL(mem2.real_name, m2.poster_name) AS name_updated
  214. FROM {db_prefix}topics AS t
  215. INNER JOIN {db_prefix}messages AS m1 ON (m1.id_msg = t.id_first_msg)
  216. INNER JOIN {db_prefix}messages AS m2 ON (m2.id_msg = t.id_last_msg)
  217. LEFT JOIN {db_prefix}members AS mem1 ON (mem1.id_member = m1.id_member)
  218. LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = m2.id_member)
  219. WHERE t.id_topic IN ({array_int:topic_list})
  220. ORDER BY t.id_first_msg
  221. LIMIT ' . count($topics),
  222. array(
  223. 'topic_list' => $topics,
  224. )
  225. );
  226. if ($smcFunc['db_num_rows']($request) < 2)
  227. fatal_lang_error('no_topic_id');
  228. $num_views = 0;
  229. $is_sticky = 0;
  230. $boardTotals = array();
  231. $boards = array();
  232. $polls = array();
  233. $firstTopic = 0;
  234. while ($row = $smcFunc['db_fetch_assoc']($request))
  235. {
  236. // Make a note for the board counts...
  237. if (!isset($boardTotals[$row['id_board']]))
  238. $boardTotals[$row['id_board']] = array(
  239. 'posts' => 0,
  240. 'topics' => 0,
  241. 'unapproved_posts' => 0,
  242. 'unapproved_topics' => 0
  243. );
  244. // We can't see unapproved topics here?
  245. if ($modSettings['postmod_active'] && !$row['approved'] && $can_approve_boards != array(0) && in_array($row['id_board'], $can_approve_boards))
  246. continue;
  247. elseif (!$row['approved'])
  248. $boardTotals[$row['id_board']]['unapproved_topics']++;
  249. else
  250. $boardTotals[$row['id_board']]['topics']++;
  251. $boardTotals[$row['id_board']]['unapproved_posts'] += $row['unapproved_posts'];
  252. $boardTotals[$row['id_board']]['posts'] += $row['num_replies'] + ($row['approved'] ? 1 : 0);
  253. $topic_data[$row['id_topic']] = array(
  254. 'id' => $row['id_topic'],
  255. 'board' => $row['id_board'],
  256. 'poll' => $row['id_poll'],
  257. 'num_views' => $row['num_views'],
  258. 'subject' => $row['subject'],
  259. 'started' => array(
  260. 'time' => timeformat($row['time_started']),
  261. 'timestamp' => forum_time(true, $row['time_started']),
  262. 'href' => empty($row['id_member_started']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_started'],
  263. 'link' => empty($row['id_member_started']) ? $row['name_started'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_started'] . '">' . $row['name_started'] . '</a>'
  264. ),
  265. 'updated' => array(
  266. 'time' => timeformat($row['time_updated']),
  267. 'timestamp' => forum_time(true, $row['time_updated']),
  268. 'href' => empty($row['id_member_updated']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_updated'],
  269. 'link' => empty($row['id_member_updated']) ? $row['name_updated'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['name_updated'] . '</a>'
  270. )
  271. );
  272. $num_views += $row['num_views'];
  273. $boards[] = $row['id_board'];
  274. // If there's no poll, id_poll == 0...
  275. if ($row['id_poll'] > 0)
  276. $polls[] = $row['id_poll'];
  277. // Store the id_topic with the lowest id_first_msg.
  278. if (empty($firstTopic))
  279. $firstTopic = $row['id_topic'];
  280. $is_sticky = max($is_sticky, $row['is_sticky']);
  281. }
  282. $smcFunc['db_free_result']($request);
  283. // If we didn't get any topics then they've been messing with unapproved stuff.
  284. if (empty($topic_data))
  285. fatal_lang_error('no_topic_id');
  286. $boards = array_values(array_unique($boards));
  287. // The parameters of action_mergeExecute were set, so this must've been an internal call.
  288. if (!empty($topics))
  289. {
  290. isAllowedTo('merge_any', $boards);
  291. loadTemplate('MergeTopics');
  292. }
  293. // Get the boards a user is allowed to merge in.
  294. $merge_boards = boardsAllowedTo('merge_any');
  295. if (empty($merge_boards))
  296. fatal_lang_error('cannot_merge_any', 'user');
  297. // Make sure they can see all boards....
  298. $request = $smcFunc['db_query']('', '
  299. SELECT b.id_board
  300. FROM {db_prefix}boards AS b
  301. WHERE b.id_board IN ({array_int:boards})
  302. AND {query_see_board}' . (!in_array(0, $merge_boards) ? '
  303. AND b.id_board IN ({array_int:merge_boards})' : '') . '
  304. LIMIT ' . count($boards),
  305. array(
  306. 'boards' => $boards,
  307. 'merge_boards' => $merge_boards,
  308. )
  309. );
  310. // If the number of boards that's in the output isn't exactly the same as we've put in there, you're in trouble.
  311. if ($smcFunc['db_num_rows']($request) != count($boards))
  312. fatal_lang_error('no_board');
  313. $smcFunc['db_free_result']($request);
  314. if (empty($_REQUEST['sa']) || $_REQUEST['sa'] == 'options')
  315. {
  316. if (count($polls) > 1)
  317. {
  318. $request = $smcFunc['db_query']('', '
  319. SELECT t.id_topic, t.id_poll, m.subject, p.question
  320. FROM {db_prefix}polls AS p
  321. INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll)
  322. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  323. WHERE p.id_poll IN ({array_int:polls})
  324. LIMIT ' . count($polls),
  325. array(
  326. 'polls' => $polls,
  327. )
  328. );
  329. while ($row = $smcFunc['db_fetch_assoc']($request))
  330. $context['polls'][] = array(
  331. 'id' => $row['id_poll'],
  332. 'topic' => array(
  333. 'id' => $row['id_topic'],
  334. 'subject' => $row['subject']
  335. ),
  336. 'question' => $row['question'],
  337. 'selected' => $row['id_topic'] == $firstTopic
  338. );
  339. $smcFunc['db_free_result']($request);
  340. }
  341. if (count($boards) > 1)
  342. {
  343. $request = $smcFunc['db_query']('', '
  344. SELECT id_board, name
  345. FROM {db_prefix}boards
  346. WHERE id_board IN ({array_int:boards})
  347. ORDER BY name
  348. LIMIT ' . count($boards),
  349. array(
  350. 'boards' => $boards,
  351. )
  352. );
  353. while ($row = $smcFunc['db_fetch_assoc']($request))
  354. $context['boards'][] = array(
  355. 'id' => $row['id_board'],
  356. 'name' => $row['name'],
  357. 'selected' => $row['id_board'] == $topic_data[$firstTopic]['board']
  358. );
  359. $smcFunc['db_free_result']($request);
  360. }
  361. $context['topics'] = $topic_data;
  362. foreach ($topic_data as $id => $topic)
  363. $context['topics'][$id]['selected'] = $topic['id'] == $firstTopic;
  364. $context['page_title'] = $txt['merge'];
  365. $context['sub_template'] = 'merge_extra_options';
  366. return;
  367. }
  368. // Determine target board.
  369. $target_board = count($boards) > 1 ? (int) $_REQUEST['board'] : $boards[0];
  370. if (!in_array($target_board, $boards))
  371. fatal_lang_error('no_board');
  372. // Determine which poll will survive and which polls won't.
  373. $target_poll = count($polls) > 1 ? (int) $_POST['poll'] : (count($polls) == 1 ? $polls[0] : 0);
  374. if ($target_poll > 0 && !in_array($target_poll, $polls))
  375. fatal_lang_error('no_access', false);
  376. $deleted_polls = empty($target_poll) ? $polls : array_diff($polls, array($target_poll));
  377. // Determine the subject of the newly merged topic - was a custom subject specified?
  378. if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '')
  379. {
  380. $target_subject = strtr($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
  381. // Keep checking the length.
  382. if ($smcFunc['strlen']($target_subject) > 100)
  383. $target_subject = $smcFunc['substr']($target_subject, 0, 100);
  384. // Nothing left - odd but pick the first topics subject.
  385. if ($target_subject == '')
  386. $target_subject = $topic_data[$firstTopic]['subject'];
  387. }
  388. // A subject was selected from the list.
  389. elseif (!empty($topic_data[(int) $_POST['subject']]['subject']))
  390. $target_subject = $topic_data[(int) $_POST['subject']]['subject'];
  391. // Nothing worked? Just take the subject of the first message.
  392. else
  393. $target_subject = $topic_data[$firstTopic]['subject'];
  394. // Get the first and last message and the number of messages....
  395. $request = $smcFunc['db_query']('', '
  396. SELECT approved, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg, COUNT(*) AS message_count
  397. FROM {db_prefix}messages
  398. WHERE id_topic IN ({array_int:topics})
  399. GROUP BY approved
  400. ORDER BY approved DESC',
  401. array(
  402. 'topics' => $topics,
  403. )
  404. );
  405. $topic_approved = 1;
  406. $first_msg = 0;
  407. while ($row = $smcFunc['db_fetch_assoc']($request))
  408. {
  409. // If this is approved, or is fully unapproved.
  410. if ($row['approved'] || !isset($first_msg))
  411. {
  412. $first_msg = $row['first_msg'];
  413. $last_msg = $row['last_msg'];
  414. if ($row['approved'])
  415. {
  416. $num_replies = $row['message_count'] - 1;
  417. $num_unapproved = 0;
  418. }
  419. else
  420. {
  421. $topic_approved = 0;
  422. $num_replies = 0;
  423. $num_unapproved = $row['message_count'];
  424. }
  425. }
  426. else
  427. {
  428. // If this has a lower first_msg then the first post is not approved and hence the number of replies was wrong!
  429. if ($first_msg > $row['first_msg'])
  430. {
  431. $first_msg = $row['first_msg'];
  432. $num_replies++;
  433. $topic_approved = 0;
  434. }
  435. $num_unapproved = $row['message_count'];
  436. }
  437. }
  438. $smcFunc['db_free_result']($request);
  439. // Ensure we have a board stat for the target board.
  440. if (!isset($boardTotals[$target_board]))
  441. {
  442. $boardTotals[$target_board] = array(
  443. 'posts' => 0,
  444. 'topics' => 0,
  445. 'unapproved_posts' => 0,
  446. 'unapproved_topics' => 0
  447. );
  448. }
  449. // Fix the topic count stuff depending on what the new one counts as.
  450. if ($topic_approved)
  451. $boardTotals[$target_board]['topics']--;
  452. else
  453. $boardTotals[$target_board]['unapproved_topics']--;
  454. $boardTotals[$target_board]['unapproved_posts'] -= $num_unapproved;
  455. $boardTotals[$target_board]['posts'] -= $topic_approved ? $num_replies + 1 : $num_replies;
  456. // Get the member ID of the first and last message.
  457. $request = $smcFunc['db_query']('', '
  458. SELECT id_member
  459. FROM {db_prefix}messages
  460. WHERE id_msg IN ({int:first_msg}, {int:last_msg})
  461. ORDER BY id_msg
  462. LIMIT 2',
  463. array(
  464. 'first_msg' => $first_msg,
  465. 'last_msg' => $last_msg,
  466. )
  467. );
  468. list ($member_started) = $smcFunc['db_fetch_row']($request);
  469. list ($member_updated) = $smcFunc['db_fetch_row']($request);
  470. // First and last message are the same, so only row was returned.
  471. if ($member_updated === NULL)
  472. $member_updated = $member_started;
  473. $smcFunc['db_free_result']($request);
  474. // Obtain all the message ids we are going to affect.
  475. $affected_msgs = array();
  476. $request = $smcFunc['db_query']('', '
  477. SELECT id_msg
  478. FROM {db_prefix}messages
  479. WHERE id_topic IN ({array_int:topic_list})',
  480. array(
  481. 'topic_list' => $topics,
  482. ));
  483. while ($row = $smcFunc['db_fetch_row']($request))
  484. $affected_msgs[] = $row[0];
  485. $smcFunc['db_free_result']($request);
  486. // Assign the first topic ID to be the merged topic.
  487. $id_topic = min($topics);
  488. // Delete the remaining topics.
  489. $deleted_topics = array_diff($topics, array($id_topic));
  490. $smcFunc['db_query']('', '
  491. DELETE FROM {db_prefix}topics
  492. WHERE id_topic IN ({array_int:deleted_topics})',
  493. array(
  494. 'deleted_topics' => $deleted_topics,
  495. )
  496. );
  497. $smcFunc['db_query']('', '
  498. DELETE FROM {db_prefix}log_search_subjects
  499. WHERE id_topic IN ({array_int:deleted_topics})',
  500. array(
  501. 'deleted_topics' => $deleted_topics,
  502. )
  503. );
  504. // Asssign the properties of the newly merged topic.
  505. $smcFunc['db_query']('', '
  506. UPDATE {db_prefix}topics
  507. SET
  508. id_board = {int:id_board},
  509. id_member_started = {int:id_member_started},
  510. id_member_updated = {int:id_member_updated},
  511. id_first_msg = {int:id_first_msg},
  512. id_last_msg = {int:id_last_msg},
  513. id_poll = {int:id_poll},
  514. num_replies = {int:num_replies},
  515. unapproved_posts = {int:unapproved_posts},
  516. num_views = {int:num_views},
  517. is_sticky = {int:is_sticky},
  518. approved = {int:approved}
  519. WHERE id_topic = {int:id_topic}',
  520. array(
  521. 'id_board' => $target_board,
  522. 'is_sticky' => $is_sticky,
  523. 'approved' => $topic_approved,
  524. 'id_topic' => $id_topic,
  525. 'id_member_started' => $member_started,
  526. 'id_member_updated' => $member_updated,
  527. 'id_first_msg' => $first_msg,
  528. 'id_last_msg' => $last_msg,
  529. 'id_poll' => $target_poll,
  530. 'num_replies' => $num_replies,
  531. 'unapproved_posts' => $num_unapproved,
  532. 'num_views' => $num_views,
  533. )
  534. );
  535. // Grab the response prefix (like 'Re: ') in the default forum language.
  536. if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix')))
  537. {
  538. if ($language === $user_info['language'])
  539. $context['response_prefix'] = $txt['response_prefix'];
  540. else
  541. {
  542. loadLanguage('index', $language, false);
  543. $context['response_prefix'] = $txt['response_prefix'];
  544. loadLanguage('index');
  545. }
  546. cache_put_data('response_prefix', $context['response_prefix'], 600);
  547. }
  548. // Change the topic IDs of all messages that will be merged. Also adjust subjects if 'enforce subject' was checked.
  549. $smcFunc['db_query']('', '
  550. UPDATE {db_prefix}messages
  551. SET
  552. id_topic = {int:id_topic},
  553. id_board = {int:target_board}' . (empty($_POST['enforce_subject']) ? '' : ',
  554. subject = {string:subject}') . '
  555. WHERE id_topic IN ({array_int:topic_list})',
  556. array(
  557. 'topic_list' => $topics,
  558. 'id_topic' => $id_topic,
  559. 'target_board' => $target_board,
  560. 'subject' => $context['response_prefix'] . $target_subject,
  561. )
  562. );
  563. // Any reported posts should reflect the new board.
  564. $smcFunc['db_query']('', '
  565. UPDATE {db_prefix}log_reported
  566. SET
  567. id_topic = {int:id_topic},
  568. id_board = {int:target_board}
  569. WHERE id_topic IN ({array_int:topics_list})',
  570. array(
  571. 'topics_list' => $topics,
  572. 'id_topic' => $id_topic,
  573. 'target_board' => $target_board,
  574. )
  575. );
  576. // Change the subject of the first message...
  577. $smcFunc['db_query']('', '
  578. UPDATE {db_prefix}messages
  579. SET subject = {string:target_subject}
  580. WHERE id_msg = {int:first_msg}',
  581. array(
  582. 'first_msg' => $first_msg,
  583. 'target_subject' => $target_subject,
  584. )
  585. );
  586. // Adjust all calendar events to point to the new topic.
  587. $smcFunc['db_query']('', '
  588. UPDATE {db_prefix}calendar
  589. SET
  590. id_topic = {int:id_topic},
  591. id_board = {int:target_board}
  592. WHERE id_topic IN ({array_int:deleted_topics})',
  593. array(
  594. 'deleted_topics' => $deleted_topics,
  595. 'id_topic' => $id_topic,
  596. 'target_board' => $target_board,
  597. )
  598. );
  599. // Merge log topic entries.
  600. // The disregard setting comes from the oldest topic
  601. $request = $smcFunc['db_query']('', '
  602. SELECT id_member, MIN(id_msg) AS new_id_msg, disregarded
  603. FROM {db_prefix}log_topics
  604. WHERE id_topic IN ({array_int:topics})
  605. GROUP BY id_member',
  606. array(
  607. 'topics' => $topics,
  608. )
  609. );
  610. if ($smcFunc['db_num_rows']($request) > 0)
  611. {
  612. $replaceEntries = array();
  613. while ($row = $smcFunc['db_fetch_assoc']($request))
  614. $replaceEntries[] = array($row['id_member'], $id_topic, $row['new_id_msg'], $row['disregarded']);
  615. require_once(SUBSDIR . '/Topic.subs.php');
  616. markTopicsRead($replaceEntries, true);
  617. unset($replaceEntries);
  618. // Get rid of the old log entries.
  619. $smcFunc['db_query']('', '
  620. DELETE FROM {db_prefix}log_topics
  621. WHERE id_topic IN ({array_int:deleted_topics})',
  622. array(
  623. 'deleted_topics' => $deleted_topics,
  624. )
  625. );
  626. }
  627. $smcFunc['db_free_result']($request);
  628. // Merge topic notifications.
  629. $notifications = isset($_POST['notifications']) && is_array($_POST['notifications']) ? array_intersect($topics, $_POST['notifications']) : array();
  630. if (!empty($notifications))
  631. {
  632. $request = $smcFunc['db_query']('', '
  633. SELECT id_member, MAX(sent) AS sent
  634. FROM {db_prefix}log_notify
  635. WHERE id_topic IN ({array_int:topics_list})
  636. GROUP BY id_member',
  637. array(
  638. 'topics_list' => $notifications,
  639. )
  640. );
  641. if ($smcFunc['db_num_rows']($request) > 0)
  642. {
  643. $replaceEntries = array();
  644. while ($row = $smcFunc['db_fetch_assoc']($request))
  645. $replaceEntries[] = array($row['id_member'], $id_topic, 0, $row['sent']);
  646. $smcFunc['db_insert']('replace',
  647. '{db_prefix}log_notify',
  648. array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'sent' => 'int'),
  649. $replaceEntries,
  650. array('id_member', 'id_topic', 'id_board')
  651. );
  652. unset($replaceEntries);
  653. $smcFunc['db_query']('', '
  654. DELETE FROM {db_prefix}log_topics
  655. WHERE id_topic IN ({array_int:deleted_topics})',
  656. array(
  657. 'deleted_topics' => $deleted_topics,
  658. )
  659. );
  660. }
  661. $smcFunc['db_free_result']($request);
  662. }
  663. // Get rid of the redundant polls.
  664. if (!empty($deleted_polls))
  665. {
  666. $smcFunc['db_query']('', '
  667. DELETE FROM {db_prefix}polls
  668. WHERE id_poll IN ({array_int:deleted_polls})',
  669. array(
  670. 'deleted_polls' => $deleted_polls,
  671. )
  672. );
  673. $smcFunc['db_query']('', '
  674. DELETE FROM {db_prefix}poll_choices
  675. WHERE id_poll IN ({array_int:deleted_polls})',
  676. array(
  677. 'deleted_polls' => $deleted_polls,
  678. )
  679. );
  680. $smcFunc['db_query']('', '
  681. DELETE FROM {db_prefix}log_polls
  682. WHERE id_poll IN ({array_int:deleted_polls})',
  683. array(
  684. 'deleted_polls' => $deleted_polls,
  685. )
  686. );
  687. }
  688. // Cycle through each board...
  689. foreach ($boardTotals as $id_board => $stats)
  690. {
  691. $smcFunc['db_query']('', '
  692. UPDATE {db_prefix}boards
  693. SET
  694. num_topics = CASE WHEN {int:topics} > num_topics THEN 0 ELSE num_topics - {int:topics} END,
  695. unapproved_topics = CASE WHEN {int:unapproved_topics} > unapproved_topics THEN 0 ELSE unapproved_topics - {int:unapproved_topics} END,
  696. num_posts = CASE WHEN {int:posts} > num_posts THEN 0 ELSE num_posts - {int:posts} END,
  697. unapproved_posts = CASE WHEN {int:unapproved_posts} > unapproved_posts THEN 0 ELSE unapproved_posts - {int:unapproved_posts} END
  698. WHERE id_board = {int:id_board}',
  699. array(
  700. 'id_board' => $id_board,
  701. 'topics' => $stats['topics'],
  702. 'unapproved_topics' => $stats['unapproved_topics'],
  703. 'posts' => $stats['posts'],
  704. 'unapproved_posts' => $stats['unapproved_posts'],
  705. )
  706. );
  707. }
  708. // Determine the board the final topic resides in
  709. $request = $smcFunc['db_query']('', '
  710. SELECT id_board
  711. FROM {db_prefix}topics
  712. WHERE id_topic = {int:id_topic}
  713. LIMIT 1',
  714. array(
  715. 'id_topic' => $id_topic,
  716. )
  717. );
  718. list($id_board) = $smcFunc['db_fetch_row']($request);
  719. $smcFunc['db_free_result']($request);
  720. require_once(SUBSDIR . '/Post.subs.php');
  721. // Update all the statistics.
  722. updateStats('topic');
  723. updateStats('subject', $id_topic, $target_subject);
  724. updateLastMessages($boards);
  725. logAction('merge', array('topic' => $id_topic, 'board' => $id_board));
  726. // Notify people that these topics have been merged?
  727. sendNotifications($id_topic, 'merge');
  728. // If there's a search index that needs updating, update it...
  729. require_once(SUBSDIR . '/Search.subs.php');
  730. $searchAPI = findSearchAPI();
  731. if (is_callable(array($searchAPI, 'topicMerge')))
  732. $searchAPI->topicMerge($id_topic, $topics, $affected_msgs, empty($_POST['enforce_subject']) ? null : array($context['response_prefix'], $target_subject));
  733. // Send them to the all done page.
  734. redirectexit('action=mergetopics;sa=done;to=' . $id_topic . ';targetboard=' . $target_board);
  735. }
  736. /**
  737. * Shows a 'merge completed' screen.
  738. * is accessed with ?action=mergetopics;sa=done.
  739. * uses 'merge_done' sub template of the MergeTopics template.
  740. */
  741. function action_mergeDone()
  742. {
  743. global $txt, $context;
  744. // Make sure the template knows everything...
  745. $context['target_board'] = (int) $_GET['targetboard'];
  746. $context['target_topic'] = (int) $_GET['to'];
  747. $context['page_title'] = $txt['merge'];
  748. $context['sub_template'] = 'merge_done';
  749. }