functions.php 35 KB

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