1
0

helpers.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. // Globals
  25. $OGPLangPre = "OGP_LANG_";
  26. define('OGP_GITHUB_MAIN_URL', 'https://github.com/OpenGamePanel/');
  27. // Ignore any request with unwanted values at 'm' or 'p'
  28. if( isset($_REQUEST['m']) and !preg_match("/^([a-z]|[0-9]|_|-)+$/i", $_REQUEST['m']) )
  29. unset($_POST['m'], $_GET['m'], $_REQUEST['m']);
  30. if( isset($_REQUEST['p']) and ( !isset($_REQUEST['m']) or !preg_match("/^([a-z]|[0-9]|_|-)+$/i", $_REQUEST['p']) ) )
  31. {
  32. if( isset($_REQUEST['m']) )
  33. unset($_POST['m'], $_GET['m'], $_REQUEST['m']);
  34. unset($_POST['p'], $_GET['p'], $_REQUEST['p']);
  35. }
  36. if(file_exists(__DIR__ . "/lang.php")){
  37. require_once(__DIR__ . "/lang.php");
  38. }else{
  39. require_once("lang.php");
  40. }
  41. /// \return the database object when the creation was successfull.
  42. /// \return FALSE if database type was invalid.
  43. /// \return negative value in case of error
  44. function createDatabaseConnection($db_type,$db_host,$db_user,$db_pass,$db_name,$table_prefix)
  45. {
  46. if ( $db_type == "mysql" )
  47. {
  48. if ( function_exists('mysqli_connect') )
  49. require_once("includes/database_mysqli.php");
  50. else
  51. die("<p class='failure'>OGP requires the <a href='http://php.net/manual/en/book.mysqli.php' target='_blank'>mysqli PHP extension</a>. Please install it, and then try again.</p>");
  52. $database = new OGPDatabaseMysql();
  53. $connect_value = $database->connect($db_host,$db_user,$db_pass,$db_name,$table_prefix);
  54. if ($connect_value === TRUE)
  55. return $database;
  56. // See return values from database classes.
  57. return $connect_value;
  58. }
  59. else
  60. {
  61. return -98;
  62. }
  63. }
  64. function get_db_error_text ($db_retval, &$error_text)
  65. {
  66. if (is_a($db_retval,"OGPDatabase"))
  67. return FALSE;
  68. switch ($db_retval) {
  69. case -1:
  70. $error_text = get_lang("db_error_invalid_host");
  71. break;
  72. case -11:
  73. $error_text = get_lang("db_error_invalid_user_and_pass");
  74. break;
  75. case -12:
  76. $error_text = get_lang("db_error_invalid_database");
  77. break;
  78. case -98:
  79. $error_text = get_lang("db_error_invalid_db_type");
  80. break;
  81. case -99:
  82. $error_text = get_lang("db_error_module_missing");
  83. break;
  84. default:
  85. $error_text = get_lang_f("db_unknown_error",$db_retval);
  86. break;
  87. }
  88. return TRUE;
  89. }
  90. // Create a list of files or folders and store them in an array
  91. function makefilelist($folder, $filter, $sort=true, $type="files") {
  92. $res = array();
  93. $filter = explode("|", $filter);
  94. $temp = opendir($folder);
  95. while ($file = readdir($temp)) {
  96. if ($type == "files" && !in_array($file, $filter)) {
  97. if (!is_dir($folder.$file)) $res[] = $file;
  98. } elseif ($type == "folders" && !in_array($file, $filter)) {
  99. if (is_dir($folder.$file)) $res[] = $file;
  100. }
  101. }
  102. closedir($temp);
  103. if ($sort) sort($res);
  104. return $res;
  105. }
  106. function isPortValid($port)
  107. {
  108. return ( $port > 0 && $port <= 65535 );
  109. }
  110. function cleanFilenames($file_array)
  111. {
  112. $retval = array();
  113. foreach($file_array as $file_name)
  114. {
  115. if($file_name === "." && $file_name === "..")
  116. continue;
  117. /// \todo @ is because of files without . in the name.extension.
  118. @list($value, $ext) = explode(".", $file_name);
  119. array_push($retval,$value);
  120. }
  121. return $retval;
  122. }
  123. function clean_id_string($id_string)
  124. {
  125. return preg_replace("/-/","",$id_string);
  126. }
  127. function get_first_existing_file($paths, $referrer = "", $agent = "")
  128. {
  129. foreach ($paths as $path)
  130. {
  131. if(preg_match("/^http/", $path))
  132. {
  133. if(cURLEnabled()){
  134. // Get headers using cURL
  135. $file_headers = @get_headers_curl($path, $referrer, $agent);
  136. }else{
  137. // Five second timeout...
  138. $origSocketTimeout = ini_get('default_socket_timeout');
  139. ini_set('default_socket_timeout', 5);
  140. // Get headers with a socket timeout value of 5 seconds...
  141. if(isset($agent) && !empty($agent)){
  142. stream_context_set_default(
  143. array(
  144. 'http' => array(
  145. 'method' => 'GET',
  146. 'user_agent' => $agent
  147. )
  148. )
  149. );
  150. }
  151. $file_headers = @get_headers($path);
  152. // Reset timeout to old value
  153. ini_set('default_socket_timeout', $origSocketTimeout);
  154. }
  155. if(trim($file_headers[0]) == 'HTTP/1.0 200 OK' || trim($file_headers[0]) == 'HTTP/1.1 200 OK' || trim($file_headers[0]) == 'HTTP/2 200' || trim($file_headers[0]) == 'HTTP/1.1 200' || trim($file_headers[0]) == 'HTTP/1.0 200') return $path;
  156. }
  157. if (file_exists($path)) return $path;
  158. }
  159. return false;
  160. }
  161. function cURLEnabled(){
  162. return function_exists('curl_version');
  163. }
  164. function get_headers_curl($url, $referrer = "", $agent = "")
  165. {
  166. $ch = curl_init();
  167. curl_setopt($ch, CURLOPT_URL, $url);
  168. curl_setopt($ch, CURLOPT_HEADER, true);
  169. curl_setopt($ch, CURLOPT_NOBODY, true);
  170. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  171. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  172. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  173. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  174. if(isset($referrer) && !empty($referrer)){
  175. curl_setopt($ch, CURLOPT_REFERER, $referrer);
  176. }
  177. if(isset($agent) && !empty($agent)){
  178. curl_setopt($ch, CURLOPT_USERAGENT, $agent);
  179. }
  180. // 5 second timeout should be reasonable...
  181. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  182. $r = curl_exec($ch);
  183. $r = explode("\n", $r);
  184. if(is_array($r)){
  185. $r = array_filter($r, 'strlen');
  186. // Get rid of the last index value which appears to be holding odd characters
  187. array_pop($r);
  188. }
  189. return $r;
  190. }
  191. function clean_path($path)
  192. {
  193. // Replace multiple / or \ marks with one /.
  194. return preg_replace("/[\/|\\\\]+/","/",$path);
  195. }
  196. function sanitizeInputStr($strToProcess, $removeHTML = true, $trim = true, $removeQuotes = true){
  197. // Remove quotes from string
  198. if($removeQuotes){
  199. // For magic quotes or addslashes values
  200. $strToProcess = str_replace('\"', '', $strToProcess);
  201. $strToProcess = str_replace("\'", "", $strToProcess);
  202. // Remove any possible leftovers
  203. $strToProcess = str_replace('"', '', $strToProcess);
  204. $strToProcess = str_replace("'", "", $strToProcess);
  205. }
  206. // Trim string value
  207. if($trim){
  208. $strToProcess = trim($strToProcess);
  209. }
  210. // Remove HTML tags
  211. if($removeHTML){
  212. $strToProcess = strip_tags($strToProcess);
  213. }
  214. // Return the processed string
  215. return $strToProcess;
  216. }
  217. function startSession(){
  218. if(!isset($_SESSION)){
  219. session_name("opengamepanel_web");
  220. session_start();
  221. }
  222. }
  223. function updateGameConfigsPostInstall($clear_old = false){
  224. global $db;
  225. if(file_exists('modules/config_games/server_config_parser.php')){
  226. require_once('modules/config_games/server_config_parser.php');
  227. }else{
  228. require_once(__DIR__ . '/../modules/config_games/server_config_parser.php');
  229. }
  230. if(function_exists("read_server_config")){
  231. removeOldGameConfigs();
  232. $files = glob(SERVER_CONFIG_LOCATION."*.xml");
  233. if ( empty($files) )
  234. {
  235. return false;
  236. }
  237. $db->clearGameCfgs($clear_old);
  238. $counter = 0;
  239. foreach ( $files as $config_file )
  240. {
  241. $config = read_server_config($config_file);
  242. if ( !$db->addGameCfg($config) )
  243. {
  244. $counter++;
  245. continue;
  246. }
  247. }
  248. if($counter == count($files)){
  249. return false;
  250. }
  251. return true;
  252. }
  253. return false;
  254. }
  255. function isCoreModule($module){
  256. $coreModules = array('modulemanager', 'server', 'settings', 'gamemanager', 'config_games', 'administration', 'user_games', 'user_admin', 'update');
  257. if(in_array($module, $coreModules)){
  258. return true;
  259. }
  260. return false;
  261. }
  262. function recursiveDelete($str) {
  263. if (file_exists($str) && is_file($str)) {
  264. return @unlink($str);
  265. }else if(file_exists($str) && is_dir($str)){
  266. // Strip the trailing slash from the directory if there is one
  267. $str = rtrim($str,'/');
  268. // Get the index of the last slash in the path so that we can pull just the relative folder name being scanned
  269. $lastSlash = strrpos($str, "/");
  270. if($lastSlash != false){
  271. // Get the folder name so we can ignore "." and ".." which relates to current directory and up a level
  272. $folder = substr($str, $lastSlash + 1);
  273. if($folder != ".." && $folder != "."){
  274. $scan = glob($str . '/{,.}*', GLOB_BRACE);
  275. if(isset($scan) && is_array($scan)){
  276. foreach($scan as $index=>$path) {
  277. recursiveDelete($path);
  278. }
  279. }
  280. return @rmdir($str);
  281. }
  282. }
  283. }
  284. return true;
  285. }
  286. function removeOldGameConfigs(){ // Wrote this function in-case we rename config files like we did for TS3 (https://sourceforge.net/p/hldstart/svn/3376/)
  287. $oldConfigsToRemove = array(
  288. 'modules/config_games/server_configs/ins_win32.xml',
  289. 'modules/config_games/server_configs/ins.xml',
  290. 'modules/config_games/server_configs/insurgency.xml',
  291. 'modules/config_games/server_configs/left_4_dead.xml',
  292. 'modules/config_games/server_configs/left_4_dead2.xml',
  293. 'modules/config_games/server_configs/left_4_dead2_win.xml',
  294. 'modules/config_games/server_configs/warsow.xml',
  295. 'modules/config_games/server_configs/big_brother_bot.xml',
  296. 'modules/config_games/server_configs/big_brother_bot_win.xml',
  297. 'modules/config_games/server_configs/egs_win64.xml',
  298. 'modules/config_games/server_configs/7_days_to_die_linux.xml',
  299. 'modules/config_games/server_configs/7_days_to_die_linux64.xml',
  300. 'modules/config_games/server_configs/TrackManiaForever.xml',
  301. 'modules/config_games/server_configs/trackmania_nations.xml',
  302. 'modules/config_games/server_configs/ventrilo.xml',
  303. 'modules/config_games/server_configs/ventrilo_win.xml',
  304. 'modules/config_games/server_configs/vice_city_multiplayer.xml',
  305. 'modules/config_games/server_configs/vice_city_multiplayer_win.xml',
  306. 'modules/config_games/server_configs/san_andreas_multiplayer.xml',
  307. 'modules/config_games/server_configs/san_andreas_multiplayer_win.xml',
  308. 'modules/config_games/server_configs/MultiTheftAuto.xml',
  309. 'modules/config_games/server_configs/MultiTheftAuto_win.xml',
  310. 'modules/config_games/server_configs/alienvspredator2010.xml',
  311. 'modules/config_games/server_configs/cod_mw2_win.xml',
  312. 'modules/config_games/server_configs/cod_uo_win.xml',
  313. 'modules/config_games/server_configs/cod_1_win.xml',
  314. 'modules/config_games/server_configs/cod_mw3_win.xml',
  315. 'modules/config_games/server_configs/cod2.xml',
  316. 'modules/config_games/server_configs/cod2_win.xml',
  317. 'modules/config_games/server_configs/cod4.xml',
  318. 'modules/config_games/server_configs/cod4_win.xml',
  319. 'modules/config_games/server_configs/cod5.xml',
  320. 'modules/config_games/server_configs/cod_world_at_war_win.xml',
  321. 'modules/config_games/server_configs/minecraft_tekkit.xml',
  322. 'modules/config_games/server_configs/minecraft_tekkit_win.xml',
  323. 'modules/config_games/server_configs/minecraft_bukkit.xml',
  324. 'modules/config_games/server_configs/minecraft_bukkit_win.xml',
  325. 'modules/config_games/server_configs/minecraft_server.xml',
  326. 'modules/config_games/server_configs/minecraft_server_win.xml',
  327. 'modules/config_games/server_configs/life_is_feudal_win32.xml',
  328. 'modules/config_games/server_configs/cs2d.xml',
  329. 'modules/config_games/server_configs/openttd.xml',
  330. 'modules/config_games/server_configs/ark_linux.xml',
  331. 'modules/config_games/server_configs/ark_win.xml',
  332. 'modules/config_games/server_configs/teamspeak3_32bit.xml',
  333. 'modules/config_games/server_configs/teamspeak3_64bit.xml',
  334. 'modules/config_games/server_configs/tekkit_linux32.xml',
  335. 'modules/config_games/server_configs/tekkit_linux64.xml',
  336. 'modules/config_games/server_configs/tekkit_win32.xml',
  337. 'modules/config_games/server_configs/tekkit_win64.xml',
  338. 'modules/config_games/server_configs/bukkit_linux32.xml',
  339. 'modules/config_games/server_configs/bukkit_linux64.xml',
  340. 'modules/config_games/server_configs/bukkit_win32.xml',
  341. 'modules/config_games/server_configs/bukkit_win64.xml',
  342. );
  343. foreach($oldConfigsToRemove as $config){
  344. recursiveDelete($config);
  345. }
  346. }
  347. function removeOldPanelFiles(){ // Should run post panel update to remove old files that are no longer users
  348. $oldFiles = array(
  349. 'includes/database_mysql.php',
  350. 'protocol/GameQ/gameq'
  351. );
  352. foreach($oldFiles as $file){
  353. recursiveDelete($file);
  354. }
  355. }
  356. function runPostUpdateOperations(){
  357. if(file_exists('modules/cron/shared_cron_functions.php')){
  358. // Update cronjobs to use the new token based API
  359. require_once('modules/cron/shared_cron_functions.php');
  360. if(function_exists("updateCronJobsToNewApi")){
  361. updateCronJobsToNewApi();
  362. }
  363. }
  364. if(function_exists("updateAllPanelModules")){
  365. updateAllPanelModules();
  366. }
  367. if(function_exists("removeOldPanelFiles")){
  368. removeOldPanelFiles();
  369. }
  370. if(!array_key_exists("users_api_key", $_SESSION)){
  371. $_SESSION['users_api_key'] = $db->getApiToken($_SESSION['user_id']);
  372. }
  373. }
  374. function getOGPGitHubURL($gitHubUsername, $repo, $branch = "master"){
  375. $OGPGitHub = OGP_GITHUB_MAIN_URL;
  376. $gitHubURL = $OGPGitHub;
  377. if(isset($gitHubUsername) && !empty($gitHubUsername)){
  378. $gitHubURL = "https://github.com/" . $gitHubUsername . "/";
  379. }
  380. $paths[] = $gitHubURL . $repo . "/commits/" . $branch . '.atom';
  381. $exists = get_first_existing_file($paths);
  382. if($exists !== false){
  383. return $gitHubURL;
  384. }
  385. return $OGPGitHub;
  386. }
  387. function getOGPGitHubURLUnstrict($gitHubUsername){
  388. $OGPGitHub = OGP_GITHUB_MAIN_URL;
  389. $gitHubURL = $OGPGitHub;
  390. if(isset($gitHubUsername) && !empty($gitHubUsername)){
  391. $gitHubURL = "https://github.com/" . $gitHubUsername . "/" . 'OGP-Website';
  392. }
  393. $paths[] = $gitHubURL;
  394. $exists = get_first_existing_file($paths);
  395. if($exists !== false){
  396. if(isset($gitHubUsername) && !empty($gitHubUsername)){
  397. return "https://github.com/" . $gitHubUsername . "/";
  398. }
  399. }
  400. return $OGPGitHub;
  401. }
  402. function getGitHubOrganization($gitHubURL){
  403. $gitHubOrg = "OpenGamePanel";
  404. $githubCom = "github.com";
  405. if(substr($gitHubURL, -1) == "/" && stripos($gitHubURL, $githubCom) !== false){
  406. // Get the immediate folder after github.com
  407. $gitHubOrg = substr($gitHubURL, stripos($gitHubURL, $githubCom) + strlen($githubCom) + 1);
  408. // Strip last forward slash
  409. $gitHubOrg = substr($gitHubOrg, 0, -1);
  410. }
  411. return $gitHubOrg;
  412. }
  413. function getOGPLangConstantsJSON(){
  414. global $OGPLangPre;
  415. $finalConsts = array();
  416. $consts = get_defined_constants(true);
  417. foreach($consts["user"] as $key => $value){
  418. if(startsWith($key, $OGPLangPre)){
  419. $finalConsts[$key] = $value;
  420. }
  421. }
  422. if(count($finalConsts) > 0){
  423. return json_encode(utf8ize($finalConsts));
  424. }
  425. return false;
  426. }
  427. /**
  428. * Validates a file path for security before passing to RPC/Shell.
  429. *
  430. * @param string $path The full path to validate.
  431. * @return bool True if safe, False if it contains dangerous characters or traversal.
  432. */
  433. function validate_path($path) {
  434. // 1. Block any instance of ".." (Parent Directory Traversal)
  435. if (strpos($path, '..') !== false) {
  436. return false;
  437. }
  438. // 2. Block "." if it is the entire filename or a standalone path segment
  439. // This prevents operations on the "current directory" itself.
  440. $parts = explode('/', $path);
  441. foreach ($parts as $part) {
  442. if ($part === '.') {
  443. return false;
  444. }
  445. }
  446. // 3. Strict Whitelist: Allow only alphanumeric, underscores, dots (within names), hyphens, and slashes.
  447. // This blocks ; | & ` $ \n and other shell/perl injection characters.
  448. if (preg_match('/[^a-zA-Z0-9._\-\/]/', $path)) {
  449. return false;
  450. }
  451. return true;
  452. }
  453. ?>