SplitTopics.php 53 KB

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