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: 
<?php
if (!defined('SMF'))
    die('No direct access...');
function validateSession($type = 'admin', $force = false)
{
    global $modSettings, $sourcedir, $user_info;
    
    is_not_guest();
    
    $types = array();
    call_integration_hook('integrate_validateSession', array(&$types));
    $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
    
    $refreshTime = isset($_GET['xml']) ? 4200 : 3600;
    if (empty($force))
    {
        
        if (!empty($modSettings['securityDisable' . ($type != 'admin' ? '_' . $type : '')]))
            return;
        
        if ((!empty($_SESSION[$type . '_time']) && $_SESSION[$type . '_time'] + $refreshTime >= time()) || (!empty($_SESSION['admin_time']) && $_SESSION['admin_time'] + $refreshTime >= time()))
            return;
    }
    require_once($sourcedir . '/Subs-Auth.php');
    
    if (isset($_POST[$type . '_pass']))
    {
        
        if (!empty($modSettings['force_ssl']) && empty($maintenance) && !httpsOn())
            fatal_lang_error('login_ssl_required');
        checkSession();
        $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST[$type . '_pass'], false)), true);
        
        if ($good_password || hash_verify_password($user_info['username'], $_POST[$type . '_pass'], $user_info['passwd']))
        {
            $_SESSION[$type . '_time'] = time();
            unset($_SESSION['request_referer']);
            return;
        }
    }
    
    if (empty($_SESSION['request_referer']))
        $_SESSION['request_referer'] = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
    elseif (empty($_POST))
        unset($_SESSION['request_referer']);
    
    if (!isset($_GET['xml']))
        adminLogin($type);
    else
        return 'session_verify_fail';
}
function is_not_guest($message = '')
{
    global $user_info, $txt, $context, $scripturl, $modSettings;
    
    if (!$user_info['is_guest'])
        return;
    
    if (!empty($modSettings['who_enabled']))
        $_GET['error'] = 'guest_login';
    writeLog(true);
    
    if (isset($_REQUEST['xml']))
        obExit(false);
    
    if (SMF != 'SSI' && empty($context['theme_loaded']))
        loadTheme();
    
    if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
        $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
    
    loadLanguage('Login');
    
    if (empty($context['template_layers']))
    {
        $_SESSION['login_url'] = $scripturl . '?' . $_SERVER['QUERY_STRING'];
        redirectexit('action=login');
    }
    else
    {
        loadTemplate('Login');
        $context['sub_template'] = 'kick_guest';
        $context['robot_no_index'] = true;
    }
    
    $context['kick_message'] = $message;
    $context['page_title'] = $txt['login'];
    obExit();
    
    trigger_error('Hacking attempt...', E_USER_ERROR);
}
function is_not_banned($forceCheck = false)
{
    global $txt, $modSettings, $context, $user_info;
    global $sourcedir, $cookiename, $user_settings, $smcFunc;
    
    if ($user_info['is_admin'])
        return;
    
    if ($forceCheck || !isset($_SESSION['ban']) || empty($modSettings['banLastUpdated']) || ($_SESSION['ban']['last_checked'] < $modSettings['banLastUpdated']) || $_SESSION['ban']['id_member'] != $user_info['id'] || $_SESSION['ban']['ip'] != $user_info['ip'] || $_SESSION['ban']['ip2'] != $user_info['ip2'] || (isset($user_info['email'], $_SESSION['ban']['email']) && $_SESSION['ban']['email'] != $user_info['email']))
    {
        
        $_SESSION['ban'] = array(
            'last_checked' => time(),
            'id_member' => $user_info['id'],
            'ip' => $user_info['ip'],
            'ip2' => $user_info['ip2'],
            'email' => $user_info['email'],
        );
        $ban_query = array();
        $ban_query_vars = array('current_time' => time());
        $flag_is_activated = false;
        
        foreach (array('ip', 'ip2') as $ip_number)
        {
            if ($ip_number == 'ip2' && $user_info['ip2'] == $user_info['ip'])
                continue;
            $ban_query[] = ' {inet:' . $ip_number . '} BETWEEN bi.ip_low and bi.ip_high';
            $ban_query_vars[$ip_number] = $user_info[$ip_number];
            
            if (empty($modSettings['disableHostnameLookup']) && $user_info[$ip_number] != 'unknown')
            {
                $hostname = host_from_ip($user_info[$ip_number]);
                if (strlen($hostname) > 0)
                {
                    $ban_query[] = '({string:hostname' . $ip_number . '} LIKE bi.hostname)';
                    $ban_query_vars['hostname' . $ip_number] = $hostname;
                }
            }
        }
        
        if (strlen($user_info['email']) != 0)
        {
            $ban_query[] = '({string:email} LIKE bi.email_address)';
            $ban_query_vars['email'] = $user_info['email'];
        }
        
        if (!$user_info['is_guest'] && !empty($user_info['id']))
        {
            $ban_query[] = 'bi.id_member = {int:id_member}';
            $ban_query_vars['id_member'] = $user_info['id'];
        }
        
        if (!empty($ban_query))
        {
            $restrictions = array(
                'cannot_access',
                'cannot_login',
                'cannot_post',
                'cannot_register',
            );
            $request = $smcFunc['db_query']('', '
                SELECT bi.id_ban, bi.email_address, bi.id_member, bg.cannot_access, bg.cannot_register,
                    bg.cannot_post, bg.cannot_login, bg.reason, COALESCE(bg.expire_time, 0) AS expire_time
                FROM {db_prefix}ban_items AS bi
                    INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time}))
                WHERE
                    (' . implode(' OR ', $ban_query) . ')',
                $ban_query_vars
            );
            
            while ($row = $smcFunc['db_fetch_assoc']($request))
            {
                foreach ($restrictions as $restriction)
                    if (!empty($row[$restriction]))
                    {
                        $_SESSION['ban'][$restriction]['reason'] = $row['reason'];
                        $_SESSION['ban'][$restriction]['ids'][] = $row['id_ban'];
                        if (!isset($_SESSION['ban']['expire_time']) || ($_SESSION['ban']['expire_time'] != 0 && ($row['expire_time'] == 0 || $row['expire_time'] > $_SESSION['ban']['expire_time'])))
                            $_SESSION['ban']['expire_time'] = $row['expire_time'];
                        if (!$user_info['is_guest'] && $restriction == 'cannot_access' && ($row['id_member'] == $user_info['id'] || $row['email_address'] == $user_info['email']))
                            $flag_is_activated = true;
                    }
            }
            $smcFunc['db_free_result']($request);
        }
        
        if (isset($_SESSION['ban']['cannot_access']) || isset($_SESSION['ban']['cannot_post']) || isset($_SESSION['ban']['cannot_login']))
            log_ban(array_merge(isset($_SESSION['ban']['cannot_access']) ? $_SESSION['ban']['cannot_access']['ids'] : array(), isset($_SESSION['ban']['cannot_post']) ? $_SESSION['ban']['cannot_post']['ids'] : array(), isset($_SESSION['ban']['cannot_login']) ? $_SESSION['ban']['cannot_login']['ids'] : array()));
        
        if ($user_info['id'] && (($user_settings['is_activated'] >= 10 && !$flag_is_activated)
            || ($user_settings['is_activated'] < 10 && $flag_is_activated)))
        {
            require_once($sourcedir . '/ManageBans.php');
            updateBanMembers();
        }
    }
    
    if (!isset($_SESSION['ban']['cannot_access']) && !empty($_COOKIE[$cookiename . '_']))
    {
        $bans = explode(',', $_COOKIE[$cookiename . '_']);
        foreach ($bans as $key => $value)
            $bans[$key] = (int) $value;
        $request = $smcFunc['db_query']('', '
            SELECT bi.id_ban, bg.reason, COALESCE(bg.expire_time, 0) AS expire_time
            FROM {db_prefix}ban_items AS bi
                INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
            WHERE bi.id_ban IN ({array_int:ban_list})
                AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})
                AND bg.cannot_access = {int:cannot_access}
            LIMIT {int:limit}',
            array(
                'cannot_access' => 1,
                'ban_list' => $bans,
                'current_time' => time(),
                'limit' => count($bans),
            )
        );
        while ($row = $smcFunc['db_fetch_assoc']($request))
        {
            $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
            $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
            $_SESSION['ban']['expire_time'] = $row['expire_time'];
        }
        $smcFunc['db_free_result']($request);
        
        if (!isset($_SESSION['ban']['cannot_access']))
        {
            require_once($sourcedir . '/Subs-Auth.php');
            $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
            smf_setcookie($cookiename . '_', '', time() - 3600, $cookie_url[1], $cookie_url[0], false, false);
        }
    }
    
    if (isset($_SESSION['ban']['cannot_access']))
    {
        
        if (!$user_info['is_guest'])
            $smcFunc['db_query']('', '
                DELETE FROM {db_prefix}log_online
                WHERE id_member = {int:current_member}',
                array(
                    'current_member' => $user_info['id'],
                )
            );
        
        $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
        $user_info['name'] = '';
        $user_info['username'] = '';
        $user_info['is_guest'] = true;
        $user_info['is_admin'] = false;
        $user_info['permissions'] = array();
        $user_info['id'] = 0;
        $context['user'] = array(
            'id' => 0,
            'username' => '',
            'name' => $txt['guest_title'],
            'is_guest' => true,
            'is_logged' => false,
            'is_admin' => false,
            'is_mod' => false,
            'can_mod' => false,
            'language' => $user_info['language'],
        );
        
        require_once($sourcedir . '/Subs-Auth.php');
        require_once($sourcedir . '/LogInOut.php');
        $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
        smf_setcookie($cookiename . '_', implode(',', $_SESSION['ban']['cannot_access']['ids']), time() + 3153600, $cookie_url[1], $cookie_url[0], false, false);
        
        $_GET['action'] = '';
        $_GET['board'] = '';
        $_GET['topic'] = '';
        writeLog(true);
        Logout(true, false);
        
        fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_access']['reason']) ? '' : '<br>' . $_SESSION['ban']['cannot_access']['reason']) . '<br>' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']), false);
        
        trigger_error('Hacking attempt...', E_USER_ERROR);
    }
    
    elseif (isset($_SESSION['ban']['cannot_login']) && !$user_info['is_guest'])
    {
        
        $smcFunc['db_query']('', '
            DELETE FROM {db_prefix}log_online
            WHERE id_member = {int:current_member}',
            array(
                'current_member' => $user_info['id'],
            )
        );
        
        $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
        $user_info['name'] = '';
        $user_info['username'] = '';
        $user_info['is_guest'] = true;
        $user_info['is_admin'] = false;
        $user_info['permissions'] = array();
        $user_info['id'] = 0;
        $context['user'] = array(
            'id' => 0,
            'username' => '',
            'name' => $txt['guest_title'],
            'is_guest' => true,
            'is_logged' => false,
            'is_admin' => false,
            'is_mod' => false,
            'can_mod' => false,
            'language' => $user_info['language'],
        );
        
        $_GET['action'] = '';
        $_GET['board'] = '';
        $_GET['topic'] = '';
        writeLog(true);
        require_once($sourcedir . '/LogInOut.php');
        Logout(true, false);
        fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_login']['reason']) ? '' : '<br>' . $_SESSION['ban']['cannot_login']['reason']) . '<br>' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']) . '<br>' . $txt['ban_continue_browse'], false);
    }
    
    if (isset($user_info['permissions']))
        banPermissions();
}
function banPermissions()
{
    global $user_info, $sourcedir, $modSettings, $context;
    
    if (isset($_SESSION['ban']['cannot_access']))
        $user_info['permissions'] = array();
    
    elseif (isset($_SESSION['ban']['cannot_post']) || (!empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $user_info['warning']))
    {
        $denied_permissions = array(
            'pm_send',
            'calendar_post', 'calendar_edit_own', 'calendar_edit_any',
            'poll_post',
            'poll_add_own', 'poll_add_any',
            'poll_edit_own', 'poll_edit_any',
            'poll_lock_own', 'poll_lock_any',
            'poll_remove_own', 'poll_remove_any',
            'manage_attachments', 'manage_smileys', 'manage_boards', 'admin_forum', 'manage_permissions',
            'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news',
            'profile_identity_any', 'profile_extra_any', 'profile_title_any',
            'profile_forum_any', 'profile_other_any', 'profile_signature_any',
            'post_new', 'post_reply_own', 'post_reply_any',
            'delete_own', 'delete_any', 'delete_replies',
            'make_sticky',
            'merge_any', 'split_any',
            'modify_own', 'modify_any', 'modify_replies',
            'move_any',
            'lock_own', 'lock_any',
            'remove_own', 'remove_any',
            'post_unapproved_topics', 'post_unapproved_replies_own', 'post_unapproved_replies_any',
        );
        call_integration_hook('integrate_post_ban_permissions', array(&$denied_permissions));
        $user_info['permissions'] = array_diff($user_info['permissions'], $denied_permissions);
    }
    
    elseif (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $user_info['warning'])
    {
        
        $permission_change = array(
            'post_new' => 'post_unapproved_topics',
            'post_reply_own' => 'post_unapproved_replies_own',
            'post_reply_any' => 'post_unapproved_replies_any',
            'post_attachment' => 'post_unapproved_attachments',
        );
        call_integration_hook('integrate_warn_permissions', array(&$permission_change));
        foreach ($permission_change as $old => $new)
        {
            if (!in_array($old, $user_info['permissions']))
                unset($permission_change[$old]);
            else
                $user_info['permissions'][] = $new;
        }
        $user_info['permissions'] = array_diff($user_info['permissions'], array_keys($permission_change));
    }
    
    
    if (isset($_SESSION['mc']) && $_SESSION['mc']['time'] > $modSettings['settings_updated'] && $_SESSION['mc']['id'] == $user_info['id'])
        $user_info['mod_cache'] = $_SESSION['mc'];
    else
    {
        require_once($sourcedir . '/Subs-Auth.php');
        rebuildModCache();
    }
    
    if (isset($_SESSION['rc']['reports']) && isset($_SESSION['rc']['member_reports']) && $_SESSION['rc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rc']['id'] == $user_info['id'])
    {
        $context['open_mod_reports'] = $_SESSION['rc']['reports'];
        $context['open_member_reports'] = $_SESSION['rc']['member_reports'];
    }
    elseif ($_SESSION['mc']['bq'] != '0=1')
    {
        require_once($sourcedir . '/Subs-ReportedContent.php');
        $context['open_mod_reports'] = recountOpenReports('posts');
        $context['open_member_reports'] = recountOpenReports('members');
    }
    else
    {
        $context['open_mod_reports'] = 0;
        $context['open_member_reports'] = 0;
    }
}
function log_ban($ban_ids = array(), $email = null)
{
    global $user_info, $smcFunc;
    
    if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
        return;
    $smcFunc['db_insert']('',
        '{db_prefix}log_banned',
        array('id_member' => 'int', 'ip' => 'inet', 'email' => 'string', 'log_time' => 'int'),
        array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
        array('id_ban_log')
    );
    
    if (!empty($ban_ids))
        $smcFunc['db_query']('', '
            UPDATE {db_prefix}ban_items
            SET hits = hits + 1
            WHERE id_ban IN ({array_int:ban_ids})',
            array(
                'ban_ids' => $ban_ids,
            )
        );
}
function isBannedEmail($email, $restriction, $error)
{
    global $txt, $smcFunc;
    
    if (empty($email) || trim($email) == '')
        return;
    
    $ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
    $ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';
    
    $request = $smcFunc['db_query']('', '
        SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
        FROM {db_prefix}ban_items AS bi
            INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
        WHERE {string:email} LIKE bi.email_address
            AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
            AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
        array(
            'email' => $email,
            'cannot_access' => 1,
            'now' => time(),
        )
    );
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        if (!empty($row['cannot_access']))
        {
            $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
            $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
        }
        if (!empty($row[$restriction]))
        {
            $ban_ids[] = $row['id_ban'];
            $ban_reason = $row['reason'];
        }
    }
    $smcFunc['db_free_result']($request);
    
    if (isset($_SESSION['ban']['cannot_access']))
    {
        log_ban($_SESSION['ban']['cannot_access']['ids']);
        $_SESSION['ban']['last_checked'] = time();
        fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
    }
    if (!empty($ban_ids))
    {
        
        log_ban($ban_ids, $email);
        fatal_error($error . $ban_reason, false);
    }
}
function checkSession($type = 'post', $from_action = '', $is_fatal = true)
{
    global $sc, $modSettings, $boardurl;
    
    if ($type == 'post')
    {
        $check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
        if ($check !== $sc)
            $error = 'session_timeout';
    }
    
    elseif ($type == 'get')
    {
        $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
        if ($check !== $sc)
            $error = 'session_verify_fail';
    }
    
    elseif ($type == 'request')
    {
        $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : (isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null)));
        if ($check !== $sc)
            $error = 'session_verify_fail';
    }
    
    if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
        $error = 'session_verify_fail';
    
    if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
    {
        ob_end_clean();
        send_http_status(403);
        die;
    }
    
    if (isset($_SESSION['request_referer']))
        $referrer = $_SESSION['request_referer'];
    else
        $referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
    if (!empty($referrer['host']))
    {
        if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
            $real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
        else
            $real_host = $_SERVER['HTTP_HOST'];
        $parsed_url = parse_url($boardurl);
        
        if (!empty($modSettings['globalCookies']))
        {
            if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
                $parsed_url['host'] = $parts[1];
            if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
                $referrer['host'] = $parts[1];
            if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
                $real_host = $parts[1];
        }
        
        if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
        {
            $error = 'verify_url_fail';
            $log_error = true;
        }
    }
    
    if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
    {
        $error = 'verify_url_fail';
        $log_error = true;
    }
    if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
        fatal_error('Sound the alarm!  It\'s a hacker!  Close the castle gates!!', false);
    
    if (!isset($error))
        return '';
    
    elseif ($is_fatal)
    {
        if (isset($_GET['xml']))
        {
            ob_end_clean();
            send_http_status(403, 'Forbidden - Session timeout');
            die;
        }
        else
            fatal_lang_error($error, isset($log_error) ? 'user' : false);
    }
    
    else
        return $error;
    
    trigger_error('Hacking attempt...', E_USER_ERROR);
}
function checkConfirm($action)
{
    global $modSettings, $smcFunc;
    if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
        return true;
    else
    {
        $token = md5($smcFunc['random_int']() . session_id() . (string) microtime() . $modSettings['rand_seed']);
        $_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);
        return $token;
    }
}
function createToken($action, $type = 'post')
{
    global $modSettings, $context, $smcFunc;
    $token = md5($smcFunc['random_int']() . session_id() . (string) microtime() . $modSettings['rand_seed'] . $type);
    $token_var = substr(preg_replace('~^\d+~', '', md5($smcFunc['random_int']() . (string) microtime() . $smcFunc['random_int']())), 0, $smcFunc['random_int'](7, 12));
    $_SESSION['token'][$type . '-' . $action] = array($token_var, md5($token . $_SERVER['HTTP_USER_AGENT']), time(), $token);
    $context[$action . '_token'] = $token;
    $context[$action . '_token_var'] = $token_var;
    return array($action . '_token_var' => $token_var, $action . '_token' => $token);
}
function validateToken($action, $type = 'post', $reset = true)
{
    $type = $type == 'get' || $type == 'request' ? $type : 'post';
    
    if ($action == 'login')
    {
        if (isset($_SESSION['token'][$type . '-' . $action]))
        {
            $return = $_SESSION['token'][$type . '-' . $action][3];
            unset($_SESSION['token'][$type . '-' . $action]);
            return $return;
        }
        else
            return '';
    }
    
    
    if (isset($_SESSION['token'][$type . '-' . $action], $GLOBALS['_' . strtoupper($type)][$_SESSION['token'][$type . '-' . $action][0]]) && md5($GLOBALS['_' . strtoupper($type)][$_SESSION['token'][$type . '-' . $action][0]] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['token'][$type . '-' . $action][1])
    {
        
        unset($_SESSION['token'][$type . '-' . $action]);
        return true;
    }
    
    if ($reset)
    {
        
        cleanTokens();
        
        createToken($action, $type);
        fatal_lang_error('token_verify_fail', false);
    }
    
    else
        unset($_SESSION['token'][$type . '-' . $action]);
    
    if (mt_rand(0, 138) == 23)
        cleanTokens();
    return false;
}
function cleanTokens($complete = false)
{
    
    if (!isset($_SESSION['token']))
        return;
    
    foreach ($_SESSION['token'] as $key => $data)
        if ($data[2] + 10800 < time() || $complete)
            unset($_SESSION['token'][$key]);
}
function checkSubmitOnce($action, $is_fatal = true)
{
    global $context;
    if (!isset($_SESSION['forms']))
        $_SESSION['forms'] = array();
    
    if ($action == 'register')
    {
        $context['form_sequence_number'] = 0;
        while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
            $context['form_sequence_number'] = mt_rand(1, 16000000);
    }
    
    elseif ($action == 'check')
    {
        if (!isset($_REQUEST['seqnum']))
            return true;
        elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
        {
            $_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
            return true;
        }
        elseif ($is_fatal)
            fatal_lang_error('error_form_already_submitted', false);
        else
            return false;
    }
    
    elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
        $_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
    elseif ($action != 'free')
        trigger_error('checkSubmitOnce(): Invalid action \'' . $action . '\'', E_USER_WARNING);
}
function allowedTo($permission, $boards = null, $any = false)
{
    global $user_info, $smcFunc;
    static $perm_cache = array();
    
    if (empty($permission))
        return true;
    
    if (empty($user_info) || !isset($user_info['permissions']))
        return false;
    
    if ($user_info['is_admin'])
        return true;
    
    $permission = (array) $permission;
    
    if ($boards === null)
    {
        if (count(array_intersect($permission, $user_info['permissions'])) != 0)
            return true;
        
        else
            return false;
    }
    elseif (!is_array($boards))
        $boards = array($boards);
    $cache_key = hash('md5', $user_info['id'] . '-' . implode(',', $permission) . '-' . implode(',', $boards) . '-' . $any);
    if (isset($perm_cache[$cache_key]))
        return $perm_cache[$cache_key];
    $request = $smcFunc['db_query']('', '
        SELECT MIN(bp.add_deny) AS add_deny
        FROM {db_prefix}boards AS b
            INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
            LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
            LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:group_list}))
        WHERE b.id_board IN ({array_int:board_list})
            AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
            AND bp.permission IN ({array_string:permission_list})
            AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})
        GROUP BY b.id_board',
        array(
            'current_member' => $user_info['id'],
            'board_list' => $boards,
            'group_list' => $user_info['groups'],
            'moderator_group' => 3,
            'permission_list' => $permission,
        )
    );
    if ($any)
    {
        $result = false;
        while ($row = $smcFunc['db_fetch_assoc']($request))
        {
            $result = !empty($row['add_deny']);
            if ($result == true)
                break;
        }
        $smcFunc['db_free_result']($request);
        $return = $result;
    }
    
    elseif ($smcFunc['db_num_rows']($request) != count($boards))
        $return = false;
    else
    {
        $result = true;
        while ($row = $smcFunc['db_fetch_assoc']($request))
            $result &= !empty($row['add_deny']);
        $smcFunc['db_free_result']($request);
        $return = $result;
    }
    $perm_cache[$cache_key] = $return;
    
    return $return;
}
function isAllowedTo($permission, $boards = null, $any = false)
{
    global $user_info, $txt;
    $heavy_permissions = array(
        'admin_forum',
        'manage_attachments',
        'manage_smileys',
        'manage_boards',
        'edit_news',
        'moderate_forum',
        'manage_bans',
        'manage_membergroups',
        'manage_permissions',
    );
    
    $permission = (array) $permission;
    call_integration_hook('integrate_heavy_permissions_session', array(&$heavy_permissions));
    
    if (!allowedTo($permission, $boards, $any))
    {
        
        $error_permission = array_shift($permission);
        
        if ($user_info['is_guest'])
        {
            loadLanguage('Errors');
            is_not_guest($txt['cannot_' . $error_permission]);
        }
        
        $_GET['action'] = '';
        $_GET['board'] = '';
        $_GET['topic'] = '';
        writeLog(true);
        fatal_lang_error('cannot_' . $error_permission, false);
        
        trigger_error('Hacking attempt...', E_USER_ERROR);
    }
    
    
    if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
        validateSession();
}
function boardsAllowedTo($permissions, $check_access = true, $simple = true)
{
    global $user_info, $smcFunc;
    
    $permissions = (array) $permissions;
    
    
    if ($user_info['is_admin'])
    {
        if ($simple)
            return array(0);
        else
        {
            $boards = array();
            foreach ($permissions as $permission)
                $boards[$permission] = array(0);
            return $boards;
        }
    }
    
    $groups = array_diff($user_info['groups'], array(3));
    $request = $smcFunc['db_query']('', '
        SELECT b.id_board, bp.add_deny' . ($simple ? '' : ', bp.permission') . '
        FROM {db_prefix}board_permissions AS bp
            INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
            LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
            LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:group_list}))
        WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
            AND bp.permission IN ({array_string:permissions})
            AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})' .
            ($check_access ? ' AND {query_see_board}' : ''),
        array(
            'current_member' => $user_info['id'],
            'group_list' => $groups,
            'moderator_group' => 3,
            'permissions' => $permissions,
        )
    );
    $boards = array();
    $deny_boards = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
    {
        if ($simple)
        {
            if (empty($row['add_deny']))
                $deny_boards[] = $row['id_board'];
            else
                $boards[] = $row['id_board'];
        }
        else
        {
            if (empty($row['add_deny']))
                $deny_boards[$row['permission']][] = $row['id_board'];
            else
                $boards[$row['permission']][] = $row['id_board'];
        }
    }
    $smcFunc['db_free_result']($request);
    if ($simple)
        $boards = array_unique(array_values(array_diff($boards, $deny_boards)));
    else
    {
        foreach ($permissions as $permission)
        {
            
            if (empty($boards[$permission]))
                $boards[$permission] = array();
            else
            {
                
                $deny_boards[$permission] = isset($deny_boards[$permission]) ? $deny_boards[$permission] : array();
                $boards[$permission] = array_unique(array_values(array_diff($boards[$permission], $deny_boards[$permission])));
            }
        }
    }
    return $boards;
}
function spamProtection($error_type, $only_return_result = false)
{
    global $modSettings, $user_info, $smcFunc;
    
    $timeOverrides = array(
        'login' => 2,
        'register' => 2,
        'remind' => 30,
        'sendmail' => $modSettings['spamWaitTime'] * 5,
        'reporttm' => $modSettings['spamWaitTime'] * 4,
        'search' => !empty($modSettings['search_floodcontrol_time']) ? $modSettings['search_floodcontrol_time'] : 1,
    );
    call_integration_hook('integrate_spam_protection', array(&$timeOverrides));
    
    if (!allowedTo('moderate_board'))
        $timeLimit = isset($timeOverrides[$error_type]) ? $timeOverrides[$error_type] : $modSettings['spamWaitTime'];
    else
        $timeLimit = 2;
    
    $smcFunc['db_query']('', '
        DELETE FROM {db_prefix}log_floodcontrol
        WHERE log_time < {int:log_time}
            AND log_type = {string:log_type}',
        array(
            'log_time' => time() - $timeLimit,
            'log_type' => $error_type,
        )
    );
    
    $smcFunc['db_insert']('replace',
        '{db_prefix}log_floodcontrol',
        array('ip' => 'inet', 'log_time' => 'int', 'log_type' => 'string'),
        array($user_info['ip'], time(), $error_type),
        array('ip', 'log_type')
    );
    
    if ($smcFunc['db_affected_rows']() != 1)
    {
        
        if (!$only_return_result)
            fatal_lang_error($error_type . '_WaitTime_broken', false, array($timeLimit));
        return true;
    }
    
    return false;
}
function secureDirectory($paths, $attachments = false)
{
    $errors = array();
    
    $paths = (array) $paths;
    if (empty($path))
        $errors[] = 'empty_path';
    if (!empty($errors))
        return $errors;
    foreach ($paths as $path)
    {
        if (!is_writable($path))
        {
            $errors[] = 'path_not_writable';
            continue;
        }
        $directory_name = basename($path);
        $close = empty($attachments) ? '
</Files>' : '
    Allow from localhost
</Files>
RemoveHandler .php .php3 .phtml .cgi .fcgi .pl .fpl .shtml';
        if (file_exists($path . '/.htaccess'))
        {
            $errors[] = 'htaccess_exists';
            continue;
        }
        else
        {
            $fh = @fopen($path . '/.htaccess', 'w');
            if ($fh)
            {
                fwrite($fh, '<Files *>
    Order Deny,Allow
    Deny from all' . $close);
                fclose($fh);
            }
            else
                $errors[] = 'htaccess_cannot_create_file';
        }
        if (file_exists($path . '/index.php'))
        {
            $errors[] = 'index-php_exists';
            continue;
        }
        else
        {
            $fh = @fopen($path . '/index.php', 'w');
            if ($fh)
            {
                fwrite($fh, '<' . '?php
/**
 * This file is here solely to protect your ' . $directory_name . ' directory.
 */
// Look for Settings.php....
if (file_exists(dirname(dirname(__FILE__)) . \'/Settings.php\'))
{
    // Found it!
    require(dirname(dirname(__FILE__)) . \'/Settings.php\');
    header(\'location: \' . $boardurl);
}
// Can\'t find it... just forget it.
else
    exit;
?' . '>');
                fclose($fh);
            }
            else
                $errors[] = 'index-php_cannot_create_file';
        }
    }
    if (!empty($errors))
        return $errors;
    else
        return true;
}
function frameOptionsHeader($override = null)
{
    global $modSettings;
    $option = 'SAMEORIGIN';
    if (is_null($override) && !empty($modSettings['frame_security']))
        $option = $modSettings['frame_security'];
    elseif (in_array($override, array('SAMEORIGIN', 'DENY')))
        $option = $override;
    
    if ($option == 'DISABLE')
        return;
    
    header('x-frame-options: ' . $option);
    
    header('x-xss-protection: 1');
    header('x-content-type-options: nosniff');
}
?>