PageRenderTime 28ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Web Files/ASP/includes/admin.process.php

https://code.google.com/p/bf2stats/
PHP | 1397 lines | 1233 code | 99 blank | 65 comment | 141 complexity | 283fc23a9ac642c668a12067a2c7fe06 MD5 | raw file
  1. <?php
  2. // MY EDIT LINE: 800 - 812
  3. // No Direct Access
  4. defined( '_BF2_ADMIN' ) or die( 'Restricted access' );
  5. // Build Data Table Array
  6. $DataTables = array('army','awards','kills','kits','mapinfo','maps','player','player_history','round_history','servers','unlocks','vehicles','weapons','data','stats');
  7. // Do Tasks
  8. $task = $_POST['task'] ? $_POST['task'] : '';
  9. switch ($task) {
  10. case "saveconfig":
  11. showHeader('Save Configuration');
  12. saveConfig();
  13. break;
  14. case "testconfig":
  15. showHeader('Test Configuration');
  16. testConfig();
  17. break;
  18. case "clanmanager":
  19. showHeader('Clan Manager');
  20. //processClanManager();
  21. break;
  22. case "changerank":
  23. showHeader('Edit Players');
  24. processChangeRank();
  25. break;
  26. case "banplayers":
  27. showHeader('Ban Players');
  28. processBanPlayers();
  29. break;
  30. case "unbanplayers":
  31. showHeader('Un-Ban Players');
  32. processUnBanPlayers();
  33. break;
  34. case "resetunlocks":
  35. showHeader('Reset Unlocks');
  36. processResetUnlocks();
  37. break;
  38. case "mergeplayers":
  39. showHeader('Merge Players');
  40. processMergePlayers();
  41. break;
  42. case "deleteplayers":
  43. showHeader('Delete Players');
  44. processDeletePlayers();
  45. break;
  46. case "installdb":
  47. showHeader('Install Database');
  48. processInstallDB();
  49. break;
  50. case "upgradedb":
  51. showHeader('Upgrade Database');
  52. processUpgradeDB();
  53. break;
  54. case "cleardb":
  55. showHeader('Clear Database');
  56. processClearDB();
  57. break;
  58. case "backupdb":
  59. showHeader('Backup Database');
  60. processBackupDB();
  61. break;
  62. case "restoredb":
  63. showHeader('Restore Database');
  64. processClearDB();
  65. processRestoreDB();
  66. break;
  67. case "validateranks":
  68. showHeader('Validate Ranks');
  69. processValidateRanks();
  70. break;
  71. case "checkawards":
  72. showHeader('Check Backend Awards');
  73. processCheckAwards();
  74. break;
  75. case "importlogs":
  76. showHeader('Import SNAPSHOT Logs');
  77. processImportLogs();;
  78. break;
  79. default:
  80. showLoginForm();
  81. break;
  82. }
  83. // Tidy up HTML
  84. echo "</pre></div>";
  85. function showHeader($str) {
  86. echo "<div class=\"content-head\"><div class=\"desc-title\">Processing: {$str}</div></div><div class=\"readme\"><pre>";
  87. }
  88. // Display Log Message to Browser
  89. function showLog($msg) {
  90. global $cfg;
  91. $outmsg = date('Y-m-d H:i:s')." : ".$msg."\n";
  92. echo $outmsg;
  93. if ($cfg->get('admin_log') != '') {
  94. $file = @fopen($cfg->get('admin_log'), 'a');
  95. @fwrite($file, $outmsg);
  96. @fclose($file);
  97. }
  98. flush();
  99. if (ini_get('zlib.output_compression') != 0) { ob_flush(); }
  100. }
  101. function saveConfig() {
  102. $cfg = new Config();
  103. // Store New/Changed config items
  104. showLog("Saving Config...");
  105. foreach ($_POST as $item => $val) {
  106. $key = explode('__', $item);
  107. if ($key[0] == 'cfg') {
  108. showLog(" -> Found Key: '{$key[1]}' => '".((is_array($cfg->get($key[1])))?str_replace("\r\n", ",",$val):$val)."' (Old: ".((is_array($cfg->get($key[1])))?implode(',',$cfg->get($key[1])):$cfg->get($key[1])).")...");
  109. $cfg->set($key[1],$val);
  110. }
  111. }
  112. $cfg->Save();
  113. }
  114. function testConfig() {
  115. include('class.validator.php');
  116. DEFINE('__PASS','<b><font color="green">Pass</font></b>');
  117. DEFINE('__WARN','<b><font color="orange">Warn</font></b>');
  118. DEFINE('__FAIL','<b><font color="red">Fail</font></b>');
  119. // Define Test Snapshot String (PID: 111)
  120. $tst_prefix = 'TST'.uniqid(rand());
  121. $tst_snapshot = $tst_prefix.'\test_map\queryport\29900\mapstart\1157264950.7\mapend\1157266995.57\win\1\gm\0\m\999\v\bf2\pc\1\rwa\2\ra1\0\rs1\25\ra2\2\rs2\0\pID_0\999\name_0\Test Player\t_0\2\a_0\0\ctime_0\1559\c_0\1\ip_0\0\rs_0\24\cs_0\0\ss_0\18\ts_0\6\kills_0\9\deaths_0\17\cpc_0\0\cpn_0\1\cpa_0\0\cpna_0\0\cpd_0\0\ka_0\0\he_0\0\rev_0\0\rsp_0\0\rep_0\0\tre_0\0\drs_0\0\dra_0\4\pa_0\0\tmkl_0\0\tmdg_0\0\tmvd_0\0\su_0\0\ks_0\6\ds_0\6\rank_0\3\ban_0\0\kck_0\0\tco_0\0\tsl_0\1559\tsm_0\0\tlw_0\0\ta0_0\1559\ta1_0\0\ta2_0\0\ta3_0\0\ta4_0\0\ta5_0\0\ta6_0\0\ta7_0\0\ta8_0\0\ta9_0\0\mvns_0\29000037\mvks_0\1\mvns_0\29000113\mvks_0\1\mvns_0\29000069\mvks_0\1\mvns_0\29000081\mvks_0\2\mvns_0\29000108\mvks_0\1\mvns_0\29000080\mvks_0\1\mvns_0\29000089\mvks_0\1\mvns_0\29000041\mvks_0\1\tv0_0\278\tv1_0\0\tv2_0\0\tv3_0\532\tv4_0\227\tv5_0\0\tv6_0\0\tvp_0\17\kv0_0\5\kv1_0\0\kv2_0\0\kv3_0\0\kv4_0\0\kv5_0\0\kv6_0\0\bv0_0\3\bv1_0\0\bv2_0\0\bv3_0\0\bv4_0\0\bv5_0\0\bv6_0\0\kvr0_0\1\kvr1_0\0\kvr2_0\0\kvr3_0\0\kvr4_0\0\kvr5_0\0\kvr6_0\0\tk0_0\736\tk1_0\20\tk2_0\311\tk3_0\0\tk4_0\320\tk5_0\84\tk6_0\29\kk0_0\8\kk1_0\0\kk2_0\0\kk3_0\0\kk4_0\1\kk5_0\0\kk6_0\0\dk0_0\10\dk1_0\1\dk2_0\2\dk3_0\0\dk4_0\2\dk5_0\1\dk6_0\1\tw0_0\11\tw1_0\0\tw2_0\49\tw3_0\28\tw4_0\10\tw5_0\5\tw6_0\54\tw7_0\382\tw8_0\47\te0_0\2\te1_0\0\te3_0\48\te2_0\0\te4_0\0\te5_0\0\te6_0\0\te7_0\0\te8_0\0\kw0_0\0\kw1_0\0\kw2_0\0\kw3_0\0\kw4_0\0\kw5_0\1\kw6_0\0\kw7_0\1\kw8_0\0\ke0_0\1\ke1_0\0\ke3_0\0\ke2_0\0\ke4_0\0\ke5_0\0\bw0_0\1\bw1_0\0\bw2_0\2\bw3_0\1\bw4_0\0\bw5_0\0\bw6_0\3\bw7_0\5\bw8_0\1\be0_0\0\be1_0\0\be3_0\1\be2_0\0\be4_0\0\be5_0\0\be8_0\0\be9_0\0\de6_0\0\de7_0\0\de8_0\0\sw0_0\0\sw1_0\0\sw2_0\26\sw3_0\0\sw4_0\0\sw5_0\15\sw6_0\4\sw7_0\53\sw8_0\0\se0_0\2\se1_0\0\se2_0\0\se3_0\6\se4_0\0\se5_0\0\hw0_0\0\hw1_0\0\hw2_0\3\hw3_0\0\hw4_0\0\hw5_0\5\hw6_0\1\hw7_0\8\hw8_0\0\he0_0\1\he1_0\0\he2_0\0\he3_0\3\he4_0\0\he5_0\0\EOF\1';
  122. $tst_pid = 999;
  123. $tst_mapid = 999;
  124. $cfg = new Config();
  125. $chk = new Validator();
  126. showLog("Testing Config...");
  127. // Check Config File Write Access
  128. showLog(" > Checking Config File...");
  129. if (!$chk->is_sane('_config.php')) {
  130. showLog("\t - Config File Writable: ".__FAIL);
  131. } else {
  132. showLog("\t - Config File Writable: ".__PASS);
  133. }
  134. // Check Log File Write Access
  135. showLog(" > Checking Log Files...");
  136. if (!$chk->is_sane($cfg->get('debug_log'))) {
  137. showLog("\t - Error Log File Writable: ".__WARN);
  138. } else {
  139. showLog("\t - Error Log File Writable: ".__PASS);
  140. }
  141. if (!$chk->is_sane($cfg->get('admin_log'))) {
  142. showLog("\t - Admin Log File Writable: ".__WARN);
  143. } else {
  144. showLog("\t - Admin Log File Writable: ".__PASS);
  145. }
  146. // DB Host Access
  147. showLog(" > Checking Database Host...");
  148. if ($chk->is_ipaddress($cfg->get('db_host'))) {
  149. showLog("\t - Database host (".$cfg->get('db_host').") IP Address valid: ".__PASS);
  150. } elseif ($chk->is_hostname($cfg->get('db_host'))) {
  151. showLog("\t - Database host (".$cfg->get('db_host').") appears valid: ".__PASS);
  152. if(PHP_OS == 'WINNT'){
  153. showLog("\t - Database host (".$cfg->get('db_host').") resolves: ".__WARN);
  154. } elseif(!checkdnsrr($cfg->get('db_host'),"ANY")) {
  155. showLog("\t - Database host (".$cfg->get('db_host').") resolves: ".__PASS);
  156. } else {
  157. showLog("\t - Database host (".$cfg->get('db_host').") resolves: ".__FAIL);
  158. }
  159. } else {
  160. if ($cfg->get('db_host') == 'localhost') {
  161. showLog("\t - Database host (".$cfg->get('db_host').") valid: ".__PASS);
  162. } elseif(PHP_OS == 'WINNT'){
  163. showLog("\t - Database host (".$cfg->get('db_host').") resolves: ".__WARN);
  164. } elseif(!checkdnsrr($cfg->get('db_host'),"ANY")) {
  165. showLog("\t - Database host (".$cfg->get('db_host').") valid: ".__PASS);
  166. } else {
  167. showLog("\t - Database host (".$cfg->get('db_host').") valid: ".__FAIL);
  168. }
  169. }
  170. // DB MySQL Access
  171. showLog(" > Checking Database Config...");
  172. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  173. if (!$connection) {
  174. showLog("\t - Database host (".$cfg->get('db_host').") access: ".__FAIL);
  175. } else {
  176. showLog("\t - Database host (".$cfg->get('db_host').") access: ".__PASS);
  177. // DB Access
  178. $db_selected = @mysql_select_db($cfg->get('db_name'), $connection);
  179. if (!$db_selected) {
  180. showLog("\t - Database (".$cfg->get('db_name').") access: ".__FAIL);
  181. } else {
  182. showLog("\t - Database (".$cfg->get('db_name').") access: ".__PASS);
  183. // DB Version
  184. if (getDbVer() != $cfg->get('db_expected_ver')) {
  185. showLog("\t - Database version (".$cfg->get('db_expected_ver')."): ".__FAIL);
  186. } else {
  187. showLog("\t - Database version (".$cfg->get('db_expected_ver')."): ".__PASS);
  188. }
  189. }
  190. }
  191. // Check SNAPSHOT Storage Write Access
  192. showLog(" > Checking SNAPSHOT Storage Path...");
  193. if (!$chk->is_sane_dir($cfg->get('stats_logs'))) {
  194. showLog("\t - SNAPSHOT Path Writable: ".__FAIL);
  195. } else {
  196. showLog("\t - SNAPSHOT Path Writable: ".__PASS);
  197. }
  198. // Check SNAPSHOT Archive Write Access
  199. showLog(" > Checking SNAPSHOT Archive Storage Path...");
  200. if (!$chk->is_sane_dir($cfg->get('stats_logs_store'))) {
  201. showLog("\t - SNAPSHOT Archive Path Writable: ".__FAIL);
  202. } else {
  203. showLog("\t - SNAPSHOT Archive Path Writable: ".__PASS);
  204. }
  205. // Check Admin Backup Write Access
  206. showLog(" > Checking Backup Storage Path...");
  207. if (!$chk->is_sane_dir($cfg->get('admin_backup_path'))) {
  208. showLog("\t - Backup Path Writable: ".__FAIL);
  209. } else {
  210. showLog("\t - Backup Path Writable: ".__PASS);
  211. }
  212. // Check For Required Functions
  213. showLog(" > Checking Remote URL Functions...");
  214. if( function_exists('file') && function_exists('fopen') && ini_get('allow_url_fopen') ) {
  215. showLog("\t - Remote URL Function Exist ('FOPEN'): ".__PASS);
  216. $doURLChecks = true;
  217. } elseif( (function_exists('curl_exec')) ) {
  218. showLog("\t - Remote URL Function Exist ('CURL'): ".__PASS);
  219. $doURLChecks = true;
  220. } else {
  221. showLog("\t - Remote URL Function Exist: ".__WARN);
  222. $doURLChecks = false;
  223. }
  224. // Close database connection
  225. @mysql_close($connection);
  226. if ($doURLChecks) {
  227. // Check bf2statistics.php Processing
  228. showLog(" > Checking BF2Statistics Processing...");
  229. $fh = @fsockopen($_SERVER['HTTP_HOST'], 80);
  230. if ($fh) {
  231. fwrite($fh, "POST /ASP/bf2statistics.php HTTP/1.1\r\n");
  232. fwrite($fh, "HOST: ".$_SERVER['HTTP_HOST']."\r\n");
  233. fwrite($fh, "User-Agent: GameSpyHTTP/1.0\r\n");
  234. fwrite($fh, "Content-Type: application/x-www-form-urlencoded\r\n");
  235. fwrite($fh, "Content-Length: " . strlen($tst_snapshot) . "\r\n\r\n");
  236. fwrite($fh, $tst_snapshot . "\r\n");
  237. $buffer = "";
  238. while (!feof($fh)) {
  239. $buffer .= fgets($fh, 4096);
  240. }
  241. fclose($fh);
  242. // Check Response Buffer
  243. if (preg_match("%^HTTP/1.[01]\s*(\d+) *([^\n\r]*)(.*?)$%is", $buffer, $matches)) {
  244. $responsecode = $matches[1];
  245. }
  246. if ($responsecode != '200') {
  247. showLog("\t - BF2Statistics Processing Check: ".__FAIL);
  248. } else {
  249. showLog("\t - BF2Statistics Processing Check: ".__PASS);
  250. }
  251. } else {
  252. showLog("\t - BF2Statistics Processing Check: ".__FAIL);
  253. }
  254. // Check .aspx Page Responses
  255. showLog(" > Checking Gamespy (.aspx) File Basic Response...");
  256. $url = "http://".$_SERVER['HTTP_HOST']."/ASP/getbackendinfo.aspx";
  257. $response = getPageContents($url);
  258. if (trim($response[0]) != 'O') {
  259. showLog("\t - Gamespy (.aspx) Basic Response: ".__FAIL);
  260. } else {
  261. showLog("\t - Gamespy (.aspx) Basic Response: ".__PASS);
  262. }
  263. showLog(" > Checking Gamespy (.aspx) File Advanced Responses...");
  264. $url = "http://".$_SERVER['HTTP_HOST']."/ASP/getawardsinfo.aspx?pid={$tst_pid}";
  265. $response = getPageContents($url);
  266. if (trim($response[0]) != 'O') {
  267. showLog("\t - Gamespy (.aspx) Advanced (1) Response: ".__FAIL);
  268. } else {
  269. showLog("\t - Gamespy (.aspx) Advanced (1) Response: ".__PASS);
  270. }
  271. $url = "http://".$_SERVER['HTTP_HOST']."/ASP/getrankinfo.aspx?pid={$tst_pid}";
  272. $response = getPageContents($url);
  273. if (trim($response[0]) != 'O') {
  274. showLog("\t - Gamespy (.aspx) Advanced (2) Response: ".__FAIL);
  275. } else {
  276. showLog("\t - Gamespy (.aspx) Advanced (2) Response: ".__PASS);
  277. }
  278. $url = "http://".$_SERVER['HTTP_HOST']."/ASP/getunlocksinfo.aspx?pid={$tst_pid}";
  279. $response = getPageContents($url);
  280. if (trim($response[0]) != 'O') {
  281. showLog("\t - Gamespy (.aspx) Advanced (3) Response: ".__FAIL);
  282. } else {
  283. showLog("\t - Gamespy (.aspx) Advanced (3) Response: ".__PASS);
  284. }
  285. }
  286. // Re-Connect to DB (The above scripts sometimes removes it)
  287. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  288. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  289. // Remove Test Server Data
  290. $query = "DELETE FROM `servers` WHERE prefix = '{$tst_prefix}';";
  291. $result = mysql_query($query);
  292. if ($result) {
  293. showLog(" -> Server Info ({$tst_prefix}) removed from Table (servers).");
  294. } else {
  295. showLog(" -> <font color='red'>ERROR:</font> Server Info ({$tst_prefix}) removed from Table (servers)!\n".mysql_error());
  296. }
  297. // Remove Test Map Data
  298. $query = "DELETE FROM `mapinfo` WHERE id = {$tst_mapid};";
  299. $result = mysql_query($query);
  300. if ($result) {
  301. showLog(" -> Map Info ({$tst_mapid}) removed from Table (mapinfo).");
  302. } else {
  303. showLog(" -> <font color='red'>ERROR:</font> Map Info ({$tst_mapid}) removed from Table (mapinfo)!\n".mysql_error());
  304. }
  305. $query = "DELETE FROM `round_history` WHERE mapid = {$tst_mapid};";
  306. $result = mysql_query($query);
  307. if ($result) {
  308. showLog(" -> Map Info ({$tst_mapid}) removed from Table (round_history).");
  309. } else {
  310. showLog(" -> <font color='red'>ERROR:</font> Map Info ({$tst_mapid}) removed from Table (round_history)!\n".mysql_error());
  311. }
  312. showLog("Done! :)");
  313. showLog("");
  314. // Close database connection
  315. @mysql_close($connection);
  316. // Remove Test Player Data
  317. $_POST['selitems'] = array($tst_pid);
  318. processDeletePlayers();
  319. }
  320. function processChangeLeaders() {
  321. // This script will edits your characters rank and assign awards
  322. global $cfg, $DB;
  323. $bco = $_POST['b_commander'];
  324. $oco = $_POST['o_commander'];
  325. $bdco = $_POST['b_d_commander'];
  326. $odco = $_POST['o_d_commander'];
  327. $bdcor = $_POST['b_d_rank'];
  328. $odcor = $_POST['o_d_rank'];
  329. $tour = $_POST['tour'];
  330. $check = $DB->query("SELECT tour FROM tour_leaders WHERE tour='$tour' LIMIT 1");
  331. if(count($check) > 0){
  332. $howmany = $check;
  333. $DB->query("UPDATE `tour_leaders` SET `b_commander`='$bco',`o_commander`='$oco',`b_d_commander`='$bdco',`bdrank`='$bdcor',`o_d_commander`='$odco',`odrank`='$odcor' WHERE (tour='$tour')");
  334. }else{
  335. $DB->query("INSERT INTO tour_leaders(tour, b_commander, o_commander, b_d_commander, bdrank, o_d_commander, odrank) VALUES('$tour', '$bco', '$oco', '$bdco', '$bdcor', '$odco', '$odcor') LIMIT 1");
  336. }
  337. showLog("Done! :)");
  338. }
  339. function processChangeRank() {
  340. // This script will edits your characters rank and assign awards
  341. global $cfg, $DB;
  342. $rank = $_POST['selected_rank'];
  343. $id = $_POST['player'];
  344. $changerank = $DB->query("UPDATE player SET rank='$rank' WHERE id LIKE '$id'");
  345. showLog("Done! :)");
  346. }
  347. function processAddCustomBadge() {
  348. // This script will edits your characters rank and assign awards
  349. global $cfg, $DB;
  350. $award = $_POST['selected_badge'];
  351. $id = $_POST['player'];
  352. $addaward = $DB->query("INSERT INTO custom_awards(pid, award, count, type) VALUES($id, $award, 1, 1)");
  353. showLog("Done! :)");
  354. }
  355. function processAddCustomMedal() {
  356. // This script will edits your characters rank and assign awards
  357. global $cfg, $DB;
  358. $award = $_POST['medal'];
  359. $id = $_POST['player'];
  360. $count = $_POST['count'];
  361. $check = $DB->query("SELECT count FROM custom_awards WHERE pid='$id' AND award='$award' LIMIT 1");
  362. if(count($check) > 0){
  363. $howmany = $check;
  364. $DB->query("UPDATE `custom_awards` SET `count`=(`count` + ".$count.") WHERE pid='$id' AND award='$award'");
  365. }else{
  366. $DB->query("INSERT INTO custom_awards(pid, award, count, type) VALUES($id, $award, $count, 2)");
  367. }
  368. showLog("Done! :)");
  369. }
  370. function processScoreManager() {
  371. // This script will edits your characters rank and assign awards
  372. global $cfg, $DB;
  373. $a = $_POST['tour'];
  374. $b = $_POST['mapid'];
  375. $c = $_POST['mapname'];
  376. $d = $_POST['team'];
  377. $e = $_POST['tickets'];
  378. $f = $_POST['ntp'];
  379. $g = $_POST['oftp'];
  380. $h = $_POST['ntpp'];
  381. $i = $_POST['ofpp'];
  382. $DB->query("INSERT INTO scoreboard(tour, number, mapname, winner, tickets, natotp, opfortp, ntpPoints, otpPoints) VALUES('$a', '$b', '$c', '$d', '$e', '$f', '$g', '$h', '$i')");
  383. showLog("Done! :)");
  384. }
  385. function processBanPlayers() {
  386. // This script will validate the BF2 Gamespy Ranks
  387. global $cfg;
  388. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  389. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  390. $pids_arr = $_POST['selitems'];
  391. showLog("Banning Players...");
  392. $query = "SELECT id FROM player";
  393. if ($pids_arr) {
  394. $pids = implode(", ", $pids_arr);
  395. $query .= " WHERE id IN ({$pids})";
  396. } else {
  397. showLog("ERROR:<font color='red'>ERROR:</font> No Players Selected!");
  398. return;
  399. }
  400. $result = mysql_query($query);
  401. if (mysql_num_rows($result)) {
  402. while ($row = mysql_fetch_array($result)) {
  403. $pid = $row['id'];
  404. $query = "UPDATE player SET permban = 1 WHERE (id = {$pid})";
  405. $updateresult = mysql_query($query);
  406. if ($updateresult) {
  407. showLog(" -> Player ({$pid}) Banned");
  408. } else {
  409. showLog(" -> <font color='red'>ERROR:</font> Player ({$pid}) *NOT* Banned: ".mysql_error());
  410. }
  411. }
  412. } else {
  413. showLog("<font color='red'>ERROR:</font> No Data Found!");
  414. }
  415. // Close database connection
  416. @mysql_close($connection);
  417. showLog("Done! :)");
  418. }
  419. function processUnBanPlayers() {
  420. // This script will validate the BF2 Gamespy Ranks
  421. global $cfg;
  422. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  423. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  424. $pids_arr = $_POST['selitems'];
  425. showLog("Un-Banning Players...");
  426. $query = "SELECT id FROM player";
  427. if ($pids_arr) {
  428. $pids = implode(", ", $pids_arr);
  429. $query .= " WHERE id IN ({$pids})";
  430. } else {
  431. showLog("ERROR:<font color='red'>ERROR:</font> No Players Selected!");
  432. return;
  433. }
  434. $result = mysql_query($query);
  435. if (mysql_num_rows($result)) {
  436. while ($row = mysql_fetch_array($result)) {
  437. $pid = $row['id'];
  438. $query = "UPDATE player SET permban = 0 WHERE (id = {$pid})";
  439. $updateresult = mysql_query($query);
  440. if ($updateresult) {
  441. showLog(" -> Player ({$pid}) Un-Banned");
  442. } else {
  443. showLog(" -> <font color='red'>ERROR:</font> Player ({$pid}) *NOT* Un-Banned: ".mysql_error());
  444. }
  445. }
  446. } else {
  447. showLog("<font color='red'>ERROR:</font> No Data Found!");
  448. }
  449. // Close database connection
  450. @mysql_close($connection);
  451. showLog("Done! :)");
  452. }
  453. function processResetUnlocks() {
  454. // This script will validate the BF2 Gamespy Ranks
  455. global $cfg;
  456. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  457. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  458. $pids_arr = $_POST['selitems'];
  459. showLog("Reseting Player Unlocks...");
  460. $query = "SELECT id, availunlocks, usedunlocks FROM player";
  461. if ($pids_arr) {
  462. $pids = implode(", ", $pids_arr);
  463. $query .= " WHERE id IN ({$pids})";
  464. } else {
  465. showLog("ERROR:<font color='red'>ERROR:</font> No Players Selected!");
  466. return;
  467. }
  468. $result = mysql_query($query);
  469. if (mysql_num_rows($result)) {
  470. while ($row = mysql_fetch_array($result)) {
  471. $pid = $row['id'];
  472. $unlocks = $row['availunlocks'] + $row['usedunlocks'];
  473. $used = 0;
  474. showLog(" -> Found Player ({$pid}) : $unlocks : $used");
  475. showLog(" -> Reseting Unlocks for Player ({$pid})");
  476. $query = "UPDATE unlocks SET state = 'n' WHERE (id = {$pid})";
  477. mysql_query($query) or die(mysql_error());
  478. $query = "UPDATE player SET availunlocks = {$unlocks}, usedunlocks = {$used} WHERE id = {$pid}";
  479. mysql_query($query) or die(mysql_error());
  480. showLog("Done! :)");
  481. }
  482. } else {
  483. showLog("<font color='red'>ERROR:</font> No Data Found!");
  484. }
  485. // Close database connection
  486. @mysql_close($connection);
  487. showLog("Done! :)");
  488. }
  489. function processDeletePlayers() {
  490. // This script will permantly delete player data. Use with EXTREME cation!!
  491. global $cfg;
  492. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  493. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  494. // Build Data Table Array
  495. $DataTables = array('army','awards','kills','kits','mapinfo','maps','player','player_history','unlocks','vehicles','weapons');
  496. $pids_arr = $_POST['selitems'];
  497. if ($pids_arr) {
  498. $pids = implode(", ", $pids_arr);
  499. } else {
  500. showLog("<font color='red'>ERROR:</font> No Players Selected!");
  501. return;
  502. }
  503. showLog("Delete Player Data ({$pids})...");
  504. foreach ($DataTables as $DataTable) {
  505. // Check Table Exists
  506. $query = "SHOW TABLES LIKE '" . $DataTable . "'";
  507. $result = mysql_query($query);
  508. if (mysql_num_rows($result)==1) {
  509. // Table Exists, lets clear it
  510. $query = "DELETE FROM `" . $DataTable . "` ";
  511. if ($DataTable == 'kills') {
  512. $query .= "WHERE ((attacker IN ({$pids})) OR (victim IN ({$pids})));";
  513. } else {
  514. $query .= "WHERE id IN ({$pids});";
  515. }
  516. $result = mysql_query($query);
  517. if ($result) {
  518. showLog(" -> Player(s) removed from Table (" . $DataTable . ").");
  519. } else {
  520. showLog(" -> <font color='red'>ERROR:</font> Player(s) *NOT* removed from Table (" . $DataTable . ")!\n".mysql_error());
  521. }
  522. }
  523. }
  524. // Close database connection
  525. @mysql_close($connection);
  526. showLog("Done! :)");
  527. }
  528. function processMergePlayers() {
  529. // This script will merge 2 player ID's, setting the first one as . Use with EXTREME cation!!
  530. global $cfg;
  531. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  532. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  533. // Get PlayerID's
  534. $pids = array();
  535. $pids[0] = ($_POST['target_pid'])?$_POST['target_pid']:0; // Target PID
  536. $pids[1] = ($_POST['source_pid'])?$_POST['source_pid']:0; // Source PID
  537. // Check PID Values
  538. if ($pids[0]==0 || $pids[1]==0) {
  539. showLog("<font color='red'>ERROR:</font> Data input missing!");
  540. return;
  541. }
  542. if ($pids[0] == $pids[1]) {
  543. showLog("<font color='red'>ERROR:</font> Target &amp; Source are Identical!!");
  544. return;
  545. }
  546. // Check Players Exist
  547. foreach ($pids as $pid) {
  548. if (!is_numeric($pid)) {
  549. showLog("<font color='red'>ERROR:</font> PID ({$pid}) is not a valid player!");
  550. return;
  551. }
  552. $query = "SELECT id FROM player WHERE id = {$pid}";
  553. $result = mysql_query($query);
  554. if (mysql_num_rows($result)==1) {
  555. $pids_exist = true;
  556. } else {
  557. showLog("<<font color='red'>ERROR:</font> PID ({$pid}) is not a valid player!");
  558. return;
  559. }
  560. }
  561. // We are still here, so everything must have checked out
  562. showLog("Merging Player Data...");
  563. // Note: PID1 -->> PID0. PID0 becomes the primary and PID1 is removed! Make sure you get this RIGHT!!!!
  564. // Merge Single-line data tables
  565. $DataTables = array('army','kits','vehicles','weapons','player');
  566. foreach ($DataTables as $DataTable) {
  567. showLog(" -> Merging {$DataTable} table...");
  568. $query = "SELECT * FROM {$DataTable} WHERE id = {$pids[1]}";
  569. $result = mysql_query($query);
  570. if (mysql_num_rows($result)==1) {
  571. $fieldCount = mysql_num_fields($result);
  572. $row = mysql_fetch_row($result);
  573. // Build Update Query
  574. $query = "UPDATE {$DataTable} SET ";
  575. for( $i = 1; $i < $fieldCount; $i++ ) {
  576. if (mysql_field_type($result, $i)=='int') {
  577. if ($DataTable == 'player' && mysql_field_name($result, $i) == 'joined') {
  578. $query .= "`" . mysql_field_name($result, $i) . "` = " . $row[$i] . ",\n";
  579. } elseif ($DataTable == 'player' && mysql_field_name($result, $i) == 'lastonline') {
  580. $query .= "`" . mysql_field_name($result, $i) . "` = `" . mysql_field_name($result, $i) . "`,\n";
  581. } elseif ($DataTable == 'player' && mysql_field_name($result, $i) == 'rndscore') {
  582. $query .= "`" . mysql_field_name($result, $i) . "` = (SELECT IF(" . $row[$i] . " > `" . mysql_field_name($result, $i) . "`, " . $row[$i] . ", `" . mysql_field_name($result, $i) . "`)),\n";
  583. } else {
  584. $query .= "`" . mysql_field_name($result, $i) . "` = `" . mysql_field_name($result, $i) . "` + " . $row[$i] . ",\n";
  585. }
  586. }
  587. }
  588. $query = rtrim($query, ",\n") . "\nWHERE id = {$pids[0]};";
  589. // Update Data
  590. if (mysql_query($query)) {
  591. showLog("\t\tSuccess!");
  592. // Remove Old Data
  593. $query="DELETE FROM `{$DataTable}` WHERE id = {$pids[1]};";
  594. if (mysql_query($query)) {
  595. showLog(" -> Old Player Data ({$DataTable}) Removed.");
  596. } else {
  597. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  598. }
  599. } else {
  600. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  601. return;
  602. }
  603. } else {
  604. showLog("\t\tNo Data");
  605. }
  606. }
  607. // Reset Unlocks
  608. showLog(" -> Reseting Unlocks for Player ({$pids[0]})...");
  609. $query = "UPDATE unlocks SET state = 'n' WHERE (id = {$pids[0]})";
  610. if (mysql_query($query)) {
  611. $query = "UPDATE player SET availunlocks = 0, usedunlocks = 0 WHERE id = {$pids[0]}";
  612. mysql_query($query) or die(mysql_error());
  613. showLog("\t\tSuccess!");
  614. // Remove Old Unlocks Data
  615. showLog(" -> Removing Old Unlocks for Player ({$pids[1]})...");
  616. $query = "DELETE FROM unlocks WHERE (id = {$pids[1]})";
  617. if (mysql_query($query)) {
  618. showLog("\t\tUnlocks Removed!");
  619. } else {
  620. showLog("\t\t<font color='red'>ERROR:</font> Unlocks Removal Failed!".mysql_error());
  621. }
  622. } else {
  623. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  624. return;
  625. }
  626. // Merge Awards Data
  627. showLog(" -> Merging Awards table...");
  628. $query = "SELECT * FROM awards WHERE id = {$pids[1]};";
  629. $result = mysql_query($query);
  630. if( mysql_num_rows( $result ) ) {
  631. while( $rowsrc = mysql_fetch_array( $result ) ) {
  632. // Check Awards exist
  633. if ($rowsrc['awd']) {
  634. $query = "SELECT * FROM awards WHERE id = {$pids[0]} AND awd = " . $rowsrc['awd'] . ";";
  635. $chkresult = mysql_query($query);
  636. if( mysql_num_rows( $chkresult ) ) {
  637. // Update Award
  638. $rowdest = mysql_fetch_array( $chkresult );
  639. $query = "UPDATE `awards` SET\n";
  640. switch ($rowsrc['awd']){
  641. case 2051902: // Gold
  642. case 2051907: // Silver
  643. case 2051919: // Bronze
  644. $query .= "`level` = `level` + " . $rowsrc['level'] . ",\n";
  645. break;
  646. default:
  647. $query .= "level = " . MAX($rowsrc['level'],$rowdest['level']) . ",\n";
  648. }
  649. $query .= "earned = " . MIN($rowsrc['earned'],$rowdest['earned']) . ",\n";
  650. $query .= "first = " . MIN($rowsrc['first'],$rowdest['first']) . "\n";
  651. $query .= "WHERE id = {$pids[0]} AND `awd` = " . $rowsrc['awd'] . ";";
  652. if (mysql_query($query)) {
  653. showLog("\t\tAward {$rowsrc[awd]} Update Success!");
  654. } else {
  655. showLog("\t\t<font color='red'>ERROR:</font> Award {$rowsrc[awd]} Update Failed: ".mysql_error());
  656. }
  657. } else {
  658. // Insert Award
  659. $query = "INSERT INTO `awards` SET\n";
  660. $query .= "`id` = {$pids[0]},\n";
  661. $query .= "`awd` = " . $rowsrc['awd'] . ",\n";
  662. $query .= "`level` = " . $rowsrc['level'] . ",\n";
  663. $query .= "`earned` = " . $rowsrc['earned'] . ",\n";
  664. $query .= "`first` = " . $rowsrc['first'] . ";";
  665. if (mysql_query($query)) {
  666. showLog("\t\tAward {$rowsrc[awd]} Insert Success!");
  667. } else {
  668. showLog("\t\t<font color='red'>ERROR:</font> Award {$rowsrc[awd]} Insert Failed: ".mysql_error());
  669. }
  670. }
  671. } else {
  672. showLog("\t\t<font color='red'>ERROR:</font> Err, that shouldn't have happend! :(");
  673. }
  674. }
  675. showLog("\t\tAwards Table Merged!");
  676. // Remove Old Awards Data
  677. showLog(" -> Removing Old Awards for Player ({$pids[1]})...");
  678. $query = "DELETE FROM awards WHERE (id = {$pids[1]})";
  679. if (mysql_query($query)) {
  680. showLog("\t\tSuccess!");
  681. } else {
  682. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  683. }
  684. }
  685. // Merge Maps Data
  686. showLog(" -> Merging Maps table...");
  687. $query = "SELECT * FROM `maps` WHERE `id` = {$pids[1]};";
  688. $result = mysql_query($query);
  689. if( mysql_num_rows( $result ) ) {
  690. while( $rowsrc = mysql_fetch_array( $result ) ) {
  691. // Check Map exist
  692. if ($rowsrc['mapid']>=0) {
  693. $query = "SELECT * FROM `maps` WHERE `id`= {$pids[0]} AND `mapid` = " . $rowsrc['mapid'] . ";";
  694. $chkresult = mysql_query($query);
  695. if( mysql_num_rows( $chkresult ) ) {
  696. // Update Map Data
  697. $rowdest = mysql_fetch_array( $chkresult );
  698. $query = "UPDATE `maps` SET\n";
  699. $query .= "`time` = `time` + " . $rowsrc['time'] . ",\n";
  700. $query .= "`win` = `win` + " . $rowsrc['win'] . ",\n";
  701. $query .= "`loss` = `loss` + " . $rowsrc['loss'] . ",\n";
  702. if ($rowsrc['best'] > $rowdest['best']) {
  703. $query .= "`best` = " . $rowsrc['best'] . ",\n";
  704. }
  705. if ($rowsrc['worst'] < $rowdest['worst']) {
  706. $query .= "`worst` = `worst` + " . $rowsrc['worst'] . "\n";
  707. }
  708. $query .= "WHERE id = {$pids[0]} AND `mapid` = " . $rowsrc['mapid'] . ";";
  709. if (mysql_query($query)) {
  710. showLog("\t\tMap {$rowsrc[mapid]} Update Success!");
  711. } else {
  712. showLog("\t\t<font color='red'>ERROR:</font> Map {$rowsrc[mapid]} Update Failed: ".mysql_error());
  713. }
  714. } else {
  715. // Insert Map Data
  716. $query = "INSERT INTO `maps` SET\n";
  717. $query .= "`id` = {$pids[0]},\n";
  718. $query .= "`mapid` = " . $rowsrc['mapid'] . ",\n";
  719. $query .= "`time` = " . $rowsrc['time'] . ",\n";
  720. $query .= "`win` = " . $rowsrc['win'] . ",\n";
  721. $query .= "`loss` = " . $rowsrc['loss'] . ",\n";
  722. $query .= "`best` = " . $rowsrc['best'] . ",\n";
  723. $query .= "`worst` = " . $rowsrc['worst'] . ";";
  724. if (mysql_query($query)) {
  725. showLog("\t\tMap {$rowsrc[mapid]} Insert Success!");
  726. } else {
  727. showLog("\t\t<font color='red'>ERROR:</font> Map {$rowsrc[mapid]} Insert Failed: ".mysql_error());
  728. }
  729. }
  730. } else {
  731. showLog("\t\t<font color='red'>ERROR:</font> MapID Invalid!");
  732. }
  733. }
  734. showLog("\t\tDone!");
  735. // Remove Old Maps Data
  736. showLog(" -> Removing Old Maps for Player ({$pids[1]})...");
  737. $query = "DELETE FROM maps WHERE (id = {$pids[1]})";
  738. if (mysql_query($query)) {
  739. showLog("\t\tSuccess!");
  740. } else {
  741. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  742. }
  743. }
  744. // Update Kills Data
  745. showLog(" -> Updating Kills Data...");
  746. $query = "SELECT * FROM kills WHERE attacker = {$pids[1]};";
  747. $result = mysql_query($query);
  748. if( mysql_num_rows( $result ) ) {
  749. while( $rowsrc = mysql_fetch_array( $result ) ) {
  750. // Check Kills exist
  751. if ($rowsrc['victim']) {
  752. $query = "SELECT * FROM kills WHERE attacker = {$pids[0]} AND victim = " . $rowsrc['victim'] . ";";
  753. $chkresult = mysql_query($query);
  754. if( mysql_num_rows( $chkresult ) ) {
  755. // Update Existing record
  756. $query = "UPDATE `kills` SET\n";
  757. $query .= "`count` = `count` + " . $rowsrc['count'] . "\n";
  758. $query .= "WHERE attacker = {$pids[0]} AND victim = " . $rowsrc['victim'] . ";";
  759. if (mysql_query($query)) {
  760. // Success
  761. } else {
  762. showLog("\t\t<font color='red'>ERROR:</font> Kills data not updated: ".mysql_error());
  763. }
  764. } else {
  765. // Insert Kills
  766. $query = "INSERT INTO `kills` SET\n";
  767. $query .= "attacker = {$pids[0]},\n";
  768. $query .= "victim = " . $rowsrc['victim'] . ",\n";
  769. $query .= "`count` = " . $rowsrc['count'] . ";";
  770. if (mysql_query($query)) {
  771. // Success
  772. } else {
  773. showLog("\t\t<font color='red'>ERROR:</font> Kills data not inserted: ".mysql_error());
  774. }
  775. }
  776. } else {
  777. showLog("<font color='red'>#</font>");
  778. }
  779. }
  780. showLog("\t\tKills Done!");
  781. // Remove Old Kills Data
  782. showLog(" -> Removing Old Kills for Player ({$pids[1]})...");
  783. $query = "DELETE FROM kills WHERE (attacker = {$pids[1]})";
  784. if (mysql_query($query)) {
  785. showLog("\t\tSuccess!");
  786. } else {
  787. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  788. }
  789. }
  790. // Update Deaths Data
  791. showLog(" -> Updating Deaths Data...");
  792. $query = "SELECT * FROM kills WHERE victim = {$pids[1]};";
  793. $result = mysql_query($query);
  794. if( mysql_num_rows( $result ) ) {
  795. while( $rowsrc = mysql_fetch_array( $result ) ) {
  796. // Check Deaths exist
  797. if ($rowsrc['attacker']) {
  798. $query = "SELECT * FROM kills WHERE attacker = " . $rowsrc['attacker'] . " AND victim = {$pids[0]};;";
  799. $chkresult = mysql_query($query);
  800. if( mysql_num_rows( $chkresult ) ) {
  801. // Update Existing record
  802. $query = "UPDATE `kills` SET\n";
  803. $query .= "`count` = `count` + " . $rowsrc['count'] . "\n";
  804. $query .= "WHERE attacker = " . $rowsrc['attacker'] . " AND victim = {$pids[0]};";
  805. if (mysql_query($query)) {
  806. // Success
  807. } else {
  808. showLog("\t\t<font color='red'>ERROR:</font> Kills data not updated: ".mysql_error());
  809. }
  810. } else {
  811. // Insert Deaths
  812. $query = "INSERT INTO `kills` SET\n";
  813. $query .= "attacker = " . $rowsrc['attacker'] . ",\n";
  814. $query .= "victim = {$pids[0]},\n";
  815. $query .= "`count` = " . $rowsrc['count'] . ";";
  816. if (mysql_query($query)) {
  817. // Success
  818. } else {
  819. showLog("\t\t<font color='red'>ERROR:</font> Kills data not inserted: ".mysql_error());
  820. }
  821. }
  822. } else {
  823. showLog("<font color='red'>#</font>");
  824. }
  825. }
  826. showLog("\t\tDeaths Done!");
  827. // Remove Old Deaths Data
  828. showLog(" -> Removing Old Deaths for Player ({$pids[1]})...");
  829. $query = "DELETE FROM kills WHERE (victim = {$pids[1]})";
  830. if (mysql_query($query)) {
  831. showLog("\t\tSuccess!");
  832. } else {
  833. showLog("\t\t<font color='red'>ERROR:</font> ".mysql_error());
  834. }
  835. }
  836. showLog("Done! :)\n");
  837. // Close database connection
  838. @mysql_close($connection);
  839. //Validating Rank
  840. $_POST['selitems'] = array($pids[0]);
  841. processValidateRanks();
  842. // Ensure Old player does not exist
  843. $_POST['selitems'] = array($pids[1]);
  844. processDeletePlayers();
  845. }
  846. function processInstallDB() {
  847. // Install Default DB Schema
  848. $cfg = new Config();
  849. // Store New/Changed config items
  850. showLog("Saving Config...");
  851. foreach ($_POST as $item => $val) {
  852. $key = explode('__', $item);
  853. if ($key[0] == 'cfg') {
  854. showLog(" -> Found Key: '{$key[1]}' => '".((is_array($cfg->get($key[1])))?str_replace("\r\n", ",",$val):$val)."' (Old: ".((is_array($cfg->get($key[1])))?implode(',',$cfg->get($key[1])):$cfg->get($key[1])).")...");
  855. $cfg->set($key[1],$val);
  856. }
  857. }
  858. $cfg->Save();
  859. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  860. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  861. // Import Schema
  862. require('includes/db/sql.dbschema.php');
  863. showLog("Installing Database Schema");
  864. foreach ($sqlschema as $query) {
  865. if (mysql_query($query[1])) {
  866. showLog(" -> ".$query[0]." Installed");
  867. } else {
  868. showLog(" -> <font color='red'>ERROR:</font> ".$query[0]." *NOT* Installed: ".mysql_error());
  869. }
  870. }
  871. // Import Defaut Data
  872. require('includes/db/sql.dbdata.php');
  873. $i = 0;
  874. showLog("Loading Default Database Data");
  875. foreach ($sqldata as $query) {
  876. if (mysql_query($query[1])) {
  877. if ($query[0] == _IPN) {
  878. if (($i % 100) == 0) {showLog(" -> ".$query[0]." ({$i} records) Loaded");}
  879. $i++;
  880. } else {
  881. showLog(" -> ".$query[0]." Loaded");
  882. }
  883. } else {
  884. showLog(" -> <font color='red'>ERROR:</font> ".$query[0]." *NOT* Loaded: ".mysql_error());
  885. }
  886. }
  887. // Close database connection
  888. @mysql_close($connection);
  889. showLog("Done! :)");
  890. }
  891. function processUpgradeDB() {
  892. // Update Scheme to Include EF & AF Booster Pack Info
  893. $cfg = new Config();
  894. // Store New/Changed config items
  895. showLog("Saving Config...");
  896. foreach ($_POST as $item => $val) {
  897. $key = explode('__', $item);
  898. if ($key[0] == 'cfg') {
  899. showLog(" -> Found Key: '{$key[1]}' => '".((is_array($cfg->get($key[1])))?str_replace("\r\n", ",",$val):$val)."' (Old: ".((is_array($cfg->get($key[1])))?implode(',',$cfg->get($key[1])):$cfg->get($key[1])).")...");
  900. $cfg->set($key[1],$val);
  901. }
  902. }
  903. $cfg->Save();
  904. // Get DB Version
  905. $curdbver = verCmp(getDbVer());
  906. // Open Database connection
  907. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  908. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  909. // Upgrade Schema
  910. require('includes/db/sql.dbupgrade.php');
  911. showLog("Upgrading Database Schema");
  912. foreach ($sqlupgrade as $query) {
  913. if ($curdbver < verCmp($query[1])) {
  914. if (mysql_query($query[2])) {
  915. showLog(" -> ".$query[0]." Success");
  916. } else {
  917. showLog(" -> <font color='red'>ERROR:</font> ".$query[0]." *FAILED*: ".mysql_error());
  918. }
  919. } else {
  920. showLog(" -> <font color='blue'>Skipping:</font> ".$query[0]);
  921. }
  922. }
  923. // Close database connection
  924. @mysql_close($connection);
  925. showLog("Done! :)");
  926. }
  927. function processClearDB() {
  928. // This script will clear the Gamespy tables. Use with EXTREME cation!!
  929. global $cfg, $DataTables;
  930. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  931. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  932. showLog("Clearing Data Tables");
  933. foreach ($DataTables as $DataTable) {
  934. // Check Table Exists
  935. $query = "SHOW TABLES LIKE '" . $DataTable . "'";
  936. $result = mysql_query($query);
  937. if (mysql_num_rows($result)) {
  938. // Table Exists, lets clear it
  939. $query="TRUNCATE TABLE `" . $DataTable . "`;";
  940. $result = mysql_query($query);
  941. if ($result) {
  942. showLog(" -> Table (" . $DataTable . ") Cleared.");
  943. } else {
  944. showLog(" -> <font color='red'>ERROR:</font> Table (" . $DataTable . ") NOT Cleared!\n".mysql_error());
  945. }
  946. }
  947. }
  948. // Close database connection
  949. @mysql_close($connection);
  950. showLog("Done! :)");
  951. }
  952. function processBackupDB() {
  953. // This script will backup the "Gamespy" Data Tabels
  954. global $cfg, $DataTables;
  955. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  956. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  957. showLog("Backing Up Data Tables");
  958. // Create Backup Folder
  959. $backupPath = chkPath($cfg->get('admin_backup_path'));
  960. $backupPath .= "bak_".date('Ymd_Hi');
  961. mkdir($backupPath, 0666); // Read and write for owner, nothing for everybody else
  962. showLog(" -> Created Backup Directory: {$backupPath}");
  963. foreach ($DataTables as $DataTable) {
  964. // Check Table Exists
  965. $query = "SHOW TABLES LIKE '" . $DataTable . "'";
  966. $result = mysql_query($query);
  967. if (mysql_num_rows($result)==1) {
  968. // Table Exists, lets back it up
  969. $backupFile = $backupPath."/".$DataTable.$cfg->get('admin_backup_ext');
  970. $query="SELECT * INTO OUTFILE '{$backupFile}' FROM {$DataTable};";
  971. $result = mysql_query($query);
  972. if ($result) {
  973. showLog(" -> Table (" . $DataTable . ") Backed Up.");
  974. } else {
  975. showLog(" -> <font color='red'>ERROR:</font> Table (" . $DataTable . ") *NOT* Backed Up: ".mysql_error());
  976. }
  977. }
  978. }
  979. // Close database connection
  980. @mysql_close($connection);
  981. showLog("Done! :)");
  982. }
  983. function processRestoreDB() {
  984. // This script will backup the "Gamespy" Data Tabels
  985. global $cfg, $DataTables;
  986. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  987. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  988. showLog("Restore Data Tables");
  989. // Check Backup Folder
  990. $backupPath = chkPath($cfg->get('admin_backup_path'));
  991. $backupPath .= $_POST["backupname"];
  992. showLog(" -> Loaded Backup Directory: {$backupPath}");
  993. foreach ($DataTables as $DataTable) {
  994. // Check Table Exists
  995. $query = "SHOW TABLES LIKE '" . $DataTable . "'";
  996. $result = mysql_query($query);
  997. if (mysql_num_rows($result)==1) {
  998. // Table Exists
  999. $backupFile = $backupPath."/".$DataTable.$cfg->get('admin_backup_ext');
  1000. if (file_exists($backupFile)) {
  1001. // File Exists, lets restore it
  1002. $query="LOAD DATA INFILE '{$backupFile}' INTO TABLE {$DataTable};";
  1003. $result = mysql_query($query);
  1004. if ($result) {
  1005. showLog(" -> Table (" . $DataTable . ") Restored.");
  1006. } else {
  1007. showLog(" -> <font color='red'>ERROR:</font> Table (" . $DataTable . ") *NOT* Restored: ".mysql_error());
  1008. }
  1009. } else {
  1010. showLog(" -> <font color='red'>ERROR:</font> Data File (" . $backupFile . ") does *NOT* Exist!!");
  1011. }
  1012. }
  1013. }
  1014. // Close database connection
  1015. @mysql_close($connection);
  1016. showLog("Done! :)");
  1017. }
  1018. function processValidateRanks() {
  1019. // This script will validate the BF2 Gamespy Ranks
  1020. global $cfg;
  1021. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  1022. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  1023. $pids_arr = $_POST['selitems'];
  1024. showLog("Validating Player Ranks");
  1025. $query = "SELECT `id`, score, rank FROM player";
  1026. if ($pids_arr) {
  1027. $pids = implode(", ", $pids_arr);
  1028. $query .= " WHERE id IN ({$pids})";
  1029. } else {
  1030. showLog("<font color='red'>ERROR:</font> No Players Selected!");
  1031. return;
  1032. }
  1033. $result = mysql_query($query);
  1034. if (mysql_num_rows($result)>0) {
  1035. $expRank = array();
  1036. while ($row = mysql_fetch_array($result)) {
  1037. $pid = $row['id'];
  1038. $score = $row['score'];
  1039. $rank = $row['rank'];
  1040. showLog(" -> Found Player ({$pid}) : Score:{$score} : Rank:{$rank}");
  1041. // Verify/Correct Rank
  1042. // NOTE: Ranks 1SG/SGM/BG/MG/SMOC/GEN cannot be awarded here.
  1043. if ($score >= 200000) {$expRank[0] = 20;$expRank[1] = 20;}
  1044. elseif ($score >= 150000) {$expRank[0] = 17;$expRank[1] = 19;}
  1045. elseif ($score >= 125000) {$expRank[0] = 16;$expRank[1] = 16;}
  1046. elseif ($score >= 115000) {$expRank[0] = 15;$expRank[1] = 15;}
  1047. elseif ($score >= 90000) {$expRank[0] = 14;$expRank[1] = 14;}
  1048. elseif ($score >= 75000) {$expRank[0] = 13;$expRank[1] = 13;}
  1049. elseif ($score >= 60000) {$expRank[0] = 12;$expRank[1] = 12;}
  1050. elseif ($score >= 50000) {$expRank[0] = 9;$expRank[1] = 11;}
  1051. elseif ($score >= 20000) {$expRank[0] = 7;$expRank[1] = 8;}
  1052. elseif ($score >= 8000) {$expRank[0] = 6;$expRank[1] = 6;}
  1053. elseif ($score >= 5000) {$expRank[0] = 5;$expRank[1] = 5;}
  1054. elseif ($score >= 2500) {$expRank[0] = 4;$expRank[1] = 4;}
  1055. elseif ($score >= 800) {$expRank[0] = 3;$expRank[1] = 3;}
  1056. elseif ($score >= 500) {$expRank[0] = 2;$expRank[1] = 2;}
  1057. elseif ($score >= 150) {$expRank[0] = 1;$expRank[1] = 1;}
  1058. else {$expRank[0] = 0;$expRank[1] = 0;}
  1059. // Only update if Rank is less than expected.
  1060. if ($rank < $expRank[0] || $rank > $expRank[1]){
  1061. // Rank seems to be messed up, will reset to minimum rank for this level
  1062. showLog(" -> Rank Correction (".$row['id']."):");
  1063. showLog(" Score: ".$score);
  1064. showLog(" Expected: ".$expRank[0]."-".$expRank[1]);
  1065. showLog(" Found: ".$row['rank']);
  1066. showLog(" New Rank: ".$expRank[0]);
  1067. // Update Database
  1068. $query = "UPDATE player SET rank = ".$expRank[0]." WHERE id = ".$row['id'];
  1069. if (mysql_query($query)) {
  1070. showLog(" -> Rank Correction: Success!");
  1071. } else {
  1072. showLog(" -> Rank Correction: Fail! (".mysql_error().")");
  1073. }
  1074. }
  1075. }
  1076. showLog("Done! :)");
  1077. } else {
  1078. showLog("<font color='red'>ERROR:</font> No Data Found!");
  1079. }
  1080. // Close database connection
  1081. @mysql_close($connection);
  1082. }
  1083. function processCheckAwards() {
  1084. // This script will check for Backend awards
  1085. global $cfg;
  1086. $connection = @mysql_connect($cfg->get('db_host'), $cfg->get('db_user'), $cfg->get('db_pass'));
  1087. @mysql_select_db($cfg->get('db_name'), $connection) or die("Database Error: " . mysql_error());
  1088. // Import Backend Awards Data
  1089. require('includes/data.awards.php');
  1090. // Check for Backend Awards Data
  1091. if (!isset($backendawardsdata)) {
  1092. $backendawardsdata = array_merge(buildBackendAwardsData('bf2'), buildBackendAwardsData('xpack'));
  1093. }
  1094. $startTime = microtime_float();
  1095. $pids_arr = $_POST['selitems'];
  1096. showLog("Checking Player Backend Awards");
  1097. $query = "SELECT `id` FROM player";
  1098. if ($pids_arr) {
  1099. $pids = implode(", ", $pids_arr);
  1100. $query .= " WHERE id IN ({$pids})";
  1101. } else {
  1102. showLog("ERROR:<font color='red'>ERROR:</font> No Players Selected!");
  1103. return;
  1104. }
  1105. $result = mysql_query($query);
  1106. if (mysql_num_rows($result)>0) {
  1107. while ($rowp = mysql_fetch_array($result)) {
  1108. $pid = $rowp['id'];
  1109. showLog(" -> Found Player ({$pid})");
  1110. $playerStartTime = microtime_float();
  1111. // Calculate Awards
  1112. foreach ($backendawardsdata as $award) {
  1113. // Check if Player already has Award
  1114. $query = "SELECT awd, level FROM awards WHERE (id = " . $pid . ") AND (awd = {$award[0]})";
  1115. $awdresult = mysql_query($query);
  1116. if (!$awdresult) {
  1117. showLog("<font color='red'>ERROR:</font> " . mysql_error());
  1118. showLog("Query String: " . $query);
  1119. }
  1120. // Check if player has award
  1121. if (mysql_num_rows($awdresult)>0) {
  1122. $rowawd = mysql_fetch_array($awdresult);
  1123. }
  1124. // Check Criteria
  1125. $chkcriteria = false;
  1126. foreach ($award[3] as $criteria) {
  1127. if ($award[2] == 2) {
  1128. // Can receive multiple times
  1129. if (mysql_num_rows($awdresult)>0) {
  1130. $where = str_replace($awards_substr, $rowawd['level']+1, $criteria[3]);
  1131. } else {
  1132. $where = str_replace($awards_substr, 1, $criteria[3]);
  1133. }
  1134. } else {
  1135. $where = $criteria[3];
  1136. }
  1137. $query = "SELECT {$criteria[1]} AS checkval FROM {$criteria[0]}\n" .
  1138. "WHERE (id = " . $pid . ") AND ({$where})\n" .
  1139. "ORDER BY id;";
  1140. $chkresult = mysql_query($query);
  1141. if (!$chkresult) {
  1142. showLog("<font color='red'>ERROR:</font> ERROR: " . mysql_error() . "\n");
  1143. showLog("Query String: " . $query);
  1144. }
  1145. if (mysql_num_rows($chkresult)>0) {
  1146. $rowchk = mysql_fetch_array($chkresult);
  1147. if ($rowchk['checkval'] >= $criteria[2]) {
  1148. $chkcriteria = true;
  1149. break;
  1150. } else {
  1151. $chkcriteria = false;
  1152. break;
  1153. }
  1154. }
  1155. }
  1156. if ($chkcriteria && mysql_num_rows($awdresult) == 0) {
  1157. showLog(" - Award Missing ({$award[0]})");
  1158. // Insert information
  1159. $query = "INSERT INTO awards SET
  1160. id = " . $pid . ",
  1161. awd = {$award[0]},
  1162. level = 1,
  1163. earned = " . time() . ",
  1164. first = 0;";
  1165. if (!mysql_query($query)) {
  1166. showLog("<font color='red'>ERROR:</font> " . mysql_error());
  1167. showLog("Query String: " . $query);
  1168. }
  1169. } elseif (!$chkcriteria && mysql_num_rows($awdresult)>0) {
  1170. if ($rowawd['awd'] == $award[0]) {
  1171. showLog(" - Has Award ({$award[0]}), but does not meet requirements!");
  1172. // Delete information
  1173. $query = "DELETE FROM awards
  1174. WHERE (id = " . $pid . " AND awd = {$award[0]});";
  1175. if (!mysql_query($query)) {
  1176. showLog("<font color='red'>ERROR:</font> " . mysql_error());
  1177. showLog("Query String: " . $query);
  1178. }
  1179. }
  1180. } elseif ($chkcriteria) {
  1181. showLog(" - Has Award ({$award[0]}), requirements met!");
  1182. }
  1183. }
  1184. showLog(" Processing Time ({$pid}): " . (microtime_float() - $playerStartTime));
  1185. }
  1186. showLog("Done! :)");
  1187. } else {
  1188. showLog("<font color='red'>ERROR:</font> No Data Found!");
  1189. }
  1190. // Close database connection
  1191. @mysql_close($connection);
  1192. showLog("Total Processing Time: " . (microtime_float() - $startTime));
  1193. }
  1194. function processImportLogs() {
  1195. // This function will import all existing log files. This is useful for rebuilding an empty Gamespy database
  1196. global $cfg;
  1197. // Make Sure Script doesn't timeout
  1198. set_time_limit(0);
  1199. // Find Log Files
  1200. showLog("Importing Log Files");
  1201. $regex = '([0-9]{4})([0-9]{2})([0-9]{2})_([0-9]{4})';
  1202. $dir = opendir(chkPath($cfg->get('stats_logs')));
  1203. chdir(chkPath($cfg->get('stats_logs')));
  1204. while(($file = readdir($dir)) !== false)
  1205. {
  1206. if (strpos($file, $cfg->get('stats_ext')))
  1207. {
  1208. ereg($regex,$file,$sort);
  1209. $files[] = $sort[0] . "|" . $file;
  1210. }
  1211. }
  1212. // Sort Files
  1213. sort($files, SORT_STRING);
  1214. // Re-post existing log data to bf2statistics
  1215. $total = 0;
  1216. for ($x = 0; $x < count($files); $x++)
  1217. {
  1218. $file = explode("|",$files[$x]);
  1219. $fh = fsockopen($_SERVER['HTTP_HOST'], 80);
  1220. fwrite($fh, "POST /ASP/bf2statistics.php HTTP/1.1\r\n");
  1221. fwrite($fh, "HOST: localhost\r\n");
  1222. fwrite($fh, "User-Agent: GameSpyHTTP/1.0\r\n");
  1223. fwrite($fh, "Content-Type: application/x-www-form-urlencoded\r\n");
  1224. $filename = @fopen($file[1], 'r');
  1225. $data = fread($filename, filesize($file[1]));
  1226. @fclose($filename);
  1227. if (strpos($data, '\EOF\1') === false) {
  1228. // Older SNAPSHOT. Insert EOF to ensure bf2statiscs.php processes this...
  1229. $data .= '\EOF\1';
  1230. }
  1231. if (strpos($file[1], "importdata") === false) {
  1232. // Make sure we know this is an import of existing log data
  1233. $data .= '\import\1';
  1234. }
  1235. fwrite($fh, "Content-Length: " . strlen($data) . "\r\n\r\n");
  1236. fwrite($fh, $data . "\r\n");
  1237. fclose($fh);
  1238. showLog(" -> Importing $file[1]...done!");
  1239. $total++;
  1240. }
  1241. showLog("Total files imported: $total");
  1242. }
  1243. function microtime_float() {
  1244. list($usec, $sec) = explode(" ", microtime());
  1245. return ((float)$usec + (float)$sec);
  1246. }
  1247. ?>