functions.core.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. /* $Id: functions.core.php 3157 2007-07-08 18:23:08Z danez $ */
  3. /*******************************************************************************
  4. LICENSE
  5. This program is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public License (GPL)
  7. as published by the Free Software Foundation; either version 2
  8. of the License, or (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. To read the license please visit http://www.gnu.org/copyleft/gpl.html
  14. *******************************************************************************/
  15. /*
  16. * auth
  17. */
  18. require_once("inc/functions/functions.core.auth.php");
  19. /*
  20. * db
  21. */
  22. require_once("inc/functions/functions.core.db.php");
  23. /*
  24. * netstat
  25. */
  26. require_once("inc/functions/functions.core.netstat.php");
  27. /**
  28. * POSIX-wrapper for PHPs lacking posix-support (--disable-posix)
  29. */
  30. if (!function_exists("posix_kill"))
  31. require_once("inc/functions/functions.core.posix.php");
  32. /*
  33. * tfb
  34. */
  35. require_once("inc/functions/functions.core.tfb.php");
  36. /*
  37. * theme
  38. */
  39. require_once("inc/functions/functions.core.theme.php");
  40. /*
  41. * tmpl
  42. */
  43. require_once("inc/functions/functions.core.tmpl.php");
  44. /*
  45. * transfer
  46. */
  47. require_once("inc/functions/functions.core.transfer.php");
  48. /*
  49. * user
  50. */
  51. require_once("inc/functions/functions.core.user.php");
  52. /**
  53. * Returns true if user has message from admin with force_read
  54. *
  55. * @return boolean
  56. */
  57. function IsForceReadMsg() {
  58. global $cfg, $db;
  59. return ($db->GetOne("SELECT count(*) FROM tf_messages WHERE to_user=".$db->qstr($cfg["user"])." AND force_read=1") >= 1);
  60. }
  61. /**
  62. * Get Links in an array
  63. *
  64. * @return array
  65. */
  66. function GetLinks() {
  67. global $db;
  68. $link_array = array();
  69. $link_array = $db->GetAssoc("SELECT lid, url, sitename, sort_order FROM tf_links ORDER BY sort_order");
  70. return $link_array;
  71. }
  72. /**
  73. * Returns sum of max numbers of connections of all running transfers.
  74. *
  75. * @return int with max cons
  76. */
  77. function getSumMaxCons() {
  78. global $db;
  79. return $db->GetOne("SELECT SUM(maxcons) AS maxcons FROM tf_transfers WHERE running = '1'");
  80. }
  81. /**
  82. * Returns sum of max upload-speed of all running transfers.
  83. *
  84. * @return int with max upload-speed
  85. */
  86. function getSumMaxUpRate() {
  87. global $db;
  88. return $db->GetOne("SELECT SUM(rate) AS rate FROM tf_transfers WHERE running = '1'");
  89. }
  90. /**
  91. * Returns sum of max download-speed of all running transfers.
  92. *
  93. * @return int with max download-speed
  94. */
  95. function getSumMaxDownRate() {
  96. global $db;
  97. return $db->GetOne("SELECT SUM(drate) AS drate FROM tf_transfers WHERE running = '1'");
  98. }
  99. /**
  100. * get server stats
  101. * note : this can only be used after a call to update transfer-values in cfg-
  102. * array (eg by getTransferListArray)
  103. *
  104. * @return array
  105. *
  106. * "speedDown" 0
  107. * "speedUp" 1
  108. * "speedTotal" 2
  109. * "cons" 3
  110. * "freeSpace" 4
  111. * "loadavg" 5
  112. * "running" 6
  113. * "queued" 7
  114. * "speedDownPercent" 8
  115. * "speedUpPercent" 9
  116. * "driveSpacePercent" 10
  117. *
  118. */
  119. function getServerStats() {
  120. global $cfg;
  121. $serverStats = array();
  122. // speedDown
  123. $speedDown = "n/a";
  124. $speedDown = @number_format($cfg["total_download"], 2);
  125. array_push($serverStats, $speedDown);
  126. // speedUp
  127. $speedUp = "n/a";
  128. $speedUp = @number_format($cfg["total_upload"], 2);
  129. array_push($serverStats, $speedUp);
  130. // speedTotal
  131. $speedTotal = "n/a";
  132. $speedTotal = @number_format($cfg["total_download"] + $cfg["total_upload"], 2);
  133. array_push($serverStats, $speedTotal);
  134. // cons
  135. $cons = "n/a";
  136. $cons = @netstatConnectionsSum();
  137. array_push($serverStats, $cons);
  138. // freeSpace
  139. $freeSpace = "n/a";
  140. $freeSpace = @formatFreeSpace($cfg["free_space"]);
  141. array_push($serverStats, $freeSpace);
  142. // loadavg
  143. $loadavg = "n/a";
  144. $loadavg = @getLoadAverageString();
  145. array_push($serverStats, $loadavg);
  146. // running
  147. $running = "n/a";
  148. $running = @getRunningTransferCount();
  149. array_push($serverStats, $running);
  150. // queued
  151. $queued = FluxdQmgr::countQueuedTransfers();
  152. array_push($serverStats, $queued);
  153. // speedDownPercent
  154. $percentDownload = 0;
  155. $maxDownload = $cfg["bandwidth_down"] / 8;
  156. $percentDownload = ($maxDownload > 0)
  157. ? @number_format(($cfg["total_download"] / $maxDownload) * 100, 0)
  158. : 0;
  159. array_push($serverStats, $percentDownload);
  160. // speedUpPercent
  161. $percentUpload = 0;
  162. $maxUpload = $cfg["bandwidth_up"] / 8;
  163. $percentUpload = ($maxUpload > 0)
  164. ? @number_format(($cfg["total_upload"] / $maxUpload) * 100, 0)
  165. : 0;
  166. array_push($serverStats, $percentUpload);
  167. // driveSpacePercent
  168. $driveSpacePercent = 0;
  169. $driveSpacePercent = @getDriveSpace($cfg["path"]);
  170. array_push($serverStats, $driveSpacePercent);
  171. // return
  172. return $serverStats;
  173. }
  174. /**
  175. * print message
  176. *
  177. * @param $msg
  178. */
  179. function printMessage($mod, $msg) {
  180. @fwrite(STDOUT, @date("[Y/m/d - H:i:s]")."[".$mod."] ".$msg);
  181. }
  182. /**
  183. * print error
  184. *
  185. * @param $msg
  186. */
  187. function printError($mod, $msg) {
  188. @fwrite(STDERR, @date("[Y/m/d - H:i:s]")."[".$mod."] ".$msg);
  189. }
  190. /**
  191. * Audit Action
  192. *
  193. * @param $action
  194. * @param $file
  195. */
  196. function AuditAction($action, $file = "") {
  197. global $cfg, $db;
  198. // add entry to the log
  199. $db->Execute("INSERT INTO tf_log (user_id,file,action,ip,ip_resolved,user_agent,time)"
  200. ." VALUES ("
  201. . $db->qstr($cfg["user"]).","
  202. . $db->qstr($file).","
  203. . $db->qstr(($action != "") ? $action : "unset").","
  204. . $db->qstr($cfg['ip']).","
  205. . $db->qstr($cfg['ip_resolved']).","
  206. . $db->qstr($cfg['user_agent']).","
  207. . $db->qstr(time())
  208. .")"
  209. );
  210. }
  211. /**
  212. * global error-function
  213. *
  214. * @param $msg
  215. * @param $link
  216. * @param $linklabel
  217. * @param $msgs
  218. */
  219. function error($msg, $link = "", $linklabel = "", $msgs = array()) {
  220. global $cfg, $argv;
  221. // web/cli/tfbf
  222. if ((empty($argv[0])) &&
  223. (!("tfbf" == @substr($cfg['user_agent'], 0, 4)))) { // web
  224. // theme
  225. $theme = CheckandSetUserTheme();
  226. // template
  227. require_once("themes/".$theme."/index.php");
  228. require_once("inc/lib/vlib/vlibTemplate.php");
  229. $_tmpl = tmplGetInstance($theme, "page.error.tmpl");
  230. // message
  231. $_tmpl->setvar('message', htmlentities($msg, ENT_QUOTES));
  232. // messages
  233. if (!empty($msgs)) {
  234. $msgAry = array_map("htmlentities", $msgs);
  235. $_tmpl->setvar('messages', implode("\n", $msgAry));
  236. }
  237. // link + linklabel
  238. if (!empty($link)) {
  239. $_tmpl->setvar('link', $link);
  240. $_tmpl->setvar('linklabel', (!empty($linklabel)) ? htmlentities($linklabel, ENT_QUOTES) : "Ok");
  241. }
  242. // parse template
  243. $_tmpl->pparse();
  244. // get out here
  245. exit();
  246. } else { // cli/tfbf
  247. // message
  248. $exitMsg = "Error: ".$msg."\n";
  249. // messages
  250. if (!empty($msgs))
  251. $exitMsg .= implode("\n", $msgs)."\n";
  252. // get out here
  253. exit($exitMsg);
  254. }
  255. }
  256. /**
  257. * checks if a path-string has a trailing slash. concat if it hasn't
  258. *
  259. * @param $dirPath
  260. * @return string with dirPath
  261. */
  262. function checkDirPathString($dirPath) {
  263. if (((strlen($dirPath) > 0)) && (substr($dirPath, -1 ) != "/"))
  264. $dirPath .= "/";
  265. return $dirPath;
  266. }
  267. /**
  268. * checks a dir. recursive process to emulate "mkdir -p" if dir not present
  269. *
  270. * @param $dir the name of the dir
  271. * @param $mode the mode of the dir if created. default is 0755
  272. * @return boolean if dir exists/could be created
  273. */
  274. function checkDirectory($dir, $mode = 0755, $depth = 0) {
  275. if ($depth > 32)
  276. return false;
  277. if ((@is_dir($dir) && @is_writable($dir)) || @mkdir($dir, $mode))
  278. return true;
  279. if ($dir == '/')
  280. return false;
  281. if (!@checkDirectory(dirname($dir), $mode, ++$depth))
  282. return false;
  283. return @mkdir($dir, $mode);
  284. }
  285. /**
  286. * isFile
  287. *
  288. * @param $file
  289. * @return boolean
  290. */
  291. function isFile($file) {
  292. $rtnValue = False;
  293. if (@is_file($file)) {
  294. $rtnValue = True;
  295. } else {
  296. if ($file == @trim(shell_exec("ls 2>/dev/null ".tfb_shellencode($file))))
  297. $rtnValue = True;
  298. }
  299. return $rtnValue;
  300. }
  301. /**
  302. * Returns file size... overcomes PHP limit of 2.0GB
  303. *
  304. * @param $file
  305. * @return int
  306. */
  307. function file_size($file) {
  308. $size = @filesize($file);
  309. if ($size == 0)
  310. return exec("ls -l ".tfb_shellencode($file)." 2>/dev/null | awk '{print $5}'");
  311. return $size;
  312. }
  313. /**
  314. * avddelete
  315. *
  316. * @param $file
  317. */
  318. function avddelete($file) {
  319. @chmod($file,0777);
  320. if (@is_dir($file)) {
  321. $handle = @opendir($file);
  322. while($filename = readdir($handle)) {
  323. if ($filename != "." && $filename != "..")
  324. avddelete($file."/".$filename);
  325. }
  326. closedir($handle);
  327. @rmdir($file);
  328. } else {
  329. @unlink($file);
  330. }
  331. }
  332. /**
  333. * getLoadAverageString
  334. *
  335. * @return string with load-average
  336. */
  337. function getLoadAverageString() {
  338. global $cfg;
  339. switch ($cfg["_OS"]) {
  340. case 1: // linux
  341. $loadavg = @explode(" ", @file_get_contents($cfg["loadavg_path"]));
  342. return ((is_array($loadavg)) && (count($loadavg) > 2))
  343. ? $loadavg[2]
  344. : 'n/a';
  345. case 2: // bsd
  346. return preg_replace("/.*load averages:(.*)/", "$1", exec("uptime"));
  347. default:
  348. return 'n/a';
  349. }
  350. }
  351. /**
  352. * Returns the drive space used as a percentage i.e 85 or 95
  353. *
  354. * @param $drive
  355. * @return int
  356. */
  357. function getDriveSpace($drive) {
  358. if (@is_dir($drive)) {
  359. $dt = disk_total_space($drive);
  360. $df = disk_free_space($drive);
  361. return round((($dt - $df) / $dt) * 100);
  362. }
  363. return 0;
  364. }
  365. /**
  366. * Function to convert bit-array to (unsigned) byte
  367. *
  368. * @param $dataArray
  369. * @return byte
  370. */
  371. function convertArrayToByte($dataArray) {
  372. if (count($dataArray) > 8) return false;
  373. foreach ($dataArray as $key => $value)
  374. $dataArray[$key] = ($value) ? 1 : 0;
  375. $binString = strrev(implode('', $dataArray));
  376. $bitByte = bindec($binString);
  377. return $bitByte;
  378. }
  379. /**
  380. * Function to convert (unsigned) byte to bit-array
  381. *
  382. * @param $dataByte
  383. * @return array
  384. */
  385. function convertByteToArray($dataByte) {
  386. if (($dataByte > 255) || ($dataByte < 0)) return false;
  387. $binString = strrev(str_pad(decbin($dataByte), 8, "0", STR_PAD_LEFT));
  388. $bitArray = explode(":", chunk_split($binString, 1, ":"));
  389. return $bitArray;
  390. }
  391. /**
  392. * Function to convert bit-array to (unsigned) integer
  393. *
  394. * @param $dataArray
  395. * @return int
  396. */
  397. function convertArrayToInteger($dataArray) {
  398. if (count($dataArray) > 31) return false;
  399. foreach ($dataArray as $key => $value)
  400. $dataArray[$key] = ($value) ? 1 : 0;
  401. $binString = strrev(implode('', $dataArray));
  402. $bitInteger = bindec($binString);
  403. return $bitInteger;
  404. }
  405. /**
  406. * Function to convert (unsigned) integer to bit-array
  407. *
  408. * @param $dataInt
  409. * @return array
  410. */
  411. function convertIntegerToArray($dataInt) {
  412. if (($dataInt > 2147483647) || ($dataInt < 0)) return false;
  413. $binString = strrev(str_pad(decbin($dataInt), 31, "0", STR_PAD_LEFT));
  414. $bitArray = explode(":", chunk_split($binString, 1, ":"));
  415. return $bitArray;
  416. }
  417. /**
  418. * convertTime
  419. *
  420. * @param $seconds
  421. * @return common time-delta-string
  422. */
  423. function convertTime($seconds) {
  424. // sanity-check
  425. if ($seconds < 0) return '?';
  426. // one week is enough
  427. if ($seconds >= 604800) return '-';
  428. // format time-delta
  429. $periods = array (/* 31556926, 2629743, 604800,*/ 86400, 3600, 60, 1);
  430. $seconds = floatval($seconds);
  431. $values = array();
  432. $leading = true;
  433. foreach ($periods as $period) {
  434. $count = floor($seconds / $period);
  435. if ($leading) {
  436. if ($count == 0)
  437. continue;
  438. $leading = false;
  439. }
  440. array_push($values, ($count < 10) ? "0".$count : $count);
  441. $seconds = $seconds % $period;
  442. }
  443. return (empty($values)) ? "?" : implode(':', $values);
  444. }
  445. /**
  446. * Returns a string in format of TB, GB, MB, or kB depending on the size
  447. *
  448. * @param $inBytes
  449. * @return string
  450. */
  451. function formatBytesTokBMBGBTB($inBytes) {
  452. if(!is_numeric($inBytes)) return "";
  453. if ($inBytes > 1099511627776)
  454. return round($inBytes / 1099511627776, 2) . " TB";
  455. elseif ($inBytes > 1073741824)
  456. return round($inBytes / 1073741824, 2) . " GB";
  457. elseif ($inBytes > 1048576)
  458. return round($inBytes / 1048576, 1) . " MB";
  459. elseif ($inBytes > 1024)
  460. return round($inBytes / 1024, 1) . " kB";
  461. else
  462. return $inBytes . " B";
  463. }
  464. /**
  465. * Convert free space to TB, GB or MB depending on size
  466. *
  467. * @param $freeSpace
  468. * @return string
  469. */
  470. function formatFreeSpace($freeSpace) {
  471. if ($freeSpace > 1048576)
  472. return number_format($freeSpace / 1048576, 2)." TB";
  473. elseif ($freeSpace > 1024)
  474. return number_format($freeSpace / 1024, 2)." GB";
  475. else
  476. return number_format($freeSpace, 2)." MB";
  477. }
  478. /**
  479. * GetSpeedValue
  480. *
  481. * @param $inValue
  482. * @return number
  483. */
  484. function GetSpeedValue($inValue) {
  485. $arTemp = explode(" ", trim($inValue));
  486. return (is_numeric($arTemp[0])) ? $arTemp[0] : 0;
  487. }
  488. /**
  489. * Estimated time left to seed
  490. *
  491. * @param $inValue
  492. * @return string
  493. */
  494. function GetSpeedInBytes($inValue) {
  495. $arTemp = explode(" ", trim($inValue));
  496. return ($arTemp[1] == "kB/s") ? $arTemp[0] * 1024 : $arTemp[0];
  497. }
  498. ?>