functions.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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 6.1; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.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. // Cheap way to parse Bcc addresses as defined in register-exec.php
  298. $bcc_email_addresses = explode( "|", $email_address );
  299. if (isset($bcc_email_addresses[1])) {
  300. $email_addresses = explode( ",", $bcc_email_addresses[1] );
  301. $bcc_email_addresses = explode( ",", $bcc_email_addresses[0] );
  302. } else {
  303. $bcc_email_addresses = 0;
  304. $email_addresses = explode( ",", $email_address );
  305. }
  306. if( $user_to_panel )
  307. {
  308. $mail->AddAddress($panel_email);
  309. $user_to_panel = is_bool($user_to_panel) ? "" : $user_to_panel; // True boolean or user name string
  310. foreach ( $email_addresses as $address )
  311. {
  312. $mail->SetFrom($address,$user_to_panel);
  313. $mail->AddReplyTo($address,$user_to_panel);
  314. }
  315. }
  316. else // panel to user
  317. {
  318. foreach ( $email_addresses as $address )
  319. {
  320. $mail->AddAddress($address);
  321. }
  322. // Loop through Bcc addresses, if any, and add them as proper Bcc recipients
  323. if ($bcc_email_addresses != 0)
  324. {
  325. foreach ( $bcc_email_addresses as $bcc_address )
  326. {
  327. if ($bcc_address != "")
  328. $mail->addBCC($bcc_address);
  329. }
  330. }
  331. $mail->SetFrom($panel_email,$panel_name);
  332. $mail->AddReplyTo($panel_email,$panel_name);
  333. }
  334. $mail->CharSet = $view->charset;
  335. $mail->Subject = $subject;
  336. $mail->MsgHTML($message);
  337. $mail->SMTPOptions = array(
  338. 'ssl' => array(
  339. 'verify_peer' => false,
  340. 'verify_peer_name' => false,
  341. 'allow_self_signed' => true
  342. )
  343. );
  344. $mail->Send();
  345. }
  346. catch (phpmailerException $e)
  347. {
  348. $mymail = FALSE;
  349. echo $e->errorMessage(); //Pretty error messages from PHPMailer
  350. }
  351. catch (Exception $e)
  352. {
  353. $mymail = FALSE;
  354. echo $e->getMessage(); //Boring error messages from anything else!
  355. }
  356. return $mymail;
  357. }
  358. if( !function_exists("sys_get_temp_dir") )
  359. {
  360. function sys_get_temp_dir(){
  361. if ($temp = getenv('TMP') ) {
  362. if (file_exists($temp)) { return realpath($temp); }
  363. }
  364. if ($temp = getenv('TEMP') ) {
  365. if (file_exists($temp)) { return realpath($temp); }
  366. }
  367. if ($temp = getenv('TMPDIR') ) {
  368. if (file_exists($temp)) { return realpath($temp); }
  369. }
  370. // trick for creating a file in system's temporary dir
  371. // without knowing the path of the system's temporary dir
  372. $temp = tempnam(__FILE__, '');
  373. if (file_exists($temp)) {
  374. unlink($temp);
  375. return realpath(dirname($temp));
  376. }
  377. return null;
  378. }
  379. }
  380. function set_firewall($remote, $firewall_settings, $action, $port, $ip = FALSE)
  381. {
  382. if($action == "allow" or $action == "deny")
  383. {
  384. if($ip)
  385. $command = str_replace("%IP%",$ip,str_replace("%PORT%",$port,$firewall_settings[$action.'_ip_port_command']));
  386. else
  387. $command = str_replace("%PORT%",$port,$firewall_settings[$action.'_port_command']);
  388. }
  389. if(isset($command))
  390. return $remote->sudo_exec($command);
  391. else
  392. return FALSE;
  393. }
  394. function strip_real_escape_string($text)
  395. {
  396. $search = array('\"', "\'", "\\r", "\\n","\\\\");
  397. $replace = array('"', "'", "\r", "\n", '\\');
  398. $text = str_replace($search, $replace, $text);
  399. return $text;
  400. }
  401. function get_true_boolean($bool)
  402. {
  403. if ( (int) $bool > 0 )
  404. $ret = true;
  405. else
  406. {
  407. $lowered_bool = strtolower($bool); // that could be 'True' or 'true' or 'TRUE', etc...
  408. if( $lowered_bool === "true" || $lowered_bool === "on" || $lowered_bool === "yes" )
  409. $ret = true;
  410. else
  411. $ret = false;
  412. }
  413. return $ret;
  414. }
  415. function get_temp_dir($curdir)
  416. {
  417. $temp = sys_get_temp_dir();
  418. if( ini_get('open_basedir') )
  419. {
  420. $dirs = preg_split( "/:|;/", ini_get('open_basedir') , -1, PREG_SPLIT_NO_EMPTY );
  421. if( !in_array($temp, $dirs) )
  422. $temp = $curdir . DIRECTORY_SEPARATOR . 'temp';
  423. }
  424. if( $temp == null )
  425. $temp = $curdir . DIRECTORY_SEPARATOR . 'temp';
  426. if( !file_exists($temp) )
  427. if( is_writable( dirname($temp) ) ) mkdir($temp);
  428. return $temp;
  429. }
  430. // ### Escape some characters that could break the server startup or make the user capable to run other programs. ###
  431. // \ (backslash) -> At the end of the string, can scape the next quote,
  432. // and is commonly used to create Windows paths, must be escaped.
  433. // " (quote) -> Not escaped quote, without an ending quote, would break the startup command.
  434. // ' (single quote) -> same than quote.
  435. // | (pipe) -> Not escaped pipe would break the startup command and could use the next argument as new command.
  436. // & (ampersand) -> Same than pipe. If double ampersand is used it would run the command (if any) once the server process ends.
  437. // ; (semicolon) -> Same than double ampersand.
  438. // > (greater than) -> Could redirect the server output and ignore the next arguments.
  439. // < (lower than) -> Could send the content of a file to the server executable and ignore the the next arguments.
  440. // ` (apostrophe) -> Could get the return value of a given (system) command or variable.
  441. // $ (¿sigil?) -> Same than apostrophe.
  442. // ( and ) (parenthesis) -> starts or ends a bash/batch statement, could break the server startup
  443. // [ and ] (test) -> test is part of bash language, could break the server startup
  444. function clean_server_param_value($value, $cli_allow_chars) {
  445. $value = strip_real_escape_string($value);
  446. $escape_chars = array("\\", "\"", "'", "|", "&", ";", ">", "<", "`", "$", "(", ")", "[", "]");
  447. if($cli_allow_chars)
  448. {
  449. $cli_allow_chars = str_split($cli_allow_chars);
  450. $escape_chars = array_diff($escape_chars, $cli_allow_chars);
  451. }
  452. $find = array();
  453. $repl = array();
  454. foreach($escape_chars as $char)
  455. {
  456. $find[] = '%'.preg_quote($char).'%';
  457. $char = $char == '\\' ? preg_quote('\\\\') : $char;
  458. $repl[] = '\\'.$char;
  459. }
  460. return preg_replace($find, $repl, $value);
  461. }
  462. // ### Validate FTP user/password and control_protocol_password. ###
  463. function validate_login($value) {
  464. $value = strip_real_escape_string($value);
  465. $value = trim($value);
  466. $find = '%\\\\|"|\||&|;|>|<|`|\$|\s%';
  467. return preg_match($find, $value) ? FALSE : $value;
  468. }
  469. // Order a multidimensional array by keys. Source http://php.net/manual/es/function.array-multisort.php#100534
  470. function array_orderby()
  471. {
  472. $args = func_get_args();
  473. $data = array_shift($args);
  474. foreach ($args as $n => $field)
  475. {
  476. if (is_string($field))
  477. {
  478. $tmp = array();
  479. foreach ($data as $key => $row)
  480. $tmp[$key] = $row[$field];
  481. $args[$n] = $tmp;
  482. }
  483. }
  484. $args[] = &$data;
  485. call_user_func_array('array_multisort', $args);
  486. return array_pop($args);
  487. }
  488. // Escape a single quote or multiple single quotes
  489. // in a string that is passed to bash
  490. // and this string is single quoted
  491. function esc_squote($str)
  492. {
  493. return preg_replace("#('+)#", "'\"\${1}\"'", $str);
  494. }
  495. function get_game_selector($os, $game_cfgs, $home_cfg_id = FALSE)
  496. {
  497. if(preg_match("/64/", $os))
  498. {
  499. $arch_64_bit = true;
  500. }
  501. if(preg_match("/linux/i", $os))
  502. {
  503. if(preg_match("/wine/i", $os))
  504. {
  505. $os_match = $arch_64_bit ? '/(win|linux)(32|64)?$/i' : '/(win|linux)(32)?$/i';
  506. }
  507. else
  508. {
  509. $os_match = $arch_64_bit ? '/(linux)(32|64)?$/i' : '/(linux)(32)?$/i';
  510. }
  511. }
  512. elseif(preg_match("/cygwin/i", $os))
  513. {
  514. $os_match = $arch_64_bit ? '/(win)(32|64)?$/i' : '/(win)(32)?$/i';
  515. }
  516. else
  517. {
  518. $os_match = '/(win|linux)(32|64)?$/i';
  519. }
  520. $selector = "";
  521. foreach ( $game_cfgs as $row )
  522. {
  523. if ( preg_match($os_match, $row['game_key'], $matches) )
  524. {
  525. $selector .= "<option value='".$row['home_cfg_id']."' ".
  526. ($home_cfg_id == $row['home_cfg_id'] ? 'selected="selected"' : "").
  527. ">".$row['game_name'].
  528. (preg_match('/^linux$/i', $matches[1]) ? " (Linux" : " (Windows").
  529. ((isset($matches[2]) and $matches[2] == '64') ? " 64bit)" : ")").
  530. "</option>\n";
  531. }
  532. }
  533. return $selector;
  534. }
  535. function getClientIPAddress(){
  536. if(isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])){
  537. $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
  538. }else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  539. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  540. }else if(isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP'])){
  541. $ip = $_SERVER['HTTP_X_REAL_IP'];
  542. }
  543. if(filter_var($ip, FILTER_VALIDATE_IP)){
  544. return $ip;
  545. }
  546. return $_SERVER['REMOTE_ADDR'];
  547. }
  548. function getOGPSiteURL(){
  549. $url = '';
  550. $scheme = ( isset($_SERVER['HTTPS']) and get_true_boolean($_SERVER['HTTPS']) ) ? "https://" : "http://";
  551. $url .= $scheme;
  552. if(strtolower($_SERVER['HTTP_HOST']) == "localhost"){
  553. $ip = getRemoteIPAddressFromSite('http://grabip.tk/');
  554. if(!hasValue($ip)){
  555. if(cURLEnabled()){
  556. $ipOfServer = get_headers_curl("http://grabip.tk/", $referrer, $agent);
  557. if(hasValue($ipOfServer) && is_array($ipOfServer)){
  558. $ipOfServer = $ipOfServer[0];
  559. if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $ipOfServer, $ip_match)) {
  560. $ipStr = $ip_match[0];
  561. if(isValidIP($ipStr) && !isPrivateIp($ipStr)){
  562. $ip = $ipStr;
  563. }
  564. }
  565. }
  566. }
  567. }
  568. }
  569. if(isset($ip) and !empty($ip)){
  570. $url .= $ip;
  571. }else{
  572. $url .= $_SERVER['HTTP_HOST'];
  573. }
  574. if(!empty($_SERVER['REQUEST_URI'])){
  575. $lastSlash = strrpos($_SERVER['REQUEST_URI'], "/");
  576. if($lastSlash !== false){
  577. $url .= substr($_SERVER['REQUEST_URI'], 0, $lastSlash);
  578. }
  579. }
  580. if(!empty($url)){
  581. return $url;
  582. }
  583. return false;
  584. }
  585. function getRemoteIPAddressFromSite($site){
  586. $str = "";
  587. if(isset($site) && !empty($site)){
  588. $str=trim(file_get_contents($site));
  589. // Look for an IP
  590. if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $str, $ip_match)) {
  591. $ip = $ip_match[0];
  592. if(isValidIP($ip) && !isPrivateIp($ip)){
  593. $str = $ip;
  594. }
  595. }
  596. }
  597. return $str;
  598. }
  599. function isValidIP($ip){
  600. 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)){
  601. return True;
  602. }else{
  603. return False;
  604. }
  605. }
  606. function isPrivateIp($ip){
  607. if(is_array($ip)) {
  608. $ret=false;
  609. foreach($ip as $i)
  610. $ret=$ret or isPrivateIp($i);
  611. return $ret;
  612. }
  613. return (substr($ip,0,7)=='192.168' or substr($ip,0,6)=='172.16' or substr($ip,0,3)=='10.');
  614. }
  615. function hasValue($val, $zeroAllowed = false){
  616. if(isset($val) && !empty($val)){
  617. return true;
  618. }else{
  619. if($zeroAllowed == true && $val == 0){
  620. return true;
  621. }else{
  622. return false;
  623. }
  624. }
  625. }
  626. function paginationPages($pageResults, $currentPage, $perPage, $pageUri, $pagesShown, $classPrefix) {
  627. $pagination = '<div id="pagination">';
  628. if ($pageResults > $perPage) {
  629. $totalPages = ceil($pageResults/$perPage);
  630. $pageStart = (($currentPage - $pagesShown) > 0) ? $currentPage - $pagesShown : 1;
  631. $pageEnd = (($currentPage + $pagesShown) < $totalPages) ? $currentPage + $pagesShown : $totalPages;
  632. if ($pageStart > 1) {
  633. $pagination .= '<span class="'.$classPrefix.'_paginationStart">
  634. <a href="'.$pageUri . ($currentPage-1) .'" class="'.$classPrefix.'_previousPageLink">&laquo;</a>
  635. <a href="'.$pageUri .'1" class="'.$classPrefix.'_firstPageLink">1</a>
  636. <span class='.$classPrefix.'_divider">&hellip;</span>
  637. </span>';
  638. }
  639. $pagination .= '<span class="'.$classPrefix.'_paginationPages">';
  640. for ($i=$pageStart; $i<=$pageEnd; ++$i) {
  641. if ($currentPage == $i) {
  642. $pagination .= '<a href="'.$pageUri . $i .'" class="'.$classPrefix.'_currentPageLink">['.$i.']</a>';
  643. } else {
  644. $pagination .= '<a href="'.$pageUri . $i .'" class="'.$classPrefix.'_pageLinks">'.$i.'</a>';
  645. }
  646. $pagination .= ($i < $pageEnd) ? ', ' : ' ';
  647. }
  648. $pagination .= '</span>';
  649. if ($pageEnd < $totalPages) {
  650. $pagination .= '<span class="'.$classPrefix.'_paginationEnd">
  651. <span class='.$classPrefix.'_divider">&hellip;</span>
  652. <a href="'.$pageUri . $totalPages .'" class="'.$classPrefix.'_lastPageLink">'.$totalPages.'</a>
  653. <a href="'.$pageUri . ($currentPage+1) .'" class="'.$classPrefix.'_nextPageLink">&raquo;</a>
  654. </span>';
  655. }
  656. }
  657. $pagination .= '</div>';
  658. return $pagination;
  659. }
  660. function checkDisplayPublicIP($display_public_ip,$internal_ip){
  661. // Set Cache Timer in Seconds
  662. $cache_timer = 600;
  663. // Exit Function when External IP is Internal IP or when Display Public IP is not set
  664. if($display_public_ip==$internal_ip || empty($display_public_ip)){
  665. return $internal_ip;
  666. }
  667. if(!isset($_SESSION['gethostbyname_cache'])){
  668. $_SESSION['gethostbyname_cache'] = array();
  669. }
  670. if(filter_var($display_public_ip, FILTER_VALIDATE_IP)){
  671. return $display_public_ip;
  672. }else{
  673. if(!array_key_exists($display_public_ip, $_SESSION['gethostbyname_cache'])){
  674. $_SESSION['gethostbyname_cache'][$display_public_ip] = array();
  675. $dns_check = dns_get_record($display_public_ip, DNS_A);
  676. $ipcheck = isset($dns_check[0]['ip']) ? $dns_check[0]['ip'] : $internal_ip;
  677. if($ipcheck!=$display_public_ip){
  678. $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'] = $ipcheck;
  679. $_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'] = time();
  680. }else{
  681. unset($_SESSION['gethostbyname_cache'][$display_public_ip]);
  682. return $internal_ip;
  683. }
  684. }else{
  685. if((time()-$_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'])>=$cache_timer){
  686. $dns_check = dns_get_record($display_public_ip, DNS_A);
  687. $ipcheck = isset($dns_check[0]['ip']) ? $dns_check[0]['ip'] : $internal_ip;
  688. if($ipcheck!=$display_public_ip){
  689. $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'] = $ipcheck;
  690. $_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'] = time();
  691. }else{
  692. unset($_SESSION['gethostbyname_cache'][$display_public_ip]);
  693. return $internal_ip;
  694. }
  695. }
  696. }
  697. if(filter_var($_SESSION['gethostbyname_cache'][$display_public_ip]['ip'], FILTER_VALIDATE_IP)){
  698. return $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'];
  699. }
  700. }
  701. return $internal_ip;
  702. }
  703. function startsWith($haystack, $needle) {
  704. // search backwards starting from haystack length characters from the end
  705. return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
  706. }
  707. function endsWith($haystack, $needle) {
  708. // search forward starting from end minus needle length characters
  709. return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
  710. }
  711. // Super ingenious function from https://stackoverflow.com/questions/5519630/php-preg-replace-x-occurence#answer-17047405
  712. function preg_replace_nth($pattern, $replacement, $subject, $nth=1) {
  713. return preg_replace_callback($pattern,
  714. function($found) use (&$pattern, &$replacement, &$nth) {
  715. $nth--;
  716. if ($nth==0) return preg_replace($pattern, $replacement, reset($found) );
  717. return reset($found);
  718. }, $subject,$nth);
  719. }
  720. // https://stackoverflow.com/questions/12559878/multidimensional-array-find-item-and-move-to-the-top
  721. function customShift($array, $keyToMoveOn, $valueToMoveOn){
  722. foreach($array as $key => $val){
  723. if($val[$keyToMoveOn] == $valueToMoveOn){
  724. unset($array[$key]);
  725. array_unshift($array, $val);
  726. return $array;
  727. }
  728. }
  729. return $array;
  730. }
  731. function getURLParam($param, $url){
  732. if(stripos($url, $param) !== false){
  733. $param = substr($url, stripos($url, $param) + strlen($param));
  734. if(stripos($param, "&")){
  735. $param = substr($param, 0, stripos($param, "&"));
  736. }
  737. return $param;
  738. }
  739. return false;
  740. }
  741. function utf8ize($d, $htmlEntities = true) {
  742. if (is_array($d)) {
  743. foreach ($d as $k => $v) {
  744. $d[$k] = utf8ize($v, $htmlEntities);
  745. }
  746. } else if (is_string ($d)) {
  747. if($htmlEntities){
  748. $d = htmlentities($d);
  749. }
  750. return utf8_encode($d);
  751. }
  752. return $d;
  753. }
  754. function preReqInstalled($prereq){
  755. if (($prereq['type'] === "f" && function_exists($prereq['value'])) || ($prereq['type'] === "c" && class_exists($prereq['value'])) || ($prereq['type'] === "x" && extension_loaded($prereq['value']))){
  756. return true;
  757. }
  758. return false;
  759. }
  760. if (!function_exists('boolval')) {
  761. function boolval($val) {
  762. return (bool) $val;
  763. }
  764. }
  765. function getThemePath()
  766. {
  767. global $settings;
  768. $path = "";
  769. if ( isset($_SESSION['users_theme']) &&
  770. !empty($_SESSION['users_theme']) &&
  771. is_dir( 'themes/'.$_SESSION['users_theme'] ) &&
  772. is_file( 'themes/'.$_SESSION['users_theme'].'/layout.html') )
  773. {
  774. $path = 'themes/'.$_SESSION['users_theme'].'/';
  775. }
  776. // Using default theme if there is not one selected.
  777. else if ( !isset($settings['theme']) )
  778. {
  779. $path = 'themes/Revolution/';
  780. }
  781. else if ( is_dir( 'themes/'.$settings['theme'] ) &&
  782. is_file( 'themes/'.$settings['theme'].'/layout.html') )
  783. {
  784. $path = 'themes/'.$settings['theme'].'/';
  785. }
  786. // In case the theme that was selected is invalid print error and use default.
  787. else
  788. {
  789. $path = 'themes/Revolution/';
  790. }
  791. return $path;
  792. }
  793. function updateAllPanelModules(){
  794. global $db;
  795. if(file_exists('modules/modulemanager/module_handling.php')){
  796. require_once('modules/modulemanager/module_handling.php');
  797. $modules = $db->getInstalledModules();
  798. // update module manager first
  799. foreach ( $modules as $row )
  800. {
  801. if($row['folder'] == 'modulemanager')
  802. {
  803. update_module($db, $row['id'], $row['folder']);
  804. break;
  805. }
  806. }
  807. foreach ( $modules as $row )
  808. {
  809. if($row['folder'] == 'modulemanager')//already updated
  810. continue;
  811. update_module($db, $row['id'], $row['folder']);
  812. }
  813. }
  814. }
  815. function getRemoteContent($url, $timeout = 5, $referrer = ""){
  816. $useCURL = false;
  817. $agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0';
  818. try{
  819. $currentTimeout = ini_get('default_socket_timeout');
  820. ini_set('default_socket_timeout', $timeout); // Timeout in seconds
  821. $streamOptions = array(
  822. 'http' => array(
  823. 'method' => 'GET',
  824. 'user_agent' => $agent,
  825. 'timeout' => ($timeout + 3) // https://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting#answer-10236480
  826. ),
  827. 'ssl'=> array(
  828. 'verify_peer' => false,
  829. 'verify_peer_name' => false,
  830. )
  831. );
  832. if(!empty($referrer)){
  833. $streamOptions['header'] = array("Referer: $referer\r\n");
  834. }
  835. stream_context_set_default($streamOptions);
  836. $content = file_get_contents($url);
  837. if(empty($content) || strlen($content) <=5){
  838. $useCURL = true;
  839. }else{
  840. ini_set('default_socket_timeout', $currentTimeout); // Set it back to the original
  841. return $content;
  842. }
  843. }catch (Exception $e) {
  844. $useCURL = true;
  845. }
  846. if($useCURL && cURLEnabled()){
  847. try{
  848. $ch = curl_init();
  849. curl_setopt($ch, CURLOPT_URL, $url);
  850. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  851. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  852. curl_setopt($ch, CURLOPT_TIMEOUT, ($timeout + 3));
  853. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  854. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  855. curl_setopt($ch, CURLOPT_USERAGENT, $agent);
  856. if(!empty($referrer)){
  857. curl_setopt($ch, CURLOPT_REFERER, $referrer);
  858. }
  859. $data = curl_exec($ch);
  860. curl_close($ch);
  861. if(!empty($data)){
  862. return $data;
  863. }
  864. } catch (Exception $e) {
  865. }
  866. }
  867. return false;
  868. }
  869. function getQueryPortOverridesForGame($protocol, $ip, $port, $defaultQueryPort){
  870. $q_port = $defaultQueryPort;
  871. if(strpos($protocol, 'mohaa') !== false){
  872. $realQPort = getRemoteContent("http://mohaaservers.tk/get_query_port_fast.php?ip=" . $ip . ":" . $port);
  873. if($realQPort != -1 && is_numeric($realQPort)){
  874. $q_port = $realQPort;
  875. }
  876. }
  877. return $q_port;
  878. }
  879. function removeInvalidFileNameCharacters($string){
  880. global $settings;
  881. $pattern = '/[\^\$\*\+\?\(\)\[\{\\\|\]!@#%&=~`,\'<>"}\s]/i';
  882. if(is_array($settings) && array_key_exists("regex_invalid_file_name_chars", $settings) && !empty($settings["regex_invalid_file_name_chars"])){
  883. $pattern = $settings["regex_invalid_file_name_chars"];
  884. }
  885. $string = preg_replace($pattern, '', $string);
  886. return $string;
  887. }
  888. function deleteMysqlAddonDatabasesForGameServerHome($home_id){
  889. global $db, $db_host, $db_user, $db_pass, $db_name, $table_prefix;
  890. if ( function_exists('mysqli_connect') )
  891. require_once("modules/mysql/mysqli_database.php");
  892. else
  893. require_once("modules/mysql/mysql_database.php");
  894. require_once('includes/lib_remote.php');
  895. $modDb = new MySQLModuleDatabase();
  896. require_once("includes/config.inc.php");
  897. $modDb->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  898. if(hasValue($home_id) && is_numeric($home_id)){
  899. $dbDeletedCount = 0;
  900. $dbsToDelete = $modDb->getMysqlDBsbyHomeId($home_id);
  901. if(is_array($dbsToDelete) && count($dbsToDelete)){
  902. foreach($dbsToDelete as $dbToDel){
  903. $mysql_db = $dbToDel;
  904. if($mysql_db['remote_server_id'] != "0")
  905. {
  906. $remote_server = $db->getRemoteServer($mysql_db['remote_server_id']);
  907. $remote = new OGPRemoteLibrary($remote_server['agent_ip'],$remote_server['agent_port'],$remote_server['encryption_key'],$remote_server['timeout']);
  908. $host_stat = $remote->status_chk();
  909. if($host_stat === 1 )
  910. {
  911. $remote->exec('mysql --host=localhost --port='.$mysql_db['mysql_port'].' -uroot -p'.$mysql_db['mysql_root_passwd'].
  912. ' -e "DROP DATABASE '.$mysql_db['db_name'].";DROP USER '".$mysql_db['db_user']."'@'%';\"");
  913. }
  914. }
  915. else
  916. {
  917. if( function_exists('mysqli_connect') )
  918. {
  919. @$link = mysqli_connect($mysql_db['mysql_ip'], 'root', $mysql_db['mysql_root_passwd'], "", $mysql_db['mysql_port']);
  920. if ( $link !== FALSE )
  921. {
  922. $queries = array("DROP DATABASE ".$mysql_db['db_name'].";",
  923. "DROP USER '".$mysql_db['db_user']."'@'%';");
  924. foreach( $queries as $query )
  925. {
  926. @$return = mysqli_query($link, $query);
  927. if(!$return)
  928. break;
  929. }
  930. mysqli_close($link);
  931. $db->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  932. }
  933. }
  934. else
  935. {
  936. @$link = mysql_connect($mysql_db['mysql_ip'].':'.$mysql_db['mysql_port'], 'root', $mysql_db['mysql_root_passwd']);
  937. if ( $link !== FALSE )
  938. {
  939. $queries = array("DROP DATABASE ".$mysql_db['db_name'].";",
  940. "DROP USER '".$mysql_db['db_user']."'@'%';");
  941. foreach( $queries as $query )
  942. {
  943. @$return = mysql_query($query);
  944. if(!$return)
  945. break;
  946. }
  947. mysql_close($link);
  948. $db->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  949. }
  950. }
  951. }
  952. if ( $modDb->removeMysqlServerDB($db_id) !== FALSE )
  953. {
  954. $dbDeletedCount++;
  955. }
  956. }
  957. if($dbDeletedCount == count($dbsToDelete)){
  958. return true;
  959. }else if($dbDeletedCount > 0){
  960. return 'partial';
  961. }
  962. }
  963. }
  964. return false;
  965. }
  966. function get_magic_quotes_gpc_wrapper(){
  967. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()){
  968. return true;
  969. }
  970. return false;
  971. }
  972. ?>