/**
  * get AliasFile-instance
  *
  * @param $inFile the path to stats-file
  * @param $user the user
  * @param $fluxCfg torrent-flux config-array
  * @param $clientType client-type
  * @return $aliasFileInstance AliasFile-instance
  */
 function getAliasFileInstance($inFile, $user = "", $fluxCfg, $clientType = '')
 {
     // check if file is a sane file
     if (ereg("(\\.\\.\\/)", $inFile) || !preg_match('/^[a-zA-Z0-9._\\/]+(stat)$/', $inFile)) {
         AuditAction($fluxCfg["constants"]["error"], "Invalid AliasFile : " . $fluxCfg["user"] . " tried to access " . $inFile);
         global $argv;
         if (isset($argv)) {
             die("Invalid AliasFile : " . $inFile);
         } else {
             showErrorPage("Invalid AliasFile : <br>" . htmlentities($inFile, ENT_QUOTES));
         }
     }
     // damn dirty but does php (< 5) have reflection or something like
     // class-by-name ?
     if (isset($clientType) && $clientType != '') {
         $clientClass = $clientType;
         $fluxCfg["btclient"] = $clientType;
     } else {
         $clientClass = $fluxCfg["btclient"];
     }
     $classFile = 'AliasFile.' . $clientClass . '.php';
     if (is_file($classFile)) {
         include_once $classFile;
         switch ($clientClass) {
             case "tornado":
                 return new AliasFileTornado($inFile, $user, serialize($fluxCfg));
                 break;
             case "transmission":
                 return new AliasFileTransmission($inFile, $user, serialize($fluxCfg));
                 break;
         }
     }
 }
/**
 * UpdateUserProfile
 *
 * @param $user_id
 * @param $pass1
 * @param $hideOffline
 * @param $theme
 * @param $language
 */
function UpdateUserProfile($user_id, $pass1, $hideOffline, $theme, $language)
{
    global $cfg, $db;
    if (empty($hideOffline) || $hideOffline == "" || !isset($hideOffline)) {
        $hideOffline = "0";
    }
    // update values
    $rec = array();
    if ($pass1 != "") {
        $rec['password'] = md5($pass1);
        AuditAction($cfg["constants"]["update"], $cfg['_PASSWORD']);
    }
    $sql = "select * from tf_users where user_id = " . $db->qstr($user_id);
    $rs = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    $rec['hide_offline'] = $hideOffline;
    $rec['theme'] = $theme;
    $rec['language_file'] = $language;
    $sql = $db->GetUpdateSQL($rs, $rec);
    if ($sql != "") {
        $result = $db->Execute($sql);
        if ($db->ErrorNo() != 0) {
            dbError($sql);
        }
        // flush session-cache
        cacheFlush($cfg["user"]);
    }
}
 /**
  * get AliasFile-instance
  *
  * @param $inFile the path to stats-file
  * @param $user the user
  * @param $fluxCfg torrent-flux config-array
  * @param $clientType client-type
  * @return $aliasFileInstance AliasFile-instance
  */
 function getAliasFileInstance($inFile, $user = "", $fluxCfg, $clientType = '')
 {
     // check if file is a sane file
     if (strpos($inFile, "../") !== false || !preg_match('/^[a-zA-Z0-9._\\-\\/]+(stat)$/', $inFile)) {
         AuditAction($fluxCfg["constants"]["error"], "Invalid AliasFile : " . $fluxCfg["user"] . " tried to access " . $inFile);
         global $argv;
         if (isset($argv)) {
             die("Invalid AliasFile");
         } else {
             showErrorPage("Invalid AliasFile");
         }
     }
     // damn dirty but does php (< 5) have reflection or something like
     // class-by-name ?
     if (isset($clientType) && $clientType != '') {
         $clientClass = $clientType;
         $fluxCfg["btclient"] = $clientType;
     } else {
         $clientClass = $fluxCfg["btclient"];
     }
     switch ($clientClass) {
         case "tornado":
             require_once 'AliasFile.tornado.php';
             return new AliasFileTornado($inFile, $user, serialize($fluxCfg));
         case "transmission":
             require_once 'AliasFile.transmission.php';
             return new AliasFileTransmission($inFile, $user, serialize($fluxCfg));
     }
 }
/**
 * init
 */
function transfer_init()
{
    global $cfg, $tmpl, $transfer, $transferLabel, $ch;
    // request-var
    $transfer = tfb_getRequestVar('transfer');
    if (empty($transfer)) {
        @error("missing params", "", "", array('transfer'));
    }
    // validate transfer
    if (tfb_isValidTransfer($transfer) !== true) {
        AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $transfer);
        @error("Invalid Transfer", "", "", array($transfer));
    }
    // permission
    if (!$cfg['isAdmin'] && !IsOwner($cfg["user"], getOwner($transfer))) {
        AuditAction($cfg["constants"]["error"], "ACCESS DENIED: " . $transfer);
        @error("Access Denied", "", "", array($transfer));
    }
    // get label
    $transferLabel = strlen($transfer) >= 39 ? substr($transfer, 0, 35) . "..." : $transfer;
    // set transfer vars
    $tmpl->setvar('transfer', $transfer);
    $tmpl->setvar('transferLabel', $transferLabel);
    $tmpl->setvar('transfer_exists', transferExists($transfer) ? 1 : 0);
}
 /**
  * starts a client
  *
  * @param $transfer name of the transfer
  * @param $interactive (boolean) : is this a interactive startup with dialog ?
  * @param $enqueue (boolean) : enqueue ?
  */
 function start($transfer, $interactive = false, $enqueue = false)
 {
     global $cfg;
     // set vars
     $this->_setVarsForTransfer($transfer);
     // log
     $this->logMessage($this->client . "-start : " . $transfer . "\n", true);
     // FluAzu
     require_once "inc/classes/FluAzu.php";
     // do azureus special-pre-start-checks
     // check to see if fluazu is running
     if (!FluAzu::isRunning()) {
         $this->state = CLIENTHANDLER_STATE_ERROR;
         $msg = "fluazu not running, cannot start transfer " . $transfer;
         AuditAction($cfg["constants"]["error"], $msg);
         $this->logMessage($msg . "\n", true);
         array_push($this->messages, $msg);
         // write error to stat
         $sf = new StatFile($this->transfer, $this->owner);
         $sf->time_left = 'Error: fluazu down';
         $sf->write();
         // return
         return false;
     }
     // init starting of client
     $this->_init($interactive, $enqueue, true, false);
     // only continue if init succeeded (skip start / error)
     if ($this->state != CLIENTHANDLER_STATE_READY) {
         if ($this->state == CLIENTHANDLER_STATE_ERROR) {
             $msg = "Error after init (" . $transfer . "," . $interactive . "," . $enqueue . ",true," . $cfg['enable_sharekill'] . ")";
             array_push($this->messages, $msg);
             $this->logMessage($msg . "\n", true);
         }
         // return
         return false;
     }
     // build the command-string
     $content = $cfg['user'] . "\n";
     $content .= $this->savepath . "\n";
     $content .= $this->rate . "\n";
     $content .= $this->drate . "\n";
     $content .= $this->maxuploads . "\n";
     $content .= $this->superseeder . "\n";
     $content .= $this->runtime . "\n";
     $content .= $this->sharekill_param . "\n";
     $content .= $this->minport . "\n";
     $content .= $this->maxport . "\n";
     $content .= $this->maxcons . "\n";
     $content .= $this->rerequest;
     $this->command = "echo -e " . tfb_shellencode($content) . " > " . tfb_shellencode($cfg["path"] . '.fluazu/run/' . $transfer);
     $this->command .= " && ";
     $this->command .= "echo r > " . tfb_shellencode($cfg["path"] . '.fluazu/fluazu.cmd');
     if ($this->isWinOS()) {
         file_put_contents($cfg["path"] . '.fluazu/run/' . $transfer, $content);
         $this->command = "echo r > " . tfb_shellencode($cfg["path"] . '.fluazu/fluazu.cmd');
     }
     // start the client
     $this->_start();
 }
function rpc_error($errorstr, $dummy = "", $dummy = "", $response = "")
{
    global $cfg;
    AuditAction($cfg["constants"]["error"], "Transmission RPC : {$errorstr} - {$response}");
    @error($errorstr . "\n" . $response, "", "", $response, $response);
    addGrowlMessage('transmission-rpc', $errorstr . $response);
    //dbError($errorstr);
}
 /**
  * starts a bittorrent-client
  * @param $torrent name of the torrent
  * @param $interactive (1|0) : is this a interactive startup with dialog ?
  */
 function startTorrentClient($torrent, $interactive)
 {
     // do tornado special-pre-start-checks
     // check to see if the path to the python script is valid
     if (!is_file($this->cfg["btclient_tornado_bin"])) {
         AuditAction($this->cfg["constants"]["error"], "Error  Path for " . $this->cfg["btclient_tornado_bin"] . " is not valid");
         if (IsAdmin()) {
             $this->status = -1;
             header("location: admin.php?op=configSettings");
             return;
         } else {
             $this->status = -1;
             $this->messages .= "<b>Error</b> TorrentFlux settings are not correct (path to python script is not valid) -- please contact an admin.<br>";
             return;
         }
     }
     // prepare starting of client
     parent::prepareStartTorrentClient($torrent, $interactive);
     // prepare succeeded ?
     if ($this->status != 2) {
         $this->status = -1;
         $this->messages .= "<b>Error</b> parent::prepareStartTorrentClient(" . $torrent . "," . $interactive . ") failed<br>";
         return;
     }
     // build the command-string
     $skipHashCheck = "";
     if (!empty($this->skip_hash_check) && getTorrentDataSize($torrent) > 0) {
         $skipHashCheck = " --check_hashes 0";
     }
     $this->command = $this->runtime . " " . $this->sharekill_param . " " . $this->cfg["torrent_file_path"] . $this->alias . ".stat " . $this->owner . " --responsefile '" . $this->cfg["torrent_file_path"] . $this->torrent . "' --display_interval 5 --max_download_rate " . $this->drate . " --max_upload_rate " . $this->rate . " --max_uploads " . $this->maxuploads . " --minport " . $this->port . " --maxport " . $this->maxport . " --rerequest_interval " . $this->rerequest . " --super_seeder " . $this->superseeder . " --max_initiate " . $this->maxcons . $skipHashCheck;
     if (file_exists($this->cfg["torrent_file_path"] . $this->alias . ".prio")) {
         $priolist = explode(',', file_get_contents($this->cfg["torrent_file_path"] . $this->alias . ".prio"));
         $priolist = implode(',', array_slice($priolist, 1, $priolist[0]));
         $this->command .= " --priority " . $priolist;
     }
     $this->command .= " " . $this->cfg["btclient_tornado_options"] . " > /dev/null &";
     if ($this->cfg["AllowQueing"] && $this->queue == "1") {
         //  This file is queued.
     } else {
         // This file is started manually.
         if (!array_key_exists("pythonCmd", $this->cfg)) {
             insertSetting("pythonCmd", "/usr/bin/python");
         }
         if (!array_key_exists("debugTorrents", $this->cfg)) {
             insertSetting("debugTorrents", "0");
         }
         $pyCmd = "";
         if (!$this->cfg["debugTorrents"]) {
             $pyCmd = $this->cfg["pythonCmd"] . " -OO";
         } else {
             $pyCmd = $this->cfg["pythonCmd"];
         }
         $this->command = "cd " . $this->savepath . "; HOME=" . $this->cfg["path"] . "; export HOME;" . $this->umask . " nohup " . $this->nice . $pyCmd . " " . $this->cfg["btclient_tornado_bin"] . " " . $this->command;
     }
     // start the client
     parent::doStartTorrentClient();
 }
 /**
  * starts a bittorrent-client
  * @param $torrent name of the torrent
  * @param $interactive (1|0) : is this a interactive startup with dialog ?
  */
 function startTorrentClient($torrent, $interactive)
 {
     // do transmission special-pre-start-checks
     // check to see if the path to the transmission-bin is valid
     if (!is_file($this->cfg["btclient_transmission_bin"])) {
         AuditAction($this->cfg["constants"]["error"], "Error Path for " . $this->cfg["btclient_transmission_bin"] . " is not valid");
         $this->status = -1;
         if (IsAdmin()) {
             header("location: admin.php?op=configSettings");
             return;
         } else {
             $this->messages .= "<b>Error</b> TorrentFlux settings are not correct (path to transmission-bin is not valid) -- please contact an admin.<br>";
             return;
         }
     }
     // prepare starting of client
     parent::prepareStartTorrentClient($torrent, $interactive);
     // prepare succeeded ?
     if ($this->status != 2) {
         $this->status = -1;
         $this->messages .= "<b>Error</b> parent::prepareStartTorrentClient(" . $torrent . "," . $interactive . ") failed<br>";
         return;
     }
     // included in transmissioncli
     // quick-hack for transmission--1
     //if ($this->rate == 0)
     //    $this->rate = -1;
     //if ($this->drate == 0)
     //    $this->drate = -1;
     // included in transmissioncli
     // pid-file
     $this->pidFile = "\"" . $this->cfg["torrent_file_path"] . $this->alias . ".stat.pid\"";
     // build the command-string
     $this->command = "-t \"" . $this->cfg["torrent_file_path"] . $this->alias . ".stat\" -w " . $this->owner;
     // "new" transmission-patch has pid-file included
     $this->command .= " -z " . $this->pidFile;
     /* - bsd-workaround */
     $this->command .= " -e 5 -p " . $this->port . " -u " . $this->rate . " -c " . $this->sharekill_param . " -d " . $this->drate;
     $this->command .= " " . $this->cfg["btclient_transmission_options"] . "\"" . $this->cfg["torrent_file_path"] . $this->torrent;
     // standard, no shell trickery ("new" transmission-patch has pid-file included) :
     $this->command .= '" &> /dev/null &';
     /* - bsd-workaround */
     // <begin shell-trickery> to write the pid of the client into the pid-file
     // * b4rt :
     //$this->command .= '" &> /dev/null & echo $! > "'. $this->pidFile .'"';
     // * lord_nor :
     //$this->command .= '" > /dev/null & echo $! & > "'. $this->pidFile .'"'; /* + bsd-workaround */
     // <end shell-trickery>
     if ($this->cfg["AllowQueing"] && $this->queue == "1") {
         //  This file is queued.
     } else {
         // This file is started manually.
         $this->command = "cd " . $this->savepath . "; HOME=" . $this->cfg["path"] . "; export HOME;" . $this->umask . " nohup " . $this->nice . $this->cfg["btclient_transmission_bin"] . " " . $this->command;
     }
     // start the client
     parent::doStartTorrentClient();
 }
function SecurityCleanPath($string)
{
    global $cfg;
    if (empty($string)) {
        return $string;
    }
    $array = array("<", ">", "\\", "//", "..", "'");
    foreach ($array as $char) {
        $string = str_replace($char, NULL, $string);
    }
    if (strtolower(substr($string, -4)) == ".txt" || strtolower(substr($string, -4)) == ".nfo") {
        // we are good
    } else {
        AuditAction($cfg["constants"]["error"], "Not a text or NFO: " . $string);
        die("Invalid file specified.  Action has been logged.");
    }
    return $string;
}
Example #10
0
/**
 * init
 */
function transfer_init()
{
    global $cfg, $tmpl, $transfer, $transferLabel, $ch;
    // request-var
    $transfer = tfb_getRequestVar('transfer');
    if (empty($transfer)) {
        @error("missing params", "", "", array('transfer'));
    }
    if ($cfg["transmission_rpc_enable"] && isHash($transfer)) {
        require_once 'inc/functions/functions.rpc.transmission.php';
        $theTorrent = getTransmissionTransfer($transfer, array('hashString', 'id', 'name'));
        if (is_array($theTorrent)) {
            $transferLabel = strlen($theTorrent[name]) >= 39 ? substr($theTorrent[name], 0, 35) . "..." : $theTorrent[name];
            $tmpl->setvar('transfer', $theTorrent[hashString]);
            $tmpl->setvar('transferLabel', $transferLabel);
            $tmpl->setvar('transfer_exists', 0);
            return;
            // We really don't need this. Only the hash is a unique way of finding transfers. So all transfer operations should use the hash.
            /*
            			//tf compatible... erk
            			$transfer = getTransferFromHash($transfer);
            			if (empty($transfer))
            				$transfer = $theTorrent[name];
            */
        }
    }
    // validate transfer
    if (tfb_isValidTransfer($transfer) !== true) {
        AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $transfer);
        @error("Invalid Transfer", "", "", array($transfer));
    }
    // permission
    if (!$cfg['isAdmin'] && !IsOwner($cfg["user"], getOwner($transfer))) {
        AuditAction($cfg["constants"]["error"], "ACCESS DENIED: " . $transfer);
        @error("Access Denied", "", "", array($transfer));
    }
    // get label
    $transferLabel = preg_replace("#\\.torrent\$#", "", $transfer);
    $transferLabel = strlen($transferLabel) >= 39 ? substr($transferLabel, 0, 35) . "..." : $transferLabel;
    // set transfer vars
    $tmpl->setvar('transfer', $transfer);
    $tmpl->setvar('transferLabel', $transferLabel);
    $tmpl->setvar('transfer_exists', transferExists($transfer) ? 1 : 0);
}
 /**
  * updateStatFiles
  *
  * @param $transfer string torrent name
  * @return boolean
  */
 function updateStatFiles($transfer = "")
 {
     global $cfg, $db;
     //$rpc = Transmission::getInstance();
     $tfs = $this->monitorRunningTransfers();
     if (!is_array($tfs)) {
         return false;
     }
     $sql = "SELECT hash, transfer, sharekill FROM tf_transfers WHERE type='torrent' AND client = 'transmissionrpc'";
     if ($transfer != "") {
         //only update one transfer...
         $sql .= " AND transfer=" . $db->qstr($transfer);
     } else {
         $hashes = array("''");
         foreach ($tfs as $hash => $t) {
             $hashes[] = "'" . strtolower($hash) . "'";
         }
         $sql .= " AND hash IN (" . implode(',', $hashes) . ")";
     }
     $recordset = $db->Execute($sql);
     while (list($hash, $transfer, $sharekill) = $recordset->FetchRow()) {
         $hash = strtolower($hash);
         $hashes[$hash] = $transfer;
         $sharekills[$hash] = $sharekill;
     }
     //convertTimeText
     require_once "inc/functions/functions.core.php";
     foreach ($tfs as $hash => $t) {
         if (!isset($hashes[$hash])) {
             continue;
         }
         $transfer = $hashes[$hash];
         $sf = new StatFile($transfer);
         $sf->running = $t['running'];
         $sf->percent_done = round($t['percentDone'] * 100, 2);
         if ($t['status'] == 8 || $t['status'] == 9) {
             $sf->sharing = round($t['uploadRatio'] * 100, 2);
         }
         $sf->downtotal = $t['downloadedEver'];
         $sf->uptotal = $t['uploadedEver'];
         $sf->write();
     }
     //SHAREKILLS Checks
     foreach ($tfs as $hash => $t) {
         if (!isset($sharekills[$hash])) {
             continue;
         }
         if (($t['status'] == 8 || $t['status'] == 9) && $t['uploadRatio'] * 100 > $sharekills[$hash]) {
             $transfer = $hashes[$hash];
             if (stopTransmissionTransfer($hash)) {
                 AuditAction($cfg["constants"]["stop_transfer"], $this->client . "-stat. : sharekill stopped {$transfer}");
                 stopTransferSettings($transfer);
             }
         }
     }
     return true;
 }
 /**
  * Inject Transfer
  *
  * @param $transferFile
  * @param $username
  * @param $options
  * @param array $extra
  * @return mixed
  */
 function _inject($transferFile, $username, $options = '', $extra = array())
 {
     global $cfg;
     // check file
     if (!@is_file($transferFile)) {
         $this->_outputError("transfer-file " . $transferFile . " is no file.\n");
         return false;
     }
     // check username
     if (!IsUser($username)) {
         $this->_outputError("username " . $username . " is no valid user.\n");
         return false;
     }
     // parse options
     $optionsSet = $this->_parseOptions(array('d' => 0, 's' => 0, 'p' => 1), $options, $extra);
     if ($optionsSet === false) {
         return false;
     }
     $profile = isset($optionsSet['p']) ? $optionsSet['p'][0] : null;
     $this->_outputMessage("Inject " . $transferFile . " for user " . $username . (!empty($profile) ? " using profile " . $profile : '') . " ...\n");
     // set user
     $cfg["user"] = $username;
     // set filename
     $transfer = basename($transferFile);
     $transfer = tfb_cleanFileName($transfer);
     // only inject valid transfers
     $msgs = array();
     if ($transfer !== false) {
         $targetFile = $cfg["transfer_file_path"] . $transfer;
         if (@is_file($targetFile)) {
             array_push($msgs, "transfer " . $transfer . ", already exists.");
         } else {
             $this->_outputMessage("copy " . $transferFile . " to " . $targetFile . " ...\n");
             if (@copy($transferFile, $targetFile)) {
                 // chmod
                 @chmod($cfg["transfer_file_path"] . $transfer, 0644);
                 // make owner entry
                 AuditAction($cfg["constants"]["file_upload"], $transfer);
                 // inject
                 $this->_outputMessage("injecting " . $transfer . " ...\n");
                 injectTransfer($transfer);
                 // delete source-file
                 if (isset($optionsSet['d'])) {
                     $this->_outputMessage("deleting source-file " . $transferFile . " ...\n");
                     @unlink($transferFile);
                 }
                 // start
                 if (isset($optionsSet['s'])) {
                     // build args for _transferStart
                     $newOptions = $this->_buildOptions('p', $optionsSet);
                     // Pass-thru option 'p'.
                     return $this->_transferStart($transfer, $newOptions[0], $newOptions[1]);
                 } else {
                     return true;
                 }
             } else {
                 array_push($msgs, "File could not be copied: " . $transferFile);
             }
         }
     } else {
         array_push($msgs, "The type of file you are injecting is not allowed.");
         array_push($msgs, "valid file-extensions: ");
         array_push($msgs, $cfg["file_types_label"]);
     }
     if (count($msgs) == 0) {
         $this->_outputMessage("done.\n");
         return true;
     } else {
         $this->_outputError("failed: " . implode("\n", $msgs) . "\n");
         return false;
     }
 }
function indexProcessUpload()
{
    global $cfg, $messages;
    $file_name = stripslashes($_FILES['upload_file']['name']);
    $file_name = str_replace(array("'", ","), "", $file_name);
    $file_name = cleanFileName($file_name);
    $ext_msg = "";
    if ($_FILES['upload_file']['size'] <= 1000000 && $_FILES['upload_file']['size'] > 0) {
        if (ereg(getFileFilter($cfg["file_types_array"]), $file_name)) {
            //FILE IS BEING UPLOADED
            if (is_file($cfg["torrent_file_path"] . $file_name)) {
                // Error
                $messages .= "<b>Error</b> with (<b>" . $file_name . "</b>), the file already exists on the server.<br><center><a href=\"" . $_SERVER['PHP_SELF'] . "\">[Refresh]</a></center>";
                $ext_msg = "DUPLICATE :: ";
            } else {
                if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $cfg["torrent_file_path"] . $file_name)) {
                    chmod($cfg["torrent_file_path"] . $file_name, 0644);
                    AuditAction($cfg["constants"]["file_upload"], $file_name);
                    // init stat-file
                    injectTorrent($file_name);
                    // instant action ?
                    $actionId = getRequestVar('aid');
                    if (isset($actionId)) {
                        switch ($actionId) {
                            case 3:
                                $_REQUEST['queue'] = 'on';
                            case 2:
                                if ($cfg["enable_file_priority"]) {
                                    include_once "setpriority.php";
                                    // Process setPriority Request.
                                    setPriority(urldecode($file_name));
                                }
                                include_once "ClientHandler.php";
                                $clientHandler = ClientHandler::getClientHandlerInstance($cfg);
                                $clientHandler->startTorrentClient($file_name, 0);
                                // just a sec..
                                sleep(1);
                                break;
                        }
                    }
                } else {
                    $messages .= "<font color=\"#ff0000\" size=3>ERROR: File not uploaded, file could not be found or could not be moved:<br>" . $cfg["torrent_file_path"] . $file_name . "</font><br>";
                }
            }
        } else {
            $messages .= "<font color=\"#ff0000\" size=3>ERROR: The type of file you are uploading is not allowed.</font><br>";
        }
    } else {
        $messages .= "<font color=\"#ff0000\" size=3>ERROR: File not uploaded, check file size limit.</font><br>";
    }
    if ($messages != "") {
        // there was an error
        AuditAction($cfg["constants"]["error"], $cfg["constants"]["file_upload"] . " :: " . $ext_msg . $file_name);
    } else {
        header("location: index.php");
        exit;
    }
}
/**
 * Modify Profile Information
 *
 * @param $pid
 * @param $newProfile
 */
function modProfileInfo($pid, $newProfile)
{
    global $cfg, $db;
    // b4rt: var not used, commented this out
    //	$default_savepath = " value=\"" . ($cfg["enable_home_dirs"] != 0)
    //		? $cfg['path'].$cfg["user"].'/'
    //		: $cfg['path'].$cfg["path_incoming"].'/' . "\"";
    // in case of homedirs, ensure profile doesnt go out of savepath.
    if ($cfg["enable_home_dirs"] != 0) {
        if (substr($newProfile["savepath"], 0, strlen($cfg['path'] . $cfg["user"])) != $cfg['path'] . $cfg["user"]) {
            AuditAction($cfg["constants"]["error"], "INVALID TRANSFER DIRECTORY.: ");
            @error("Invalid directory. You can only set transfer paths within your own directory.", "", "", array());
        }
    } else {
        if (substr($newProfile["savepath"], 0, strlen($cfg['path'])) != $cfg['path']) {
            AuditAction($cfg["constants"]["error"], "INVALID TRANSFER DIRECTORY.: ");
            @error("Invalid directory. You can only set transfer paths within the root directory " . $cfg['path'] . ".", "", "", array());
        }
    }
    $sql = "UPDATE tf_trprofiles SET" . " owner = " . $db->qstr($cfg['uid']) . ", name = " . $db->qstr($newProfile["name"]) . ", minport = " . $db->qstr($newProfile["minport"]) . ", maxport = " . $db->qstr($newProfile["maxport"]) . ", maxcons = " . $db->qstr($newProfile["maxcons"]) . ", rerequest = " . $db->qstr($newProfile["rerequest"]) . ", rate = " . $db->qstr($newProfile["rate"]) . ", maxuploads = " . $db->qstr($newProfile["maxuploads"]) . ", drate = " . $db->qstr($newProfile["drate"]) . ", runtime = " . $db->qstr($newProfile["runtime"]) . ", sharekill = " . $db->qstr($newProfile["sharekill"]) . ", superseeder = " . $db->qstr($newProfile["superseeder"]) . ", public = " . $db->qstr($newProfile["public"]) . ", savepath = " . $db->qstr($newProfile["savepath"]) . " WHERE id = " . $db->qstr($pid);
    $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
}
Example #15
0
    $tmpl->setvar('_REN_FILE', $cfg['_REN_FILE']);
    $tmpl->setvar('_REN_STRING', $cfg['_REN_STRING']);
} else {
    $file = tfb_getRequestVar('fileFrom');
    $fileTo = tfb_getRequestVar('fileTo');
    $dir = tfb_getRequestVar('dir');
    $sourceDir = $cfg["path"] . $dir;
    $targetDir = $cfg["path"] . $dir . $fileTo;
    // Add slashes if magic_quotes off:
    if (get_magic_quotes_gpc() !== 1) {
        $targetDir = addslashes($targetDir);
        $sourceDir = addslashes($sourceDir);
    }
    // only valid dirs + entries with permission
    if (!(tfb_isValidPath($sourceDir) && tfb_isValidPath($sourceDir . $file) && tfb_isValidPath($targetDir) && isValidEntry($file) && isValidEntry($fileTo) && hasPermission($dir, $cfg["user"], 'w'))) {
        AuditAction($cfg["constants"]["error"], "ILLEGAL RENAME: " . $cfg["user"] . " tried to rename " . $file . " in " . $dir . " to " . $fileTo);
        @error("Illegal rename. Action has been logged.", "", "");
    }
    // Use single quote to escape mv args:
    $cmd = "mv '" . $sourceDir . $file . "' '" . $targetDir . "'";
    $cmd .= ' 2>&1';
    $handle = popen($cmd, 'r');
    $gotError = -1;
    $buff = fgets($handle);
    $gotError = $gotError + 1;
    pclose($handle);
    // template
    $tmpl->setvar('is_start', 0);
    $tmpl->setvar('messages', nl2br($buff));
    if ($gotError <= 0) {
        $tmpl->setvar('no_error', 1);
Example #16
0
        $hits++;
        $sql = 'select * from tf_users where uid = ' . $uid;
        $rs = $db->Execute($sql);
        showError($db, $sql);
        $rec = array('hits' => $hits, 'last_visit' => $db->DBDate($create_time), 'theme' => $cfg['theme'], 'language_file' => $cfg['language_file'], 'shutdown' => $cfg['shutdown'], 'upload_rate' => $cfg['upload_rate']);
        $sql = $db->GetUpdateSQL($rs, $rec);
        $result = $db->Execute($sql);
        showError($db, $sql);
        $_SESSION['user'] = $user;
        session_write_close();
        header("location: " . $next_loc);
        exit;
    } else {
        // wrong credentials
        $login_failed = 1;
        AuditAction($cfg["constants"]["access_denied"], "FAILED AUTH: " . $user);
    }
} else {
    $login_failed = 0;
}
// html part
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title><?php 
echo $cfg["pagetitle"];
?>
</title>
 /**
  * store new jobs-list setting
  *
  * @param $jobs jobs-list as array
  * @return boolean
  */
 function _jobsUpdateSetting($jobs)
 {
     global $cfg;
     // build setting value
     $setting = $this->_jobsSerialize($jobs);
     if ($setting === false) {
         return false;
     }
     // update setting
     updateSetting("tf_settings", "fluxd_Watch_jobs", $setting);
     // log
     AuditAction($cfg["constants"]["fluxd"], "Watch Jobs Saved : \n" . $setting);
     return true;
 }
/**
 * backup of flux-installation
 *
 * @param $talk : boolean if function should talk
 * @param $compression : 0 = none | 1 = gzip | 2 = bzip2
 * @return string with name of backup-archive, string with "" in error-case.
 */
function backupCreate($talk = false, $compression = 0)
{
    global $cfg, $error;
    // backup-dir
    $dirBackup = $cfg["path"] . _DIR_BACKUP;
    if (!checkDir($dirBackup)) {
        $error = "Errors when checking/creating backup-dir : " . $dirBackup;
        return "";
    }
    // files and more strings
    $backupName = "backup_" . _VERSION_THIS . "_" . date("YmdHis");
    $fileArchiveName = $backupName . ".tar";
    $tarSwitch = "-cf";
    switch ($compression) {
        case 1:
            $fileArchiveName .= ".gz";
            $tarSwitch = "-zcf";
            break;
        case 2:
            $fileArchiveName .= ".bz2";
            $tarSwitch = "-jcf";
            break;
    }
    $fileArchive = $dirBackup . '/' . $fileArchiveName;
    $fileDatabase = $dirBackup . '/database.sql';
    $fileDocroot = $dirBackup . '/docroot.tar';
    // command-strings
    $commandArchive = "cd " . $dirBackup . "; tar " . $tarSwitch . " " . $fileArchiveName . " ";
    $commandDatabase = "";
    switch ($cfg["db_type"]) {
        case "mysql":
            $commandDatabase = "mysqldump -h " . $cfg["db_host"] . " -u " . $cfg["db_user"] . " --password="******"db_pass"] . " --all -f " . $cfg["db_name"] . " > " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
        case "sqlite":
            $commandDatabase = "sqlite " . $cfg["db_host"] . " .dump > " . $fileDatabase;
            $commandArchive .= 'database.sql ';
            break;
    }
    $commandArchive .= 'docroot.tar';
    //$commandDocroot = "cd ".$dirBackup."; tar -cf docroot.tar ".$_SERVER['DOCUMENT_ROOT']; // with path of docroot
    $commandDocroot = "cd " . $_SERVER['DOCUMENT_ROOT'] . "; tar -cf " . $fileDocroot . " .";
    // only content of docroot
    // database-command
    if ($commandDatabase != "") {
        if ($talk) {
            sendLine('Backup of Database <em>' . $cfg["db_name"] . '</em> ...');
        }
        shell_exec($commandDatabase);
    }
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // docroot-command
    if ($talk) {
        sendLine('Backup of Docroot <em>' . $_SERVER['DOCUMENT_ROOT'] . '</em> ...');
    }
    shell_exec($commandDocroot);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // create the archive
    if ($talk) {
        sendLine('Creating Archive <em>' . $fileArchiveName . '</em> ...');
    }
    shell_exec($commandArchive);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // delete temp-file(s)
    if ($talk) {
        sendLine('Deleting temp-files ...');
    }
    if ($commandDatabase != "") {
        @unlink($fileDatabase);
    }
    @unlink($fileDocroot);
    if ($talk) {
        sendLine(' <font color="green">Ok</font><br>');
    }
    // log
    if ($talk) {
        sendLine('<font color="green">Backup Complete.</font><br>');
    }
    AuditAction($cfg["constants"]["admin"], "FluxBackup Created : " . $fileArchiveName);
    return $fileArchiveName;
}
/**
 * deletes data of a transfer
 *
 * @param $transfer name of the transfer
 * @return array
 */
function deleteTransferData($transfer)
{
    global $cfg, $transfers;
    $msgs = array();
    $isTransmissionTorrent = false;
    if ($cfg["transmission_rpc_enable"] == 2 && isHash($transfer)) {
        require_once 'inc/classes/Transmission.class.php';
        $trans = new Transmission();
        require_once 'inc/functions/functions.rpc.transmission.php';
        $theTorrent = getTransmissionTransfer($transfer, array('hashString', 'id', 'name'));
        $isTransmissionTorrent = is_array($theTorrent);
    }
    if ($isTransmissionTorrent) {
        $response = $trans->remove($theTorrent['id'], true);
        if ($response[result] != "success") {
            @error("Delete of torrent failed", "", "", $response[result]);
        }
    } else {
        if ($cfg['isAdmin'] || IsOwner($cfg["user"], getOwner($transfer))) {
            // only torrent
            if (substr($transfer, -8) != ".torrent") {
                return $msgs;
            }
            // delete data
            $datapath = getTransferDatapath($transfer);
            if ($datapath != "" && $datapath != ".") {
                $targetPath = getTransferSavepath($transfer) . $datapath;
                if (tfb_isValidPath($targetPath)) {
                    if (@is_dir($targetPath) || @is_file($targetPath)) {
                        avddelete($targetPath);
                        AuditAction($cfg["constants"]["fm_delete"], $targetPath);
                    }
                } else {
                    $msg = "ILLEGAL DELETE: " . $cfg["user"] . " attempted to delete data of " . $transfer;
                    AuditAction($cfg["constants"]["error"], $msg);
                    array_push($msgs, $msg);
                }
            }
        } else {
            $msg = "ILLEGAL DELETE: " . $cfg["user"] . " attempted to delete data of " . $transfer;
            AuditAction($cfg["constants"]["error"], $msg);
            array_push($msgs, $msg);
        }
    }
    return $msgs;
}
 /**
  * starts a client
  *
  * @param $transfer name of the transfer
  * @param $interactive (boolean) : is this a interactive startup with dialog ?
  * @param $enqueue (boolean) : enqueue ?
  */
 function start($transfer, $interactive = false, $enqueue = false)
 {
     global $cfg;
     // set vars
     $this->_setVarsForTransfer($transfer);
     // log
     $this->logMessage($this->client . "-start : " . $transfer . "\n", true);
     // do tornado special-pre-start-checks
     // check to see if the path to the python script is valid
     if (!is_file($this->tornadoBin)) {
         $this->state = CLIENTHANDLER_STATE_ERROR;
         $msg = "path for tftornado.py is not valid";
         AuditAction($cfg["constants"]["error"], $msg);
         $this->logMessage($msg . "\n", true);
         array_push($this->messages, $msg);
         array_push($this->messages, "tornadoBin : " . $this->tornadoBin);
         // write error to stat
         $sf = new StatFile($this->transfer, $this->owner);
         $sf->time_left = 'Error';
         $sf->write();
         // return
         return false;
     }
     // init starting of client
     $this->_init($interactive, $enqueue, true, $cfg['enable_sharekill'] == 1);
     // only continue if init succeeded (skip start / error)
     if ($this->state != CLIENTHANDLER_STATE_READY) {
         if ($this->state == CLIENTHANDLER_STATE_ERROR) {
             $msg = "Error after init (" . $transfer . "," . $interactive . "," . $enqueue . ",true," . $cfg['enable_sharekill'] . ")";
             array_push($this->messages, $msg);
             $this->logMessage($msg . "\n", true);
         }
         // return
         return false;
     }
     // file-prio
     if ($cfg["enable_file_priority"]) {
         setFilePriority($transfer);
     }
     // pythonCmd
     $pyCmd = $cfg["pythonCmd"] . " -OO";
     // build the command-string
     $skipHashCheck = "";
     if (!empty($this->skip_hash_check) && getTorrentDataSize($transfer) > 0) {
         $skipHashCheck = " --check_hashes 0";
     }
     $filePrio = "";
     if (@file_exists($this->transferFilePath . ".prio")) {
         $priolist = explode(',', @file_get_contents($this->transferFilePath . ".prio"));
         $priolist = implode(',', array_slice($priolist, 1, $priolist[0]));
         $filePrio = " --priority " . tfb_shellencode($priolist);
     }
     // build the command-string
     // note : order of args must not change for ps-parsing-code in
     // RunningTransferTornado
     $this->command = "";
     //	       Proxy Hack
     //	       $this->command .= 'export http_proxy=127.0.0.1:8118; HTTP_PROXY=$http_proxy;';
     $this->command .= "cd " . tfb_shellencode($this->savepath) . ";";
     $this->command .= " HOME=" . tfb_shellencode($cfg["path"]);
     $this->command .= "; export HOME;";
     $this->command .= $this->umask;
     $this->command .= " nohup ";
     $this->command .= $this->nice;
     $this->command .= $pyCmd . " " . tfb_shellencode($this->tornadoBin);
     $this->command .= " " . tfb_shellencode($this->runtime);
     $this->command .= " " . tfb_shellencode($this->sharekill_param);
     $this->command .= " " . tfb_shellencode($this->owner);
     $this->command .= " " . tfb_shellencode($this->transferFilePath);
     $this->command .= " --responsefile " . tfb_shellencode($this->transferFilePath);
     $this->command .= " --display_interval 1";
     $this->command .= " --max_download_rate " . tfb_shellencode($this->drate);
     $this->command .= " --max_upload_rate " . tfb_shellencode($this->rate);
     $this->command .= " --max_uploads " . tfb_shellencode($this->maxuploads);
     $this->command .= " --minport " . tfb_shellencode($this->port);
     $this->command .= " --maxport " . tfb_shellencode($this->maxport);
     $this->command .= " --rerequest_interval " . tfb_shellencode($this->rerequest);
     $this->command .= " --super_seeder " . tfb_shellencode($this->superseeder);
     $this->command .= " --max_connections " . tfb_shellencode($this->maxcons);
     $this->command .= $skipHashCheck;
     $this->command .= $filePrio;
     if (strlen($cfg["btclient_tornado_options"]) > 0) {
         $this->command .= " " . $cfg["btclient_tornado_options"];
     }
     $this->command .= " 1>> " . tfb_shellencode($this->transferFilePath . ".log");
     $this->command .= " 2>> " . tfb_shellencode($this->transferFilePath . ".log");
     $this->command .= " &";
     // start the client
     $this->_start();
 }
Example #21
0
 /**
  * write the command-file
  *
  * @param $content
  * @return boolean
  */
 function _writeCommandFile($content)
 {
     global $cfg;
     $handle = false;
     $handle = @fopen($this->_pathCommandFile, "w");
     if (!$handle) {
         $msg = "cannot open command-file " . $this->_pathCommandFile . " for writing.";
         array_push($this->messages, $msg);
         AuditAction($cfg["constants"]["error"], "FluAzu _writeCommandFile-Error : " . $msg);
         return false;
     }
     $result = @fwrite($handle, $content);
     @fclose($handle);
     if ($result === false) {
         $msg = "cannot write content to command-file " . $this->_pathCommandFile . ".";
         array_push($this->messages, $msg);
         AuditAction($cfg["constants"]["error"], "FluAzu _writeCommandFile-Error : " . $msg);
         return false;
     }
     return true;
 }
 /**
  * dequeueTorrent
  * @param $torrent name of the torrent
  */
 function dequeueTorrent($torrent)
 {
     $torrent = urldecode($torrent);
     $alias_file = getRequestVar('alias_file');
     // Is the Qinfo file still there?
     if (file_exists($this->cfg["torrent_file_path"] . "queue/" . $alias_file . ".Qinfo")) {
         // flag the torrent as stopped (in db)
         stopTorrentSettings($torrent);
         // update the stat file.
         parent::updateStatFile($torrent, $alias_file);
         // Remove Qinfo file.
         @unlink($this->cfg["torrent_file_path"] . "queue/" . $alias_file . ".Qinfo");
         // log
         AuditAction($this->cfg["constants"]["unqueued_torrent"], $torrent);
     } else {
         // torrent has been started... try and kill it.
         AuditAction($this->cfg["constants"]["unqueued_torrent"], $torrent . "has been started -- TRY TO KILL IT");
         header("location: index.php?alias_file=" . $alias_file . "&kill=true&kill_torrent=" . urlencode($torrent));
         exit;
     }
 }
function saveUserSettings($uid, $settings)
{
    global $cfg;
    // Messy - a not exists would prob work better. but would have to be done
    // on every key/value pair so lots of extra-statements.
    deleteUserSettings($uid);
    // load global settings + overwrite per-user settings
    loadSettings('tf_settings');
    // insert new settings
    foreach ($settings as $key => $value) {
        if (in_array($key, $cfg['validUserSettingsKeys'])) {
            insertUserSettingPair($uid, $key, $value);
        } else {
            AuditAction($cfg["constants"]["error"], "ILLEGAL SETTING: " . $cfg["user"] . " tried to insert " . $value . " for key " . $key);
        }
    }
    // flush session-cache
    cacheFlush($cfg["user"]);
    // return
    return true;
}
Example #24
0
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 To read the license please visit http://www.gnu.org/copyleft/gpl.html

*******************************************************************************/
include_once "config.php";
include_once "functions.php";
require_once "metaInfo.php";
// is enabled ?
if ($cfg["advanced_start"] != 1) {
    AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to use advanced start");
    showErrorPage("advanced start is disabled.");
}
$torrent = getRequestVar('torrent');
// Load saved settings
$btclient_default = $cfg["btclient"];
$torrentExists = loadTorrentSettingsToConfig($torrent);
// savepath
if (!isset($cfg["savepath"]) || empty($cfg["savepath"])) {
    $cfg["savepath"] = $cfg["path"] . getOwner($torrent) . '/';
}
// torrent exists ?
$torrentExists = getTorrentDataSize($torrent) > 0;
// display name
$displayName = htmlentities($torrent, ENT_QUOTES);
if (strlen($displayName) >= 55) {
/**
 * exit
 */
function dispatcher_exit()
{
    global $cfg;
    $redir = isset($_REQUEST['riid']) ? tfb_getRequestVar('riid') : "index";
    switch ($redir) {
        case "_exit_":
            exit("1");
        case "_none_":
            break;
        case "_referer_":
            if (isset($_SERVER["HTTP_REFERER"])) {
                @header("location: " . $_SERVER["HTTP_REFERER"]);
            }
            break;
        default:
            if (preg_match('/^[a-zA-Z]+$/D', $redir)) {
                @header("location: index.php?iid=" . $redir);
            } else {
                AuditAction($cfg["constants"]["error"], "INVALID PAGE (riid): " . $redir);
                @error("Invalid Page", "", "", array($redir));
            }
    }
    // exit
    exit;
}
function FetchTorrent($url)
{
    global $cfg, $db;
    ini_set("allow_url_fopen", "1");
    ini_set("user_agent", $_SERVER["HTTP_USER_AGENT"]);
    $domain = parse_url($url);
    if (strtolower(substr($domain["path"], -8)) != ".torrent") {
        // Check know domain types
        if (strpos(strtolower($domain["host"]), "mininova") !== false) {
            // Sample (http://www.mininova.org/rss.xml):
            // http://www.mininova.org/tor/2254847
            // <a href="/get/2281554">FreeLinux.ISO.iso.torrent</a>
            // If received a /tor/ get the required information
            if (strpos($url, "/tor/") !== false) {
                // Get the contents of the /tor/ to find the real torrent name
                $html = FetchHTML($url);
                // Check for the tag used on mininova.org
                if (preg_match("/<a href=\"\\/get\\/[0-9].[^\"]+\">(.[^<]+)<\\/a>/i", $html, $html_preg_match)) {
                    // This is the real torrent filename
                    $cfg["save_torrent_name"] = $html_preg_match[1];
                }
                // Change to GET torrent url
                $url = str_replace("/tor/", "/get/", $url);
            }
            // Now fetch the torrent file
            $html = FetchHTML($url);
            // This usually gets triggered if the original URL was /get/ instead of /tor/
            if (!isset($cfg["save_torrent_name"]) || strlen($cfg["save_torrent_name"]) == 0) {
                // Get the name of the torrent, and make it the filename
                if (preg_match("/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match)) {
                    $filelength = $html_preg_match[1];
                    $filename = $html_preg_match[2];
                    $cfg["save_torrent_name"] = substr($filename, 0, $filelength) . ".torrent";
                } else {
                    $cfg["save_torrent_name"] = "unknown.torrent";
                }
            }
            // Make sure we have a torrent file
            if (strpos($html, "d8:") === false) {
                // We don't have a Torrent File... it is something else
                AuditAction($cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html);
                $html = "";
            }
            return $html;
        } elseif (strpos(strtolower($domain["host"]), "isohunt") !== false) {
            // Sample (http://isohunt.com/js/rss.php):
            // http://isohunt.com/download.php?mode=bt&id=8837938
            // http://isohunt.com/btDetails.php?ihq=&id=8464972
            $referer = "http://" . $domain["host"] . "/btDetails.php?id=";
            // If the url points to the details page, change it to the download url
            if (strpos(strtolower($url), "/btdetails.php?") !== false) {
                $url = str_replace("/btDetails.php?", "/download.php?", $url) . "&mode=bt";
                // Need to make it grab the torrent
            }
            // Grab contents of details page
            $html = FetchHTML($url, $referer);
            // Get the name of the torrent, and make it the filename
            if (preg_match("/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match)) {
                $filelength = $html_preg_match[1];
                $filename = $html_preg_match[2];
                $cfg["save_torrent_name"] = substr($filename, 0, $filelength) . ".torrent";
            } else {
                $cfg["save_torrent_name"] = "unknown.torrent";
            }
            // Make sure we have a torrent file
            if (strpos($html, "d8:") === false) {
                // We don't have a Torrent File... it is something else
                AuditAction($cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html);
                $html = "";
            }
            return $html;
        } elseif (strpos(strtolower($url), "details.php?") !== false) {
            // Sample (http://www.bitmetv.org/rss.php?passkey=123456):
            // http://www.bitmetv.org/details.php?id=18435&hit=1
            $referer = "http://" . $domain["host"] . "/details.php?id=";
            $html = FetchHTML($url, $referer);
            // Sample (http://www.bitmetv.org/details.php?id=18435)
            // download.php/18435/SpiderMan%20Season%204.torrent
            if (preg_match("/(download.php.[^\"]+)/i", $html, $html_preg_match)) {
                $torrent = str_replace(" ", "%20", substr($html_preg_match[0], 0, -1));
                $url2 = "http://" . $domain["host"] . "/" . $torrent;
                $html2 = FetchHTML($url2);
                // Make sure we have a torrent file
                if (strpos($html2, "d8:") === false) {
                    // We don't have a Torrent File... it is something else
                    AuditAction($cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html2);
                    $html2 = "";
                }
                return $html2;
            } else {
                return "";
            }
        } elseif (strpos(strtolower($url), "download.asp?") !== false) {
            // Sample (TF's TorrenySpy Search):
            // http://www.torrentspy.com/download.asp?id=519793
            $referer = "http://" . $domain["host"] . "/download.asp?id=";
            $html = FetchHTML($url, $referer);
            // Get the name of the torrent, and make it the filename
            if (preg_match("/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match)) {
                $filelength = $html_preg_match[1];
                $filename = $html_preg_match[2];
                $cfg["save_torrent_name"] = substr($filename, 0, $filelength) . ".torrent";
            } else {
                $cfg["save_torrent_name"] = "unknown.torrent";
            }
            if (!empty($html)) {
                // Make sure we have a torrent file
                if (strpos($html, "d8:") === false) {
                    // We don't have a Torrent File... it is something else
                    AuditAction($cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html);
                    $html = "";
                }
                return $html;
            } else {
                return "";
            }
        }
    }
    $html = FetchHTML($url);
    // Make sure we have a torrent file
    if (strpos($html, "d8:") === false) {
        // We don't have a Torrent File... it is something else
        AuditAction($cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html);
        $html = "";
    } else {
        // Get the name of the torrent, and make it the filename
        if (preg_match("/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match)) {
            $filelength = $html_preg_match[1];
            $filename = $html_preg_match[2];
            $cfg["save_torrent_name"] = substr($filename, 0, $filelength) . ".torrent";
        } else {
            $cfg["save_torrent_name"] = "unknown.torrent";
        }
    }
    return $html;
}
Example #27
0
 /**
  * process a request
  */
 function instance_processRequest()
 {
     global $cfg, $db;
     // type-switch
     switch ($this->_type) {
         case "all":
             if (!($this->_format == "txt" && $this->_header == 0)) {
                 $this->_transferHeads = getTransferListHeadArray();
             }
             $this->_indent = " ";
             // xfer-init
             if ($cfg['xfer_realtime'] == 0) {
                 $cfg['xfer_realtime'] = 1;
                 // set xfer-newday
                 Xfer::setNewday();
             }
             $this->_transferList = getTransferListArray();
             $this->_initServerStats();
             $this->_initXferStats();
             $this->_initUserStats();
             break;
         case "server":
             $this->_indent = "";
             $this->_transferList = getTransferListArray();
             $this->_initServerStats();
             break;
         case "xfer":
             $this->_indent = "";
             // xfer-init
             if ($cfg['xfer_realtime'] == 0) {
                 $cfg['xfer_realtime'] = 1;
                 // set xfer-newday
                 Xfer::setNewday();
             }
             $this->_transferList = getTransferListArray();
             $this->_initXferStats();
             break;
         case "transfers":
             $this->_indent = "";
             $this->_transferList = getTransferListArray();
             if (!($this->_format == "txt" && $this->_header == 0)) {
                 $this->_transferHeads = getTransferListHeadArray();
             }
             break;
         case "transfer":
             // transfer-id
             if (empty($this->_transferID)) {
                 @error("missing params", "stats.php", "", array('i'));
             }
             // validate transfer
             if (tfb_isValidTransfer($this->_transferID) !== true) {
                 AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $this->_transferID);
                 @error("Invalid Transfer", "", "", array($this->_transferID));
             }
             $this->_indent = "";
             $this->_transferDetails = getTransferDetails($this->_transferID, false);
             break;
         case "users":
             $this->_indent = "";
             $this->_initUserStats();
             break;
         case "usage":
             $this->_sendUsage();
     }
     // action
     switch ($this->_format) {
         case "xml":
             $this->_sendXML();
         case "rss":
             $this->_sendRSS();
         case "txt":
             $this->_sendTXT();
     }
 }
 /**
  * _maintenanceDatabase
  */
 function _maintenanceDatabase()
 {
     global $cfg, $db;
     // output
     $this->_outputMessage("database-maintenance...\n");
     /* tf_transfers */
     $this->_countProblems = 0;
     $this->_countFixed = 0;
     // output
     $this->_outputMessage("table-maintenance : tf_transfers\n");
     // running-flag
     $sql = "SELECT transfer FROM tf_transfers WHERE running = '1'";
     $recordset = $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $rc = $recordset->RecordCount();
     if ($rc > 0) {
         while (list($tname) = $recordset->FetchRow()) {
             if (!isTransferRunning($tname)) {
                 $this->_countProblems++;
                 // t is not running, reset running-flag
                 $this->_outputMessage("reset of running-flag for transfer which is not running : " . $tname . "\n");
                 $sql = "UPDATE tf_transfers SET running = '0' WHERE transfer = " . $db->qstr($tname);
                 $db->Execute($sql);
                 $this->_countFixed++;
                 // output
                 $this->_outputMessage("done.\n");
             }
         }
     }
     // empty hash
     $sql = "SELECT transfer FROM tf_transfers WHERE hash = ''";
     $recordset = $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $rc = $recordset->RecordCount();
     if ($rc > 0) {
         $this->_countProblems += $rc;
         while (list($tname) = $recordset->FetchRow()) {
             // t has no hash, update
             $this->_outputMessage("updating transfer which has empty hash : " . $tname . "\n");
             // get hash
             $thash = getTransferHash($tname);
             // update
             if (!empty($thash)) {
                 $sql = "UPDATE tf_transfers SET hash = " . $db->qstr($thash) . " WHERE transfer = " . $db->qstr($tname);
                 $db->Execute($sql);
                 $this->_countFixed++;
                 // output
                 $this->_outputMessage("done.\n");
             }
         }
     }
     // empty datapath
     $sql = "SELECT transfer FROM tf_transfers WHERE datapath = ''";
     $recordset = $db->Execute($sql);
     if ($db->ErrorNo() != 0) {
         dbError($sql);
     }
     $rc = $recordset->RecordCount();
     if ($rc > 0) {
         $this->_countProblems += $rc;
         while (list($tname) = $recordset->FetchRow()) {
             // t has no datapath, update
             $this->_outputMessage("updating transfer which has empty datapath : " . $tname . "\n");
             // get datapath
             $tDatapath = getTransferDatapath($tname);
             // update
             if ($tDatapath != "") {
                 $sql = "UPDATE tf_transfers SET datapath = " . $db->qstr($tDatapath) . " WHERE transfer = " . $db->qstr($tname);
                 $db->Execute($sql);
                 $this->_countFixed++;
                 // output
                 $this->_outputMessage("done.\n");
             } else {
                 // output
                 $this->_outputMessage("cannot get datapath for " . $tname . ".\n");
             }
         }
     }
     // output + log
     if ($this->_countProblems == 0) {
         // output
         $this->_outputMessage("no problems found.\n");
     } else {
         // DEBUG : log
         $msg = "found and fixed problems in tf_transfers : " . $this->_countFixed . "/" . $this->_countProblems;
         if ($cfg['debuglevel'] > 0) {
             AuditAction($cfg["constants"]["debug"], "database-maintenance : table-maintenance : " . $msg);
         }
         // output
         $this->_outputMessage($msg . "\n");
     }
     /* tf_transfer_totals */
     $this->_countProblems = 0;
     $this->_countFixed = 0;
     // output
     $this->_outputMessage("table-maintenance : tf_transfer_totals\n");
     $this->_countProblems = $db->GetOne("SELECT COUNT(*) FROM tf_transfer_totals WHERE tid = ''");
     if ($this->_countProblems !== false && $this->_countProblems > 0) {
         // output
         $this->_outputMessage("found " . $this->_countProblems . " invalid entries, deleting...\n");
         $sql = "DELETE FROM tf_transfer_totals WHERE tid = ''";
         $result = $db->Execute($sql);
         if ($db->ErrorNo() != 0) {
             dbError($sql);
         }
         $this->_countFixed = $db->Affected_Rows();
         // output
         $this->_outputMessage("done.\n");
         $rCount = $this->_countFixed !== false ? $this->_countFixed : $this->_countProblems;
         // DEBUG : log
         $msg = "found and removed invalid totals-entries from tf_transfer_totals : " . $rCount . "/" . $this->_countProblems;
         if ($cfg['debuglevel'] > 0) {
             AuditAction($cfg["constants"]["debug"], "database-maintenance : table-maintenance : " . $msg);
         }
         // output
         $this->_outputMessage($msg . "\n");
     } else {
         // output
         $this->_outputMessage("no problems found.\n");
     }
     // prune db
     $this->_maintenanceDatabasePrune();
     /* done */
     $this->_outputMessage("database-maintenance done.\n");
 }
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 To read the license please visit http://www.gnu.org/copyleft/gpl.html

*******************************************************************************/
include_once "config.php";
include_once "functions.php";
include_once "searchEngines/SearchEngineBase.php";
// is enabled ?
if ($cfg["enable_search"] != 1) {
    AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to use search");
    showErrorPage("search is disabled.");
}
// Go get the if this is a search request. go get the data and produce output.
$hideSeedless = getRequestVar('hideSeedless');
if (!empty($hideSeedless)) {
    $_SESSION['hideSeedless'] = $hideSeedless;
}
if (!isset($_SESSION['hideSeedless'])) {
    $_SESSION['hideSeedless'] = 'no';
}
$hideSeedless = $_SESSION['hideSeedless'];
$pg = getRequestVar('pg');
$searchEngine = getRequestVar('searchEngine');
if (empty($searchEngine)) {
    $searchEngine = $cfg["searchEngine"];
 /**
  * dequeueTorrent
  * @param $torrent name of the torrent
  */
 function dequeueTorrent($torrent)
 {
     $torrent = urldecode($torrent);
     $alias_file = getRequestVar('alias_file');
     if (isTorrentRunning($torrent)) {
         // torrent has been started... try and kill it.
         AuditAction($this->cfg["constants"]["unqueued_torrent"], $torrent . "has been started -- TRY TO KILL IT");
         header("location: index.php?alias_file=" . $alias_file . "&kill=true&kill_torrent=" . urlencode($torrent));
         exit;
     } else {
         if ($this->isQueueManagerRunning()) {
             // send command to daemon
             $this->sendQueueCommand('remove ' . substr($torrent, 0, -8));
             // flag the torrent as stopped (in db)
             stopTorrentSettings($torrent);
             // update the stat file.
             parent::updateStatFile($torrent, $alias_file);
             // log
             AuditAction($this->cfg["constants"]["unqueued_torrent"], $torrent);
         } else {
             header("location: admin.php?op=queueSettings");
             exit;
         }
     }
 }