PageRenderTime 45ms CodeModel.GetById 3ms app.highlight 30ms RepoModel.GetById 1ms app.codeStats 1ms

/functions.php

https://github.com/alx/torrentflux
PHP | 2665 lines | 2410 code | 142 blank | 113 comment | 107 complexity | 1e92daaaa2488bda38df4a0cc403412c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2
   3/*************************************************************
   4*  TorrentFlux - PHP Torrent Manager
   5*  www.torrentflux.com
   6**************************************************************/
   7/*
   8    This file is part of TorrentFlux.
   9
  10    TorrentFlux is free software; you can redistribute it and/or modify
  11    it under the terms of the GNU General Public License as published by
  12    the Free Software Foundation; either version 2 of the License, or
  13    (at your option) any later version.
  14
  15    TorrentFlux is distributed in the hope that it will be useful,
  16    but WITHOUT ANY WARRANTY; without even the implied warranty of
  17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18    GNU General Public License for more details.
  19
  20    You should have received a copy of the GNU General Public License
  21    along with TorrentFlux; if not, write to the Free Software
  22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  23*/
  24
  25// Start Session and grab user
  26session_name("TorrentFlux");
  27session_start();
  28
  29if(isset($_SESSION['user']))
  30{
  31    $cfg["user"] = strtolower($_SESSION['user']);
  32}else{
  33    $cfg["user"] = "root";
  34}
  35
  36include_once('db.php');
  37include_once("settingsfunctions.php");
  38
  39// Create Connection.
  40$db = getdb();
  41
  42loadSettings();
  43
  44// Free space in MB
  45$cfg["free_space"] = @disk_free_space($cfg["path"])/(1024*1024);
  46
  47// Path to where the torrent meta files will be stored... usually a sub of $cfg["path"]
  48// also, not the '.' to make this a hidden directory
  49$cfg["torrent_file_path"] = $cfg["path"].".torrents/";
  50
  51Authenticate();
  52
  53include_once("language/".$cfg["language_file"]);
  54include_once("themes/".$cfg["theme"]."/index.php");
  55AuditAction($cfg["constants"]["hit"], $_SERVER['PHP_SELF']);
  56PruneDB();
  57
  58// is there a stat and torrent dir?  If not then it will create it.
  59checkTorrentPath();
  60
  61//**********************************************************************************
  62// START FUNCTIONS HERE
  63//**********************************************************************************
  64
  65//*********************************************************
  66function getLinkSortOrder($lid)
  67{
  68    global $db;
  69
  70    // Get Current sort order index of link with this link id:
  71    $sql="SELECT sort_order FROM tf_links WHERE lid=$lid";
  72    $rtnValue=$db->GetOne($sql);
  73    showError($db,$sql);
  74
  75    return $rtnValue;
  76}
  77
  78//*********************************************************
  79// avddelete()
  80function avddelete($file)
  81{
  82    $file = html_entity_decode($file, ENT_QUOTES);
  83    chmod($file,0777);
  84    if (@is_dir($file))
  85    {
  86        $handle = @opendir($file);
  87        while($filename = readdir($handle))
  88        {
  89            if ($filename != "." && $filename != "..")
  90            {
  91                avddelete($file."/".$filename);
  92            }
  93        }
  94        closedir($handle);
  95        @rmdir($file);
  96    }
  97    else
  98    {
  99        @unlink($file);
 100    }
 101}
 102
 103
 104//*********************************************************
 105// Authenticate()
 106function Authenticate()
 107{
 108    global $cfg, $db;
 109
 110    $create_time = time();
 111
 112    if(!isset($_SESSION['user']))
 113    {
 114        //header('location: login.php');
 115        //exit();
 116    }
 117
 118    if ($_SESSION['user'] == md5($cfg["pagetitle"]))
 119    {
 120        // user changed password and needs to login again
 121        header('location: logout.php');
 122        exit();
 123    }
 124
 125    $sql = "SELECT uid, hits, hide_offline, theme, language_file FROM tf_users WHERE user_id=".$db->qstr($cfg['user']);
 126    $recordset = $db->Execute($sql);
 127    showError($db, $sql);
 128
 129    if($recordset->RecordCount() != 1)
 130    {
 131        AuditAction($cfg["constants"]["error"], "FAILED AUTH: ".$cfg['user']);
 132        session_destroy();
 133        header('location: login.php');
 134        exit();
 135    }
 136
 137    list($uid, $hits, $cfg["hide_offline"], $cfg["theme"], $cfg["language_file"]) = $recordset->FetchRow();
 138
 139    // Check for valid theme
 140    if (!ereg('^[^./][^/]*$', $cfg["theme"]))
 141    {
 142        AuditAction($cfg["constants"]["error"], "THEME VARIABLE CHANGE ATTEMPT: ".$cfg["theme"]." from ".$cfg['user']);
 143        $cfg["theme"] = $cfg["default_theme"];
 144    }
 145
 146    // Check for valid language file
 147    if(!ereg('^[^./][^/]*$', $cfg["language_file"]))
 148    {
 149        AuditAction($cfg["constants"]["error"], "LANGUAGE VARIABLE CHANGE ATTEMPT: ".$cfg["language_file"]." from ".$cfg['user']);
 150        $cfg["language_file"] = $cfg["default_language"];
 151    }
 152
 153    if (!is_dir("themes/".$cfg["theme"]))
 154    {
 155        $cfg["theme"] = $cfg["default_theme"];
 156    }
 157
 158    // Check for valid language file
 159    if (!is_file("language/".$cfg["language_file"]))
 160    {
 161        $cfg["language_file"] = $cfg["default_language"];
 162    }
 163
 164    $hits++;
 165
 166    $sql = 'select * from tf_users where uid = '.$uid;
 167    $rs = $db->Execute($sql);
 168    showError($db, $sql);
 169
 170    $rec = array(
 171                    'hits' => $hits,
 172                    'last_visit' => $create_time,
 173                    'theme' => $cfg['theme'],
 174                    'language_file' => $cfg['language_file']
 175                );
 176    $sql = $db->GetUpdateSQL($rs, $rec);
 177
 178    $result = $db->Execute($sql);
 179    showError($db,$sql);
 180}
 181
 182
 183//*********************************************************
 184// SaveMessage
 185function SaveMessage($to_user, $from_user, $message, $to_all=0, $force_read=0)
 186{
 187    global $_SERVER, $cfg, $db;
 188
 189    $message = str_replace(array("'"), "", $message);
 190
 191    $create_time = time();
 192
 193    $sTable = 'tf_messages';
 194    if($to_all == 1)
 195    {
 196        $message .= "\n\n__________________________________\n*** "._MESSAGETOALL." ***";
 197        $sql = 'select user_id from tf_users';
 198        $result = $db->Execute($sql);
 199        showError($db,$sql);
 200
 201        while($row = $result->FetchRow())
 202        {
 203            $rec = array(
 204                        'to_user' => $row['user_id'],
 205                        'from_user' => $from_user,
 206                        'message' => $message,
 207                        'IsNew' => 1,
 208                        'ip' => $cfg['ip'],
 209                        'time' => $create_time,
 210                        'force_read' => $force_read
 211                        );
 212
 213            $sql = $db->GetInsertSql($sTable, $rec);
 214
 215            $result2 = $db->Execute($sql);
 216            showError($db,$sql);
 217        }
 218    }
 219    else
 220    {
 221        // Only Send to one Person
 222        $rec = array(
 223                    'to_user' => $to_user,
 224                    'from_user' => $from_user,
 225                    'message' => $message,
 226                    'IsNew' => 1,
 227                    'ip' => $cfg['ip'],
 228                    'time' => $create_time,
 229                    'force_read' => $force_read
 230                    );
 231        $sql = $db->GetInsertSql($sTable, $rec);
 232        $result = $db->Execute($sql);
 233        showError($db,$sql);
 234    }
 235
 236}
 237
 238//*********************************************************
 239function addNewUser($newUser, $pass1, $userType)
 240{
 241    global $cfg, $db;
 242
 243    $create_time = time();
 244
 245    $record = array(
 246                    'user_id'=>strtolower($newUser),
 247                    'password'=>md5($pass1),
 248                    'hits'=>0,
 249                    'last_visit'=>$create_time,
 250                    'time_created'=>$create_time,
 251                    'user_level'=>$userType,
 252                    'hide_offline'=>"0",
 253                    'theme'=>$cfg["default_theme"],
 254                    'language_file'=>$cfg["default_language"]
 255                    );
 256
 257    $sTable = 'tf_users';
 258    $sql = $db->GetInsertSql($sTable, $record);
 259    $result = $db->Execute($sql);
 260    showError($db,$sql);
 261}
 262
 263//*********************************************************
 264function PruneDB()
 265{
 266    global $cfg, $db;
 267
 268    // Prune LOG
 269    $testTime = time()-($cfg['days_to_keep'] * 86400); // 86400 is one day in seconds
 270    $sql = "delete from tf_log where time < " . $db->qstr($testTime);
 271    $result = $db->Execute($sql);
 272    showError($db,$sql);
 273    unset($result);
 274
 275    $testTime = time()-($cfg['minutes_to_keep'] * 60);
 276    $sql = "delete from tf_log where time < " . $db->qstr($testTime). " and action=".$db->qstr($cfg["constants"]["hit"]);
 277    $result = $db->Execute($sql);
 278    showError($db,$sql);
 279    unset($result);
 280}
 281
 282//*********************************************************
 283function IsOnline($user)
 284{
 285    global $cfg, $db;
 286
 287    $online = false;
 288
 289    $sql = "SELECT count(*) FROM tf_log WHERE user_id=" . $db->qstr($user)." AND action=".$db->qstr($cfg["constants"]["hit"]);
 290
 291    $number_hits = $db->GetOne($sql);
 292    showError($db,$sql);
 293
 294    if ($number_hits > 0)
 295    {
 296        $online = true;
 297    }
 298
 299    return $online;
 300}
 301
 302//*********************************************************
 303function IsUser($user)
 304{
 305    global $cfg, $db;
 306
 307    $isUser = false;
 308
 309    $sql = "SELECT count(*) FROM tf_users WHERE user_id=".$db->qstr($user);
 310    $number_users = $db->GetOne($sql);
 311
 312    if ($number_users > 0)
 313    {
 314        $isUser = true;
 315    }
 316
 317    return $isUser;
 318}
 319
 320//*********************************************************
 321function getOwner($file)
 322{
 323    global $cfg, $db;
 324
 325    $rtnValue = "n/a";
 326
 327    // Check log to see what user has a history with this file
 328    $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";
 329    $user_id = $db->GetOne($sql);
 330
 331    if($user_id != "")
 332    {
 333        $rtnValue = $user_id;
 334    }
 335    else
 336    {
 337        // try and get the owner from the stat file
 338        $rtnValue = resetOwner($file);
 339    }
 340
 341    return $rtnValue;
 342}
 343
 344//*********************************************************
 345function resetOwner($file)
 346{
 347    global $cfg, $db;
 348    include_once("AliasFile.php");
 349
 350    // log entry has expired so we must renew it
 351    $rtnValue = "";
 352
 353    $alias = getAliasName($file).".stat";
 354
 355    if(file_exists($cfg["torrent_file_path"].$alias))
 356    {
 357        $af = new AliasFile($cfg["torrent_file_path"].$alias);
 358
 359        if (IsUser($af->torrentowner))
 360        {
 361            // We have an owner!
 362            $rtnValue = $af->torrentowner;
 363        }
 364        else
 365        {
 366            // no owner found, so the super admin will now own it
 367            $rtnValue = GetSuperAdmin();
 368        }
 369
 370        $host_resolved = $cfg['ip'];
 371        $create_time = time();
 372
 373        $rec = array(
 374                        'user_id' => $rtnValue,
 375                        'file' => $file,
 376                        'action' => $cfg["constants"]["reset_owner"],
 377                        'ip' => $cfg['ip'],
 378                        'ip_resolved' => $host_resolved,
 379                        'user_agent' => $_SERVER['HTTP_USER_AGENT'],
 380                        'time' => $create_time
 381                    );
 382
 383        $sTable = 'tf_log';
 384        $sql = $db->GetInsertSql($sTable, $rec);
 385
 386        // add record to the log
 387        $result = $db->Execute($sql);
 388        showError($db,$sql);
 389    }
 390
 391    return $rtnValue;
 392}
 393
 394//*********************************************************
 395function getCookie($cid)
 396{
 397    global $cfg, $db;
 398
 399    $rtnValue = "";
 400
 401    $sql = "SELECT host, data FROM tf_cookies WHERE cid=".$cid;
 402    $rtnValue = $db->GetAll($sql);
 403
 404    return $rtnValue[0];
 405}
 406
 407//*********************************************************
 408function getAllCookies($uid)
 409{
 410    global $cfg, $db;
 411
 412    $rtnValue = "";
 413
 414    $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";
 415    $rtnValue = $db->GetAll($sql);
 416
 417    return $rtnValue;
 418}
 419
 420// ***************************************************************************
 421// Delete Cookie Host Information
 422function deleteCookieInfo($cid)
 423{
 424    global $db;
 425    $sql = "delete from tf_cookies where cid=".$cid;
 426    $result = $db->Execute($sql);
 427    showError($db,$sql);
 428}
 429
 430// ***************************************************************************
 431// addCookieInfo - Add New Cookie Host Information
 432function addCookieInfo( $newCookie )
 433{
 434    global $db, $cfg;
 435    // Get uid of user
 436    $sql = "SELECT uid FROM tf_users WHERE user_id = '" . $cfg["user"] . "'";
 437    $uid = $db->GetOne( $sql );
 438    $sql = "INSERT INTO tf_cookies ( uid, host, data ) VALUES ( " . $uid . ", " . $db->qstr($newCookie["host"]) . ", " . $db->qstr($newCookie["data"]) . " )";
 439    $db->Execute( $sql );
 440    showError( $db, $sql );
 441}
 442
 443// ***************************************************************************
 444// modCookieInfo - Modify Cookie Host Information
 445function modCookieInfo($cid, $newCookie)
 446{
 447    global $db;
 448    $sql = "UPDATE tf_cookies SET host='" . $newCookie["host"] . "', data='" . $newCookie["data"] . "' WHERE cid=" . $cid;
 449    $db->Execute($sql);
 450    showError($db,$sql);
 451}
 452
 453//*********************************************************
 454function getSite($lid)
 455{
 456    global $cfg, $db;
 457
 458    $rtnValue = "";
 459
 460    $sql = "SELECT sitename FROM tf_links WHERE lid=".$lid;
 461    $rtnValue = $db->GetOne($sql);
 462
 463    return $rtnValue;
 464}
 465
 466//*********************************************************
 467function getLink($lid)
 468{
 469    global $cfg, $db;
 470
 471    $rtnValue = "";
 472
 473    $sql = "SELECT url FROM tf_links WHERE lid=".$lid;
 474    $rtnValue = $db->GetOne($sql);
 475
 476    return $rtnValue;
 477}
 478
 479//*********************************************************
 480function getRSS($rid)
 481{
 482    global $cfg, $db;
 483
 484    $rtnValue = "";
 485
 486    $sql = "SELECT url FROM tf_rss WHERE rid=".$rid;
 487    $rtnValue = $db->GetOne($sql);
 488
 489    return $rtnValue;
 490}
 491
 492//*********************************************************
 493function IsOwner($user, $owner)
 494{
 495    $rtnValue = false;
 496
 497    if (strtolower($user) == strtolower($owner))
 498    {
 499        $rtnValue = true;
 500    }
 501
 502    return $rtnValue;
 503}
 504
 505//*********************************************************
 506function GetActivityCount($user="")
 507{
 508    global $cfg, $db;
 509
 510    $count = 0;
 511    $for_user = "";
 512
 513    if ($user != "")
 514    {
 515        $for_user = "user_id=".$db->qstr($user)." AND ";
 516    }
 517
 518    $sql = "SELECT count(*) FROM tf_log WHERE ".$for_user."(action=".$db->qstr($cfg["constants"]["file_upload"])." OR action=".$db->qstr($cfg["constants"]["url_upload"]).")";
 519    $count = $db->GetOne($sql);
 520
 521    return $count;
 522}
 523
 524//*********************************************************
 525function GetSpeedValue($inValue)
 526{
 527    $rtnValue = 0;
 528    $arTemp = split(" ", trim($inValue));
 529
 530    if (is_numeric($arTemp[0]))
 531    {
 532        $rtnValue = $arTemp[0];
 533    }
 534    return $rtnValue;
 535}
 536
 537// ***************************************************************************
 538// Is User Admin
 539// user is Admin if level is 1 or higher
 540function IsAdmin($user="")
 541{
 542    global $cfg, $db;
 543
 544    $isAdmin = false;
 545
 546    if($user == "")
 547    {
 548        $user = $cfg["user"];
 549    }
 550
 551    $sql = "SELECT user_level FROM tf_users WHERE user_id=".$db->qstr($user);
 552    $user_level = $db->GetOne($sql);
 553
 554    if ($user_level >= 1)
 555    {
 556        $isAdmin = true;
 557    }
 558    return $isAdmin;
 559}
 560
 561// ***************************************************************************
 562// Is User SUPER Admin
 563// user is Super Admin if level is higher than 1
 564function IsSuperAdmin($user="")
 565{
 566    global $cfg, $db;
 567
 568    $isAdmin = false;
 569
 570    if($user == "")
 571    {
 572        $user = $cfg["user"];
 573    }
 574
 575    $sql = "SELECT user_level FROM tf_users WHERE user_id=".$db->qstr($user);
 576    $user_level = $db->GetOne($sql);
 577
 578    if ($user_level > 1)
 579    {
 580        $isAdmin = true;
 581    }
 582    return $isAdmin;
 583}
 584
 585
 586// ***************************************************************************
 587// Returns true if user has message from admin with force_read
 588function IsForceReadMsg()
 589{
 590    global $cfg, $db;
 591    $rtnValue = false;
 592
 593    $sql = "SELECT count(*) FROM tf_messages WHERE to_user=".$db->qstr($cfg["user"])." AND force_read=1";
 594    $count = $db->GetOne($sql);
 595    showError($db,$sql);
 596
 597    if ($count >= 1)
 598    {
 599        $rtnValue = true;
 600    }
 601    return $rtnValue;
 602}
 603
 604// ***************************************************************************
 605// Get Message data in an array
 606function GetMessage($mid)
 607{
 608    global $cfg, $db;
 609
 610    $rtnValue = array();
 611
 612    if (is_numeric($mid))
 613    {
 614        $sql = "select from_user, message, ip, time, isnew, force_read from tf_messages where mid=".$mid." and to_user=".$db->qstr($cfg['user']);
 615        $rtnValue = $db->GetRow($sql);
 616        showError($db,$sql);
 617    }
 618
 619    return $rtnValue;
 620}
 621
 622// ***************************************************************************
 623// Get Themes data in an array
 624function GetThemes()
 625{
 626    $arThemes = array();
 627    $dir = "themes/";
 628
 629    $handle = opendir($dir);
 630    while($entry = readdir($handle))
 631    {
 632        if (is_dir($dir.$entry) && ($entry != "." && $entry != ".."))
 633        {
 634            array_push($arThemes, $entry);
 635        }
 636    }
 637    closedir($handle);
 638
 639    sort($arThemes);
 640
 641    return $arThemes;
 642}
 643
 644// ***************************************************************************
 645// Get Languages in an array
 646function GetLanguages()
 647{
 648    $arLanguages = array();
 649    $dir = "language/";
 650
 651    $handle = opendir($dir);
 652    while($entry = readdir($handle))
 653    {
 654        if (is_file($dir.$entry) && (strcmp(strtolower(substr($entry, strlen($entry)-4, 4)), ".php") == 0))
 655        {
 656            array_push($arLanguages, $entry);
 657        }
 658    }
 659    closedir($handle);
 660
 661    sort($arLanguages);
 662
 663    return $arLanguages;
 664}
 665
 666// ***************************************************************************
 667// Get Language name from file name
 668function GetLanguageFromFile($inFile)
 669{
 670    $rtnValue = "";
 671
 672    $rtnValue = str_replace("lang-", "", $inFile);
 673    $rtnValue = str_replace(".php", "", $rtnValue);
 674
 675    return $rtnValue;
 676}
 677
 678// ***************************************************************************
 679// Delete Message
 680function DeleteMessage($mid)
 681{
 682    global $cfg, $db;
 683
 684    $sql = "delete from tf_messages where mid=".$mid." and to_user=".$db->qstr($cfg['user']);
 685    $result = $db->Execute($sql);
 686    showError($db,$sql);
 687}
 688
 689
 690// ***************************************************************************
 691// Delete Link
 692function deleteOldLink($lid)
 693{
 694    global $db;
 695    // Get Current sort order index of link with this link id:
 696    $idx = getLinkSortOrder($lid);
 697
 698    // Fetch all link ids and their sort orders where the sort order is greater
 699    // than the one we're removing - we need to shuffle each sort order down
 700    // one:
 701    $sql = "SELECT sort_order, lid FROM tf_links ";
 702    $sql .= "WHERE sort_order > ".$idx." ORDER BY sort_order ASC";
 703    $result = $db->Execute($sql);
 704    showError($db,$sql);
 705    $arLinks = $result->GetAssoc();
 706
 707    // Decrement the sort order of each link:
 708    foreach($arLinks as $sid => $this_lid)
 709    {
 710        $sql="UPDATE tf_links SET sort_order=sort_order-1 WHERE lid=".$this_lid;
 711        $db->Execute($sql);
 712        showError($db,$sql);
 713    }
 714
 715    // Finally delete the link:
 716    $sql = "DELETE FROM tf_links WHERE lid=".$lid;
 717    $result = $db->Execute($sql);
 718    showError($db,$sql);
 719}
 720
 721// ***************************************************************************
 722// Delete RSS
 723function deleteOldRSS($rid)
 724{
 725    global $db;
 726    $sql = "delete from tf_rss where rid=".$rid;
 727    $result = $db->Execute($sql);
 728    showError($db,$sql);
 729}
 730
 731// ***************************************************************************
 732// Delete User
 733function DeleteThisUser($user_id)
 734{
 735    global $db;
 736
 737    $sql = "SELECT uid FROM tf_users WHERE user_id = ".$db->qstr($user_id);
 738    $uid = $db->GetOne( $sql );
 739    showError($db,$sql);
 740
 741    // delete any cookies this user may have had
 742    //$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);
 743    $sql = "DELETE FROM tf_cookies WHERE uid=".$uid;
 744    $result = $db->Execute($sql);
 745    showError($db,$sql);
 746
 747    // Now cleanup any message this person may have had
 748    $sql = "DELETE FROM tf_messages WHERE to_user=".$db->qstr($user_id);
 749    $result = $db->Execute($sql);
 750    showError($db,$sql);
 751
 752    // now delete the user from the table
 753    $sql = "DELETE FROM tf_users WHERE user_id=".$db->qstr($user_id);
 754    $result = $db->Execute($sql);
 755    showError($db,$sql);
 756}
 757
 758// ***************************************************************************
 759// Update User -- used by admin
 760function updateThisUser($user_id, $org_user_id, $pass1, $userType, $hideOffline)
 761{
 762    global $db;
 763
 764    if ($hideOffline == "")
 765    {
 766        $hideOffline = 0;
 767    }
 768
 769    $sql = 'select * from tf_users where user_id = '.$db->qstr($org_user_id);
 770    $rs = $db->Execute($sql);
 771    showError($db,$sql);
 772
 773    $rec = array();
 774    $rec['user_id'] = $user_id;
 775    $rec['user_level'] = $userType;
 776    $rec['hide_offline'] = $hideOffline;
 777
 778    if ($pass1 != "")
 779    {
 780        $rec['password'] = md5($pass1);
 781    }
 782
 783    $sql = $db->GetUpdateSQL($rs, $rec);
 784
 785    if ($sql != "")
 786    {
 787        $result = $db->Execute($sql);
 788        showError($db,$sql);
 789    }
 790
 791    // if the original user id and the new id do not match, we need to update messages and log
 792    if ($user_id != $org_user_id)
 793    {
 794        $sql = "UPDATE tf_messages SET to_user=".$db->qstr($user_id)." WHERE to_user=".$db->qstr($org_user_id);
 795
 796        $result = $db->Execute($sql);
 797        showError($db,$sql);
 798
 799        $sql = "UPDATE tf_messages SET from_user=".$db->qstr($user_id)." WHERE from_user=".$db->qstr($org_user_id);
 800        $result = $db->Execute($sql);
 801        showError($db,$sql);
 802
 803        $sql = "UPDATE tf_log SET user_id=".$db->qstr($user_id)." WHERE user_id=".$db->qstr($org_user_id);
 804        $result = $db->Execute($sql);
 805        showError($db,$sql);
 806    }
 807}
 808
 809// ***************************************************************************
 810// changeUserLevel Changes the Users Level
 811function changeUserLevel($user_id, $level)
 812{
 813    global $db;
 814
 815    $sql='select * from tf_users where user_id = '.$db->qstr($user_id);
 816    $rs = $db->Execute($sql);
 817    showError($db,$sql);
 818
 819    $rec = array('user_level'=>$level);
 820    $sql = $db->GetUpdateSQL($rs, $rec);
 821    $result = $db->Execute($sql);
 822    showError($db,$sql);
 823}
 824
 825// ***************************************************************************
 826// Mark Message as Read
 827function MarkMessageRead($mid)
 828{
 829    global $cfg, $db;
 830
 831    $sql = 'select * from tf_messages where mid = '.$mid;
 832    $rs = $db->Execute($sql);
 833    showError($db,$sql);
 834
 835    $rec = array('IsNew'=>0,
 836             'force_read'=>0);
 837
 838    $sql = $db->GetUpdateSQL($rs, $rec);
 839    $db->Execute($sql);
 840    showError($db,$sql);
 841}
 842
 843//**************************************************************************
 844// alterLink()
 845// This function updates the database and alters the selected links values
 846function alterLink($lid,$newLink,$newSite)
 847{
 848    global $cfg, $db;
 849
 850    $sql = "UPDATE tf_links SET url='".$newLink."',`sitename`='".$newSite."' WHERE `lid`=".$lid;
 851    $db->Execute($sql);
 852    showError($db,$sql);
 853}
 854
 855// ***************************************************************************
 856// addNewLink - Add New Link
 857function addNewLink($newLink,$newSite)
 858{
 859    global $db;
 860    // Link sort order index:
 861    $idx = -1;
 862
 863    // Get current highest link index:
 864    $sql = "SELECT sort_order FROM tf_links ORDER BY sort_order DESC";
 865    $result = $db->SelectLimit($sql, 1);
 866    showError($db, $sql);
 867
 868    if($result->fields === false)
 869    {
 870        // No links currently in db:
 871        $idx = 0;
 872    }
 873    else
 874    {
 875        $idx = $result->fields["sort_order"]+1;
 876    }
 877
 878    $rec = array
 879    (
 880        'url'=>$newLink,
 881        'sitename'=>$newSite,
 882        'sort_order'=>$idx
 883    );
 884    $sTable = 'tf_links';
 885    $sql = $db->GetInsertSql($sTable, $rec);
 886    $db->Execute($sql);
 887    showError($db,$sql);
 888}
 889
 890
 891// ***************************************************************************
 892// addNewRSS - Add New RSS Link
 893function addNewRSS($newRSS)
 894{
 895    global $db;
 896    $rec = array('url'=>$newRSS);
 897    $sTable = 'tf_rss';
 898    $sql = $db->GetInsertSql($sTable, $rec);
 899    $db->Execute($sql);
 900    showError($db,$sql);
 901}
 902
 903// ***************************************************************************
 904// UpdateUserProfile
 905function UpdateUserProfile($user_id, $pass1, $hideOffline, $theme, $language)
 906{
 907    global $cfg, $db;
 908
 909    if (empty($hideOffline) || $hideOffline == "" || !isset($hideOffline))
 910    {
 911        $hideOffline = "0";
 912    }
 913
 914    // update values
 915    $rec = array();
 916
 917    if ($pass1 != "")
 918    {
 919        $rec['password'] = md5($pass1);
 920        AuditAction($cfg["constants"]["update"], _PASSWORD);
 921    }
 922
 923    $sql = 'select * from tf_users where user_id = '.$db->qstr($user_id);
 924    $rs = $db->Execute($sql);
 925    showError($db,$sql);
 926
 927    $rec['hide_offline'] = $hideOffline;
 928    $rec['theme'] = $theme;
 929    $rec['language_file'] = $language;
 930
 931    $sql = $db->GetUpdateSQL($rs, $rec);
 932
 933    $result = $db->Execute($sql);
 934    showError($db,$sql);
 935}
 936
 937
 938// ***************************************************************************
 939// Get Users in an array
 940function GetUsers()
 941{
 942    global $cfg, $db;
 943
 944    $user_array = array();
 945
 946    $sql = "select user_id from tf_users order by user_id";
 947    $user_array = $db->GetCol($sql);
 948    showError($db,$sql);
 949    return $user_array;
 950}
 951
 952// ***************************************************************************
 953// Get Super Admin User ID as a String
 954function GetSuperAdmin()
 955{
 956    global $cfg, $db;
 957
 958    $rtnValue = "";
 959
 960    $sql = "select user_id from tf_users WHERE user_level=2";
 961    $rtnValue = $db->GetOne($sql);
 962    showError($db,$sql);
 963    return $rtnValue;
 964}
 965
 966// ***************************************************************************
 967// Get Links in an array
 968function GetLinks()
 969{
 970    global $cfg, $db;
 971
 972    $link_array = array();
 973
 974    $link_array = $db->GetAssoc("SELECT lid, url, sitename, sort_order FROM tf_links ORDER BY sort_order");
 975    return $link_array;
 976}
 977
 978// ***************************************************************************
 979// Get RSS Links in an array
 980function GetRSSLinks()
 981{
 982    global $cfg, $db;
 983
 984    $link_array = array();
 985
 986    $sql = "SELECT rid, url FROM tf_rss ORDER BY rid";
 987    $link_array = $db->GetAssoc($sql);
 988    showError($db,$sql);
 989
 990    return $link_array;
 991}
 992
 993// ***************************************************************************
 994// Build Search Engine Drop Down List
 995function buildSearchEngineDDL($selectedEngine = 'PirateBay', $autoSubmit = false)
 996{
 997    $output = "<select name=\"searchEngine\" ";
 998    if ($autoSubmit)
 999    {
1000         $output .= "onchange=\"this.form.submit();\" ";
1001    }
1002    $output .= " STYLE=\"width: 125px\">";
1003
1004    $handle = opendir("./searchEngines");
1005    while($entry = readdir($handle))
1006    {
1007        $entrys[] = $entry;
1008    }
1009    natcasesort($entrys);
1010
1011    foreach($entrys as $entry)
1012    {
1013        if ($entry != "." && $entry != ".." && substr($entry, 0, 1) != ".")
1014            if(strpos($entry,"Engine.php"))
1015            {
1016                $tmpEngine = str_replace("Engine",'',substr($entry,0,strpos($entry,".")));
1017                $output .= "<option";
1018                if ($selectedEngine == $tmpEngine)
1019                {
1020                    $output .= " selected";
1021                }
1022                $output .= ">".str_replace("Engine",'',substr($entry,0,strpos($entry,".")))."</option>";
1023            }
1024    }
1025    $output .= "</select>\n";
1026
1027    return $output;
1028}
1029
1030// ***************************************************************************
1031// Build Search Engine Links
1032function buildSearchEngineLinks($selectedEngine = 'PirateBay')
1033{
1034    global $cfg;
1035
1036    $settingsNeedsSaving = false;
1037    $settings['searchEngineLinks'] = Array();
1038
1039    $output = '';
1040
1041    if( (!array_key_exists('searchEngineLinks', $cfg)) || (!is_array($cfg['searchEngineLinks'])))
1042    {
1043        saveSettings($settings);
1044    }
1045
1046    $handle = opendir("./searchEngines");
1047    while($entry = readdir($handle))
1048    {
1049        $entrys[] = $entry;
1050    }
1051    natcasesort($entrys);
1052
1053    foreach($entrys as $entry)
1054    {
1055        if ($entry != "." && $entry != ".." && substr($entry, 0, 1) != ".")
1056            if(strpos($entry,"Engine.php"))
1057            {
1058                $tmpEngine = str_replace("Engine",'',substr($entry,0,strpos($entry,".")));
1059
1060                if(array_key_exists($tmpEngine,$cfg['searchEngineLinks']))
1061                {
1062                    $hreflink = $cfg['searchEngineLinks'][$tmpEngine];
1063                    $settings['searchEngineLinks'][$tmpEngine] = $hreflink;
1064                }
1065                else
1066                {
1067                    $hreflink = getEngineLink($tmpEngine);
1068                    $settings['searchEngineLinks'][$tmpEngine] = $hreflink;
1069                    $settingsNeedsSaving = true;
1070                }
1071
1072                if (strlen($hreflink) > 0)
1073                {
1074                    $output .=  "<a href=\"http://".$hreflink."/\" target=\"_blank\">";
1075                    if ($selectedEngine == $tmpEngine)
1076                    {
1077                        $output .= "<b>".$hreflink."</b>";
1078                    }
1079                    else
1080                    {
1081                        $output .= $hreflink;
1082                    }
1083                    $output .= "</a><br>\n";
1084                }
1085            }
1086    }
1087
1088    if ( count($settings['searchEngineLinks'],COUNT_RECURSIVE) <> count($cfg['searchEngineLinks'],COUNT_RECURSIVE))
1089    {
1090        $settingsNeedsSaving = true;
1091    }
1092
1093    if ($settingsNeedsSaving)
1094    {
1095        natcasesort($settings['searchEngineLinks']);
1096
1097        saveSettings($settings);
1098    }
1099
1100    return $output;
1101}
1102function getEngineLink($searchEngine)
1103{
1104    $tmpLink = '';
1105    $engineFile = 'searchEngines/'.$searchEngine.'Engine.php';
1106    if (is_file($engineFile))
1107    {
1108        $fp = @fopen($engineFile,'r');
1109        if ($fp)
1110        {
1111            $tmp = fread($fp, filesize($engineFile));
1112            @fclose( $fp );
1113
1114            $tmp = substr($tmp,strpos($tmp,'$this->mainURL'),100);
1115            $tmp = substr($tmp,strpos($tmp,"=")+1);
1116            $tmp = substr($tmp,0,strpos($tmp,";"));
1117            $tmpLink = trim(str_replace(array("'","\""),"",$tmp));
1118        }
1119    }
1120    return $tmpLink;
1121}
1122
1123// ***************************************************************************
1124// ***************************************************************************
1125// Display Functions
1126
1127
1128// ***************************************************************************
1129// ***************************************************************************
1130// Display the header portion of admin views
1131function DisplayHead($subTopic, $showButtons=true, $refresh="", $percentdone="")
1132{
1133    global $cfg;
1134    ?>
1135
1136    <html>
1137    <HEAD>
1138        <TITLE><?php echo $percentdone.$cfg["pagetitle"] ?></TITLE>
1139        <link rel="icon" href="images/favicon.ico" type="image/x-icon" />
1140        <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
1141        <LINK REL="StyleSheet" HREF="themes/<?php echo $cfg["theme"] ?>/style.css" TYPE="text/css">
1142        <META HTTP-EQUIV="Pragma" CONTENT="no-cache" charset="<?php echo _CHARSET ?>">
1143
1144    <?php
1145    if ($refresh != "")
1146    {
1147        echo "<meta http-equiv=\"REFRESH\" content=\"".$refresh."\">";
1148    }
1149    ?>
1150    </HEAD>
1151
1152    <body topmargin="8" leftmargin="5" bgcolor="<?php echo $cfg["main_bgcolor"] ?>">
1153
1154    <div align="center">
1155    <table border="0" cellpadding="0" cellspacing="0">
1156    <tr>
1157        <td>
1158
1159    <table border="1" bordercolor="<?php echo $cfg["table_border_dk"] ?>" cellpadding="4" cellspacing="0">
1160    <tr>
1161        <td bgcolor="<?php echo $cfg["main_bgcolor"] ?>" background="themes/<?php echo $cfg["theme"] ?>/images/bar.gif">
1162        <?php DisplayTitleBar($cfg["pagetitle"]." - ".$subTopic, $showButtons); ?>
1163        </td>
1164    </tr>
1165    <tr>
1166    <td bgcolor="<?php echo $cfg["table_header_bg"] ?>">
1167    <div align="center">
1168
1169    <table width="100%" bgcolor="<?php echo $cfg["body_data_bg"] ?>">
1170     <tr><td>
1171<?php
1172}
1173
1174
1175// ***************************************************************************
1176// ***************************************************************************
1177// Display the footer portion
1178function DisplayFoot($showReturn=true)
1179{
1180    global $cfg;
1181    ?>
1182     </td></tr>
1183    </table>
1184<?php
1185    if ($showReturn)
1186    {
1187        echo "[<a href=\"index.php\">"._RETURNTOTORRENTS."</a>]";
1188        echo "</form>";
1189    }
1190?>
1191    </div>
1192    </td>
1193    </tr>
1194    </table>
1195<?php
1196    echo DisplayTorrentFluxLink();
1197?>
1198
1199        </td>
1200    </tr>
1201    </table>
1202    </div>
1203
1204   </body>
1205  </html>
1206
1207    <?php
1208}
1209
1210
1211// ***************************************************************************
1212// ***************************************************************************
1213// Dipslay TF Link and Version
1214function DisplayTorrentFluxLink()
1215{
1216    global $cfg;
1217
1218    echo "<div align=\"right\">";
1219    echo "<a href=\"http://www.torrentflux.com\" target=\"_blank\"><font class=\"tinywhite\">TorrentFlux ".$cfg["version"]."</font></a>&nbsp;&nbsp;";
1220    echo "</div>";
1221}
1222
1223
1224// ***************************************************************************
1225// ***************************************************************************
1226// Dipslay Title Bar
1227// 2004-12-09 PFM: now using adodb.
1228function DisplayTitleBar($pageTitleText, $showButtons=true)
1229{
1230    global $cfg, $db;
1231    ?>
1232        <table width="100%" cellpadding="0" cellspacing="0" border="0">
1233        <tr>
1234            <td align="left"><font class="title"><?php echo $pageTitleText ?></font></td>
1235
1236    <?php
1237    if ($showButtons)
1238    {
1239        echo "<td align=right>";
1240        // Top Buttons
1241        echo "&nbsp;&nbsp;";
1242
1243        echo "<a href=\"index.php\"><img src=\"themes/".$cfg["theme"]."/images/home.gif\" width=49 height=13 title=\""._TORRENTS."\" border=0></a>&nbsp;";
1244        echo "<a href=\"dir.php\"><img src=\"themes/".$cfg["theme"]."/images/directory.gif\" width=49 height=13 title=\""._DIRECTORYLIST."\" border=0></a>&nbsp;";
1245        echo "<a href=\"history.php\"><img src=\"themes/".$cfg["theme"]."/images/history.gif\" width=49 height=13 title=\""._UPLOADHISTORY."\" border=0></a>&nbsp;";
1246        echo "<a href=\"profile.php\"><img src=\"themes/".$cfg["theme"]."/images/profile.gif\" width=49 height=13 title=\""._MYPROFILE."\" border=0></a>&nbsp;";
1247
1248        // Does the user have messages?
1249        $sql = "select count(*) from tf_messages where to_user='".$cfg['user']."' and IsNew=1";
1250
1251        $number_messages = $db->GetOne($sql);
1252        showError($db,$sql);
1253        if ($number_messages > 0)
1254        {
1255            // We have messages
1256            $message_image = "themes/".$cfg["theme"]."/images/messages_on.gif";
1257        }
1258        else
1259        {
1260            // No messages
1261            $message_image = "themes/".$cfg["theme"]."/images/messages_off.gif";
1262        }
1263
1264        echo "<a href=\"readmsg.php\"><img src=\"".$message_image."\" width=49 height=13 title=\""._MESSAGES."\" border=0></a>";
1265
1266        if(IsAdmin())
1267        {
1268            echo "&nbsp;<a href=\"admin.php\"><img src=\"themes/".$cfg["theme"]."/images/admin.gif\" width=49 height=13 title=\""._ADMINISTRATION."\" border=0></a>";
1269        }
1270
1271        echo "&nbsp;<a href=\"logout.php\"><img src=\"images/logout.gif\" width=13 height=12 title=\"Logout\" border=0></a>";
1272    }
1273?>
1274            </td>
1275        </tr>
1276        </table>
1277<?php
1278}
1279
1280
1281// ***************************************************************************
1282// ***************************************************************************
1283// Dipslay dropdown list to send message to a user
1284function DisplayMessageList()
1285{
1286    global $cfg;
1287    $users = GetUsers();
1288
1289    echo '<div align="center">'.
1290    '<table border="0" cellpadding="0" cellspacing="0">'.
1291    '<form name="formMessage" action="message.php" method="post">'.
1292    '<tr><td>' . _SENDMESSAGETO ;
1293
1294    echo '<select name="to_user">';
1295        for($inx = 0; $inx < sizeof($users); $inx++)
1296        {
1297        echo '<option>'.htmlentities($users[$inx], ENT_QUOTES).'</option>';
1298        }
1299    echo '</select>';
1300    echo '<input type="Submit" value="' . _COMPOSE .'">';
1301    echo '</td></tr></form></table></div>';
1302}
1303
1304// ***************************************************************************
1305// ***************************************************************************
1306// Removes HTML from Messages
1307function check_html ($str, $strip="")
1308{
1309    /* The core of this code has been lifted from phpslash */
1310    /* which is licenced under the GPL. */
1311    if ($strip == "nohtml")
1312    {
1313        $AllowableHTML=array('');
1314    }
1315    $str = stripslashes($str);
1316    $str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",'<\\1>', $str);
1317            // Delete all spaces from html tags .
1318    $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>",'<a href="\\1">', $str);
1319            // Delete all attribs from Anchor, except an href, double quoted.
1320    $str = eregi_replace("<[[:space:]]* img[[:space:]]*([^>]*)[[:space:]]*>", '', $str);
1321        // Delete all img tags
1322    $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?javascript[[:punct:]]*\"?[^>]*>", '', $str);
1323        // Delete javascript code from a href tags -- Zhen-Xjell @ http://nukecops.com
1324    $tmp = "";
1325
1326    while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg))
1327    {
1328        $i = strpos($str,$reg[0]);
1329        $l = strlen($reg[0]);
1330        if ($reg[1][0] == "/")
1331        {
1332            $tag = strtolower(substr($reg[1],1));
1333        }
1334        else
1335        {
1336            $tag = strtolower($reg[1]);
1337        }
1338        if ($a = $AllowableHTML[$tag])
1339        {
1340            if ($reg[1][0] == "/")
1341            {
1342                $tag = "</$tag>";
1343            }
1344            elseif (($a == 1) || ($reg[2] == ""))
1345            {
1346                $tag = "<$tag>";
1347            }
1348            else
1349            {
1350              # Place here the double quote fix function.
1351              $attrb_list=delQuotes($reg[2]);
1352              // A VER
1353              $attrb_list = ereg_replace("&","&amp;",$attrb_list);
1354              $tag = "<$tag" . $attrb_list . ">";
1355            } # Attribs in tag allowed
1356        }
1357        else
1358        {
1359            $tag = "";
1360        }
1361        $tmp .= substr($str,0,$i) . $tag;
1362        $str = substr($str,$i+$l);
1363    }
1364    $str = $tmp . $str;
1365    return $str;
1366}
1367
1368
1369// ***************************************************************************
1370// ***************************************************************************
1371// Checks for the location of the torrents
1372// If it does not exist, then it creates it.
1373function checkTorrentPath()
1374{
1375    global $cfg;
1376    // is there a stat and torrent dir?
1377    if (!@is_dir($cfg["torrent_file_path"]) && is_writable($cfg["path"]))
1378    {
1379        //Then create it
1380        @mkdir($cfg["torrent_file_path"], 0777);
1381    }
1382}
1383
1384// ***************************************************************************
1385// ***************************************************************************
1386// Returns the drive space used as a percentage i.e 85 or 95
1387function getDriveSpace($drive)
1388{
1389    $percent = 0;
1390
1391    if (is_dir($drive))
1392    {
1393        $dt = disk_total_space($drive);
1394        $df = disk_free_space($drive);
1395
1396        $percent = round((($dt - $df)/$dt) * 100);
1397    }
1398    return $percent;
1399}
1400
1401// ***************************************************************************
1402// ***************************************************************************
1403// Display the Drive Space Graphical Bar
1404function displayDriveSpaceBar($drivespace)
1405{
1406    global $cfg;
1407    $freeSpace = "";
1408
1409    if ($drivespace > 20)
1410    {
1411        $freeSpace = " (".formatFreeSpace($cfg["free_space"])." Free)";
1412    }
1413?>
1414    <table width="100%" border="0" cellpadding="0" cellspacing="0">
1415    <tr nowrap>
1416        <td width="2%"><div class="tiny"><?php echo _STORAGE ?>:</div></td>
1417        <td width="80%">
1418            <table width="100%" border="0" cellpadding="0" cellspacing="0">
1419            <tr>
1420                <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>
1421                <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>
1422            </tr>
1423            </table>
1424        </td>
1425    </tr>
1426    </table>
1427<?php
1428}
1429
1430// ***************************************************************************
1431// ***************************************************************************
1432// Convert free space to GB or MB depending on size
1433function formatFreeSpace($freeSpace)
1434{
1435    $rtnValue = "";
1436    if ($freeSpace > 1024)
1437    {
1438        $rtnValue = number_format($freeSpace/1024, 2)." GB";
1439    }
1440    else
1441    {
1442        $rtnValue = number_format($freeSpace, 2)." MB";
1443    }
1444
1445    return $rtnValue;
1446}
1447
1448//**************************************************************************
1449// getFileFilter()
1450// Returns a string used as a file filter.
1451// Takes in an array of file types.
1452function getFileFilter($inArray)
1453{
1454    $filter = "(\.".strtolower($inArray[0]).")|"; // used to hold the file type filter
1455    $filter .= "(\.".strtoupper($inArray[0]).")";
1456    // Build the file filter
1457    for($inx = 1; $inx < sizeof($inArray); $inx++)
1458    {
1459        $filter .= "|(\.".strtolower($inArray[$inx]).")";
1460        $filter .= "|(\.".strtoupper($inArray[$inx]).")";
1461    }
1462    $filter .= "$";
1463    return $filter;
1464}
1465
1466
1467//**************************************************************************
1468// getAliasName()
1469// Create Alias name for Text file and Screen Alias
1470function getAliasName($inName)
1471{
1472    $replaceItems = array(" ", ".", "-", "[", "]", "(", ")", "#", "&", "@");
1473    $alias = str_replace($replaceItems, "_", $inName);
1474    $alias = strtolower($alias);
1475    $alias = str_replace("_torrent", "", $alias);
1476
1477    return $alias;
1478}
1479
1480
1481//**************************************************************************
1482// cleanFileName()
1483// Remove bad characters that cause problems
1484function cleanFileName($inName)
1485{
1486    $replaceItems = array("?", "&", "'", "\"", "+", "@");
1487    $cleanName = str_replace($replaceItems, "", $inName);
1488    $cleanName = ltrim($cleanName, "-");
1489    $cleanName = preg_replace("/[^0-9a-z.]+/i",'_', $cleanName);
1490    return $cleanName;
1491}
1492
1493//**************************************************************************
1494// usingTornado()
1495// returns true if client is tornado
1496function usingTornado()
1497{
1498    return true;
1499}
1500
1501//**************************************************************************
1502// cleanURL()
1503// split on the "*" coming from Varchar URL
1504function cleanURL($url)
1505{
1506    $rtnValue = $url;
1507    $arURL = explode("*", $url);
1508
1509    if (sizeof($arURL) > 1)
1510    {
1511        $rtnValue = $arURL[1];
1512    }
1513
1514    return $rtnValue;
1515}
1516
1517// -------------------------------------------------------------------
1518// FetchTorrent() method to get data from URL
1519// Has support for specific sites
1520// -------------------------------------------------------------------
1521function FetchTorrent($url)
1522{
1523    global $cfg, $db;
1524    ini_set("allow_url_fopen", "1");
1525    ini_set("user_agent", $_SERVER["HTTP_USER_AGENT"]);
1526
1527    $rtnValue = "";
1528
1529    $domain  = parse_url( $url );
1530
1531    if( strtolower( substr( $domain["path"], -8 ) ) != ".torrent" )
1532    {
1533        // Check know domain types
1534        if( strpos( strtolower ( $domain["host"] ), "mininova" ) !== false )
1535        {
1536            // Sample (http://www.mininova.org/rss.xml):
1537            // http://www.mininova.org/tor/2254847
1538            // <a href="/get/2281554">FreeLinux.ISO.iso.torrent</a>
1539
1540            // If received a /tor/ get the required information
1541            if( strpos( $url, "/tor/" ) !== false )
1542            {
1543                // Get the contents of the /tor/ to find the real torrent name
1544                $html = FetchHTML( $url );
1545
1546                // Check for the tag used on mininova.org
1547                if( preg_match( "/<a href=\"\/get\/[0-9].[^\"]+\">(.[^<]+)<\/a>/i", $html, $html_preg_match ) )
1548                {
1549                    // This is the real torrent filename
1550                    $cfg["save_torrent_name"] = $html_preg_match[1];
1551                }
1552
1553                // Change to GET torrent url
1554                $url = str_replace( "/tor/", "/get/", $url );
1555            }
1556
1557            // Now fetch the torrent file
1558            $html = FetchHTML( $url );
1559
1560            // This usually gets triggered if the original URL was /get/ instead of /tor/
1561            if( strlen( $cfg["save_torrent_name"] ) == 0 )
1562            {
1563                // Get the name of the torrent, and make it the filename
1564                if( preg_match( "/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match ) )
1565                {
1566                    $filelength = $html_preg_match[1];
1567                    $filename = $html_preg_match[2];
1568                    $cfg["save_torrent_name"] = substr( $filename, 0, $filelength ) . ".torrent";
1569                }
1570            }
1571
1572            // Make sure we have a torrent file
1573            if( strpos( $html, "d8:" ) === false )
1574            {
1575                // We don't have a Torrent File... it is something else
1576                AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
1577                $html = "";
1578            }
1579
1580            return $html;
1581        }
1582        elseif( strpos( strtolower ( $domain["host"] ), "isohunt" ) !== false )
1583        {
1584            // Sample (http://isohunt.com/js/rss.php):
1585            // http://isohunt.com/download.php?mode=bt&id=8837938
1586            // http://isohunt.com/btDetails.php?ihq=&id=8464972
1587            $referer = "http://" . $domain["host"] . "/btDetails.php?id=";
1588
1589            // If the url points to the details page, change it to the download url
1590            if( strpos( strtolower( $url ), "/btdetails.php?" ) !== false )
1591            {
1592                $url = str_replace( "/btDetails.php?", "/download.php?", $url ) . "&mode=bt"; // Need to make it grab the torrent
1593            }
1594
1595            // Grab contents of details page
1596            $html = FetchHTML( $url, $referer );
1597
1598            // Get the name of the torrent, and make it the filename
1599            if( preg_match( "/name([0-9]+):[^:]+/i", $html, $html_preg_match ) )
1600            {
1601                $filelength = $html_preg_match[1];
1602                $filename = $html_preg_match[0];
1603                $cfg["save_torrent_name"] = substr( $filename, 5+strlen($filelength), $filelength ) . ".torrent";
1604            }
1605
1606
1607            // Make sure we have a torrent file
1608            if( strpos( $html, "d8:" ) === false )
1609            {
1610                // We don't have a Torrent File... it is something else
1611                AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
1612                $html = "";
1613            }
1614
1615            return $html;
1616        }
1617        elseif( strpos( strtolower( $url ), "details.php?" ) !== false )
1618        {
1619            // Sample (http://www.bitmetv.org/rss.php?passkey=123456):
1620            // http://www.bitmetv.org/details.php?id=18435&hit=1
1621            $referer = "http://" . $domain["host"] . "/details.php?id=";
1622
1623            $html = FetchHTML( $url, $referer );
1624
1625            // Sample (http://www.bitmetv.org/details.php?id=18435)
1626            // download.php/18435/SpiderMan%20Season%204.torrent
1627            if( preg_match( "/(download.php.[^\"]+)/i", $html, $html_preg_match ) )
1628            {
1629                $torrent = str_replace( " ", "%20", substr( $html_preg_match[0], 0, -1 ) );
1630                $url2 = "http://" . $domain["host"] . "/" . $torrent;
1631                $html2 = FetchHTML( $url2 );
1632
1633                // Make sure we have a torrent file
1634                if (strpos($html2, "d8:") === false)
1635                {
1636                    // We don't have a Torrent File... it is something else
1637                    AuditAction($cfg["constants"]["error"], "BAD TORRENT for: ".$url."\n".$html2);
1638                    $html2 = "";
1639                }
1640                return $html2;
1641            }
1642            else
1643            {
1644                return "";
1645            }
1646        }
1647        elseif( strpos( strtolower( $url ), "download.asp?" ) !== false )
1648        {
1649            // Sample (TF's TorrenySpy Search):
1650            // http://www.torrentspy.com/download.asp?id=519793
1651            $referer = "http://" . $domain["host"] . "/download.asp?id=";
1652
1653            $html = FetchHTML( $url, $referer );
1654
1655            // Get the name of the torrent, and make it the filename
1656            if( preg_match( "/name([0-9]+):[^:]+/i", $html, $html_preg_match ) )
1657            {
1658                $filelength = $html_preg_match[1];
1659                $filename = $html_preg_match[0];
1660                $cfg["save_torrent_name"] = substr( $filename, 5+strlen($filelength), $filelength ) . ".torrent";
1661            }
1662
1663            if( !empty( $html ) )
1664            {
1665                // Make sure we have a torrent file
1666                if( strpos( $html, "d8:" ) === false )
1667                {
1668                    // We don't have a Torrent File... it is something else
1669                    AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
1670                    $html = "";
1671                }
1672                return $html;
1673            }
1674            else
1675            {
1676                return "";
1677            }
1678        }
1679    }
1680
1681    $html = FetchHTML( $url );
1682    // Make sure we have a torrent file
1683    if( strpos( $html, "d8:" ) === false )
1684    {
1685        // We don't have a Torrent File... it is something else
1686        AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url.  "\n" . $html );
1687        $html = "";
1688    }
1689    else
1690    {
1691    	$html = substr($html, strpos($html, "d8:"));
1692        // Get the name of the torrent, and make it the filename
1693        if( preg_match( "/name([0-9]+):[^:]+/i", $html, $html_preg_match ) )
1694        {
1695            $filelength = $html_preg_match[1];
1696            $filename = $html_preg_match[0];
1697            $cfg["save_torrent_name"] = substr( $filename, 5+strlen($filelength), $filelength ) . ".torrent";
1698        }
1699    }
1700
1701    return $html;
1702}
1703
1704// --------------------------------------------------…

Large files files are truncated, but you can click here to view the full file