functions.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. <?php
  2. /*
  3. *
  4. * OGP - Open Game Panel
  5. * Copyright (C) 2008 - 2018 The OGP Development Team
  6. *
  7. * http://www.opengamepanel.org/
  8. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public License
  11. * as published by the Free Software Foundation; either version 2
  12. * of the License, or any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. *
  23. */
  24. #functions go here
  25. //read_expire() converts a time stamp to a human readable form
  26. //Used as a count down to when the user's account expires
  27. //Example would be User's account expires in 200 days, 20 hours, 18 minutes
  28. function read_expire($endtime)
  29. {
  30. #Feed the user's expire time stamp to this, and it returns a human readable date
  31. if($endtime == 'X')
  32. {
  33. $timediff = 'X';
  34. return $timediff;
  35. }
  36. //Thanks to manhon824 at gmail dot com - found on http://us2.php.net/manual/en/function.mktime.php
  37. $starttime=time();
  38. // the start time can change to =strtotime($endtime);
  39. //$endtime=strtotime($expires);
  40. // $endtime = $expires;
  41. //$endtime can be any format as well as it can be converted to secs
  42. $timediff = $endtime-$starttime;
  43. $days=intval($timediff/86400);
  44. $remain=$timediff%86400;
  45. $hours=intval($remain/3600);
  46. $remain=$remain%3600;
  47. $mins=intval($remain/60);
  48. $secs=$remain%60;
  49. //this code is copied from the other note!thx to that guy!
  50. $stampdiff = $timediff;
  51. $timediff=$days.' days '.$hours.' hr '.$mins.' min ';
  52. return $timediff;
  53. }
  54. function genRandomString($length) {
  55. $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
  56. $string = "";
  57. for ($p = 0; $p < $length; $p++) {
  58. $string .= $characters[mt_rand(0, strlen($characters)-1)];
  59. }
  60. return $string;
  61. }
  62. function get_map_path($query_name,$mod,$map) {
  63. $mod_gt = $mod;
  64. if($mod == "cstrike")
  65. {
  66. if ($query_name == "halflife")
  67. $mod_gt = "cs";
  68. elseif($query_name == "source")
  69. $mod_gt = "css";
  70. }
  71. if($mod == "tf")
  72. {
  73. if ($query_name == "halflife")
  74. $mod_gt = "tf";
  75. elseif($query_name == "source")
  76. $mod_gt = "tf2";
  77. }
  78. $mod_gt = $mod == "fof" ? "hl2dm" : $mod_gt;
  79. $mod_gt = $mod == "insurgency" ? "ins" : $mod_gt;
  80. $mod_gt = $mod == "redorchestra2" ? "ro2" : $mod_gt;
  81. $mod_gt = $mod == "killingfloor2" ? "kf2" : $mod_gt;
  82. $mod_gt = $query_name == "7dtd" ? "7daystodie" : $mod_gt;
  83. $mod_gt = $query_name == "callofduty" ? "cod" : $mod_gt;
  84. $mod_gt = $query_name == "callofdutyuo" ? "uo" : $mod_gt;
  85. $mod_gt = $query_name == "callofduty2" ? "cod2" : $mod_gt;
  86. $mod_gt = $query_name == "callofduty4mw" ? "cod4" : $mod_gt;
  87. $mod_gt = $query_name == "callofdutywaw" ? "codww" : $mod_gt;
  88. $mod_gt = $query_name == "callofdutymw3" ? "mw3" : $mod_gt;
  89. $mod_gt = $query_name == "conanexiles" ? "conan" : $mod_gt;
  90. $map_paths= array(
  91. "https://image.gametracker.com/images/maps/160x120/$mod_gt/$map.jpg",
  92. "https://image.gametracker.com/images/maps/160x120/$query_name/$map.jpg",
  93. "protocol/lgsl/maps/$query_name/$mod/$map.jpg",
  94. "protocol/lgsl/maps/$query_name/$mod/$map.gif",
  95. "protocol/lgsl/maps/$query_name/$mod/$map.png",
  96. "protocol/lgsl/maps/$query_name/$map.jpg",
  97. "protocol/lgsl/maps/$query_name/$map.gif",
  98. "protocol/lgsl/maps/$query_name/$map.png",
  99. "images/online_big.png"
  100. );
  101. return get_first_existing_file($map_paths, 'http://gametracker.com', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0');
  102. }
  103. // Thanks adjo (http://opengamepanel.org/forum/viewthread.php?thread_id=5209#post_25073)
  104. function curlCacheImage($cachePath, $resource){
  105. if(preg_match('/^(https?:\/\/)/', $resource)){
  106. $map = explode('/', $resource);
  107. if(!file_exists($cachePath . '/cache/' . end($map))){
  108. $ch = curl_init();
  109. curl_setopt($ch, CURLOPT_HEADER, 0);
  110. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  111. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0');
  112. curl_setopt($ch, CURLOPT_REFERER, 'http://gametracker.com');
  113. curl_setopt($ch, CURLOPT_URL, $resource);
  114. $result = curl_exec($ch);
  115. curl_close($ch);
  116. file_put_contents($cachePath . '/cache/' . end($map), $result);
  117. }
  118. return $cachePath . '/cache/' . end($map);
  119. }
  120. return $resource;
  121. }
  122. //Refreshed Div:
  123. //Below is under construction:
  124. // Usage: $data .= PopupData($id);
  125. // PopupBuild($data);
  126. function PopupTrigger($id){
  127. return "<a href='#' class='ex".$id."trigger'></a>";
  128. }
  129. function PopupData($id,$link){//Trigger: ex($id)trigger
  130. return "$('#ex".$id."').jqm({ajax: '$link', trigger: 'a.ex".$id."trigger'});";
  131. }
  132. function PopupBuild($data){
  133. return "<script type='text/javascript'>$(document).ready(function()\{".$data."\});</script>";
  134. }
  135. function create_home_selector($module, $subpage, $server_homes) {
  136. if ($server_homes == "show_all")
  137. {
  138. echo "<form method='GET' action=''>\n";
  139. echo "<input type='hidden' name='m' value='".$module."' />\n";
  140. if( $subpage ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  141. echo "<input type='SUBMIT' value='" . get_lang('show_all') . "'/>\n";
  142. echo "</form>\n";
  143. }
  144. else
  145. {
  146. foreach ($server_homes as $key => $row) {
  147. $home_name[$key] = $row['home_name'];
  148. $home_id[$key] = $row['home_id'];
  149. $mod_id[$key] = $row['home_id'];
  150. $ip[$key] = $row['ip'];
  151. $port[$key] = $row['port'];
  152. }
  153. array_multisort($home_name, $ip, $port, $mod_id, $home_id, SORT_DESC, $server_homes);
  154. echo "<form method='GET' name='select' action=''>\n";
  155. echo "<input type='hidden' name='m' value='".$module."' />\n";
  156. if( $subpage ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  157. echo "<select onchange=".'"this.form.submit()"'." name='home_id'>\n";
  158. echo "<option></option>\n";
  159. foreach ( $server_homes as $server_home )
  160. {
  161. if( isset( $_GET['home_id'] ) and $_GET['home_id'] == $server_home['home_id'] )
  162. $selected = 'selected="selected"';
  163. else
  164. $selected = '';
  165. echo "<option value='". $server_home['home_id'] . "' $selected >" . htmlentities($server_home['home_name']) . "</option>\n";
  166. }
  167. echo "</select>\n";
  168. echo "</form>";
  169. }
  170. }
  171. function create_home_selector_address($module, $subpage, $server_homes, $extra_inputs = FALSE, $method = "GET") {
  172. if( isset($_GET['home_id-mod_id-ip-port']) and $_GET['home_id-mod_id-ip-port'] != "" )
  173. {
  174. list($get_home_id,
  175. $get_mod_id,
  176. $get_ip,
  177. $get_port) = explode( "-", $_GET['home_id-mod_id-ip-port'] );
  178. }
  179. echo "<form method='$method' name='select' action=''>\n";
  180. echo "<input type='hidden' name='m' value='$module' />\n";
  181. if( $subpage ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  182. if($extra_inputs)
  183. {
  184. foreach($extra_inputs as $input)
  185. {
  186. echo "<input type='$input[type]' name='$input[name]' value='$input[value]' />\n";
  187. }
  188. }
  189. echo "<select onchange=\"this.form.submit();\" name='home_id-mod_id-ip-port'>\n";
  190. echo "<option></option>\n";
  191. foreach ($server_homes as $key => $row) {
  192. if( !isset($row['ip']) or !isset($row['mod_id']) )
  193. {
  194. unset($server_homes[$key]);
  195. continue;
  196. }
  197. $home_name[$key] = $row['home_name'];
  198. $home_id[$key] = $row['home_id'];
  199. $mod_id[$key] = $row['home_id'];
  200. $ip[$key] = $row['ip'];
  201. $port[$key] = $row['port'];
  202. }
  203. array_multisort($home_name, $ip, $port, $mod_id,
  204. $home_id, SORT_DESC, $server_homes);
  205. foreach ( $server_homes as $server_home )
  206. {
  207. $display_ip = checkDisplayPublicIP($server_home['display_public_ip'],$server_home['ip'] != $server_home['agent_ip'] ? $server_home['ip'] : $server_home['agent_ip']);
  208. if(isset($_GET['home_id-mod_id-ip-port']) and
  209. $get_home_id == $server_home['home_id'] and
  210. $get_mod_id == $server_home['mod_id'] and
  211. $get_ip == $server_home['ip'] and
  212. $get_port == $server_home['port'])
  213. $selected = 'selected="selected"';
  214. else
  215. $selected = '';
  216. echo "<option value='". $server_home['home_id'] .
  217. "-" . $server_home['mod_id'] . "-" . $server_home['ip'] .
  218. "-" . $server_home['port'] . "' $selected >" .
  219. htmlentities($server_home['home_name']) . " - " . $display_ip .
  220. ":" . $server_home['port'] . "</option>\n";
  221. }
  222. echo "</select>\n";
  223. echo "</form>";
  224. }
  225. function create_home_selector_game_type($module, $subpage, $server_homes) {
  226. echo "<form method='GET' name='select' action=''>\n".
  227. "<input type='hidden' name='m' value='".$module."' />\n";
  228. if( $subpage != "" ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  229. echo "<select onchange=".'"this.form.submit()"'." name='home_cfg_id'>\n".
  230. "<option>".get_lang('game_type')."</option>\n";
  231. $servers_by_game_name = array();
  232. foreach( $server_homes as $server_home )
  233. {
  234. if( !isset($server_home['ip']) or !isset($server_home['mod_id']) )
  235. continue;
  236. $servers_by_game_name["$server_home[game_name]"] = $server_home['home_cfg_id'];
  237. }
  238. ksort($servers_by_game_name);
  239. foreach( $servers_by_game_name as $game_name => $home_cfg_id )
  240. {
  241. $selected = (isset($_GET['home_cfg_id']) and $_GET['home_cfg_id'] == $home_cfg_id) ? 'selected="selected"' : "";
  242. echo "<option value='". $home_cfg_id . "' $selected >" . $game_name . "</option>\n";
  243. }
  244. echo "</select>\n</form>\n";
  245. }
  246. function mymail($email_address, $subject, $message, $panel_settings, $user_to_panel = FALSE){
  247. global $view;
  248. if( empty( $panel_settings['panel_name'] ) )
  249. $panel_name = "Open Game Panel";
  250. else
  251. $panel_name = $panel_settings['panel_name'];
  252. // PHP Mailer
  253. require_once("PHPMailer/class.phpmailer.php");
  254. require_once("PHPMailer/class.smtp.php");
  255. // Create the mail object using the Mail::factory method
  256. $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
  257. $mail->IsSMTP(); // telling the class to use SMTP
  258. $mymail = TRUE;
  259. try
  260. {
  261. $mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
  262. // 1 = errors and messages
  263. // 2 = messages only
  264. // SMTP server
  265. if (isset($panel_settings['smtp_server']) and !empty($panel_settings['smtp_server']))
  266. $mail->Host = $panel_settings['smtp_server'];
  267. else
  268. $mail->Host = 'localhost';
  269. // set the SMTP port
  270. if (isset($panel_settings['smtp_port']) and !empty($panel_settings['smtp_port']))
  271. $mail->Port = $panel_settings['smtp_port'];
  272. else
  273. $mail->Port = 25;
  274. // sets the prefix to the servier
  275. if (isset($panel_settings['smtp_ssl']) and $panel_settings['smtp_ssl'] == 1)
  276. $mail->SMTPSecure = "ssl";
  277. elseif (isset($panel_settings['smtp_tls']) and $panel_settings['smtp_tls'] == 1)
  278. $mail->SMTPSecure = "tls";
  279. if (isset($panel_settings['smtp_login']) and !empty($panel_settings['smtp_login']))
  280. {
  281. // enable SMTP authentication
  282. $mail->SMTPAuth = true;
  283. // SMTP username
  284. $mail->Username = $panel_settings['smtp_login'];
  285. if (isset($panel_settings['smtp_passw']) and !empty($panel_settings['smtp_passw']))
  286. {
  287. // SMTP password
  288. $mail->Password = $panel_settings['smtp_passw'];
  289. }
  290. }
  291. if(empty($panel_settings['panel_email_address'])){
  292. $panel_email = "[email protected]";
  293. }else{
  294. $panel_email = $panel_settings['panel_email_address'];
  295. }
  296. $email_addresses = explode( ",", $email_address );
  297. if( $user_to_panel )
  298. {
  299. $mail->AddAddress($panel_email);
  300. $user_to_panel = is_bool($user_to_panel) ? "" : $user_to_panel; // True boolean or user name string
  301. foreach ( $email_addresses as $address )
  302. {
  303. $mail->SetFrom($address,$user_to_panel);
  304. $mail->AddReplyTo($address,$user_to_panel);
  305. }
  306. }
  307. else // panel to user
  308. {
  309. foreach ( $email_addresses as $address )
  310. {
  311. $mail->AddAddress($address);
  312. }
  313. $mail->SetFrom($panel_email,$panel_name);
  314. $mail->AddReplyTo($panel_email,$panel_name);
  315. }
  316. $mail->CharSet = $view->charset;
  317. $mail->Subject = $subject;
  318. $mail->MsgHTML($message);
  319. $mail->SMTPOptions = array(
  320. 'ssl' => array(
  321. 'verify_peer' => false,
  322. 'verify_peer_name' => false,
  323. 'allow_self_signed' => true
  324. )
  325. );
  326. $mail->Send();
  327. }
  328. catch (phpmailerException $e)
  329. {
  330. $mymail = FALSE;
  331. echo $e->errorMessage(); //Pretty error messages from PHPMailer
  332. }
  333. catch (Exception $e)
  334. {
  335. $mymail = FALSE;
  336. echo $e->getMessage(); //Boring error messages from anything else!
  337. }
  338. return $mymail;
  339. }
  340. if( !function_exists("sys_get_temp_dir") )
  341. {
  342. function sys_get_temp_dir(){
  343. if ($temp = getenv('TMP') ) {
  344. if (file_exists($temp)) { return realpath($temp); }
  345. }
  346. if ($temp = getenv('TEMP') ) {
  347. if (file_exists($temp)) { return realpath($temp); }
  348. }
  349. if ($temp = getenv('TMPDIR') ) {
  350. if (file_exists($temp)) { return realpath($temp); }
  351. }
  352. // trick for creating a file in system's temporary dir
  353. // without knowing the path of the system's temporary dir
  354. $temp = tempnam(__FILE__, '');
  355. if (file_exists($temp)) {
  356. unlink($temp);
  357. return realpath(dirname($temp));
  358. }
  359. return null;
  360. }
  361. }
  362. function set_firewall($remote, $firewall_settings, $action, $port, $ip = FALSE)
  363. {
  364. if($action == "allow" or $action == "deny")
  365. {
  366. if($ip)
  367. $command = str_replace("%IP%",$ip,str_replace("%PORT%",$port,$firewall_settings[$action.'_ip_port_command']));
  368. else
  369. $command = str_replace("%PORT%",$port,$firewall_settings[$action.'_port_command']);
  370. }
  371. if(isset($command))
  372. return $remote->sudo_exec($command);
  373. else
  374. return FALSE;
  375. }
  376. function strip_real_escape_string($text)
  377. {
  378. $search = array('\"', "\'", "\\r", "\\n","\\\\");
  379. $replace = array('"', "'", "\r", "\n", '\\');
  380. $text = str_replace($search, $replace, $text);
  381. return $text;
  382. }
  383. function get_true_boolean($bool)
  384. {
  385. if ( (int) $bool > 0 )
  386. $ret = true;
  387. else
  388. {
  389. $lowered_bool = strtolower($bool); // that could be 'True' or 'true' or 'TRUE', etc...
  390. if( $lowered_bool === "true" || $lowered_bool === "on" || $lowered_bool === "yes" )
  391. $ret = true;
  392. else
  393. $ret = false;
  394. }
  395. return $ret;
  396. }
  397. function get_temp_dir($curdir)
  398. {
  399. $temp = sys_get_temp_dir();
  400. if( ini_get('open_basedir') )
  401. {
  402. $dirs = preg_split( "/:|;/", ini_get('open_basedir') , -1, PREG_SPLIT_NO_EMPTY );
  403. if( !in_array($temp, $dirs) )
  404. $temp = $curdir . DIRECTORY_SEPARATOR . 'temp';
  405. }
  406. if( $temp == null )
  407. $temp = $curdir . DIRECTORY_SEPARATOR . 'temp';
  408. if( !file_exists($temp) )
  409. if( is_writable( dirname($temp) ) ) mkdir($temp);
  410. return $temp;
  411. }
  412. // ### Escape some characters that could break the server startup or make the user capable to run other programs. ###
  413. // \ (backslash) -> At the end of the string, can scape the next quote,
  414. // and is commonly used to create Windows paths, must be escaped.
  415. // " (quote) -> Not escaped quote, without an ending quote, would break the startup command.
  416. // ' (single quote) -> same than quote.
  417. // | (pipe) -> Not escaped pipe would break the startup command and could use the next argument as new command.
  418. // & (ampersand) -> Same than pipe. If double ampersand is used it would run the command (if any) once the server process ends.
  419. // ; (semicolon) -> Same than double ampersand.
  420. // > (greater than) -> Could redirect the server output and ignore the next arguments.
  421. // < (lower than) -> Could send the content of a file to the server executable and ignore the the next arguments.
  422. // ` (apostrophe) -> Could get the return value of a given (system) command or variable.
  423. // $ (¿sigil?) -> Same than apostrophe.
  424. // ( and ) (parenthesis) -> starts or ends a bash/batch statement, could break the server startup
  425. // [ and ] (test) -> test is part of bash language, could break the server startup
  426. function clean_server_param_value($value, $cli_allow_chars) {
  427. $value = strip_real_escape_string($value);
  428. $escape_chars = array("\\", "\"", "'", "|", "&", ";", ">", "<", "`", "$", "(", ")", "[", "]");
  429. if($cli_allow_chars)
  430. {
  431. $cli_allow_chars = str_split($cli_allow_chars);
  432. $escape_chars = array_diff($escape_chars, $cli_allow_chars);
  433. }
  434. $find = array();
  435. $repl = array();
  436. foreach($escape_chars as $char)
  437. {
  438. $find[] = '%'.preg_quote($char).'%';
  439. $char = $char == '\\' ? preg_quote('\\\\') : $char;
  440. $repl[] = '\\'.$char;
  441. }
  442. return preg_replace($find, $repl, $value);
  443. }
  444. // ### Validate FTP user/password and control_protocol_password. ###
  445. function validate_login($value) {
  446. $value = strip_real_escape_string($value);
  447. $value = trim($value);
  448. $find = '%\\\\|"|\||&|;|>|<|`|\$|\s%';
  449. return preg_match($find, $value) ? FALSE : $value;
  450. }
  451. // Order a multidimensional array by keys. Source http://php.net/manual/es/function.array-multisort.php#100534
  452. function array_orderby()
  453. {
  454. $args = func_get_args();
  455. $data = array_shift($args);
  456. foreach ($args as $n => $field)
  457. {
  458. if (is_string($field))
  459. {
  460. $tmp = array();
  461. foreach ($data as $key => $row)
  462. $tmp[$key] = $row[$field];
  463. $args[$n] = $tmp;
  464. }
  465. }
  466. $args[] = &$data;
  467. call_user_func_array('array_multisort', $args);
  468. return array_pop($args);
  469. }
  470. // Escape a single quote or multiple single quotes
  471. // in a string that is passed to bash
  472. // and this string is single quoted
  473. function esc_squote($str)
  474. {
  475. return preg_replace("#('+)#", "'\"\${1}\"'", $str);
  476. }
  477. function get_game_selector($os, $game_cfgs, $home_cfg_id = FALSE)
  478. {
  479. if(preg_match("/64/", $os))
  480. {
  481. $arch_64_bit = true;
  482. }
  483. if(preg_match("/linux/i", $os))
  484. {
  485. if(preg_match("/wine/i", $os))
  486. {
  487. $os_match = $arch_64_bit ? '/(win|linux)(32|64)?$/i' : '/(win|linux)(32)?$/i';
  488. }
  489. else
  490. {
  491. $os_match = $arch_64_bit ? '/(linux)(32|64)?$/i' : '/(linux)(32)?$/i';
  492. }
  493. }
  494. elseif(preg_match("/cygwin/i", $os))
  495. {
  496. $os_match = $arch_64_bit ? '/(win)(32|64)?$/i' : '/(win)(32)?$/i';
  497. }
  498. else
  499. {
  500. $os_match = '/(win|linux)(32|64)?$/i';
  501. }
  502. $selector = "";
  503. foreach ( $game_cfgs as $row )
  504. {
  505. if ( preg_match($os_match, $row['game_key'], $matches) )
  506. {
  507. $selector .= "<option value='".$row['home_cfg_id']."' ".
  508. ($home_cfg_id == $row['home_cfg_id'] ? 'selected="selected"' : "").
  509. ">".$row['game_name'].
  510. (preg_match('/^linux$/i', $matches[1]) ? " (Linux" : " (Windows").
  511. ((isset($matches[2]) and $matches[2] == '64') ? " 64bit)" : ")").
  512. "</option>\n";
  513. }
  514. }
  515. return $selector;
  516. }
  517. function getClientIPAddress(){
  518. if(isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])){
  519. return $_SERVER['HTTP_CF_CONNECTING_IP'];
  520. }else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  521. return $_SERVER['HTTP_X_FORWARDED_FOR'];
  522. }else if(isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP'])){
  523. return $_SERVER['HTTP_X_REAL_IP'];
  524. }else{
  525. return $_SERVER['REMOTE_ADDR'];
  526. }
  527. }
  528. function getOGPSiteURL(){
  529. $url = '';
  530. $scheme = ( isset($_SERVER['HTTPS']) and get_true_boolean($_SERVER['HTTPS']) ) ? "https://" : "http://";
  531. $url .= $scheme;
  532. if(strtolower($_SERVER['HTTP_HOST']) == "localhost"){
  533. $ip = getRemoteIPAddressFromSite('http://grabip.tk/');
  534. if(!hasValue($ip)){
  535. if(cURLEnabled()){
  536. $ipOfServer = get_headers_curl("http://grabip.tk/", $referrer, $agent);
  537. if(hasValue($ipOfServer) && is_array($ipOfServer)){
  538. $ipOfServer = $ipOfServer[0];
  539. if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $ipOfServer, $ip_match)) {
  540. $ipStr = $ip_match[0];
  541. if(isValidIP($ipStr) && !isPrivateIp($ipStr)){
  542. $ip = $ipStr;
  543. }
  544. }
  545. }
  546. }
  547. }
  548. }
  549. if(hasValue($ip)){
  550. $url .= $ip;
  551. }else{
  552. $url .= $_SERVER['HTTP_HOST'];
  553. }
  554. if(!empty($_SERVER['REQUEST_URI'])){
  555. $lastSlash = strrpos($_SERVER['REQUEST_URI'], "/");
  556. if($lastSlash !== false){
  557. $url .= substr($_SERVER['REQUEST_URI'], 0, $lastSlash);
  558. }
  559. }
  560. if(!empty($url)){
  561. return $url;
  562. }
  563. return false;
  564. }
  565. function getRemoteIPAddressFromSite($site){
  566. $str = "";
  567. if(isset($site) && !empty($site)){
  568. $str=trim(file_get_contents($site));
  569. // Look for an IP
  570. if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $str, $ip_match)) {
  571. $ip = $ip_match[0];
  572. if(isValidIP($ip) && !isPrivateIp($ip)){
  573. $str = $ip;
  574. }
  575. }
  576. }
  577. return $str;
  578. }
  579. function isValidIP($ip){
  580. if(preg_match( "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/", $ip)){
  581. return True;
  582. }else{
  583. return False;
  584. }
  585. }
  586. function isPrivateIp($ip){
  587. if(is_array($ip)) {
  588. $ret=false;
  589. foreach($ip as $i)
  590. $ret=$ret or isPrivateIp($i);
  591. return $ret;
  592. }
  593. return (substr($ip,0,7)=='192.168' or substr($ip,0,6)=='172.16' or substr($ip,0,3)=='10.');
  594. }
  595. function hasValue($val, $zeroAllowed = false){
  596. if(isset($val) && !empty($val)){
  597. return true;
  598. }else{
  599. if($zeroAllowed == true && $val == 0){
  600. return true;
  601. }else{
  602. return false;
  603. }
  604. }
  605. }
  606. function paginationPages($pageResults, $currentPage, $perPage, $pageUri, $pagesShown, $classPrefix) {
  607. $pagination = '<div id="pagination">';
  608. if ($pageResults > $perPage) {
  609. $totalPages = ceil($pageResults/$perPage);
  610. $pageStart = (($currentPage - $pagesShown) > 0) ? $currentPage - $pagesShown : 1;
  611. $pageEnd = (($currentPage + $pagesShown) < $totalPages) ? $currentPage + $pagesShown : $totalPages;
  612. if ($pageStart > 1) {
  613. $pagination .= '<span class="'.$classPrefix.'_paginationStart">
  614. <a href="'.$pageUri . ($currentPage-1) .'" class="'.$classPrefix.'_previousPageLink">&laquo;</a>
  615. <a href="'.$pageUri .'1" class="'.$classPrefix.'_firstPageLink">1</a>
  616. <span class='.$classPrefix.'_divider">&hellip;</span>
  617. </span>';
  618. }
  619. $pagination .= '<span class="'.$classPrefix.'_paginationPages">';
  620. for ($i=$pageStart; $i<=$pageEnd; ++$i) {
  621. if ($currentPage == $i) {
  622. $pagination .= '<a href="'.$pageUri . $i .'" class="'.$classPrefix.'_currentPageLink">['.$i.']</a>';
  623. } else {
  624. $pagination .= '<a href="'.$pageUri . $i .'" class="'.$classPrefix.'_pageLinks">'.$i.'</a>';
  625. }
  626. $pagination .= ($i < $pageEnd) ? ', ' : ' ';
  627. }
  628. $pagination .= '</span>';
  629. if ($pageEnd < $totalPages) {
  630. $pagination .= '<span class="'.$classPrefix.'_paginationEnd">
  631. <span class='.$classPrefix.'_divider">&hellip;</span>
  632. <a href="'.$pageUri . $totalPages .'" class="'.$classPrefix.'_lastPageLink">'.$totalPages.'</a>
  633. <a href="'.$pageUri . ($currentPage+1) .'" class="'.$classPrefix.'_nextPageLink">&raquo;</a>
  634. </span>';
  635. }
  636. }
  637. $pagination .= '</div>';
  638. return $pagination;
  639. }
  640. function checkDisplayPublicIP($display_public_ip,$internal_ip){
  641. // Set Cache Timer in Seconds
  642. $cache_timer = 600;
  643. // Exit Function when External IP is Internal IP or when Display Public IP is not set
  644. if($display_public_ip==$internal_ip || empty($display_public_ip)){
  645. return $internal_ip;
  646. }
  647. if(!isset($_SESSION['gethostbyname_cache'])){
  648. $_SESSION['gethostbyname_cache'] = array();
  649. }
  650. if(filter_var($display_public_ip, FILTER_VALIDATE_IP)){
  651. return $display_public_ip;
  652. }else{
  653. if(!array_key_exists($display_public_ip, $_SESSION['gethostbyname_cache'])){
  654. $_SESSION['gethostbyname_cache'][$display_public_ip] = array();
  655. $dns_check = dns_get_record($display_public_ip, DNS_A);
  656. $ipcheck = isset($dns_check[0]['ip']) ? $dns_check[0]['ip'] : $internal_ip;
  657. if($ipcheck!=$display_public_ip){
  658. $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'] = $ipcheck;
  659. $_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'] = time();
  660. }else{
  661. unset($_SESSION['gethostbyname_cache'][$display_public_ip]);
  662. return $internal_ip;
  663. }
  664. }else{
  665. if((time()-$_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'])>=$cache_timer){
  666. $dns_check = dns_get_record($display_public_ip, DNS_A);
  667. $ipcheck = isset($dns_check[0]['ip']) ? $dns_check[0]['ip'] : $internal_ip;
  668. if($ipcheck!=$display_public_ip){
  669. $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'] = $ipcheck;
  670. $_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'] = time();
  671. }else{
  672. unset($_SESSION['gethostbyname_cache'][$display_public_ip]);
  673. return $internal_ip;
  674. }
  675. }
  676. }
  677. if(filter_var($_SESSION['gethostbyname_cache'][$display_public_ip]['ip'], FILTER_VALIDATE_IP)){
  678. return $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'];
  679. }
  680. }
  681. return $internal_ip;
  682. }
  683. function startsWith($haystack, $needle) {
  684. // search backwards starting from haystack length characters from the end
  685. return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
  686. }
  687. function endsWith($haystack, $needle) {
  688. // search forward starting from end minus needle length characters
  689. return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
  690. }
  691. // Super ingenious function from https://stackoverflow.com/questions/5519630/php-preg-replace-x-occurence#answer-17047405
  692. function preg_replace_nth($pattern, $replacement, $subject, $nth=1) {
  693. return preg_replace_callback($pattern,
  694. function($found) use (&$pattern, &$replacement, &$nth) {
  695. $nth--;
  696. if ($nth==0) return preg_replace($pattern, $replacement, reset($found) );
  697. return reset($found);
  698. }, $subject,$nth);
  699. }
  700. // https://stackoverflow.com/questions/12559878/multidimensional-array-find-item-and-move-to-the-top
  701. function customShift($array, $keyToMoveOn, $valueToMoveOn){
  702. foreach($array as $key => $val){
  703. if($val[$keyToMoveOn] == $valueToMoveOn){
  704. unset($array[$key]);
  705. array_unshift($array, $val);
  706. return $array;
  707. }
  708. }
  709. return $array;
  710. }
  711. function getURLParam($param, $url){
  712. if(stripos($url, $param) !== false){
  713. $param = substr($url, stripos($url, $param) + strlen($param));
  714. if(stripos($param, "&")){
  715. $param = substr($param, 0, stripos($param, "&"));
  716. }
  717. return $param;
  718. }
  719. return false;
  720. }
  721. function utf8ize($d, $htmlEntities = true) {
  722. if (is_array($d)) {
  723. foreach ($d as $k => $v) {
  724. $d[$k] = utf8ize($v, $htmlEntities);
  725. }
  726. } else if (is_string ($d)) {
  727. if($htmlEntities){
  728. $d = htmlentities($d);
  729. }
  730. return utf8_encode($d);
  731. }
  732. return $d;
  733. }
  734. function preReqInstalled($prereq){
  735. if (($prereq['type'] === "f" && function_exists($prereq['value'])) || ($prereq['type'] === "c" && class_exists($prereq['value'])) || ($prereq['type'] === "x" && extension_loaded($prereq['value']))){
  736. return true;
  737. }
  738. return false;
  739. }
  740. ?>