PageRenderTime 75ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/functions.php

https://github.com/alx/torrentflux
PHP | 2665 lines | 2410 code | 142 blank | 113 comment | 107 complexity | 1e92daaaa2488bda38df4a0cc403412c MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /*************************************************************
  3. * TorrentFlux - PHP Torrent Manager
  4. * www.torrentflux.com
  5. **************************************************************/
  6. /*
  7. This file is part of TorrentFlux.
  8. TorrentFlux is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 2 of the License, or
  11. (at your option) any later version.
  12. TorrentFlux is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU General Public License
  17. along with TorrentFlux; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. // Start Session and grab user
  21. session_name("TorrentFlux");
  22. session_start();
  23. if(isset($_SESSION['user']))
  24. {
  25. $cfg["user"] = strtolower($_SESSION['user']);
  26. }else{
  27. $cfg["user"] = "root";
  28. }
  29. include_once('db.php');
  30. include_once("settingsfunctions.php");
  31. // Create Connection.
  32. $db = getdb();
  33. loadSettings();
  34. // Free space in MB
  35. $cfg["free_space"] = @disk_free_space($cfg["path"])/(1024*1024);
  36. // Path to where the torrent meta files will be stored... usually a sub of $cfg["path"]
  37. // also, not the '.' to make this a hidden directory
  38. $cfg["torrent_file_path"] = $cfg["path"].".torrents/";
  39. Authenticate();
  40. include_once("language/".$cfg["language_file"]);
  41. include_once("themes/".$cfg["theme"]."/index.php");
  42. AuditAction($cfg["constants"]["hit"], $_SERVER['PHP_SELF']);
  43. PruneDB();
  44. // is there a stat and torrent dir? If not then it will create it.
  45. checkTorrentPath();
  46. //**********************************************************************************
  47. // START FUNCTIONS HERE
  48. //**********************************************************************************
  49. //*********************************************************
  50. function getLinkSortOrder($lid)
  51. {
  52. global $db;
  53. // Get Current sort order index of link with this link id:
  54. $sql="SELECT sort_order FROM tf_links WHERE lid=$lid";
  55. $rtnValue=$db->GetOne($sql);
  56. showError($db,$sql);
  57. return $rtnValue;
  58. }
  59. //*********************************************************
  60. // avddelete()
  61. function avddelete($file)
  62. {
  63. $file = html_entity_decode($file, ENT_QUOTES);
  64. chmod($file,0777);
  65. if (@is_dir($file))
  66. {
  67. $handle = @opendir($file);
  68. while($filename = readdir($handle))
  69. {
  70. if ($filename != "." && $filename != "..")
  71. {
  72. avddelete($file."/".$filename);
  73. }
  74. }
  75. closedir($handle);
  76. @rmdir($file);
  77. }
  78. else
  79. {
  80. @unlink($file);
  81. }
  82. }
  83. //*********************************************************
  84. // Authenticate()
  85. function Authenticate()
  86. {
  87. global $cfg, $db;
  88. $create_time = time();
  89. if(!isset($_SESSION['user']))
  90. {
  91. //header('location: login.php');
  92. //exit();
  93. }
  94. if ($_SESSION['user'] == md5($cfg["pagetitle"]))
  95. {
  96. // user changed password and needs to login again
  97. header('location: logout.php');
  98. exit();
  99. }
  100. $sql = "SELECT uid, hits, hide_offline, theme, language_file FROM tf_users WHERE user_id=".$db->qstr($cfg['user']);
  101. $recordset = $db->Execute($sql);
  102. showError($db, $sql);
  103. if($recordset->RecordCount() != 1)
  104. {
  105. AuditAction($cfg["constants"]["error"], "FAILED AUTH: ".$cfg['user']);
  106. session_destroy();
  107. header('location: login.php');
  108. exit();
  109. }
  110. list($uid, $hits, $cfg["hide_offline"], $cfg["theme"], $cfg["language_file"]) = $recordset->FetchRow();
  111. // Check for valid theme
  112. if (!ereg('^[^./][^/]*$', $cfg["theme"]))
  113. {
  114. AuditAction($cfg["constants"]["error"], "THEME VARIABLE CHANGE ATTEMPT: ".$cfg["theme"]." from ".$cfg['user']);
  115. $cfg["theme"] = $cfg["default_theme"];
  116. }
  117. // Check for valid language file
  118. if(!ereg('^[^./][^/]*$', $cfg["language_file"]))
  119. {
  120. AuditAction($cfg["constants"]["error"], "LANGUAGE VARIABLE CHANGE ATTEMPT: ".$cfg["language_file"]." from ".$cfg['user']);
  121. $cfg["language_file"] = $cfg["default_language"];
  122. }
  123. if (!is_dir("themes/".$cfg["theme"]))
  124. {
  125. $cfg["theme"] = $cfg["default_theme"];
  126. }
  127. // Check for valid language file
  128. if (!is_file("language/".$cfg["language_file"]))
  129. {
  130. $cfg["language_file"] = $cfg["default_language"];
  131. }
  132. $hits++;
  133. $sql = 'select * from tf_users where uid = '.$uid;
  134. $rs = $db->Execute($sql);
  135. showError($db, $sql);
  136. $rec = array(
  137. 'hits' => $hits,
  138. 'last_visit' => $create_time,
  139. 'theme' => $cfg['theme'],
  140. 'language_file' => $cfg['language_file']
  141. );
  142. $sql = $db->GetUpdateSQL($rs, $rec);
  143. $result = $db->Execute($sql);
  144. showError($db,$sql);
  145. }
  146. //*********************************************************
  147. // SaveMessage
  148. function SaveMessage($to_user, $from_user, $message, $to_all=0, $force_read=0)
  149. {
  150. global $_SERVER, $cfg, $db;
  151. $message = str_replace(array("'"), "", $message);
  152. $create_time = time();
  153. $sTable = 'tf_messages';
  154. if($to_all == 1)
  155. {
  156. $message .= "\n\n__________________________________\n*** "._MESSAGETOALL." ***";
  157. $sql = 'select user_id from tf_users';
  158. $result = $db->Execute($sql);
  159. showError($db,$sql);
  160. while($row = $result->FetchRow())
  161. {
  162. $rec = array(
  163. 'to_user' => $row['user_id'],
  164. 'from_user' => $from_user,
  165. 'message' => $message,
  166. 'IsNew' => 1,
  167. 'ip' => $cfg['ip'],
  168. 'time' => $create_time,
  169. 'force_read' => $force_read
  170. );
  171. $sql = $db->GetInsertSql($sTable, $rec);
  172. $result2 = $db->Execute($sql);
  173. showError($db,$sql);
  174. }
  175. }
  176. else
  177. {
  178. // Only Send to one Person
  179. $rec = array(
  180. 'to_user' => $to_user,
  181. 'from_user' => $from_user,
  182. 'message' => $message,
  183. 'IsNew' => 1,
  184. 'ip' => $cfg['ip'],
  185. 'time' => $create_time,
  186. 'force_read' => $force_read
  187. );
  188. $sql = $db->GetInsertSql($sTable, $rec);
  189. $result = $db->Execute($sql);
  190. showError($db,$sql);
  191. }
  192. }
  193. //*********************************************************
  194. function addNewUser($newUser, $pass1, $userType)
  195. {
  196. global $cfg, $db;
  197. $create_time = time();
  198. $record = array(
  199. 'user_id'=>strtolower($newUser),
  200. 'password'=>md5($pass1),
  201. 'hits'=>0,
  202. 'last_visit'=>$create_time,
  203. 'time_created'=>$create_time,
  204. 'user_level'=>$userType,
  205. 'hide_offline'=>"0",
  206. 'theme'=>$cfg["default_theme"],
  207. 'language_file'=>$cfg["default_language"]
  208. );
  209. $sTable = 'tf_users';
  210. $sql = $db->GetInsertSql($sTable, $record);
  211. $result = $db->Execute($sql);
  212. showError($db,$sql);
  213. }
  214. //*********************************************************
  215. function PruneDB()
  216. {
  217. global $cfg, $db;
  218. // Prune LOG
  219. $testTime = time()-($cfg['days_to_keep'] * 86400); // 86400 is one day in seconds
  220. $sql = "delete from tf_log where time < " . $db->qstr($testTime);
  221. $result = $db->Execute($sql);
  222. showError($db,$sql);
  223. unset($result);
  224. $testTime = time()-($cfg['minutes_to_keep'] * 60);
  225. $sql = "delete from tf_log where time < " . $db->qstr($testTime). " and action=".$db->qstr($cfg["constants"]["hit"]);
  226. $result = $db->Execute($sql);
  227. showError($db,$sql);
  228. unset($result);
  229. }
  230. //*********************************************************
  231. function IsOnline($user)
  232. {
  233. global $cfg, $db;
  234. $online = false;
  235. $sql = "SELECT count(*) FROM tf_log WHERE user_id=" . $db->qstr($user)." AND action=".$db->qstr($cfg["constants"]["hit"]);
  236. $number_hits = $db->GetOne($sql);
  237. showError($db,$sql);
  238. if ($number_hits > 0)
  239. {
  240. $online = true;
  241. }
  242. return $online;
  243. }
  244. //*********************************************************
  245. function IsUser($user)
  246. {
  247. global $cfg, $db;
  248. $isUser = false;
  249. $sql = "SELECT count(*) FROM tf_users WHERE user_id=".$db->qstr($user);
  250. $number_users = $db->GetOne($sql);
  251. if ($number_users > 0)
  252. {
  253. $isUser = true;
  254. }
  255. return $isUser;
  256. }
  257. //*********************************************************
  258. function getOwner($file)
  259. {
  260. global $cfg, $db;
  261. $rtnValue = "n/a";
  262. // Check log to see what user has a history with this file
  263. $sql = "SELECT user_id FROM tf_log WHERE file=".$db->qstr($file)." AND (action=".$db->qstr($cfg["constants"]["file_upload"])." OR action=".$db->qstr($cfg["constants"]["url_upload"])." OR action=".$db->qstr($cfg["constants"]["reset_owner"]).") ORDER BY time DESC";
  264. $user_id = $db->GetOne($sql);
  265. if($user_id != "")
  266. {
  267. $rtnValue = $user_id;
  268. }
  269. else
  270. {
  271. // try and get the owner from the stat file
  272. $rtnValue = resetOwner($file);
  273. }
  274. return $rtnValue;
  275. }
  276. //*********************************************************
  277. function resetOwner($file)
  278. {
  279. global $cfg, $db;
  280. include_once("AliasFile.php");
  281. // log entry has expired so we must renew it
  282. $rtnValue = "";
  283. $alias = getAliasName($file).".stat";
  284. if(file_exists($cfg["torrent_file_path"].$alias))
  285. {
  286. $af = new AliasFile($cfg["torrent_file_path"].$alias);
  287. if (IsUser($af->torrentowner))
  288. {
  289. // We have an owner!
  290. $rtnValue = $af->torrentowner;
  291. }
  292. else
  293. {
  294. // no owner found, so the super admin will now own it
  295. $rtnValue = GetSuperAdmin();
  296. }
  297. $host_resolved = $cfg['ip'];
  298. $create_time = time();
  299. $rec = array(
  300. 'user_id' => $rtnValue,
  301. 'file' => $file,
  302. 'action' => $cfg["constants"]["reset_owner"],
  303. 'ip' => $cfg['ip'],
  304. 'ip_resolved' => $host_resolved,
  305. 'user_agent' => $_SERVER['HTTP_USER_AGENT'],
  306. 'time' => $create_time
  307. );
  308. $sTable = 'tf_log';
  309. $sql = $db->GetInsertSql($sTable, $rec);
  310. // add record to the log
  311. $result = $db->Execute($sql);
  312. showError($db,$sql);
  313. }
  314. return $rtnValue;
  315. }
  316. //*********************************************************
  317. function getCookie($cid)
  318. {
  319. global $cfg, $db;
  320. $rtnValue = "";
  321. $sql = "SELECT host, data FROM tf_cookies WHERE cid=".$cid;
  322. $rtnValue = $db->GetAll($sql);
  323. return $rtnValue[0];
  324. }
  325. //*********************************************************
  326. function getAllCookies($uid)
  327. {
  328. global $cfg, $db;
  329. $rtnValue = "";
  330. $sql = "SELECT c.cid, c.host, c.data FROM tf_cookies AS c, tf_users AS u WHERE u.uid=c.uid AND u.user_id='" . $uid . "' order by host";
  331. $rtnValue = $db->GetAll($sql);
  332. return $rtnValue;
  333. }
  334. // ***************************************************************************
  335. // Delete Cookie Host Information
  336. function deleteCookieInfo($cid)
  337. {
  338. global $db;
  339. $sql = "delete from tf_cookies where cid=".$cid;
  340. $result = $db->Execute($sql);
  341. showError($db,$sql);
  342. }
  343. // ***************************************************************************
  344. // addCookieInfo - Add New Cookie Host Information
  345. function addCookieInfo( $newCookie )
  346. {
  347. global $db, $cfg;
  348. // Get uid of user
  349. $sql = "SELECT uid FROM tf_users WHERE user_id = '" . $cfg["user"] . "'";
  350. $uid = $db->GetOne( $sql );
  351. $sql = "INSERT INTO tf_cookies ( uid, host, data ) VALUES ( " . $uid . ", " . $db->qstr($newCookie["host"]) . ", " . $db->qstr($newCookie["data"]) . " )";
  352. $db->Execute( $sql );
  353. showError( $db, $sql );
  354. }
  355. // ***************************************************************************
  356. // modCookieInfo - Modify Cookie Host Information
  357. function modCookieInfo($cid, $newCookie)
  358. {
  359. global $db;
  360. $sql = "UPDATE tf_cookies SET host='" . $newCookie["host"] . "', data='" . $newCookie["data"] . "' WHERE cid=" . $cid;
  361. $db->Execute($sql);
  362. showError($db,$sql);
  363. }
  364. //*********************************************************
  365. function getSite($lid)
  366. {
  367. global $cfg, $db;
  368. $rtnValue = "";
  369. $sql = "SELECT sitename FROM tf_links WHERE lid=".$lid;
  370. $rtnValue = $db->GetOne($sql);
  371. return $rtnValue;
  372. }
  373. //*********************************************************
  374. function getLink($lid)
  375. {
  376. global $cfg, $db;
  377. $rtnValue = "";
  378. $sql = "SELECT url FROM tf_links WHERE lid=".$lid;
  379. $rtnValue = $db->GetOne($sql);
  380. return $rtnValue;
  381. }
  382. //*********************************************************
  383. function getRSS($rid)
  384. {
  385. global $cfg, $db;
  386. $rtnValue = "";
  387. $sql = "SELECT url FROM tf_rss WHERE rid=".$rid;
  388. $rtnValue = $db->GetOne($sql);
  389. return $rtnValue;
  390. }
  391. //*********************************************************
  392. function IsOwner($user, $owner)
  393. {
  394. $rtnValue = false;
  395. if (strtolower($user) == strtolower($owner))
  396. {
  397. $rtnValue = true;
  398. }
  399. return $rtnValue;
  400. }
  401. //*********************************************************
  402. function GetActivityCount($user="")
  403. {
  404. global $cfg, $db;
  405. $count = 0;
  406. $for_user = "";
  407. if ($user != "")
  408. {
  409. $for_user = "user_id=".$db->qstr($user)." AND ";
  410. }
  411. $sql = "SELECT count(*) FROM tf_log WHERE ".$for_user."(action=".$db->qstr($cfg["constants"]["file_upload"])." OR action=".$db->qstr($cfg["constants"]["url_upload"]).")";
  412. $count = $db->GetOne($sql);
  413. return $count;
  414. }
  415. //*********************************************************
  416. function GetSpeedValue($inValue)
  417. {
  418. $rtnValue = 0;
  419. $arTemp = split(" ", trim($inValue));
  420. if (is_numeric($arTemp[0]))
  421. {
  422. $rtnValue = $arTemp[0];
  423. }
  424. return $rtnValue;
  425. }
  426. // ***************************************************************************
  427. // Is User Admin
  428. // user is Admin if level is 1 or higher
  429. function IsAdmin($user="")
  430. {
  431. global $cfg, $db;
  432. $isAdmin = false;
  433. if($user == "")
  434. {
  435. $user = $cfg["user"];
  436. }
  437. $sql = "SELECT user_level FROM tf_users WHERE user_id=".$db->qstr($user);
  438. $user_level = $db->GetOne($sql);
  439. if ($user_level >= 1)
  440. {
  441. $isAdmin = true;
  442. }
  443. return $isAdmin;
  444. }
  445. // ***************************************************************************
  446. // Is User SUPER Admin
  447. // user is Super Admin if level is higher than 1
  448. function IsSuperAdmin($user="")
  449. {
  450. global $cfg, $db;
  451. $isAdmin = false;
  452. if($user == "")
  453. {
  454. $user = $cfg["user"];
  455. }
  456. $sql = "SELECT user_level FROM tf_users WHERE user_id=".$db->qstr($user);
  457. $user_level = $db->GetOne($sql);
  458. if ($user_level > 1)
  459. {
  460. $isAdmin = true;
  461. }
  462. return $isAdmin;
  463. }
  464. // ***************************************************************************
  465. // Returns true if user has message from admin with force_read
  466. function IsForceReadMsg()
  467. {
  468. global $cfg, $db;
  469. $rtnValue = false;
  470. $sql = "SELECT count(*) FROM tf_messages WHERE to_user=".$db->qstr($cfg["user"])." AND force_read=1";
  471. $count = $db->GetOne($sql);
  472. showError($db,$sql);
  473. if ($count >= 1)
  474. {
  475. $rtnValue = true;
  476. }
  477. return $rtnValue;
  478. }
  479. // ***************************************************************************
  480. // Get Message data in an array
  481. function GetMessage($mid)
  482. {
  483. global $cfg, $db;
  484. $rtnValue = array();
  485. if (is_numeric($mid))
  486. {
  487. $sql = "select from_user, message, ip, time, isnew, force_read from tf_messages where mid=".$mid." and to_user=".$db->qstr($cfg['user']);
  488. $rtnValue = $db->GetRow($sql);
  489. showError($db,$sql);
  490. }
  491. return $rtnValue;
  492. }
  493. // ***************************************************************************
  494. // Get Themes data in an array
  495. function GetThemes()
  496. {
  497. $arThemes = array();
  498. $dir = "themes/";
  499. $handle = opendir($dir);
  500. while($entry = readdir($handle))
  501. {
  502. if (is_dir($dir.$entry) && ($entry != "." && $entry != ".."))
  503. {
  504. array_push($arThemes, $entry);
  505. }
  506. }
  507. closedir($handle);
  508. sort($arThemes);
  509. return $arThemes;
  510. }
  511. // ***************************************************************************
  512. // Get Languages in an array
  513. function GetLanguages()
  514. {
  515. $arLanguages = array();
  516. $dir = "language/";
  517. $handle = opendir($dir);
  518. while($entry = readdir($handle))
  519. {
  520. if (is_file($dir.$entry) && (strcmp(strtolower(substr($entry, strlen($entry)-4, 4)), ".php") == 0))
  521. {
  522. array_push($arLanguages, $entry);
  523. }
  524. }
  525. closedir($handle);
  526. sort($arLanguages);
  527. return $arLanguages;
  528. }
  529. // ***************************************************************************
  530. // Get Language name from file name
  531. function GetLanguageFromFile($inFile)
  532. {
  533. $rtnValue = "";
  534. $rtnValue = str_replace("lang-", "", $inFile);
  535. $rtnValue = str_replace(".php", "", $rtnValue);
  536. return $rtnValue;
  537. }
  538. // ***************************************************************************
  539. // Delete Message
  540. function DeleteMessage($mid)
  541. {
  542. global $cfg, $db;
  543. $sql = "delete from tf_messages where mid=".$mid." and to_user=".$db->qstr($cfg['user']);
  544. $result = $db->Execute($sql);
  545. showError($db,$sql);
  546. }
  547. // ***************************************************************************
  548. // Delete Link
  549. function deleteOldLink($lid)
  550. {
  551. global $db;
  552. // Get Current sort order index of link with this link id:
  553. $idx = getLinkSortOrder($lid);
  554. // Fetch all link ids and their sort orders where the sort order is greater
  555. // than the one we're removing - we need to shuffle each sort order down
  556. // one:
  557. $sql = "SELECT sort_order, lid FROM tf_links ";
  558. $sql .= "WHERE sort_order > ".$idx." ORDER BY sort_order ASC";
  559. $result = $db->Execute($sql);
  560. showError($db,$sql);
  561. $arLinks = $result->GetAssoc();
  562. // Decrement the sort order of each link:
  563. foreach($arLinks as $sid => $this_lid)
  564. {
  565. $sql="UPDATE tf_links SET sort_order=sort_order-1 WHERE lid=".$this_lid;
  566. $db->Execute($sql);
  567. showError($db,$sql);
  568. }
  569. // Finally delete the link:
  570. $sql = "DELETE FROM tf_links WHERE lid=".$lid;
  571. $result = $db->Execute($sql);
  572. showError($db,$sql);
  573. }
  574. // ***************************************************************************
  575. // Delete RSS
  576. function deleteOldRSS($rid)
  577. {
  578. global $db;
  579. $sql = "delete from tf_rss where rid=".$rid;
  580. $result = $db->Execute($sql);
  581. showError($db,$sql);
  582. }
  583. // ***************************************************************************
  584. // Delete User
  585. function DeleteThisUser($user_id)
  586. {
  587. global $db;
  588. $sql = "SELECT uid FROM tf_users WHERE user_id = ".$db->qstr($user_id);
  589. $uid = $db->GetOne( $sql );
  590. showError($db,$sql);
  591. // delete any cookies this user may have had
  592. //$sql = "DELETE tf_cookies FROM tf_cookies, tf_users WHERE (tf_users.uid = tf_cookies.uid) AND tf_users.user_id=".$db->qstr($user_id);
  593. $sql = "DELETE FROM tf_cookies WHERE uid=".$uid;
  594. $result = $db->Execute($sql);
  595. showError($db,$sql);
  596. // Now cleanup any message this person may have had
  597. $sql = "DELETE FROM tf_messages WHERE to_user=".$db->qstr($user_id);
  598. $result = $db->Execute($sql);
  599. showError($db,$sql);
  600. // now delete the user from the table
  601. $sql = "DELETE FROM tf_users WHERE user_id=".$db->qstr($user_id);
  602. $result = $db->Execute($sql);
  603. showError($db,$sql);
  604. }
  605. // ***************************************************************************
  606. // Update User -- used by admin
  607. function updateThisUser($user_id, $org_user_id, $pass1, $userType, $hideOffline)
  608. {
  609. global $db;
  610. if ($hideOffline == "")
  611. {
  612. $hideOffline = 0;
  613. }
  614. $sql = 'select * from tf_users where user_id = '.$db->qstr($org_user_id);
  615. $rs = $db->Execute($sql);
  616. showError($db,$sql);
  617. $rec = array();
  618. $rec['user_id'] = $user_id;
  619. $rec['user_level'] = $userType;
  620. $rec['hide_offline'] = $hideOffline;
  621. if ($pass1 != "")
  622. {
  623. $rec['password'] = md5($pass1);
  624. }
  625. $sql = $db->GetUpdateSQL($rs, $rec);
  626. if ($sql != "")
  627. {
  628. $result = $db->Execute($sql);
  629. showError($db,$sql);
  630. }
  631. // if the original user id and the new id do not match, we need to update messages and log
  632. if ($user_id != $org_user_id)
  633. {
  634. $sql = "UPDATE tf_messages SET to_user=".$db->qstr($user_id)." WHERE to_user=".$db->qstr($org_user_id);
  635. $result = $db->Execute($sql);
  636. showError($db,$sql);
  637. $sql = "UPDATE tf_messages SET from_user=".$db->qstr($user_id)." WHERE from_user=".$db->qstr($org_user_id);
  638. $result = $db->Execute($sql);
  639. showError($db,$sql);
  640. $sql = "UPDATE tf_log SET user_id=".$db->qstr($user_id)." WHERE user_id=".$db->qstr($org_user_id);
  641. $result = $db->Execute($sql);
  642. showError($db,$sql);
  643. }
  644. }
  645. // ***************************************************************************
  646. // changeUserLevel Changes the Users Level
  647. function changeUserLevel($user_id, $level)
  648. {
  649. global $db;
  650. $sql='select * from tf_users where user_id = '.$db->qstr($user_id);
  651. $rs = $db->Execute($sql);
  652. showError($db,$sql);
  653. $rec = array('user_level'=>$level);
  654. $sql = $db->GetUpdateSQL($rs, $rec);
  655. $result = $db->Execute($sql);
  656. showError($db,$sql);
  657. }
  658. // ***************************************************************************
  659. // Mark Message as Read
  660. function MarkMessageRead($mid)
  661. {
  662. global $cfg, $db;
  663. $sql = 'select * from tf_messages where mid = '.$mid;
  664. $rs = $db->Execute($sql);
  665. showError($db,$sql);
  666. $rec = array('IsNew'=>0,
  667. 'force_read'=>0);
  668. $sql = $db->GetUpdateSQL($rs, $rec);
  669. $db->Execute($sql);
  670. showError($db,$sql);
  671. }
  672. //**************************************************************************
  673. // alterLink()
  674. // This function updates the database and alters the selected links values
  675. function alterLink($lid,$newLink,$newSite)
  676. {
  677. global $cfg, $db;
  678. $sql = "UPDATE tf_links SET url='".$newLink."',`sitename`='".$newSite."' WHERE `lid`=".$lid;
  679. $db->Execute($sql);
  680. showError($db,$sql);
  681. }
  682. // ***************************************************************************
  683. // addNewLink - Add New Link
  684. function addNewLink($newLink,$newSite)
  685. {
  686. global $db;
  687. // Link sort order index:
  688. $idx = -1;
  689. // Get current highest link index:
  690. $sql = "SELECT sort_order FROM tf_links ORDER BY sort_order DESC";
  691. $result = $db->SelectLimit($sql, 1);
  692. showError($db, $sql);
  693. if($result->fields === false)
  694. {
  695. // No links currently in db:
  696. $idx = 0;
  697. }
  698. else
  699. {
  700. $idx = $result->fields["sort_order"]+1;
  701. }
  702. $rec = array
  703. (
  704. 'url'=>$newLink,
  705. 'sitename'=>$newSite,
  706. 'sort_order'=>$idx
  707. );
  708. $sTable = 'tf_links';
  709. $sql = $db->GetInsertSql($sTable, $rec);
  710. $db->Execute($sql);
  711. showError($db,$sql);
  712. }
  713. // ***************************************************************************
  714. // addNewRSS - Add New RSS Link
  715. function addNewRSS($newRSS)
  716. {
  717. global $db;
  718. $rec = array('url'=>$newRSS);
  719. $sTable = 'tf_rss';
  720. $sql = $db->GetInsertSql($sTable, $rec);
  721. $db->Execute($sql);
  722. showError($db,$sql);
  723. }
  724. // ***************************************************************************
  725. // UpdateUserProfile
  726. function UpdateUserProfile($user_id, $pass1, $hideOffline, $theme, $language)
  727. {
  728. global $cfg, $db;
  729. if (empty($hideOffline) || $hideOffline == "" || !isset($hideOffline))
  730. {
  731. $hideOffline = "0";
  732. }
  733. // update values
  734. $rec = array();
  735. if ($pass1 != "")
  736. {
  737. $rec['password'] = md5($pass1);
  738. AuditAction($cfg["constants"]["update"], _PASSWORD);
  739. }
  740. $sql = 'select * from tf_users where user_id = '.$db->qstr($user_id);
  741. $rs = $db->Execute($sql);
  742. showError($db,$sql);
  743. $rec['hide_offline'] = $hideOffline;
  744. $rec['theme'] = $theme;
  745. $rec['language_file'] = $language;
  746. $sql = $db->GetUpdateSQL($rs, $rec);
  747. $result = $db->Execute($sql);
  748. showError($db,$sql);
  749. }
  750. // ***************************************************************************
  751. // Get Users in an array
  752. function GetUsers()
  753. {
  754. global $cfg, $db;
  755. $user_array = array();
  756. $sql = "select user_id from tf_users order by user_id";
  757. $user_array = $db->GetCol($sql);
  758. showError($db,$sql);
  759. return $user_array;
  760. }
  761. // ***************************************************************************
  762. // Get Super Admin User ID as a String
  763. function GetSuperAdmin()
  764. {
  765. global $cfg, $db;
  766. $rtnValue = "";
  767. $sql = "select user_id from tf_users WHERE user_level=2";
  768. $rtnValue = $db->GetOne($sql);
  769. showError($db,$sql);
  770. return $rtnValue;
  771. }
  772. // ***************************************************************************
  773. // Get Links in an array
  774. function GetLinks()
  775. {
  776. global $cfg, $db;
  777. $link_array = array();
  778. $link_array = $db->GetAssoc("SELECT lid, url, sitename, sort_order FROM tf_links ORDER BY sort_order");
  779. return $link_array;
  780. }
  781. // ***************************************************************************
  782. // Get RSS Links in an array
  783. function GetRSSLinks()
  784. {
  785. global $cfg, $db;
  786. $link_array = array();
  787. $sql = "SELECT rid, url FROM tf_rss ORDER BY rid";
  788. $link_array = $db->GetAssoc($sql);
  789. showError($db,$sql);
  790. return $link_array;
  791. }
  792. // ***************************************************************************
  793. // Build Search Engine Drop Down List
  794. function buildSearchEngineDDL($selectedEngine = 'PirateBay', $autoSubmit = false)
  795. {
  796. $output = "<select name=\"searchEngine\" ";
  797. if ($autoSubmit)
  798. {
  799. $output .= "onchange=\"this.form.submit();\" ";
  800. }
  801. $output .= " STYLE=\"width: 125px\">";
  802. $handle = opendir("./searchEngines");
  803. while($entry = readdir($handle))
  804. {
  805. $entrys[] = $entry;
  806. }
  807. natcasesort($entrys);
  808. foreach($entrys as $entry)
  809. {
  810. if ($entry != "." && $entry != ".." && substr($entry, 0, 1) != ".")
  811. if(strpos($entry,"Engine.php"))
  812. {
  813. $tmpEngine = str_replace("Engine",'',substr($entry,0,strpos($entry,".")));
  814. $output .= "<option";
  815. if ($selectedEngine == $tmpEngine)
  816. {
  817. $output .= " selected";
  818. }
  819. $output .= ">".str_replace("Engine",'',substr($entry,0,strpos($entry,".")))."</option>";
  820. }
  821. }
  822. $output .= "</select>\n";
  823. return $output;
  824. }
  825. // ***************************************************************************
  826. // Build Search Engine Links
  827. function buildSearchEngineLinks($selectedEngine = 'PirateBay')
  828. {
  829. global $cfg;
  830. $settingsNeedsSaving = false;
  831. $settings['searchEngineLinks'] = Array();
  832. $output = '';
  833. if( (!array_key_exists('searchEngineLinks', $cfg)) || (!is_array($cfg['searchEngineLinks'])))
  834. {
  835. saveSettings($settings);
  836. }
  837. $handle = opendir("./searchEngines");
  838. while($entry = readdir($handle))
  839. {
  840. $entrys[] = $entry;
  841. }
  842. natcasesort($entrys);
  843. foreach($entrys as $entry)
  844. {
  845. if ($entry != "." && $entry != ".." && substr($entry, 0, 1) != ".")
  846. if(strpos($entry,"Engine.php"))
  847. {
  848. $tmpEngine = str_replace("Engine",'',substr($entry,0,strpos($entry,".")));
  849. if(array_key_exists($tmpEngine,$cfg['searchEngineLinks']))
  850. {
  851. $hreflink = $cfg['searchEngineLinks'][$tmpEngine];
  852. $settings['searchEngineLinks'][$tmpEngine] = $hreflink;
  853. }
  854. else
  855. {
  856. $hreflink = getEngineLink($tmpEngine);
  857. $settings['searchEngineLinks'][$tmpEngine] = $hreflink;
  858. $settingsNeedsSaving = true;
  859. }
  860. if (strlen($hreflink) > 0)
  861. {
  862. $output .= "<a href=\"http://".$hreflink."/\" target=\"_blank\">";
  863. if ($selectedEngine == $tmpEngine)
  864. {
  865. $output .= "<b>".$hreflink."</b>";
  866. }
  867. else
  868. {
  869. $output .= $hreflink;
  870. }
  871. $output .= "</a><br>\n";
  872. }
  873. }
  874. }
  875. if ( count($settings['searchEngineLinks'],COUNT_RECURSIVE) <> count($cfg['searchEngineLinks'],COUNT_RECURSIVE))
  876. {
  877. $settingsNeedsSaving = true;
  878. }
  879. if ($settingsNeedsSaving)
  880. {
  881. natcasesort($settings['searchEngineLinks']);
  882. saveSettings($settings);
  883. }
  884. return $output;
  885. }
  886. function getEngineLink($searchEngine)
  887. {
  888. $tmpLink = '';
  889. $engineFile = 'searchEngines/'.$searchEngine.'Engine.php';
  890. if (is_file($engineFile))
  891. {
  892. $fp = @fopen($engineFile,'r');
  893. if ($fp)
  894. {
  895. $tmp = fread($fp, filesize($engineFile));
  896. @fclose( $fp );
  897. $tmp = substr($tmp,strpos($tmp,'$this->mainURL'),100);
  898. $tmp = substr($tmp,strpos($tmp,"=")+1);
  899. $tmp = substr($tmp,0,strpos($tmp,";"));
  900. $tmpLink = trim(str_replace(array("'","\""),"",$tmp));
  901. }
  902. }
  903. return $tmpLink;
  904. }
  905. // ***************************************************************************
  906. // ***************************************************************************
  907. // Display Functions
  908. // ***************************************************************************
  909. // ***************************************************************************
  910. // Display the header portion of admin views
  911. function DisplayHead($subTopic, $showButtons=true, $refresh="", $percentdone="")
  912. {
  913. global $cfg;
  914. ?>
  915. <html>
  916. <HEAD>
  917. <TITLE><?php echo $percentdone.$cfg["pagetitle"] ?></TITLE>
  918. <link rel="icon" href="images/favicon.ico" type="image/x-icon" />
  919. <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
  920. <LINK REL="StyleSheet" HREF="themes/<?php echo $cfg["theme"] ?>/style.css" TYPE="text/css">
  921. <META HTTP-EQUIV="Pragma" CONTENT="no-cache" charset="<?php echo _CHARSET ?>">
  922. <?php
  923. if ($refresh != "")
  924. {
  925. echo "<meta http-equiv=\"REFRESH\" content=\"".$refresh."\">";
  926. }
  927. ?>
  928. </HEAD>
  929. <body topmargin="8" leftmargin="5" bgcolor="<?php echo $cfg["main_bgcolor"] ?>">
  930. <div align="center">
  931. <table border="0" cellpadding="0" cellspacing="0">
  932. <tr>
  933. <td>
  934. <table border="1" bordercolor="<?php echo $cfg["table_border_dk"] ?>" cellpadding="4" cellspacing="0">
  935. <tr>
  936. <td bgcolor="<?php echo $cfg["main_bgcolor"] ?>" background="themes/<?php echo $cfg["theme"] ?>/images/bar.gif">
  937. <?php DisplayTitleBar($cfg["pagetitle"]." - ".$subTopic, $showButtons); ?>
  938. </td>
  939. </tr>
  940. <tr>
  941. <td bgcolor="<?php echo $cfg["table_header_bg"] ?>">
  942. <div align="center">
  943. <table width="100%" bgcolor="<?php echo $cfg["body_data_bg"] ?>">
  944. <tr><td>
  945. <?php
  946. }
  947. // ***************************************************************************
  948. // ***************************************************************************
  949. // Display the footer portion
  950. function DisplayFoot($showReturn=true)
  951. {
  952. global $cfg;
  953. ?>
  954. </td></tr>
  955. </table>
  956. <?php
  957. if ($showReturn)
  958. {
  959. echo "[<a href=\"index.php\">"._RETURNTOTORRENTS."</a>]";
  960. echo "</form>";
  961. }
  962. ?>
  963. </div>
  964. </td>
  965. </tr>
  966. </table>
  967. <?php
  968. echo DisplayTorrentFluxLink();
  969. ?>
  970. </td>
  971. </tr>
  972. </table>
  973. </div>
  974. </body>
  975. </html>
  976. <?php
  977. }
  978. // ***************************************************************************
  979. // ***************************************************************************
  980. // Dipslay TF Link and Version
  981. function DisplayTorrentFluxLink()
  982. {
  983. global $cfg;
  984. echo "<div align=\"right\">";
  985. echo "<a href=\"http://www.torrentflux.com\" target=\"_blank\"><font class=\"tinywhite\">TorrentFlux ".$cfg["version"]."</font></a>&nbsp;&nbsp;";
  986. echo "</div>";
  987. }
  988. // ***************************************************************************
  989. // ***************************************************************************
  990. // Dipslay Title Bar
  991. // 2004-12-09 PFM: now using adodb.
  992. function DisplayTitleBar($pageTitleText, $showButtons=true)
  993. {
  994. global $cfg, $db;
  995. ?>
  996. <table width="100%" cellpadding="0" cellspacing="0" border="0">
  997. <tr>
  998. <td align="left"><font class="title"><?php echo $pageTitleText ?></font></td>
  999. <?php
  1000. if ($showButtons)
  1001. {
  1002. echo "<td align=right>";
  1003. // Top Buttons
  1004. echo "&nbsp;&nbsp;";
  1005. echo "<a href=\"index.php\"><img src=\"themes/".$cfg["theme"]."/images/home.gif\" width=49 height=13 title=\""._TORRENTS."\" border=0></a>&nbsp;";
  1006. echo "<a href=\"dir.php\"><img src=\"themes/".$cfg["theme"]."/images/directory.gif\" width=49 height=13 title=\""._DIRECTORYLIST."\" border=0></a>&nbsp;";
  1007. echo "<a href=\"history.php\"><img src=\"themes/".$cfg["theme"]."/images/history.gif\" width=49 height=13 title=\""._UPLOADHISTORY."\" border=0></a>&nbsp;";
  1008. echo "<a href=\"profile.php\"><img src=\"themes/".$cfg["theme"]."/images/profile.gif\" width=49 height=13 title=\""._MYPROFILE."\" border=0></a>&nbsp;";
  1009. // Does the user have messages?
  1010. $sql = "select count(*) from tf_messages where to_user='".$cfg['user']."' and IsNew=1";
  1011. $number_messages = $db->GetOne($sql);
  1012. showError($db,$sql);
  1013. if ($number_messages > 0)
  1014. {
  1015. // We have messages
  1016. $message_image = "themes/".$cfg["theme"]."/images/messages_on.gif";
  1017. }
  1018. else
  1019. {
  1020. // No messages
  1021. $message_image = "themes/".$cfg["theme"]."/images/messages_off.gif";
  1022. }
  1023. echo "<a href=\"readmsg.php\"><img src=\"".$message_image."\" width=49 height=13 title=\""._MESSAGES."\" border=0></a>";
  1024. if(IsAdmin())
  1025. {
  1026. echo "&nbsp;<a href=\"admin.php\"><img src=\"themes/".$cfg["theme"]."/images/admin.gif\" width=49 height=13 title=\""._ADMINISTRATION."\" border=0></a>";
  1027. }
  1028. echo "&nbsp;<a href=\"logout.php\"><img src=\"images/logout.gif\" width=13 height=12 title=\"Logout\" border=0></a>";
  1029. }
  1030. ?>
  1031. </td>
  1032. </tr>
  1033. </table>
  1034. <?php
  1035. }
  1036. // ***************************************************************************
  1037. // ***************************************************************************
  1038. // Dipslay dropdown list to send message to a user
  1039. function DisplayMessageList()
  1040. {
  1041. global $cfg;
  1042. $users = GetUsers();
  1043. echo '<div align="center">'.
  1044. '<table border="0" cellpadding="0" cellspacing="0">'.
  1045. '<form name="formMessage" action="message.php" method="post">'.
  1046. '<tr><td>' . _SENDMESSAGETO ;
  1047. echo '<select name="to_user">';
  1048. for($inx = 0; $inx < sizeof($users); $inx++)
  1049. {
  1050. echo '<option>'.htmlentities($users[$inx], ENT_QUOTES).'</option>';
  1051. }
  1052. echo '</select>';
  1053. echo '<input type="Submit" value="' . _COMPOSE .'">';
  1054. echo '</td></tr></form></table></div>';
  1055. }
  1056. // ***************************************************************************
  1057. // ***************************************************************************
  1058. // Removes HTML from Messages
  1059. function check_html ($str, $strip="")
  1060. {
  1061. /* The core of this code has been lifted from phpslash */
  1062. /* which is licenced under the GPL. */
  1063. if ($strip == "nohtml")
  1064. {
  1065. $AllowableHTML=array('');
  1066. }
  1067. $str = stripslashes($str);
  1068. $str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",'<\\1>', $str);
  1069. // Delete all spaces from html tags .
  1070. $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>",'<a href="\\1">', $str);
  1071. // Delete all attribs from Anchor, except an href, double quoted.
  1072. $str = eregi_replace("<[[:space:]]* img[[:space:]]*([^>]*)[[:space:]]*>", '', $str);
  1073. // Delete all img tags
  1074. $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?javascript[[:punct:]]*\"?[^>]*>", '', $str);
  1075. // Delete javascript code from a href tags -- Zhen-Xjell @ http://nukecops.com
  1076. $tmp = "";
  1077. while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg))
  1078. {
  1079. $i = strpos($str,$reg[0]);
  1080. $l = strlen($reg[0]);
  1081. if ($reg[1][0] == "/")
  1082. {
  1083. $tag = strtolower(substr($reg[1],1));
  1084. }
  1085. else
  1086. {
  1087. $tag = strtolower($reg[1]);
  1088. }
  1089. if ($a = $AllowableHTML[$tag])
  1090. {
  1091. if ($reg[1][0] == "/")
  1092. {
  1093. $tag = "</$tag>";
  1094. }
  1095. elseif (($a == 1) || ($reg[2] == ""))
  1096. {
  1097. $tag = "<$tag>";
  1098. }
  1099. else
  1100. {
  1101. # Place here the double quote fix function.
  1102. $attrb_list=delQuotes($reg[2]);
  1103. // A VER
  1104. $attrb_list = ereg_replace("&","&amp;",$attrb_list);
  1105. $tag = "<$tag" . $attrb_list . ">";
  1106. } # Attribs in tag allowed
  1107. }
  1108. else
  1109. {
  1110. $tag = "";
  1111. }
  1112. $tmp .= substr($str,0,$i) . $tag;
  1113. $str = substr($str,$i+$l);
  1114. }
  1115. $str = $tmp . $str;
  1116. return $str;
  1117. }
  1118. // ***************************************************************************
  1119. // ***************************************************************************
  1120. // Checks for the location of the torrents
  1121. // If it does not exist, then it creates it.
  1122. function checkTorrentPath()
  1123. {
  1124. global $cfg;
  1125. // is there a stat and torrent dir?
  1126. if (!@is_dir($cfg["torrent_file_path"]) && is_writable($cfg["path"]))
  1127. {
  1128. //Then create it
  1129. @mkdir($cfg["torrent_file_path"], 0777);
  1130. }
  1131. }
  1132. // ***************************************************************************
  1133. // ***************************************************************************
  1134. // Returns the drive space used as a percentage i.e 85 or 95
  1135. function getDriveSpace($drive)
  1136. {
  1137. $percent = 0;
  1138. if (is_dir($drive))
  1139. {
  1140. $dt = disk_total_space($drive);
  1141. $df = disk_free_space($drive);
  1142. $percent = round((($dt - $df)/$dt) * 100);
  1143. }
  1144. return $percent;
  1145. }
  1146. // ***************************************************************************
  1147. // ***************************************************************************
  1148. // Display the Drive Space Graphical Bar
  1149. function displayDriveSpaceBar($drivespace)
  1150. {
  1151. global $cfg;
  1152. $freeSpace = "";
  1153. if ($drivespace > 20)
  1154. {
  1155. $freeSpace = " (".formatFreeSpace($cfg["free_space"])." Free)";
  1156. }
  1157. ?>
  1158. <table width="100%" border="0" cellpadding="0" cellspacing="0">
  1159. <tr nowrap>
  1160. <td width="2%"><div class="tiny"><?php echo _STORAGE ?>:</div></td>
  1161. <td width="80%">
  1162. <table width="100%" border="0" cellpadding="0" cellspacing="0">
  1163. <tr>
  1164. <td background="themes/<?php echo $cfg["theme"] ?>/images/proglass.gif" width="<?php echo $drivespace ?>%"><div class="tinypercent" align="center"><?php echo $drivespace."%".$freeSpace ?></div></td>
  1165. <td background="themes/<?php echo $cfg["theme"] ?>/images/noglass.gif" width="<?php echo (100 - $drivespace) ?>%"><img src="images/blank.gif" width="1" height="3" border="0"></td>
  1166. </tr>
  1167. </table>
  1168. </td>
  1169. </tr>
  1170. </table>
  1171. <?php
  1172. }
  1173. // ***************************************************************************
  1174. // ***************************************************************************
  1175. // Convert free space to GB or MB depending on size
  1176. function formatFreeSpace($freeSpace)
  1177. {
  1178. $rtnValue = "";
  1179. if ($freeSpace > 1024)
  1180. {
  1181. $rtnValue = number_format($freeSpace/1024, 2)." GB";
  1182. }
  1183. else
  1184. {
  1185. $rtnValue = number_format($freeSpace, 2)." MB";
  1186. }
  1187. return $rtnValue;
  1188. }
  1189. //**************************************************************************
  1190. // getFileFilter()
  1191. // Returns a string used as a file filter.
  1192. // Takes in an array of file types.
  1193. function getFileFilter($inArray)
  1194. {
  1195. $filter = "(\.".strtolower($inArray[0]).")|"; // used to hold the file type filter
  1196. $filter .= "(\.".strtoupper($inArray[0]).")";
  1197. // Build the file filter
  1198. for($inx = 1; $inx < sizeof($inArray); $inx++)
  1199. {
  1200. $filter .= "|(\.".strtolower($inArray[$inx]).")";
  1201. $filter .= "|(\.".strtoupper($inArray[$inx]).")";
  1202. }
  1203. $filter .= "$";
  1204. return $filter;
  1205. }
  1206. //**************************************************************************
  1207. // getAliasName()
  1208. // Create Alias name for Text file and Screen Alias
  1209. function getAliasName($inName)
  1210. {
  1211. $replaceItems = array(" ", ".", "-", "[", "]", "(", ")", "#", "&", "@");
  1212. $alias = str_replace($replaceItems, "_", $inName);
  1213. $alias = strtolower($alias);
  1214. $alias = str_replace("_torrent", "", $alias);
  1215. return $alias;
  1216. }
  1217. //**************************************************************************
  1218. // cleanFileName()
  1219. // Remove bad characters that cause problems
  1220. function cleanFileName($inName)
  1221. {
  1222. $replaceItems = array("?", "&", "'", "\"", "+", "@");
  1223. $cleanName = str_replace($replaceItems, "", $inName);
  1224. $cleanName = ltrim($cleanName, "-");
  1225. $cleanName = preg_replace("/[^0-9a-z.]+/i",'_', $cleanName);
  1226. return $cleanName;
  1227. }
  1228. //**************************************************************************
  1229. // usingTornado()
  1230. // returns true if client is tornado
  1231. function usingTornado()
  1232. {
  1233. return true;
  1234. }
  1235. //**************************************************************************
  1236. // cleanURL()
  1237. // split on the "*" coming from Varchar URL
  1238. function cleanURL($url)
  1239. {
  1240. $rtnValue = $url;
  1241. $arURL = explode("*", $url);
  1242. if (sizeof($arURL) > 1)
  1243. {
  1244. $rtnValue = $arURL[1];
  1245. }
  1246. return $rtnValue;
  1247. }
  1248. // -------------------------------------------------------------------
  1249. // FetchTorrent() method to get data from URL
  1250. // Has support for specific sites
  1251. // -------------------------------------------------------------------
  1252. function FetchTorrent($url)
  1253. {
  1254. global $cfg, $db;
  1255. ini_set("allow_url_fopen", "1");
  1256. ini_set("user_agent", $_SERVER["HTTP_USER_AGENT"]);
  1257. $rtnValue = "";
  1258. $domain = parse_url( $url );
  1259. if( strtolower( substr( $domain["path"], -8 ) ) != ".torrent" )
  1260. {
  1261. // Check know domain types
  1262. if( strpos( strtolower ( $domain["host"] ), "mininova" ) !== false )
  1263. {
  1264. // Sample (http://www.mininova.org/rss.xml):
  1265. // http://www.mininova.org/tor/2254847
  1266. // <a href="/get/2281554">FreeLinux.ISO.iso.torrent</a>
  1267. // If received a /tor/ get the required information
  1268. if( strpos( $url, "/tor/" ) !== false )
  1269. {
  1270. // Get the contents of the /tor/ to find the real torrent name
  1271. $html = FetchHTML( $url );
  1272. // Check for the tag used on mininova.org
  1273. if( preg_match( "/<a href=\"\/get\/[0-9].[^\"]+\">(.[^<]+)<\/a>/i", $html, $html_preg_match ) )
  1274. {
  1275. // This is the real torrent filename
  1276. $cfg["save_torrent_name"] = $html_preg_match[1];
  1277. }
  1278. // Change to GET torrent url
  1279. $url = str_replace( "/tor/", "/get/", $url );
  1280. }
  1281. // Now fetch the torrent file
  1282. $html = FetchHTML( $url );
  1283. // This usually gets triggered if the original URL was /get/ instead of /tor/
  1284. if( strlen( $cfg["save_torrent_name"] ) == 0 )
  1285. {
  1286. // Get the name of the torrent, and make it the filename
  1287. if( preg_match( "/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match ) )
  1288. {
  1289. $filelength = $html_preg_match[1];
  1290. $filename = $html_preg_match[2];
  1291. $cfg["save_torrent_name"] = substr( $filename, 0, $filelength ) . ".torrent";
  1292. }
  1293. }
  1294. // Make sure we have a torrent file
  1295. if( strpos( $html, "d8:" ) === false )
  1296. {
  1297. // We don't have a Torrent File... it is something else
  1298. AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
  1299. $html = "";
  1300. }
  1301. return $html;
  1302. }
  1303. elseif( strpos( strtolower ( $domain["host"] ), "isohunt" ) !== false )
  1304. {
  1305. // Sample (http://isohunt.com/js/rss.php):
  1306. // http://isohunt.com/download.php?mode=bt&id=8837938
  1307. // http://isohunt.com/btDetails.php?ihq=&id=8464972
  1308. $referer = "http://" . $domain["host"] . "/btDetails.php?id=";
  1309. // If the url points to the details page, change it to the download url
  1310. if( strpos( strtolower( $url ), "/btdetails.php?" ) !== false )
  1311. {
  1312. $url = str_replace( "/btDetails.php?", "/download.php?", $url ) . "&mode=bt"; // Need to make it grab the torrent
  1313. }
  1314. // Grab contents of details page
  1315. $html = FetchHTML( $url, $referer );
  1316. // Get the name of the torrent, and make it the filename
  1317. if( preg_match( "/name([0-9]+):[^:]+/i", $html, $html_preg_match ) )
  1318. {
  1319. $filelength = $html_preg_match[1];
  1320. $filename = $html_preg_match[0];
  1321. $cfg["save_torrent_name"] = substr( $filename, 5+strlen($filelength), $filelength ) . ".torrent";
  1322. }
  1323. // Make sure we have a torrent file
  1324. if( strpos( $html, "d8:" ) === false )
  1325. {
  1326. // We don't have a Torrent File... it is something else
  1327. AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
  1328. $html = "";
  1329. }
  1330. return $html;
  1331. }
  1332. elseif( strpos( strtolower( $url ), "details.php?" ) !== false )
  1333. {
  1334. // Sample (http://www.bitmetv.org/rss.php?passkey=123456):
  1335. // http://www.bitmetv.org/details.php?id=18435&hit=1
  1336. $referer = "http://" . $domain["host"] . "/details.php?id=";
  1337. $html = FetchHTML( $url, $referer );
  1338. // Sample (http://www.bitmetv.org/details.php?id=18435)
  1339. // download.php/18435/SpiderMan%20Season%204.torrent
  1340. if( preg_match( "/(download.php.[^\"]+)/i", $html, $html_preg_match ) )
  1341. {
  1342. $torrent = str_replace( " ", "%20", substr( $html_preg_match[0], 0, -1 ) );
  1343. $url2 = "http://" . $domain["host"] . "/" . $torrent;
  1344. $html2 = FetchHTML( $url2 );
  1345. // Make sure we have a torrent file
  1346. if (strpos($html2, "d8:") === false)
  1347. {
  1348. // We don't have a Torrent File... it is something else
  1349. AuditAction($cfg["constants"]["error"], "BAD TORRENT for: ".$url."\n".$html2);
  1350. $html2 = "";
  1351. }
  1352. return $html2;
  1353. }
  1354. else
  1355. {
  1356. return "";
  1357. }
  1358. }
  1359. elseif( strpos( strtolower( $url ), "download.asp?" ) !== false )
  1360. {
  1361. // Sample (TF's TorrenySpy Search):
  1362. // http://www.torrentspy.com/download.asp?id=519793
  1363. $referer = "http://" . $domain["host"] . "/download.asp?id=";
  1364. $html = FetchHTML( $url, $referer );
  1365. // Get the name of the torrent, and make it the filename
  1366. if( preg_match( "/name([0-9]+):[^:]+/i", $html, $html_preg_match ) )
  1367. {
  1368. $filelength = $html_preg_match[1];
  1369. $filename = $html_preg_match[0];
  1370. $cfg["save_torrent_name"] = substr( $filename, 5+strlen($filelength), $filelength ) . ".torrent";
  1371. }
  1372. if( !empty( $html ) )
  1373. {
  1374. // Make sure we have a torrent file
  1375. if( strpos( $html, "d8:" ) === false )
  1376. {
  1377. // We don't have a Torrent File... it is something else
  1378. AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
  1379. $html = "";
  1380. }
  1381. return $html;
  1382. }
  1383. else
  1384. {
  1385. return "";
  1386. }
  1387. }
  1388. }
  1389. $html = FetchHTML( $url );
  1390. // Make sure we have a torrent file
  1391. if( strpos( $html, "d8:" ) === false )
  1392. {
  1393. // We don't have a Torrent File... it is something else
  1394. AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url. "\n" . $html );
  1395. $html = "";
  1396. }
  1397. else
  1398. {
  1399. $html = substr($html, strpos($html, "d8:"));
  1400. // Get the name of the torrent, and make it the filename
  1401. if( preg_match( "/name([0-9]+):[^:]+/i", $html, $html_preg_match ) )
  1402. {
  1403. $filelength = $html_preg_match[1];
  1404. $filename = $html_preg_match[0];
  1405. $cfg["save_torrent_name"] = substr( $filename, 5+strlen($filelength), $filelength ) . ".torrent";
  1406. }
  1407. }
  1408. return $html;
  1409. }
  1410. // -------------------------------------------------------------------
  1411. // FetchHTML() method to get data from URL -- uses timeout and user agent
  1412. // -------------------------------------------------------------------
  1413. function FetchHTML( $url, $referer = "" )
  1414. {
  1415. global $cfg, $db;
  1416. ini_set("allow_url_fopen", "1");
  1417. ini_set("user_agent", $_SERVER["HTTP_USER_AGENT"]);
  1418. //$url = cleanURL( $url );
  1419. $domain = parse_url( $url );
  1420. $getcmd = $domain["path"];
  1421. if(!array_key_exists("query", $domain))
  1422. {
  1423. $domain["query"] = "";
  1424. }
  1425. $getcmd .= ( !empty( $domain["query"] ) ) ? "?" . $domain["query"] : "";
  1426. $cookie = "";
  1427. $rtnValue = "";
  1428. // If the url already doesn't contain a passkey, then check
  1429. // to see if it has cookies set to the domain name.
  1430. if( ( strpos( $domain["query"], "passkey=" ) ) === false )
  1431. {
  1432. $sql = "SELECT c.data FROM tf_cookies AS c LEFT JOIN tf_users AS u ON ( u.uid = c.uid ) WHERE u.user_id = '" . $cfg["user"] . "' AND c.host = '" . $domain['host'] . "'";
  1433. $cookie = $db->GetOne( $sql );
  1434. showError( $db, $sql );
  1435. }
  1436. if( !array_key_exists("port", $domain) )
  1437. {
  1438. $domain["port"] = 80;
  1439. }
  1440. // Check to see if this site requires the use of cookies
  1441. if( !empty( $cookie ) )
  1442. {
  1443. $socket = @fsockopen( $domain["host"], $domain["port"], $errno, $errstr, 30 ); //connect to server
  1444. if( !empty( $socket ) )
  1445. {
  1446. // Write the outgoing header packet
  1447. // Using required cookie information
  1448. $packet = "GET " . $url . " HTTP/1.0\r\n";
  1449. $packet .= ( !empty( $referer ) ) ? "Referer: " . $referer . "\r\n" : "";
  1450. $packet .= "Accept: */*\r\n";
  1451. $packet .= "Accept-Language: en-us\r\n";
  1452. $packet .= "User-Agent: ".$_SERVER["HTTP_USER_AGENT"]."\r\n";
  1453. $packet .= "Host: " . $domain["host"] . "\r\n";
  1454. $packet .= "Connection: Close\r\n";
  1455. $packet .= "Cookie: " . $cookie . "\r\n\r\n";
  1456. // Send header packet information to server
  1457. @fputs( $socket, $packet );
  1458. // Initialize variable, make sure null until we add too it.
  1459. $rtnValue = null;
  1460. // If http 1.0 just take it all as 1 chunk (Much easier, but for old servers)
  1461. while( !@feof( $socket ) )
  1462. {
  1463. $rtnValue .= @fgets( $socket, 500000 );
  1464. }
  1465. @fclose( $socket ); // Close our connection
  1466. }
  1467. }
  1468. else
  1469. {
  1470. if( $fp = @fopen( $url, 'r' ) )
  1471. {
  1472. $rtnValue = "";
  1473. while( !@feof( $fp ) )
  1474. {
  1475. $rtnValue .= @fgets( $fp, 4096 );
  1476. }
  1477. @fclose( $fp );
  1478. }
  1479. }
  1480. // If the HTML is still empty, then try CURL
  1481. if (($rtnValue == "" && function_exists("curl_init")) ||
  1482. (strpos($rtnValue, "HTTP/1.0 302") > 0 && function_exists("curl_init")) ||
  1483. (strpos($rtnValue, "HTTP/1.1 302") > 0 && function_exists("curl_init")))
  1484. {
  1485. // Give CURL a Try
  1486. $ch = curl_init();
  1487. if ($cookie != "")
  1488. {
  1489. curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  1490. }
  1491. curl_setopt($ch, CURLOPT_PORT, $domain["port"]);
  1492. curl_setopt($ch, CURLOPT_URL, $url);
  1493. curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
  1494. curl_setopt($ch, CURLOPT_HEADER, TRUE);
  1495. curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
  1496. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  1497. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  1498. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  1499. curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, TRUE);
  1500. $response = curl_exec($ch);
  1501. curl_close($ch);
  1502. $rtnValue = substr($response, strpos($response, "d8:"));
  1503. $rtnValue = rtrim($rtnValue, "\r\n");
  1504. }
  1505. return $rtnValue;
  1506. }
  1507. //**************************************************************************
  1508. // getDownloadSize()
  1509. // Grab the full size of the download from the torrent metafile
  1510. function getDownloadSize($torrent)
  1511. {
  1512. $rtnValue = "";
  1513. if (file_exists($torrent))
  1514. {
  1515. include_once("BDecode.php");
  1516. $fd = fopen($torrent, "rd");
  1517. $alltorrent = fread($fd, filesize($torrent));
  1518. $array = BDecode($alltorrent);
  1519. fclose($fd);
  1520. $rtnValue = $array["info"]["piece length"] * (strlen($array["info"]["pieces"]) / 20);
  1521. }
  1522. return $rtnValue;
  1523. }
  1524. //**************************************************************************
  1525. // formatBytesToKBMGGB()
  1526. // Returns a string in format of GB, MB, or KB depending on the size for display
  1527. function formatBytesToKBMGGB($inBytes)
  1528. {
  1529. $rsize = "";
  1530. if ($inBytes > (1024 * 1024 * 1024))
  1531. {
  1532. $rsize = round($inBytes / (1024 * 1024 * 1024), 2) . " GB";
  1533. }
  1534. elseif ($inBytes < 1024 * 1024)
  1535. {
  1536. $rsize = round($inBytes / 1024, 1) . " KB";
  1537. }
  1538. else
  1539. {
  1540. $rsize = round($inBytes / (1024 * 1024), 1) . " MB";
  1541. }
  1542. return $rsize;
  1543. }
  1544. //**************************************************************************
  1545. // HealthData
  1546. // Stores the image and title of for the health of a file.
  1547. class HealthData
  1548. {
  1549. var $image = "";
  1550. var $title = "";
  1551. }
  1552. //**************************************************************************
  1553. // getStatusImage() Takes in an AliasFile object
  1554. // Returns a string "file name" of the status image icon
  1555. function getStatusImage($af)
  1556. {
  1557. $hd = new HealthData();
  1558. $hd->image = "black.gif";
  1559. $hd->title = "";
  1560. if ($af->running == "1")
  1561. {
  1562. // torrent is running
  1563. if ($af->seeds < 2)
  1564. {
  1565. $hd->image = "yellow.gif";
  1566. }
  1567. if ($af->seeds == 0)
  1568. {
  1569. $hd->image = "red.gif";
  1570. }
  1571. if ($af->seeds >= 2)
  1572. {
  1573. $hd->image = "green.gif";
  1574. }
  1575. }
  1576. if ($af->percent_done >= 100)
  1577. {
  1578. if(trim($af->up_speed) != "" && $af->running == "1")
  1579. {
  1580. // is seeding
  1581. $hd->image = "green.gif";
  1582. } else {
  1583. // the torrent is finished
  1584. $hd->image = "black.gif";
  1585. }
  1586. }
  1587. if ($hd->image != "black.gif")
  1588. {
  1589. $hd->title = "S:".$af->seeds." P:".$af->peers." ";
  1590. }
  1591. if ($af->running == "3")
  1592. {
  1593. // torrent is queued
  1594. $hd->image = "black.gif";
  1595. }
  1596. return $hd;
  1597. }
  1598. //**************************************************************************
  1599. function writeQinfo($fileName,$command)
  1600. {
  1601. $fp = fopen($fileName.".Qinfo","w");
  1602. fwrite($fp, $command);
  1603. fflush($fp);
  1604. fclose($fp);
  1605. }
  1606. //**************************************************************************
  1607. class ProcessInfo
  1608. {
  1609. var $pid = "";
  1610. var $ppid = "";
  1611. var $cmdline = "";
  1612. function ProcessInfo($psLine)
  1613. {
  1614. $psLine = trim($psLine);
  1615. if (strlen($psLine) > 12)
  1616. {
  1617. $this->pid = trim(substr($psLine, 0, 5));
  1618. $this->ppid = trim(substr($psLine, 5, 6));
  1619. $this->cmdline = trim(substr($psLine, 12));
  1620. }
  1621. }
  1622. }
  1623. //**************************************************************************
  1624. function runPS()
  1625. {
  1626. global $cfg;
  1627. return shell_exec("ps x -o pid,ppid,command -ww | grep ".basename($cfg["btphpbin"])." | grep ".$cfg["torrent_file_path"]." | grep -v grep");
  1628. }
  1629. //**************************************************************************
  1630. function RunningProcessInfo()
  1631. {
  1632. global $cfg;
  1633. if (IsAdmin())
  1634. {
  1635. include_once("RunningTorrent.php");
  1636. $screenStatus = runPS();
  1637. $arScreen = array();
  1638. $tok = strtok($screenStatus, "\n");
  1639. while ($tok)
  1640. {
  1641. array_push($arScreen, $tok);
  1642. $tok = strtok("\n");
  1643. }
  1644. $cProcess = array();
  1645. $cpProcess = array();
  1646. $pProcess = array();
  1647. $ProcessCmd = array();
  1648. $QLine = "";
  1649. for($i = 0; $i < sizeof($arScreen); $i++)
  1650. {
  1651. if(strpos($arScreen[$i], $cfg["tfQManager"]) > 0)
  1652. {
  1653. $pinfo = new ProcessInfo($arScreen[$i]);
  1654. $QLine = $pinfo->pid;
  1655. }
  1656. else
  1657. {
  1658. if(strpos($arScreen[$i], basename($cfg["btphpbin"])) !== false)
  1659. {
  1660. $pinfo = new ProcessInfo($arScreen[$i]);
  1661. if (intval($pinfo->ppid) == 1)
  1662. {
  1663. if(!strpos($pinfo->cmdline, "rep python") > 0)
  1664. {
  1665. if(!strpos($pinfo->cmdline, "ps x") > 0)
  1666. {
  1667. array_push($pProcess,$pinfo->pid);
  1668. $rt = new RunningTorrent($pinfo->pid . " " . $pinfo->cmdline);
  1669. //array_push($ProcessCmd,$pinfo->cmdline);
  1670. array_push($ProcessCmd,$rt->torrentOwner . "\t". str_replace(array(".stat"),"",$rt->statFile));
  1671. }
  1672. }
  1673. }
  1674. else
  1675. {
  1676. if(!strpos($pinfo->cmdline, "rep python") > 0)
  1677. {
  1678. if(!strpos($pinfo->cmdline, "ps x") > 0)
  1679. {
  1680. array_push($cProcess,$pinfo->pid);
  1681. array_push($cpProcess,$pinfo->ppid);
  1682. }
  1683. }
  1684. }
  1685. }
  1686. }
  1687. }
  1688. echo " --- Running Processes ---\n";
  1689. echo " Parents : " . count($pProcess) . "\n";
  1690. echo " Children : " . count($cProcess) . "\n";
  1691. echo "\n";
  1692. echo " PID \tOwner\tTorrent File\n";
  1693. foreach($pProcess as $key => $value)
  1694. {
  1695. echo " " . $value . "\t" . $ProcessCmd[$key] . "\n";
  1696. foreach($cpProcess as $cKey => $cValue)
  1697. if (intval($value) == intval($cValue))
  1698. echo "\t" . $cProcess[$cKey] . "\n";
  1699. }
  1700. echo "\n";
  1701. echo " --- QManager --- \n";
  1702. echo " PID : ";
  1703. echo " ".$QLine;
  1704. }
  1705. }
  1706. //**************************************************************************
  1707. function getNumberOfQueuedTorrents()
  1708. {
  1709. global $cfg;
  1710. $rtnValue = 0;
  1711. $dirName = $cfg["torrent_file_path"] . "queue/";
  1712. $handle = @opendir($dirName);
  1713. if ($handle)
  1714. {
  1715. while($entry = readdir($handle))
  1716. {
  1717. if ($entry != "." && $entry != "..")
  1718. {
  1719. if (!(@is_dir($dirName.$entry)) && (substr($entry, -6) == ".Qinfo"))
  1720. {
  1721. $rtnValue = $rtnValue + 1;
  1722. }
  1723. }
  1724. }
  1725. }
  1726. return $rtnValue;
  1727. }
  1728. //**************************************************************************
  1729. function getRunningTorrentCount()
  1730. {
  1731. return count(getRunningTorrents());
  1732. }
  1733. //**************************************************************************
  1734. function getRunningTorrents()
  1735. {
  1736. global $cfg;
  1737. $screenStatus = runPS();
  1738. $arScreen = array();
  1739. $tok = strtok($screenStatus, "\n");
  1740. while ($tok)
  1741. {
  1742. array_push($arScreen, $tok);
  1743. $tok = strtok("\n");
  1744. }
  1745. $artorrent = array();
  1746. for($i = 0; $i < sizeof($arScreen); $i++)
  1747. {
  1748. if(! strpos($arScreen[$i], $cfg["tfQManager"]) > 0)
  1749. {
  1750. if(strpos($arScreen[$i], basename($cfg["btphpbin"])) !== false)
  1751. {
  1752. $pinfo = new ProcessInfo($arScreen[$i]);
  1753. if (intval($pinfo->ppid) == 1)
  1754. {
  1755. if(!strpos($pinfo->cmdline, "rep python") > 0)
  1756. {
  1757. if(!strpos($pinfo->cmdline, "ps x") > 0)
  1758. {
  1759. array_push($artorrent,$pinfo->pid . " " . $pinfo->cmdline);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. }
  1765. }
  1766. return $artorrent;
  1767. }
  1768. //**************************************************************************
  1769. function checkQManager()
  1770. {
  1771. $x = getQManagerPID();
  1772. if (strlen($x) > 0)
  1773. {
  1774. $y = $x;
  1775. $arScreen = array();
  1776. $tok = strtok(shell_exec("ps -p " . $x . " | grep " . $y), "\n");
  1777. while ($tok)
  1778. {
  1779. array_push($arScreen, $tok);
  1780. $tok = strtok("\n");
  1781. }
  1782. $QMgrCount = sizeOf($arScreen);
  1783. }
  1784. else
  1785. {
  1786. $QMgrCount = 0;
  1787. }
  1788. return $QMgrCount;
  1789. }
  1790. //**************************************************************************
  1791. function getQManagerPID()
  1792. {
  1793. global $cfg;
  1794. $rtnValue = "";
  1795. $pidFile = $cfg["torrent_file_path"] . "queue/tfQManager.pid";
  1796. if(file_exists($pidFile))
  1797. {
  1798. $fp = fopen($pidFile,"r");
  1799. if ($fp)
  1800. {
  1801. while (!feof($fp))
  1802. {
  1803. $tmpValue = fread($fp,1);
  1804. if($tmpValue != "\n")
  1805. $rtnValue .= $tmpValue;
  1806. }
  1807. fclose($fp);
  1808. }
  1809. }
  1810. return $rtnValue;
  1811. }
  1812. //**************************************************************************
  1813. function startQManager($maxServerThreads=5,$maxUserThreads=2,$sleepInterval=10)
  1814. {
  1815. global $cfg;
  1816. // is there a stat and torrent dir?
  1817. if (is_dir($cfg["torrent_file_path"]))
  1818. {
  1819. if (is_writable($cfg["torrent_file_path"]) && !is_dir($cfg["torrent_file_path"]."queue/"))
  1820. {
  1821. //Then create it
  1822. mkdir($cfg["torrent_file_path"]."queue/", 0777);
  1823. }
  1824. }
  1825. if (checkQManager() == 0)
  1826. {
  1827. $cmd1 = "cd " . $cfg["path"] . "TFQUSERNAME";
  1828. if (! array_key_exists("pythonCmd",$cfg))
  1829. {
  1830. insertSetting("pythonCmd","/usr/bin/python");
  1831. }
  1832. if (! array_key_exists("debugTorrents",$cfg))
  1833. {
  1834. insertSetting("debugTorrents",false);
  1835. }
  1836. if (!$cfg["debugTorrents"])
  1837. {
  1838. $pyCmd = $cfg["pythonCmd"] . " -OO";
  1839. }
  1840. else
  1841. {
  1842. $pyCmd = $cfg["pythonCmd"];
  1843. }
  1844. $btphp = "'" . $cmd1. "; HOME=".$cfg["path"]."; export HOME; nohup " . $pyCmd . " " .$cfg["btphpbin"] . " '";
  1845. $command = $pyCmd . " " . $cfg["tfQManager"] . " ".$cfg["torrent_file_path"]."queue/ ".escapeshellarg($maxServerThreads)." ".escapeshellarg($maxUserThreads)." ".escapeshellarg($sleepInterval)." ".$btphp." > /dev/null &";
  1846. //$command = $pyCmd . " " . $cfg["tfQManager"] . " ".$cfg["torrent_file_path"]."queue/ ".$maxServerThreads." ".$maxUserThreads." ".$sleepInterval." ".$btphp." > /dev/null2>&1 & &";
  1847. $result = exec($command);
  1848. sleep(2); // wait for it to start prior to getting pid
  1849. AuditAction($cfg["constants"]["QManager"], "Started PID:" . getQManagerPID());
  1850. }else{
  1851. AuditAction($cfg["constants"]["QManager"], "QManager Already Started PID:" . getQManagerPID());
  1852. }
  1853. }
  1854. //**************************************************************************
  1855. function stopQManager()
  1856. {
  1857. global $cfg;
  1858. $QmgrPID = getQManagerPID();
  1859. if($QmgrPID != "")
  1860. {
  1861. AuditAction($cfg["constants"]["QManager"], "Stopping PID:" . $QmgrPID);
  1862. $result = exec("kill ".escapeshellarg($QmgrPID));
  1863. unlink($cfg["torrent_file_path"] . "queue/tfQManager.pid");
  1864. }
  1865. }
  1866. //**************************************************************************
  1867. // file_size()
  1868. // Returns file size... overcomes PHP limit of 2.0GB
  1869. function file_size($file)
  1870. {
  1871. $size = @filesize($file);
  1872. if ( $size == 0)
  1873. {
  1874. $size = exec("ls -l \"".escapeshellarg($file)."\" | awk '{print $5}'");
  1875. }
  1876. return $size;
  1877. }
  1878. //**************************************************************************
  1879. // SecurityClean()
  1880. // Cleans the file name for delete and alias file creation
  1881. function SecurityClean($string)
  1882. {
  1883. global $cfg;
  1884. if (empty($string))
  1885. {
  1886. return $string;
  1887. }
  1888. $array = array("<", ">", "\\", "//", "..", "'", "/");
  1889. foreach ($array as $char)
  1890. {
  1891. $string = str_replace($char, NULL, $string);
  1892. }
  1893. if( (strtolower( substr( $string, -8 ) ) == ".torrent") || (strtolower( substr( $string, -5 ) ) == ".stat") )
  1894. {
  1895. // we are good
  1896. }
  1897. else
  1898. {
  1899. AuditAction($cfg["constants"]["error"], "Not a stat or torrent: " . $string);
  1900. die("Invalid file specified. Action has been logged.");
  1901. }
  1902. return $string;
  1903. }
  1904. //**************************************************************************
  1905. // getDirList()
  1906. // This method Builds and displays the Torrent Section of the Index Page
  1907. function getDirList($dirName)
  1908. {
  1909. global $cfg, $db;
  1910. include_once("AliasFile.php");
  1911. include_once("RunningTorrent.php");
  1912. $runningTorrents = getRunningTorrents();
  1913. $arList = array();
  1914. $file_filter = getFileFilter($cfg["file_types_array"]);
  1915. if (is_dir($dirName))
  1916. {
  1917. $handle = opendir($dirName);
  1918. }
  1919. else
  1920. {
  1921. // nothing to read
  1922. if (IsAdmin())
  1923. {
  1924. echo "<b>ERROR:</b> ".$dirName." Path is not valid. Please edit <a href='admin.php?op=configSettings'>settings</a><br>";
  1925. }
  1926. else
  1927. {
  1928. echo "<b>ERROR:</b> Contact an admin the Path is not valid.<br>";
  1929. }
  1930. return;
  1931. }
  1932. $lastUser = "";
  1933. $arUserTorrent = array();
  1934. $arListTorrent = array();
  1935. while($entry = readdir($handle))
  1936. {
  1937. if ($entry != "." && $entry != "..")
  1938. {
  1939. if (is_dir($dirName."/".$entry))
  1940. {
  1941. // don''t do a thing
  1942. }
  1943. else
  1944. {
  1945. if (ereg($file_filter, $entry))
  1946. {
  1947. $key = filemtime($dirName."/".$entry).md5($entry);
  1948. $arList[$key] = $entry;
  1949. }
  1950. }
  1951. }
  1952. }
  1953. // sort the files by date
  1954. krsort($arList);
  1955. foreach($arList as $entry)
  1956. {
  1957. $output = "";
  1958. $displayname = $entry;
  1959. $show_run = true;
  1960. $torrentowner = getOwner($entry);
  1961. $owner = IsOwner($cfg["user"], $torrentowner);
  1962. $kill_id = "";
  1963. $estTime = "&nbsp;";
  1964. $alias = getAliasName($entry).".stat";
  1965. $af = new AliasFile($dirName.$alias, $torrentowner);
  1966. $timeStarted = "";
  1967. $torrentfilelink = "";
  1968. if(!file_exists($dirName.$alias))
  1969. {
  1970. $af->running = "2"; // file is new
  1971. $af->size = getDownloadSize($dirName.$entry);
  1972. $af->WriteFile();
  1973. }
  1974. if(strlen($entry) >= 47)
  1975. {
  1976. // needs to be trimmed
  1977. $displayname = substr($entry, 0, 44);
  1978. $displayname .= "...";
  1979. }
  1980. // find out if any screens are running and take their PID and make a KILL option
  1981. foreach ($runningTorrents as $key => $value)
  1982. {
  1983. $rt = new RunningTorrent($value);
  1984. if ($rt->statFile == $alias) {
  1985. if ($kill_id == "")
  1986. {
  1987. $kill_id = $rt->processId;
  1988. }
  1989. else
  1990. {
  1991. // there is more than one PID for this torrent
  1992. // Add it so it can be killed as well.
  1993. $kill_id .= "|".$rt->processId;
  1994. }
  1995. }
  1996. }
  1997. // Check to see if we have a pid without a process.
  1998. if (is_file($cfg["torrent_file_path"].$alias.".pid") && empty($kill_id))
  1999. {
  2000. // died outside of tf and pid still exists.
  2001. @unlink($cfg["torrent_file_path"].$alias.".pid");
  2002. if(($af->percent_done < 100) && ($af->percent_done >= 0))
  2003. {
  2004. // The file is not running and the percent done needs to be changed
  2005. $af->percent_done = ($af->percent_done+100)*-1;
  2006. }
  2007. $af->running = "0";
  2008. $af->time_left = "Torrent Died";
  2009. $af->up_speed = "";
  2010. $af->down_speed = "";
  2011. // write over the status file so that we can display a new status
  2012. $af->WriteFile();
  2013. }
  2014. if ($cfg["enable_torrent_download"])
  2015. {
  2016. $torrentfilelink = "<a href=\"maketorrent.php?download=".urlencode($entry)."\"><img src=\"images/down.gif\" width=9 height=9 title=\"Download Torrent File\" border=0 align=\"absmiddle\"></a>";
  2017. }
  2018. $hd = getStatusImage($af);
  2019. $output .= "<tr><td class=\"tiny\"><img src=\"images/".$hd->image."\" width=16 height=16 title=\"".$hd->title.$entry."\" border=0 align=\"absmiddle\">".$torrentfilelink.$displayname."</td>";
  2020. $output .= "<td align=\"right\"><font class=\"tiny\">".formatBytesToKBMGGB($af->size)."</font></td>";
  2021. $output .= "<td align=\"center\"><a href=\"message.php?to_user=".$torrentowner."\"><font class=\"tiny\">".$torrentowner."</font></a></td>";
  2022. $output .= "<td valign=\"bottom\"><div align=\"center\">";
  2023. if ($af->running == "2")
  2024. {
  2025. $output .= "<i><font color=\"#32cd32\">"._NEW."</font></i>";
  2026. }
  2027. elseif ($af->running == "3" )
  2028. {
  2029. $estTime = "Waiting...";
  2030. $qDateTime = '';
  2031. if(is_file($dirName."queue/".$alias.".Qinfo"))
  2032. {
  2033. $qDateTime = date("m/d/Y H:i:s", strval(filectime($dirName."queue/".$alias.".Qinfo")));
  2034. }
  2035. $output .= "<i><font color=\"#000000\" onmouseover=\"return overlib('"._QUEUED.": ".$qDateTime."<br>', CSSCLASS);\" onmouseout=\"return nd();\">"._QUEUED."</font></i>";
  2036. }
  2037. else
  2038. {
  2039. if ($af->time_left != "" && $af->time_left != "0")
  2040. {
  2041. $estTime = $af->time_left;
  2042. }
  2043. $sql_search_time = "Select time from tf_log where action like '%Upload' and file like '".$entry."%'";
  2044. $result_search_time = $db->Execute($sql_search_time);
  2045. list($uploaddate) = $result_search_time->FetchRow();
  2046. $lastUser = $torrentowner;
  2047. $sharing = $af->sharing."%";
  2048. $graph_width = 1;
  2049. $progress_color = "#00ff00";
  2050. $background = "#000000";
  2051. $bar_width = "4";
  2052. $popup_msg = _ESTIMATEDTIME.": ".$af->time_left;
  2053. $popup_msg .= "<br>"._DOWNLOADSPEED.": ".$af->down_speed;
  2054. $popup_msg .= "<br>"._UPLOADSPEED.": ".$af->up_speed;
  2055. $popup_msg .= "<br>"._SHARING.": ".$sharing;
  2056. $popup_msg .= "<br>Seeds: ".$af->seeds;
  2057. $popup_msg .= "<br>Peers: ".$af->peers;
  2058. $popup_msg .= "<br>"._USER.": ".$torrentowner;
  2059. $eCount = 0;
  2060. foreach ($af->errors as $key => $value)
  2061. {
  2062. if(strpos($value," (x"))
  2063. {
  2064. $curEMsg = substr($value,strpos($value," (x")+3);
  2065. $eCount += substr($curEMsg,0,strpos($curEMsg,")"));
  2066. }
  2067. else
  2068. {
  2069. $eCount += 1;
  2070. }
  2071. }
  2072. $popup_msg .= "<br>"._ERRORSREPORTED.": ".strval($eCount);
  2073. $popup_msg .= "<br>"._UPLOADED.": ".date("m/d/Y H:i:s", $uploaddate);
  2074. if (is_file($dirName.$alias.".pid"))
  2075. {
  2076. $timeStarted = "<br>"._STARTED.": ".date("m/d/Y H:i:s", strval(filectime($dirName.$alias.".pid")));
  2077. }
  2078. // incriment the totals
  2079. if(!isset($cfg["total_upload"])) $cfg["total_upload"] = 0;
  2080. if(!isset($cfg["total_download"])) $cfg["total_download"] = 0;
  2081. $cfg["total_upload"] = $cfg["total_upload"] + GetSpeedValue($af->up_speed);
  2082. $cfg["total_download"] = $cfg["total_download"] + GetSpeedValue($af->down_speed);
  2083. if($af->percent_done >= 100)
  2084. {
  2085. if(trim($af->up_speed) != "" && $af->running == "1")
  2086. {
  2087. $popup_msg .= $timeStarted;
  2088. $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" style=\"font-size:7pt;\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\">seeding (".$af->up_speed.") ".$sharing."</a>";
  2089. }
  2090. else
  2091. {
  2092. $popup_msg .= "<br>"._ENDED.": ".date("m/d/Y H:i:s", strval(filemtime($dirName.$alias)));
  2093. $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=red>"._DONE."</font></i></a>";
  2094. }
  2095. $show_run = false;
  2096. }
  2097. else if ($af->percent_done < 0)
  2098. {
  2099. $popup_msg .= $timeStarted;
  2100. $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=\"#989898\">"._INCOMPLETE."</font></i></a>";
  2101. $show_run = true;
  2102. }
  2103. else
  2104. {
  2105. $popup_msg .= $timeStarted;
  2106. if($af->percent_done > 1)
  2107. {
  2108. $graph_width = $af->percent_done;
  2109. }
  2110. if($graph_width == 100)
  2111. {
  2112. $background = $progress_color;
  2113. }
  2114. $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\">";
  2115. $output .= "<font class=\"tiny\"><strong>".$af->percent_done."%</strong> @ ".$af->down_speed."</font></a><br>";
  2116. $output .= "<table width=\"100\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
  2117. $output .= "<tr><td background=\"themes/".$cfg["theme"]."/images/progressbar.gif\" bgcolor=\"".$progress_color."\"><img src=\"images/blank.gif\" width=\"".$graph_width."\" height=\"".$bar_width."\" border=\"0\"></td>";
  2118. $output .= "<td bgcolor=\"".$background."\"><img src=\"images/blank.gif\" width=\"".(100 - $graph_width)."\" height=\"".$bar_width."\" border=\"0\"></td>";
  2119. $output .= "</tr></table>";
  2120. }
  2121. }
  2122. $output .= "</div></td>";
  2123. $output .= "<td><div class=\"tiny\" align=\"center\">".$estTime."</div></td>";
  2124. $output .= "<td><div align=center>";
  2125. $torrentDetails = _TORRENTDETAILS;
  2126. if ($lastUser != "")
  2127. {
  2128. $torrentDetails .= "\n"._USER.": ".$lastUser;
  2129. }
  2130. $output .= "<a href=\"details.php?torrent=".urlencode($entry);
  2131. if($af->running == 1)
  2132. {
  2133. $output .= "&als=false";
  2134. }
  2135. $output .= "\"><img src=\"images/properties.png\" width=18 height=13 title=\"".$torrentDetails."\" border=0></a>";
  2136. if ($owner || IsAdmin($cfg["user"]))
  2137. {
  2138. if($kill_id != "" && $af->percent_done >= 0 && $af->running == 1)
  2139. {
  2140. $output .= "<a href=\"index.php?alias_file=".$alias."&kill=".$kill_id."&kill_torrent=".urlencode($entry)."\"><img src=\"images/kill.gif\" width=16 height=16 title=\""._STOPDOWNLOAD."\" border=0></a>";
  2141. $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 border=0>";
  2142. }
  2143. else
  2144. {
  2145. if($torrentowner == "n/a")
  2146. {
  2147. $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\""._NOTOWNER."\">";
  2148. }
  2149. else
  2150. {
  2151. if ($af->running == "3")
  2152. {
  2153. $output .= "<a href=\"index.php?alias_file=".$alias."&dQueue=".$kill_id."&QEntry=".urlencode($entry)."\"><img src=\"images/queued.gif\" width=16 height=16 title=\""._DELQUEUE."\" border=0></a>";
  2154. }
  2155. else
  2156. {
  2157. if (!is_file($cfg["torrent_file_path"].$alias.".pid"))
  2158. {
  2159. // Allow Avanced start popup?
  2160. if ($cfg["advanced_start"])
  2161. {
  2162. if($show_run)
  2163. {
  2164. $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=".urlencode($entry)."')\"><img src=\"images/run_on.gif\" width=16 height=16 title=\""._RUNTORRENT."\" border=0></a>";
  2165. }
  2166. else
  2167. {
  2168. $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=".urlencode($entry)."')\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\""._SEEDTORRENT."\" border=0></a>";
  2169. }
  2170. }
  2171. else
  2172. {
  2173. // Quick Start
  2174. if($show_run)
  2175. {
  2176. $output .= "<a href=\"".$_SERVER['PHP_SELF']."?torrent=".urlencode($entry)."\"><img src=\"images/run_on.gif\" width=16 height=16 title=\""._RUNTORRENT."\" border=0></a>";
  2177. }
  2178. else
  2179. {
  2180. $output .= "<a href=\"".$_SERVER['PHP_SELF']."?torrent=".urlencode($entry)."\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\""._SEEDTORRENT."\" border=0></a>";
  2181. }
  2182. }
  2183. }
  2184. else
  2185. {
  2186. // pid file exists so this may still be running or dieing.
  2187. $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\""._STOPPING."\">";
  2188. }
  2189. }
  2190. }
  2191. if (!is_file($cfg["torrent_file_path"].$alias.".pid"))
  2192. {
  2193. $deletelink = $_SERVER['PHP_SELF']."?alias_file=".$alias."&delfile=".urlencode($entry);
  2194. $output .= "<a href=\"".$deletelink."\" onclick=\"return ConfirmDelete('".$entry."')\"><img src=\"images/delete_on.gif\" width=16 height=16 title=\""._DELETE."\" border=0></a>";
  2195. }
  2196. else
  2197. {
  2198. // pid file present so process may be still running. don't allow deletion.
  2199. $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 title=\""._STOPPING."\" border=0>";
  2200. }
  2201. }
  2202. }
  2203. else
  2204. {
  2205. $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\""._NOTOWNER."\">";
  2206. $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\""._NOTOWNER."\">";
  2207. }
  2208. $output .= "</div>";
  2209. $output .= "</td>";
  2210. $output .= "</tr>\n";
  2211. // Is this torrent for the user list or the general list?
  2212. if ($cfg["user"] == getOwner($entry))
  2213. {
  2214. array_push($arUserTorrent, $output);
  2215. }
  2216. else
  2217. {
  2218. array_push($arListTorrent, $output);
  2219. }
  2220. }
  2221. closedir($handle);
  2222. // Now spit out the junk
  2223. echo "<table bgcolor=\"".$cfg["table_data_bg"]."\" width=\"100%\" bordercolor=\"".$cfg["table_border_dk"]."\" border=1 cellpadding=3 cellspacing=0>";
  2224. if (sizeof($arUserTorrent) > 0)
  2225. {
  2226. echo "<tr><td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">".$cfg["user"].": "._TORRENTFILE."</div></td>";
  2227. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">Size</div></td>";
  2228. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._USER."</div></td>";
  2229. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._STATUS."</div></td>";
  2230. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ESTIMATEDTIME."</div></td>";
  2231. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ADMIN."</div></td>";
  2232. echo "</tr>\n";
  2233. foreach($arUserTorrent as $torrentrow)
  2234. {
  2235. echo $torrentrow;
  2236. }
  2237. }
  2238. if (sizeof($arListTorrent) > 0)
  2239. {
  2240. echo "<tr><td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._TORRENTFILE."</div></td>";
  2241. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">Size</div></td>";
  2242. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._USER."</div></td>";
  2243. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._STATUS."</div></td>";
  2244. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ESTIMATEDTIME."</div></td>";
  2245. echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ADMIN."</div></td>";
  2246. echo "</tr>\n";
  2247. foreach($arListTorrent as $torrentrow)
  2248. {
  2249. echo $torrentrow;
  2250. }
  2251. }
  2252. }
  2253. ?>