functions.php 26 KB

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