functions.php 33 KB

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