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: 1788: 1789: 1790: 1791: 1792: 1793: 1794: 1795: 1796: 1797: 1798: 1799: 1800: 1801: 1802: 1803: 1804: 1805: 1806: 1807: 1808: 1809: 1810: 1811: 1812: 1813: 1814: 1815: 1816: 1817: 1818: 1819: 1820: 1821: 1822: 1823: 1824: 1825: 1826: 1827: 1828: 1829: 1830: 1831: 1832: 1833: 1834: 1835: 1836: 1837: 1838: 1839: 1840: 1841: 1842: 1843: 1844: 1845: 1846: 1847: 1848: 1849: 1850: 1851: 1852: 1853: 1854: 1855: 1856: 1857: 1858: 1859: 1860: 1861: 1862: 1863: 1864: 1865: 1866: 1867: 1868: 1869: 1870: 1871: 1872: 1873: 1874: 1875: 1876: 1877: 1878: 1879: 1880: 1881: 1882: 1883: 1884: 1885: 1886: 1887: 1888: 1889: 1890: 1891: 1892: 1893: 1894: 1895: 1896: 1897: 1898: 1899: 1900: 1901: 1902: 1903: 1904: 1905: 1906: 1907: 1908: 1909: 1910: 1911: 1912: 1913: 1914: 1915: 1916: 1917: 1918: 1919: 1920: 1921: 1922: 1923: 1924: 1925: 1926: 1927: 1928: 1929: 1930: 1931: 1932: 1933: 1934: 1935: 1936: 1937: 1938: 1939: 1940: 1941: 1942: 1943: 1944: 1945: 1946: 1947: 1948: 1949: 1950: 1951: 1952: 1953: 1954: 1955: 1956: 1957: 1958: 1959: 1960: 1961: 1962: 1963: 1964: 1965: 1966: 1967: 1968: 1969: 1970: 1971: 1972: 1973: 1974: 1975: 1976: 1977: 1978: 1979: 1980: 1981: 1982: 1983: 1984: 1985: 1986: 1987: 1988: 1989: 1990: 1991: 1992: 1993: 1994: 1995: 1996: 1997: 1998: 1999: 2000: 2001: 2002: 2003: 2004: 2005: 2006: 2007: 2008: 2009: 2010: 2011: 2012: 2013: 2014: 2015: 2016: 2017: 2018: 2019: 2020: 2021: 2022: 2023: 2024: 2025: 2026: 2027: 2028: 2029: 2030: 2031: 2032: 2033: 2034: 2035: 2036: 2037: 2038: 2039: 2040: 2041: 2042: 2043: 2044: 2045: 2046: 2047: 2048: 2049: 2050: 2051: 2052: 2053: 2054: 2055: 2056: 2057: 2058: 2059: 2060: 2061: 2062: 2063: 2064: 2065: 2066: 2067: 2068: 2069: 2070: 2071: 2072: 2073: 2074: 2075: 2076: 2077: 2078: 2079: 2080: 2081: 2082: 2083: 
<?php

/**
 * Moderation Center.
 *
 * Simple Machines Forum (SMF)
 *
 * @package SMF
 * @author Simple Machines http://www.simplemachines.org
 * @copyright 2019 Simple Machines and individual contributors
 * @license http://www.simplemachines.org/about/smf/license.php BSD
 *
 * @version 2.1 RC1
 */

if (!defined('SMF'))
    die('No direct access...');

/**
 * Entry point for the moderation center.
 *
 * @param bool $dont_call If true, doesn't call the function for the appropriate mod area
 */
function ModerationMain($dont_call = false)
{
    global $smcFunc, $txt, $context, $scripturl, $modSettings, $user_info, $sourcedir, $options;

    // Don't run this twice... and don't conflict with the admin bar.
    if (isset($context['admin_area']))
        return;

    $context['can_moderate_boards'] = $user_info['mod_cache']['bq'] != '0=1';
    $context['can_moderate_groups'] = $user_info['mod_cache']['gq'] != '0=1';
    $context['can_moderate_approvals'] = $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap']);
    $context['can_moderate_users'] = allowedTo('moderate_forum');

    // Everyone using this area must be allowed here!
    if (!$context['can_moderate_boards'] && !$context['can_moderate_groups'] && !$context['can_moderate_approvals'] && !$context['can_moderate_users'])
        isAllowedTo('access_mod_center');

    // We're gonna want a menu of some kind.
    require_once($sourcedir . '/Subs-Menu.php');

    // Load the language, and the template.
    loadLanguage('ModerationCenter');
    loadTemplate(false, 'admin');

    $context['admin_preferences'] = !empty($options['admin_preferences']) ? $smcFunc['json_decode']($options['admin_preferences'], true) : array();
    $context['robot_no_index'] = true;

    // This is the menu structure - refer to Subs-Menu.php for the details.
    $moderation_areas = array(
        'main' => array(
            'title' => $txt['mc_main'],
            'areas' => array(
                'index' => array(
                    'label' => $txt['moderation_center'],
                    'function' => 'ModerationHome',
                    'icon' => 'administration',
                ),
                'settings' => array(
                    'label' => $txt['mc_settings'],
                    'function' => 'ModerationSettings',
                    'icon' => 'features',
                ),
                'modlogoff' => array(
                    'label' => $txt['mc_logoff'],
                    'function' => 'ModEndSession',
                    'enabled' => empty($modSettings['securityDisable_moderate']),
                    'icon' => 'exit',
                ),
                'notice' => array(
                    'file' => 'ModerationCenter.php',
                    'function' => 'ShowNotice',
                    'select' => 'index'
                ),
            ),
        ),
        'logs' => array(
            'title' => $txt['mc_logs'],
            'areas' => array(
                'modlog' => array(
                    'label' => $txt['modlog_view'],
                    'enabled' => !empty($modSettings['modlog_enabled']) && $context['can_moderate_boards'],
                    'file' => 'Modlog.php',
                    'function' => 'ViewModlog',
                    'icon' => 'logs',
                ),
                'warnings' => array(
                    'label' => $txt['mc_warnings'],
                    'enabled' => $modSettings['warning_settings'][0] == 1 && $context['can_moderate_boards'],
                    'function' => 'ViewWarnings',
                    'icon' => 'warning',
                    'subsections' => array(
                        'log' => array($txt['mc_warning_log']),
                        'templates' => array($txt['mc_warning_templates'], 'issue_warning'),
                    ),
                ),
            ),
        ),
        'posts' => array(
            'title' => $txt['mc_posts'],
            'enabled' => $context['can_moderate_boards'] || $context['can_moderate_approvals'],
            'areas' => array(
                'postmod' => array(
                    'label' => $txt['mc_unapproved_posts'],
                    'enabled' => $context['can_moderate_approvals'],
                    'file' => 'PostModeration.php',
                    'function' => 'PostModerationMain',
                    'icon' => 'posts',
                    'custom_url' => $scripturl . '?action=moderate;area=postmod',
                    'subsections' => array(
                        'posts' => array($txt['mc_unapproved_replies']),
                        'topics' => array($txt['mc_unapproved_topics']),
                    ),
                ),
                'attachmod' => array(
                    'label' => $txt['mc_unapproved_attachments'],
                    'enabled' => $context['can_moderate_approvals'],
                    'file' => 'PostModeration.php',
                    'function' => 'PostModerationMain',
                    'icon' => 'post_moderation_attach',
                    'custom_url' => $scripturl . '?action=moderate;area=attachmod;sa=attachments',
                ),
                'reportedposts' => array(
                    'label' => $txt['mc_reported_posts'],
                    'enabled' => $context['can_moderate_boards'],
                    'file' => 'ReportedContent.php',
                    'function' => 'ReportedContent',
                    'icon' => 'reports',
                    'subsections' => array(
                        'show' => array($txt['mc_reportedp_active']),
                        'closed' => array($txt['mc_reportedp_closed']),
                    ),
                ),
            ),
        ),
        'groups' => array(
            'title' => $txt['mc_groups'],
            'enabled' => $context['can_moderate_groups'],
            'areas' => array(
                'groups' => array(
                    'label' => $txt['mc_group_requests'],
                    'file' => 'Groups.php',
                    'function' => 'Groups',
                    'icon' => 'members_request',
                    'custom_url' => $scripturl . '?action=moderate;area=groups;sa=requests',
                ),
                'viewgroups' => array(
                    'label' => $txt['mc_view_groups'],
                    'file' => 'Groups.php',
                    'function' => 'Groups',
                    'icon' => 'membergroups',
                ),
            ),
        ),
        'members' => array(
            'title' => $txt['mc_members'],
            'enabled' => $context['can_moderate_users'] || ($modSettings['warning_settings'][0] == 1 && $context['can_moderate_boards']),
            'areas' => array(
                'userwatch' => array(
                    'label' => $txt['mc_watched_users_title'],
                    'enabled' => $modSettings['warning_settings'][0] == 1 && $context['can_moderate_boards'],
                    'function' => 'ViewWatchedUsers',
                    'icon' => 'members_watched',
                    'subsections' => array(
                        'member' => array($txt['mc_watched_users_member']),
                        'post' => array($txt['mc_watched_users_post']),
                    ),
                ),
                'reportedmembers' => array(
                    'label' => $txt['mc_reported_members_title'],
                    'enabled' => $context['can_moderate_users'],
                    'file' => 'ReportedContent.php',
                    'function' => 'ReportedContent',
                    'icon' => 'members_watched',
                    'subsections' => array(
                        'open' => array($txt['mc_reportedp_active']),
                        'closed' => array($txt['mc_reportedp_closed']),
                    ),
                ),
            ),
        )
    );

    // Make sure the administrator has a valid session...
    validateSession('moderate');

    // I don't know where we're going - I don't know where we've been...
    $menuOptions = array(
        'action' => 'moderate',
        'disable_url_session_check' => true,
    );
    $mod_include_data = createMenu($moderation_areas, $menuOptions);
    unset($moderation_areas);

    // We got something - didn't we? DIDN'T WE!
    if ($mod_include_data == false)
        fatal_lang_error('no_access', false);

    // Retain the ID information in case required by a subaction.
    $context['moderation_menu_id'] = $context['max_menu_id'];
    $context['moderation_menu_name'] = 'menu_data_' . $context['moderation_menu_id'];

    // @todo: html in here is not good
    $context[$context['moderation_menu_name']]['tab_data'] = array(
        'title' => $txt['moderation_center'],
        'help' => '',
        'description' => '
            <strong>' . $txt['hello_guest'] . ' ' . $context['user']['name'] . '!</strong>
            <br><br>
            ' . $txt['mc_description']);

    // What a pleasant shortcut - even tho we're not *really* on the admin screen who cares...
    $context['admin_area'] = $mod_include_data['current_area'];

    // Build the link tree.
    $context['linktree'][] = array(
        'url' => $scripturl . '?action=moderate',
        'name' => $txt['moderation_center'],
    );
    if (isset($mod_include_data['current_area']) && $mod_include_data['current_area'] != 'index')
        $context['linktree'][] = array(
            'url' => $scripturl . '?action=moderate;area=' . $mod_include_data['current_area'],
            'name' => $mod_include_data['label'],
        );
    if (!empty($mod_include_data['current_subsection']) && $mod_include_data['subsections'][$mod_include_data['current_subsection']][0] != $mod_include_data['label'])
        $context['linktree'][] = array(
            'url' => $scripturl . '?action=moderate;area=' . $mod_include_data['current_area'] . ';sa=' . $mod_include_data['current_subsection'],
            'name' => $mod_include_data['subsections'][$mod_include_data['current_subsection']][0],
        );

    // Now - finally - the bit before the encore - the main performance of course!
    if (!$dont_call)
    {
        if (isset($mod_include_data['file']))
            require_once($sourcedir . '/' . $mod_include_data['file']);

        call_helper($mod_include_data['function']);
    }
}

/**
 * This function basically is the home page of the moderation center.
 */
function ModerationHome()
{
    global $smcFunc, $txt, $context, $options;

    loadTemplate('ModerationCenter');
    loadJavaScriptFile('admin.js', array('minimize' => true), 'smf_admin');

    $context['page_title'] = $txt['moderation_center'];
    $context['sub_template'] = 'moderation_center';

    // Handle moderators notes.
    ModBlockNotes();

    // Load what blocks the user actually can see...
    $valid_blocks = array();

    if ($context['can_moderate_groups'])
        $valid_blocks['g'] = 'GroupRequests';
    if ($context['can_moderate_boards'])
    {
        $valid_blocks['r'] = 'ReportedPosts';
        $valid_blocks['w'] = 'WatchedUsers';
    }
    if ($context['can_moderate_users'])
    {
        // This falls under the category of moderating users as well...
        if (!$context['can_moderate_boards'])
            $valid_blocks['w'] = 'WatchedUsers';

        $valid_blocks['rm'] = 'ReportedMembers';
    }

    call_integration_hook('integrate_mod_centre_blocks', array(&$valid_blocks));

    $context['mod_blocks'] = array();
    foreach ($valid_blocks as $k => $block)
    {
        $block = 'ModBlock' . $block;
        if (function_exists($block))
            $context['mod_blocks'][] = $block();
    }

    $context['admin_prefs'] = !empty($options['admin_preferences']) ? $smcFunc['json_decode']($options['admin_preferences'], true) : array();
}

/**
 * Show a list of the most active watched users.
 */
function ModBlockWatchedUsers()
{
    global $context, $smcFunc, $scripturl, $modSettings;

    if (($watched_users = cache_get_data('recent_user_watches', 240)) === null)
    {
        $modSettings['warning_watch'] = empty($modSettings['warning_watch']) ? 1 : $modSettings['warning_watch'];
        $request = $smcFunc['db_query']('', '
            SELECT id_member, real_name, last_login
            FROM {db_prefix}members
            WHERE warning >= {int:warning_watch}
            ORDER BY last_login DESC
            LIMIT 10',
            array(
                'warning_watch' => $modSettings['warning_watch'],
            )
        );
        $watched_users = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $watched_users[] = $row;
        $smcFunc['db_free_result']($request);

        cache_put_data('recent_user_watches', $watched_users, 240);
    }

    $context['watched_users'] = array();
    foreach ($watched_users as $user)
    {
        $context['watched_users'][] = array(
            'id' => $user['id_member'],
            'name' => $user['real_name'],
            'link' => '<a href="' . $scripturl . '?action=profile;u=' . $user['id_member'] . '">' . $user['real_name'] . '</a>',
            'href' => $scripturl . '?action=profile;u=' . $user['id_member'],
            'last_login' => !empty($user['last_login']) ? timeformat($user['last_login']) : '',
        );
    }

    return 'watched_users';
}

/**
 * Show an area for the moderator to type into.
 */
function ModBlockNotes()
{
    global $context, $smcFunc, $scripturl, $user_info;

    // Set a nice and informative message.
    $context['report_post_action'] = !empty($_SESSION['rc_confirmation']) ? $_SESSION['rc_confirmation'] : array();
    unset($_SESSION['rc_confirmation']);

    // Are we saving a note?
    if (isset($_GET['modnote']) && isset($_POST['makenote']) && isset($_POST['new_note']))
    {
        checkSession();
        validateToken('mod-modnote-add');

        $_POST['new_note'] = $smcFunc['htmlspecialchars'](trim($_POST['new_note']));
        // Make sure they actually entered something.
        if (!empty($_POST['new_note']))
        {
            // Insert it into the database then!
            $smcFunc['db_insert']('',
                '{db_prefix}log_comments',
                array(
                    'id_member' => 'int', 'member_name' => 'string', 'comment_type' => 'string', 'recipient_name' => 'string',
                    'body' => 'string', 'log_time' => 'int',
                ),
                array(
                    $user_info['id'], $user_info['name'], 'modnote', '', $_POST['new_note'], time(),
                ),
                array('id_comment')
            );

            // Clear the cache.
            cache_put_data('moderator_notes', null, 240);
            cache_put_data('moderator_notes_total', null, 240);
        }

        // Everything went better than expected!
        $_SESSION['rc_confirmation'] = 'message_saved';

        // Redirect otherwise people can resubmit.
        redirectexit('action=moderate');
    }

    // Bye... bye...
    if (isset($_GET['notes']) && isset($_GET['delete']) && is_numeric($_GET['delete']))
    {
        checkSession('get');
        validateToken('mod-modnote-del', 'get');

        // No sneaky stuff now!
        if (!allowedTo('admin_forum'))
        {
            // Is this your note?
            $get_owner = $smcFunc['db_query']('', '
                SELECT id_member
                FROM {db_prefix}log_comments
                WHERE id_comment = {int:note}
                    AND comment_type = {literal:modnote}
                    AND id_member = {int:user}',
                array(
                    'note' => $_GET['delete'],
                    'user' => $user_info['id'],
                )
            );

            $note_owner = $smcFunc['db_num_rows']($get_owner);
            $smcFunc['db_free_result']($get_owner);

            if (empty($note_owner))
                fatal_lang_error('mc_notes_delete_own', false);
        }

        // Lets delete it.
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}log_comments
            WHERE id_comment = {int:note}
                AND comment_type = {literal:modnote}',
            array(
                'note' => $_GET['delete'],
            )
        );

        // Clear the cache.
        cache_put_data('moderator_notes', null, 240);
        cache_put_data('moderator_notes_total', null, 240);

        // Tell them the message was deleted.
        $_SESSION['rc_confirmation'] = 'message_deleted';

        redirectexit('action=moderate');
    }

    // How many notes in total?
    if (($moderator_notes_total = cache_get_data('moderator_notes_total', 240)) === null)
    {
        $request = $smcFunc['db_query']('', '
            SELECT COUNT(*)
            FROM {db_prefix}log_comments AS lc
                LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
            WHERE lc.comment_type = {literal:modnote}',
            array(
            )
        );
        list ($moderator_notes_total) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);

        cache_put_data('moderator_notes_total', $moderator_notes_total, 240);
    }

    // Grab the current notes. We can only use the cache for the first page of notes.
    $offset = isset($_GET['notes']) && isset($_GET['start']) ? $_GET['start'] : 0;
    if ($offset != 0 || ($moderator_notes = cache_get_data('moderator_notes', 240)) === null)
    {
        $request = $smcFunc['db_query']('', '
            SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
                lc.log_time, lc.body, lc.id_comment AS id_note
            FROM {db_prefix}log_comments AS lc
                LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
            WHERE lc.comment_type = {literal:modnote}
            ORDER BY id_comment DESC
            LIMIT {int:offset}, 10',
            array(
                'offset' => $offset,
            )
        );
        $moderator_notes = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $moderator_notes[] = $row;
        $smcFunc['db_free_result']($request);

        if ($offset == 0)
            cache_put_data('moderator_notes', $moderator_notes, 240);
    }

    // Lets construct a page index.
    $context['page_index'] = constructPageIndex($scripturl . '?action=moderate;area=index;notes', $_GET['start'], $moderator_notes_total, 10);
    $context['start'] = $_GET['start'];

    $context['notes'] = array();
    foreach ($moderator_notes as $note)
    {
        $context['notes'][] = array(
            'author' => array(
                'id' => $note['id_member'],
                'link' => $note['id_member'] ? ('<a href="' . $scripturl . '?action=profile;u=' . $note['id_member'] . '">' . $note['member_name'] . '</a>') : $note['member_name'],
            ),
            'time' => timeformat($note['log_time']),
            'text' => parse_bbc($note['body']),
            'delete_href' => $scripturl . '?action=moderate;area=index;notes;delete=' . $note['id_note'] . ';' . $context['session_var'] . '=' . $context['session_id'],
            'can_delete' => allowedTo('admin_forum') || $note['id_member'] == $user_info['id'],
        );
    }

    // Couple tokens for add/delete modnotes
    createToken('mod-modnote-add');
    createToken('mod-modnote-del', 'get');

    return 'notes';
}

/**
 * Show a list of the most recent reported posts.
 */
function ModBlockReportedPosts()
{
    global $context, $user_info, $scripturl, $smcFunc;

    // Got the info already?
    $cachekey = md5($smcFunc['json_encode']($user_info['mod_cache']['bq']));
    $context['reported_posts'] = array();
    if ($user_info['mod_cache']['bq'] == '0=1')
        return 'reported_posts_block';

    if (($reported_posts = cache_get_data('reported_posts_' . $cachekey, 90)) === null)
    {
        // By George, that means we in a position to get the reports, jolly good.
        $request = $smcFunc['db_query']('', '
            SELECT lr.id_report, lr.id_msg, lr.id_topic, lr.id_board, lr.id_member, lr.subject,
                lr.num_reports, COALESCE(mem.real_name, lr.membername) AS author_name,
                COALESCE(mem.id_member, 0) AS id_author
            FROM {db_prefix}log_reported AS lr
                LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lr.id_member)
            WHERE ' . ($user_info['mod_cache']['bq'] == '1=1' || $user_info['mod_cache']['bq'] == '0=1' ? $user_info['mod_cache']['bq'] : 'lr.' . $user_info['mod_cache']['bq']) . '
                AND lr.id_board != {int:not_a_reported_post}
                AND lr.closed = {int:not_closed}
                AND lr.ignore_all = {int:not_ignored}
            ORDER BY lr.time_updated DESC
            LIMIT 10',
            array(
                'not_a_reported_post' => 0,
                'not_closed' => 0,
                'not_ignored' => 0,
            )
        );
        $reported_posts = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $reported_posts[] = $row;
        $smcFunc['db_free_result']($request);

        // Cache it.
        cache_put_data('reported_posts_' . $cachekey, $reported_posts, 90);
    }

    $context['reported_posts'] = array();
    foreach ($reported_posts as $i => $row)
    {
        $context['reported_posts'][] = array(
            'id' => $row['id_report'],
            'topic_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
            'report_href' => $scripturl . '?action=moderate;area=reportedposts;sa=details;rid=' . $row['id_report'],
            'report_link' => '<a href="' . $scripturl . '?action=moderate;area=reportedposts;sa=details;rid=' . $row['id_report'] . '">' . $row['subject'] . '</a>',
            'author' => array(
                'id' => $row['id_author'],
                'name' => $row['author_name'],
                'link' => $row['id_author'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_author'] . '">' . $row['author_name'] . '</a>' : $row['author_name'],
                'href' => $scripturl . '?action=profile;u=' . $row['id_author'],
            ),
            'subject' => $row['subject'],
            'num_reports' => $row['num_reports'],
        );
    }

    return 'reported_posts_block';
}

/**
 * Show a list of all the group requests they can see.
 */
function ModBlockGroupRequests()
{
    global $context, $user_info, $scripturl, $smcFunc;

    $context['group_requests'] = array();
    // Make sure they can even moderate someone!
    if ($user_info['mod_cache']['gq'] == '0=1')
        return 'group_requests_block';

    // What requests are outstanding?
    $request = $smcFunc['db_query']('', '
        SELECT lgr.id_request, lgr.id_member, lgr.id_group, lgr.time_applied, mem.member_name, mg.group_name, mem.real_name
        FROM {db_prefix}log_group_requests AS lgr
            INNER JOIN {db_prefix}members AS mem ON (mem.id_member = lgr.id_member)
            INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = lgr.id_group)
        WHERE ' . ($user_info['mod_cache']['gq'] == '1=1' || $user_info['mod_cache']['gq'] == '0=1' ? $user_info['mod_cache']['gq'] : 'lgr.' . $user_info['mod_cache']['gq']) . '
            AND lgr.status = {int:status_open}
        ORDER BY lgr.id_request DESC
        LIMIT 10',
        array(
            'status_open' => 0,
        )
    );
    for ($i = 0; $row = $smcFunc['db_fetch_assoc']($request); $i++)
    {
        $context['group_requests'][] = array(
            'id' => $row['id_request'],
            'request_href' => $scripturl . '?action=groups;sa=requests;gid=' . $row['id_group'],
            'member' => array(
                'id' => $row['id_member'],
                'name' => $row['real_name'],
                'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
                'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
            ),
            'group' => array(
                'id' => $row['id_group'],
                'name' => $row['group_name'],
            ),
            'time_submitted' => timeformat($row['time_applied']),
        );
    }
    $smcFunc['db_free_result']($request);

    return 'group_requests_block';
}

/**
 * Show a list of the most recent reported posts.
 */
function ModBlockReportedMembers()
{
    global $context, $scripturl, $smcFunc;

    // Got the info already?
    $cachekey = md5($smcFunc['json_encode']((int) allowedTo('moderate_forum')));
    $context['reported_users'] = array();
    if (!allowedTo('moderate_forum'))
        return 'reported_users_block';

    if (($reported_users = cache_get_data('reported_users_' . $cachekey, 90)) === null)
    {
        // By George, that means we in a position to get the reports, jolly good.
        $request = $smcFunc['db_query']('', '
            SELECT lr.id_report, lr.id_member,
                lr.num_reports, COALESCE(mem.real_name, lr.membername) AS user_name,
                COALESCE(mem.id_member, 0) AS id_user
            FROM {db_prefix}log_reported AS lr
                LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lr.id_member)
            WHERE lr.id_board = {int:not_a_reported_post}
                AND lr.closed = {int:not_closed}
                AND lr.ignore_all = {int:not_ignored}
            ORDER BY lr.time_updated DESC
            LIMIT 10',
            array(
                'not_a_reported_post' => 0,
                'not_closed' => 0,
                'not_ignored' => 0,
            )
        );
        $reported_users = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $reported_users[] = $row;
        $smcFunc['db_free_result']($request);

        // Cache it.
        cache_put_data('reported_users_' . $cachekey, $reported_users, 90);
    }

    $context['reported_users'] = array();
    foreach ($reported_users as $i => $row)
    {
        $context['reported_users'][] = array(
            'id' => $row['id_report'],
            'report_href' => $scripturl . '?action=moderate;area=reportedmembers;report=' . $row['id_report'],
            'user' => array(
                'id' => $row['id_user'],
                'name' => $row['user_name'],
                'link' => $row['id_user'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_user'] . '">' . $row['user_name'] . '</a>' : $row['user_name'],
                'href' => $scripturl . '?action=profile;u=' . $row['id_user'],
            ),
            'num_reports' => $row['num_reports'],
        );
    }

    return 'reported_users_block';
}

/**
 * Browse all the reported users...
 */
function ReportedMembers()
{
    global $txt, $context, $scripturl, $smcFunc;

    loadTemplate('ModerationCenter');

    // Set an empty var for the server response.
    $context['report_member_action'] = '';

    // Put the open and closed options into tabs, because we can...
    $context[$context['moderation_menu_name']]['tab_data'] = array(
        'title' => $txt['mc_reported_members'],
        'help' => '',
        'description' => $txt['mc_reported_members_desc'],
    );

    isAllowedTo('moderate_forum');

    // Set up the comforting bits...
    $context['page_title'] = $txt['mc_reported_members'];
    $context['sub_template'] = 'reported_members';

    // Are we viewing open or closed reports?
    $context['view_closed'] = isset($_GET['sa']) && $_GET['sa'] == 'closed' ? 1 : 0;

    // Are we doing any work?
    if ((isset($_GET['ignore']) || isset($_GET['close'])) && isset($_GET['rid']))
    {
        checkSession('get');
        $_GET['rid'] = (int) $_GET['rid'];

        // Update the report...
        $smcFunc['db_query']('', '
            UPDATE {db_prefix}log_reported
            SET ' . (isset($_GET['ignore']) ? 'ignore_all = {int:ignore_all}' : 'closed = {int:closed}') . '
            WHERE id_report = {int:id_report}',
            array(
                'ignore_all' => isset($_GET['ignore']) ? (int) $_GET['ignore'] : 0,
                'closed' => isset($_GET['close']) ? (int) $_GET['close'] : 0,
                'id_report' => $_GET['rid'],
            )
        );

        // Get the board, topic and message for this report
        $request = $smcFunc['db_query']('', '
            SELECT id_member, membername
            FROM {db_prefix}log_reported
            WHERE id_report = {int:id_report}',
            array(
                'id_report' => $_GET['rid'],
            )
        );

        // Set up the data for the log...
        $extra = array('report' => $_GET['rid']);
        list($extra['member'], $extra['membername']) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);

        // Stick this in string format for consistency
        $extra['member'] = (string) $extra['member'];

        // Tell the user about it.
        $context['report_member_action'] = isset($_GET['ignore']) ? (!empty($_GET['ignore']) ? 'ignore' : 'unignore') : (!empty($_GET['close']) ? 'close' : 'open');

        // Log this action
        logAction($context['report_member_action'] . '_user_report', $extra);

        // Time to update.
        updateSettings(array('last_mod_report_action' => time()));
        recountOpenReports('members');
    }
    elseif (isset($_POST['close']) && isset($_POST['close_selected']))
    {
        checkSession();

        // All the ones to update...
        $toClose = array();
        foreach ($_POST['close'] as $rid)
            $toClose[] = (int) $rid;

        if (!empty($toClose))
        {
            // Get the data for each of these reports
            $request = $smcFunc['db_query']('', '
                SELECT id_report, id_member, membername
                FROM {db_prefix}log_reported
                WHERE id_report IN ({array_int:report_list})',
                array(
                    'report_list' => $toClose,
                )
            );

            $logs = array();
            while ($reports = $smcFunc['db_fetch_assoc']($request))
            {
                $logs[] = array(
                    'action' => 'close_user_report',
                    'log_type' => 'moderate',
                    'extra' => array(
                        'report' => $reports['id_report'],
                        'membername' => $reports['membername'],
                        'member' => (string) $reports['id_member'],
                    ),
                );
            }

            $smcFunc['db_free_result']($request);

            // Log the closing of all the reports
            logActions($logs);

            $smcFunc['db_query']('', '
                UPDATE {db_prefix}log_reported
                SET closed = {int:is_closed}
                WHERE id_report IN ({array_int:report_list})',
                array(
                    'report_list' => $toClose,
                    'is_closed' => 1,
                )
            );

            // Time to update.
            updateSettings(array('last_mod_report_action' => time()));
            recountOpenReports('members');
        }

        // Go on and tell the result.
        $context['report_member_action'] = 'close_all';
    }

    // How many entries are we viewing?
    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}log_reported AS lr
        WHERE lr.closed = {int:view_closed}
            AND lr.id_board = {int:not_a_reported_post}',
        array(
            'view_closed' => $context['view_closed'],
            'not_a_reported_post' => 0,
        )
    );
    list ($context['total_reports']) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    // So, that means we can page index, yes?
    $context['page_index'] = constructPageIndex($scripturl . '?action=moderate;area=reportedmembers' . ($context['view_closed'] ? ';sa=closed' : ''), $_GET['start'], $context['total_reports'], 10);
    $context['start'] = $_GET['start'];

    // By George, that means we in a position to get the reports, golly good.
    $request = $smcFunc['db_query']('', '
        SELECT lr.id_report, lr.id_member, lr.time_started, lr.time_updated, lr.num_reports, lr.closed, lr.ignore_all,
            COALESCE(mem.real_name, lr.membername) AS user_name, COALESCE(mem.id_member, 0) AS id_user
        FROM {db_prefix}log_reported AS lr
            LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lr.id_member)
        WHERE lr.closed = {int:view_closed}
            AND lr.id_board = {int:not_a_reported_post}
        ORDER BY lr.time_updated DESC
        LIMIT {int:limit}, {int:max}',
        array(
            'view_closed' => $context['view_closed'],
            'not_a_reported_post' => 0,
            'limit' => $context['start'],
            'max' => 10,
        )
    );
    $context['reports'] = array();
    $report_ids = array();
    for ($i = 0; $row = $smcFunc['db_fetch_assoc']($request); $i++)
    {
        $report_ids[] = $row['id_report'];
        $context['reports'][$row['id_report']] = array(
            'id' => $row['id_report'],
            'report_href' => $scripturl . '?action=moderate;area=reportedmembers;report=' . $row['id_report'],
            'user' => array(
                'id' => $row['id_user'],
                'name' => $row['user_name'],
                'link' => $row['id_user'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_user'] . '">' . $row['user_name'] . '</a>' : $row['user_name'],
                'href' => $scripturl . '?action=profile;u=' . $row['id_user'],
            ),
            'comments' => array(),
            'time_started' => timeformat($row['time_started']),
            'last_updated' => timeformat($row['time_updated']),
            'num_reports' => $row['num_reports'],
            'closed' => $row['closed'],
            'ignore' => $row['ignore_all']
        );
    }
    $smcFunc['db_free_result']($request);

    // Now get all the people who reported it.
    if (!empty($report_ids))
    {
        $request = $smcFunc['db_query']('', '
            SELECT lrc.id_comment, lrc.id_report, lrc.time_sent, lrc.comment,
                COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lrc.membername) AS reporter
            FROM {db_prefix}log_reported_comments AS lrc
                LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lrc.id_member)
            WHERE lrc.id_report IN ({array_int:report_list})',
            array(
                'report_list' => $report_ids,
            )
        );
        while ($row = $smcFunc['db_fetch_assoc']($request))
        {
            $context['reports'][$row['id_report']]['comments'][] = array(
                'id' => $row['id_comment'],
                'message' => $row['comment'],
                'time' => timeformat($row['time_sent']),
                'member' => array(
                    'id' => $row['id_member'],
                    'name' => empty($row['reporter']) ? $txt['guest'] : $row['reporter'],
                    'link' => $row['id_member'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['reporter'] . '</a>' : (empty($row['reporter']) ? $txt['guest'] : $row['reporter']),
                    'href' => $row['id_member'] ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
                ),
            );
        }
        $smcFunc['db_free_result']($request);
    }

    $context['report_manage_bans'] = allowedTo('manage_bans');
}

/**
 * Act as an entrace for all group related activity.
 *
 * @todo As for most things in this file, this needs to be moved somewhere appropriate?
 */
function ModerateGroups()
{
    global $context, $user_info;

    // You need to be allowed to moderate groups...
    if ($user_info['mod_cache']['gq'] == '0=1')
        isAllowedTo('manage_membergroups');

    // Load the group templates.
    loadTemplate('ModerationCenter');

    // Setup the subactions...
    $subActions = array(
        'requests' => 'GroupRequests',
        'view' => 'ViewGroups',
    );

    if (!isset($_GET['sa']) || !isset($subActions[$_GET['sa']]))
        $_GET['sa'] = 'view';
    $context['sub_action'] = $_GET['sa'];

    // Call the relevant function.
    call_helper($subActions[$context['sub_action']]);
}

/**
 * Show a notice sent to a user.
 */
function ShowNotice()
{
    global $smcFunc, $txt, $context;

    $context['page_title'] = $txt['show_notice'];
    $context['sub_template'] = 'show_notice';
    $context['template_layers'] = array();

    loadTemplate('ModerationCenter');

    // @todo Assumes nothing needs permission more than accessing moderation center!
    $id_notice = (int) $_GET['nid'];
    $request = $smcFunc['db_query']('', '
        SELECT body, subject
        FROM {db_prefix}log_member_notices
        WHERE id_notice = {int:id_notice}',
        array(
            'id_notice' => $id_notice,
        )
    );
    if ($smcFunc['db_num_rows']($request) == 0)
        fatal_lang_error('no_access', false);
    list ($context['notice_body'], $context['notice_subject']) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    $context['notice_body'] = parse_bbc($context['notice_body'], false);
}

/**
 * View watched users.
 */
function ViewWatchedUsers()
{
    global $modSettings, $context, $txt, $scripturl, $sourcedir;

    // Some important context!
    $context['page_title'] = $txt['mc_watched_users_title'];
    $context['view_posts'] = isset($_GET['sa']) && $_GET['sa'] == 'post';
    $context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;

    loadTemplate('ModerationCenter');

    // Get some key settings!
    $modSettings['warning_watch'] = empty($modSettings['warning_watch']) ? 1 : $modSettings['warning_watch'];

    // Put some pretty tabs on cause we're gonna be doing hot stuff here...
    $context[$context['moderation_menu_name']]['tab_data'] = array(
        'title' => $txt['mc_watched_users_title'],
        'help' => '',
        'description' => $txt['mc_watched_users_desc'],
    );

    // First off - are we deleting?
    if (!empty($_REQUEST['delete']))
    {
        checkSession(!is_array($_REQUEST['delete']) ? 'get' : 'post');

        $toDelete = array();
        if (!is_array($_REQUEST['delete']))
            $toDelete[] = (int) $_REQUEST['delete'];
        else
            foreach ($_REQUEST['delete'] as $did)
                $toDelete[] = (int) $did;

        if (!empty($toDelete))
        {
            require_once($sourcedir . '/RemoveTopic.php');
            // If they don't have permission we'll let it error - either way no chance of a security slip here!
            foreach ($toDelete as $did)
                removeMessage($did);
        }
    }

    // Start preparing the list by grabbing relevant permissions.
    if (!$context['view_posts'])
    {
        $approve_query = '';
        $delete_boards = array();
    }
    else
    {
        // Still obey permissions!
        $approve_boards = boardsAllowedTo('approve_posts');
        $delete_boards = boardsAllowedTo('delete_any');

        if ($approve_boards == array(0))
            $approve_query = '';
        elseif (!empty($approve_boards))
            $approve_query = ' AND m.id_board IN (' . implode(',', $approve_boards) . ')';
        // Nada, zip, etc...
        else
            $approve_query = ' AND 1=0';
    }

    require_once($sourcedir . '/Subs-List.php');

    // This is all the information required for a watched user listing.
    $listOptions = array(
        'id' => 'watch_user_list',
        'title' => $txt['mc_watched_users_title'] . ' - ' . ($context['view_posts'] ? $txt['mc_watched_users_post'] : $txt['mc_watched_users_member']),
        'items_per_page' => $modSettings['defaultMaxListItems'],
        'no_items_label' => $context['view_posts'] ? $txt['mc_watched_users_no_posts'] : $txt['mc_watched_users_none'],
        'base_href' => $scripturl . '?action=moderate;area=userwatch;sa=' . ($context['view_posts'] ? 'post' : 'member'),
        'default_sort_col' => $context['view_posts'] ? '' : 'member',
        'get_items' => array(
            'function' => $context['view_posts'] ? 'list_getWatchedUserPosts' : 'list_getWatchedUsers',
            'params' => array(
                $approve_query,
                $delete_boards,
            ),
        ),
        'get_count' => array(
            'function' => $context['view_posts'] ? 'list_getWatchedUserPostsCount' : 'list_getWatchedUserCount',
            'params' => array(
                $approve_query,
            ),
        ),
        // This assumes we are viewing by user.
        'columns' => array(
            'member' => array(
                'header' => array(
                    'value' => $txt['mc_watched_users_member'],
                ),
                'data' => array(
                    'sprintf' => array(
                        'format' => '<a href="' . $scripturl . '?action=profile;u=%1$d">%2$s</a>',
                        'params' => array(
                            'id' => false,
                            'name' => false,
                        ),
                    ),
                ),
                'sort' => array(
                    'default' => 'real_name',
                    'reverse' => 'real_name DESC',
                ),
            ),
            'warning' => array(
                'header' => array(
                    'value' => $txt['mc_watched_users_warning'],
                ),
                'data' => array(
                    'function' => function($member) use ($scripturl)
                    {
                        return allowedTo('issue_warning') ? '<a href="' . $scripturl . '?action=profile;area=issuewarning;u=' . $member['id'] . '">' . $member['warning'] . '%</a>' : $member['warning'] . '%';
                    },
                ),
                'sort' => array(
                    'default' => 'warning',
                    'reverse' => 'warning DESC',
                ),
            ),
            'posts' => array(
                'header' => array(
                    'value' => $txt['posts'],
                ),
                'data' => array(
                    'sprintf' => array(
                        'format' => '<a href="' . $scripturl . '?action=profile;u=%1$d;area=showposts;sa=messages">%2$s</a>',
                        'params' => array(
                            'id' => false,
                            'posts' => false,
                        ),
                    ),
                ),
                'sort' => array(
                    'default' => 'posts',
                    'reverse' => 'posts DESC',
                ),
            ),
            'last_login' => array(
                'header' => array(
                    'value' => $txt['mc_watched_users_last_login'],
                ),
                'data' => array(
                    'db' => 'last_login',
                ),
                'sort' => array(
                    'default' => 'last_login',
                    'reverse' => 'last_login DESC',
                ),
            ),
            'last_post' => array(
                'header' => array(
                    'value' => $txt['mc_watched_users_last_post'],
                ),
                'data' => array(
                    'function' => function($member) use ($scripturl)
                    {
                        if ($member['last_post_id'])
                            return '<a href="' . $scripturl . '?msg=' . $member['last_post_id'] . '">' . $member['last_post'] . '</a>';
                        else
                            return $member['last_post'];
                    },
                ),
            ),
        ),
        'form' => array(
            'href' => $scripturl . '?action=moderate;area=userwatch;sa=post',
            'include_sort' => true,
            'include_start' => true,
            'hidden_fields' => array(
                $context['session_var'] => $context['session_id'],
            ),
        ),
        'additional_rows' => array(
            $context['view_posts'] ?
                array(
                    'position' => 'bottom_of_list',
                    'value' => '
                    <input type="submit" name="delete_selected" value="' . $txt['quickmod_delete_selected'] . '" class="button">',
                    'class' => 'floatright',
                ) : array(),
        ),
    );

    // If this is being viewed by posts we actually change the columns to call a template each time.
    if ($context['view_posts'])
    {
        $listOptions['columns'] = array(
            'posts' => array(
                'data' => array(
                    'function' => function($post)
                    {
                        return template_user_watch_post_callback($post);
                    },
                    'class' => 'unique'
                ),
            ),
        );
    }

    // Create the watched user list.
    createList($listOptions);

    $context['sub_template'] = 'show_list';
    $context['default_list'] = 'watch_user_list';
}

/**
 * Callback for createList().
 *
 * @param string $approve_query Not used here
 * @return int The number of users on the watch list
 */
function list_getWatchedUserCount($approve_query)
{
    global $smcFunc, $modSettings;

    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}members
        WHERE warning >= {int:warning_watch}',
        array(
            'warning_watch' => $modSettings['warning_watch'],
        )
    );
    list ($totalMembers) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    return $totalMembers;
}

/**
 * Callback for createList().
 *
 * @param int $start The item to start with (for pagination purposes)
 * @param int $items_per_page The number of items to show per page
 * @param string $sort A string indicating how to sort things
 * @param string $approve_query A query for approving things. Not used here.
 * @param string $dummy Not used here.
 */
function list_getWatchedUsers($start, $items_per_page, $sort, $approve_query, $dummy)
{
    global $smcFunc, $txt, $modSettings, $user_info;

    $request = $smcFunc['db_query']('', '
        SELECT id_member, real_name, last_login, posts, warning
        FROM {db_prefix}members
        WHERE warning >= {int:warning_watch}
        ORDER BY {raw:sort}
        LIMIT {int:start}, {int:max}',
        array(
            'warning_watch' => $modSettings['warning_watch'],
            'sort' => $sort,
            'start' => $start,
            'max' => $items_per_page,
        )
    );
    $watched_users = array();
    $members = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        $watched_users[$row['id_member']] = array(
            'id' => $row['id_member'],
            'name' => $row['real_name'],
            'last_login' => $row['last_login'] ? timeformat($row['last_login']) : $txt['never'],
            'last_post' => $txt['not_applicable'],
            'last_post_id' => 0,
            'warning' => $row['warning'],
            'posts' => $row['posts'],
        );
        $members[] = $row['id_member'];
    }
    $smcFunc['db_free_result']($request);

    if (!empty($members))
    {
        // First get the latest messages from these users.
        $request = $smcFunc['db_query']('', '
            SELECT m.id_member, MAX(m.id_msg) AS last_post_id
            FROM {db_prefix}messages AS m' . ($user_info['query_see_board'] == '1=1' ? '' : '
                INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})') . '
            WHERE m.id_member IN ({array_int:member_list})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
                AND m.approved = {int:is_approved}') . '
            GROUP BY m.id_member',
            array(
                'member_list' => $members,
                'is_approved' => 1,
            )
        );
        $latest_posts = array();
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $latest_posts[$row['id_member']] = $row['last_post_id'];

        if (!empty($latest_posts))
        {
            // Now get the time those messages were posted.
            $request = $smcFunc['db_query']('', '
                SELECT id_member, poster_time
                FROM {db_prefix}messages
                WHERE id_msg IN ({array_int:message_list})',
                array(
                    'message_list' => $latest_posts,
                )
            );
            while ($row = $smcFunc['db_fetch_assoc']($request))
            {
                $watched_users[$row['id_member']]['last_post'] = timeformat($row['poster_time']);
                $watched_users[$row['id_member']]['last_post_id'] = $latest_posts[$row['id_member']];
            }

            $smcFunc['db_free_result']($request);
        }

        $request = $smcFunc['db_query']('', '
            SELECT MAX(m.poster_time) AS last_post, MAX(m.id_msg) AS last_post_id, m.id_member
            FROM {db_prefix}messages AS m' . ($user_info['query_see_board'] == '1=1' ? '' : '
                INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND {query_see_board})') . '
            WHERE m.id_member IN ({array_int:member_list})' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
                AND m.approved = {int:is_approved}') . '
            GROUP BY m.id_member',
            array(
                'member_list' => $members,
                'is_approved' => 1,
            )
        );
        while ($row = $smcFunc['db_fetch_assoc']($request))
        {
            $watched_users[$row['id_member']]['last_post'] = timeformat($row['last_post']);
            $watched_users[$row['id_member']]['last_post_id'] = $row['last_post_id'];
        }
        $smcFunc['db_free_result']($request);
    }

    return $watched_users;
}

/**
 * Callback for createList().
 *
 * @param string $approve_query A query to pull only approved items
 * @return int The total number of posts by watched users
 */
function list_getWatchedUserPostsCount($approve_query)
{
    global $smcFunc, $modSettings;

    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}messages AS m
            INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
            INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
        WHERE mem.warning >= {int:warning_watch}
            AND {query_see_board}
            ' . $approve_query,
        array(
            'warning_watch' => $modSettings['warning_watch'],
        )
    );
    list ($totalMemberPosts) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    return $totalMemberPosts;
}

/**
 * Callback for createList().
 *
 * @param int $start The item to start with (for pagination purposes)
 * @param int $items_per_page The number of items to show per page
 * @param string $sort A string indicating how to sort the results (not used here)
 * @param string $approve_query A query to only pull approved items
 * @param int[] $delete_boards An array containing the IDs of boards we can delete posts in
 * @return array An array of info about posts by watched users
 */
function list_getWatchedUserPosts($start, $items_per_page, $sort, $approve_query, $delete_boards)
{
    global $smcFunc, $scripturl, $modSettings;

    $request = $smcFunc['db_query']('', '
        SELECT m.id_msg, m.id_topic, m.id_board, m.id_member, m.subject, m.body, m.poster_time,
            m.approved, mem.real_name, m.smileys_enabled
        FROM {db_prefix}messages AS m
            INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
            INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
        WHERE mem.warning >= {int:warning_watch}
            AND {query_see_board}
            ' . $approve_query . '
        ORDER BY m.id_msg DESC
        LIMIT {int:start}, {int:max}',
        array(
            'warning_watch' => $modSettings['warning_watch'],
            'start' => $start,
            'max' => $items_per_page,
        )
    );
    $member_posts = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        $row['subject'] = censorText($row['subject']);
        $row['body'] = censorText($row['body']);

        $member_posts[$row['id_msg']] = array(
            'id' => $row['id_msg'],
            'id_topic' => $row['id_topic'],
            'author_link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
            'subject' => $row['subject'],
            'body' => parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']),
            'poster_time' => timeformat($row['poster_time']),
            'approved' => $row['approved'],
            'can_delete' => $delete_boards == array(0) || in_array($row['id_board'], $delete_boards),
        );
    }
    $smcFunc['db_free_result']($request);

    return $member_posts;
}

/**
 * Entry point for viewing warning related stuff.
 */
function ViewWarnings()
{
    global $context, $txt;

    $subActions = array(
        'log' => array('ViewWarningLog'),
        'templateedit' => array('ModifyWarningTemplate', 'issue_warning'),
        'templates' => array('ViewWarningTemplates', 'issue_warning'),
    );

    call_integration_hook('integrate_warning_log_actions', array(&$subActions));

    $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) && (empty($subActions[$_REQUEST['sa']][1]) || allowedTo($subActions[$_REQUEST['sa']])) ? $_REQUEST['sa'] : 'log';

    // Some of this stuff is overseas, so to speak.
    loadTemplate('ModerationCenter');
    loadLanguage('Profile');

    // Setup the admin tabs.
    $context[$context['moderation_menu_name']]['tab_data'] = array(
        'title' => $txt['mc_warnings'],
        'description' => $txt['mc_warnings_description'],
    );

    // Call the right function.
    call_helper($subActions[$_REQUEST['sa']][0]);
}

/**
 * Simply put, look at the warning log!
 */
function ViewWarningLog()
{
    global $smcFunc, $modSettings, $context, $txt, $scripturl, $sourcedir;

    // Setup context as always.
    $context['page_title'] = $txt['mc_warning_log_title'];

    loadLanguage('Modlog');

    // If we're coming from a search, get the variables.
    if (!empty($_REQUEST['params']) && empty($_REQUEST['is_search']))
    {
        $search_params = base64_decode(strtr($_REQUEST['params'], array(' ' => '+')));
        $search_params = $smcFunc['json_decode']($search_params, true);
    }

    // This array houses all the valid search types.
    $searchTypes = array(
        'member' => array('sql' => 'member_name_col', 'label' => $txt['profile_warning_previous_issued']),
        'recipient' => array('sql' => 'recipient_name', 'label' => $txt['mc_warnings_recipient']),
    );

    // Do the column stuff!
    $sort_types = array(
        'member' => 'member_name_col',
        'recipient' => 'recipient_name',
    );

    // Setup the direction stuff...
    $context['order'] = isset($_REQUEST['sort']) && isset($sort_types[$_REQUEST['sort']]) ? $_REQUEST['sort'] : 'member';

    if (!isset($search_params['string']) || (!empty($_REQUEST['search']) && $search_params['string'] != $_REQUEST['search']))
        $search_params_string = empty($_REQUEST['search']) ? '' : $_REQUEST['search'];
    else
        $search_params_string = $search_params['string'];

    if (isset($_REQUEST['search_type']) || empty($search_params['type']) || !isset($searchTypes[$search_params['type']]))
        $search_params_type = isset($_REQUEST['search_type']) && isset($searchTypes[$_REQUEST['search_type']]) ? $_REQUEST['search_type'] : (isset($searchTypes[$context['order']]) ? $context['order'] : 'member');
    else
        $search_params_type = $search_params['type'];

    $search_params = array(
        'string' => $search_params_string,
        'type' => $search_params_type,
    );

    $context['url_start'] = '?action=moderate;area=warnings;sa=log;sort=' . $context['order'];

    // Setup the search context.
    $context['search_params'] = empty($search_params['string']) ? '' : base64_encode($smcFunc['json_encode']($search_params));
    $context['search'] = array(
        'string' => $search_params['string'],
        'type' => $search_params['type'],
        'label' => $searchTypes[$search_params_type]['label'],
    );

    require_once($sourcedir . '/Subs-List.php');

    // This is all the information required for a watched user listing.
    $listOptions = array(
        'id' => 'warning_list',
        'title' => $txt['mc_warning_log_title'],
        'items_per_page' => $modSettings['defaultMaxListItems'],
        'no_items_label' => $txt['mc_warnings_none'],
        'base_href' => $scripturl . '?action=moderate;area=warnings;sa=log;' . $context['session_var'] . '=' . $context['session_id'],
        'default_sort_col' => 'time',
        'get_items' => array(
            'function' => 'list_getWarnings',
        ),
        'get_count' => array(
            'function' => 'list_getWarningCount',
        ),
        // This assumes we are viewing by user.
        'columns' => array(
            'issuer' => array(
                'header' => array(
                    'value' => $txt['profile_warning_previous_issued'],
                ),
                'data' => array(
                    'db' => 'issuer_link',
                ),
                'sort' => array(
                    'default' => 'member_name_col',
                    'reverse' => 'member_name_col DESC',
                ),
            ),
            'recipient' => array(
                'header' => array(
                    'value' => $txt['mc_warnings_recipient'],
                ),
                'data' => array(
                    'db' => 'recipient_link',
                ),
                'sort' => array(
                    'default' => 'recipient_name',
                    'reverse' => 'recipient_name DESC',
                ),
            ),
            'time' => array(
                'header' => array(
                    'value' => $txt['profile_warning_previous_time'],
                ),
                'data' => array(
                    'db' => 'time',
                ),
                'sort' => array(
                    'default' => 'lc.log_time DESC',
                    'reverse' => 'lc.log_time',
                ),
            ),
            'reason' => array(
                'header' => array(
                    'value' => $txt['profile_warning_previous_reason'],
                ),
                'data' => array(
                    'function' => function($rowData) use ($scripturl, $txt)
                    {
                        $output = '
                            <div class="floatleft">
                                ' . $rowData['reason'] . '
                            </div>';

                        if (!empty($rowData['id_notice']))
                            $output .= '
                                &nbsp;<a href="' . $scripturl . '?action=moderate;area=notice;nid=' . $rowData['id_notice'] . '" onclick="window.open(this.href, \'\', \'scrollbars=yes,resizable=yes,width=400,height=250\');return false;" target="_blank" rel="noopener" title="' . $txt['profile_warning_previous_notice'] . '"><span class="main_icons filter centericon"></span></a>';
                        return $output;
                    },
                ),
            ),
            'points' => array(
                'header' => array(
                    'value' => $txt['profile_warning_previous_level'],
                ),
                'data' => array(
                    'db' => 'counter',
                ),
            ),
        ),
        'form' => array(
            'href' => $scripturl . $context['url_start'],
            'include_sort' => true,
            'include_start' => true,
            'hidden_fields' => array(
                $context['session_var'] => $context['session_id'],
                'params' => false
            ),
        ),
        'additional_rows' => array(
            array(
                'position' => 'below_table_data',
                'value' => '
                    ' . $txt['modlog_search'] . ':
                    <input type="text" name="search" size="18" value="' . $smcFunc['htmlspecialchars']($context['search']['string']) . '">
                    <input type="submit" name="is_search" value="' . $txt['modlog_go'] . '" class="button">',
                'class' => 'floatright',
            ),
        ),
    );

    // Create the watched user list.
    createList($listOptions);

    $context['sub_template'] = 'show_list';
    $context['default_list'] = 'warning_list';
}

/**
 * Callback for createList().
 *
 * @return int The total number of warnings that have been issued
 */
function list_getWarningCount()
{
    global $smcFunc;

    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}log_comments
        WHERE comment_type = {string:warning}',
        array(
            'warning' => 'warning',
        )
    );
    list ($totalWarns) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    return $totalWarns;
}

/**
 * Callback for createList().
 *
 * @param int $start The item to start with (for pagination purposes)
 * @param int $items_per_page The number of items to show per page
 * @param string $sort A string indicating how to sort the results
 * @return array An array of data about warning log entries
 */
function list_getWarnings($start, $items_per_page, $sort)
{
    global $smcFunc, $scripturl;

    $request = $smcFunc['db_query']('', '
        SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name_col,
            COALESCE(mem2.id_member, 0) AS id_recipient, COALESCE(mem2.real_name, lc.recipient_name) AS recipient_name,
            lc.log_time, lc.body, lc.id_notice, lc.counter
        FROM {db_prefix}log_comments AS lc
            LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
            LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = lc.id_recipient)
        WHERE lc.comment_type = {string:warning}
        ORDER BY {raw:sort}
        LIMIT {int:start}, {int:max}',
        array(
            'warning' => 'warning',
            'start' => $start,
            'max' => $items_per_page,
            'sort' => $sort,
        )
    );
    $warnings = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        $warnings[] = array(
            'issuer_link' => $row['id_member'] ? ('<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['member_name_col'] . '</a>') : $row['member_name_col'],
            'recipient_link' => $row['id_recipient'] ? ('<a href="' . $scripturl . '?action=profile;u=' . $row['id_recipient'] . '">' . $row['recipient_name'] . '</a>') : $row['recipient_name'],
            'time' => timeformat($row['log_time']),
            'reason' => $row['body'],
            'counter' => $row['counter'] > 0 ? '+' . $row['counter'] : $row['counter'],
            'id_notice' => $row['id_notice'],
        );
    }
    $smcFunc['db_free_result']($request);

    return $warnings;
}

/**
 * Load all the warning templates.
 */
function ViewWarningTemplates()
{
    global $smcFunc, $modSettings, $context, $txt, $scripturl, $sourcedir, $user_info;

    // Submitting a new one?
    if (isset($_POST['add']))
        return ModifyWarningTemplate();
    elseif (isset($_POST['delete']) && !empty($_POST['deltpl']))
    {
        checkSession();
        validateToken('mod-wt');

        // Log the actions.
        $request = $smcFunc['db_query']('', '
            SELECT recipient_name
            FROM {db_prefix}log_comments
            WHERE id_comment IN ({array_int:delete_ids})
                AND comment_type = {string:warntpl}
                AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
            array(
                'delete_ids' => $_POST['deltpl'],
                'warntpl' => 'warntpl',
                'generic' => 0,
                'current_member' => $user_info['id'],
            )
        );
        while ($row = $smcFunc['db_fetch_assoc']($request))
            logAction('delete_warn_template', array('template' => $row['recipient_name']));
        $smcFunc['db_free_result']($request);

        // Do the deletes.
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}log_comments
            WHERE id_comment IN ({array_int:delete_ids})
                AND comment_type = {string:warntpl}
                AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
            array(
                'delete_ids' => $_POST['deltpl'],
                'warntpl' => 'warntpl',
                'generic' => 0,
                'current_member' => $user_info['id'],
            )
        );
    }

    // Setup context as always.
    $context['page_title'] = $txt['mc_warning_templates_title'];

    require_once($sourcedir . '/Subs-List.php');

    // This is all the information required for a watched user listing.
    $listOptions = array(
        'id' => 'warning_template_list',
        'title' => $txt['mc_warning_templates_title'],
        'items_per_page' => $modSettings['defaultMaxListItems'],
        'no_items_label' => $txt['mc_warning_templates_none'],
        'base_href' => $scripturl . '?action=moderate;area=warnings;sa=templates;' . $context['session_var'] . '=' . $context['session_id'],
        'default_sort_col' => 'title',
        'get_items' => array(
            'function' => 'list_getWarningTemplates',
        ),
        'get_count' => array(
            'function' => 'list_getWarningTemplateCount',
        ),
        // This assumes we are viewing by user.
        'columns' => array(
            'title' => array(
                'header' => array(
                    'value' => $txt['mc_warning_templates_name'],
                ),
                'data' => array(
                    'sprintf' => array(
                        'format' => '<a href="' . $scripturl . '?action=moderate;area=warnings;sa=templateedit;tid=%1$d">%2$s</a>',
                        'params' => array(
                            'id_comment' => false,
                            'title' => false,
                            'body' => false,
                        ),
                    ),
                ),
                'sort' => array(
                    'default' => 'template_title',
                    'reverse' => 'template_title DESC',
                ),
            ),
            'creator' => array(
                'header' => array(
                    'value' => $txt['mc_warning_templates_creator'],
                ),
                'data' => array(
                    'db' => 'creator',
                ),
                'sort' => array(
                    'default' => 'creator_name',
                    'reverse' => 'creator_name DESC',
                ),
            ),
            'time' => array(
                'header' => array(
                    'value' => $txt['mc_warning_templates_time'],
                ),
                'data' => array(
                    'db' => 'time',
                ),
                'sort' => array(
                    'default' => 'lc.log_time DESC',
                    'reverse' => 'lc.log_time',
                ),
            ),
            'delete' => array(
                'header' => array(
                    'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
                    'style' => 'width: 4%;',
                    'class' => 'centercol',
                ),
                'data' => array(
                    'function' => function($rowData)
                    {
                        return '<input type="checkbox" name="deltpl[]" value="' . $rowData['id_comment'] . '">';
                    },
                    'class' => 'centercol',
                ),
            ),
        ),
        'form' => array(
            'href' => $scripturl . '?action=moderate;area=warnings;sa=templates',
            'token' => 'mod-wt',
        ),
        'additional_rows' => array(
            array(
                'position' => 'bottom_of_list',
                'value' => '&nbsp;<input type="submit" name="delete" value="' . $txt['mc_warning_template_delete'] . '" data-confirm="' . $txt['mc_warning_template_delete_confirm'] . '" class="button you_sure">',
            ),
            array(
                'position' => 'bottom_of_list',
                'value' => '<input type="submit" name="add" value="' . $txt['mc_warning_template_add'] . '" class="button">',
            ),
        ),
    );

    // Create the watched user list.
    createToken('mod-wt');
    createList($listOptions);

    $context['sub_template'] = 'show_list';
    $context['default_list'] = 'warning_template_list';
}

/**
 * Callback for createList().
 *
 * @return int The total number of warning templates
 */
function list_getWarningTemplateCount()
{
    global $smcFunc, $user_info;

    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}log_comments
        WHERE comment_type = {string:warntpl}
            AND (id_recipient = {string:generic} OR id_recipient = {int:current_member})',
        array(
            'warntpl' => 'warntpl',
            'generic' => 0,
            'current_member' => $user_info['id'],
        )
    );
    list ($totalWarns) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    return $totalWarns;
}

/**
 * Callback for createList().
 *
 * @param int $start The item to start with (for pagination purposes)
 * @param int $items_per_page The number of items to show per page
 * @param string $sort A string indicating how to sort the results
 * @return array An arrray of info about the available warning templates
 */
function list_getWarningTemplates($start, $items_per_page, $sort)
{
    global $smcFunc, $scripturl, $user_info;

    $request = $smcFunc['db_query']('', '
        SELECT lc.id_comment, COALESCE(mem.id_member, 0) AS id_member,
            COALESCE(mem.real_name, lc.member_name) AS creator_name, recipient_name AS template_title,
            lc.log_time, lc.body
        FROM {db_prefix}log_comments AS lc
            LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
        WHERE lc.comment_type = {string:warntpl}
            AND (id_recipient = {string:generic} OR id_recipient = {int:current_member})
        ORDER BY ' . $sort . '
        LIMIT ' . $start . ', ' . $items_per_page,
        array(
            'warntpl' => 'warntpl',
            'generic' => 0,
            'current_member' => $user_info['id'],
        )
    );
    $templates = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        $templates[] = array(
            'id_comment' => $row['id_comment'],
            'creator' => $row['id_member'] ? ('<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['creator_name'] . '</a>') : $row['creator_name'],
            'time' => timeformat($row['log_time']),
            'title' => $row['template_title'],
            'body' => $smcFunc['htmlspecialchars']($row['body']),
        );
    }
    $smcFunc['db_free_result']($request);

    return $templates;
}

/**
 * Edit a warning template.
 */
function ModifyWarningTemplate()
{
    global $smcFunc, $context, $txt, $user_info, $sourcedir;

    $context['id_template'] = isset($_REQUEST['tid']) ? (int) $_REQUEST['tid'] : 0;
    $context['is_edit'] = $context['id_template'];

    // Standard template things.
    $context['page_title'] = $context['is_edit'] ? $txt['mc_warning_template_modify'] : $txt['mc_warning_template_add'];
    $context['sub_template'] = 'warn_template';
    $context[$context['moderation_menu_name']]['current_subsection'] = 'templates';

    // Defaults.
    $context['template_data'] = array(
        'title' => '',
        'body' => $txt['mc_warning_template_body_default'],
        'personal' => false,
        'can_edit_personal' => true,
    );

    // If it's an edit load it.
    if ($context['is_edit'])
    {
        $request = $smcFunc['db_query']('', '
            SELECT id_member, id_recipient, recipient_name AS template_title, body
            FROM {db_prefix}log_comments
            WHERE id_comment = {int:id}
                AND comment_type = {string:warntpl}
                AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
            array(
                'id' => $context['id_template'],
                'warntpl' => 'warntpl',
                'generic' => 0,
                'current_member' => $user_info['id'],
            )
        );
        while ($row = $smcFunc['db_fetch_assoc']($request))
        {
            $context['template_data'] = array(
                'title' => $row['template_title'],
                'body' => $smcFunc['htmlspecialchars']($row['body']),
                'personal' => $row['id_recipient'],
                'can_edit_personal' => $row['id_member'] == $user_info['id'],
            );
        }
        $smcFunc['db_free_result']($request);
    }

    // Wait, we are saving?
    if (isset($_POST['save']))
    {
        checkSession();
        validateToken('mod-wt');

        // To check the BBC is pretty good...
        require_once($sourcedir . '/Subs-Post.php');

        // Bit of cleaning!
        $_POST['template_body'] = trim($_POST['template_body']);
        $_POST['template_title'] = trim($_POST['template_title']);

        // Need something in both boxes.
        if (!empty($_POST['template_body']) && !empty($_POST['template_title']))
        {
            // Safety first.
            $_POST['template_title'] = $smcFunc['htmlspecialchars']($_POST['template_title']);

            // Clean up BBC.
            preparsecode($_POST['template_body']);
            // But put line breaks back!
            $_POST['template_body'] = strtr($_POST['template_body'], array('<br>' => "\n"));

            // Is this personal?
            $recipient_id = !empty($_POST['make_personal']) ? $user_info['id'] : 0;

            // If we are this far it's save time.
            if ($context['is_edit'])
            {
                // Simple update...
                $smcFunc['db_query']('', '
                    UPDATE {db_prefix}log_comments
                    SET id_recipient = {int:personal}, recipient_name = {string:title}, body = {string:body}
                    WHERE id_comment = {int:id}
                        AND comment_type = {string:warntpl}
                        AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})'.
                        ($recipient_id ? ' AND id_member = {int:current_member}' : ''),
                    array(
                        'personal' => $recipient_id,
                        'title' => $_POST['template_title'],
                        'body' => $_POST['template_body'],
                        'id' => $context['id_template'],
                        'warntpl' => 'warntpl',
                        'generic' => 0,
                        'current_member' => $user_info['id'],
                    )
                );

                // If it wasn't visible and now is they've effectively added it.
                if ($context['template_data']['personal'] && !$recipient_id)
                    logAction('add_warn_template', array('template' => $_POST['template_title']));
                // Conversely if they made it personal it's a delete.
                elseif (!$context['template_data']['personal'] && $recipient_id)
                    logAction('delete_warn_template', array('template' => $_POST['template_title']));
                // Otherwise just an edit.
                else
                    logAction('modify_warn_template', array('template' => $_POST['template_title']));
            }
            else
            {
                $smcFunc['db_insert']('',
                    '{db_prefix}log_comments',
                    array(
                        'id_member' => 'int', 'member_name' => 'string', 'comment_type' => 'string', 'id_recipient' => 'int',
                        'recipient_name' => 'string-255', 'body' => 'string-65535', 'log_time' => 'int',
                    ),
                    array(
                        $user_info['id'], $user_info['name'], 'warntpl', $recipient_id,
                        $_POST['template_title'], $_POST['template_body'], time(),
                    ),
                    array('id_comment')
                );

                logAction('add_warn_template', array('template' => $_POST['template_title']));
            }

            // Get out of town...
            redirectexit('action=moderate;area=warnings;sa=templates');
        }
        else
        {
            $context['warning_errors'] = array();
            $context['template_data']['title'] = !empty($_POST['template_title']) ? $_POST['template_title'] : '';
            $context['template_data']['body'] = !empty($_POST['template_body']) ? $_POST['template_body'] : $txt['mc_warning_template_body_default'];
            $context['template_data']['personal'] = !empty($_POST['make_personal']);

            if (empty($_POST['template_title']))
                $context['warning_errors'][] = $txt['mc_warning_template_error_no_title'];
            if (empty($_POST['template_body']))
                $context['warning_errors'][] = $txt['mc_warning_template_error_no_body'];
        }
    }

    createToken('mod-wt');
}

/**
 * Change moderation preferences.
 */
function ModerationSettings()
{
    global $context, $txt, $user_info;

    // Some useful context stuff.
    loadTemplate('ModerationCenter');
    $context['page_title'] = $txt['mc_settings'];
    $context['sub_template'] = 'moderation_settings';
    $context[$context['moderation_menu_name']]['tab_data'] = array(
        'title' => $txt['mc_prefs_title'],
        'help' => '',
        'description' => $txt['mc_prefs_desc']
    );

    $pref_binary = 5;

    // Are we saving?
    if (isset($_POST['save']))
    {
        checkSession();
        validateToken('mod-set');

        /* Current format of mod_prefs is:
            x|ABCD|yyy

            WHERE:
                x = Show report count on forum header.
                ABCD = Block indexes to show on moderation main page.
                yyy = Integer with the following bit status:
                    - yyy & 4 = Notify about posts awaiting approval.
        */

        // Now check other options!
        $pref_binary = 0;

        // Put it all together.
        $mod_prefs = '0||' . $pref_binary;
        updateMemberData($user_info['id'], array('mod_prefs' => $mod_prefs));
    }

    // What blocks does the user currently have selected?
    $context['mod_settings'] = array(
    );

    createToken('mod-set');
}

/**
 * This ends a moderator session, requiring authentication to access the MCP again.
 */
function ModEndSession()
{
    // This is so easy!
    unset($_SESSION['moderate_time']);

    // Clean any moderator tokens as well.
    foreach ($_SESSION['token'] as $key => $token)
        if (strpos($key, '-mod') !== false)
            unset($_SESSION['token'][$key]);

    redirectexit();
}

?>