1:    2:    3:    4:    5:    6:    7:    8:    9:   10:   11:   12:   13:   14:   15:   16:   17:   18:   19:   20:   21:   22:   23:   24:   25:   26:   27:   28:   29:   30:   31:   32:   33:   34:   35:   36:   37:   38:   39:   40:   41:   42:   43:   44:   45:   46:   47:   48:   49:   50:   51:   52:   53:   54:   55:   56:   57:   58:   59:   60:   61:   62:   63:   64:   65:   66:   67:   68:   69:   70:   71:   72:   73:   74:   75:   76:   77:   78:   79:   80:   81:   82:   83:   84:   85:   86:   87:   88:   89:   90:   91:   92:   93:   94:   95:   96:   97:   98:   99:  100:  101:  102:  103:  104:  105:  106:  107:  108:  109:  110:  111:  112:  113:  114:  115:  116:  117:  118:  119:  120:  121:  122:  123:  124:  125:  126:  127:  128:  129:  130:  131:  132:  133:  134:  135:  136:  137:  138:  139:  140:  141:  142:  143:  144:  145:  146:  147:  148:  149:  150:  151:  152:  153:  154:  155:  156:  157:  158:  159:  160:  161:  162:  163:  164:  165:  166:  167:  168:  169:  170:  171:  172:  173:  174:  175:  176:  177:  178:  179:  180:  181:  182:  183:  184:  185:  186:  187:  188:  189:  190:  191:  192:  193:  194:  195:  196:  197:  198:  199:  200:  201:  202:  203:  204:  205:  206:  207:  208:  209:  210:  211:  212:  213:  214:  215:  216:  217:  218:  219:  220:  221:  222:  223:  224:  225:  226:  227:  228:  229:  230:  231:  232:  233:  234:  235:  236:  237:  238:  239:  240:  241:  242:  243:  244:  245:  246:  247:  248:  249:  250:  251:  252:  253:  254:  255:  256:  257:  258:  259:  260:  261:  262:  263:  264:  265:  266:  267:  268:  269:  270:  271:  272:  273:  274:  275:  276:  277:  278:  279:  280:  281:  282:  283:  284:  285:  286:  287:  288:  289:  290:  291:  292:  293:  294:  295:  296:  297:  298:  299:  300:  301:  302:  303:  304:  305:  306:  307:  308:  309:  310:  311:  312:  313:  314:  315:  316:  317:  318:  319:  320:  321:  322:  323:  324:  325:  326:  327:  328:  329:  330:  331:  332:  333:  334:  335:  336:  337:  338:  339:  340:  341:  342:  343:  344:  345:  346:  347:  348:  349:  350:  351:  352:  353:  354:  355:  356:  357:  358:  359:  360:  361:  362:  363:  364:  365:  366:  367:  368:  369:  370:  371:  372:  373:  374:  375:  376:  377:  378:  379:  380:  381:  382:  383:  384:  385:  386:  387:  388:  389:  390:  391:  392:  393:  394:  395:  396:  397:  398:  399:  400:  401:  402:  403:  404:  405:  406:  407:  408:  409:  410:  411:  412:  413:  414:  415:  416:  417:  418:  419:  420:  421:  422:  423:  424:  425:  426:  427:  428:  429:  430:  431:  432:  433:  434:  435:  436:  437:  438:  439:  440:  441:  442:  443:  444:  445:  446:  447:  448:  449:  450:  451:  452:  453:  454:  455:  456:  457:  458:  459:  460:  461:  462:  463:  464:  465:  466:  467:  468:  469:  470:  471:  472:  473:  474:  475:  476:  477:  478:  479:  480:  481:  482:  483:  484:  485:  486:  487:  488:  489:  490:  491:  492:  493:  494:  495:  496:  497:  498:  499:  500:  501:  502:  503:  504:  505:  506:  507:  508:  509:  510:  511:  512:  513:  514:  515:  516:  517:  518:  519:  520:  521:  522:  523:  524:  525:  526:  527:  528:  529:  530:  531:  532:  533:  534:  535:  536:  537:  538:  539:  540:  541:  542:  543:  544:  545:  546:  547:  548:  549:  550:  551:  552:  553:  554:  555:  556:  557:  558:  559:  560:  561:  562:  563:  564:  565:  566:  567:  568:  569:  570:  571:  572:  573:  574:  575:  576:  577:  578:  579:  580:  581:  582:  583:  584:  585:  586:  587:  588:  589:  590:  591:  592:  593:  594:  595:  596:  597:  598:  599:  600:  601:  602:  603:  604:  605:  606:  607:  608:  609:  610:  611:  612:  613:  614:  615:  616:  617:  618:  619:  620:  621:  622:  623:  624:  625:  626:  627:  628:  629:  630:  631:  632:  633:  634:  635:  636:  637:  638:  639:  640:  641:  642:  643:  644:  645:  646:  647:  648:  649:  650:  651:  652:  653:  654:  655:  656:  657:  658:  659:  660:  661:  662:  663:  664:  665:  666:  667:  668:  669:  670:  671:  672:  673:  674:  675:  676:  677:  678:  679:  680:  681:  682:  683:  684:  685:  686:  687:  688:  689:  690:  691:  692:  693:  694:  695:  696:  697:  698:  699:  700:  701:  702:  703:  704:  705:  706:  707:  708:  709:  710:  711:  712:  713:  714:  715:  716:  717:  718:  719:  720:  721:  722:  723:  724:  725:  726:  727:  728:  729:  730:  731:  732:  733:  734:  735:  736:  737:  738:  739:  740:  741:  742:  743:  744:  745:  746:  747:  748:  749:  750:  751:  752:  753:  754:  755:  756:  757:  758:  759:  760:  761:  762:  763:  764:  765:  766:  767:  768:  769:  770:  771:  772:  773:  774:  775:  776:  777:  778:  779:  780:  781:  782:  783:  784:  785:  786:  787:  788:  789:  790:  791:  792:  793:  794:  795:  796:  797:  798:  799:  800:  801:  802:  803:  804:  805:  806:  807:  808:  809:  810:  811:  812:  813:  814:  815:  816:  817:  818:  819:  820:  821:  822:  823:  824:  825:  826:  827:  828:  829:  830:  831:  832:  833:  834:  835:  836:  837:  838:  839:  840:  841:  842:  843:  844:  845:  846:  847:  848:  849:  850:  851:  852:  853:  854:  855:  856:  857:  858:  859:  860:  861:  862:  863:  864:  865:  866:  867:  868:  869:  870:  871:  872:  873:  874:  875:  876:  877:  878:  879:  880:  881:  882:  883:  884:  885:  886:  887:  888:  889:  890:  891:  892:  893:  894:  895:  896:  897:  898:  899:  900:  901:  902:  903:  904:  905:  906:  907:  908:  909:  910:  911:  912:  913:  914:  915:  916:  917:  918:  919:  920:  921:  922:  923:  924:  925:  926:  927:  928:  929:  930:  931:  932:  933:  934:  935:  936:  937:  938:  939:  940:  941:  942:  943:  944:  945:  946:  947:  948:  949:  950:  951:  952:  953:  954:  955:  956:  957:  958:  959:  960:  961:  962:  963:  964:  965:  966:  967:  968:  969:  970:  971:  972:  973:  974:  975:  976:  977:  978:  979:  980:  981:  982:  983:  984:  985:  986:  987:  988:  989:  990:  991:  992:  993:  994:  995:  996:  997:  998:  999: 1000: 1001: 1002: 1003: 1004: 1005: 1006: 1007: 1008: 1009: 1010: 1011: 1012: 1013: 1014: 1015: 1016: 1017: 1018: 1019: 1020: 1021: 1022: 1023: 1024: 1025: 1026: 1027: 1028: 1029: 1030: 1031: 1032: 1033: 1034: 1035: 1036: 1037: 1038: 1039: 1040: 1041: 1042: 1043: 1044: 1045: 1046: 1047: 1048: 1049: 1050: 1051: 1052: 1053: 1054: 1055: 1056: 1057: 1058: 1059: 1060: 1061: 1062: 1063: 1064: 1065: 1066: 1067: 1068: 1069: 1070: 1071: 1072: 1073: 1074: 1075: 1076: 1077: 1078: 1079: 1080: 1081: 1082: 1083: 1084: 1085: 1086: 1087: 1088: 1089: 1090: 1091: 1092: 1093: 1094: 1095: 1096: 1097: 1098: 1099: 1100: 1101: 1102: 1103: 1104: 1105: 1106: 1107: 1108: 1109: 1110: 1111: 1112: 1113: 1114: 1115: 1116: 1117: 1118: 1119: 1120: 1121: 1122: 1123: 1124: 1125: 1126: 1127: 1128: 1129: 1130: 1131: 1132: 1133: 1134: 1135: 1136: 1137: 1138: 1139: 1140: 1141: 1142: 1143: 1144: 1145: 1146: 1147: 1148: 1149: 1150: 1151: 1152: 1153: 1154: 1155: 1156: 1157: 1158: 1159: 1160: 1161: 1162: 1163: 1164: 1165: 1166: 1167: 1168: 1169: 1170: 1171: 1172: 1173: 1174: 1175: 1176: 1177: 1178: 1179: 1180: 1181: 1182: 1183: 1184: 1185: 1186: 1187: 1188: 1189: 1190: 1191: 1192: 1193: 1194: 1195: 1196: 1197: 1198: 1199: 1200: 1201: 1202: 1203: 1204: 1205: 1206: 1207: 1208: 1209: 1210: 1211: 1212: 1213: 1214: 1215: 1216: 1217: 1218: 1219: 1220: 1221: 1222: 1223: 1224: 1225: 1226: 1227: 1228: 1229: 1230: 1231: 1232: 1233: 1234: 1235: 1236: 1237: 1238: 1239: 1240: 1241: 1242: 1243: 1244: 1245: 1246: 1247: 1248: 1249: 1250: 1251: 1252: 1253: 1254: 1255: 1256: 1257: 1258: 1259: 1260: 1261: 1262: 1263: 1264: 1265: 1266: 1267: 1268: 1269: 1270: 1271: 1272: 1273: 1274: 1275: 1276: 1277: 1278: 1279: 1280: 1281: 1282: 1283: 1284: 1285: 1286: 1287: 1288: 1289: 1290: 1291: 1292: 1293: 1294: 1295: 1296: 1297: 1298: 1299: 1300: 1301: 1302: 1303: 1304: 1305: 1306: 1307: 1308: 1309: 1310: 1311: 1312: 1313: 1314: 1315: 1316: 1317: 1318: 1319: 1320: 1321: 1322: 1323: 1324: 1325: 1326: 1327: 1328: 1329: 1330: 1331: 1332: 1333: 1334: 1335: 1336: 1337: 1338: 1339: 1340: 1341: 1342: 1343: 1344: 1345: 1346: 1347: 1348: 1349: 1350: 1351: 1352: 1353: 1354: 1355: 1356: 1357: 1358: 1359: 1360: 1361: 1362: 1363: 1364: 1365: 1366: 1367: 1368: 1369: 1370: 1371: 1372: 1373: 1374: 1375: 1376: 1377: 1378: 1379: 1380: 1381: 1382: 1383: 1384: 1385: 1386: 1387: 1388: 1389: 1390: 1391: 1392: 1393: 1394: 1395: 1396: 1397: 1398: 1399: 1400: 1401: 1402: 1403: 1404: 1405: 1406: 1407: 1408: 1409: 1410: 1411: 1412: 1413: 1414: 1415: 1416: 1417: 1418: 1419: 1420: 1421: 1422: 1423: 1424: 1425: 1426: 1427: 1428: 1429: 1430: 1431: 1432: 1433: 1434: 1435: 1436: 1437: 1438: 1439: 1440: 1441: 1442: 1443: 1444: 1445: 1446: 1447: 1448: 1449: 1450: 1451: 1452: 1453: 1454: 1455: 1456: 1457: 1458: 1459: 1460: 1461: 1462: 1463: 1464: 1465: 1466: 1467: 1468: 1469: 1470: 1471: 1472: 1473: 1474: 1475: 1476: 1477: 1478: 1479: 1480: 1481: 1482: 1483: 1484: 1485: 1486: 1487: 1488: 1489: 1490: 1491: 1492: 1493: 1494: 1495: 1496: 1497: 1498: 1499: 1500: 1501: 1502: 1503: 1504: 1505: 1506: 1507: 1508: 1509: 1510: 1511: 1512: 1513: 1514: 1515: 1516: 1517: 1518: 1519: 1520: 1521: 1522: 1523: 1524: 1525: 1526: 1527: 1528: 1529: 1530: 1531: 1532: 1533: 1534: 1535: 1536: 1537: 1538: 1539: 1540: 1541: 1542: 1543: 1544: 1545: 1546: 1547: 1548: 1549: 1550: 1551: 1552: 1553: 1554: 1555: 1556: 1557: 1558: 1559: 1560: 1561: 1562: 1563: 1564: 1565: 1566: 1567: 1568: 1569: 1570: 1571: 1572: 1573: 1574: 1575: 1576: 1577: 1578: 1579: 1580: 1581: 1582: 1583: 1584: 1585: 1586: 1587: 1588: 1589: 1590: 1591: 1592: 1593: 1594: 1595: 1596: 1597: 1598: 1599: 1600: 1601: 1602: 1603: 1604: 1605: 1606: 1607: 1608: 1609: 1610: 1611: 1612: 1613: 1614: 1615: 1616: 1617: 1618: 1619: 1620: 1621: 1622: 1623: 1624: 1625: 1626: 1627: 1628: 1629: 1630: 1631: 1632: 1633: 1634: 1635: 1636: 1637: 1638: 1639: 1640: 1641: 1642: 1643: 1644: 1645: 1646: 1647: 1648: 1649: 1650: 1651: 1652: 1653: 1654: 1655: 1656: 1657: 1658: 1659: 1660: 1661: 1662: 1663: 1664: 1665: 1666: 1667: 1668: 1669: 1670: 1671: 1672: 1673: 1674: 1675: 1676: 1677: 1678: 1679: 1680: 1681: 1682: 1683: 1684: 1685: 1686: 1687: 1688: 1689: 1690: 1691: 1692: 1693: 1694: 1695: 1696: 1697: 1698: 1699: 1700: 1701: 1702: 1703: 1704: 1705: 1706: 1707: 1708: 1709: 1710: 1711: 1712: 1713: 1714: 1715: 1716: 1717: 1718: 1719: 1720: 1721: 1722: 1723: 1724: 1725: 1726: 1727: 1728: 1729: 1730: 1731: 1732: 1733: 1734: 1735: 1736: 1737: 1738: 1739: 1740: 1741: 1742: 1743: 1744: 1745: 1746: 1747: 1748: 1749: 1750: 1751: 1752: 1753: 1754: 1755: 1756: 1757: 1758: 1759: 1760: 1761: 1762: 1763: 1764: 1765: 1766: 1767: 1768: 1769: 1770: 1771: 1772: 1773: 1774: 1775: 1776: 1777: 1778: 1779: 1780: 1781: 1782: 1783: 1784: 1785: 1786: 1787: 
<?php
if (!defined('SMF'))
    die('No direct access...');
function SplitTopics()
{
    global $topic, $sourcedir;
    
    if (empty($topic))
        fatal_lang_error('numbers_one_to_nine', false);
    
    isAllowedTo('split_any');
    
    if (!isset($_REQUEST['xml']))
        loadTemplate('SplitTopics');
    require_once($sourcedir . '/Subs-Boards.php');
    require_once($sourcedir . '/Subs-Post.php');
    $subActions = array(
        'selectTopics' => 'SplitSelectTopics',
        'execute' => 'SplitExecute',
        'index' => 'SplitIndex',
        'splitSelection' => 'SplitSelectionExecute',
    );
    
    if (empty($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
        SplitIndex();
    else
        call_helper($subActions[$_REQUEST['sa']]);
}
function SplitIndex()
{
    global $txt, $topic, $context, $smcFunc, $modSettings;
    
    if (empty($_GET['at']))
        fatal_lang_error('numbers_one_to_nine', false);
    $_GET['at'] = (int) $_GET['at'];
    
    $request = $smcFunc['db_query']('', '
        SELECT m.subject, t.num_replies, t.unapproved_posts, t.id_first_msg, t.approved
        FROM {db_prefix}messages AS m
            INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
        WHERE m.id_msg = {int:split_at}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
            AND m.approved = 1') . '
            AND m.id_topic = {int:current_topic}
        LIMIT 1',
        array(
            'current_topic' => $topic,
            'split_at' => $_GET['at'],
        )
    );
    if ($smcFunc['db_num_rows']($request) == 0)
        fatal_lang_error('cant_find_messages');
    list ($_REQUEST['subname'], $num_replies, $unapproved_posts, $id_first_msg, $approved) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    
    if ($modSettings['postmod_active'] && !$approved)
        isAllowedTo('approve_posts');
    
    if ($modSettings['postmod_active'] && allowedTo('approve_posts'))
        $num_replies += $unapproved_posts - ($approved ? 0 : 1);
    
    if ($num_replies < 1)
        fatal_lang_error('topic_one_post', false);
    
    if ($id_first_msg == $_GET['at'])
        return SplitSelectTopics();
    
    $context['message'] = array(
        'id' => $_GET['at'],
        'subject' => $_REQUEST['subname']
    );
    $context['sub_template'] = 'ask';
    $context['page_title'] = $txt['split'];
}
function SplitExecute()
{
    global $txt, $topic, $context, $smcFunc;
    
    checkSession();
    
    if (!isset($_POST['subname']) || $_POST['subname'] == '')
        $_POST['subname'] = $txt['new_topic'];
    
    if ($_POST['step2'] == 'selective')
        redirectexit ('action=splittopics;sa=selectTopics;subname=' . $_POST['subname'] . ';topic=' . $topic . '.0;start2=0');
    $_POST['at'] = (int) $_POST['at'];
    $messagesToBeSplit = array();
    if ($_POST['step2'] == 'afterthis')
    {
        
        $request = $smcFunc['db_query']('', '
            SELECT id_msg
            FROM {db_prefix}messages
            WHERE id_topic = {int:current_topic}
                AND id_msg >= {int:split_at}',
            array(
                'current_topic' => $topic,
                'split_at' => $_POST['at'],
            )
        );
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $messagesToBeSplit[] = $row['id_msg'];
        $smcFunc['db_free_result']($request);
    }
    
    elseif ($_POST['step2'] == 'onlythis')
        $messagesToBeSplit[] = $_POST['at'];
    
    else
        fatal_lang_error('no_access', false);
    $context['old_topic'] = $topic;
    $context['new_topic'] = splitTopic($topic, $messagesToBeSplit, $_POST['subname']);
    $context['page_title'] = $txt['split'];
}
function SplitSelectTopics()
{
    global $txt, $scripturl, $topic, $context, $modSettings, $original_msgs, $smcFunc, $options;
    $context['page_title'] = $txt['split'] . ' - ' . $txt['select_split_posts'];
    
    $_SESSION['split_selection'][$topic] = empty($_SESSION['split_selection'][$topic]) ? array() : $_SESSION['split_selection'][$topic];
    
    if (isset($_REQUEST['subname_enc']))
        $_REQUEST['subname'] = urldecode($_REQUEST['subname_enc']);
    $context['not_selected'] = array(
        'num_messages' => 0,
        'start' => empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'],
        'messages' => array(),
    );
    $context['selected'] = array(
        'num_messages' => 0,
        'start' => empty($_REQUEST['start2']) ? 0 : (int) $_REQUEST['start2'],
        'messages' => array(),
    );
    $context['topic'] = array(
        'id' => $topic,
        'subject' => urlencode($_REQUEST['subname']),
    );
    
    $context['new_subject'] = $_REQUEST['subname'];
    
    $context['sub_template'] = isset($_REQUEST['xml']) ? 'split' : 'select';
    
    $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
    
    if (isset($_REQUEST['xml']))
    {
        $original_msgs = array(
            'not_selected' => array(),
            'selected' => array(),
        );
        $request = $smcFunc['db_query']('', '
            SELECT id_msg
            FROM {db_prefix}messages
            WHERE id_topic = {int:current_topic}' . (empty($_SESSION['split_selection'][$topic]) ? '' : '
                AND id_msg NOT IN ({array_int:no_split_msgs})') . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
                AND approved = {int:is_approved}') . '
                ' . (empty($options['view_newest_first']) ? '' : 'ORDER BY id_msg DESC') . '
                LIMIT {int:start}, {int:messages_per_page}',
            array(
                'current_topic' => $topic,
                'no_split_msgs' => empty($_SESSION['split_selection'][$topic]) ? array() : $_SESSION['split_selection'][$topic],
                'is_approved' => 1,
                'start' => $context['not_selected']['start'],
                'messages_per_page' => $context['messages_per_page'],
            )
        );
        
        if (empty($context['not_selected']['start']) && $smcFunc['db_num_rows']($request) <= 1 && $_REQUEST['move'] == 'down')
            $_REQUEST['move'] = '';
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $original_msgs['not_selected'][] = $row['id_msg'];
        $smcFunc['db_free_result']($request);
        if (!empty($_SESSION['split_selection'][$topic]))
        {
            $request = $smcFunc['db_query']('', '
                SELECT id_msg
                FROM {db_prefix}messages
                WHERE id_topic = {int:current_topic}
                    AND id_msg IN ({array_int:split_msgs})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
                    AND approved = {int:is_approved}') . '
                ' . (empty($options['view_newest_first']) ? '' : 'ORDER BY id_msg DESC') . '
                LIMIT {int:start}, {int:messages_per_page}',
                array(
                    'current_topic' => $topic,
                    'split_msgs' => $_SESSION['split_selection'][$topic],
                    'is_approved' => 1,
                    'start' => $context['selected']['start'],
                    'messages_per_page' => $context['messages_per_page'],
                )
            );
            while ($row = $smcFunc['db_fetch_assoc']($request))
                $original_msgs['selected'][] = $row['id_msg'];
            $smcFunc['db_free_result']($request);
        }
    }
    
    if (!empty($_REQUEST['move']))
    {
        $_REQUEST['msg'] = (int) $_REQUEST['msg'];
        if ($_REQUEST['move'] == 'reset')
            $_SESSION['split_selection'][$topic] = array();
        elseif ($_REQUEST['move'] == 'up')
            $_SESSION['split_selection'][$topic] = array_diff($_SESSION['split_selection'][$topic], array($_REQUEST['msg']));
        else
            $_SESSION['split_selection'][$topic][] = $_REQUEST['msg'];
    }
    
    if (!empty($_SESSION['split_selection'][$topic]))
    {
        $request = $smcFunc['db_query']('', '
            SELECT id_msg
            FROM {db_prefix}messages
            WHERE id_topic = {int:current_topic}
                AND id_msg IN ({array_int:split_msgs})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
                AND approved = {int:is_approved}'),
            array(
                'current_topic' => $topic,
                'split_msgs' => $_SESSION['split_selection'][$topic],
                'is_approved' => 1,
            )
        );
        $_SESSION['split_selection'][$topic] = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $_SESSION['split_selection'][$topic][] = $row['id_msg'];
        $smcFunc['db_free_result']($request);
    }
    
    $request = $smcFunc['db_query']('', '
        SELECT ' . (empty($_SESSION['split_selection'][$topic]) ? '0' : 'm.id_msg IN ({array_int:split_msgs})') . ' AS is_selected, COUNT(*) AS num_messages
        FROM {db_prefix}messages AS m
        WHERE m.id_topic = {int:current_topic}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
            AND approved = {int:is_approved}') . (empty($_SESSION['split_selection'][$topic]) ? '' : '
        GROUP BY is_selected'),
        array(
            'current_topic' => $topic,
            'split_msgs' => !empty($_SESSION['split_selection'][$topic]) ? $_SESSION['split_selection'][$topic] : array(),
            'is_approved' => 1,
        )
    );
    while ($row = $smcFunc['db_fetch_assoc']($request))
        $context[empty($row['is_selected']) || $row['is_selected'] == 'f' ? 'not_selected' : 'selected']['num_messages'] = $row['num_messages'];
    $smcFunc['db_free_result']($request);
    
    if ($context['selected']['start'] >= $context['selected']['num_messages'])
        $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'])));
    
    $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);
    
    $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);
    
    $request = $smcFunc['db_query']('', '
        SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS real_name, m.poster_time, m.body, m.id_msg, m.smileys_enabled
        FROM {db_prefix}messages AS m
            LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
        WHERE m.id_topic = {int:current_topic}' . (empty($_SESSION['split_selection'][$topic]) ? '' : '
            AND id_msg NOT IN ({array_int:no_split_msgs})') . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
            AND approved = {int:is_approved}') . '
            ' . (empty($options['view_newest_first']) ? '' : 'ORDER BY m.id_msg DESC') . '
            LIMIT {int:start}, {int:messages_per_page}',
        array(
            'current_topic' => $topic,
            'no_split_msgs' => !empty($_SESSION['split_selection'][$topic]) ? $_SESSION['split_selection'][$topic] : array(),
            'is_approved' => 1,
            'start' => $context['not_selected']['start'],
            'messages_per_page' => $context['messages_per_page'],
        )
    );
    $context['messages'] = array();
    for ($counter = 0; $row = $smcFunc['db_fetch_assoc']($request); $counter++)
    {
        censorText($row['subject']);
        censorText($row['body']);
        $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
        $context['not_selected']['messages'][$row['id_msg']] = array(
            'id' => $row['id_msg'],
            'subject' => $row['subject'],
            'time' => timeformat($row['poster_time']),
            'timestamp' => forum_time(true, $row['poster_time']),
            'body' => $row['body'],
            'poster' => $row['real_name'],
        );
    }
    $smcFunc['db_free_result']($request);
    
    if (!empty($_SESSION['split_selection'][$topic]))
    {
        
        $request = $smcFunc['db_query']('', '
            SELECT m.subject, COALESCE(mem.real_name, m.poster_name) AS real_name,  m.poster_time, m.body, m.id_msg, m.smileys_enabled
            FROM {db_prefix}messages AS m
                LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
            WHERE m.id_topic = {int:current_topic}
                AND m.id_msg IN ({array_int:split_msgs})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
                AND approved = {int:is_approved}') . '
            ' . (empty($options['view_newest_first']) ? '' : 'ORDER BY m.id_msg DESC') . '
            LIMIT {int:start}, {int:messages_per_page}',
            array(
                'current_topic' => $topic,
                'split_msgs' => $_SESSION['split_selection'][$topic],
                'is_approved' => 1,
                'start' => $context['selected']['start'],
                'messages_per_page' => $context['messages_per_page'],
            )
        );
        $context['messages'] = array();
        for ($counter = 0; $row = $smcFunc['db_fetch_assoc']($request); $counter++)
        {
            censorText($row['subject']);
            censorText($row['body']);
            $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
            $context['selected']['messages'][$row['id_msg']] = array(
                'id' => $row['id_msg'],
                'subject' => $row['subject'],
                'time' => timeformat($row['poster_time']),
                'timestamp' => forum_time(true, $row['poster_time']),
                'body' => $row['body'],
                'poster' => $row['real_name']
            );
        }
        $smcFunc['db_free_result']($request);
    }
    
    if (isset($_REQUEST['xml']))
    {
        $changes = array(
            'remove' => array(
                'not_selected' => array_diff($original_msgs['not_selected'], array_keys($context['not_selected']['messages'])),
                'selected' => array_diff($original_msgs['selected'], array_keys($context['selected']['messages'])),
            ),
            'insert' => array(
                'not_selected' => array_diff(array_keys($context['not_selected']['messages']), $original_msgs['not_selected']),
                'selected' => array_diff(array_keys($context['selected']['messages']), $original_msgs['selected']),
            ),
        );
        $context['changes'] = array();
        foreach ($changes as $change_type => $change_array)
            foreach ($change_array as $section => $msg_array)
            {
                if (empty($msg_array))
                    continue;
                foreach ($msg_array as $id_msg)
                {
                    $context['changes'][$change_type . $id_msg] = array(
                        'id' => $id_msg,
                        'type' => $change_type,
                        'section' => $section,
                    );
                    if ($change_type == 'insert')
                        $context['changes']['insert' . $id_msg]['insert_value'] = $context[$section]['messages'][$id_msg];
                }
            }
    }
}
function SplitSelectionExecute()
{
    global $txt, $topic, $context;
    
    checkSession();
    
    if (!isset($_POST['subname']) || $_POST['subname'] == '')
        $_POST['subname'] = $txt['new_topic'];
    
    if (empty($_SESSION['split_selection'][$topic]))
        fatal_lang_error('no_posts_selected', false);
    $context['old_topic'] = $topic;
    $context['new_topic'] = splitTopic($topic, $_SESSION['split_selection'][$topic], $_POST['subname']);
    $context['page_title'] = $txt['split'];
}
function splitTopic($split1_ID_TOPIC, $splitMessages, $new_subject)
{
    global $smcFunc, $txt, $sourcedir;
    
    if (empty($splitMessages))
        fatal_lang_error('no_posts_selected', false);
    
    $request = $smcFunc['db_query']('', '
        SELECT id_board, approved
        FROM {db_prefix}topics
        WHERE id_topic = {int:id_topic}
        LIMIT 1',
        array(
            'id_topic' => $split1_ID_TOPIC,
        )
    );
    list ($id_board, $split1_approved) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    
    $request = $smcFunc['db_query']('', '
        SELECT
            MIN(m.id_msg) AS myid_first_msg, MAX(m.id_msg) AS myid_last_msg, COUNT(*) AS message_count, m.approved
        FROM {db_prefix}messages AS m
            INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:id_topic})
        WHERE m.id_msg NOT IN ({array_int:no_msg_list})
            AND m.id_topic = {int:id_topic}
        GROUP BY m.approved
        ORDER BY m.approved DESC
        LIMIT 2',
        array(
            'id_topic' => $split1_ID_TOPIC,
            'no_msg_list' => $splitMessages,
        )
    );
    
    if ($smcFunc['db_num_rows']($request) == 0)
        fatal_lang_error('selected_all_posts', false);
    $split1_first_msg = null;
    $split1_last_msg = null;
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        
        if (empty($split1_first_msg) || $row['myid_first_msg'] < $split1_first_msg)
            $split1_first_msg = $row['myid_first_msg'];
        if (empty($split1_last_msg) || $row['approved'])
            $split1_last_msg = $row['myid_last_msg'];
        
        if ($row['approved'])
        {
            $split1_replies = $row['message_count'] - 1;
            $split1_unapprovedposts = 0;
        }
        else
        {
            if (!isset($split1_replies))
                $split1_replies = 0;
            
            elseif (!$split1_approved)
                $split1_replies++;
            $split1_unapprovedposts = $row['message_count'];
        }
    }
    $smcFunc['db_free_result']($request);
    $split1_firstMem = getMsgMemberID($split1_first_msg);
    $split1_lastMem = getMsgMemberID($split1_last_msg);
    
    $request = $smcFunc['db_query']('', '
        SELECT MIN(id_msg) AS myid_first_msg, MAX(id_msg) AS myid_last_msg, COUNT(*) AS message_count, approved
        FROM {db_prefix}messages
        WHERE id_msg IN ({array_int:msg_list})
            AND id_topic = {int:id_topic}
        GROUP BY id_topic, approved
        ORDER BY approved DESC
        LIMIT 2',
        array(
            'msg_list' => $splitMessages,
            'id_topic' => $split1_ID_TOPIC,
        )
    );
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        
        if (empty($split2_first_msg) || $row['myid_first_msg'] < $split2_first_msg)
            $split2_first_msg = $row['myid_first_msg'];
        if (empty($split2_last_msg) || $row['approved'])
            $split2_last_msg = $row['myid_last_msg'];
        
        if ($row['approved'])
        {
            $split2_approved = true;
            $split2_replies = $row['message_count'] - 1;
            $split2_unapprovedposts = 0;
        }
        else
        {
            
            if ($split2_first_msg == $row['myid_first_msg'])
                $split2_approved = false;
            if (!isset($split2_replies))
                $split2_replies = 0;
            
            elseif (!$split2_approved)
                $split2_replies++;
            $split2_unapprovedposts = $row['message_count'];
        }
    }
    $smcFunc['db_free_result']($request);
    $split2_firstMem = getMsgMemberID($split2_first_msg);
    $split2_lastMem = getMsgMemberID($split2_last_msg);
    
    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))
        fatal_lang_error('cant_find_messages');
    
    if ($split1_first_msg > $split2_first_msg)
        fatal_lang_error('split_first_post', false);
    
    $split2_ID_TOPIC = $smcFunc['db_insert']('',
        '{db_prefix}topics',
        array(
            'id_board' => 'int',
            'id_member_started' => 'int',
            'id_member_updated' => 'int',
            'id_first_msg' => 'int',
            'id_last_msg' => 'int',
            'num_replies' => 'int',
            'unapproved_posts' => 'int',
            'approved' => 'int',
            'is_sticky' => 'int',
        ),
        array(
            (int) $id_board, $split2_firstMem, $split2_lastMem, 0,
            0, $split2_replies, $split2_unapprovedposts, (int) $split2_approved, 0,
        ),
        array('id_topic'),
        1
    );
    if ($split2_ID_TOPIC <= 0)
        fatal_lang_error('cant_insert_topic');
    
    $new_subject = strtr($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($new_subject)), array("\r" => '', "\n" => '', "\t" => ''));
    
    if ($smcFunc['strlen']($new_subject) > 100)
        $new_subject = $smcFunc['substr']($new_subject, 0, 100);
    
    if ($new_subject != '')
    {
        $smcFunc['db_query']('', '
            UPDATE {db_prefix}messages
            SET
                id_topic = {int:id_topic},
                subject = CASE WHEN id_msg = {int:split_first_msg} THEN {string:new_subject} ELSE {string:new_subject_replies} END
            WHERE id_msg IN ({array_int:split_msgs})',
            array(
                'split_msgs' => $splitMessages,
                'id_topic' => $split2_ID_TOPIC,
                'new_subject' => $new_subject,
                'split_first_msg' => $split2_first_msg,
                'new_subject_replies' => $txt['response_prefix'] . $new_subject,
            )
        );
        
        updateStats('subject', $split2_ID_TOPIC, $new_subject);
    }
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}log_reported
        SET id_topic = {int:id_topic}
        WHERE id_msg IN ({array_int:split_msgs})',
        array(
            'split_msgs' => $splitMessages,
            'id_topic' => $split2_ID_TOPIC,
        )
    );
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}topics
        SET
            num_replies = {int:num_replies},
            id_first_msg = {int:id_first_msg},
            id_last_msg = {int:id_last_msg},
            id_member_started = {int:id_member_started},
            id_member_updated = {int:id_member_updated},
            unapproved_posts = {int:unapproved_posts}
        WHERE id_topic = {int:id_topic}',
        array(
            'num_replies' => $split1_replies,
            'id_first_msg' => $split1_first_msg,
            'id_last_msg' => $split1_last_msg,
            'id_member_started' => $split1_firstMem,
            'id_member_updated' => $split1_lastMem,
            'unapproved_posts' => $split1_unapprovedposts,
            'id_topic' => $split1_ID_TOPIC,
        )
    );
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}topics
        SET
            id_first_msg = {int:id_first_msg},
            id_last_msg = {int:id_last_msg}
        WHERE id_topic = {int:id_topic}',
        array(
            'id_first_msg' => $split2_first_msg,
            'id_last_msg' => $split2_last_msg,
            'id_topic' => $split2_ID_TOPIC,
        )
    );
    
    if (!$split2_approved)
        $smcFunc['db_query']('', '
            UPDATE {db_prefix}messages
            SET approved = {int:approved}
            WHERE id_msg = {int:id_msg}
                AND id_topic = {int:id_topic}',
            array(
                'approved' => 0,
                'id_msg' => $split2_first_msg,
                'id_topic' => $split2_ID_TOPIC,
            )
        );
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}boards
        SET ' . ($split2_approved ? '
            num_topics = num_topics + 1' : '
            unapproved_topics = unapproved_topics + 1') . '
        WHERE id_board = {int:id_board}',
        array(
            'id_board' => $id_board,
        )
    );
    
    
    $request = $smcFunc['db_query']('', '
        SELECT id_member, id_msg, unwatched
        FROM {db_prefix}log_topics
        WHERE id_topic = {int:id_topic}',
        array(
            'id_topic' => (int) $split1_ID_TOPIC,
        )
    );
    if ($smcFunc['db_num_rows']($request) > 0)
    {
        $replaceEntries = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $replaceEntries[] = array($row['id_member'], $split2_ID_TOPIC, $row['id_msg'], $row['unwatched']);
        $smcFunc['db_insert']('ignore',
            '{db_prefix}log_topics',
            array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int'),
            $replaceEntries,
            array('id_member', 'id_topic')
        );
        unset($replaceEntries);
    }
    $smcFunc['db_free_result']($request);
    
    updateStats('topic');
    updateLastMessages($id_board);
    logAction('split', array('topic' => $split1_ID_TOPIC, 'new_topic' => $split2_ID_TOPIC, 'board' => $id_board));
    
    sendNotifications($split1_ID_TOPIC, 'split');
    
    require_once($sourcedir . '/Search.php');
    $searchAPI = findSearchAPI();
    if (is_callable(array($searchAPI, 'topicSplit')))
        $searchAPI->topicSplit($split2_ID_TOPIC, $splitMessages);
    
    $split1 = array(
        'num_replies' => $split1_replies,
        'id_first_msg' => $split1_first_msg,
        'id_last_msg' => $split1_last_msg,
        'id_member_started' => $split1_firstMem,
        'id_member_updated' => $split1_lastMem,
        'unapproved_posts' => $split1_unapprovedposts,
        'id_topic' => $split1_ID_TOPIC,
    );
    $split2 = array(
        'num_replies' => $split2_replies,
        'id_first_msg' => $split2_first_msg,
        'id_last_msg' => $split2_last_msg,
        'id_member_started' => $split2_firstMem,
        'id_member_updated' => $split2_lastMem,
        'unapproved_posts' => $split2_unapprovedposts,
        'id_topic' => $split2_ID_TOPIC,
    );
    call_integration_hook('integrate_split_topic', array($split1, $split2, $new_subject, $id_board));
    
    return $split2_ID_TOPIC;
}
function MergeTopics()
{
    
    loadTemplate('MoveTopic');
    $subActions = array(
        'done' => 'MergeDone',
        'execute' => 'MergeExecute',
        'index' => 'MergeIndex',
        'options' => 'MergeExecute',
    );
    
    if (empty($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]))
        MergeIndex();
    else
        call_helper($subActions[$_REQUEST['sa']]);
}
function MergeIndex()
{
    global $txt, $board, $context, $smcFunc, $sourcedir;
    global $scripturl, $modSettings;
    if (!isset($_GET['from']))
        fatal_lang_error('no_access', false);
    $_GET['from'] = (int) $_GET['from'];
    $_REQUEST['targetboard'] = isset($_REQUEST['targetboard']) ? (int) $_REQUEST['targetboard'] : $board;
    $context['target_board'] = $_REQUEST['targetboard'];
    
    if ($modSettings['postmod_active'])
    {
        $can_approve_boards = boardsAllowedTo('approve_posts');
        $onlyApproved = $can_approve_boards !== array(0) && !in_array($_REQUEST['targetboard'], $can_approve_boards);
    }
    else
        $onlyApproved = false;
    
    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}topics AS t
        WHERE t.id_board = {int:id_board}' . ($onlyApproved ? '
            AND t.approved = {int:is_approved}' : ''),
        array(
            'id_board' => $_REQUEST['targetboard'],
            'is_approved' => 1,
        )
    );
    list ($topiccount) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    
    $context['page_index'] = constructPageIndex($scripturl . '?action=mergetopics;from=' . $_GET['from'] . ';targetboard=' . $_REQUEST['targetboard'] . ';board=' . $board . '.%1$d', $_REQUEST['start'], $topiccount, $modSettings['defaultMaxTopics'], true);
    
    $request = $smcFunc['db_query']('', '
        SELECT m.subject
        FROM {db_prefix}topics AS t
            INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
        WHERE t.id_topic = {int:id_topic}
            AND t.id_board = {int:current_board}' . ($onlyApproved ? '
            AND t.approved = {int:is_approved}' : '') . '
        LIMIT 1',
        array(
            'current_board' => $board,
            'id_topic' => $_GET['from'],
            'is_approved' => 1,
        )
    );
    if ($smcFunc['db_num_rows']($request) == 0)
        fatal_lang_error('no_board');
    list ($subject) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    
    $context['origin_topic'] = $_GET['from'];
    $context['origin_subject'] = $subject;
    $context['origin_js_subject'] = addcslashes(addslashes($subject), '/');
    $context['page_title'] = $txt['merge'];
    
    $merge_boards = boardsAllowedTo('merge_any');
    if (empty($merge_boards))
        fatal_lang_error('cannot_merge_any', 'user');
    
    if (count($merge_boards) > 1 || in_array(0, $merge_boards))
    {
        require_once($sourcedir . '/Subs-MessageIndex.php');
        
        $options = array(
            'not_redirection' => true,
            'selected_board' => $context['target_board'],
        );
        
        if (!in_array(0, $merge_boards))
            $options['included_boards'] = $merge_boards;
        $context['merge_categories'] = getBoardList($options);
    }
    
    $request = $smcFunc['db_query']('', '
        SELECT t.id_topic, m.subject, m.id_member, COALESCE(mem.real_name, m.poster_name) AS poster_name
        FROM {db_prefix}topics AS t
            INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
            LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
        WHERE t.id_board = {int:id_board}
            AND t.id_topic != {int:id_topic}
            AND t.id_redirect_topic = {int:not_redirect}' . ($onlyApproved ? '
            AND t.approved = {int:is_approved}' : '') . '
        ORDER BY {raw:sort}
        LIMIT {int:offset}, {int:limit}',
        array(
            'id_board' => $_REQUEST['targetboard'],
            'id_topic' => $_GET['from'],
            'sort' => 't.is_sticky DESC, t.id_last_msg DESC',
            'offset' => $_REQUEST['start'],
            'limit' => $modSettings['defaultMaxTopics'],
            'is_approved' => 1,
            'not_redirect' => 0,
        )
    );
    $context['topics'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        censorText($row['subject']);
        $context['topics'][] = array(
            'id' => $row['id_topic'],
            'poster' => array(
                'id' => $row['id_member'],
                'name' => $row['poster_name'],
                'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
                'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" target="_blank" rel="noopener">' . $row['poster_name'] . '</a>'
            ),
            'subject' => $row['subject'],
            'js_subject' => addcslashes(addslashes($row['subject']), '/')
        );
    }
    $smcFunc['db_free_result']($request);
    if (empty($context['topics']) && count($merge_boards) <= 1 && !in_array(0, $merge_boards))
        fatal_lang_error('merge_need_more_topics');
    $context['sub_template'] = 'merge';
}
function MergeExecute($topics = array())
{
    global $user_info, $txt, $context, $scripturl, $sourcedir;
    global $smcFunc, $language, $modSettings;
    
    checkSession('request');
    
    if (!empty($_GET['from']) && !empty($_GET['to']))
        $topics = array((int) $_GET['from'], (int) $_GET['to']);
    
    if (!empty($_POST['topics']) && is_array($_POST['topics']))
        $topics = $_POST['topics'];
    
    if (empty($topics) || !is_array($topics) || count($topics) == 1)
        fatal_lang_error('merge_need_more_topics');
    
    foreach ($topics as $id => $topic)
        $topics[$id] = (int) $topic;
    
    if ($modSettings['postmod_active'])
        $can_approve_boards = boardsAllowedTo('approve_posts');
    
    $request = $smcFunc['db_query']('', '
        SELECT
            t.id_topic, t.id_board, t.id_poll, t.num_views, t.is_sticky, t.approved, t.num_replies, t.unapproved_posts, t.id_redirect_topic,
            m1.subject, m1.poster_time AS time_started, COALESCE(mem1.id_member, 0) AS id_member_started, COALESCE(mem1.real_name, m1.poster_name) AS name_started,
            m2.poster_time AS time_updated, COALESCE(mem2.id_member, 0) AS id_member_updated, COALESCE(mem2.real_name, m2.poster_name) AS name_updated
        FROM {db_prefix}topics AS t
            INNER JOIN {db_prefix}messages AS m1 ON (m1.id_msg = t.id_first_msg)
            INNER JOIN {db_prefix}messages AS m2 ON (m2.id_msg = t.id_last_msg)
            LEFT JOIN {db_prefix}members AS mem1 ON (mem1.id_member = m1.id_member)
            LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = m2.id_member)
        WHERE t.id_topic IN ({array_int:topic_list})
        ORDER BY t.id_first_msg
        LIMIT {int:limit}',
        array(
            'topic_list' => $topics,
            'limit' => count($topics),
        )
    );
    if ($smcFunc['db_num_rows']($request) < 2)
        fatal_lang_error('no_topic_id');
    $num_views = 0;
    $is_sticky = 0;
    $boardTotals = array();
    $boards = array();
    $polls = array();
    $firstTopic = 0;
    $context['is_approved'] = 1;
    $lowestTopicId = 0;
    $lowestTopicBoard = 0;
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        
        if (!empty($row['id_redirect_topic']))
            fatal_lang_error('cannot_merge_redirect', false);
        
        if (!isset($boardTotals[$row['id_board']]))
            $boardTotals[$row['id_board']] = array(
                'posts' => 0,
                'topics' => 0,
                'unapproved_posts' => 0,
                'unapproved_topics' => 0
            );
        
        if ($modSettings['postmod_active'] && !$row['approved'] && $can_approve_boards != array(0) && in_array($row['id_board'], $can_approve_boards))
        {
            unset($topics[$row['id_topic']]); 
            continue;
        }
        elseif (!$row['approved'])
            $boardTotals[$row['id_board']]['unapproved_topics']++;
        else
            $boardTotals[$row['id_board']]['topics']++;
        $boardTotals[$row['id_board']]['unapproved_posts'] += $row['unapproved_posts'];
        $boardTotals[$row['id_board']]['posts'] += $row['num_replies'] + ($row['approved'] ? 1 : 0);
        
        if (isset($_POST['postRedirect']))
            $boardTotals[$row['id_board']]['topics']--;
        $topic_data[$row['id_topic']] = array(
            'id' => $row['id_topic'],
            'board' => $row['id_board'],
            'poll' => $row['id_poll'],
            'num_views' => $row['num_views'],
            'subject' => $row['subject'],
            'started' => array(
                'time' => timeformat($row['time_started']),
                'timestamp' => forum_time(true, $row['time_started']),
                'href' => empty($row['id_member_started']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_started'],
                'link' => empty($row['id_member_started']) ? $row['name_started'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_started'] . '">' . $row['name_started'] . '</a>'
            ),
            'updated' => array(
                'time' => timeformat($row['time_updated']),
                'timestamp' => forum_time(true, $row['time_updated']),
                'href' => empty($row['id_member_updated']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_updated'],
                'link' => empty($row['id_member_updated']) ? $row['name_updated'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['name_updated'] . '</a>'
            ),
            'approved' => $row['approved']
        );
        $num_views += $row['num_views'];
        $boards[] = $row['id_board'];
        
        if ($row['id_poll'] > 0)
            $polls[] = $row['id_poll'];
        
        if (empty($firstTopic))
            $firstTopic = $row['id_topic'];
        
        if ($row['id_topic'] < $lowestTopicId || empty($lowestTopicId))
        {
            $lowestTopicId = $row['id_topic'];
            $lowestTopicBoard = $row['id_board'];
        }
        $is_sticky = max($is_sticky, $row['is_sticky']);
    }
    $smcFunc['db_free_result']($request);
    
    if (empty($topic_data))
        fatal_lang_error('no_topic_id');
    if (isset($_POST['postRedirect']) && !empty($lowestTopicBoard))
        $boardTotals[$lowestTopicBoard]['topics']++;
    
    $context['is_approved'] = $topic_data[$firstTopic]['approved'];
    $boards = array_values(array_unique($boards));
    
    if (!empty($topics))
    {
        isAllowedTo('merge_any', $boards);
        loadTemplate('MoveTopic');
    }
    
    $merge_boards = boardsAllowedTo('merge_any');
    if (empty($merge_boards))
        fatal_lang_error('cannot_merge_any', 'user');
    
    $request = $smcFunc['db_query']('', '
        SELECT b.id_board
        FROM {db_prefix}boards AS b
        WHERE b.id_board IN ({array_int:boards})
            AND {query_see_board}' . (!in_array(0, $merge_boards) ? '
            AND b.id_board IN ({array_int:merge_boards})' : '') . '
        LIMIT {int:limit}',
        array(
            'boards' => $boards,
            'merge_boards' => $merge_boards,
            'limit' => count($boards),
        )
    );
    
    if ($smcFunc['db_num_rows']($request) != count($boards))
        fatal_lang_error('no_board');
    $smcFunc['db_free_result']($request);
    if (empty($_REQUEST['sa']) || $_REQUEST['sa'] == 'options')
    {
        if (count($polls) > 1)
        {
            $request = $smcFunc['db_query']('', '
                SELECT t.id_topic, t.id_poll, m.subject, p.question
                FROM {db_prefix}polls AS p
                    INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll)
                    INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
                WHERE p.id_poll IN ({array_int:polls})
                LIMIT {int:limit}',
                array(
                    'polls' => $polls,
                    'limit' => count($polls),
                )
            );
            while ($row = $smcFunc['db_fetch_assoc']($request))
                $context['polls'][] = array(
                    'id' => $row['id_poll'],
                    'topic' => array(
                        'id' => $row['id_topic'],
                        'subject' => $row['subject']
                    ),
                    'question' => $row['question'],
                    'selected' => $row['id_topic'] == $firstTopic
                );
            $smcFunc['db_free_result']($request);
        }
        if (count($boards) > 1)
        {
            $request = $smcFunc['db_query']('', '
                SELECT id_board, name
                FROM {db_prefix}boards
                WHERE id_board IN ({array_int:boards})
                ORDER BY name
                LIMIT {int:limit}',
                array(
                    'boards' => $boards,
                    'limit' => count($boards),
                )
            );
            while ($row = $smcFunc['db_fetch_assoc']($request))
                $context['boards'][] = array(
                    'id' => $row['id_board'],
                    'name' => $row['name'],
                    'selected' => $row['id_board'] == $topic_data[$firstTopic]['board']
                );
            $smcFunc['db_free_result']($request);
        }
        $context['topics'] = $topic_data;
        foreach ($topic_data as $id => $topic)
            $context['topics'][$id]['selected'] = $topic['id'] == $firstTopic;
        $context['page_title'] = $txt['merge'];
        $context['sub_template'] = 'merge_extra_options';
        return;
    }
    
    $target_board = count($boards) > 1 ? (int) $_REQUEST['board'] : $boards[0];
    if (!in_array($target_board, $boards))
        fatal_lang_error('no_board');
    
    $target_poll = count($polls) > 1 ? (int) $_POST['poll'] : (count($polls) == 1 ? $polls[0] : 0);
    if ($target_poll > 0 && !in_array($target_poll, $polls))
        fatal_lang_error('no_access', false);
    $deleted_polls = empty($target_poll) ? $polls : array_diff($polls, array($target_poll));
    
    if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '')
    {
        $target_subject = strtr($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
        
        if ($smcFunc['strlen']($target_subject) > 100)
            $target_subject = $smcFunc['substr']($target_subject, 0, 100);
        
        if ($target_subject == '')
            $target_subject = $topic_data[$firstTopic]['subject'];
    }
    
    elseif (!empty($topic_data[(int) $_POST['subject']]['subject']))
        $target_subject = $topic_data[(int) $_POST['subject']]['subject'];
    
    else
        $target_subject = $topic_data[$firstTopic]['subject'];
    
    $request = $smcFunc['db_query']('', '
        SELECT approved, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg, COUNT(*) AS message_count
        FROM {db_prefix}messages
        WHERE id_topic IN ({array_int:topics})
        GROUP BY approved
        ORDER BY approved DESC',
        array(
            'topics' => $topics,
        )
    );
    $topic_approved = 1;
    $first_msg = 0;
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        
        if ($row['approved'] || !empty($first_msg))
        {
            $first_msg = $row['first_msg'];
            $last_msg = $row['last_msg'];
            if ($row['approved'])
            {
                $num_replies = $row['message_count'] - 1;
                $num_unapproved = 0;
            }
            else
            {
                $topic_approved = 0;
                $num_replies = 0;
                $num_unapproved = $row['message_count'];
            }
        }
        else
        {
            
            if ($first_msg > $row['first_msg'])
            {
                $first_msg = $row['first_msg'];
                $num_replies++;
                $topic_approved = 0;
            }
            $num_unapproved = $row['message_count'];
        }
    }
    $smcFunc['db_free_result']($request);
    
    if (!isset($boardTotals[$target_board]))
    {
        $boardTotals[$target_board] = array(
            'posts' => 0,
            'topics' => 0,
            'unapproved_posts' => 0,
            'unapproved_topics' => 0
        );
    }
    
    $boardTotals[$target_board][(!$topic_approved) ? 'unapproved_topics' : 'topics']--;
    $boardTotals[$target_board]['unapproved_posts'] -= $num_unapproved;
    $boardTotals[$target_board]['posts'] -= $topic_approved ? $num_replies + 1 : $num_replies;
    
    $request = $smcFunc['db_query']('', '
        SELECT id_member
        FROM {db_prefix}messages
        WHERE id_msg IN ({int:first_msg}, {int:last_msg})
        ORDER BY id_msg
        LIMIT 2',
        array(
            'first_msg' => $first_msg,
            'last_msg' => $last_msg,
        )
    );
    list ($member_started) = $smcFunc['db_fetch_row']($request);
    list ($member_updated) = $smcFunc['db_fetch_row']($request);
    
    if ($member_updated === null)
        $member_updated = $member_started;
    $smcFunc['db_free_result']($request);
    
    $affected_msgs = array();
    $request = $smcFunc['db_query']('', '
        SELECT id_msg
        FROM {db_prefix}messages
        WHERE id_topic IN ({array_int:topic_list})',
        array(
            'topic_list' => $topics,
        )
    );
    while ($row = $smcFunc['db_fetch_row']($request))
        $affected_msgs[] = $row[0];
    $smcFunc['db_free_result']($request);
    
    $id_topic = min($topics);
    $deleted_topics = array_diff($topics, array($id_topic));
    $updated_topics = array();
    
    
    if (!isset($_POST['postRedirect']))
    {
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}log_search_subjects
            WHERE id_topic IN ({array_int:deleted_topics})',
            array(
                'deleted_topics' => $deleted_topics,
            )
        );
    }
    require_once($sourcedir . '/Subs-Post.php');
    $posterOptions = array(
        'id' => $user_info['id'],
        'update_post_count' => false,
    );
    
    if (isset($_POST['postRedirect']))
    {
        $_POST['reason'] = $smcFunc['htmlspecialchars']($_POST['reason'], ENT_QUOTES);
        preparsecode($_POST['reason']);
        
        $reason = strtr($_POST['reason'], array(
            $txt['movetopic_auto_topic'] => '[iurl=' . $scripturl . '?topic=' . $id_topic . '.0]' . $target_subject . '[/iurl]'
        ));
        
        $redirect_expires = !empty($_POST['redirect_expires']) ? ((int) ($_POST['redirect_expires'] * 60) + time()) : 0;
        
        $redirect_topic = isset($_POST['redirect_topic']) ? $id_topic : 0;
        foreach ($deleted_topics as $this_old_topic)
        {
            $redirect_subject = sprintf($txt['merged_subject'], $topic_data[$this_old_topic]['subject']);
            $msgOptions = array(
                'icon' => 'moved',
                'subject' => $redirect_subject,
                'body' => $reason,
                'approved' => 1,
            );
            $topicOptions = array(
                'id' => $this_old_topic,
                'is_approved' => true,
                'lock_mode' => 1,
                'board' => $topic_data[$this_old_topic]['board'],
                'mark_as_read' => true,
            );
            
            
            if (createPost($msgOptions, $topicOptions, $posterOptions))
            {
                $updated_topics[$this_old_topic] = $msgOptions['id'];
            }
            
            updateStats('subject', $this_old_topic, $redirect_subject);
        }
    }
    
    if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix')))
    {
        if ($language === $user_info['language'])
            $context['response_prefix'] = $txt['response_prefix'];
        else
        {
            loadLanguage('index', $language, false);
            $context['response_prefix'] = $txt['response_prefix'];
            loadLanguage('index');
        }
        cache_put_data('response_prefix', $context['response_prefix'], 600);
    }
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}messages
        SET
            id_topic = {int:id_topic},
            id_board = {int:target_board}' . (empty($_POST['enforce_subject']) ? '' : ',
            subject = {string:subject}') . '
        WHERE id_topic IN ({array_int:topic_list})' . (!empty($updated_topics) ? '
            AND id_msg NOT IN ({array_int:merge_msg})' : ''),
        array(
            'topic_list' => $topics,
            'id_topic' => $id_topic,
            'merge_msg' => $updated_topics,
            'target_board' => $target_board,
            'subject' => $context['response_prefix'] . $target_subject,
        )
    );
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}log_reported
        SET
            id_topic = {int:id_topic},
            id_board = {int:target_board}
        WHERE id_topic IN ({array_int:topics_list})',
        array(
            'topics_list' => $topics,
            'id_topic' => $id_topic,
            'target_board' => $target_board,
        )
    );
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}messages
        SET subject = {string:target_subject}
        WHERE id_msg = {int:first_msg}',
        array(
            'first_msg' => $first_msg,
            'target_subject' => $target_subject,
        )
    );
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}calendar
        SET
            id_topic = {int:id_topic},
            id_board = {int:target_board}
        WHERE id_topic IN ({array_int:deleted_topics})',
        array(
            'deleted_topics' => $deleted_topics,
            'id_topic' => $id_topic,
            'target_board' => $target_board,
        )
    );
    
    
    $request = $smcFunc['db_query']('', '
        SELECT id_member, MIN(id_msg) AS new_id_msg, unwatched
        FROM {db_prefix}log_topics
        WHERE id_topic IN ({array_int:topics})
        GROUP BY id_member, unwatched',
        array(
            'topics' => $topics,
        )
    );
    if ($smcFunc['db_num_rows']($request) > 0)
    {
        $replaceEntries = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $replaceEntries[] = array($row['id_member'], $id_topic, $row['new_id_msg'], $row['unwatched']);
        $smcFunc['db_insert']('replace',
            '{db_prefix}log_topics',
            array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int'),
            $replaceEntries,
            array('id_member', 'id_topic')
        );
        unset($replaceEntries);
        
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}log_topics
            WHERE id_topic IN ({array_int:deleted_topics})',
            array(
                'deleted_topics' => $deleted_topics,
            )
        );
    }
    $smcFunc['db_free_result']($request);
    
    $notifications = isset($_POST['notifications']) && is_array($_POST['notifications']) ? array_intersect($topics, $_POST['notifications']) : array();
    if (!empty($notifications))
    {
        $request = $smcFunc['db_query']('', '
            SELECT id_member, MAX(sent) AS sent
            FROM {db_prefix}log_notify
            WHERE id_topic IN ({array_int:topics_list})
            GROUP BY id_member',
            array(
                'topics_list' => $notifications,
            )
        );
        if ($smcFunc['db_num_rows']($request) > 0)
        {
            $replaceEntries = array();
            while ($row = $smcFunc['db_fetch_assoc']($request))
                $replaceEntries[] = array($row['id_member'], $id_topic, 0, $row['sent']);
            $smcFunc['db_insert']('replace',
                '{db_prefix}log_notify',
                array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'sent' => 'int'),
                $replaceEntries,
                array('id_member', 'id_topic', 'id_board')
            );
            unset($replaceEntries);
            $smcFunc['db_query']('', '
                DELETE FROM {db_prefix}log_topics
                WHERE id_topic IN ({array_int:deleted_topics})',
                array(
                    'deleted_topics' => $deleted_topics,
                )
            );
        }
        $smcFunc['db_free_result']($request);
    }
    
    if (!empty($deleted_polls))
    {
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}polls
            WHERE id_poll IN ({array_int:deleted_polls})',
            array(
                'deleted_polls' => $deleted_polls,
            )
        );
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}poll_choices
            WHERE id_poll IN ({array_int:deleted_polls})',
            array(
                'deleted_polls' => $deleted_polls,
            )
        );
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}log_polls
            WHERE id_poll IN ({array_int:deleted_polls})',
            array(
                'deleted_polls' => $deleted_polls,
            )
        );
    }
    
    foreach ($boardTotals as $id_board => $stats)
    {
        $smcFunc['db_query']('', '
            UPDATE {db_prefix}boards
            SET
                num_topics = CASE WHEN {int:topics} > num_topics THEN 0 ELSE num_topics - {int:topics} END,
                unapproved_topics = CASE WHEN {int:unapproved_topics} > unapproved_topics THEN 0 ELSE unapproved_topics - {int:unapproved_topics} END,
                num_posts = CASE WHEN {int:posts} > num_posts THEN 0 ELSE num_posts - {int:posts} END,
                unapproved_posts = CASE WHEN {int:unapproved_posts} > unapproved_posts THEN 0 ELSE unapproved_posts - {int:unapproved_posts} END
            WHERE id_board = {int:id_board}',
            array(
                'id_board' => $id_board,
                'topics' => $stats['topics'],
                'unapproved_topics' => $stats['unapproved_topics'],
                'posts' => $stats['posts'],
                'unapproved_posts' => $stats['unapproved_posts'],
            )
        );
    }
    
    $request = $smcFunc['db_query']('', '
        SELECT id_board
        FROM {db_prefix}topics
        WHERE id_topic = {int:id_topic}
        LIMIT 1',
        array(
            'id_topic' => $id_topic,
        )
    );
    list($id_board) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    
    if (isset($_POST['postRedirect']))
    {
        
        
        
        foreach ($updated_topics as $old_topic => $id_msg)
        {
            $smcFunc['db_query']('', '
                UPDATE {db_prefix}topics
                SET id_first_msg = id_last_msg,
                    id_member_started = {int:current_user},
                    id_member_updated = {int:current_user},
                    id_poll = 0,
                    approved = 1,
                    num_replies = 0,
                    unapproved_posts = 0,
                    id_redirect_topic = {int:redirect_topic},
                    redirect_expires = {int:redirect_expires}
                WHERE id_topic = {int:old_topic}',
                array(
                    'current_user' => $user_info['id'],
                    'old_topic' => $old_topic,
                    'redirect_topic' => $redirect_topic,
                    'redirect_expires' => $redirect_expires
                )
            );
        }
    }
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}topics
        SET id_poll = 0
        WHERE id_topic IN ({array_int:deleted_topics})',
        array(
            'deleted_topics' => $deleted_topics
        )
    );
    
    if (!isset($_POST['postRedirect']))
    {
        
        include_once($sourcedir . '/RemoveTopic.php');
        
        removeTopics($deleted_topics, false, true, false);
    }
    
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}topics
        SET
            id_board = {int:id_board},
            id_member_started = {int:id_member_started},
            id_member_updated = {int:id_member_updated},
            id_first_msg = {int:id_first_msg},
            id_last_msg = {int:id_last_msg},
            id_poll = {int:id_poll},
            num_replies = {int:num_replies},
            unapproved_posts = {int:unapproved_posts},
            num_views = {int:num_views},
            is_sticky = {int:is_sticky},
            approved = {int:approved}
        WHERE id_topic = {int:id_topic}',
        array(
            'id_board' => $target_board,
            'is_sticky' => $is_sticky,
            'approved' => $topic_approved,
            'id_topic' => $id_topic,
            'id_member_started' => $member_started,
            'id_member_updated' => $member_updated,
            'id_first_msg' => $first_msg,
            'id_last_msg' => $last_msg,
            'id_poll' => $target_poll,
            'num_replies' => $num_replies,
            'unapproved_posts' => $num_unapproved,
            'num_views' => $num_views,
        )
    );
    
    updateStats('topic');
    updateStats('subject', $id_topic, $target_subject);
    updateLastMessages($boards);
    logAction('merge', array('topic' => $id_topic, 'board' => $id_board));
    
    sendNotifications($id_topic, 'merge');
    
    require_once($sourcedir . '/Search.php');
    $searchAPI = findSearchAPI();
    if (is_callable(array($searchAPI, 'topicMerge')))
        $searchAPI->topicMerge($id_topic, $topics, $affected_msgs, empty($_POST['enforce_subject']) ? null : array($context['response_prefix'], $target_subject));
    
    $merged_topic = array(
        'id_board' => $target_board,
        'is_sticky' => $is_sticky,
        'approved' => $topic_approved,
        'id_topic' => $id_topic,
        'id_member_started' => $member_started,
        'id_member_updated' => $member_updated,
        'id_first_msg' => $first_msg,
        'id_last_msg' => $last_msg,
        'id_poll' => $target_poll,
        'num_replies' => $num_replies,
        'unapproved_posts' => $num_unapproved,
        'num_views' => $num_views,
        'subject' => $target_subject,
    );
    call_integration_hook('integrate_merge_topic', array($merged_topic, $updated_topics, $deleted_topics, $deleted_polls));
    
    redirectexit('action=mergetopics;sa=done;to=' . $id_topic . ';targetboard=' . $target_board);
}
function MergeDone()
{
    global $txt, $context;
    
    $context['target_board'] = (int) $_GET['targetboard'];
    $context['target_topic'] = (int) $_GET['to'];
    $context['page_title'] = $txt['merge'];
    $context['sub_template'] = 'merge_done';
}
?>