functions.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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 == "risingstorm2" ? "ro2" : $mod_gt;
  82. $mod_gt = $mod == "killingfloor2" ? "kf2" : $mod_gt;
  83. $mod_gt = $query_name == "7dtd" ? "7daystodie" : $mod_gt;
  84. $mod_gt = $query_name == "callofduty" ? "cod" : $mod_gt;
  85. $mod_gt = $query_name == "callofdutyuo" ? "uo" : $mod_gt;
  86. $mod_gt = $query_name == "callofduty2" ? "cod2" : $mod_gt;
  87. $mod_gt = $query_name == "callofduty4mw" ? "cod4" : $mod_gt;
  88. $mod_gt = $query_name == "callofdutywaw" ? "codww" : $mod_gt;
  89. $mod_gt = $query_name == "callofdutymw3" ? "mw3" : $mod_gt;
  90. $mod_gt = $query_name == "conanexiles" ? "conan" : $mod_gt;
  91. $map_paths= array(
  92. "protocol/lgsl/maps/$query_name/$mod/$map.jpg",
  93. "protocol/lgsl/maps/$query_name/$mod/$map.gif",
  94. "protocol/lgsl/maps/$query_name/$mod/$map.png",
  95. "protocol/lgsl/maps/$query_name/$map.jpg",
  96. "protocol/lgsl/maps/$query_name/$map.gif",
  97. "protocol/lgsl/maps/$query_name/$map.png",
  98. "https://image.gametracker.com/images/maps/160x120/$mod_gt/$map.jpg",
  99. "https://image.gametracker.com/images/maps/160x120/$query_name/$map.jpg",
  100. "images/online_big.png"
  101. );
  102. return get_first_existing_file($map_paths, 'https://gametracker.com', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0');
  103. }
  104. // Thanks adjo (http://opengamepanel.org/forum/viewthread.php?thread_id=5209#post_25073)
  105. function curlCacheImage($cachePath, $resource){
  106. if(preg_match('/^(https?:\/\/)/', $resource)){
  107. $map = explode('/', $resource);
  108. if(!file_exists($cachePath . '/cache/' . end($map))){
  109. $ch = curl_init();
  110. curl_setopt($ch, CURLOPT_HEADER, 0);
  111. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  112. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0');
  113. curl_setopt($ch, CURLOPT_REFERER, 'http://gametracker.com');
  114. curl_setopt($ch, CURLOPT_URL, $resource);
  115. $result = curl_exec($ch);
  116. curl_close($ch);
  117. file_put_contents($cachePath . '/cache/' . end($map), $result);
  118. }
  119. return $cachePath . '/cache/' . end($map);
  120. }
  121. return $resource;
  122. }
  123. //Refreshed Div:
  124. //Below is under construction:
  125. // Usage: $data .= PopupData($id);
  126. // PopupBuild($data);
  127. function PopupTrigger($id){
  128. return "<a href='#' class='ex".$id."trigger'></a>";
  129. }
  130. function PopupData($id,$link){//Trigger: ex($id)trigger
  131. return "$('#ex".$id."').jqm({ajax: '$link', trigger: 'a.ex".$id."trigger'});";
  132. }
  133. function PopupBuild($data){
  134. return "<script type='text/javascript'>$(document).ready(function()\{".$data."\});</script>";
  135. }
  136. function create_home_selector($module, $subpage, $server_homes) {
  137. if ($server_homes == "show_all")
  138. {
  139. echo "<form method='GET' action=''>\n";
  140. echo "<input type='hidden' name='m' value='".$module."' />\n";
  141. if( $subpage ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  142. echo "<input type='SUBMIT' value='" . get_lang('show_all') . "'/>\n";
  143. echo "</form>\n";
  144. }
  145. else
  146. {
  147. foreach ($server_homes as $key => $row) {
  148. $home_name[$key] = $row['home_name'];
  149. $home_id[$key] = $row['home_id'];
  150. $mod_id[$key] = $row['home_id'];
  151. $ip[$key] = $row['ip'];
  152. $port[$key] = $row['port'];
  153. }
  154. array_multisort($home_name, $ip, $port, $mod_id, $home_id, SORT_DESC, $server_homes);
  155. echo "<form method='GET' name='select' action=''>\n";
  156. echo "<input type='hidden' name='m' value='".$module."' />\n";
  157. if( $subpage ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  158. echo "<select onchange=".'"this.form.submit()"'." name='home_id'>\n";
  159. echo "<option></option>\n";
  160. foreach ( $server_homes as $server_home )
  161. {
  162. if( isset( $_GET['home_id'] ) and $_GET['home_id'] == $server_home['home_id'] )
  163. $selected = 'selected="selected"';
  164. else
  165. $selected = '';
  166. echo "<option value='". $server_home['home_id'] . "' $selected >" . htmlentities($server_home['home_name']) . "</option>\n";
  167. }
  168. echo "</select>\n";
  169. echo "</form>";
  170. }
  171. }
  172. function create_home_selector_address($module, $subpage, $server_homes, $extra_inputs = FALSE, $method = "GET") {
  173. $home_name = array();
  174. $home_id = array();
  175. $mod_id = array();
  176. $ip = array();
  177. $port = array();
  178. foreach ($server_homes as $key => $row) {
  179. if( !isset($row['ip']) or !isset($row['mod_id']) )
  180. {
  181. unset($server_homes[$key]);
  182. continue;
  183. }
  184. $home_name[$key] = $row['home_name'];
  185. $home_id[$key] = $row['home_id'];
  186. $mod_id[$key] = $row['home_id'];
  187. $ip[$key] = $row['ip'];
  188. $port[$key] = $row['port'];
  189. }
  190. # Make sure it has at least one server with ip and mod.
  191. if (empty($home_name))
  192. {
  193. return;
  194. }
  195. if( isset($_GET['home_id-mod_id-ip-port']) and $_GET['home_id-mod_id-ip-port'] != "" )
  196. {
  197. list($get_home_id,
  198. $get_mod_id,
  199. $get_ip,
  200. $get_port) = explode( "-", $_GET['home_id-mod_id-ip-port'] );
  201. }
  202. echo "<form method='$method' name='select' action=''>\n";
  203. echo "<input type='hidden' name='m' value='$module' />\n";
  204. if( $subpage ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  205. if($extra_inputs)
  206. {
  207. foreach($extra_inputs as $input)
  208. {
  209. echo "<input type='" . $input['type'] . "' name='" . $input['name'] . "' value='" . $input['value'] . "' />\n";
  210. }
  211. }
  212. echo "<select onchange=\"this.form.submit();\" name='home_id-mod_id-ip-port'>\n";
  213. echo "<option></option>\n";
  214. array_multisort($home_name, $ip, $port, $mod_id,
  215. $home_id, SORT_DESC, $server_homes);
  216. foreach ( $server_homes as $server_home )
  217. {
  218. $display_ip = checkDisplayPublicIP($server_home['display_public_ip'],$server_home['ip'] != $server_home['agent_ip'] ? $server_home['ip'] : $server_home['agent_ip']);
  219. if(isset($_GET['home_id-mod_id-ip-port']) and
  220. $get_home_id == $server_home['home_id'] and
  221. $get_mod_id == $server_home['mod_id'] and
  222. $get_ip == $server_home['ip'] and
  223. $get_port == $server_home['port'])
  224. $selected = 'selected="selected"';
  225. else
  226. $selected = '';
  227. echo "<option value='". $server_home['home_id'] .
  228. "-" . $server_home['mod_id'] . "-" . $server_home['ip'] .
  229. "-" . $server_home['port'] . "' $selected >" .
  230. htmlentities($server_home['home_name']) . " - " . $display_ip .
  231. ":" . $server_home['port'] . "</option>\n";
  232. }
  233. echo "</select>\n";
  234. echo "</form>";
  235. }
  236. function create_home_selector_game_type($module, $subpage, $server_homes) {
  237. echo "<form method='GET' name='select' action=''>\n".
  238. "<input type='hidden' name='m' value='".$module."' />\n";
  239. if( $subpage != "" ) echo "<input type='hidden' name='p' value='".$subpage."' />\n";
  240. echo "<select onchange=".'"this.form.submit()"'." name='home_cfg_id'>\n".
  241. "<option>".get_lang('game_type')."</option>\n";
  242. $servers_by_game_name = array();
  243. $list_of_servers_by_game_name_already_displayed = array();
  244. foreach( $server_homes as $server_home )
  245. {
  246. if( !isset($server_home['ip']) or !isset($server_home['mod_id']) )
  247. continue;
  248. $servers_by_game_name[$server_home["game_name"] . "{SPLIT_STRING_OGP}" . $server_home["game_key"]] = $server_home['home_cfg_id'];
  249. if(array_key_exists($server_home["game_name"], $list_of_servers_by_game_name_already_displayed)){
  250. if(array_key_exists($server_home['game_key'], $list_of_servers_by_game_name_already_displayed[$server_home["game_name"]])){
  251. $list_of_servers_by_game_name_already_displayed[$server_home["game_name"]][$server_home['game_key']] = $list_of_servers_by_game_name_already_displayed[$server_home["game_name"]][$server_home['game_key']] + 1;
  252. }else{
  253. $list_of_servers_by_game_name_already_displayed[$server_home["game_name"]][$server_home['game_key']] = 1;
  254. }
  255. }else{
  256. $list_of_servers_by_game_name_already_displayed[$server_home["game_name"]] = array($server_home['game_key'] => 1);
  257. }
  258. }
  259. ksort($servers_by_game_name);
  260. foreach( $servers_by_game_name as $game_name => $home_cfg_id )
  261. {
  262. $pieces = explode("{SPLIT_STRING_OGP}", $game_name);
  263. $game_key = $pieces[1];
  264. $game_key_parts = explode("_", $game_key);
  265. $game_key_os = $game_key_parts[1];
  266. $game_name = $pieces[0];
  267. $selected = (isset($_GET['home_cfg_id']) and $_GET['home_cfg_id'] == $home_cfg_id) ? 'selected="selected"' : "";
  268. echo "<option value='". $home_cfg_id . "' $selected >" . $game_name;
  269. if(count(array_keys($list_of_servers_by_game_name_already_displayed[$game_name])) > 1){
  270. echo " | " . ucfirst($game_key_os);
  271. }
  272. echo "</option>\n";
  273. }
  274. echo "</select>\n</form>\n";
  275. }
  276. function mymail($email_address, $subject, $message, $panel_settings, $user_to_panel = FALSE){
  277. global $view;
  278. if( empty( $panel_settings['panel_name'] ) )
  279. $panel_name = "Open Game Panel";
  280. else
  281. $panel_name = $panel_settings['panel_name'];
  282. // PHP Mailer
  283. require_once("PHPMailer/class.phpmailer.php");
  284. require_once("PHPMailer/class.smtp.php");
  285. // Create the mail object using the Mail::factory method
  286. $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
  287. $mail->IsSMTP(); // telling the class to use SMTP
  288. $mymail = TRUE;
  289. try
  290. {
  291. $mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
  292. // 1 = errors and messages
  293. // 2 = messages only
  294. // SMTP server
  295. if (isset($panel_settings['smtp_server']) and !empty($panel_settings['smtp_server']))
  296. $mail->Host = $panel_settings['smtp_server'];
  297. else
  298. $mail->Host = 'localhost';
  299. // set the SMTP port
  300. if (isset($panel_settings['smtp_port']) and !empty($panel_settings['smtp_port']))
  301. $mail->Port = $panel_settings['smtp_port'];
  302. else
  303. $mail->Port = 25;
  304. // sets the prefix to the servier
  305. if (isset($panel_settings['smtp_ssl']) and $panel_settings['smtp_ssl'] == 1)
  306. $mail->SMTPSecure = "ssl";
  307. elseif (isset($panel_settings['smtp_tls']) and $panel_settings['smtp_tls'] == 1)
  308. $mail->SMTPSecure = "tls";
  309. if (isset($panel_settings['smtp_login']) and !empty($panel_settings['smtp_login']))
  310. {
  311. // enable SMTP authentication
  312. $mail->SMTPAuth = true;
  313. // SMTP username
  314. $mail->Username = $panel_settings['smtp_login'];
  315. if (isset($panel_settings['smtp_passw']) and !empty($panel_settings['smtp_passw']))
  316. {
  317. // SMTP password
  318. $mail->Password = $panel_settings['smtp_passw'];
  319. }
  320. }
  321. if(empty($panel_settings['panel_email_address'])){
  322. $panel_email = "[email protected]";
  323. }else{
  324. $panel_email = $panel_settings['panel_email_address'];
  325. }
  326. //$email_addresses = explode( ",", $email_address );
  327. // Cheap way to parse Bcc addresses as defined in register-exec.php
  328. $bcc_email_addresses = explode( "|", $email_address );
  329. if (isset($bcc_email_addresses[1])) {
  330. $email_addresses = explode( ",", $bcc_email_addresses[1] );
  331. $bcc_email_addresses = explode( ",", $bcc_email_addresses[0] );
  332. } else {
  333. $bcc_email_addresses = 0;
  334. $email_addresses = explode( ",", $email_address );
  335. }
  336. if( $user_to_panel )
  337. {
  338. $mail->AddAddress($panel_email);
  339. $user_to_panel = is_bool($user_to_panel) ? "" : $user_to_panel; // True boolean or user name string
  340. foreach ( $email_addresses as $address )
  341. {
  342. $mail->SetFrom($address,$user_to_panel);
  343. $mail->AddReplyTo($address,$user_to_panel);
  344. }
  345. }
  346. else // panel to user
  347. {
  348. foreach ( $email_addresses as $address )
  349. {
  350. $mail->AddAddress($address);
  351. }
  352. // Loop through Bcc addresses, if any, and add them as proper Bcc recipients
  353. if ($bcc_email_addresses != 0)
  354. {
  355. foreach ( $bcc_email_addresses as $bcc_address )
  356. {
  357. if ($bcc_address != "")
  358. $mail->addBCC($bcc_address);
  359. }
  360. }
  361. $mail->SetFrom($panel_email,$panel_name);
  362. $mail->AddReplyTo($panel_email,$panel_name);
  363. }
  364. $mail->CharSet = $view->charset;
  365. $mail->Subject = $subject;
  366. $mail->MsgHTML($message);
  367. $mail->SMTPOptions = array(
  368. 'ssl' => array(
  369. 'verify_peer' => false,
  370. 'verify_peer_name' => false,
  371. 'allow_self_signed' => true
  372. )
  373. );
  374. $mail->Send();
  375. }
  376. catch (phpmailerException $e)
  377. {
  378. $mymail = FALSE;
  379. echo $e->errorMessage(); //Pretty error messages from PHPMailer
  380. }
  381. catch (Exception $e)
  382. {
  383. $mymail = FALSE;
  384. echo $e->getMessage(); //Boring error messages from anything else!
  385. }
  386. return $mymail;
  387. }
  388. if( !function_exists("sys_get_temp_dir") )
  389. {
  390. function sys_get_temp_dir(){
  391. if ($temp = getenv('TMP') ) {
  392. if (file_exists($temp)) { return realpath($temp); }
  393. }
  394. if ($temp = getenv('TEMP') ) {
  395. if (file_exists($temp)) { return realpath($temp); }
  396. }
  397. if ($temp = getenv('TMPDIR') ) {
  398. if (file_exists($temp)) { return realpath($temp); }
  399. }
  400. // trick for creating a file in system's temporary dir
  401. // without knowing the path of the system's temporary dir
  402. $temp = tempnam(__FILE__, '');
  403. if (file_exists($temp)) {
  404. unlink($temp);
  405. return realpath(dirname($temp));
  406. }
  407. return null;
  408. }
  409. }
  410. function set_firewall($remote, $firewall_settings, $action, $port, $ip = FALSE)
  411. {
  412. if($action == "allow" or $action == "deny")
  413. {
  414. if($ip)
  415. $command = str_replace("%IP%",$ip,str_replace("%PORT%",$port,$firewall_settings[$action.'_ip_port_command']));
  416. else
  417. $command = str_replace("%PORT%",$port,$firewall_settings[$action.'_port_command']);
  418. }
  419. if(isset($command))
  420. return $remote->sudo_exec($command);
  421. else
  422. return FALSE;
  423. }
  424. function strip_real_escape_string($text)
  425. {
  426. $search = array('\"', "\'", "\\r", "\\n","\\\\");
  427. $replace = array('"', "'", "\r", "\n", '\\');
  428. $text = str_replace($search, $replace, $text);
  429. return $text;
  430. }
  431. function get_true_boolean($bool)
  432. {
  433. if ( (int) $bool > 0 )
  434. $ret = true;
  435. else
  436. {
  437. $lowered_bool = strtolower($bool); // that could be 'True' or 'true' or 'TRUE', etc...
  438. if( $lowered_bool === "true" || $lowered_bool === "on" || $lowered_bool === "yes" )
  439. $ret = true;
  440. else
  441. $ret = false;
  442. }
  443. return $ret;
  444. }
  445. function get_temp_dir($curdir)
  446. {
  447. $temp = sys_get_temp_dir();
  448. if( ini_get('open_basedir') )
  449. {
  450. $dirs = preg_split( "/:|;/", ini_get('open_basedir') , -1, PREG_SPLIT_NO_EMPTY );
  451. if( !in_array($temp, $dirs) )
  452. $temp = $curdir . DIRECTORY_SEPARATOR . 'temp';
  453. }
  454. if( $temp == null )
  455. $temp = $curdir . DIRECTORY_SEPARATOR . 'temp';
  456. if( !file_exists($temp) )
  457. if( is_writable( dirname($temp) ) ) mkdir($temp);
  458. return $temp;
  459. }
  460. // ### Escape some characters that could break the server startup or make the user capable to run other programs. ###
  461. // \ (backslash) -> At the end of the string, can scape the next quote,
  462. // and is commonly used to create Windows paths, must be escaped.
  463. // " (quote) -> Not escaped quote, without an ending quote, would break the startup command.
  464. // ' (single quote) -> same than quote.
  465. // | (pipe) -> Not escaped pipe would break the startup command and could use the next argument as new command.
  466. // & (ampersand) -> Same than pipe. If double ampersand is used it would run the command (if any) once the server process ends.
  467. // ; (semicolon) -> Same than double ampersand.
  468. // > (greater than) -> Could redirect the server output and ignore the next arguments.
  469. // < (lower than) -> Could send the content of a file to the server executable and ignore the the next arguments.
  470. // ` (apostrophe) -> Could get the return value of a given (system) command or variable.
  471. // $ (¿sigil?) -> Same than apostrophe.
  472. // ( and ) (parenthesis) -> starts or ends a bash/batch statement, could break the server startup
  473. // [ and ] (test) -> test is part of bash language, could break the server startup
  474. function clean_server_param_value($value, $cli_allow_chars) {
  475. $value = strip_real_escape_string($value);
  476. $escape_chars = array("\\", "\"", "'", "|", "&", ";", ">", "<", "`", "$", "(", ")", "[", "]");
  477. if($cli_allow_chars)
  478. {
  479. $cli_allow_chars = str_split($cli_allow_chars);
  480. $escape_chars = array_diff($escape_chars, $cli_allow_chars);
  481. }
  482. $find = array();
  483. $repl = array();
  484. foreach($escape_chars as $char)
  485. {
  486. $find[] = '%'.preg_quote($char).'%';
  487. $char = $char == '\\' ? preg_quote('\\\\') : $char;
  488. $repl[] = '\\'.$char;
  489. }
  490. return preg_replace($find, $repl, $value);
  491. }
  492. // ### Validate FTP user/password and control_protocol_password. ###
  493. function validate_login($value) {
  494. $value = strip_real_escape_string($value);
  495. $value = trim($value);
  496. $find = '%\\\\|"|\||&|;|>|<|`|\$|\s%';
  497. return preg_match($find, $value) ? FALSE : $value;
  498. }
  499. // Order a multidimensional array by keys. Source http://php.net/manual/es/function.array-multisort.php#100534
  500. function array_orderby()
  501. {
  502. $args = func_get_args();
  503. $data = array_shift($args);
  504. foreach ($args as $n => $field)
  505. {
  506. if (is_string($field))
  507. {
  508. $tmp = array();
  509. foreach ($data as $key => $row)
  510. $tmp[$key] = $row[$field];
  511. $args[$n] = $tmp;
  512. }
  513. }
  514. $args[] = &$data;
  515. call_user_func_array('array_multisort', $args);
  516. return array_pop($args);
  517. }
  518. // Escape a single quote or multiple single quotes
  519. // in a string that is passed to bash
  520. // and this string is single quoted
  521. function esc_squote($str)
  522. {
  523. return preg_replace("#('+)#", "'\"\${1}\"'", $str);
  524. }
  525. function get_game_selector($os, $game_cfgs, $home_cfg_id = FALSE)
  526. {
  527. if(preg_match("/64/", $os))
  528. {
  529. $arch_64_bit = true;
  530. }
  531. if(preg_match("/linux/i", $os))
  532. {
  533. if(preg_match("/wine/i", $os))
  534. {
  535. $os_match = $arch_64_bit ? '/(win|linux)(32|64)?$/i' : '/(win|linux)(32)?$/i';
  536. }
  537. else
  538. {
  539. $os_match = $arch_64_bit ? '/(linux)(32|64)?$/i' : '/(linux)(32)?$/i';
  540. }
  541. }
  542. elseif(preg_match("/cygwin/i", $os))
  543. {
  544. $os_match = $arch_64_bit ? '/(win)(32|64)?$/i' : '/(win)(32)?$/i';
  545. }
  546. else
  547. {
  548. $os_match = '/(win|linux)(32|64)?$/i';
  549. }
  550. $selector = "";
  551. foreach ( $game_cfgs as $row )
  552. {
  553. if ( preg_match($os_match, $row['game_key'], $matches) )
  554. {
  555. $selector .= "<option value='".$row['home_cfg_id']."' ".
  556. ($home_cfg_id == $row['home_cfg_id'] ? 'selected="selected"' : "").
  557. ">".$row['game_name'].
  558. (preg_match('/^linux$/i', $matches[1]) ? " (Linux" : " (Windows").
  559. ((isset($matches[2]) and $matches[2] == '64') ? " 64bit)" : ")").
  560. "</option>\n";
  561. }
  562. }
  563. return $selector;
  564. }
  565. function getClientIPAddress(){
  566. if(isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])){
  567. $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
  568. }else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  569. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  570. }else if(isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP'])){
  571. $ip = $_SERVER['HTTP_X_REAL_IP'];
  572. }
  573. if(filter_var(@(string)$ip, FILTER_VALIDATE_IP)){
  574. return $ip;
  575. }
  576. return $_SERVER['REMOTE_ADDR'];
  577. }
  578. function getOGPSiteURL(){
  579. $url = '';
  580. $scheme = ( isset($_SERVER['HTTPS']) and get_true_boolean($_SERVER['HTTPS']) ) ? "https://" : "http://";
  581. $url .= $scheme;
  582. if(strtolower($_SERVER['HTTP_HOST']) == "localhost"){
  583. $ip = getRemoteIPAddressFromSite('http://grabip.tk/');
  584. if(!hasValue($ip)){
  585. if(cURLEnabled()){
  586. $ipOfServer = get_headers_curl("http://grabip.tk/", $referrer, $agent);
  587. if(hasValue($ipOfServer) && is_array($ipOfServer)){
  588. $ipOfServer = $ipOfServer[0];
  589. if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $ipOfServer, $ip_match)) {
  590. $ipStr = $ip_match[0];
  591. if(isValidIP($ipStr) && !isPrivateIp($ipStr)){
  592. $ip = $ipStr;
  593. }
  594. }
  595. }
  596. }
  597. }
  598. }
  599. if(isset($ip) and !empty($ip)){
  600. $url .= $ip;
  601. }else{
  602. $url .= $_SERVER['HTTP_HOST'];
  603. }
  604. if(!empty($_SERVER['REQUEST_URI'])){
  605. $lastSlash = strrpos($_SERVER['REQUEST_URI'], "/");
  606. if($lastSlash !== false){
  607. $url .= substr($_SERVER['REQUEST_URI'], 0, $lastSlash);
  608. }
  609. }
  610. if(!empty($url)){
  611. return $url;
  612. }
  613. return false;
  614. }
  615. function getRemoteIPAddressFromSite($site){
  616. $str = "";
  617. if(isset($site) && !empty($site)){
  618. $str=trim(file_get_contents($site));
  619. // Look for an IP
  620. if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $str, $ip_match)) {
  621. $ip = $ip_match[0];
  622. if(isValidIP($ip) && !isPrivateIp($ip)){
  623. $str = $ip;
  624. }
  625. }
  626. }
  627. return $str;
  628. }
  629. function isValidIP($ip){
  630. 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)){
  631. return True;
  632. }else{
  633. return False;
  634. }
  635. }
  636. function isPrivateIp($ip){
  637. if(is_array($ip)) {
  638. $ret=false;
  639. foreach($ip as $i)
  640. $ret=$ret or isPrivateIp($i);
  641. return $ret;
  642. }
  643. return (substr($ip,0,7)=='192.168' or substr($ip,0,6)=='172.16' or substr($ip,0,3)=='10.');
  644. }
  645. function hasValue($val, $zeroAllowed = false){
  646. if(isset($val) && !empty($val)){
  647. return true;
  648. }else{
  649. if($zeroAllowed == true && $val == 0){
  650. return true;
  651. }else{
  652. return false;
  653. }
  654. }
  655. }
  656. function paginationPages($pageResults, $currentPage, $perPage, $pageUri, $pagesShown, $classPrefix) {
  657. $pagination = '<div id="pagination">';
  658. if ($pageResults > $perPage) {
  659. $totalPages = ceil($pageResults/$perPage);
  660. $pageStart = (($currentPage - $pagesShown) > 0) ? $currentPage - $pagesShown : 1;
  661. $pageEnd = (($currentPage + $pagesShown) < $totalPages) ? $currentPage + $pagesShown : $totalPages;
  662. if ($pageStart > 1) {
  663. $pagination .= '<span class="'.$classPrefix.'_paginationStart">
  664. <a href="'.$pageUri . ($currentPage-1) .'" class="'.$classPrefix.'_previousPageLink">&laquo;</a>
  665. <a href="'.$pageUri .'1" class="'.$classPrefix.'_firstPageLink">1</a>
  666. <span class='.$classPrefix.'_divider">&hellip;</span>
  667. </span>';
  668. }
  669. $pagination .= '<span class="'.$classPrefix.'_paginationPages">';
  670. for ($i=$pageStart; $i<=$pageEnd; ++$i) {
  671. if ($currentPage == $i) {
  672. $pagination .= '<a href="'.$pageUri . $i .'" class="'.$classPrefix.'_currentPageLink">['.$i.']</a>';
  673. } else {
  674. $pagination .= '<a href="'.$pageUri . $i .'" class="'.$classPrefix.'_pageLinks">'.$i.'</a>';
  675. }
  676. $pagination .= ($i < $pageEnd) ? ', ' : ' ';
  677. }
  678. $pagination .= '</span>';
  679. if ($pageEnd < $totalPages) {
  680. $pagination .= '<span class="'.$classPrefix.'_paginationEnd">
  681. <span class='.$classPrefix.'_divider">&hellip;</span>
  682. <a href="'.$pageUri . $totalPages .'" class="'.$classPrefix.'_lastPageLink">'.$totalPages.'</a>
  683. <a href="'.$pageUri . ($currentPage+1) .'" class="'.$classPrefix.'_nextPageLink">&raquo;</a>
  684. </span>';
  685. }
  686. }
  687. $pagination .= '</div>';
  688. return $pagination;
  689. }
  690. function checkDisplayPublicIP($display_public_ip,$internal_ip){
  691. // Set Cache Timer in Seconds
  692. $cache_timer = 600;
  693. // Exit Function when External IP is Internal IP or when Display Public IP is not set
  694. if($display_public_ip==$internal_ip || empty($display_public_ip)){
  695. return $internal_ip;
  696. }
  697. if(!isset($_SESSION['gethostbyname_cache'])){
  698. $_SESSION['gethostbyname_cache'] = array();
  699. }
  700. if(filter_var($display_public_ip, FILTER_VALIDATE_IP)){
  701. return $display_public_ip;
  702. }else{
  703. if(!array_key_exists($display_public_ip, $_SESSION['gethostbyname_cache'])){
  704. $_SESSION['gethostbyname_cache'][$display_public_ip] = array();
  705. $dns_check = dns_get_record($display_public_ip, DNS_A);
  706. $ipcheck = isset($dns_check[0]['ip']) ? $dns_check[0]['ip'] : $internal_ip;
  707. if($ipcheck!=$display_public_ip){
  708. $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'] = $ipcheck;
  709. $_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'] = time();
  710. }else{
  711. unset($_SESSION['gethostbyname_cache'][$display_public_ip]);
  712. return $internal_ip;
  713. }
  714. }else{
  715. if((time()-$_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'])>=$cache_timer){
  716. $dns_check = dns_get_record($display_public_ip, DNS_A);
  717. $ipcheck = isset($dns_check[0]['ip']) ? $dns_check[0]['ip'] : $internal_ip;
  718. if($ipcheck!=$display_public_ip){
  719. $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'] = $ipcheck;
  720. $_SESSION['gethostbyname_cache'][$display_public_ip]['stamp'] = time();
  721. }else{
  722. unset($_SESSION['gethostbyname_cache'][$display_public_ip]);
  723. return $internal_ip;
  724. }
  725. }
  726. }
  727. if(filter_var($_SESSION['gethostbyname_cache'][$display_public_ip]['ip'], FILTER_VALIDATE_IP)){
  728. return $_SESSION['gethostbyname_cache'][$display_public_ip]['ip'];
  729. }
  730. }
  731. return $internal_ip;
  732. }
  733. function startsWith($haystack, $needle) {
  734. // search backwards starting from haystack length characters from the end
  735. return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
  736. }
  737. function endsWith($haystack, $needle) {
  738. // search forward starting from end minus needle length characters
  739. return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
  740. }
  741. // Super ingenious function from https://stackoverflow.com/questions/5519630/php-preg-replace-x-occurence#answer-17047405
  742. function preg_replace_nth($pattern, $replacement, $subject, $nth=1) {
  743. return preg_replace_callback($pattern,
  744. function($found) use (&$pattern, &$replacement, &$nth) {
  745. $nth--;
  746. if ($nth==0) return preg_replace($pattern, $replacement, reset($found) );
  747. return reset($found);
  748. }, $subject,$nth);
  749. }
  750. // https://stackoverflow.com/questions/12559878/multidimensional-array-find-item-and-move-to-the-top
  751. function customShift($array, $keyToMoveOn, $valueToMoveOn){
  752. foreach($array as $key => $val){
  753. if($val[$keyToMoveOn] == $valueToMoveOn){
  754. unset($array[$key]);
  755. array_unshift($array, $val);
  756. return $array;
  757. }
  758. }
  759. return $array;
  760. }
  761. function getURLParam($param, $url){
  762. if(stripos($url, $param) !== false){
  763. $param = substr($url, stripos($url, $param) + strlen($param));
  764. if(stripos($param, "&")){
  765. $param = substr($param, 0, stripos($param, "&"));
  766. }
  767. return $param;
  768. }
  769. return false;
  770. }
  771. function utf8ize($d, $htmlEntities = true) {
  772. if (is_array($d)) {
  773. foreach ($d as $k => $v) {
  774. $d[$k] = utf8ize($v, $htmlEntities);
  775. }
  776. } else if (is_string ($d)) {
  777. if($htmlEntities){
  778. $d = htmlentities($d);
  779. }
  780. return mb_convert_encoding($d, "UTF-8", "UTF-8");
  781. }
  782. return $d;
  783. }
  784. function preReqInstalled($prereq){
  785. if (($prereq['type'] === "f" && function_exists($prereq['value'])) || ($prereq['type'] === "c" && class_exists($prereq['value'])) || ($prereq['type'] === "x" && extension_loaded($prereq['value']))){
  786. return true;
  787. }
  788. return false;
  789. }
  790. if (!function_exists('boolval')) {
  791. function boolval($val) {
  792. return (bool) $val;
  793. }
  794. }
  795. function getThemePath()
  796. {
  797. global $settings;
  798. $path = "";
  799. if ( isset($_SESSION['users_theme']) &&
  800. !empty($_SESSION['users_theme']) &&
  801. is_dir( 'themes/'.$_SESSION['users_theme'] ) &&
  802. is_file( 'themes/'.$_SESSION['users_theme'].'/layout.html') )
  803. {
  804. $path = 'themes/'.$_SESSION['users_theme'].'/';
  805. }
  806. // Using default theme if there is not one selected.
  807. else if ( !isset($settings['theme']) )
  808. {
  809. $path = 'themes/Revolution/';
  810. }
  811. else if ( is_dir( 'themes/'.$settings['theme'] ) &&
  812. is_file( 'themes/'.$settings['theme'].'/layout.html') )
  813. {
  814. $path = 'themes/'.$settings['theme'].'/';
  815. }
  816. // In case the theme that was selected is invalid print error and use default.
  817. else
  818. {
  819. $path = 'themes/Revolution/';
  820. }
  821. return $path;
  822. }
  823. function updateAllPanelModules(){
  824. global $db;
  825. if(file_exists('modules/modulemanager/module_handling.php')){
  826. require_once('modules/modulemanager/module_handling.php');
  827. $modules = $db->getInstalledModules();
  828. // update module manager first
  829. foreach ( $modules as $row )
  830. {
  831. if($row['folder'] == 'modulemanager')
  832. {
  833. update_module($db, $row['id'], $row['folder']);
  834. break;
  835. }
  836. }
  837. foreach ( $modules as $row )
  838. {
  839. if($row['folder'] == 'modulemanager')//already updated
  840. continue;
  841. update_module($db, $row['id'], $row['folder']);
  842. }
  843. }
  844. }
  845. function getRemoteContent($url, $timeout = 5, $referrer = ""){
  846. $useCURL = false;
  847. $agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0';
  848. try{
  849. $currentTimeout = ini_get('default_socket_timeout');
  850. ini_set('default_socket_timeout', $timeout); // Timeout in seconds
  851. $streamOptions = array(
  852. 'http' => array(
  853. 'method' => 'GET',
  854. 'user_agent' => $agent,
  855. 'timeout' => ($timeout + 3) // https://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting#answer-10236480
  856. ),
  857. 'ssl'=> array(
  858. 'verify_peer' => false,
  859. 'verify_peer_name' => false,
  860. )
  861. );
  862. if(!empty($referrer)){
  863. $streamOptions['header'] = array("Referer: $referer\r\n");
  864. }
  865. stream_context_set_default($streamOptions);
  866. $content = file_get_contents($url);
  867. if(empty($content) || strlen($content) <=5){
  868. $useCURL = true;
  869. }else{
  870. ini_set('default_socket_timeout', $currentTimeout); // Set it back to the original
  871. return $content;
  872. }
  873. }catch (Exception $e) {
  874. $useCURL = true;
  875. }
  876. if($useCURL && cURLEnabled()){
  877. try{
  878. $ch = curl_init();
  879. curl_setopt($ch, CURLOPT_URL, $url);
  880. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  881. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  882. curl_setopt($ch, CURLOPT_TIMEOUT, ($timeout + 3));
  883. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  884. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  885. curl_setopt($ch, CURLOPT_USERAGENT, $agent);
  886. if(!empty($referrer)){
  887. curl_setopt($ch, CURLOPT_REFERER, $referrer);
  888. }
  889. $data = curl_exec($ch);
  890. curl_close($ch);
  891. if(!empty($data)){
  892. return $data;
  893. }
  894. } catch (Exception $e) {
  895. }
  896. }
  897. return false;
  898. }
  899. function getQueryPortOverridesForGame($protocol, $ip, $port, $defaultQueryPort){
  900. $q_port = $defaultQueryPort;
  901. // Removed since mohaaservers.tk isn't the master server anymore for mohaa
  902. // Also, the query port is now defined in the XML, so it will always be plus 97 to the host port
  903. /*
  904. if(strpos($protocol, 'mohaa') !== false){
  905. $realQPort = getRemoteContent("http://mohaaservers.tk/get_query_port_fast.php?ip=" . $ip . ":" . $port);
  906. if($realQPort != -1 && is_numeric($realQPort)){
  907. $q_port = $realQPort;
  908. }
  909. }
  910. */
  911. return $q_port;
  912. }
  913. function removeInvalidFileNameCharacters($string){
  914. global $settings;
  915. $pattern = '/[\^\$\*\+\?\(\)\[\{\\\|\]!@#%&=~`,\'<>"}\s]/i';
  916. if(is_array($settings) && array_key_exists("regex_invalid_file_name_chars", $settings) && !empty($settings["regex_invalid_file_name_chars"])){
  917. $pattern = $settings["regex_invalid_file_name_chars"];
  918. }
  919. $string = preg_replace($pattern, '', $string);
  920. return $string;
  921. }
  922. function deleteMysqlAddonDatabasesForGameServerHome($home_id){
  923. global $db, $db_host, $db_user, $db_pass, $db_name, $table_prefix;
  924. if ( function_exists('mysqli_connect') )
  925. require_once("modules/mysql/mysqli_database.php");
  926. else
  927. require_once("modules/mysql/mysql_database.php");
  928. require_once('includes/lib_remote.php');
  929. $modDb = new MySQLModuleDatabase();
  930. require_once("includes/config.inc.php");
  931. $modDb->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  932. if(hasValue($home_id) && is_numeric($home_id)){
  933. $dbDeletedCount = 0;
  934. $dbsToDelete = $modDb->getMysqlDBsbyHomeId($home_id);
  935. if(is_array($dbsToDelete) && count($dbsToDelete)){
  936. foreach($dbsToDelete as $dbToDel){
  937. $mysql_db = $dbToDel;
  938. if($mysql_db['remote_server_id'] != "0")
  939. {
  940. $remote_server = $db->getRemoteServer($mysql_db['remote_server_id']);
  941. $remote = new OGPRemoteLibrary($remote_server['agent_ip'],$remote_server['agent_port'],$remote_server['encryption_key'],$remote_server['timeout']);
  942. $host_stat = $remote->status_chk();
  943. if($host_stat === 1 )
  944. {
  945. $remote->exec('mysql --host=localhost --port='.$mysql_db['mysql_port'].' -uroot -p'.$mysql_db['mysql_root_passwd'].
  946. ' -e "DROP DATABASE '.$mysql_db['db_name'].";DROP USER '".$mysql_db['db_user']."'@'%';\"");
  947. }
  948. }
  949. else
  950. {
  951. if( function_exists('mysqli_connect') )
  952. {
  953. @$link = mysqli_connect($mysql_db['mysql_ip'], 'root', $mysql_db['mysql_root_passwd'], "", $mysql_db['mysql_port']);
  954. if ( $link !== FALSE )
  955. {
  956. $queries = array("DROP DATABASE ".$mysql_db['db_name'].";",
  957. "DROP USER '".$mysql_db['db_user']."'@'%';");
  958. foreach( $queries as $query )
  959. {
  960. @$return = mysqli_query($link, $query);
  961. if(!$return)
  962. break;
  963. }
  964. mysqli_close($link);
  965. $db->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  966. }
  967. }
  968. else
  969. {
  970. @$link = mysql_connect($mysql_db['mysql_ip'].':'.$mysql_db['mysql_port'], 'root', $mysql_db['mysql_root_passwd']);
  971. if ( $link !== FALSE )
  972. {
  973. $queries = array("DROP DATABASE ".$mysql_db['db_name'].";",
  974. "DROP USER '".$mysql_db['db_user']."'@'%';");
  975. foreach( $queries as $query )
  976. {
  977. @$return = mysql_query($query);
  978. if(!$return)
  979. break;
  980. }
  981. mysql_close($link);
  982. $db->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  983. }
  984. }
  985. }
  986. if ( $modDb->removeMysqlServerDB($db_id) !== FALSE )
  987. {
  988. $dbDeletedCount++;
  989. }
  990. }
  991. if($dbDeletedCount == count($dbsToDelete)){
  992. return true;
  993. }else if($dbDeletedCount > 0){
  994. return 'partial';
  995. }
  996. }
  997. }
  998. return false;
  999. }
  1000. function get_magic_quotes_gpc_wrapper(){
  1001. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()){
  1002. return true;
  1003. }
  1004. return false;
  1005. }
  1006. ?>