PageRenderTime 68ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/functions.php

https://bitbucket.org/ogsteam/ogspy
PHP | 1867 lines | 1234 code | 195 blank | 438 comment | 358 complexity | 503ee5e1cc492cdea88f337978e468b6 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause
  1. <?php
  2. /**
  3. * OGSpy Global functions
  4. * @package OGSpy
  5. * @subpackage Common
  6. * @author Kyser
  7. * @copyright Copyright &copy; 2012, http://www.ogsteam.fr/
  8. * @version 3.1.1 ($Rev: 7752 $)
  9. * @modified $Date: 2012-11-05 13:04:30 +0100 (Mon, 05 Nov 2012) $
  10. * @link $HeadURL: http://svn.ogsteam.fr/trunk/ogspy/includes/functions.php $
  11. * $Id: functions.php 7752 2012-11-05 12:04:30Z darknoon $
  12. */
  13. if (!defined('IN_SPYOGAME')) {
  14. die("Hacking attempt");
  15. }
  16. /**
  17. * URL Redirection
  18. * @param string $url target URL
  19. */
  20. function redirection($url)
  21. {
  22. if (headers_sent()) {
  23. die('<meta http-equiv="refresh" content="0; URL=' . $url . '">');
  24. } else {
  25. header("Location: " . $url);
  26. exit();
  27. }
  28. }
  29. /**
  30. * Write a text or a table in a file
  31. * @param string $file Filename
  32. * @param string $mode File Opening Mode
  33. * @param string|Array $text String or table to write
  34. * @return boolean false if failed
  35. */
  36. function write_file($file, $mode, $text)
  37. {
  38. if ($fp = fopen($file, $mode)) {
  39. if (is_array($text)) {
  40. foreach ($text as $t) {
  41. fwrite($fp, rtrim($t));
  42. fwrite($fp, "\r\n");
  43. }
  44. } else {
  45. fwrite($fp, $text);
  46. fwrite($fp, "\r\n");
  47. }
  48. fclose($fp);
  49. return true;
  50. } else
  51. return false;
  52. }
  53. /**
  54. * Write a text or a table in a gz compressed file
  55. * @param string $file Filename
  56. * @param string $mode File Opening Mode
  57. * @param string|Array $text String or table to write
  58. * @return boolean false if failed
  59. */
  60. function write_file_gz($file, $mode, $text)
  61. {
  62. if ($fp = gzopen($file . ".gz", $mode)) {
  63. if (is_array($text)) {
  64. foreach ($text as $t) {
  65. gzwrite($fp, rtrim($t));
  66. gzwrite($fp, "\r\n");
  67. }
  68. } else {
  69. gzwrite($fp, $text);
  70. gzwrite($fp, "\r\n");
  71. }
  72. gzclose($fp);
  73. return true;
  74. } else
  75. return false;
  76. }
  77. /**
  78. * Convert an IP in Hex Format
  79. * @param string $ip format xxx.xxx.xxx.xxx in IPv4 and xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx in IPv6
  80. * @return string IP in hex : HHHHHHHH for IPv4 and HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH for IPv6
  81. */
  82. function encode_ip ($ip)
  83. {
  84. $d = explode('.', $ip);
  85. if (count($d) == 4) return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]);
  86. $d = explode(':', preg_replace('/(^:)|(:$)/', '', $ip));
  87. $res = '';
  88. foreach ($d as $x)
  89. $res .= sprintf('%0'. ($x == '' ? (9 - count($d)) * 4 : 4) .'s', $x);
  90. return $res;
  91. }
  92. /**
  93. * Convert an IP in Hex format to an IPv4 or IPv6 format
  94. * @param string $int_ip IP encoded
  95. * @return string $ip format xxx.xxx.xxx.xxx in IPv4 and xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx in IPv6
  96. */
  97. function decode_ip($int_ip)
  98. {
  99. if (strlen($int_ip) == 32) {
  100. $int_ip = substr(chunk_split($int_ip, 4, ':'), 0, 39);
  101. $int_ip = ':'. implode(':', array_map("hexhex", explode(':',$int_ip))) .':';
  102. preg_match_all("/(:0)+/", $int_ip, $zeros);
  103. if (count($zeros[0]) > 0) {
  104. $match = '';
  105. foreach($zeros[0] as $zero)
  106. if (strlen($zero) > strlen($match))
  107. $match = $zero;
  108. $int_ip = preg_replace('/'. $match .'/', ':', $int_ip, 1);
  109. }
  110. return preg_replace('/(^:([^:]))|(([^:]):$)/', '$2$4', $int_ip);
  111. }
  112. $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
  113. return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
  114. }
  115. /**
  116. * Converts a hex value to another hew value (depnding of the current php version on the server)
  117. * @param string $value The initial hexvalue
  118. * @return string the new hew value
  119. */
  120. function hexhex($value) {
  121. return dechex(hexdec($value));
  122. };
  123. /**
  124. * Generates a random password with 6 chars
  125. * @return string $password The generated password
  126. */
  127. function password_generator()
  128. {
  129. $string = "abBDEFcdefghijkmnPQRSTUVWXYpqrst23456789";
  130. srand((double)microtime() * 1000000);
  131. $password = '';
  132. for ($i = 0; $i < 6; $i++) {
  133. $password .= $string[rand() % strlen($string)];
  134. }
  135. return $password;
  136. }
  137. /**
  138. * Initialisation of the cache for all Mod settings
  139. *
  140. * Generates a file which contains all configurations for different installed OGSpy Modules
  141. */
  142. function init_mod_cache()
  143. {
  144. global $cache_mod, $server_config;
  145. // Load cached config
  146. $filename = 'cache/cache_mod.php';
  147. if (file_exists($filename)) {
  148. include $filename;
  149. // regeneration si besoin
  150. if ((filemtime($filename) + $server_config['mod_cache']) < time()) {
  151. generate_mod_cache();
  152. }
  153. } else {
  154. generate_mod_cache();
  155. if (file_exists($filename)) {
  156. include $filename; // on reinjecte le fichier s'il existe'
  157. }
  158. }
  159. }
  160. /**
  161. * Initialisation of the cache for all Server settings
  162. *
  163. * Generates a file which contains all configurations for the OGSpy Server
  164. */
  165. function init_serverconfig()
  166. {
  167. global $server_config;
  168. // Load cached config
  169. $filename = 'cache/cache_config.php';
  170. if (file_exists($filename)) {
  171. include $filename;
  172. // regeneration si besoin
  173. if ((filemtime($filename) + $server_config['config_cache']) < time()) {
  174. generate_config_cache();
  175. }
  176. } else {
  177. generate_config_cache();
  178. if (file_exists($filename)) {
  179. include $filename; // on reinjecte le fichier s'il existe'
  180. }
  181. }
  182. }
  183. /**
  184. * Updates in the database all configurations displayed in the display administration Page.
  185. * @todo Query: update . TABLE_CONFIG . set config_value = . $pub_enable_portee_missil . where config_name = \'portee_missil\'
  186. * @todo Query: "update " . TABLE_CONFIG . " set config_value = " . $pub_galaxy_by_line_stat . " where config_name = 'galaxy_by_line_stat'"
  187. * @todo Query: "update " . TABLE_CONFIG . " set config_value = " . $pub_system_by_line_stat . " where config_name = 'system_by_line_stat'"
  188. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_open_user ."' where config_name = 'open_user'"
  189. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_open_admin . "' where config_name = 'open_admin'"
  190. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_enable_stat_view ." where config_name = 'enable_stat_view'"
  191. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_enable_members_view ." where config_name = 'enable_members_view'"
  192. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_nb_colonnes_ally) ."' where config_name = 'nb_colonnes_ally'"
  193. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($color_ally) . "' where config_name = 'color_ally'"
  194. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_galaxy_by_line_ally ." where config_name = 'galaxy_by_line_ally'"
  195. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_system_by_line_ally ." where config_name = 'system_by_line_ally'"
  196. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_enable_register_view ."' where config_name = 'enable_register_view'"
  197. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_register_alliance) ."' where config_name = 'register_alliance'"
  198. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_register_forum) ."' where config_name = 'register_forum'"
  199. */
  200. function set_server_view()
  201. {
  202. global $db, $user_data;
  203. global $pub_enable_portee_missil, $pub_enable_members_view, $pub_enable_stat_view,
  204. $pub_galaxy_by_line_stat, $pub_system_by_line_stat, $pub_galaxy_by_line_ally, $pub_system_by_line_ally,
  205. $pub_nb_colonnes_ally, $pub_color_ally, $pub_enable_register_view, $pub_register_alliance,
  206. $pub_register_forum, $pub_open_user, $pub_open_admin;
  207. if (!check_var($pub_enable_members_view, "Num") || !check_var($pub_enable_stat_view,
  208. "Num") || !check_var($pub_galaxy_by_line_stat, "Num") || !check_var($pub_system_by_line_stat,
  209. "Num") || !check_var($pub_galaxy_by_line_ally, "Num") || !check_var($pub_system_by_line_ally,
  210. "Num")) {
  211. redirection("index.php?action=message&id_message=errordata&info");
  212. }
  213. if ($user_data["user_admin"] != 1 && $user_data["user_coadmin"] != 1) {
  214. redirection("planetindex.php?action=message&id_message=forbidden&info");
  215. }
  216. if (!isset($pub_galaxy_by_line_stat) || !isset($pub_system_by_line_stat) || !
  217. isset($pub_galaxy_by_line_ally) || !isset($pub_system_by_line_ally)) {
  218. redirection("index.php?action=message&id_message=setting_server_view_failed&info");
  219. }
  220. if (is_null($pub_enable_portee_missil))
  221. $pub_enable_portee_missil = 0;
  222. if (is_null($pub_enable_stat_view))
  223. $pub_enable_stat_view = 0;
  224. if (is_null($pub_enable_members_view))
  225. $pub_enable_members_view = 0;
  226. $break = false;
  227. if (!is_numeric($pub_galaxy_by_line_stat))
  228. $break = true;
  229. if (!is_numeric($pub_system_by_line_stat))
  230. $break = true;
  231. if ($pub_enable_stat_view != 0 && $pub_enable_stat_view != 1)
  232. $break = true;
  233. if ($pub_enable_members_view != 0 && $pub_enable_members_view != 1)
  234. $break = true;
  235. if (!is_numeric($pub_galaxy_by_line_ally))
  236. $break = true;
  237. if (!is_numeric($pub_system_by_line_ally))
  238. $break = true;
  239. if ($pub_nb_colonnes_ally == 0 || $pub_nb_colonnes_ally > 9 || !is_numeric($pub_nb_colonnes_ally))
  240. $break = true;
  241. if ($pub_enable_register_view != 0 && $pub_enable_register_view != 1)
  242. $break = true;
  243. if ($break) {
  244. redirection("index.php?action=message&id_message=setting_server_view_failed&info");
  245. }
  246. //
  247. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_enable_portee_missil .
  248. " where config_name = 'portee_missil'";
  249. $db->sql_query($request);
  250. //
  251. if ($pub_galaxy_by_line_stat < 1)
  252. $pub_galaxy_by_line_stat = 1;
  253. if ($pub_galaxy_by_line_stat > 100)
  254. $pub_galaxy_by_line_stat = 100;
  255. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_galaxy_by_line_stat .
  256. " where config_name = 'galaxy_by_line_stat'";
  257. $db->sql_query($request);
  258. //
  259. if ($pub_system_by_line_stat < 1)
  260. $pub_system_by_line_stat = 1;
  261. if ($pub_system_by_line_stat > 100)
  262. $pub_system_by_line_stat = 100;
  263. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_system_by_line_stat .
  264. " where config_name = 'system_by_line_stat'";
  265. $db->sql_query($request);
  266. //
  267. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_open_user .
  268. "' where config_name = 'open_user'";
  269. $db->sql_query($request);
  270. //
  271. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_open_admin .
  272. "' where config_name = 'open_admin'";
  273. $db->sql_query($request);
  274. //
  275. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_enable_stat_view .
  276. " where config_name = 'enable_stat_view'";
  277. $db->sql_query($request);
  278. //
  279. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_enable_members_view .
  280. " where config_name = 'enable_members_view'";
  281. $db->sql_query($request);
  282. //
  283. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  284. sql_escape_string($pub_nb_colonnes_ally) .
  285. "' where config_name = 'nb_colonnes_ally'";
  286. $db->sql_query($request);
  287. $array = $pub_color_ally; //die(var_dump($pub_color_ally));
  288. $color_ally = implode("_", $array);
  289. //
  290. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  291. sql_escape_string($color_ally) . "' where config_name = 'color_ally'";
  292. $db->sql_query($request);
  293. //
  294. if ($pub_galaxy_by_line_ally < 1)
  295. $pub_galaxy_by_line_ally = 1;
  296. if ($pub_galaxy_by_line_ally > 100)
  297. $pub_galaxy_by_line_ally = 100;
  298. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_galaxy_by_line_ally .
  299. " where config_name = 'galaxy_by_line_ally'";
  300. $db->sql_query($request);
  301. //
  302. if ($pub_system_by_line_ally < 1)
  303. $pub_system_by_line_ally = 1;
  304. if ($pub_system_by_line_ally > 100)
  305. $pub_system_by_line_ally = 100;
  306. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_system_by_line_ally .
  307. " where config_name = 'system_by_line_ally'";
  308. $db->sql_query($request);
  309. //
  310. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_enable_register_view .
  311. "' where config_name = 'enable_register_view'";
  312. $db->sql_query($request);
  313. //
  314. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  315. sql_escape_string($pub_register_alliance) .
  316. "' where config_name = 'register_alliance'";
  317. $db->sql_query($request);
  318. //
  319. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  320. sql_escape_string($pub_register_forum) .
  321. "' where config_name = 'register_forum'";
  322. $db->sql_query($request);
  323. // mise a jour des caches avec les modifs
  324. generate_config_cache();
  325. log_("set_server_view");
  326. redirection("index.php?action=administration&subaction=affichage");
  327. }
  328. /**
  329. * Updates in the database all configurations displayed in the parameters administration Page.
  330. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_server_active ." where config_name = 'server_active'";
  331. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_debug_log ." where config_name = 'debug_log'";
  332. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_block_ratio ." where config_name = 'block_ratio'";
  333. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_log_phperror ." where config_name = 'log_phperror'";
  334. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_favorites ." where config_name = 'max_favorites'";
  335. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_favorites_spy ." where config_name = 'max_favorites_spy'";
  336. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_ratio_limit ." where config_name = 'ratio_limit'";
  337. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_spyreport ." where config_name = 'max_spyreport'";
  338. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_battlereport ." where config_name = 'max_battlereport'";
  339. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_session_time ." where config_name = 'session_time'";
  340. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_keeplog ." where config_name = 'max_keeplog'";
  341. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_default_skin) . "' where config_name = 'default_skin'";
  342. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_reason) . "' where config_name = 'reason'";
  343. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_ally_protection) ."' where config_name = 'ally_protection'";
  344. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_url_forum) . "' where config_name = 'url_forum'";
  345. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_keeprank ." where config_name = 'max_keeprank'";
  346. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_keeprank_criterion) ."' where config_name = 'keeprank_criterion'";
  347. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_max_keepspyreport ." where config_name = 'max_keepspyreport'";
  348. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_servername) . "' where config_name = 'servername'";
  349. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $db->sql_escape_string($pub_allied) . "' where config_name = 'allied'";
  350. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_disable_ip_check ." where config_name = 'disable_ip_check'";
  351. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_num_of_galaxies ." where config_name = 'num_of_galaxies'";
  352. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_num_of_systems ." where config_name = 'num_of_systems'";
  353. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_ddr ."' where config_name = 'ddr'";
  354. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_astro_strict ."' where config_name = 'astro_strict'";
  355. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_uni_arrondi_galaxy ."' where config_name = 'uni_arrondi_galaxy'";
  356. * @todo Query : "update " . TABLE_CONFIG . " set config_value = '" . $pub_uni_arrondi_system ."' where config_name = 'uni_arrondi_system'";
  357. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_speed_uni ." where config_name = 'speed_uni'";
  358. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_mod_cache ." where config_name = 'mod_cache'";
  359. * @todo Query : "update " . TABLE_CONFIG . " set config_value = " . $pub_config_cache ." where config_name = 'config_cache'";
  360. */
  361. function set_serverconfig()
  362. {
  363. global $db, $user_data, $server_config;
  364. global $pub_max_battlereport, $pub_max_favorites, $pub_max_favorites_spy, $pub_max_spyreport,
  365. $pub_server_active, $pub_session_time, $pub_max_keeplog, $pub_default_skin, $pub_debug_log,
  366. $pub_reason, $pub_ally_protection, $pub_url_forum, $pub_max_keeprank, $pub_keeprank_criterion,
  367. $pub_max_keepspyreport, $pub_servername, $pub_allied, $pub_disable_ip_check, $pub_num_of_galaxies,
  368. $pub_num_of_systems, $pub_log_phperror, $pub_block_ratio, $pub_ratio_limit, $pub_speed_uni,
  369. $pub_ddr, $pub_astro_strict, $pub_uni_arrondi_galaxy, $pub_uni_arrondi_system, $pub_config_cache, $pub_mod_cache;
  370. if (!isset($pub_num_of_galaxies))
  371. $pub_num_of_galaxies = intval($server_config['num_of_galaxies']);
  372. if (!isset($pub_num_of_systems))
  373. $pub_num_of_systems = intval($server_config['num_of_systems']);
  374. if (!check_var($pub_max_battlereport, "Num") || !check_var($pub_max_favorites,
  375. "Num") || !check_var($pub_max_favorites_spy, "Num") || !check_var($pub_ratio_limit,
  376. "Special", "#^[\w\s,\.\-]+$#") || !check_var($pub_max_spyreport, "Num") || !
  377. check_var($pub_server_active, "Num") || !check_var($pub_session_time, "Num") ||
  378. !check_var($pub_max_keeplog, "Num") || !check_var($pub_default_skin, "URL") || !
  379. check_var($pub_debug_log, "Num") || !check_var($pub_block_ratio, "Num") || !
  380. check_var(stripslashes($pub_reason), "Text") || !check_var($pub_ally_protection,
  381. "Special", "#^[\w\s,\.\-]+$#") || !check_var($pub_url_forum, "URL") || !
  382. check_var($pub_max_keeprank, "Num") || !check_var($pub_keeprank_criterion,
  383. "Char") || !check_var($pub_max_keepspyreport, "Num") || !check_var(stripslashes
  384. ($pub_servername), "Text") || !check_var($pub_allied, "Special", "#^[\w\s,\.\-]+$#") ||
  385. !check_var($pub_disable_ip_check, "Num") || !check_var($pub_num_of_galaxies,
  386. "Galaxies") || !check_var($pub_num_of_systems, "Galaxies") || !check_var($pub_config_cache,
  387. "Num") || !check_var($pub_mod_cache, "Num")) {
  388. redirection("index.php?action=message&id_message=errordata&info");
  389. }
  390. if ($user_data["user_admin"] != 1 && $user_data["user_coadmin"] != 1) {
  391. redirection("planetindex.php?action=message&id_message=forbidden&info");
  392. }
  393. if (!isset($pub_max_battlereport) || !isset($pub_max_favorites) || !isset($pub_max_favorites_spy) ||
  394. !isset($pub_ratio_limit) || !isset($pub_max_spyreport) || !isset($pub_session_time) ||
  395. !isset($pub_max_keeplog) || !isset($pub_default_skin) || !isset($pub_reason) ||
  396. !isset($pub_ally_protection) || !isset($pub_url_forum) || !isset($pub_max_keeprank) ||
  397. !isset($pub_keeprank_criterion) || !isset($pub_max_keepspyreport) || !isset($pub_servername) ||
  398. !isset($pub_allied) || !isset($pub_mod_cache) || !isset($pub_config_cache)) {
  399. redirection("index.php?action=message&id_message=setting_serverconfig_failed&info");
  400. }
  401. if (is_null($pub_server_active))
  402. $pub_server_active = 0;
  403. if (is_null($pub_disable_ip_check))
  404. $pub_disable_ip_check = 0;
  405. if (is_null($pub_log_phperror))
  406. $pub_log_phperror = 0;
  407. if (is_null($pub_debug_log))
  408. $pub_debug_log = 0;
  409. if (is_null($pub_block_ratio))
  410. $pub_block_ratio = 0;
  411. $break = false;
  412. if ($pub_server_active != 0 && $pub_server_active != 1)
  413. $break = true;
  414. if ($pub_debug_log != 0 && $pub_debug_log != 1)
  415. $break = true;
  416. if ($pub_block_ratio != 0 && $pub_block_ratio != 1)
  417. $break = true;
  418. if (!is_numeric($pub_max_favorites))
  419. $break = true;
  420. if (!is_numeric($pub_max_favorites_spy))
  421. $break = true;
  422. if (!is_numeric($pub_ratio_limit))
  423. $break = true;
  424. if (!is_numeric($pub_max_spyreport))
  425. $break = true;
  426. if (!is_numeric($pub_max_battlereport))
  427. $break = true;
  428. if (!is_numeric($pub_session_time))
  429. $break = true;
  430. if (!is_numeric($pub_max_keeplog))
  431. $break = true;
  432. if ($pub_disable_ip_check != 0 && $pub_disable_ip_check != 1)
  433. $break = true;
  434. if ($pub_log_phperror != 0 && $pub_log_phperror != 1)
  435. $break = true;
  436. if ($break) {
  437. redirection("index.php?action=message&id_message=setting_serverconfig_failed&info");
  438. }
  439. if (($pub_num_of_galaxies != intval($server_config['num_of_galaxies'])) || ($pub_num_of_systems !=
  440. intval($server_config['num_of_systems']))) {
  441. resize_db($pub_num_of_galaxies, $pub_num_of_systems);
  442. }
  443. //
  444. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_server_active .
  445. " where config_name = 'server_active'";
  446. $db->sql_query($request);
  447. //
  448. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_debug_log .
  449. " where config_name = 'debug_log'";
  450. $db->sql_query($request);
  451. //
  452. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_block_ratio .
  453. " where config_name = 'block_ratio'";
  454. $db->sql_query($request);
  455. //
  456. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_log_phperror .
  457. " where config_name = 'log_phperror'";
  458. $db->sql_query($request);
  459. //
  460. $pub_max_favorites = intval($pub_max_favorites);
  461. if ($pub_max_favorites < 0)
  462. $pub_max_favorites = 0;
  463. if ($pub_max_favorites > 99)
  464. $pub_max_favorites = 99;
  465. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_favorites .
  466. " where config_name = 'max_favorites'";
  467. $db->sql_query($request);
  468. //
  469. $pub_max_favorites_spy = intval($pub_max_favorites_spy);
  470. if ($pub_max_favorites_spy < 0)
  471. $pub_max_favorites_spy = 0;
  472. if ($pub_max_favorites_spy > 99)
  473. $pub_max_favorites_spy = 99;
  474. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_favorites_spy .
  475. " where config_name = 'max_favorites_spy'";
  476. $db->sql_query($request);
  477. //
  478. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_ratio_limit .
  479. " where config_name = 'ratio_limit'";
  480. $db->sql_query($request);
  481. //
  482. $pub_max_spyreport = intval($pub_max_spyreport);
  483. if ($pub_max_spyreport < 1)
  484. $pub_max_spyreport = 1;
  485. if ($pub_max_spyreport > 50)
  486. $pub_max_spyreport = 50;
  487. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_spyreport .
  488. " where config_name = 'max_spyreport'";
  489. $db->sql_query($request);
  490. //
  491. $pub_max_battlereport = intval($pub_max_battlereport);
  492. if ($pub_max_battlereport < 0)
  493. $pub_max_battlereport = 0;
  494. if ($pub_max_battlereport > 999)
  495. $pub_max_battlereport = 999;
  496. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_battlereport .
  497. " where config_name = 'max_battlereport'";
  498. $db->sql_query($request);
  499. //
  500. $pub_session_time = intval($pub_session_time);
  501. if ($pub_session_time < 5 && $pub_session_time != 0)
  502. $pub_session_time = 5;
  503. if ($pub_session_time > 180)
  504. $pub_session_time = 180;
  505. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_session_time .
  506. " where config_name = 'session_time'";
  507. $db->sql_query($request);
  508. //
  509. $pub_max_keeplog = intval($pub_max_keeplog);
  510. if ($pub_max_keeplog < 0)
  511. $pub_max_keeplog = 0;
  512. if ($pub_max_keeplog > 365)
  513. $pub_max_keeplog = 365;
  514. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_keeplog .
  515. " where config_name = 'max_keeplog'";
  516. $db->sql_query($request);
  517. //
  518. if (substr($pub_default_skin, strlen($pub_default_skin) - 1) != "/")
  519. $pub_default_skin .= "/";
  520. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  521. sql_escape_string($pub_default_skin) . "' where config_name = 'default_skin'";
  522. $db->sql_query($request);
  523. //
  524. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  525. sql_escape_string($pub_reason) . "' where config_name = 'reason'";
  526. $db->sql_query($request);
  527. //
  528. if (substr($pub_ally_protection, strlen($pub_ally_protection) - 1) == ",")
  529. $pub_ally_protection = substr($pub_ally_protection, 0, strlen($pub_ally_protection) -
  530. 1);
  531. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  532. sql_escape_string($pub_ally_protection) .
  533. "' where config_name = 'ally_protection'";
  534. $db->sql_query($request);
  535. //
  536. if ($pub_url_forum != "" && !preg_match("#^http://#", $pub_url_forum))
  537. $pub_url_forum = "http://" . $pub_url_forum;
  538. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  539. sql_escape_string($pub_url_forum) . "' where config_name = 'url_forum'";
  540. $db->sql_query($request);
  541. //
  542. $pub_max_keeprank = intval($pub_max_keeprank);
  543. if ($pub_max_keeprank < 1)
  544. $pub_max_keeprank = 1;
  545. if ($pub_max_keeprank > 999)
  546. $pub_max_keeprank = 999;
  547. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_keeprank .
  548. " where config_name = 'max_keeprank'";
  549. $db->sql_query($request);
  550. //
  551. if ($pub_keeprank_criterion != "quantity" && $pub_keeprank_criterion != "day")
  552. $pub_keeprank_criterion = "quantity";
  553. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  554. sql_escape_string($pub_keeprank_criterion) .
  555. "' where config_name = 'keeprank_criterion'";
  556. $db->sql_query($request);
  557. //
  558. $pub_max_keepspyreport = intval($pub_max_keepspyreport);
  559. if ($pub_max_keepspyreport < 1)
  560. $pub_max_keepspyreport = 1;
  561. if ($pub_max_keepspyreport > 999)
  562. $pub_max_keepspyreport = 999;
  563. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_max_keepspyreport .
  564. " where config_name = 'max_keepspyreport'";
  565. $db->sql_query($request);
  566. //
  567. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  568. sql_escape_string($pub_servername) . "' where config_name = 'servername'";
  569. $db->sql_query($request);
  570. //
  571. if (substr($pub_allied, strlen($pub_allied) - 1) == ",")
  572. $pub_allied = substr($pub_allied, 0, strlen($pub_allied) - 1);
  573. $request = "update " . TABLE_CONFIG . " set config_value = '" . $db->
  574. sql_escape_string($pub_allied) . "' where config_name = 'allied'";
  575. $db->sql_query($request);
  576. //
  577. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_disable_ip_check .
  578. " where config_name = 'disable_ip_check'";
  579. $db->sql_query($request);
  580. //
  581. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_num_of_galaxies .
  582. " where config_name = 'num_of_galaxies'";
  583. $db->sql_query($request);
  584. //
  585. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_num_of_systems .
  586. " where config_name = 'num_of_systems'";
  587. $db->sql_query($request);
  588. //
  589. if (!isset($pub_ddr) || !is_numeric($pub_ddr))
  590. $pub_ddr = 0;
  591. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_ddr .
  592. "' where config_name = 'ddr'";
  593. $db->sql_query($request);
  594. //
  595. if (!isset($pub_astro_strict) || !is_numeric($pub_astro_strict))
  596. $pub_astro_strict = 0;
  597. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_astro_strict .
  598. "' where config_name = 'astro_strict'";
  599. $db->sql_query($request);
  600. //
  601. if (!isset($pub_uni_arrondi_galaxy) || !is_numeric($pub_uni_arrondi_galaxy))
  602. $pub_uni_arrondi_galaxy = 0;
  603. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_uni_arrondi_galaxy .
  604. "' where config_name = 'uni_arrondi_galaxy'";
  605. $db->sql_query($request);
  606. //
  607. if (!isset($pub_uni_arrondi_system) || !is_numeric($pub_uni_arrondi_system))
  608. $pub_uni_arrondi_system = 0;
  609. $request = "update " . TABLE_CONFIG . " set config_value = '" . $pub_uni_arrondi_system .
  610. "' where config_name = 'uni_arrondi_system'";
  611. $db->sql_query($request);
  612. //
  613. if (!is_numeric($pub_speed_uni) || $pub_speed_uni < 1)
  614. $pub_speed_uni = 1;
  615. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_speed_uni .
  616. " where config_name = 'speed_uni'";
  617. $db->sql_query($request);
  618. //
  619. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_mod_cache .
  620. " where config_name = 'mod_cache'";
  621. $db->sql_query($request);
  622. //
  623. $request = "update " . TABLE_CONFIG . " set config_value = " . $pub_config_cache .
  624. " where config_name = 'config_cache'";
  625. $db->sql_query($request);
  626. // mise a jour des caches avec les mofids
  627. generate_config_cache();
  628. log_("set_serverconfig");
  629. redirection("index.php?action=administration&subaction=parameter");
  630. }
  631. /**
  632. * Returns the Status of the Database used size.
  633. * @return Array [Server], et [Total]
  634. * @todo : Query : "SHOW TABLE STATUS"
  635. */
  636. function db_size_info()
  637. {
  638. global $db;
  639. global $table_prefix;
  640. $dbSizeServer = 0;
  641. $dbSizeTotal = 0;
  642. $request = "SHOW TABLE STATUS";
  643. $result = $db->sql_query($request);
  644. while ($row = $db->sql_fetch_assoc($result)) {
  645. $dbSizeTotal += $row['Data_length'] + $row['Index_length'];
  646. if (preg_match("#^" . $table_prefix . ".*$#", $row['Name'])) {
  647. $dbSizeServer += $row['Data_length'] + $row['Index_length'];
  648. }
  649. }
  650. $bytes = array('Octets', 'Ko', 'Mo', 'Go', 'To');
  651. if ($dbSizeServer < 1024)
  652. $dbSizeServer = 1;
  653. for ($i = 0; $dbSizeServer > 1024; $i++)
  654. $dbSizeServer /= 1024;
  655. $dbSize_info["Server"] = round($dbSizeServer, 2) . " " . $bytes[$i];
  656. if ($dbSizeTotal < 1024)
  657. $dbSizeTotal = 1;
  658. for ($i = 0; $dbSizeTotal > 1024; $i++)
  659. $dbSizeTotal /= 1024;
  660. $dbSize_info["Total"] = round($dbSizeTotal, 2) . " " . $bytes[$i];
  661. return $dbSize_info;
  662. }
  663. /**
  664. * Function to Optimize all tables of the OGSpy Database
  665. * @param boolean $maintenance_action true if no url redirection is requested,false to redirect to another page
  666. * @todo : Query : "SHOW TABLES"
  667. */
  668. function db_optimize($maintenance_action = false)
  669. {
  670. global $db;
  671. $dbSize_before = db_size_info();
  672. $dbSize_before = $dbSize_before["Total"];
  673. $request = 'SHOW TABLES';
  674. $res = $db->sql_query($request);
  675. while (list($table) = $db->sql_fetch_row($res)) {
  676. $request = 'OPTIMIZE TABLE ' . $table;
  677. $db->sql_query($request);
  678. }
  679. // 09-07-2012 : Commenté car cette table n'est plus utilisée
  680. //$request = 'TRUNCATE ' . TABLE_UNIVERSE_TEMPORARY;
  681. //$db->sql_query($request);
  682. $dbSize_after = db_size_info();
  683. $dbSize_after = $dbSize_after["Total"];
  684. if (!$maintenance_action) {
  685. redirection("index.php?action=message&id_message=db_optimize&info=" . $dbSize_before .
  686. "¤" . $dbSize_after);
  687. }
  688. }
  689. /**
  690. * Adapt the database to fit on the number of galaxies and solar systems
  691. * @param int $new_num_of_galaxies Galaxy total
  692. * @param int $new_num_of_systems Solar Systems total
  693. * @return null
  694. * @todo : Query : sql_query("DELETE FROM " . TABLE_UNIVERSE . " WHERE galaxy > $new_num_of_galaxies");
  695. * @todo : Query : sql_query("UPDATE " . TABLE_USER . " SET user_galaxy=1 WHERE user_galaxy > $new_num_of_galaxies");
  696. * @todo : Query : sql_query("DELETE FROM " . TABLE_USER_FAVORITE . " WHERE galaxy > $new_num_of_galaxies");
  697. * @todo : Query : sql_query("DELETE FROM " . TABLE_UNIVERSE . " WHERE system > $new_num_of_systems");
  698. * @todo : Query : sql_query("UPDATE " . TABLE_USER . " SET user_system=1 WHERE user_system > $new_num_of_systems");
  699. * @todo : Query : sql_query("DELETE FROM " . TABLE_USER_FAVORITE . " WHERE system > $new_num_of_systems");
  700. * @todo : Query : "ALTER TABLE `" . TABLE_UNIVERSE . "` CHANGE `galaxy` `galaxy` ENUM("; -> Voir Fonction
  701. * @todo : Query : "ALTER TABLE `" . TABLE_USER ." CHANGE `user_galaxy` `user_galaxy` -> Voir fonction
  702. * @todo : Query : $request = "ALTER TABLE `" . TABLE_USER_FAVORITE ."` CHANGE `galaxy` `galaxy` ENUM(" -> Voir fonction
  703. * @todo : Query : "REPLACE INTO " . TABLE_CONFIG ." (config_name, config_value) VALUES ('num_of_galaxies','$new_num_of_galaxies')";
  704. * @todo : Query : $requests = "REPLACE INTO " . TABLE_CONFIG ." (config_name, config_value) VALUES ('num_of_systems','$new_num_of_systems')";
  705. */
  706. function resize_db($new_num_of_galaxies, $new_num_of_systems)
  707. {
  708. global $db, $db_host, $db_user, $db_password, $db_database, $table_prefix, $server_config;
  709. // si on reduit on doit supprimez toutes les entrées qui font reference au systemes ou galaxies que l'on va enlever
  710. if ($new_num_of_galaxies < intval($server_config['num_of_galaxies'])) {
  711. $db->sql_query("DELETE FROM " . TABLE_UNIVERSE . " WHERE galaxy > $new_num_of_galaxies");
  712. $db->sql_query("UPDATE " . TABLE_USER . " SET user_galaxy=1 WHERE user_galaxy > $new_num_of_galaxies");
  713. $db->sql_query("DELETE FROM " . TABLE_USER_FAVORITE . " WHERE galaxy > $new_num_of_galaxies");
  714. }
  715. if ($new_num_of_systems < intval($server_config['num_of_systems'])) {
  716. $db->sql_query("DELETE FROM " . TABLE_UNIVERSE . " WHERE system > $new_num_of_systems");
  717. $db->sql_query("UPDATE " . TABLE_USER . " SET user_system=1 WHERE user_system > $new_num_of_systems");
  718. $db->sql_query("DELETE FROM " . TABLE_USER_FAVORITE . " WHERE system > $new_num_of_systems");
  719. }
  720. $request = "ALTER TABLE `" . TABLE_UNIVERSE . "` CHANGE `galaxy` `galaxy` ENUM(";
  721. for ($i = 1; $i < $new_num_of_galaxies; $i++)
  722. $request .= "'$i' , ";
  723. $request .= "'$new_num_of_galaxies') NOT NULL DEFAULT '1'";
  724. $db->sql_query($request);
  725. $request = "ALTER TABLE `" . TABLE_USER .
  726. "` CHANGE `user_galaxy` `user_galaxy` ENUM(";
  727. for ($i = 1; $i < $new_num_of_galaxies; $i++)
  728. $request .= "'$i' , ";
  729. $request .= "'$new_num_of_galaxies') NOT NULL DEFAULT '1'";
  730. $db->sql_query($request);
  731. $request = "ALTER TABLE `" . TABLE_USER_FAVORITE .
  732. "` CHANGE `galaxy` `galaxy` ENUM(";
  733. for ($i = 1; $i < $new_num_of_galaxies; $i++)
  734. $request .= "'$i' , ";
  735. $request .= "'$new_num_of_galaxies') NOT NULL DEFAULT '1'";
  736. $db->sql_query($request);
  737. $server_config['num_of_galaxies'] = "$new_num_of_galaxies";
  738. $server_config['num_of_systems'] = "$new_num_of_systems";
  739. $requests = "REPLACE INTO " . TABLE_CONFIG .
  740. " (config_name, config_value) VALUES ('num_of_galaxies','$new_num_of_galaxies')";
  741. $db->sql_query($request);
  742. $requests = "REPLACE INTO " . TABLE_CONFIG .
  743. " (config_name, config_value) VALUES ('num_of_systems','$new_num_of_systems')";
  744. $db->sql_query($request);
  745. log_("set_db_size");
  746. }
  747. /**
  748. * File Log size on the Server
  749. * @return Array tableau [type] and [size]
  750. */
  751. function log_size_info()
  752. {
  753. $logSize = 0;
  754. $res = opendir(PATH_LOG);
  755. $directory = array();
  756. //Récupération de la liste des fichiers présents dans les répertoires répertoriés
  757. while ($file = readdir($res)) {
  758. if ($file != "." && $file != "..") {
  759. if (is_dir(PATH_LOG . $file)) {
  760. $directory[] = PATH_LOG . $file;
  761. }
  762. }
  763. }
  764. closedir($res);
  765. foreach ($directory as $v) {
  766. $res = opendir($v);
  767. $directory = array();
  768. //Récupération de la liste des fichiers présents dans les répertoires répertoriés
  769. while ($file = readdir($res)) {
  770. if ($file != "." && $file != "..") {
  771. $logSize += @filesize($v . "/" . $file);
  772. }
  773. }
  774. closedir($res);
  775. }
  776. $bytes = array('Octets', 'Ko', 'Mo', 'Go', 'To');
  777. if ($logSize < 1024)
  778. $logSize = 1;
  779. for ($i = 0; $logSize > 1024; $i++)
  780. $logSize /= 1024;
  781. $log_size_info['size'] = round($logSize, 2);
  782. $log_size_info['type'] = $bytes[$i];
  783. return $log_size_info;
  784. }
  785. /**
  786. * Checks the availability of a log File
  787. * @param int $date Requested Date
  788. * @return boolean true if the log file exists
  789. * @internal To be improved...
  790. */
  791. function log_check_exist($date)
  792. {
  793. if (!isset($date))
  794. redirection("index.php?action=message&id_message=errorfatal&info");
  795. $typelog = array("sql", "log", "txt");
  796. $root = PATH_LOG;
  797. $path = opendir("$root");
  798. //Récupération de la liste des répertoires correspondant à cette date
  799. while ($file = readdir($path)) {
  800. if ($file != "." && $file != "..") {
  801. if (is_dir($root . $file) && preg_match("/^" . $date . "/", $file))
  802. $directories[] = $file;
  803. }
  804. }
  805. closedir($path);
  806. if (!isset($directories)) {
  807. return false;
  808. }
  809. foreach ($directories as $d) {
  810. $path = opendir($root . $d);
  811. while ($file = readdir($path)) {
  812. if ($file != "." && $file != "..") {
  813. $extension = substr($file, (strrpos($file, ".") + 1));
  814. if (in_array($extension, $typelog)) {
  815. $files[] = $d . "/" . $file;
  816. }
  817. }
  818. }
  819. closedir($path);
  820. }
  821. if (!isset($files)) {
  822. return false;
  823. }
  824. return true;
  825. }
  826. /**
  827. * Sends a Compressed archive to the browser for a specific date
  828. * @global array $user_data
  829. */
  830. function log_extractor()
  831. {
  832. global $pub_date, $user_data;
  833. if ($user_data["user_admin"] != 1 && $user_data["user_coadmin"] != 1) {
  834. redirection("index.php?action=message&id_message=forbidden&info");
  835. }
  836. if (!isset($pub_date))
  837. redirection("index.php?action=message&id_message=errorfatal&info");
  838. $typelog = array("sql", "log", "txt");
  839. $root = PATH_LOG;
  840. $zip_file= $root."log.zip";
  841. $path = opendir("$root");
  842. unlink($zip_file);
  843. //Récupération de la liste des répertoires correspondant à cette date
  844. while ($file = readdir($path)) {
  845. if ($file != "." && $file != "..") {
  846. if (is_dir($root . $file) && preg_match("/^" . $pub_date . "/", $file))
  847. $directories[] = $file;
  848. }
  849. }
  850. closedir($path);
  851. if (!isset($directories)) {
  852. redirection("index.php?action=message&id_message=log_missing&info");
  853. }
  854. foreach ($directories as $d) {
  855. $path = opendir($root . $d);
  856. while ($file = readdir($path)) {
  857. if ($file != "." && $file != "..") {
  858. $extension = substr($file, (strrpos($file, ".") + 1));
  859. if (in_array($extension, $typelog)) {
  860. $files[] = $d . "/" . $file;
  861. }
  862. }
  863. }
  864. closedir($path);
  865. }
  866. if (!isset($files)) {
  867. redirection("index.php?action=message&id_message=log_missing&info");
  868. }
  869. // création d'un objet 'zipfile'
  870. $zip = new ZipArchive;
  871. $zip->open($zip_file, ZipArchive::CREATE);
  872. foreach ($files as $filename) {
  873. // ajout du fichier dans cet objet
  874. $zip->addFile($root.$filename);
  875. log_('debug',"fichier dans archive:".$filename);
  876. }
  877. // production de l'archive Zip
  878. $zip->close();
  879. // entêtes HTTP
  880. header('Content-Type: application/x-zip');
  881. // force le téléchargement
  882. header('Content-disposition: attachment; filename=log_' . $pub_date . '.zip');
  883. header('Content-Transfer-Encoding: binary');
  884. // envoi du fichier au navigateur
  885. flush();
  886. readfile($zip_file);
  887. }
  888. /**
  889. * Deletes a specified Log File
  890. *
  891. */
  892. function log_remove()
  893. {
  894. global $pub_date, $user_data, $pub_directory;
  895. if ($user_data["user_admin"] != 1 && $user_data["user_coadmin"] != 1)
  896. redirection("index.php?action=message&id_message=forbidden&info");
  897. if ($pub_directory == true) {
  898. @unlink("journal/" . $pub_date . "/log_" . $pub_date . ".log");
  899. @unlink("journal/" . $pub_date . "/index.htm");
  900. if (rmdir("journal/" . $pub_date)) {
  901. redirection("index.php?action=message&id_message=log_remove&info");
  902. } else {
  903. redirection("index.php?action=message&id_message=log_missing&info");
  904. }
  905. } else {
  906. if (unlink("journal/" . $pub_date . "/log_" . $pub_date . ".log")) {
  907. redirection("index.php?action=message&id_message=log_remove&info");
  908. } else {
  909. redirection("index.php?action=message&id_message=log_missing&info");
  910. }
  911. }
  912. }
  913. /**
  914. * Log file cleaning according the the Server configuration
  915. */
  916. function log_purge()
  917. {
  918. global $server_config;
  919. $time = $server_config["max_keeplog"];
  920. $limit = time() - (60 * 60 * 24 * $time);
  921. $limit = intval(date("ymd", $limit));
  922. $root = PATH_LOG;
  923. $path = opendir("$root");
  924. while ($file = readdir($path)) {
  925. if ($file != "." && $file != "..") {
  926. if (is_dir($root . $file) && intval($file) < $limit && @ereg("[0-9]{6}", $file)) {
  927. $directories[] = $file;
  928. }
  929. }
  930. }
  931. closedir($path);
  932. if (!isset($directories)) {
  933. return;
  934. }
  935. $files = array();
  936. foreach ($directories as $d) {
  937. $path = opendir($root . $d);
  938. while ($file = readdir($path)) {
  939. if ($file != "." && $file != "..") {
  940. $extension = substr($file, (strrpos($file, ".") + 1));
  941. unlink($root . $d . "/" . $file);
  942. }
  943. }
  944. closedir($path);
  945. rmdir($root . $d);
  946. }
  947. }
  948. /**
  949. * Formats a number.
  950. * @param int $number The value to be converted
  951. * @param int $decimal Sets the number of decimal points.
  952. * @return string The number with the new formatting
  953. */
  954. function formate_number($number, $decimal = 0)
  955. {
  956. return number_format($number, $decimal, ",", " ");
  957. }
  958. /**
  959. * Server Maintenance (Cleaning of Galaxy, Spy reports and Logs)
  960. */
  961. function maintenance_action()
  962. {
  963. global $db, $server_config;
  964. $time = mktime(0, 0, 0);
  965. if (isset($server_config["last_maintenance_action"]) && $time > $server_config["last_maintenance_action"]) {
  966. galaxy_purge_ranking();
  967. log_purge();
  968. galaxy_purge_spy();
  969. $request = "update " . TABLE_CONFIG . " set config_value = '" . $time . "' where config_name = 'last_maintenance_action'";
  970. $db->sql_query($request);
  971. }
  972. }
  973. /**
  974. * Security Function : Variable Verification according the type(Pseudo, Password, string, number,...)
  975. * @param string $value Value of the data to check
  976. * @param string $type_check Type of the value (Pseudo_Groupname, Pseudo_ingame, Password, Text, CharNum, Char, Num, Galaxies, URL, Special)
  977. * @param string $mask Can be used to specify a Regex for the check when the type is set as Special
  978. * @param boolean $auth_null Workarround linked to the authentification
  979. * @return boolean true if the value is ok or empty and false if the checking has failed.
  980. */
  981. function check_var($value, $type_check, $mask = "", $auth_null = true)
  982. {
  983. if ($auth_null && $value == "") {
  984. return true;
  985. }
  986. switch ($type_check) {
  987. //Pseudo des membres
  988. case "Pseudo_Groupname":
  989. if (!preg_match("#^[\w\s\-]{3,15}$#", $value)) {
  990. log_("check_var", array("Pseudo_Groupname", $value));
  991. return false;
  992. }
  993. break;
  994. //Pseudo ingame
  995. case "Pseudo_ingame": // caracteres autorises entre 3 et 20 ( interdit au 05/11/11 = > &"'()# `/,;+ )
  996. if (!preg_match("#^[\w@äàçéèêëïîöôûü\^\{\}\[\]\.\*\-_~%§]{3,20}$#", $value)) {
  997. log_("check_var", array("Text", $value));
  998. return false;
  999. }
  1000. break;
  1001. //Mot de passe des membres
  1002. case "Password":
  1003. if (!preg_match("#^[\w\s\-]{6,20}$#", $value)) {
  1004. return false;
  1005. }
  1006. break;
  1007. //Chaîne de caractères avec espace
  1008. case "Text":
  1009. if (!preg_match("#^[\w'äàçéèêëïîöôûü\s\.\*\-]+$#", $value)) {
  1010. log_("check_var", array("Text", $value));
  1011. return false;
  1012. }
  1013. break;
  1014. //Chaîne de caractères et chiffre
  1015. case "CharNum":
  1016. if (!preg_match("#^[\w\.\*\-\#]+$#", $value)) {
  1017. log_("check_var", array("CharNum", $value));
  1018. return false;
  1019. }
  1020. break;
  1021. //Caractères
  1022. case "Char":
  1023. if (!preg_match("#^[[:alpha:]_\.\*\-]+$#", $value)) {
  1024. log_("check_var", array("Char", $value));
  1025. return false;
  1026. }
  1027. break;
  1028. //Chiffres
  1029. case "Num":
  1030. if (!preg_match("#^[[:digit:]]+$#", $value)) {
  1031. log_("check_var", array("Num", $value));
  1032. return false;
  1033. }
  1034. break;
  1035. //Chiffres
  1036. case "Email":
  1037. if (!preg_match('#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#', $value)) {
  1038. log_("check_var", array("Email", $value));
  1039. return false;
  1040. }
  1041. break;
  1042. //Galaxies
  1043. case "Galaxies":
  1044. if ($value < 1 || $value > 999) {
  1045. log_("check_var", array("Galaxy or system", $value));
  1046. return false;
  1047. }
  1048. break;
  1049. //Adresse internet
  1050. case "URL":
  1051. if (!preg_match("#^(((?:http?)://)?(?(2)(www\.)?|(www\.){1})?[-a-z0-9~_]{2,}(\.[-a-z0-9~._]{2,})?[-a-z0-9~_\/&\?=.]{2,})$#i",
  1052. $value)) {
  1053. log_("check_var", array("URL", $value));
  1054. return false;
  1055. }
  1056. break;
  1057. //Planète, Joueur et alliance
  1058. case "Galaxy":
  1059. // if (!preg_match("#^[\w\s\.\*\-]+$#", $value)) {
  1060. // log_("check_var", array("Galaxy", $value));
  1061. // return false;
  1062. // }
  1063. break;
  1064. //Rapport d'espionnage
  1065. case "Spyreport":
  1066. // if (!preg_match("#^[\w\s\[\]\:\-'%\.\*]+$#", $value)) {
  1067. // log_("check_var", array("Spyreport", $value));
  1068. // return false;
  1069. // }
  1070. break;
  1071. //Masque paramétrable
  1072. case "Special":
  1073. if (!preg_match($mask, $value)) {
  1074. log_("check_var", array("Special", $value));
  1075. return false;
  1076. }
  1077. break;
  1078. default:
  1079. return false;
  1080. }
  1081. return true;
  1082. }
  1083. /**
  1084. * Resets the User for imported datas.
  1085. * @param boolean $maintenance_action If true the function does not redirect the user to the raz_ration Page
  1086. */
  1087. function admin_raz_ratio($maintenance_action = false)
  1088. {
  1089. global $db, $user_data;
  1090. if ($user_data["user_admin"] != 1 && $user_data["user_coadmin"] != 1 && $user_data["management_user"] !=
  1091. 1) {
  1092. die("Acces interdit");
  1093. }
  1094. $request = "UPDATE " . TABLE_USER . " set search='0'";
  1095. $db->sql_query($request);
  1096. if (!$maintenance_action) {
  1097. redirection("index.php?action=message&id_message=raz_ratio&info");
  1098. }
  1099. }
  1100. /**
  1101. * Microtime Value formatted for benchmark functions
  1102. * @return int Current microtime
  1103. */
  1104. function benchmark()
  1105. {
  1106. $mtime = microtime();
  1107. $mtime = explode(" ", $mtime);
  1108. $mtime = $mtime[1] + $mtime[0];
  1109. return $mtime;
  1110. }
  1111. /**
  1112. * Security : HTTP GET Data verifications
  1113. * @param string $secvalue The value to be checked
  1114. * @return boolean true if the verification is ok
  1115. */
  1116. function check_getvalue($secvalue)
  1117. {
  1118. if (!is_array($secvalue)) {
  1119. if ((preg_match("/<[^>]*script*\"?[^>]*>/i", $secvalue)) || (preg_match("/<[^>]*object*\"?[^>]*>/i",
  1120. $secvalue)) || (preg_match("/<[^>]*iframe*\"?[^>]*>/i", $secvalue)) || (preg_match
  1121. ("/<[^>]*applet*\"?[^>]*>/i", $secvalue)) || (preg_match("/<[^>]*meta*\"?[^>]*>/i",
  1122. $secvalue)) || (preg_match("/<[^>]*style*\"?[^>]*>/i", $secvalue)) || (preg_match
  1123. ("/<[^>]*form*\"?[^>]*>/i", $secvalue)) || (preg_match("/<[^>]*img*\"?[^>]*>/i",
  1124. $secvalue)) || (preg_match("/\([^>]*\"?[^)]*\)/i", $secvalue)) || (preg_match("/\"/i",
  1125. $secvalue))) {
  1126. return false;
  1127. }
  1128. } else {
  1129. foreach ($secvalue as $subsecvalue) {
  1130. if (!check_getvalue($subsecvalue))
  1131. return false;
  1132. }
  1133. }
  1134. return true;
  1135. }
  1136. /**
  1137. * Security : HTTP POST Data verifications
  1138. * @param string $secvalue The value to be checked
  1139. * @return boolean true if the verification is ok
  1140. */
  1141. function check_postvalue($secvalue)
  1142. {
  1143. if (!is_array($secvalue)) {
  1144. if ((preg_match("/<[^>]*script*\"?[^>]*>/", $secvalue)) || (preg_match("/<[^>]*style*\"?[^>]*>/",
  1145. $secvalue))) {
  1146. return false;
  1147. }
  1148. } else {
  1149. foreach ($secvalue as $subsecvalue) {
  1150. if (!check_postvalue($subsecvalue))
  1151. return false;
  1152. }
  1153. }
  1154. return true;
  1155. }
  1156. //\\ fonctions utilisable pour les mods //\\
  1157. /**
  1158. * Funtion to install a new mod in OGSpy
  1159. * @param string $mod_folder : Folder name which contains the mod
  1160. * @todo Query: "SELECT title FROM " . TABLE_MOD . " WHERE title='" . $value_mod[0] ."'"."'"
  1161. * @todo Query: "INSERT INTO " . TABLE_MOD .
  1162. " (title, menu, action, root, link, version, active,admin_only) VALUES ('" . $value_mod[0] .
  1163. "','" . $value_mod[1] . "','" . $value_mod[2] . "','" . $value_mod[3] . "','" .
  1164. $value_mod[4] . "','" . $mod_version . "','" . $value_mod[5] . "','" . $value_mod[6] .
  1165. "')"
  1166. * @return boolean true if the mod has been correctly installed
  1167. * @api
  1168. */
  1169. function install_mod($mod_folder)
  1170. {
  1171. global $db,$server_config;
  1172. $is_ok = false;
  1173. $filename = 'mod/' . $mod_folder . '/version.txt';
  1174. if (file_exists($filename)) {
  1175. $file = file($filename);
  1176. }
  1177. // On récupère les données du fichier version.txt
  1178. $mod_version = trim($file[1]);
  1179. $mod_config = trim($file[2]);
  1180. //Version Minimale OGSpy
  1181. /** @var string $mod_required_ogspy */
  1182. $mod_required_ogspy = trim($file[3]);
  1183. if(isset($mod_required_ogspy)){
  1184. if (version_compare($mod_required_ogspy,$server_config["version"]) > 0 ){
  1185. log_("mod_erreur_txt_version",$mod_folder);
  1186. redirection("index.php?action=message&id_message=errormod&info");
  1187. exit();
  1188. }
  1189. }
  1190. // On explode la chaine d'information
  1191. $value_mod = explode(',', $mod_config);
  1192. // On vérifie si le mod est déjà installé""
  1193. $check = "SELECT title FROM " . TABLE_MOD . " WHERE title='" . $value_mod[0] ."'";
  1194. $query_check = $db->sql_query($check);
  1195. $result_check = $db->sql_numrows($query_check);
  1196. if ($result_check != 0) {
  1197. } else
  1198. if (count($value_mod) == 7) {
  1199. // On vérifie le nombre de valeur de l'explode
  1200. $query = "INSERT INTO " . TABLE_MOD .
  1201. " (title, menu, action, root, link, version, active,admin_only) VALUES ('" . $value_mod[0] .
  1202. "','" . $value_mod[1] . "','" . $value_mod[2] . "','" . $value_mod[3] . "','" .
  1203. $value_mod[4] . "','" . $mod_version . "','" . $value_mod[5] . "','" . $value_mod[6] .
  1204. "')";
  1205. $db->sql_query($query);
  1206. $is_ok = true; /// tout c 'est bien passe'
  1207. }
  1208. return $is_ok;
  1209. }
  1210. /**
  1211. * Function to uninstall an OGSpy Module
  1212. * @param string $mod_uninstall_name : Mod name
  1213. * @param string $mod_uninstall_table : Name of the Database table used by the Mod that we need to remove
  1214. * @todo Query: "DELETE FROM " . TABLE_MOD . " WHERE title='" . $mod_uninstall_name ."'
  1215. * @api
  1216. */
  1217. function uninstall_mod($mod_uninstall_name, $mod_uninstall_table)
  1218. {
  1219. global $db;
  1220. $db->sql_query("DELETE FROM " . TABLE_MOD . " WHERE title='" . $mod_uninstall_name ."';");
  1221. if (!empty($mod_uninstall_table)) {
  1222. $db->sql_query("DROP TABLE IF EXISTS " . $mod_uninstall_table . "");
  1223. }
  1224. }
  1225. /**
  1226. * Fonction to update the OGSpy mod
  1227. * @param string $mod_folder : Folder name which contains the mod
  1228. * @param string $mod_name : Mod name
  1229. * @todo Query: "UPDATE " . TABLE_MOD . " SET version='" . $mod_version ."' WHERE action='" . $mod_name . "'";
  1230. * @return boolean true if the mod has been correctly updated
  1231. * @api [Mod] Function to be called in the update.php file to set up the new version.
  1232. */
  1233. function update_mod($mod_folder, $mod_name)
  1234. {
  1235. global $db, $server_config;
  1236. $is_oki = false;
  1237. $filename = 'mod/' . $mod_folder . '/version.txt';
  1238. if (file_exists($filename)) {
  1239. $file = file($filename);
  1240. } else {
  1241. return $is_oki;
  1242. }
  1243. $mod_version = trim($file[1]);
  1244. //Version Minimale OGSpy
  1245. /** @var string $mod_required_ogspy */
  1246. $mod_required_ogspy = trim($file[3]);
  1247. if(isset($mod_required_ogspy)){
  1248. if (version_compare($mod_required_ogspy,$server_config["version"]) > 0 ){
  1249. log_("mod_erreur_txt_version",$mod_folder);
  1250. redirection("index.php?action=message&id_message=errormod&info");
  1251. exit();
  1252. }
  1253. }
  1254. $query = "UPDATE " . TABLE_MOD . " SET version='" . $mod_version .
  1255. "' WHERE action='" . $mod_name . "'";
  1256. $db->sql_query($query);
  1257. $is_oki = true;
  1258. return $is_oki;
  1259. }
  1260. /**
  1261. * OGSpy Hash Function
  1262. * @param string The string to Hash (usually the password)
  1263. * todo : remplacer les sha1(md5()) d'ogspy par la fonction'
  1264. * @return string Returns the hash of the input function
  1265. */
  1266. function crypto($str)
  1267. {
  1268. return md5(sha1($str));
  1269. }
  1270. /**
  1271. * OGSpy Key Generator : This key will be the unique id of the current OGSpy installation.
  1272. *
  1273. * The current OGSpy Key is written in a file named parameters/key.php
  1274. */
  1275. function generate_key()
  1276. {
  1277. //création de la clef
  1278. $str = "abcdefghijklmnopqrstuvwxyzABCDEVGHIJKLMOPQRSTUVWXYZ";
  1279. srand((double)microtime() * 1000000);
  1280. $pass = time();
  1281. for ($i = 0; $i < 20; $i++) {
  1282. $pass .= $str[rand() % strlen($str)];
  1283. }
  1284. $key = crypto($pass);
  1285. // création du path
  1286. $path = $_SERVER["SCRIPT_FILENAME"];;
  1287. $key_php[] = '<?php';
  1288. $key_php[] = '/***************************************************************************';
  1289. $key_php[] = '* filename : key.php';
  1290. $key_php[] = '* generated : ' . date("d/M/Y H:i:s");
  1291. $key_php[] = '***************************************************************************/';
  1292. $key_php[] = '';
  1293. $key_php[] = 'if (!defined("IN_SPYOGAME")) die("Hacking attempt");';
  1294. $key_php[] = '';
  1295. $key_php[] = '//Paramètres unique a ne pas communiquer';
  1296. $key_php[] = '$serveur_key = "' . $key . '";';
  1297. $key_php[] = '$serveur_date = "' . time() . '";';
  1298. $key_php[] = '$serveur_path = "' . $path . '";';
  1299. $key_php[] = '';
  1300. $key_php[] = 'define("OGSPY_KEY", TRUE);';
  1301. $key_php[] = '?>';
  1302. if (!write_file("./parameters/key.php", "w", $key_php)) {
  1303. die("Echec , impossible de générer le fichier 'parameters/key.php'");
  1304. }
  1305. }
  1306. /***********************************************************************
  1307. ************** Fonctions pour table Google Cloud Messaging ************
  1308. ***********************************************************************/
  1309. /** Storing new GCM user
  1310. * @return : user true or false
  1311. */
  1312. function storeGCMUser($name,$gcm_regid) {
  1313. global $db;
  1314. $user_id = "0";
  1315. $result = $db->sql_query("SELECT user_id FROM " . TABLE_USER . " WHERE user_name = '" . $name . "' OR user_stat_name = '" . $name . "'");
  1316. $nbGcmUsers = $db->sql_numrows("SELECT * FROM " . TABLE_GCM_USERS . " WHERE gcm_regid = '" . $gcm_regid . "'");
  1317. while (list($userid) = $db->sql_fetch_row($result)) {
  1318. $user_id = $userid;
  1319. }
  1320. //return "Nombre de users GCM = " . $nbGcmUsers;
  1321. if($nbGcmUsers == 0){
  1322. // insert user into database
  1323. $result = $db->sql_query("INSERT INTO " . TABLE_GCM_USERS . "(user_id, gcm_regid, created_at) VALUES('" . $user_id ."' , '" . $gcm_regid . "', NOW())");
  1324. // check for successful store
  1325. if ($result) {
  1326. return 1;
  1327. } else {
  1328. return 0;
  1329. }
  1330. } else {
  1331. return -1;
  1332. }
  1333. }
  1334. /** Storing new GCM user
  1335. * @return : user true or false
  1336. */
  1337. function deleteGCMUser($gcm_regid) {
  1338. global $db;
  1339. // delete user in database
  1340. $result = $db->sql_query("DELETE FROM " . TABLE_GCM_USERS . " WHERE gcm_regid = '" . $gcm_regid . "'");
  1341. // check for successful store
  1342. if ($result) {
  1343. return true;
  1344. } else {
  1345. return false;
  1346. }
  1347. }
  1348. /**
  1349. * Getting all GCM users
  1350. */
  1351. function getAllGCMUsers() {
  1352. global $db;
  1353. $query = "SELECT gcm.user_id AS user_id, users.user_name AS name, users.user_stat_name AS name2, users.user_email AS email, gcm.gcm_regid AS gcm_regid, gcm.created_at AS created_at, gcm.version_android AS version_android, gcm.version_ogspy AS version_ogspy, gcm.device AS device ".
  1354. "FROM " . TABLE_GCM_USERS . " gcm ".
  1355. "INNER JOIN " . TABLE_USER . " users ON users.user_id = gcm.user_id";
  1356. return $db->sql_query($query);
  1357. }
  1358. /**
  1359. * Getting all GCM users but not me
  1360. */
  1361. function getAllGCMUsersExceptMe($id) {
  1362. global $db;
  1363. $query = "SELECT gcm_regid ".
  1364. "FROM " . TABLE_GCM_USERS .
  1365. " WHERE gcm_regid != '" . $id ."'";
  1366. return $db->sql_query($query);
  1367. }
  1368. /**
  1369. * Calcule la distance entre a et b, a - b ; en tenant en compte des univers arrondis.
  1370. * type = Représente le type de distance à calculer
  1371. * 0 : Galaxie
  1372. * 1 : Système
  1373. * 2 : Planète
  1374. * typeArrondi = true pour un univers arrondi selon le type donnée
  1375. */
  1376. function calc_distance($a, $b, $type, $typeArrondi = false) {//a-b
  1377. global $server_config;
  1378. $max_type = 0;
  1379. switch($type){
  1380. case 0: //Galaxy
  1381. $max_type = $server_config['num_of_galaxies']; //9
  1382. break;
  1383. case 1: //System
  1384. $max_type = $server_config['num_of_systems']; //499
  1385. break;
  1386. }
  1387. if($typeArrondi) {
  1388. if(abs($a - $b) < $max_type/2) {
  1389. return abs($a - $b);//|a-b|
  1390. } else {
  1391. return abs(abs($a - $b) - $max_type); //||a-b| - base|
  1392. }
  1393. } else {
  1394. return abs($a - $b);//|a-b|
  1395. }
  1396. }
  1397. /********************************************************************************/
  1398. /** Booster partie **/
  1399. /* Description :
  1400. "m:0:0_c:0:0_d:0:0_p:0_m:0" =>booster_m;booster_c;booster_d;extension_p;extension_moon
  1401. booster_x => ressource:%:date_de_fin (ressource= m|c|d)
  1402. extension_x => type:+" (type= p|m)
  1403. "m:0:0_c:0:0_d:0:0_p:0_m:0" = string de stockage par défaut
  1404. */
  1405. /*##Base de donnée ##*/
  1406. /* Lit les informations des objets Ogame dans la BDD et les transformes en un tableau
  1407. * @arg id_player id du joueur
  1408. * @arg id_planet id de la planète à rechercher
  1409. * @return tableau associatif des boosters ou NULL en cas d'échec
  1410. * array('booster_m_val', 'booster_m_date', 'booster_c_val', 'booster_c_date', 'booster_c_val', 'booster_c_date', 'extention_p', 'extention_m')
  1411. */
  1412. function booster_lire_bdd($id_player, $id_planet){
  1413. global $db;
  1414. $result = NULL;
  1415. $request = "SELECT boosters FROM ".TABLE_USER_BUILDING." WHERE user_id=".$id_player." AND planet_id=".$id_planet;
  1416. $res = $db->sql_query($request);
  1417. if($res) {
  1418. $str = $db->sql_fetch_row($res);
  1419. if($str){
  1420. return booster_decode($str[0]);
  1421. }
  1422. }
  1423. return $result;
  1424. }
  1425. /* Écrit la string de stockage des objets Ogame dans la BDD.
  1426. * @arg id_player id du joueur
  1427. * @arg id_planet id de la planète à rechercher
  1428. * @str_booster string de stockage des boosters (donnée par les fonctions booster_encode() ou booster_encodev())
  1429. * @return FALSE en cas d'échec
  1430. */
  1431. function booster_ecrire_bdd_str($id_player, $id_planet, $str_booster){
  1432. global $db;
  1433. $request = "UPDATE ".TABLE_USER_BUILDING." SET boosters='".$str_booster."' WHERE user_id=".$id_player." AND planet_id=".$id_planet;
  1434. return $db->sql_query($request);
  1435. }
  1436. /* Écrit les informations des objets Ogame dans la BDD sous forme d'une string de stockage.
  1437. * @arg id_player id du joueur
  1438. * @arg id_planet id de la planète à rechercher
  1439. * @tab_booster tableau infos des boosters (donnée par les fonctions booster_lire_bdd() ou booster_decode())
  1440. * @return FALSE en cas d'échec
  1441. */
  1442. function booster_ecrire_bdd_tab($id_player, $id_planet, $tab_booster){
  1443. return booster_ecrire_bdd_str($id_player, $id_planet, booster_encode($tab_booster));
  1444. }
  1445. /* Mets à jour les boosters de tous les users en fonction de la date de fin dans la BDD
  1446. *
  1447. */
  1448. function booster_maj_bdd(){
  1449. global $db;
  1450. $request = "SELECT user_id, planet_id, boosters FROM ".TABLE_USER_BUILDING;
  1451. $res = $db->sql_query($request);
  1452. if($res) {
  1453. $requests = array();
  1454. while($row = $db->sql_fetch_assoc($res)) {
  1455. $tmp = booster_verify_str($row['boosters']);
  1456. if($tmp !== $row['boosters']) {
  1457. $row['boosters'] = $tmp;
  1458. $requests[] = "UPDATE ".TABLE_USER_BUILDING." SET boosters = '".$row['boosters']."' ".
  1459. " WHERE user_id = ".$row['user_id'].
  1460. " AND planet_id = ".$row['planet_id'];
  1461. }
  1462. }
  1463. foreach ($requests as $request) {
  1464. $db->sql_query($request);
  1465. }
  1466. }
  1467. }
  1468. /*#######Contrôles et modifications poussées #######*/
  1469. /* Contrôle la date de validité des boosters et reset si la date est dépassée
  1470. * @param $boosters tableau infos des boosters (donnée par les fonctions booster_lire_bdd() ou booster_decode())
  1471. * @return tableau associatif des boosters mis à jour
  1472. * array('booster_m_val', 'booster_m_date', 'booster_c_val', 'booster_c_date', 'booster_d_val', 'booster_d_date', 'extention_p', 'extention_m')
  1473. */
  1474. function booster_verify($boosters) {
  1475. $b_control = array('booster_m_', 'booster_c_', 'booster_d_');
  1476. $current_time = time();
  1477. foreach($b_control as $b) {
  1478. if($boosters[$b.'date'] <= $current_time) {
  1479. $boosters[$b.'val'] = 0;
  1480. $boosters[$b.'date'] = 0;
  1481. }
  1482. }
  1483. return $boosters;
  1484. }
  1485. /* Contrôle la date de validité des boosters et reset si la date est dépassée
  1486. * @param $str string de stockage des boosters (donnée par les fonctions booster_encode() ou booster_encodev() ou directement from BDD)
  1487. * @return tableau associatif des boosters mis à jour
  1488. * array('booster_m_val', 'booster_m_date', 'booster_c_val', 'booster_c_date', 'booster_d_val', 'booster_d_date', 'extention_p', 'extention_m')
  1489. */
  1490. function booster_verify_str($str) {
  1491. return booster_encode(booster_verify(booster_decode($str)));
  1492. }
  1493. /* donne des tableaux d'informations en relation avec les objets Ogame
  1494. * @type détermine les informations renvoyées
  1495. * [Default] donne un tableau avec les uuid des objets Ogame
  1496. * 'definition' donne un tableau avec le nom de l'objet (ex. 'Booster de métal en or')
  1497. * 'array' donne un tableau asso de tab uuid=>array('booster_x'|'extension_x', valeur)
  1498. * 'string' donne un tableau asso de string uuid=>'x:valeur:0'|'x:valeur'
  1499. * 'full' donne les tableaux simple : définition, uuid, string, array)
  1500. * 'separateur' donne le char qui sert de séparateur entre les objets Ogame
  1501. * 'default_str' donne la string de stockage par défaut : "m:0:0_c:0:0_d:0:0_p:0_m:0"
  1502. * @return le tableau correspondant au type
  1503. */
  1504. function booster_objets_tab($type='') {
  1505. $objet_str = array('Booster de métal en or' ,'Booster de métal en argent' ,'Booster de métal en bronze',
  1506. 'Booster de cristal en or' ,'Booster de cristal en argent' ,'Booster de cristal en bronze',
  1507. 'Booster de deutérium en or','Booster de deutérium en argent','Booster de deutérium en bronze',
  1508. 'Extension planétaire en or','Extension planétaire en argent','Extension planétaire en bronze',
  1509. 'Extension lunaire en or' ,'Extension lunaire en argent' ,'Extension lunaire en bronze');
  1510. $objet_uuid = array('05294270032e5dc968672425ab5611998c409166',//'Booster de métal +30%'
  1511. 'ba85cc2b8a5d986bbfba6954e2164ef71af95d4a',//'Booster de métal +20%'
  1512. 'de922af379061263a56d7204d1c395cefcfb7d75',//'Booster de métal +10%'
  1513. '118d34e685b5d1472267696d1010a393a59aed03',//'Booster de cristal +30%'
  1514. '422db99aac4ec594d483d8ef7faadc5d40d6f7d3',//'Booster de cristal +20%'
  1515. '3c9f85221807b8d593fa5276cdf7af9913c4a35d',//'Booster de cristal +10%'
  1516. '5560a1580a0330e8aadf05cb5bfe6bc3200406e2',//'Booster de deutérium +30%'
  1517. 'e4b78acddfa6fd0234bcb814b676271898b0dbb3',//'Booster de deutérium +20%'
  1518. 'd9fa5f359e80ff4f4c97545d07c66dbadab1d1be',//'Booster de deutérium +10%'
  1519. '04e58444d6d0beb57b3e998edc34c60f8318825a',//'Extension planétaire +15'
  1520. '0e41524dc46225dca21c9119f2fb735fd7ea5cb3',//'Extension planétaire +9'
  1521. '16768164989dffd819a373613b5e1a52e226a5b0',//'Extension planétaire +4'
  1522. '05ee9654bd11a261f1ff0e5d0e49121b5e7e4401',//'Extension lunaire +6'
  1523. 'c21ff33ba8f0a7eadb6b7d1135763366f0c4b8bf',//'Extension lunaire +4'
  1524. 'be67e009a5894f19bbf3b0c9d9b072d49040a2cc');//'Extension lunaire +2'
  1525. $objet_uuid_str = array('m:30:0','m:20:0','m:10:0','c:30:0','c:20:0','c:10:0','d:30:0','d:20:0','d:10:0','p:15','p:9','p:4','m:6','m:4','m:2');
  1526. $objet_uuid_tab = array(array('booster_m', 30),array('booster_m', 20),array('booster_m', 10),
  1527. array('booster_c', 30),array('booster_c', 20),array('booster_c', 10),
  1528. array('booster_d', 30),array('booster_d', 20),array('booster_d', 10),
  1529. array('extention_p', 15),array('extention_p', 9),array('extention_p', 4),
  1530. array('extention_m', 6),array('extention_m', 4),array('extention_m', 2));
  1531. $separateur = '_';
  1532. $default_str = array('m:0:0', 'c:0:0', 'd:0:0', 'p:0', 'm:0');
  1533. switch($type) {
  1534. case 'definition':
  1535. return $objet_str;
  1536. case 'array':
  1537. $n = count($objet_uuid);
  1538. for($i=0 ; $i<$n ; $i++) {
  1539. $result[$objet_uuid[$i]] = $objet_uuid_tab[$i];
  1540. }
  1541. return $result;
  1542. case 'string':
  1543. $n = count($objet_uuid);
  1544. for($i=0 ; $i<$n ; $i++) {
  1545. $result[$objet_uuid[$i]] = $objet_uuid_str[$i];
  1546. }
  1547. return $result;
  1548. case 'full':
  1549. return array($objet_str, $objet_uuid, $objet_uuid_str, $objet_uuid_tab);
  1550. case 'separateur':
  1551. return $separateur;
  1552. case 'default_str':
  1553. return implode($separateur, $default_str);
  1554. default:
  1555. return $objet_uuid;
  1556. }
  1557. }
  1558. /* Indique si un uuid est enregistré dans OGSpy (il existe)
  1559. * @uuid string uuid récupéré de la page Ogame
  1560. */
  1561. function booster_is_uuid($uuid) {
  1562. return in_array($uuid, booster_objets_tab());
  1563. }
  1564. /* Mets à jour le tableau infos des boosters.
  1565. * @boosters tableau infos des boosters (donnée par les fonctions booster_lire_bdd() ou booster_decode())
  1566. * @uuid string uuid de l'objet Ogame récupéré de la page Ogame
  1567. * @date date de fin de l'objet Ogame. [defaut=0]
  1568. * return le tableau à jour (par uuid et date)
  1569. * si $boosters==NULL OU booster_uuid($b) sans uuid -> donne tableau avec valeurs par défaut (équivalent booster_decode())
  1570. * NULL en cas d'erreur (uuid inconnu)
  1571. */
  1572. function booster_uuid($boosters, $uuid='', $date=0) {
  1573. if($boosters==NULL || $uuid=='') {
  1574. $boosters = booster_decode();
  1575. return $boosters;
  1576. } else {
  1577. $objet_uuid = booster_objets_tab('array');
  1578. //if(isset($objet_uuid[$uuid]) || array_key_exists($uuid, $objet_uuid)) {
  1579. if(isset($objet_uuid[$uuid])) {
  1580. if($objet_uuid[$uuid][0][0] == 'b') { //1er lettre de booster
  1581. $boosters[$objet_uuid[$uuid][0].'_val'] = $objet_uuid[$uuid][1];
  1582. $boosters[$objet_uuid[$uuid][0].'_date'] = $date;
  1583. } elseif($objet_uuid[$uuid][0][0] == 'e') { //1er lettre de extension
  1584. $boosters[$objet_uuid[$uuid][0]] = $objet_uuid[$uuid][1];
  1585. } else { return NULL;} //Ne devrait jamais arriver si les tableaux dans booster_objets_tab() sont bien construit
  1586. return $boosters;
  1587. }
  1588. }
  1589. return NULL;
  1590. }
  1591. /* Transforme la date Ogame de format "*s *j *h *m *s" en nombre de seconde
  1592. * @str string contenant le temps
  1593. * @return int nombre de seconde correspondant à $str. 0 si problème
  1594. */
  1595. function booster_lire_date($str) {
  1596. static $tri = array( 's', 'j', 'h', 'm', 's');
  1597. static $num = array(604800, 86400, 3600, 60, 1);
  1598. static $n = 5;
  1599. $result = 0;
  1600. $j = $n-1; //Lecture de droite à gauche on démarre par les secondes.
  1601. $parts = sscanf($str, '%d%c %d%c %d%c %d%c %d%c');
  1602. for($i=$n-1 ; $i >= 0 ; $i--) {
  1603. $car = $parts[$i*2+1]; //%c
  1604. $valeur = $parts[$i*2]; //%d
  1605. if(!is_null($car)) {
  1606. if($car == $tri[$j]){
  1607. $result += $valeur * $num[$j--];
  1608. }
  1609. }
  1610. }
  1611. return $result;
  1612. }
  1613. /*#######Lecture et modifications poussées #######*/
  1614. /* Transforme en tableau les données des objets Ogame contenues dans une string de stockage.
  1615. * Si aucun argument n'ai donné alors elle renvoie les valeurs des objets par défaut.
  1616. * @param $str string de stockage des objets Ogame
  1617. * @return tableau contenant les informations des objets
  1618. * array('booster_m_val', 'booster_m_date', 'booster_c_val', 'booster_c_date', 'booster_c_val', 'booster_c_date', 'extention_p', 'extention_m')
  1619. */
  1620. function booster_decode($str=NULL, &$boosters=NULL) {
  1621. if($str) {
  1622. $s = booster_objets_tab('separateur');
  1623. $a = preg_match("/m:(\d+):(\d+)".$s."c:(\d+):(\d+)".$s."d:(\d+):(\d+)".$s."p:(\d+)".$s."m:(\d+)/", $str, $boosters);
  1624. if($a) {
  1625. $i = 1;
  1626. return array('booster_m_val'=>intval($boosters[$i++]), 'booster_m_date'=>intval($boosters[$i++]),
  1627. 'booster_c_val'=>intval($boosters[$i++]), 'booster_c_date'=>intval($boosters[$i++]),
  1628. 'booster_d_val'=>intval($boosters[$i++]), 'booster_d_date'=>intval($boosters[$i++]),
  1629. 'extention_p'=>intval($boosters[$i++]), 'extention_m'=>intval($boosters[$i++]));
  1630. }
  1631. }
  1632. return array('booster_m_val'=>0, 'booster_m_date'=>0,
  1633. 'booster_c_val'=>0, 'booster_c_date'=>0,
  1634. 'booster_d_val'=>0, 'booster_d_date'=>0,
  1635. 'extention_p'=>0, 'extention_m'=>0);
  1636. }
  1637. /* Transforme le tableau des informations des objets Ogame en une string de stockage.
  1638. * @b tableau associatif des infos array('booster_m_val', 'booster_m_date', 'booster_c_val', 'booster_c_date', 'booster_c_val', 'booster_c_date', 'extention_p', 'extention_m')
  1639. * @return objet sous format string de stockage ("m:0:0_c:0:0_d:0:0_p:0_m:0 si pas d'argument)
  1640. */
  1641. function booster_encode($b=NULL) {
  1642. $str = '';
  1643. if($b){
  1644. $separateur= booster_objets_tab('separateur');
  1645. $str .= 'm:'.$b['booster_m_val'].':'.$b['booster_m_date'].$separateur;
  1646. $str .= 'c:'.$b['booster_c_val'].':'.$b['booster_c_date'].$separateur;
  1647. $str .= 'd:'.$b['booster_d_val'].':'.$b['booster_d_date'].$separateur;
  1648. $str .= 'p:'.$b['extention_p'].$separateur;
  1649. $str .= 'm:'.$b['extention_m'];
  1650. } else {
  1651. $str = booster_objets_tab('default_str');//"m:0:0_c:0:0_d:0:0_p:0_m:0";
  1652. }
  1653. return $str;
  1654. }
  1655. /* Transforme les valeurs des objets Ogame en une string de stockage.
  1656. * string de stockage par défaut = m:0:0_c:0:0_d:0:0_p:0_m:0
  1657. * @return objet sous format string de stockage ("m:0:0_c:0:0_d:0:0_p:0_m:0" si pas d'argument)
  1658. */
  1659. function booster_encodev($booster_m_val=0, $booster_m_date=0, $booster_c_val=0, $booster_c_date=0,
  1660. $booster_d_val=0, $booster_d_date=0, $extention_p=0, $extention_m=0) {
  1661. $separateur= booster_objets_tab('separateur');
  1662. $str = '';
  1663. $str .= 'm:'.$booster_m_val.':'.$booster_m_date.$separateur;
  1664. $str .= 'c:'.$booster_c_val.':'.$booster_c_date.$separateur;
  1665. $str .= 'd:'.$booster_d_val.':'.$booster_d_date.$separateur;
  1666. $str .= 'p:'.$extention_p.$separateur;
  1667. $str .= 'm:'.$extention_m;
  1668. return $str;
  1669. }
  1670. /** Fin booster partie **/
  1671. /********************************************************************************/
  1672. ?>