SplitTopics.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.1 Alpha 1
  11. */
  12. // Original module by Mach8 - We'll never forget you.
  13. if (!defined('SMF'))
  14. die('Hacking attempt...');
  15. /* This file handles merging and splitting topics... it does this with:
  16. void SplitTopics()
  17. - splits a topic into two topics.
  18. - delegates to the other functions (based on the URL parameter 'sa').
  19. - loads the SplitTopics template.
  20. - requires the split_any permission.
  21. - is accessed with ?action=splittopics.
  22. void SplitIndex()
  23. - screen shown before the actual split.
  24. - is accessed with ?action=splittopics;sa=index.
  25. - default sub action for ?action=splittopics.
  26. - uses 'ask' sub template of the SplitTopics template.
  27. - redirects to SplitSelectTopics if the message given turns out to be
  28. the first message of a topic.
  29. - shows the user three ways to split the current topic.
  30. void SplitExecute()
  31. - do the actual split.
  32. - is accessed with ?action=splittopics;sa=execute.
  33. - uses the main SplitTopics template.
  34. - supports three ways of splitting:
  35. (1) only one message is split off.
  36. (2) all messages after and including a given message are split off.
  37. (3) select topics to split (redirects to SplitSelectTopics()).
  38. - uses splitTopic function to do the actual splitting.
  39. void SplitSelectTopics()
  40. - allows the user to select the messages to be split.
  41. - is accessed with ?action=splittopics;sa=selectTopics.
  42. - uses 'select' sub template of the SplitTopics template or (for
  43. XMLhttp) the 'split' sub template of the Xml template.
  44. - supports XMLhttp for adding/removing a message to the selection.
  45. - uses a session variable to store the selected topics.
  46. - shows two independent page indexes for both the selected and
  47. not-selected messages (;topic=1.x;start2=y).
  48. void SplitSelectionExecute()
  49. - do the actual split of a selection of topics.
  50. - is accessed with ?action=splittopics;sa=splitSelection.
  51. - uses the main SplitTopics template.
  52. - uses splitTopic function to do the actual splitting.
  53. int splitTopic(int topicID, array messagesToBeSplit, string newSubject)
  54. - general function to split off a topic.
  55. - creates a new topic and moves the messages with the IDs in
  56. array messagesToBeSplit to the new topic.
  57. - the subject of the newly created topic is set to 'newSubject'.
  58. - marks the newly created message as read for the user splitting it.
  59. - updates the statistics to reflect a newly created topic.
  60. - logs the action in the moderation log.
  61. - a notification is sent to all users monitoring this topic.
  62. - returns the topic ID of the new split topic.
  63. void MergeTopics()
  64. - merges two or more topics into one topic.
  65. - delegates to the other functions (based on the URL parameter sa).
  66. - loads the SplitTopics template.
  67. - requires the merge_any permission.
  68. - is accessed with ?action=mergetopics.
  69. void MergeIndex()
  70. - allows to pick a topic to merge the current topic with.
  71. - is accessed with ?action=mergetopics;sa=index
  72. - default sub action for ?action=mergetopics.
  73. - uses 'merge' sub template of the SplitTopics template.
  74. - allows to set a different target board.
  75. void MergeExecute(array topics = request)
  76. - set merge options and do the actual merge of two or more topics.
  77. - the merge options screen:
  78. - shows topics to be merged and allows to set some merge options.
  79. - is accessed by ?action=mergetopics;sa=options.and can also
  80. internally be called by QuickModeration() (Subs-Boards.php).
  81. - uses 'merge_extra_options' sub template of the SplitTopics
  82. template.
  83. - the actual merge:
  84. - is accessed with ?action=mergetopics;sa=execute.
  85. - updates the statistics to reflect the merge.
  86. - logs the action in the moderation log.
  87. - sends a notification is sent to all users monitoring this topic.
  88. - redirects to ?action=mergetopics;sa=done.
  89. void MergeDone()
  90. - shows a 'merge completed' screen.
  91. - is accessed with ?action=mergetopics;sa=done.
  92. - uses 'merge_done' sub template of the SplitTopics template.
  93. */
  94. // Split a topic into two separate topics... in case it got offtopic, etc.
  95. function SplitTopics()
  96. {
  97. global $topic, $sourcedir;
  98. // And... which topic were you splitting, again?
  99. if (empty($topic))
  100. fatal_lang_error('numbers_one_to_nine', false);
  101. // Are you allowed to split topics?
  102. isAllowedTo('split_any');
  103. // Load up the "dependencies" - the template, getMsgMemberID(), and sendNotifications().
  104. if (!isset($_REQUEST['xml']))
  105. loadTemplate('SplitTopics');
  106. require_once($sourcedir . '/Subs-Boards.php');
  107. require_once($sourcedir . '/Subs-Post.php');
  108. $subActions = array(
  109. 'selectTopics' => 'SplitSelectTopics',
  110. 'execute' => 'SplitExecute',
  111. 'index' => 'SplitIndex',
  112. 'splitSelection' => 'SplitSelectionExecute',
  113. );
  114. // ?action=splittopics;sa=LETSBREAKIT won't work, sorry.
  115. if (empty($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
  116. SplitIndex();
  117. else
  118. $subActions[$_REQUEST['sa']]();
  119. }
  120. // Part 1: General stuff.
  121. function SplitIndex()
  122. {
  123. global $txt, $topic, $context, $smcFunc, $modSettings;
  124. // Validate "at".
  125. if (empty($_GET['at']))
  126. fatal_lang_error('numbers_one_to_nine', false);
  127. $_GET['at'] = (int) $_GET['at'];
  128. // Retrieve the subject and stuff of the specific topic/message.
  129. $request = $smcFunc['db_query']('', '
  130. SELECT m.subject, t.num_replies, t.unapproved_posts, t.id_first_msg, t.approved
  131. FROM {db_prefix}messages AS m
  132. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
  133. WHERE m.id_msg = {int:split_at}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  134. AND m.approved = 1') . '
  135. AND m.id_topic = {int:current_topic}
  136. LIMIT 1',
  137. array(
  138. 'current_topic' => $topic,
  139. 'split_at' => $_GET['at'],
  140. )
  141. );
  142. if ($smcFunc['db_num_rows']($request) == 0)
  143. fatal_lang_error('cant_find_messages');
  144. list ($_REQUEST['subname'], $num_replies, $unapproved_posts, $id_first_msg, $approved) = $smcFunc['db_fetch_row']($request);
  145. $smcFunc['db_free_result']($request);
  146. // If not approved validate they can see it.
  147. if ($modSettings['postmod_active'] && !$approved)
  148. isAllowedTo('approve_posts');
  149. // If this topic has unapproved posts, we need to count them too...
  150. if ($modSettings['postmod_active'] && allowedTo('approve_posts'))
  151. $num_replies += $unapproved_posts - ($approved ? 0 : 1);
  152. // Check if there is more than one message in the topic. (there should be.)
  153. if ($num_replies < 1)
  154. fatal_lang_error('topic_one_post', false);
  155. // Check if this is the first message in the topic (if so, the first and second option won't be available)
  156. if ($id_first_msg == $_GET['at'])
  157. return SplitSelectTopics();
  158. // Basic template information....
  159. $context['message'] = array(
  160. 'id' => $_GET['at'],
  161. 'subject' => $_REQUEST['subname']
  162. );
  163. $context['sub_template'] = 'ask';
  164. $context['page_title'] = $txt['split'];
  165. }
  166. // Alright, you've decided what you want to do with it.... now to do it.
  167. function SplitExecute()
  168. {
  169. global $txt, $board, $topic, $context, $user_info, $smcFunc, $modSettings;
  170. // Check the session to make sure they meant to do this.
  171. checkSession();
  172. // Clean up the subject.
  173. if (!isset($_POST['subname']) || $_POST['subname'] == '')
  174. $_POST['subname'] = $txt['new_topic'];
  175. // Redirect to the selector if they chose selective.
  176. if ($_POST['step2'] == 'selective')
  177. {
  178. $_REQUEST['subname'] = $_POST['subname'];
  179. return SplitSelectTopics();
  180. }
  181. $_POST['at'] = (int) $_POST['at'];
  182. $messagesToBeSplit = array();
  183. if ($_POST['step2'] == 'afterthis')
  184. {
  185. // Fetch the message IDs of the topic that are at or after the message.
  186. $request = $smcFunc['db_query']('', '
  187. SELECT id_msg
  188. FROM {db_prefix}messages
  189. WHERE id_topic = {int:current_topic}
  190. AND id_msg >= {int:split_at}',
  191. array(
  192. 'current_topic' => $topic,
  193. 'split_at' => $_POST['at'],
  194. )
  195. );
  196. while ($row = $smcFunc['db_fetch_assoc']($request))
  197. $messagesToBeSplit[] = $row['id_msg'];
  198. $smcFunc['db_free_result']($request);
  199. }
  200. // Only the selected message has to be split. That should be easy.
  201. elseif ($_POST['step2'] == 'onlythis')
  202. $messagesToBeSplit[] = $_POST['at'];
  203. // There's another action?!
  204. else
  205. fatal_lang_error('no_access', false);
  206. $context['old_topic'] = $topic;
  207. $context['new_topic'] = splitTopic($topic, $messagesToBeSplit, $_POST['subname']);
  208. $context['page_title'] = $txt['split'];
  209. }
  210. // Get a selective list of topics...
  211. function SplitSelectTopics()
  212. {
  213. global $txt, $scripturl, $topic, $context, $modSettings, $original_msgs, $smcFunc, $options;
  214. $context['page_title'] = $txt['split'] . ' - ' . $txt['select_split_posts'];
  215. // Haven't selected anything have we?
  216. $_SESSION['split_selection'][$topic] = empty($_SESSION['split_selection'][$topic]) ? array() : $_SESSION['split_selection'][$topic];
  217. $context['not_selected'] = array(
  218. 'num_messages' => 0,
  219. 'start' => empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'],
  220. 'messages' => array(),
  221. );
  222. $context['selected'] = array(
  223. 'num_messages' => 0,
  224. 'start' => empty($_REQUEST['start2']) ? 0 : (int) $_REQUEST['start2'],
  225. 'messages' => array(),
  226. );
  227. $context['topic'] = array(
  228. 'id' => $topic,
  229. 'subject' => urlencode($_REQUEST['subname']),
  230. );
  231. // Some stuff for our favorite template.
  232. $context['new_subject'] = $_REQUEST['subname'];
  233. // Using the "select" sub template.
  234. $context['sub_template'] = isset($_REQUEST['xml']) ? 'split' : 'select';
  235. // Are we using a custom messages per page?
  236. $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
  237. // Get the message ID's from before the move.
  238. if (isset($_REQUEST['xml']))
  239. {
  240. $original_msgs = array(
  241. 'not_selected' => array(),
  242. 'selected' => array(),
  243. );
  244. $request = $smcFunc['db_query']('', '
  245. SELECT id_msg
  246. FROM {db_prefix}messages
  247. WHERE id_topic = {int:current_topic}' . (empty($_SESSION['split_selection'][$topic]) ? '' : '
  248. AND id_msg NOT IN ({array_int:no_split_msgs})') . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  249. AND approved = {int:is_approved}') . '
  250. ORDER BY id_msg DESC
  251. LIMIT {int:start}, {int:messages_per_page}',
  252. array(
  253. 'current_topic' => $topic,
  254. 'no_split_msgs' => empty($_SESSION['split_selection'][$topic]) ? array() : $_SESSION['split_selection'][$topic],
  255. 'is_approved' => 1,
  256. 'start' => $context['not_selected']['start'],
  257. 'messages_per_page' => $context['messages_per_page'],
  258. )
  259. );
  260. // You can't split the last message off.
  261. if (empty($context['not_selected']['start']) && $smcFunc['db_num_rows']($request) <= 1 && $_REQUEST['move'] == 'down')
  262. $_REQUEST['move'] = '';
  263. while ($row = $smcFunc['db_fetch_assoc']($request))
  264. $original_msgs['not_selected'][] = $row['id_msg'];
  265. $smcFunc['db_free_result']($request);
  266. if (!empty($_SESSION['split_selection'][$topic]))
  267. {
  268. $request = $smcFunc['db_query']('', '
  269. SELECT id_msg
  270. FROM {db_prefix}messages
  271. WHERE id_topic = {int:current_topic}
  272. AND id_msg IN ({array_int:split_msgs})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  273. AND approved = {int:is_approved}') . '
  274. ORDER BY id_msg DESC
  275. LIMIT {int:start}, {int:messages_per_page}',
  276. array(
  277. 'current_topic' => $topic,
  278. 'split_msgs' => $_SESSION['split_selection'][$topic],
  279. 'is_approved' => 1,
  280. 'start' => $context['selected']['start'],
  281. 'messages_per_page' => $context['messages_per_page'],
  282. )
  283. );
  284. while ($row = $smcFunc['db_fetch_assoc']($request))
  285. $original_msgs['selected'][] = $row['id_msg'];
  286. $smcFunc['db_free_result']($request);
  287. }
  288. }
  289. // (De)select a message..
  290. if (!empty($_REQUEST['move']))
  291. {
  292. $_REQUEST['msg'] = (int) $_REQUEST['msg'];
  293. if ($_REQUEST['move'] == 'reset')
  294. $_SESSION['split_selection'][$topic] = array();
  295. elseif ($_REQUEST['move'] == 'up')
  296. $_SESSION['split_selection'][$topic] = array_diff($_SESSION['split_selection'][$topic], array($_REQUEST['msg']));
  297. else
  298. $_SESSION['split_selection'][$topic][] = $_REQUEST['msg'];
  299. }
  300. // Make sure the selection is still accurate.
  301. if (!empty($_SESSION['split_selection'][$topic]))
  302. {
  303. $request = $smcFunc['db_query']('', '
  304. SELECT id_msg
  305. FROM {db_prefix}messages
  306. WHERE id_topic = {int:current_topic}
  307. AND id_msg IN ({array_int:split_msgs})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  308. AND approved = {int:is_approved}'),
  309. array(
  310. 'current_topic' => $topic,
  311. 'split_msgs' => $_SESSION['split_selection'][$topic],
  312. 'is_approved' => 1,
  313. )
  314. );
  315. $_SESSION['split_selection'][$topic] = array();
  316. while ($row = $smcFunc['db_fetch_assoc']($request))
  317. $_SESSION['split_selection'][$topic][] = $row['id_msg'];
  318. $smcFunc['db_free_result']($request);
  319. }
  320. // Get the number of messages (not) selected to be split.
  321. $request = $smcFunc['db_query']('', '
  322. SELECT ' . (empty($_SESSION['split_selection'][$topic]) ? '0' : 'm.id_msg IN ({array_int:split_msgs})') . ' AS is_selected, COUNT(*) AS num_messages
  323. FROM {db_prefix}messages AS m
  324. WHERE m.id_topic = {int:current_topic}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  325. AND approved = {int:is_approved}') . (empty($_SESSION['split_selection'][$topic]) ? '' : '
  326. GROUP BY is_selected'),
  327. array(
  328. 'current_topic' => $topic,
  329. 'split_msgs' => !empty($_SESSION['split_selection'][$topic]) ? $_SESSION['split_selection'][$topic] : array(),
  330. 'is_approved' => 1,
  331. )
  332. );
  333. while ($row = $smcFunc['db_fetch_assoc']($request))
  334. $context[empty($row['is_selected']) ? 'not_selected' : 'selected']['num_messages'] = $row['num_messages'];
  335. $smcFunc['db_free_result']($request);
  336. // Fix an oversized starting page (to make sure both pageindexes are properly set).
  337. if ($context['selected']['start'] >= $context['selected']['num_messages'])
  338. $context['selected']['start'] = $context['selected']['num_messages'] <= $context['messages_per_page'] ? 0 : ($context['selected']['num_messages'] - (($context['selected']['num_messages'] % $context['messages_per_page']) == 0 ? $context['messages_per_page'] : ($context['selected']['num_messages'] % $context['messages_per_page'])));
  339. // Build a page list of the not-selected topics...
  340. $context['not_selected']['page_index'] = constructPageIndex($scripturl . '?action=splittopics;sa=selectTopics;subname=' . strtr(urlencode($_REQUEST['subname']), array('%' => '%%')) . ';topic=' . $topic . '.%1$d;start2=' . $context['selected']['start'], $context['not_selected']['start'], $context['not_selected']['num_messages'], $context['messages_per_page'], true);
  341. // ...and one of the selected topics.
  342. $context['selected']['page_index'] = constructPageIndex($scripturl . '?action=splittopics;sa=selectTopics;subname=' . strtr(urlencode($_REQUEST['subname']), array('%' => '%%')) . ';topic=' . $topic . '.' . $context['not_selected']['start'] . ';start2=%1$d', $context['selected']['start'], $context['selected']['num_messages'], $context['messages_per_page'], true);
  343. // Get the messages and stick them into an array.
  344. $request = $smcFunc['db_query']('', '
  345. SELECT m.subject, IFNULL(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
  346. FROM {db_prefix}messages AS m
  347. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  348. WHERE m.id_topic = {int:current_topic}' . (empty($_SESSION['split_selection'][$topic]) ? '' : '
  349. AND id_msg NOT IN ({array_int:no_split_msgs})') . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  350. AND approved = {int:is_approved}') . '
  351. ORDER BY m.id_msg DESC
  352. LIMIT {int:start}, {int:messages_per_page}',
  353. array(
  354. 'current_topic' => $topic,
  355. 'no_split_msgs' => !empty($_SESSION['split_selection'][$topic]) ? $_SESSION['split_selection'][$topic] : array(),
  356. 'is_approved' => 1,
  357. 'start' => $context['not_selected']['start'],
  358. 'messages_per_page' => $context['messages_per_page'],
  359. )
  360. );
  361. $context['messages'] = array();
  362. for ($counter = 0; $row = $smcFunc['db_fetch_assoc']($request); $counter ++)
  363. {
  364. censorText($row['subject']);
  365. censorText($row['body']);
  366. $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
  367. $context['not_selected']['messages'][$row['id_msg']] = array(
  368. 'id' => $row['id_msg'],
  369. 'alternate' => $counter % 2,
  370. 'subject' => $row['subject'],
  371. 'time' => timeformat($row['poster_time']),
  372. 'timestamp' => forum_time(true, $row['poster_time']),
  373. 'body' => $row['body'],
  374. 'poster' => $row['real_name'],
  375. );
  376. }
  377. $smcFunc['db_free_result']($request);
  378. // Now get the selected messages.
  379. if (!empty($_SESSION['split_selection'][$topic]))
  380. {
  381. // Get the messages and stick them into an array.
  382. $request = $smcFunc['db_query']('', '
  383. SELECT m.subject, IFNULL(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
  384. FROM {db_prefix}messages AS m
  385. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  386. WHERE m.id_topic = {int:current_topic}
  387. AND m.id_msg IN ({array_int:split_msgs})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
  388. AND approved = {int:is_approved}') . '
  389. ORDER BY m.id_msg DESC
  390. LIMIT {int:start}, {int:messages_per_page}',
  391. array(
  392. 'current_topic' => $topic,
  393. 'split_msgs' => $_SESSION['split_selection'][$topic],
  394. 'is_approved' => 1,
  395. 'start' => $context['selected']['start'],
  396. 'messages_per_page' => $context['messages_per_page'],
  397. )
  398. );
  399. $context['messages'] = array();
  400. for ($counter = 0; $row = $smcFunc['db_fetch_assoc']($request); $counter ++)
  401. {
  402. censorText($row['subject']);
  403. censorText($row['body']);
  404. $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
  405. $context['selected']['messages'][$row['id_msg']] = array(
  406. 'id' => $row['id_msg'],
  407. 'alternate' => $counter % 2,
  408. 'subject' => $row['subject'],
  409. 'time' => timeformat($row['poster_time']),
  410. 'timestamp' => forum_time(true, $row['poster_time']),
  411. 'body' => $row['body'],
  412. 'poster' => $row['real_name']
  413. );
  414. }
  415. $smcFunc['db_free_result']($request);
  416. }
  417. // The XMLhttp method only needs the stuff that changed, so let's compare.
  418. if (isset($_REQUEST['xml']))
  419. {
  420. $changes = array(
  421. 'remove' => array(
  422. 'not_selected' => array_diff($original_msgs['not_selected'], array_keys($context['not_selected']['messages'])),
  423. 'selected' => array_diff($original_msgs['selected'], array_keys($context['selected']['messages'])),
  424. ),
  425. 'insert' => array(
  426. 'not_selected' => array_diff(array_keys($context['not_selected']['messages']), $original_msgs['not_selected']),
  427. 'selected' => array_diff(array_keys($context['selected']['messages']), $original_msgs['selected']),
  428. ),
  429. );
  430. $context['changes'] = array();
  431. foreach ($changes as $change_type => $change_array)
  432. foreach ($change_array as $section => $msg_array)
  433. {
  434. if (empty($msg_array))
  435. continue;
  436. foreach ($msg_array as $id_msg)
  437. {
  438. $context['changes'][$change_type . $id_msg] = array(
  439. 'id' => $id_msg,
  440. 'type' => $change_type,
  441. 'section' => $section,
  442. );
  443. if ($change_type == 'insert')
  444. $context['changes']['insert' . $id_msg]['insert_value'] = $context[$section]['messages'][$id_msg];
  445. }
  446. }
  447. }
  448. }
  449. // Actually and selectively split the topics out.
  450. function SplitSelectionExecute()
  451. {
  452. global $txt, $board, $topic, $context, $user_info;
  453. // Make sure the session id was passed with post.
  454. checkSession();
  455. // Default the subject in case it's blank.
  456. if (!isset($_POST['subname']) || $_POST['subname'] == '')
  457. $_POST['subname'] = $txt['new_topic'];
  458. // You must've selected some messages! Can't split out none!
  459. if (empty($_SESSION['split_selection'][$topic]))
  460. fatal_lang_error('no_posts_selected', false);
  461. $context['old_topic'] = $topic;
  462. $context['new_topic'] = splitTopic($topic, $_SESSION['split_selection'][$topic], $_POST['subname']);
  463. $context['page_title'] = $txt['split'];
  464. }
  465. // Split a topic in two topics.
  466. function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject)
  467. {
  468. global $user_info, $topic, $board, $modSettings, $smcFunc, $txt;
  469. // Nothing to split?
  470. if (empty($splitMessages))
  471. fatal_lang_error('no_posts_selected', false);
  472. // Get some board info.
  473. $request = $smcFunc['db_query']('', '
  474. SELECT id_board, approved
  475. FROM {db_prefix}topics
  476. WHERE id_topic = {int:id_topic}
  477. LIMIT 1',
  478. array(
  479. 'id_topic' => $split1_ID_TOPIC,
  480. )
  481. );
  482. list ($id_board, $split1_approved) = $smcFunc['db_fetch_row']($request);
  483. $smcFunc['db_free_result']($request);
  484. // Find the new first and last not in the list. (old topic)
  485. $request = $smcFunc['db_query']('', '
  486. SELECT
  487. MIN(m.id_msg) AS myid_first_msg, MAX(m.id_msg) AS myid_last_msg, COUNT(*) AS message_count, m.approved
  488. FROM {db_prefix}messages AS m
  489. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:id_topic})
  490. WHERE m.id_msg NOT IN ({array_int:no_msg_list})
  491. AND m.id_topic = {int:id_topic}
  492. GROUP BY m.approved
  493. ORDER BY m.approved DESC
  494. LIMIT 2',
  495. array(
  496. 'id_topic' => $split1_ID_TOPIC,
  497. 'no_msg_list' => $splitMessages,
  498. )
  499. );
  500. // You can't select ALL the messages!
  501. if ($smcFunc['db_num_rows']($request) == 0)
  502. fatal_lang_error('selected_all_posts', false);
  503. while ($row = $smcFunc['db_fetch_assoc']($request))
  504. {
  505. // Get the right first and last message dependant on approved state...
  506. if (empty($split1_first_msg) || $row['myid_first_msg'] < $split1_first_msg)
  507. $split1_first_msg = $row['myid_first_msg'];
  508. if (empty($split1_last_msg) || $row['approved'])
  509. $split1_last_msg = $row['myid_last_msg'];
  510. // Get the counts correct...
  511. if ($row['approved'])
  512. {
  513. $split1_replies = $row['message_count'] - 1;
  514. $split1_unapprovedposts = 0;
  515. }
  516. else
  517. {
  518. if (!isset($split1_replies))
  519. $split1_replies = 0;
  520. // If the topic isn't approved then num replies must go up by one... as first post wouldn't be counted.
  521. elseif (!$split1_approved)
  522. $split1_replies++;
  523. $split1_unapprovedposts = $row['message_count'];
  524. }
  525. }
  526. $smcFunc['db_free_result']($request);
  527. $split1_firstMem = getMsgMemberID($split1_first_msg);
  528. $split1_lastMem = getMsgMemberID($split1_last_msg);
  529. // Find the first and last in the list. (new topic)
  530. $request = $smcFunc['db_query']('', '
  531. SELECT MIN(id_msg) AS myid_first_msg, MAX(id_msg) AS myid_last_msg, COUNT(*) AS message_count, approved
  532. FROM {db_prefix}messages
  533. WHERE id_msg IN ({array_int:msg_list})
  534. AND id_topic = {int:id_topic}
  535. GROUP BY id_topic, approved
  536. ORDER BY approved DESC
  537. LIMIT 2',
  538. array(
  539. 'msg_list' => $splitMessages,
  540. 'id_topic' => $split1_ID_TOPIC,
  541. )
  542. );
  543. while ($row = $smcFunc['db_fetch_assoc']($request))
  544. {
  545. // As before get the right first and last message dependant on approved state...
  546. if (empty($split2_first_msg) || $row['myid_first_msg'] < $split2_first_msg)
  547. $split2_first_msg = $row['myid_first_msg'];
  548. if (empty($split2_last_msg) || $row['approved'])
  549. $split2_last_msg = $row['myid_last_msg'];
  550. // Then do the counts again...
  551. if ($row['approved'])
  552. {
  553. $split2_approved = true;
  554. $split2_replies = $row['message_count'] - 1;
  555. $split2_unapprovedposts = 0;
  556. }
  557. else
  558. {
  559. // Should this one be approved??
  560. if ($split2_first_msg == $row['myid_first_msg'])
  561. $split2_approved = false;
  562. if (!isset($split2_replies))
  563. $split2_replies = 0;
  564. // As before, fix number of replies.
  565. elseif (!$split2_approved)
  566. $split2_replies++;
  567. $split2_unapprovedposts = $row['message_count'];
  568. }
  569. }
  570. $smcFunc['db_free_result']($request);
  571. $split2_firstMem = getMsgMemberID($split2_first_msg);
  572. $split2_lastMem = getMsgMemberID($split2_last_msg);
  573. // No database changes yet, so let's double check to see if everything makes at least a little sense.
  574. if ($split1_first_msg <= 0 || $split1_last_msg <= 0 || $split2_first_msg <= 0 || $split2_last_msg <= 0 || $split1_replies < 0 || $split2_replies < 0 || $split1_unapprovedposts < 0 || $split2_unapprovedposts < 0 || !isset($split1_approved) || !isset($split2_approved))
  575. fatal_lang_error('cant_find_messages');
  576. // You cannot split off the first message of a topic.
  577. if ($split1_first_msg > $split2_first_msg)
  578. fatal_lang_error('split_first_post', false);
  579. // We're off to insert the new topic! Use 0 for now to avoid UNIQUE errors.
  580. $smcFunc['db_insert']('',
  581. '{db_prefix}topics',
  582. array(
  583. 'id_board' => 'int',
  584. 'id_member_started' => 'int',
  585. 'id_member_updated' => 'int',
  586. 'id_first_msg' => 'int',
  587. 'id_last_msg' => 'int',
  588. 'num_replies' => 'int',
  589. 'unapproved_posts' => 'int',
  590. 'approved' => 'int',
  591. 'is_sticky' => 'int',
  592. ),
  593. array(
  594. (int) $id_board, $split2_firstMem, $split2_lastMem, 0,
  595. 0, $split2_replies, $split2_unapprovedposts, (int) $split2_approved, 0,
  596. ),
  597. array('id_topic')
  598. );
  599. $split2_ID_TOPIC = $smcFunc['db_insert_id']('{db_prefix}topics', 'id_topic');
  600. if ($split2_ID_TOPIC <= 0)
  601. fatal_lang_error('cant_insert_topic');
  602. // Move the messages over to the other topic.
  603. $new_subject = strtr($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($new_subject)), array("\r" => '', "\n" => '', "\t" => ''));
  604. // Check the subject length.
  605. if ($smcFunc['strlen']($new_subject) > 100)
  606. $new_subject = $smcFunc['substr']($new_subject, 0, 100);
  607. // Valid subject?
  608. if ($new_subject != '')
  609. {
  610. $smcFunc['db_query']('', '
  611. UPDATE {db_prefix}messages
  612. SET
  613. id_topic = {int:id_topic},
  614. subject = CASE WHEN id_msg = {int:split_first_msg} THEN {string:new_subject} ELSE {string:new_subject_replies} END
  615. WHERE id_msg IN ({array_int:split_msgs})',
  616. array(
  617. 'split_msgs' => $splitMessages,
  618. 'id_topic' => $split2_ID_TOPIC,
  619. 'new_subject' => $new_subject,
  620. 'split_first_msg' => $split2_first_msg,
  621. 'new_subject_replies' => $txt['response_prefix'] . $new_subject,
  622. )
  623. );
  624. // Cache the new topics subject... we can do it now as all the subjects are the same!
  625. updateStats('subject', $split2_ID_TOPIC, $new_subject);
  626. }
  627. // Any associated reported posts better follow...
  628. $smcFunc['db_query']('', '
  629. UPDATE {db_prefix}log_reported
  630. SET id_topic = {int:id_topic}
  631. WHERE id_msg IN ({array_int:split_msgs})',
  632. array(
  633. 'split_msgs' => $splitMessages,
  634. 'id_topic' => $split2_ID_TOPIC,
  635. )
  636. );
  637. // Mess with the old topic's first, last, and number of messages.
  638. $smcFunc['db_query']('', '
  639. UPDATE {db_prefix}topics
  640. SET
  641. num_replies = {int:num_replies},
  642. id_first_msg = {int:id_first_msg},
  643. id_last_msg = {int:id_last_msg},
  644. id_member_started = {int:id_member_started},
  645. id_member_updated = {int:id_member_updated},
  646. unapproved_posts = {int:unapproved_posts}
  647. WHERE id_topic = {int:id_topic}',
  648. array(
  649. 'num_replies' => $split1_replies,
  650. 'id_first_msg' => $split1_first_msg,
  651. 'id_last_msg' => $split1_last_msg,
  652. 'id_member_started' => $split1_firstMem,
  653. 'id_member_updated' => $split1_lastMem,
  654. 'unapproved_posts' => $split1_unapprovedposts,
  655. 'id_topic' => $split1_ID_TOPIC,
  656. )
  657. );
  658. // Now, put the first/last message back to what they should be.
  659. $smcFunc['db_query']('', '
  660. UPDATE {db_prefix}topics
  661. SET
  662. id_first_msg = {int:id_first_msg},
  663. id_last_msg = {int:id_last_msg}
  664. WHERE id_topic = {int:id_topic}',
  665. array(
  666. 'id_first_msg' => $split2_first_msg,
  667. 'id_last_msg' => $split2_last_msg,
  668. 'id_topic' => $split2_ID_TOPIC,
  669. )
  670. );
  671. // If the new topic isn't approved ensure the first message flags this just in case.
  672. if (!$split2_approved)
  673. $smcFunc['db_query']('', '
  674. UPDATE {db_prefix}messages
  675. SET approved = {int:approved}
  676. WHERE id_msg = {int:id_msg}
  677. AND id_topic = {int:id_topic}',
  678. array(
  679. 'approved' => 0,
  680. 'id_msg' => $split2_first_msg,
  681. 'id_topic' => $split2_ID_TOPIC,
  682. )
  683. );
  684. // The board has more topics now (Or more unapproved ones!).
  685. $smcFunc['db_query']('', '
  686. UPDATE {db_prefix}boards
  687. SET ' . ($split2_approved ? '
  688. num_topics = num_topics + 1' : '
  689. unapproved_topics = unapproved_topics + 1') . '
  690. WHERE id_board = {int:id_board}',
  691. array(
  692. 'id_board' => $id_board,
  693. )
  694. );
  695. // Copy log topic entries.
  696. // @todo This should really be chunked.
  697. $request = $smcFunc['db_query']('', '
  698. SELECT id_member, id_msg
  699. FROM {db_prefix}log_topics
  700. WHERE id_topic = {int:id_topic}',
  701. array(
  702. 'id_topic' => (int) $split1_ID_TOPIC,
  703. )
  704. );
  705. if ($smcFunc['db_num_rows']($request) > 0)
  706. {
  707. $replaceEntries = array();
  708. while ($row = $smcFunc['db_fetch_assoc']($request))
  709. $replaceEntries[] = array($row['id_member'], $split2_ID_TOPIC, $row['id_msg']);
  710. $smcFunc['db_insert']('ignore',
  711. '{db_prefix}log_topics',
  712. array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int'),
  713. $replaceEntries,
  714. array('id_member', 'id_topic')
  715. );
  716. unset($replaceEntries);
  717. }
  718. $smcFunc['db_free_result']($request);
  719. // Housekeeping.
  720. updateStats('topic');
  721. updateLastMessages($id_board);
  722. logAction('split', array('topic' => $split1_ID_TOPIC, 'new_topic' => $split2_ID_TOPIC, 'board' => $id_board));
  723. // Notify people that this topic has been split?
  724. sendNotifications($split1_ID_TOPIC, 'split');
  725. // If there's a search index that needs updating, update it...
  726. require_once($sourcedir . '/Search.php');
  727. $searchAPI = findSearchAPI();
  728. if (is_callable(array($searchAPI, 'topicSplit')))
  729. $searchAPI->topicSplit($split2_ID_TOPIC, $splitMessages);
  730. // Return the ID of the newly created topic.
  731. return $split2_ID_TOPIC;
  732. }
  733. // Merge two topics into one topic... useful if they have the same basic subject.
  734. function MergeTopics()
  735. {
  736. // Load the template....
  737. loadTemplate('SplitTopics');
  738. $subActions = array(
  739. 'done' => 'MergeDone',
  740. 'execute' => 'MergeExecute',
  741. 'index' => 'MergeIndex',
  742. 'options' => 'MergeExecute',
  743. );
  744. // ?action=mergetopics;sa=LETSBREAKIT won't work, sorry.
  745. if (empty($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
  746. MergeIndex();
  747. else
  748. $subActions[$_REQUEST['sa']]();
  749. }
  750. // Merge two topics together.
  751. function MergeIndex()
  752. {
  753. global $txt, $board, $context, $smcFunc;
  754. global $scripturl, $topic, $user_info, $modSettings;
  755. if (!isset($_GET['from']))
  756. fatal_lang_error('no_access', false);
  757. $_GET['from'] = (int) $_GET['from'];
  758. $_REQUEST['targetboard'] = isset($_REQUEST['targetboard']) ? (int) $_REQUEST['targetboard'] : $board;
  759. $context['target_board'] = $_REQUEST['targetboard'];
  760. // Prepare a handy query bit for approval...
  761. if ($modSettings['postmod_active'])
  762. {
  763. $can_approve_boards = boardsAllowedTo('approve_posts');
  764. $onlyApproved = $can_approve_boards !== array(0) && !in_array($_REQUEST['targetboard'], $can_approve_boards);
  765. }
  766. else
  767. $onlyApproved = false;
  768. // How many topics are on this board? (used for paging.)
  769. $request = $smcFunc['db_query']('', '
  770. SELECT COUNT(*)
  771. FROM {db_prefix}topics AS t
  772. WHERE t.id_board = {int:id_board}' . ($onlyApproved ? '
  773. AND t.approved = {int:is_approved}' : ''),
  774. array(
  775. 'id_board' => $_REQUEST['targetboard'],
  776. 'is_approved' => 1,
  777. )
  778. );
  779. list ($topiccount) = $smcFunc['db_fetch_row']($request);
  780. $smcFunc['db_free_result']($request);
  781. // Make the page list.
  782. $context['page_index'] = constructPageIndex($scripturl . '?action=mergetopics;from=' . $_GET['from'] . ';targetboard=' . $_REQUEST['targetboard'] . ';board=' . $board . '.%1$d', $_REQUEST['start'], $topiccount, $modSettings['defaultMaxTopics'], true);
  783. // Get the topic's subject.
  784. $request = $smcFunc['db_query']('', '
  785. SELECT m.subject
  786. FROM {db_prefix}topics AS t
  787. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  788. WHERE t.id_topic = {int:id_topic}
  789. AND t.id_board = {int:current_board}' . ($onlyApproved ? '
  790. AND t.approved = {int:is_approved}' : '') . '
  791. LIMIT 1',
  792. array(
  793. 'current_board' => $board,
  794. 'id_topic' => $_GET['from'],
  795. 'is_approved' => 1,
  796. )
  797. );
  798. if ($smcFunc['db_num_rows']($request) == 0)
  799. fatal_lang_error('no_board');
  800. list ($subject) = $smcFunc['db_fetch_row']($request);
  801. $smcFunc['db_free_result']($request);
  802. // Tell the template a few things..
  803. $context['origin_topic'] = $_GET['from'];
  804. $context['origin_subject'] = $subject;
  805. $context['origin_js_subject'] = addcslashes(addslashes($subject), '/');
  806. $context['page_title'] = $txt['merge'];
  807. // Check which boards you have merge permissions on.
  808. $merge_boards = boardsAllowedTo('merge_any');
  809. if (empty($merge_boards))
  810. fatal_lang_error('cannot_merge_any', 'user');
  811. // Get a list of boards they can navigate to to merge.
  812. $request = $smcFunc['db_query']('order_by_board_order', '
  813. SELECT b.id_board, b.name AS board_name, c.name AS cat_name
  814. FROM {db_prefix}boards AS b
  815. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  816. WHERE {query_see_board}' . (!in_array(0, $merge_boards) ? '
  817. AND b.id_board IN ({array_int:merge_boards})' : ''),
  818. array(
  819. 'merge_boards' => $merge_boards,
  820. )
  821. );
  822. $context['boards'] = array();
  823. while ($row = $smcFunc['db_fetch_assoc']($request))
  824. $context['boards'][] = array(
  825. 'id' => $row['id_board'],
  826. 'name' => $row['board_name'],
  827. 'category' => $row['cat_name']
  828. );
  829. $smcFunc['db_free_result']($request);
  830. // Get some topics to merge it with.
  831. $request = $smcFunc['db_query']('', '
  832. SELECT t.id_topic, m.subject, m.id_member, IFNULL(mem.real_name, m.poster_name) AS poster_name
  833. FROM {db_prefix}topics AS t
  834. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  835. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  836. WHERE t.id_board = {int:id_board}
  837. AND t.id_topic != {int:id_topic}' . ($onlyApproved ? '
  838. AND t.approved = {int:is_approved}' : '') . '
  839. ORDER BY {raw:sort}
  840. LIMIT {int:offset}, {int:limit}',
  841. array(
  842. 'id_board' => $_REQUEST['targetboard'],
  843. 'id_topic' => $_GET['from'],
  844. 'sort' => (!empty($modSettings['enableStickyTopics']) ? 't.is_sticky DESC, ' : '') . 't.id_last_msg DESC',
  845. 'offset' => $_REQUEST['start'],
  846. 'limit' => $modSettings['defaultMaxTopics'],
  847. 'is_approved' => 1,
  848. )
  849. );
  850. $context['topics'] = array();
  851. while ($row = $smcFunc['db_fetch_assoc']($request))
  852. {
  853. censorText($row['subject']);
  854. $context['topics'][] = array(
  855. 'id' => $row['id_topic'],
  856. 'poster' => array(
  857. 'id' => $row['id_member'],
  858. 'name' => $row['poster_name'],
  859. 'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
  860. '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>'
  861. ),
  862. 'subject' => $row['subject'],
  863. 'js_subject' => addcslashes(addslashes($row['subject']), '/')
  864. );
  865. }
  866. $smcFunc['db_free_result']($request);
  867. if (empty($context['topics']) && count($context['boards']) <= 1)
  868. fatal_lang_error('merge_need_more_topics');
  869. $context['sub_template'] = 'merge';
  870. }
  871. // Now that the topic IDs are known, do the proper merging.
  872. function MergeExecute($topics = array())
  873. {
  874. global $user_info, $txt, $context, $scripturl, $sourcedir;
  875. global $smcFunc, $language, $modSettings;
  876. // Check the session.
  877. checkSession('request');
  878. // Handle URLs from MergeIndex.
  879. if (!empty($_GET['from']) && !empty($_GET['to']))
  880. $topics = array((int) $_GET['from'], (int) $_GET['to']);
  881. // If we came from a form, the topic IDs came by post.
  882. if (!empty($_POST['topics']) && is_array($_POST['topics']))
  883. $topics = $_POST['topics'];
  884. // There's nothing to merge with just one topic...
  885. if (empty($topics) || !is_array($topics) || count($topics) == 1)
  886. fatal_lang_error('merge_need_more_topics');
  887. // Make sure every topic is numeric, or some nasty things could be done with the DB.
  888. foreach ($topics as $id => $topic)
  889. $topics[$id] = (int) $topic;
  890. // Joy of all joys, make sure they're not pi**ing about with unapproved topics they can't see :P
  891. if ($modSettings['postmod_active'])
  892. $can_approve_boards = boardsAllowedTo('approve_posts');
  893. // Get info about the topics and polls that will be merged.
  894. $request = $smcFunc['db_query']('', '
  895. SELECT
  896. t.id_topic, t.id_board, t.id_poll, t.num_views, t.is_sticky, t.approved, t.num_replies, t.unapproved_posts,
  897. 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,
  898. 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
  899. FROM {db_prefix}topics AS t
  900. INNER JOIN {db_prefix}messages AS m1 ON (m1.id_msg = t.id_first_msg)
  901. INNER JOIN {db_prefix}messages AS m2 ON (m2.id_msg = t.id_last_msg)
  902. LEFT JOIN {db_prefix}members AS mem1 ON (mem1.id_member = m1.id_member)
  903. LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = m2.id_member)
  904. WHERE t.id_topic IN ({array_int:topic_list})
  905. ORDER BY t.id_first_msg
  906. LIMIT ' . count($topics),
  907. array(
  908. 'topic_list' => $topics,
  909. )
  910. );
  911. if ($smcFunc['db_num_rows']($request) < 2)
  912. fatal_lang_error('no_topic_id');
  913. $num_views = 0;
  914. $is_sticky = 0;
  915. $boardTotals = array();
  916. $boards = array();
  917. $polls = array();
  918. while ($row = $smcFunc['db_fetch_assoc']($request))
  919. {
  920. // Make a note for the board counts...
  921. if (!isset($boardTotals[$row['id_board']]))
  922. $boardTotals[$row['id_board']] = array(
  923. 'posts' => 0,
  924. 'topics' => 0,
  925. 'unapproved_posts' => 0,
  926. 'unapproved_topics' => 0
  927. );
  928. // We can't see unapproved topics here?
  929. if ($modSettings['postmod_active'] && !$row['approved'] && $can_approve_boards != array(0) && in_array($row['id_board'], $can_approve_boards))
  930. continue;
  931. elseif (!$row['approved'])
  932. $boardTotals[$row['id_board']]['unapproved_topics']++;
  933. else
  934. $boardTotals[$row['id_board']]['topics']++;
  935. $boardTotals[$row['id_board']]['unapproved_posts'] += $row['unapproved_posts'];
  936. $boardTotals[$row['id_board']]['posts'] += $row['num_replies'] + ($row['approved'] ? 1 : 0);
  937. $topic_data[$row['id_topic']] = array(
  938. 'id' => $row['id_topic'],
  939. 'board' => $row['id_board'],
  940. 'poll' => $row['id_poll'],
  941. 'num_views' => $row['num_views'],
  942. 'subject' => $row['subject'],
  943. 'started' => array(
  944. 'time' => timeformat($row['time_started']),
  945. 'timestamp' => forum_time(true, $row['time_started']),
  946. 'href' => empty($row['id_member_started']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_started'],
  947. 'link' => empty($row['id_member_started']) ? $row['name_started'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_started'] . '">' . $row['name_started'] . '</a>'
  948. ),
  949. 'updated' => array(
  950. 'time' => timeformat($row['time_updated']),
  951. 'timestamp' => forum_time(true, $row['time_updated']),
  952. 'href' => empty($row['id_member_updated']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_updated'],
  953. 'link' => empty($row['id_member_updated']) ? $row['name_updated'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['name_updated'] . '</a>'
  954. )
  955. );
  956. $num_views += $row['num_views'];
  957. $boards[] = $row['id_board'];
  958. // If there's no poll, id_poll == 0...
  959. if ($row['id_poll'] > 0)
  960. $polls[] = $row['id_poll'];
  961. // Store the id_topic with the lowest id_first_msg.
  962. if (empty($firstTopic))
  963. $firstTopic = $row['id_topic'];
  964. $is_sticky = max($is_sticky, $row['is_sticky']);
  965. }
  966. $smcFunc['db_free_result']($request);
  967. // If we didn't get any topics then they've been messing with unapproved stuff.
  968. if (empty($topic_data))
  969. fatal_lang_error('no_topic_id');
  970. $boards = array_values(array_unique($boards));
  971. // The parameters of MergeExecute were set, so this must've been an internal call.
  972. if (!empty($topics))
  973. {
  974. isAllowedTo('merge_any', $boards);
  975. loadTemplate('SplitTopics');
  976. }
  977. // Get the boards a user is allowed to merge in.
  978. $merge_boards = boardsAllowedTo('merge_any');
  979. if (empty($merge_boards))
  980. fatal_lang_error('cannot_merge_any', 'user');
  981. // Make sure they can see all boards....
  982. $request = $smcFunc['db_query']('', '
  983. SELECT b.id_board
  984. FROM {db_prefix}boards AS b
  985. WHERE b.id_board IN ({array_int:boards})
  986. AND {query_see_board}' . (!in_array(0, $merge_boards) ? '
  987. AND b.id_board IN ({array_int:merge_boards})' : '') . '
  988. LIMIT ' . count($boards),
  989. array(
  990. 'boards' => $boards,
  991. 'merge_boards' => $merge_boards,
  992. )
  993. );
  994. // 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.
  995. if ($smcFunc['db_num_rows']($request) != count($boards))
  996. fatal_lang_error('no_board');
  997. $smcFunc['db_free_result']($request);
  998. if (empty($_REQUEST['sa']) || $_REQUEST['sa'] == 'options')
  999. {
  1000. if (count($polls) > 1)
  1001. {
  1002. $request = $smcFunc['db_query']('', '
  1003. SELECT t.id_topic, t.id_poll, m.subject, p.question
  1004. FROM {db_prefix}polls AS p
  1005. INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll)
  1006. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  1007. WHERE p.id_poll IN ({array_int:polls})
  1008. LIMIT ' . count($polls),
  1009. array(
  1010. 'polls' => $polls,
  1011. )
  1012. );
  1013. while ($row = $smcFunc['db_fetch_assoc']($request))
  1014. $context['polls'][] = array(
  1015. 'id' => $row['id_poll'],
  1016. 'topic' => array(
  1017. 'id' => $row['id_topic'],
  1018. 'subject' => $row['subject']
  1019. ),
  1020. 'question' => $row['question'],
  1021. 'selected' => $row['id_topic'] == $firstTopic
  1022. );
  1023. $smcFunc['db_free_result']($request);
  1024. }
  1025. if (count($boards) > 1)
  1026. {
  1027. $request = $smcFunc['db_query']('', '
  1028. SELECT id_board, name
  1029. FROM {db_prefix}boards
  1030. WHERE id_board IN ({array_int:boards})
  1031. ORDER BY name
  1032. LIMIT ' . count($boards),
  1033. array(
  1034. 'boards' => $boards,
  1035. )
  1036. );
  1037. while ($row = $smcFunc['db_fetch_assoc']($request))
  1038. $context['boards'][] = array(
  1039. 'id' => $row['id_board'],
  1040. 'name' => $row['name'],
  1041. 'selected' => $row['id_board'] == $topic_data[$firstTopic]['board']
  1042. );
  1043. $smcFunc['db_free_result']($request);
  1044. }
  1045. $context['topics'] = $topic_data;
  1046. foreach ($topic_data as $id => $topic)
  1047. $context['topics'][$id]['selected'] = $topic['id'] == $firstTopic;
  1048. $context['page_title'] = $txt['merge'];
  1049. $context['sub_template'] = 'merge_extra_options';
  1050. return;
  1051. }
  1052. // Determine target board.
  1053. $target_board = count($boards) > 1 ? (int) $_REQUEST['board'] : $boards[0];
  1054. if (!in_array($target_board, $boards))
  1055. fatal_lang_error('no_board');
  1056. // Determine which poll will survive and which polls won't.
  1057. $target_poll = count($polls) > 1 ? (int) $_POST['poll'] : (count($polls) == 1 ? $polls[0] : 0);
  1058. if ($target_poll > 0 && !in_array($target_poll, $polls))
  1059. fatal_lang_error('no_access', false);
  1060. $deleted_polls = empty($target_poll) ? $polls : array_diff($polls, array($target_poll));
  1061. // Determine the subject of the newly merged topic - was a custom subject specified?
  1062. if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '')
  1063. {
  1064. $target_subject = strtr($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
  1065. // Keep checking the length.
  1066. if ($smcFunc['strlen']($target_subject) > 100)
  1067. $target_subject = $smcFunc['substr']($target_subject, 0, 100);
  1068. // Nothing left - odd but pick the first topics subject.
  1069. if ($target_subject == '')
  1070. $target_subject = $topic_data[$firstTopic]['subject'];
  1071. }
  1072. // A subject was selected from the list.
  1073. elseif (!empty($topic_data[(int) $_POST['subject']]['subject']))
  1074. $target_subject = $topic_data[(int) $_POST['subject']]['subject'];
  1075. // Nothing worked? Just take the subject of the first message.
  1076. else
  1077. $target_subject = $topic_data[$firstTopic]['subject'];
  1078. // Get the first and last message and the number of messages....
  1079. $request = $smcFunc['db_query']('', '
  1080. SELECT approved, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg, COUNT(*) AS message_count
  1081. FROM {db_prefix}messages
  1082. WHERE id_topic IN ({array_int:topics})
  1083. GROUP BY approved
  1084. ORDER BY approved DESC',
  1085. array(
  1086. 'topics' => $topics,
  1087. )
  1088. );
  1089. $topic_approved = 1;
  1090. while ($row = $smcFunc['db_fetch_assoc']($request))
  1091. {
  1092. // If this is approved, or is fully unapproved.
  1093. if ($row['approved'] || !isset($first_msg))
  1094. {
  1095. $first_msg = $row['first_msg'];
  1096. $last_msg = $row['last_msg'];
  1097. if ($row['approved'])
  1098. {
  1099. $num_replies = $row['message_count'] - 1;
  1100. $num_unapproved = 0;
  1101. }
  1102. else
  1103. {
  1104. $topic_approved = 0;
  1105. $num_replies = 0;
  1106. $num_unapproved = $row['message_count'];
  1107. }
  1108. }
  1109. else
  1110. {
  1111. // If this has a lower first_msg then the first post is not approved and hence the number of replies was wrong!
  1112. if ($first_msg > $row['first_msg'])
  1113. {
  1114. $first_msg = $row['first_msg'];
  1115. $num_replies++;
  1116. $topic_approved = 0;
  1117. }
  1118. $num_unapproved = $row['message_count'];
  1119. }
  1120. }
  1121. $smcFunc['db_free_result']($request);
  1122. // Ensure we have a board stat for the target board.
  1123. if (!isset($boardTotals[$target_board]))
  1124. {
  1125. $boardTotals[$target_board] = array(
  1126. 'posts' => 0,
  1127. 'topics' => 0,
  1128. 'unapproved_posts' => 0,
  1129. 'unapproved_topics' => 0
  1130. );
  1131. }
  1132. // Fix the topic count stuff depending on what the new one counts as.
  1133. if ($topic_approved)
  1134. $boardTotals[$target_board]['topics']--;
  1135. else
  1136. $boardTotals[$target_board]['unapproved_topics']--;
  1137. $boardTotals[$target_board]['unapproved_posts'] -= $num_unapproved;
  1138. $boardTotals[$target_board]['posts'] -= $topic_approved ? $num_replies + 1 : $num_replies;
  1139. // Get the member ID of the first and last message.
  1140. $request = $smcFunc['db_query']('', '
  1141. SELECT id_member
  1142. FROM {db_prefix}messages
  1143. WHERE id_msg IN ({int:first_msg}, {int:last_msg})
  1144. ORDER BY id_msg
  1145. LIMIT 2',
  1146. array(
  1147. 'first_msg' => $first_msg,
  1148. 'last_msg' => $last_msg,
  1149. )
  1150. );
  1151. list ($member_started) = $smcFunc['db_fetch_row']($request);
  1152. list ($member_updated) = $smcFunc['db_fetch_row']($request);
  1153. // First and last message are the same, so only row was returned.
  1154. if ($member_updated === NULL)
  1155. $member_updated = $member_started;
  1156. $smcFunc['db_free_result']($request);
  1157. // Obtain all the message ids we are going to affect.
  1158. $affected_msgs = array();
  1159. $request = $smcFunc['db_query']('', '
  1160. SELECT id_msg
  1161. FROM {db_prefix}messages
  1162. WHERE id_topic IN ({array_int:topic_list})',
  1163. array(
  1164. 'topic_list' => $topics,
  1165. ));
  1166. while ($row = $smcFunc['db_fetch_row']($request))
  1167. $affected_msgs[] = $row[0];
  1168. $smcFunc['db_free_result']($request);
  1169. // Assign the first topic ID to be the merged topic.
  1170. $id_topic = min($topics);
  1171. // Delete the remaining topics.
  1172. $deleted_topics = array_diff($topics, array($id_topic));
  1173. $smcFunc['db_query']('', '
  1174. DELETE FROM {db_prefix}topics
  1175. WHERE id_topic IN ({array_int:deleted_topics})',
  1176. array(
  1177. 'deleted_topics' => $deleted_topics,
  1178. )
  1179. );
  1180. $smcFunc['db_query']('', '
  1181. DELETE FROM {db_prefix}log_search_subjects
  1182. WHERE id_topic IN ({array_int:deleted_topics})',
  1183. array(
  1184. 'deleted_topics' => $deleted_topics,
  1185. )
  1186. );
  1187. // Asssign the properties of the newly merged topic.
  1188. $smcFunc['db_query']('', '
  1189. UPDATE {db_prefix}topics
  1190. SET
  1191. id_board = {int:id_board},
  1192. id_member_started = {int:id_member_started},
  1193. id_member_updated = {int:id_member_updated},
  1194. id_first_msg = {int:id_first_msg},
  1195. id_last_msg = {int:id_last_msg},
  1196. id_poll = {int:id_poll},
  1197. num_replies = {int:num_replies},
  1198. unapproved_posts = {int:unapproved_posts},
  1199. num_views = {int:num_views},
  1200. is_sticky = {int:is_sticky},
  1201. approved = {int:approved}
  1202. WHERE id_topic = {int:id_topic}',
  1203. array(
  1204. 'id_board' => $target_board,
  1205. 'is_sticky' => $is_sticky,
  1206. 'approved' => $topic_approved,
  1207. 'id_topic' => $id_topic,
  1208. 'id_member_started' => $member_started,
  1209. 'id_member_updated' => $member_updated,
  1210. 'id_first_msg' => $first_msg,
  1211. 'id_last_msg' => $last_msg,
  1212. 'id_poll' => $target_poll,
  1213. 'num_replies' => $num_replies,
  1214. 'unapproved_posts' => $num_unapproved,
  1215. 'num_views' => $num_views,
  1216. )
  1217. );
  1218. // Grab the response prefix (like 'Re: ') in the default forum language.
  1219. if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix')))
  1220. {
  1221. if ($language === $user_info['language'])
  1222. $context['response_prefix'] = $txt['response_prefix'];
  1223. else
  1224. {
  1225. loadLanguage('index', $language, false);
  1226. $context['response_prefix'] = $txt['response_prefix'];
  1227. loadLanguage('index');
  1228. }
  1229. cache_put_data('response_prefix', $context['response_prefix'], 600);
  1230. }
  1231. // Change the topic IDs of all messages that will be merged. Also adjust subjects if 'enforce subject' was checked.
  1232. $smcFunc['db_query']('', '
  1233. UPDATE {db_prefix}messages
  1234. SET
  1235. id_topic = {int:id_topic},
  1236. id_board = {int:target_board}' . (empty($_POST['enforce_subject']) ? '' : ',
  1237. subject = {string:subject}') . '
  1238. WHERE id_topic IN ({array_int:topic_list})',
  1239. array(
  1240. 'topic_list' => $topics,
  1241. 'id_topic' => $id_topic,
  1242. 'target_board' => $target_board,
  1243. 'subject' => $context['response_prefix'] . $target_subject,
  1244. )
  1245. );
  1246. // Any reported posts should reflect the new board.
  1247. $smcFunc['db_query']('', '
  1248. UPDATE {db_prefix}log_reported
  1249. SET
  1250. id_topic = {int:id_topic},
  1251. id_board = {int:target_board}
  1252. WHERE id_topic IN ({array_int:topics_list})',
  1253. array(
  1254. 'topics_list' => $topics,
  1255. 'id_topic' => $id_topic,
  1256. 'target_board' => $target_board,
  1257. )
  1258. );
  1259. // Change the subject of the first message...
  1260. $smcFunc['db_query']('', '
  1261. UPDATE {db_prefix}messages
  1262. SET subject = {string:target_subject}
  1263. WHERE id_msg = {int:first_msg}',
  1264. array(
  1265. 'first_msg' => $first_msg,
  1266. 'target_subject' => $target_subject,
  1267. )
  1268. );
  1269. // Adjust all calendar events to point to the new topic.
  1270. $smcFunc['db_query']('', '
  1271. UPDATE {db_prefix}calendar
  1272. SET
  1273. id_topic = {int:id_topic},
  1274. id_board = {int:target_board}
  1275. WHERE id_topic IN ({array_int:deleted_topics})',
  1276. array(
  1277. 'deleted_topics' => $deleted_topics,
  1278. 'id_topic' => $id_topic,
  1279. 'target_board' => $target_board,
  1280. )
  1281. );
  1282. // Merge log topic entries.
  1283. $request = $smcFunc['db_query']('', '
  1284. SELECT id_member, MIN(id_msg) AS new_id_msg
  1285. FROM {db_prefix}log_topics
  1286. WHERE id_topic IN ({array_int:topics})
  1287. GROUP BY id_member',
  1288. array(
  1289. 'topics' => $topics,
  1290. )
  1291. );
  1292. if ($smcFunc['db_num_rows']($request) > 0)
  1293. {
  1294. $replaceEntries = array();
  1295. while ($row = $smcFunc['db_fetch_assoc']($request))
  1296. $replaceEntries[] = array($row['id_member'], $id_topic, $row['new_id_msg']);
  1297. $smcFunc['db_insert']('replace',
  1298. '{db_prefix}log_topics',
  1299. array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int'),
  1300. $replaceEntries,
  1301. array('id_member', 'id_topic')
  1302. );
  1303. unset($replaceEntries);
  1304. // Get rid of the old log entries.
  1305. $smcFunc['db_query']('', '
  1306. DELETE FROM {db_prefix}log_topics
  1307. WHERE id_topic IN ({array_int:deleted_topics})',
  1308. array(
  1309. 'deleted_topics' => $deleted_topics,
  1310. )
  1311. );
  1312. }
  1313. $smcFunc['db_free_result']($request);
  1314. // Merge topic notifications.
  1315. $notifications = isset($_POST['notifications']) && is_array($_POST['notifications']) ? array_intersect($topics, $_POST['notifications']) : array();
  1316. if (!empty($notifications))
  1317. {
  1318. $request = $smcFunc['db_query']('', '
  1319. SELECT id_member, MAX(sent) AS sent
  1320. FROM {db_prefix}log_notify
  1321. WHERE id_topic IN ({array_int:topics_list})
  1322. GROUP BY id_member',
  1323. array(
  1324. 'topics_list' => $notifications,
  1325. )
  1326. );
  1327. if ($smcFunc['db_num_rows']($request) > 0)
  1328. {
  1329. $replaceEntries = array();
  1330. while ($row = $smcFunc['db_fetch_assoc']($request))
  1331. $replaceEntries[] = array($row['id_member'], $id_topic, 0, $row['sent']);
  1332. $smcFunc['db_insert']('replace',
  1333. '{db_prefix}log_notify',
  1334. array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'sent' => 'int'),
  1335. $replaceEntries,
  1336. array('id_member', 'id_topic', 'id_board')
  1337. );
  1338. unset($replaceEntries);
  1339. $smcFunc['db_query']('', '
  1340. DELETE FROM {db_prefix}log_topics
  1341. WHERE id_topic IN ({array_int:deleted_topics})',
  1342. array(
  1343. 'deleted_topics' => $deleted_topics,
  1344. )
  1345. );
  1346. }
  1347. $smcFunc['db_free_result']($request);
  1348. }
  1349. // Get rid of the redundant polls.
  1350. if (!empty($deleted_polls))
  1351. {
  1352. $smcFunc['db_query']('', '
  1353. DELETE FROM {db_prefix}polls
  1354. WHERE id_poll IN ({array_int:deleted_polls})',
  1355. array(
  1356. 'deleted_polls' => $deleted_polls,
  1357. )
  1358. );
  1359. $smcFunc['db_query']('', '
  1360. DELETE FROM {db_prefix}poll_choices
  1361. WHERE id_poll IN ({array_int:deleted_polls})',
  1362. array(
  1363. 'deleted_polls' => $deleted_polls,
  1364. )
  1365. );
  1366. $smcFunc['db_query']('', '
  1367. DELETE FROM {db_prefix}log_polls
  1368. WHERE id_poll IN ({array_int:deleted_polls})',
  1369. array(
  1370. 'deleted_polls' => $deleted_polls,
  1371. )
  1372. );
  1373. }
  1374. // Cycle through each board...
  1375. foreach ($boardTotals as $id_board => $stats)
  1376. {
  1377. $smcFunc['db_query']('', '
  1378. UPDATE {db_prefix}boards
  1379. SET
  1380. num_topics = CASE WHEN {int:topics} > num_topics THEN 0 ELSE num_topics - {int:topics} END,
  1381. unapproved_topics = CASE WHEN {int:unapproved_topics} > unapproved_topics THEN 0 ELSE unapproved_topics - {int:unapproved_topics} END,
  1382. num_posts = CASE WHEN {int:posts} > num_posts THEN 0 ELSE num_posts - {int:posts} END,
  1383. unapproved_posts = CASE WHEN {int:unapproved_posts} > unapproved_posts THEN 0 ELSE unapproved_posts - {int:unapproved_posts} END
  1384. WHERE id_board = {int:id_board}',
  1385. array(
  1386. 'id_board' => $id_board,
  1387. 'topics' => $stats['topics'],
  1388. 'unapproved_topics' => $stats['unapproved_topics'],
  1389. 'posts' => $stats['posts'],
  1390. 'unapproved_posts' => $stats['unapproved_posts'],
  1391. )
  1392. );
  1393. }
  1394. // Determine the board the final topic resides in
  1395. $request = $smcFunc['db_query']('', '
  1396. SELECT id_board
  1397. FROM {db_prefix}topics
  1398. WHERE id_topic = {int:id_topic}
  1399. LIMIT 1',
  1400. array(
  1401. 'id_topic' => $id_topic,
  1402. )
  1403. );
  1404. list($id_board) = $smcFunc['db_fetch_row']($request);
  1405. $smcFunc['db_free_result']($request);
  1406. require_once($sourcedir . '/Subs-Post.php');
  1407. // Update all the statistics.
  1408. updateStats('topic');
  1409. updateStats('subject', $id_topic, $target_subject);
  1410. updateLastMessages($boards);
  1411. logAction('merge', array('topic' => $id_topic, 'board' => $id_board));
  1412. // Notify people that these topics have been merged?
  1413. sendNotifications($id_topic, 'merge');
  1414. // If there's a search index that needs updating, update it...
  1415. require_once($sourcedir . '/Search.php');
  1416. $searchAPI = findSearchAPI();
  1417. if (is_callable(array($searchAPI, 'topicMerge')))
  1418. $searchAPI->topicMerge($id_topic, $topics, $affected_msgs, empty($_POST['enforce_subject']) ? null : array($context['response_prefix'], $target_subject));
  1419. // Send them to the all done page.
  1420. redirectexit('action=mergetopics;sa=done;to=' . $id_topic . ';targetboard=' . $target_board);
  1421. }
  1422. // Tell the user the move was done properly.
  1423. function MergeDone()
  1424. {
  1425. global $txt, $context;
  1426. // Make sure the template knows everything...
  1427. $context['target_board'] = (int) $_GET['targetboard'];
  1428. $context['target_topic'] = (int) $_GET['to'];
  1429. $context['page_title'] = $txt['merge'];
  1430. $context['sub_template'] = 'merge_done';
  1431. }
  1432. ?>