Esempio n. 1
0
 /**
  * This method is called there is activity in the API socket.
  */
 public function onApiActivity($type)
 {
     /* Accept incoming requests and handle them as child processes */
     $client = @stream_socket_accept($this->apisocket);
     if ($client !== false) {
         $clientHandler = new ClientHandler($client, $this->logger);
         // Read the input from the client
         $apiRequest = $clientHandler->readPacket();
         if ($apiRequest->version != API_VERSION) {
             $clientHandler->writePacket(new APIResponse(API_INVALID_VERSION, "API version must be: " . API_VERSION));
             return;
         }
         $userPassword = $this->preferences->get($apiRequest->username, 'apipassword');
         $isSuperAdmin = $apiRequest->username == $this->chatBot->vars['SuperAdmin'];
         $fromLocalHost = $clientHandler->getClientAddress() == '127.0.0.1';
         // password is not needed for superadmin from 'localhost' if the superadmin hasn't set password yet
         $noPasswordNeeded = $isSuperAdmin && $fromLocalHost && !$userPassword;
         if (!$noPasswordNeeded) {
             if ($userPassword === false) {
                 $clientHandler->writePacket(new APIResponse(API_UNSET_PASSWORD, "Password has not been set for this user."));
                 return;
             } else {
                 if ($userPassword != $apiRequest->password) {
                     $clientHandler->writePacket(new APIResponse(API_INVALID_PASSWORD, "Password was incorrect."));
                     return;
                 }
             }
         }
         if ($apiRequest->type == API_SIMPLE_MSG) {
             $type = 'msg';
             $apiReply = new APISimpleReply();
         } else {
             if ($apiRequest->type == API_ADVANCED_MSG) {
                 $type = 'api';
                 $apiReply = new APIAdvancedReply();
             } else {
                 $clientHandler->writePacket(new APIResponse(API_INVALID_REQUEST_TYPE, "Invalid request type."));
                 return;
             }
         }
         try {
             $responseCode = $this->process($type, $apiRequest->command, $apiRequest->username, $apiReply);
             $response = new APIResponse($responseCode, $apiReply->getOutput());
         } catch (APIException $e) {
             $response = new APIResponse(API_EXCEPTION, $e->getResponseMessage());
         } catch (Exception $e) {
             $response = new APIResponse(API_EXCEPTION, $e->getMessage());
         }
         $clientHandler->writePacket($response);
     }
 }
Esempio n. 2
0
 public function __construct($socket, $opts)
 {
     parent::__construct($socket);
     $this->Terminator = "\r\n\r\n";
     $this->Callback = $opts;
     $this->Request = NULL;
     $this->RequestSplit = NULL;
     $this->RequestHeaders = array();
     $this->RequestBytesRead = 0;
     $this->ContentLength = 0;
     $this->ContentType = NULL;
     $this->MIMEBoundary = NULL;
 }
/**
 * pieTransferTotals
 */
function image_pieTransferTotals()
{
    global $cfg;
    // transfer-id
    $transfer = tfb_getRequestVar('transfer');
    if (empty($transfer)) {
        Image::paintNoOp();
    }
    // validate transfer
    if (tfb_isValidTransfer($transfer) !== true) {
        AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $transfer);
        Image::paintNoOp();
    }
    // client-handler + totals
    $ch = ClientHandler::getInstance(getTransferClient($transfer));
    $totals = $ch->getTransferTotal($transfer);
    // draw image
    Image::paintPie3D(202, 160, 100, 50, 200, 100, 20, Image::stringToRGBColor($cfg["body_data_bg"]), array($totals["uptotal"] + 1, $totals["downtotal"] + 1), array(array('r' => 0x0, 'g' => 0xeb, 'b' => 0xc), array('r' => 0x10, 'g' => 0x0, 'b' => 0xff)), array('Up : ' . @formatFreeSpace($totals["uptotal"] / 1048576), 'Down : ' . @formatFreeSpace($totals["downtotal"] / 1048576)), 48, 130, 2, 14);
}
 /**
  * gets ary of running bittorrent-clients
  *
  * @return client-ary
  */
 function getRunningClients()
 {
     return parent::getRunningClients();
 }
/**
 * processes
 *
 * @param $action
 */
function sa_processes($action = "")
{
    global $cfg, $error, $statusImage, $statusMessage, $htmlTitle, $htmlTop, $htmlMain;
    if ($action == "") {
        return;
    }
    buildPage("p");
    switch ($action) {
        case "0":
            // Processes-main
            $htmlTitle = "Processes";
            $htmlMain .= '<p>';
            $htmlMain .= 'View currently running torrentflux-b4rt processes:<br><br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?p=1"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="All" border="0"> All</a> - detailed process list';
            $htmlMain .= '<p>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?p=2"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Transfers" border="0"> Transfers</a> - simple list of running transfers with option to force stop individual transfers';
            $htmlMain .= '<br><br>';
            break;
        case "1":
            // Processes - All
            $htmlTitle = "Processes - All";
            $htmlMain .= '<div align="left" id="BodyLayer" name="BodyLayer" style="border: thin solid ' . $cfg['main_bgcolor'] . '; position:relative; width:740; height:498; padding-left: 5px; padding-right: 5px; z-index:1; overflow: scroll; visibility: visible">';
            $htmlMain .= '<br>';
            $htmlMain .= '<p><strong>fluxd</strong>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(shell_exec("ps auxww | " . $cfg['bin_grep'] . " fluxd | " . $cfg['bin_grep'] . " -v grep"));
            $htmlMain .= '</pre>';
            $htmlMain .= '<p><strong>fluazu</strong>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(shell_exec("ps auxww | " . $cfg['bin_grep'] . " fluazu.py | " . $cfg['bin_grep'] . " -v grep"));
            $htmlMain .= '</pre>';
            $clients = array('tornado', 'transmission', 'mainline', 'wget', 'nzbperl', 'azureus');
            foreach ($clients as $client) {
                $ch = ClientHandler::getInstance($client);
                $htmlMain .= '<p><strong>' . $client . '</strong>';
                $htmlMain .= '<br>';
                $htmlMain .= '<pre>';
                $htmlMain .= tfb_htmlencode(shell_exec("ps auxww | " . $cfg['bin_grep'] . " " . tfb_shellencode($ch->binClient) . " | " . $cfg['bin_grep'] . " -v grep"));
                $htmlMain .= '</pre>';
                $htmlMain .= '<br>';
                $htmlMain .= '<pre>';
                $htmlMain .= $ch->runningProcessInfo();
                $htmlMain .= '</pre>';
            }
            $htmlMain .= '</div>';
            break;
        case "2":
            // Processes - Transfers
            $htmlTitle = "Processes - Transfers";
            $htmlMain .= '<div align="left" id="BodyLayer" name="BodyLayer" style="border: thin solid ' . $cfg['main_bgcolor'] . '; position:relative; width:740; height:498; padding-left: 5px; padding-right: 5px; z-index:1; overflow: scroll; visibility: visible">';
            $htmlMain .= '<br>
				<table width="700" border=1 bordercolor="' . $cfg["table_admin_border"] . '" cellpadding="2" cellspacing="0" bgcolor="' . $cfg["table_data_bg"] . '">
			    <tr><td colspan=6 bgcolor="' . $cfg["table_header_bg"] . '" background="themes/' . $cfg["theme"] . '/images/bar.gif">
			    	<table width="100%" cellpadding=0 cellspacing=0 border=0><tr><td><font class="title"> Running Items </font></td></tr></table>
			    </td></tr>
			    <tr>
			        <td bgcolor="' . $cfg["table_header_bg"] . '" width="15%" nowrap><div align=center class="title">' . $cfg["_USER"] . '</div></td>
			        <td bgcolor="' . $cfg["table_header_bg"] . '" nowrap><div align=center class="title">' . $cfg["_FILE"] . '</div></td>
			        <td bgcolor="' . $cfg["table_header_bg"] . '" width="1%" nowrap><div align=center class="title">' . $cfg["_FORCESTOP"] . '</div></td>
			    </tr>
			';
            $running = getRunningClientProcesses();
            foreach ($running as $rng) {
                $rt = RunningTransfer::getInstance($rng['pinfo'], $rng['client']);
                $htmlMain .= '<tr bgcolor="' . $cfg["table_header_bg"] . '">';
                $htmlMain .= '<td nowrap><div class="tiny">';
                $htmlMain .= tfb_htmlencodekeepspaces($rt->transferowner);
                $htmlMain .= '</div></td>';
                $htmlMain .= '<td nowrap><div align=center><div class="tiny" align="left">';
                $htmlMain .= $rt->transferFile;
                $htmlMain .= '</div></td>';
                $htmlMain .= '<td nowrap>';
                $htmlMain .= '<a href="dispatcher.php?action=forceStop&riid=_referer_';
                $htmlMain .= "&transfer=" . urlencode($rt->transferFile);
                $htmlMain .= "&pid=" . $rt->processId;
                $htmlMain .= '"><img src="themes/' . $cfg["theme"] . '/images/kill.gif" width="16" height="16" title="' . $cfg['_FORCESTOP'] . '" border="0"></a></td>';
                $htmlMain .= '</tr>';
            }
            $htmlMain .= '</table>';
            $htmlMain .= '</div>';
            break;
    }
    printPage();
    exit;
}
     $tmpl->setvar('who_w', shell_exec("w"));
     $tmpl->setvar('who_free', shell_exec("free -mo"));
     // drivespace-bar
     tmplSetDriveSpaceBar();
     break;
     // ps
 // ps
 case "ps":
     // set vars
     if ($cfg['isAdmin']) {
         // array with all clients
         $clients = array('tornado', 'transmission', 'mainline', 'wget', 'nzbperl', 'azureus');
         // get informations
         $process_list = array();
         foreach ($clients as $client) {
             $ch = ClientHandler::getInstance($client);
             array_push($process_list, array('client' => $client, 'RunningProcessInfo' => $ch->runningProcessInfo(), 'pinfo' => shell_exec("ps auxww | " . $cfg['bin_grep'] . " " . tfb_shellencode($ch->binClient) . " | " . $cfg['bin_grep'] . " -v grep")));
         }
         $tmpl->setloop('process_list', $process_list);
     }
     // drivespace-bar
     tmplSetDriveSpaceBar();
     break;
     // netstat
 // netstat
 case "netstat":
     // set vars
     if ($cfg['isAdmin']) {
         // set vars
         $tmpl->setvar('netstatConnectionsSum', netstatConnectionsSum());
         $tmpl->setvar('netstatPortList', netstatPortList());
/**
 * get info of running clients (via call to ps)
 *
 * @param $client
 * @return string
 */
function getRunningClientProcessInfo($client = '')
{
    // client-array
    $clients = $client == '' ? array('tornado', 'transmission', 'mainline', 'wget', 'nzbperl', 'azureus') : array($client);
    // get clients
    $retVal = "";
    foreach ($clients as $client) {
        // client-handler
        $ch = ClientHandler::getInstance($client);
        $retVal .= $ch->runningProcessInfo();
    }
    // return
    return $retVal;
}
Esempio n. 8
0
*******************************************************************************/
// prevent direct invocation
if (!isset($cfg['user']) || isset($_REQUEST['cfg'])) {
    @ob_end_clean();
    @header("location: ../../index.php");
    exit;
}
/******************************************************************************/
// common functions
require_once 'inc/functions/functions.common.php';
// transfer functions
require_once 'inc/functions/functions.transfer.php';
// init template-instance
tmplInitializeInstance($cfg["theme"], "page.transferDetails.tmpl");
// init transfer
transfer_init();
// init ch-instance
$ch = ClientHandler::getInstance(getTransferClient($transfer));
// load settings, default if settings could not be loaded (fresh transfer)
if ($ch->settingsLoad($transfer) !== true) {
    $ch->settingsDefault();
}
// set details vars
transfer_setDetailsVars();
// title + foot
tmplSetFoot(false);
tmplSetTitleBar($transferLabel . " - Details", false);
// iid
tmplSetIidVars();
// parse template
$tmpl->pparse();
Esempio n. 9
0
 /**
  * set transfer setting
  *
  * @param $transfer
  * @param $key
  * @param $val
  * @param $options
  * @return mixed
  */
 function _tset($transfer, $key, $val, $options)
 {
     global $cfg;
     // check transfer
     if (!transferExists($transfer)) {
         $this->_outputError("transfer does not exist.\n");
         return false;
     }
     // check params
     $settingsKeys = array('uprate' => 'NUMBER', 'downrate' => 'NUMBER', 'completion' => 'BOOL', 'sharekill' => 'NUMBER');
     if (!array_key_exists($key, $settingsKeys)) {
         $this->_outputError("invalid settings-key: " . $key . "\n");
         return false;
     }
     if (strlen($val) < 1) {
         $this->_outputError("value for " . $key . " invalid.\n");
         return false;
     }
     switch ($settingsKeys[$key]) {
         case 'NUMBER':
             if (!preg_match('/^[0-9\\-]+$/D', $val)) {
                 $this->_outputError("value for " . $key . " must be a number: " . $val . "\n");
                 return false;
             }
             break;
         case 'BOOL':
             $val = strtolower($val);
             if ($val != 'true' && $val != 'false') {
                 $this->_outputError("value for " . $key . " must be true or false: " . $val . "\n");
                 return false;
             }
             break;
     }
     // set user
     $cfg["user"] = getOwner($transfer);
     // output
     $this->_outputMessage("Setting " . $key . " to " . $val . " for " . $transfer . " for user " . $cfg["user"] . "...\n");
     // init ch-instance
     $ch = ClientHandler::getInstance(getTransferClient($transfer));
     // load settings, default if settings could not be loaded (fresh transfer)
     if ($ch->settingsLoad($transfer) !== true) {
         $ch->settingsDefault();
     }
     // autosend
     $send = strpos($options, 's') !== false && isTransferRunning($transfer);
     // set setting
     switch ($key) {
         case 'uprate':
             if ($ch->rate != $val) {
                 $ch->setRateUpload($transfer, $val, $send);
                 break;
             } else {
                 $this->_outputMessage("no changes.\n");
                 return false;
             }
         case 'downrate':
             if ($ch->drate != $val) {
                 $ch->setRateDownload($transfer, $val, $send);
                 break;
             } else {
                 $this->_outputMessage("no changes.\n");
                 return false;
             }
         case 'completion':
             if (strtolower($ch->runtime) != $val) {
                 $ch->setRuntime($transfer, $val == 'true' ? 'True' : 'False', $send);
                 break;
             } else {
                 $this->_outputMessage("no changes.\n");
                 return false;
             }
         case 'sharekill':
             if ($ch->sharekill != $val) {
                 $ch->setSharekill($transfer, $val, $send);
                 break;
             } else {
                 $this->_outputMessage("no changes.\n");
                 return false;
             }
     }
     // save
     $ch->settingsSave();
     // output + return
     if ($send) {
         $this->_outputMessage("settings saved + changes sent to client.\n");
     } else {
         $this->_outputMessage("settings saved.\n");
     }
     return true;
 }
Esempio n. 10
0
}
// =============================================================================
// if a file was set to be deleted then delete it
$delfile = getRequestVar('delfile');
if (!$delfile == '') {
    deleteTorrent($delfile, getRequestVar('alias_file'));
    header("location: index.php");
    exit;
}
// =============================================================================
// Did the user select the option to kill a running torrent?
$killTorrent = getRequestVar('kill_torrent');
if (!$killTorrent == '') {
    $return = getRequestVar('return');
    include_once "ClientHandler.php";
    $clientHandler = ClientHandler::getClientHandlerInstance($cfg, getTorrentClient($killTorrent));
    $clientHandler->stopTorrentClient($killTorrent, getRequestVar('alias_file'), getRequestVar('kill'), $return);
    if (!empty($return)) {
        header("location: " . $return . ".php?op=queueSettings");
    } else {
        header("location: index.php");
    }
    exit;
}
// =============================================================================
// Did the user select the option to remove a torrent from the Queue?
if (isset($_REQUEST["dQueue"])) {
    $QEntry = getRequestVar('QEntry');
    include_once "QueueManager.php";
    $queueManager = QueueManager::getQueueManagerInstance($cfg);
    $queueManager->dequeueTorrent($QEntry);
 /**
  * get ClientHandler-instance
  *
  * @param $client client-type
  * @return ClientHandler
  */
 function getInstance($client = "")
 {
     // create and return object-instance
     switch ($client) {
         case "tornado":
             require_once 'inc/classes/ClientHandler.tornado.php';
             return new ClientHandlerTornado();
         case "transmission":
             require_once 'inc/classes/ClientHandler.transmission.php';
             return new ClientHandlerTransmission();
         case "mainline":
             require_once 'inc/classes/ClientHandler.mainline.php';
             return new ClientHandlerMainline();
         case "azureus":
             require_once 'inc/classes/ClientHandler.azureus.php';
             return new ClientHandlerAzureus();
         case "wget":
             require_once 'inc/classes/ClientHandler.wget.php';
             return new ClientHandlerWget();
         case "nzbperl":
             require_once 'inc/classes/ClientHandler.nzbperl.php';
             return new ClientHandlerNzbperl();
         default:
             global $cfg;
             return ClientHandler::getInstance($cfg["btclient"]);
     }
 }
/**
 * setFileVars
 */
function transfer_setFileVars()
{
    global $cfg, $tmpl, $transfer, $transferLabel, $ch;
    // set vars for transfer
    $transferFilesList = array();
    switch ($ch->type) {
        case "torrent":
            require_once "inc/classes/BDecode.php";
            $tFile = $cfg["transfer_file_path"] . $transfer;
            if ($fd = @fopen($tFile, "rd")) {
                $alltorrent = @fread($fd, @filesize($tFile));
                $btmeta = @BDecode($alltorrent);
                @fclose($fd);
            }
            $transferSizeSum = 0;
            if (isset($btmeta) && is_array($btmeta) && isset($btmeta['info'])) {
                if (array_key_exists('files', $btmeta['info'])) {
                    foreach ($btmeta['info']['files'] as $filenum => $file) {
                        $name = is_array($file['path']) ? implode("/", $file['path']) : $file['path'];
                        $size = isset($file['length']) && is_numeric($file['length']) ? $file['length'] : 0;
                        $transferSizeSum += $size;
                        array_push($transferFilesList, array('name' => $name, 'size' => $size != 0 ? formatBytesTokBMBGBTB($size) : 0));
                    }
                } else {
                    $size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
                    $transferSizeSum += $size;
                    array_push($transferFilesList, array('name' => $btmeta["info"]["name"], 'size' => formatBytesTokBMBGBTB($size)));
                }
            }
            if (empty($transferFilesList)) {
                $tmpl->setvar('transferFilesString', "Empty");
                $tmpl->setvar('transferFileCount', count($btmeta['info']['files']));
            } else {
                $tmpl->setloop('transferFilesList', $transferFilesList);
                $tmpl->setvar('transferFileCount', count($transferFilesList));
            }
            $tmpl->setvar('transferSizeSum', $transferSizeSum > 0 ? formatBytesTokBMBGBTB($transferSizeSum) : 0);
            return;
        case "wget":
            $ch = ClientHandler::getInstance('wget');
            $ch->setVarsFromFile($transfer);
            $transferSizeSum = 0;
            if (!empty($ch->url)) {
                require_once "inc/classes/SimpleHTTP.php";
                $size = SimpleHTTP::getRemoteSize($ch->url);
                $transferSizeSum += $size;
                array_push($transferFilesList, array('name' => $ch->url, 'size' => formatBytesTokBMBGBTB($size)));
            }
            if (empty($transferFilesList)) {
                $tmpl->setvar('transferFilesString', "Empty");
                $tmpl->setvar('transferFileCount', 0);
            } else {
                $tmpl->setloop('transferFilesList', $transferFilesList);
                $tmpl->setvar('transferFileCount', count($transferFilesList));
            }
            $tmpl->setvar('transferSizeSum', $transferSizeSum > 0 ? formatBytesTokBMBGBTB($transferSizeSum) : 0);
            return;
        case "nzb":
            require_once "inc/classes/NZBFile.php";
            $nzb = new NZBFile($transfer);
            $transferSizeSum = 0;
            if (empty($nzb->files)) {
                $tmpl->setvar('transferFilesString', "Empty");
                $tmpl->setvar('transferFileCount', 0);
            } else {
                foreach ($nzb->files as $file) {
                    $transferSizeSum += $file['size'];
                    array_push($transferFilesList, array('name' => $file['name'], 'size' => formatBytesTokBMBGBTB($file['size'])));
                }
                $tmpl->setloop('transferFilesList', $transferFilesList);
                $tmpl->setvar('transferFileCount', $nzb->filecount);
            }
            $tmpl->setvar('transferSizeSum', $transferSizeSum > 0 ? formatBytesTokBMBGBTB($transferSizeSum) : 0);
            return;
    }
}
Esempio n. 13
0
 /**
  * get ClientHandler-instance
  *
  * @param $client client-type
  * @return ClientHandler
  */
 function getInstance($client = "")
 {
     // create and return object-instance
     switch ($client) {
         case "tornado":
             require_once 'inc/classes/ClientHandler.tornado.php';
             $ch = new ClientHandlerTornado();
             break;
         case "transmission":
             //patched transmissioncli
             require_once 'inc/classes/ClientHandler.transmission.php';
             $ch = new ClientHandlerTransmission();
             break;
         case "transmissionrpc":
             require_once 'inc/classes/ClientHandler.transmissionrpc.php';
             $ch = new ClientHandlerTransmissionRPC();
             break;
         case "azureus":
             global $cfg;
             if ($cfg['vuze_rpc_enable']) {
                 //vuze rpc torrents are compatible with azureus (both in vuze)
                 //so we can ask vuze for old fluazu transfers stats
                 require_once 'inc/classes/ClientHandler.vuzerpc.php';
                 $ch = new ClientHandlerVuzeRPC();
             } else {
                 //fluazu/dopal/xml_http (slow)
                 require_once 'inc/classes/ClientHandler.azureus.php';
                 $ch = new ClientHandlerAzureus();
             }
             break;
         case "vuzerpc":
             //xmwebui (json) (fast)
             require_once 'inc/classes/ClientHandler.vuzerpc.php';
             $ch = new ClientHandlerVuzeRPC();
             break;
         case "wget":
             require_once 'inc/classes/ClientHandler.wget.php';
             $ch = new ClientHandlerWget();
             break;
         case "nzbperl":
             require_once 'inc/classes/ClientHandler.nzbperl.php';
             $ch = new ClientHandlerNzbperl();
             break;
         case "mainline":
             require_once 'inc/classes/ClientHandler.mainline.php';
             $ch = new ClientHandlerMainline();
             break;
         default:
             global $cfg;
             $ch = ClientHandler::getInstance($cfg["btclient"]);
     }
     return $ch;
 }
Esempio n. 14
0
/**
 * Function with which metafiles are uploaded and injected
 *
 * @deprecated
 */
function compat_tf_processUpload()
{
    global $cfg;
    $filename = "";
    $uploadMessages = array();
    if (isset($_FILES['upload_file']) && !empty($_FILES['upload_file']['name'])) {
        $filename = stripslashes($_FILES['upload_file']['name']);
        $filename = tfb_cleanFileName($filename);
        if ($filename === false) {
            // invalid file
            array_push($uploadMessages, "The type of file you are uploading is not allowed.");
            array_push($uploadMessages, "\nvalid file-extensions: ");
            array_push($uploadMessages, $cfg["file_types_label"]);
        } else {
            // file is valid
            if (substr($filename, -5) == ".wget") {
                // is enabled ?
                if ($cfg["enable_wget"] == 0) {
                    AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to upload wget-file " . $filename);
                    @error("wget is disabled", "", "");
                } else {
                    if ($cfg["enable_wget"] == 1) {
                        if (!$cfg['isAdmin']) {
                            AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to upload wget-file " . $filename);
                            @error("wget is disabled for users", "", "");
                        }
                    }
                }
            } else {
                if (substr($filename, -4) == ".nzb") {
                    // is enabled ?
                    if ($cfg["enable_nzbperl"] == 0) {
                        AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to upload nzb-file " . $filename);
                        @error("nzbperl is disabled", "", "");
                    } else {
                        if ($cfg["enable_nzbperl"] == 1) {
                            if (!$cfg['isAdmin']) {
                                AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to upload nzb-file " . $filename);
                                @error("nzbperl is disabled for users", "", "");
                            }
                        }
                    }
                }
            }
            if ($_FILES['upload_file']['size'] <= $cfg["upload_limit"] && $_FILES['upload_file']['size'] > 0) {
                //FILE IS BEING UPLOADED
                if (@is_file($cfg["transfer_file_path"] . $filename)) {
                    // Error
                    array_push($uploadMessages, "the file " . $filename . " already exists on the server.");
                } else {
                    if (@move_uploaded_file($_FILES['upload_file']['tmp_name'], $cfg["transfer_file_path"] . $filename)) {
                        @chmod($cfg["transfer_file_path"] . $filename, 0644);
                        AuditAction($cfg["constants"]["file_upload"], $filename);
                        // inject
                        injectTransfer($filename);
                        // instant action ?
                        $actionId = tfb_getRequestVar('aid');
                        if ($actionId > 1) {
                            $ch = ClientHandler::getInstance(getTransferClient($filename));
                            switch ($actionId) {
                                case 3:
                                    $ch->start($filename, false, true);
                                    break;
                                case 2:
                                    $ch->start($filename, false, false);
                                    break;
                            }
                            if (count($ch->messages) > 0) {
                                $uploadMessages = array_merge($uploadMessages, $ch->messages);
                            }
                        }
                    } else {
                        array_push($uploadMessages, "File not uploaded, file could not be found or could not be moved: " . $cfg["transfer_file_path"] . $filename);
                    }
                }
            } else {
                array_push($uploadMessages, "File not uploaded, file size limit is " . $cfg["upload_limit"] . ". file has " . $_FILES['upload_file']['size']);
            }
        }
    }
    if (count($uploadMessages) > 0) {
        AuditAction($cfg["constants"]["error"], $cfg["constants"]["file_upload"] . " :: " . $filename);
        @error("There were Problems", "", "", $uploadMessages);
    }
}
/**
 * netstatHostList
 *
 * @return string
 */
function netstatHostList()
{
    global $cfg;
    $retStr = "";
    switch ($cfg["_OS"]) {
        case 1:
            // linux
            // not time-critical (only used on allServices-page), use the
            // generic and correct way :
            // array with all clients
            $clients = array('tornado', 'transmission', 'wget', 'nzbperl', 'azureus');
            // get informations
            foreach ($clients as $client) {
                $ch = ClientHandler::getInstance($client);
                $retStr .= shell_exec($cfg['bin_netstat'] . " -e -p --tcp --numeric-hosts --numeric-ports 2> /dev/null | " . $cfg['bin_grep'] . " -v root | " . $cfg['bin_grep'] . " -v 127.0.0.1 | " . $cfg['bin_grep'] . " " . $ch->binSocket . " | " . $cfg['bin_awk'] . " '{print \$5}'");
            }
            break;
        case 2:
            // bsd
            $processUser = posix_getpwuid(posix_geteuid());
            $webserverUser = $processUser['name'];
            $retStr .= shell_exec($cfg['bin_sockstat'] . " -4 -c | " . $cfg['bin_awk'] . " '/" . $webserverUser . ".+(python|transmissi|nzbperl|wget|java)/ {split(\$7, a, \":\"); print a[1]}'");
            break;
    }
    return $retStr;
}
Esempio n. 16
0
/**
 * pieTransferPeers
 */
function image_pieTransferPeers()
{
    global $cfg;
    // transfer-id
    $transfer = tfb_getRequestVar('transfer');
    if (empty($transfer)) {
        Image::paintNoOp();
    }
    // validate transfer
    $validTransfer = false;
    if (isHash($transfer)) {
        $hash = $transfer;
    } else {
        $hash = getTransferHash($transfer);
    }
    if ($cfg["transmission_rpc_enable"]) {
        require_once 'inc/functions/functions.rpc.transmission.php';
        $options = array('trackerStats', 'peers');
        $transTransfer = getTransmissionTransfer($hash, $options);
        // false if not found; TODO check if transmission enabled
        if (is_array($transTransfer)) {
            $validTransfer = true;
            $client = "transmissionrpc";
        }
    }
    if (!$validTransfer) {
        // If not found in transmission transfer
        if (tfb_isValidTransfer($transfer)) {
            // stat
            $sf = new StatFile($transfer);
            $seeds = trim($sf->seeds);
            $peers = trim($sf->peers);
            // client-switch + get peer-data
            $peerData = array();
            $peerData['seeds'] = 0;
            $peerData['peers'] = 0;
            $peerData['seedsLabel'] = $seeds != "" ? $seeds : 0;
            $peerData['peersLabel'] = $peers != "" ? $peers : 0;
            $client = getTransferClient($transfer);
            $validTransfer = true;
        }
    }
    if (!$validTransfer) {
        AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $transfer);
        Image::paintNoOp();
    }
    switch ($client) {
        case "tornado":
            if ($seeds != "") {
                if (strpos($seeds, "+") !== false) {
                    $seeds = preg_replace('/(\\d+)\\+.*/i', '${1}', $seeds);
                }
                if (is_numeric($seeds)) {
                    $peerData['seeds'] = $seeds;
                }
                $peerData['seedsLabel'] = $seeds;
            }
            if ($peers != "") {
                if (strpos($peers, "+") !== false) {
                    $peers = preg_replace('/(\\d+)\\+.*/i', '${1}', $peers);
                }
                if (is_numeric($peers)) {
                    $peerData['peers'] = $peers;
                }
                $peerData['peersLabel'] = $peers;
            }
            break;
        case "transmission":
        case "transmissionrpc":
            $peers = sizeof($transTransfer['peers']);
            $seeds = 0;
            foreach ($transTransfer['trackerStats'] as $tracker) {
                $seeds += $tracker['seederCount'] == -1 ? 0 : $tracker['seederCount'];
            }
            $peerData['seedsLabel'] = $seeds;
            $peerData['seeds'] = $seeds;
            $peerData['peersLabel'] = $peers;
            $peerData['peers'] = $peers;
            break;
        case "vuzerpc":
            if (empty($seeds) || empty($peers)) {
                $ch = ClientHandler::getInstance($client);
                $running = $ch->monitorRunningTransfers();
                $hash = strtoupper(getTransferHash($transfer));
                if (!empty($running[$hash])) {
                    $t = $running[$hash];
                    $peerData['seeds'] = $t['seeds'];
                    $peerData['seedsLabel'] = $t['seeds'];
                    $peerData['peers'] = $t['peers'];
                    $peerData['peersLabel'] = $t['peers'];
                }
            }
            break;
        case "azureus":
            if ($seeds != "") {
                if (strpos($seeds, "(") !== false) {
                    $seeds = preg_replace('/.*(\\d+) .*/i', '${1}', $seeds);
                }
                if (is_numeric($seeds)) {
                    $peerData['seeds'] = $seeds;
                }
                $peerData['seedsLabel'] = $seeds;
            }
            if ($peers != "") {
                if (strpos($peers, "(") !== false) {
                    $peers = preg_replace('/.*(\\d+) .*/i', '${1}', $peers);
                }
                if (is_numeric($peers)) {
                    $peerData['peers'] = $peers;
                }
                $peerData['peersLabel'] = $peers;
            }
            break;
        case "mainline":
            if ($seeds != "" && is_numeric($seeds)) {
                $peerData['seeds'] = $seeds;
                $peerData['seedsLabel'] = $seeds;
            }
            if ($peers != "" && is_numeric($peers)) {
                $peerData['peers'] = $peers;
                $peerData['peersLabel'] = $peers;
            }
            break;
        case "wget":
        case "nzbperl":
            $peerData['seeds'] = $seeds != "" ? $seeds : 0;
            $peerData['peers'] = $peers != "" ? $peers : 0;
            break;
        default:
            AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $transfer);
            Image::paintNoOp();
    }
    // draw image
    Image::paintPie3D(202, 160, 100, 50, 200, 100, 20, Image::stringToRGBColor($cfg["body_data_bg"]), array($peerData['seeds'] + 1.0E-5, $peerData['peers'] + 1.0E-5), image_getColors(), array('Seeds : ' . $peerData['seedsLabel'], 'Peers : ' . $peerData['peersLabel']), 58, 130, 2, 14);
}
 /**
  * _maintenanceTransfers
  *
  * @param $trestart
  * @return boolean
  */
 function _maintenanceTransfers($trestart = false)
 {
     global $cfg, $db, $transfers;
     // set var
     $this->_restartTransfers = $trestart;
     // output
     $this->_outputMessage("transfers-maintenance...\n");
     // sanity-check for transfers-dir
     if (!is_dir($cfg["transfer_file_path"])) {
         $this->state = MAINTENANCEANDREPAIR_STATE_ERROR;
         $msg = "invalid dir-settings. no dir : " . $cfg["transfer_file_path"];
         array_push($this->messages, $msg);
         $this->_outputError($msg . "\n");
         return false;
     }
     // pid-files of transfer-clients
     $pidFiles = array();
     if ($dirHandle = @opendir($cfg["transfer_file_path"])) {
         while (false !== ($file = @readdir($dirHandle))) {
             if (strlen($file) > 3 && substr($file, -4, 4) == ".pid") {
                 array_push($pidFiles, $file);
             }
         }
         @closedir($dirHandle);
     }
     // return if no pid-files found
     if (count($pidFiles) < 1) {
         $this->_outputMessage("no pid-files found.\n");
         $this->_outputMessage("transfers-maintenance done.\n");
         return true;
     }
     // get process-list
     $psString = trim(shell_exec("ps x -o pid='' -o ppid='' -o command='' -ww"));
     // test if client for pid is still up
     $this->_bogusTransfers = array();
     foreach ($pidFiles as $pidFile) {
         $transfer = substr($pidFile, 0, -4);
         if (stristr($psString, $transfer) === false) {
             if (getTransferClient($transfer) != "azureus") {
                 array_push($this->_bogusTransfers, $transfer);
             }
         }
     }
     // return if no stale pid-files
     $this->_countProblems = count($this->_bogusTransfers);
     if ($this->_countProblems < 1) {
         $this->_outputMessage("no stale pid-files found.\n");
         $this->_outputMessage("transfers-maintenance done.\n");
         return true;
     }
     /* repair the bogus clients */
     $this->_countFixed = 0;
     $this->_outputMessage("repairing died clients...\n");
     foreach ($this->_bogusTransfers as $transfer) {
         // output
         $this->_outputMessage("repairing " . $transfer . " ...\n");
         // set stopped flag in db
         stopTransferSettings($transfer);
         // rewrite stat-file
         $sf = new StatFile($transfer, getOwner($transfer));
         $sf->running = 0;
         $sf->percent_done = -100.0;
         $sf->time_left = 'Transfer Died';
         $sf->down_speed = 0;
         $sf->up_speed = 0;
         $sf->seeds = 0;
         $sf->peers = 0;
         $sf->write();
         // delete pid-file
         @unlink($cfg["transfer_file_path"] . $transfer . ".pid");
         // DEBUG : log the repair of the bogus transfer
         if ($cfg['debuglevel'] > 0) {
             AuditAction($cfg["constants"]["debug"], "transfers-maintenance : transfer repaired : " . $transfer);
         }
         // output
         $this->_outputMessage("done.\n");
         // count
         $this->_countFixed++;
     }
     // output
     if ($this->_countProblems > 0) {
         $this->_outputMessage("repaired transfers : " . $this->_countFixed . "/" . $this->_countProblems . "\n");
     }
     /* restart transfers */
     if ($this->_restartTransfers) {
         $this->_fixedTransfers = array();
         $this->_outputMessage("restarting died clients...\n");
         // hold current user
         $whoami = $this->_mode == MAINTENANCEANDREPAIR_MODE_CLI ? GetSuperAdmin() : $cfg["user"];
         foreach ($this->_bogusTransfers as $transfer) {
             // output
             $this->_outputMessage("Starting " . $transfer . " ...\n");
             // set current user to transfer-owner
             $cfg["user"] = getOwner($transfer);
             // clientHandler + start
             $ch = ClientHandler::getInstance(getTransferClient($transfer));
             $ch->start($transfer, false, FluxdQmgr::isRunning());
             // DEBUG : log the restart of the died transfer
             if ($cfg['debuglevel'] > 0) {
                 $staret = $ch->state == CLIENTHANDLER_STATE_OK ? "OK" : "FAILED";
                 AuditAction($cfg["constants"]["debug"], "transfers-maintenance : restarted transfer " . $transfer . " by " . $whoami . " : " . $staret);
             }
             if ($ch->state == CLIENTHANDLER_STATE_OK) {
                 // output
                 $this->_outputMessage("done.\n");
                 // add to ary
                 array_push($this->_fixedTransfers, $transfer);
                 // count
                 $this->_countFixed++;
             } else {
                 $this->messages = array_merge($this->messages, $ch->messages);
                 $this->_outputError(implode("\n", $ch->messages) . "\n");
             }
         }
         // set user back
         $cfg["user"] = $whoami;
         // output
         $this->_countFixed = count($this->_fixedTransfers);
         if ($this->_countFixed > 0) {
             $this->_outputMessage("restarted transfers : " . $this->_countFixed . "/" . $this->_countProblems . "\n");
         }
     }
     /* done */
     $this->_outputMessage("transfers-maintenance done.\n");
     // return
     return true;
 }
}
/******************************************************************************/
// common functions
require_once 'inc/functions/functions.common.php';
// transfer functions
require_once 'inc/functions/functions.transfer.php';
// init template-instance
tmplInitializeInstance($cfg["theme"], "page.transferSettings.tmpl");
// init transfer
transfer_init();
// request-vars
$saveop = tfb_getRequestVar('save');
$client = tfb_getRequestVar('client');
$isSave = $saveop == 1 ? true : false;
// init ch-instance
$ch = $client == "" ? ClientHandler::getInstance(getTransferClient($transfer)) : ClientHandler::getInstance($client);
// customize-vars
transfer_setCustomizeVars();
// load settings, default if settings could not be loaded (fresh transfer)
if ($ch->settingsLoad($transfer) !== true) {
    $ch->settingsDefault();
}
// set running-field
$ch->running = isTransferRunning($transfer) ? 1 : 0;
// save/display
if ($isSave) {
    /* save */
    // set save-var
    $tmpl->setvar('isSave', 1);
    // send to client
    $doSend = isset($_REQUEST['sendbox']) && $ch->running == 1 ? true : false;
Esempio n. 19
0
 /**
  * xfer update 1
  * add upload/download stats to the xfer array
  *
  * @param $entry
  * @param $transferowner
  * @param $client
  * @param $hash
  * @param $uptotal
  * @param $downtotal
  */
 function instance_update1($entry, $transferowner, $client, $hash, $uptotal, $downtotal)
 {
     global $cfg, $db;
     $ch = ClientHandler::getInstance($client);
     $transferTotalsCurrent = $ch->getTransferCurrentOP($entry, $hash, $uptotal, $downtotal);
     $this->_sumUsage($transferowner, $transferTotalsCurrent["downtotal"], $transferTotalsCurrent["uptotal"], 'total');
     $this->_sumUsage($transferowner, $transferTotalsCurrent["downtotal"], $transferTotalsCurrent["uptotal"], 'month');
     $this->_sumUsage($transferowner, $transferTotalsCurrent["downtotal"], $transferTotalsCurrent["uptotal"], 'week');
     $this->_sumUsage($transferowner, $transferTotalsCurrent["downtotal"], $transferTotalsCurrent["uptotal"], 'day');
     //XFER: if new day add upload/download totals to last date on record and subtract from today in SQL
     if ($this->xfer_newday != 0) {
         $this->xfer_newday = 2;
         $lastDate = $db->GetOne('SELECT date FROM tf_xfer ORDER BY date DESC');
         $sql = $db->GetOne("SELECT 1 FROM tf_xfer WHERE user_id = " . $db->qstr($transferowner) . " AND date = " . $db->qstr($lastDate)) ? "UPDATE tf_xfer SET download = download+" . @($transferTotalsCurrent["downtotal"] + 0) . ", upload = upload+" . @($transferTotalsCurrent["uptotal"] + 0) . " WHERE user_id = " . $db->qstr($transferowner) . " AND date = " . $db->qstr($lastDate) : "INSERT INTO tf_xfer (user_id,date,download,upload) values (" . $db->qstr($transferowner) . "," . $db->qstr($lastDate) . "," . @($transferTotalsCurrent["downtotal"] + 0) . "," . @($transferTotalsCurrent["uptotal"] + 0) . ")";
         $db->Execute($sql);
         $sql = $db->GetOne("SELECT 1 FROM tf_xfer WHERE user_id = " . $db->qstr($transferowner) . " AND date = " . $db->DBDate(time())) ? "UPDATE tf_xfer SET download = download-" . @($transferTotalsCurrent["downtotal"] + 0) . ", upload = upload-" . @($transferTotalsCurrent["uptotal"] + 0) . " WHERE user_id = " . $db->qstr($transferowner) . " AND date = " . $db->DBDate(time()) : "INSERT INTO tf_xfer (user_id,date,download,upload) values (" . $db->qstr($transferowner) . "," . $db->DBDate(time()) . "," . @($transferTotalsCurrent["downtotal"] + 0) . "," . @($transferTotalsCurrent["uptotal"] + 0) . ")";
         $db->Execute($sql);
     }
 }
/**
 * This method gets the list of transfer
 *
 * @return array
 */
function getTransferListArray()
{
    global $cfg, $db, $transfers;
    $kill_id = "";
    $lastUser = "";
    $arUserTransfers = array();
    $arListTransfers = array();
    // settings
    $settings = convertIntegerToArray($cfg["index_page_settings"]);
    // sortOrder
    $sortOrder = tfb_getRequestVar("so");
    if ($sortOrder == "") {
        $sortOrder = $cfg["index_page_sortorder"];
    }
    if ($cfg["transmission_rpc_enable"] == 2) {
        require_once 'inc/functions/functions.rpc.transmission.php';
        // New method for transmission-daemon transfers
        $result = getUserTransmissionTransfers($cfg['uid']);
        foreach ($result as $aTorrent) {
            if ($aTorrent['status'] == 4 || $aTorrent['status'] == 8) {
                if (!isset($cfg["total_upload"])) {
                    $cfg["total_upload"] = 0;
                }
                if (!isset($cfg["total_download"])) {
                    $cfg["total_download"] = 0;
                }
                $cfg["total_upload"] = $cfg["total_upload"] + GetSpeedValue($aTorrent['rateUpload'] / 1000);
                $cfg["total_download"] = $cfg["total_download"] + GetSpeedValue($aTorrent['rateDownload'] / 1000);
            }
            array_push($arUserTransfers, $aTorrent);
        }
    }
    $arList = getTransferArray($sortOrder);
    foreach ($arList as $transfer) {
        // init some vars
        $displayname = $transfer;
        $show_run = true;
        $transferowner = getOwner($transfer);
        $owner = IsOwner($cfg["user"], $transferowner);
        // stat
        $sf = new StatFile($transfer, $transferowner);
        // settings
        if (isset($transfers['settings'][$transfer])) {
            $settingsAry = $transfers['settings'][$transfer];
        } else {
            $settingsAry = array();
            if (substr(str_replace('.imported', '', $transfer), -8) == ".torrent") {
                // this is a t-client
                $settingsAry['type'] = "torrent";
                $settingsAry['client'] = $cfg["btclient"];
            } else {
                if (substr($transfer, -5) == ".wget") {
                    // this is wget.
                    $settingsAry['type'] = "wget";
                    $settingsAry['client'] = "wget";
                } else {
                    if (substr($transfer, -4) == ".nzb") {
                        // this is nzbperl.
                        $settingsAry['type'] = "nzb";
                        $settingsAry['client'] = "nzbperl";
                    } else {
                        AuditAction($cfg["constants"]["error"], "INVALID TRANSFER: " . $transfer);
                        @error("Invalid Transfer", "", "", array($transfer));
                    }
                }
            }
            $settingsAry['hash'] = "";
            $settingsAry["savepath"] = $cfg["enable_home_dirs"] != 0 ? $cfg["path"] . $transferowner . '/' : $cfg["path"] . $cfg["path_incoming"] . '/';
            $settingsAry['datapath'] = "";
        }
        // cache running-flag in local var. we will access that often
        $transferRunning = $sf->running;
        // cache percent-done in local var. ...
        $percentDone = $sf->percent_done;
        // ---------------------------------------------------------------------
        //XFER: update1: add upload/download stats to the xfer array
        if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
            @Xfer::update1($transfer, $transferowner, $settingsAry['client'], $settingsAry['hash'], $sf->uptotal, $sf->downtotal);
        }
        // ---------------------------------------------------------------------
        // injects
        if (!file_exists($cfg["transfer_file_path"] . $transfer . ".stat")) {
            $transferRunning = 2;
            $sf->running = "2";
            $sf->size = getTransferSize($transfer);
            injectTransfer($transfer);
        }
        // use default client if client is not set
        if (!isset($settingsAry['client'])) {
            $settingsAry['client'] = $cfg['btclient'];
        }
        // totals-preparation
        // if downtotal + uptotal + progress > 0
        if ($settings[2] + $settings[3] + $settings[5] > 0) {
            $ch = ClientHandler::getInstance($settingsAry['client']);
            $transferTotals = $ch->getTransferTotalOP($transfer, $settingsAry['hash'], $sf->uptotal, $sf->downtotal);
        }
        // ---------------------------------------------------------------------
        // preprocess stat-file and get some vars
        $estTime = "";
        $statusStr = "";
        switch ($transferRunning) {
            case 2:
                // new
                $statusStr = 'New';
                break;
            case 3:
                // queued
                $statusStr = 'Queued';
                $estTime = 'Waiting';
                break;
            default:
                // running + stopped
                // increment the totals
                if (!isset($cfg["total_upload"])) {
                    $cfg["total_upload"] = 0;
                }
                if (!isset($cfg["total_download"])) {
                    $cfg["total_download"] = 0;
                }
                $cfg["total_upload"] += GetSpeedValue($sf->up_speed);
                $cfg["total_download"] += GetSpeedValue($sf->down_speed);
                // $estTime
                if ($transferRunning == 0) {
                    $estTime = $sf->time_left;
                } else {
                    if ($sf->time_left != "" && $sf->time_left != "0") {
                        if ($cfg["display_seeding_time"] == 1 && $sf->percent_done >= 100) {
                            $estTime = $sf->seedlimit > 0 && !empty($sf->up_speed) && intval($sf->up_speed[0]) > 0 ? convertTimeText(($sf->seedlimit / 100 * $sf->size - $sf->uptotal) / GetSpeedInBytes($sf->up_speed)) : '-';
                        } else {
                            $estTime = $sf->time_left;
                        }
                    }
                }
                // $lastUser
                $lastUser = $transferowner;
                // $show_run + $statusStr
                if ($percentDone >= 100) {
                    $statusStr = $transferRunning == 1 && trim($sf->up_speed) != "" ? 'Seeding' : 'Done';
                    $show_run = false;
                } else {
                    if ($percentDone < 0) {
                        $statusStr = 'Stopped';
                        $show_run = true;
                    } else {
                        $statusStr = 'Leeching';
                    }
                }
                break;
        }
        // ---------------------------------------------------------------------
        // fill temp array
        $transferAry = array();
        // ================================================================ name
        array_push($transferAry, $transfer);
        // =============================================================== owner
        if ($settings[0] != 0) {
            array_push($transferAry, $transferowner);
        }
        // ================================================================ size
        if ($settings[1] != 0) {
            array_push($transferAry, @formatBytesTokBMBGBTB($sf->size));
        }
        // =========================================================== downtotal
        if ($settings[2] != 0) {
            array_push($transferAry, @formatBytesTokBMBGBTB($transferTotals["downtotal"]));
        }
        // ============================================================= uptotal
        if ($settings[3] != 0) {
            array_push($transferAry, @formatBytesTokBMBGBTB($transferTotals["uptotal"]));
        }
        // ============================================================== status
        if ($settings[4] != 0) {
            array_push($transferAry, $statusStr);
        }
        // ============================================================ progress
        if ($settings[5] != 0) {
            $percentage = "";
            if ($percentDone >= 100 && trim($sf->up_speed) != "") {
                $percentage = @number_format($transferTotals["uptotal"] / $sf->size * 100, 2) . '%';
            } else {
                if ($percentDone >= 1) {
                    $percentage = $percentDone . '%';
                } else {
                    if ($percentDone < 0) {
                        $percentage = round($percentDone * -1 - 100, 1) . '%';
                    } else {
                        $percentage = '0%';
                    }
                }
            }
            array_push($transferAry, $percentage);
        }
        // ================================================================ down
        if ($settings[6] != 0) {
            $down = "";
            if ($transferRunning == 1) {
                $down = trim($sf->down_speed) != "" ? $sf->down_speed : '0.0 kB/s';
            }
            array_push($transferAry, $down);
        }
        // ================================================================== up
        if ($settings[7] != 0) {
            $up = "";
            if ($transferRunning == 1) {
                $up = trim($sf->up_speed) != "" ? $sf->up_speed : '0.0 kB/s';
            }
            array_push($transferAry, $up);
        }
        // =============================================================== seeds
        if ($settings[8] != 0) {
            $seeds = $transferRunning == 1 ? $sf->seeds : "";
            array_push($transferAry, $seeds);
        }
        // =============================================================== peers
        if ($settings[9] != 0) {
            $peers = $transferRunning == 1 ? $sf->peers : "";
            array_push($transferAry, $peers);
        }
        // ================================================================= ETA
        if ($settings[10] != 0) {
            array_push($transferAry, $estTime);
        }
        // ============================================================== client
        if ($settings[11] != 0) {
            switch ($settingsAry['client']) {
                case "tornado":
                    array_push($transferAry, "B");
                    break;
                case "transmission":
                    array_push($transferAry, "T");
                    break;
                case "transmissionrpc":
                    array_push($transferAry, "Tr");
                    break;
                case "mainline":
                    array_push($transferAry, "M");
                    break;
                case "azureus":
                    array_push($transferAry, "A");
                    break;
                case "vuzerpc":
                    array_push($transferAry, "V");
                    break;
                case "wget":
                    array_push($transferAry, "W");
                    break;
                case "nzbperl":
                    array_push($transferAry, "N");
                    break;
                default:
                    array_push($transferAry, "U");
            }
        }
        // ---------------------------------------------------------------------
        // Is this transfer for the user list or the general list?
        if ($owner) {
            array_push($arUserTransfers, $transferAry);
        } else {
            array_push($arListTransfers, $transferAry);
        }
    }
    //XFER: update 2
    if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
        @Xfer::update2();
    }
    // -------------------------------------------------------------------------
    // build output-array
    $retVal = array();
    if (sizeof($arUserTransfers) > 0) {
        foreach ($arUserTransfers as $torrentrow) {
            array_push($retVal, $torrentrow);
        }
    }
    $boolCond = true;
    if ($cfg['enable_restrictivetview'] == 1) {
        $boolCond = $cfg['isAdmin'];
    }
    if ($boolCond && sizeof($arListTransfers) > 0) {
        foreach ($arListTransfers as $torrentrow) {
            array_push($retVal, $torrentrow);
        }
    }
    return $retVal;
}
Esempio n. 21
0
         // Torrents-Resume
         include_once "ClientHandler.php";
         $htmlTitle = "Torrents-Resume";
         $htmlMain .= '<br><strong>Torrents Resumed :</strong><br>';
         $htmlMain .= '<pre>';
         $torrents = getTorrentListFromDB();
         foreach ($torrents as $torrent) {
             $torrentRunningFlag = isTorrentRunning($torrent);
             if ($torrentRunningFlag == 0) {
                 $btclient = getTorrentClient($torrent);
                 if ($cfg["enable_file_priority"]) {
                     include_once "setpriority.php";
                     // Process setPriority Request.
                     setPriority($torrent);
                 }
                 $clientHandler = ClientHandler::getClientHandlerInstance($cfg, $btclient);
                 $clientHandler->startTorrentClient($torrent, 0);
                 $htmlMain .= ' - ' . $torrent . "";
                 $htmlMain .= "\n";
                 // just 2 sec..
                 sleep(2);
             }
         }
         $htmlMain .= '</pre>';
         $htmlMain .= '<hr><br>';
         break;
 }
 $htmlMain .= '<br><strong>Torrents :</strong><br>';
 $htmlMain .= '<pre>';
 $torrents = getTorrentListFromFS();
 foreach ($torrents as $torrent) {
Esempio n. 22
0
function cliWatchDir($tpath = "", $username = "")
{
    global $cfg;
    if (isset($tpath) && $tpath != "" && isset($username) && $username != "") {
        if (is_dir($tpath)) {
            $cfg['user'] = $username;
            $watchDir = checkDirPathString($tpath);
            if ($dirHandle = opendir($tpath)) {
                while (false !== ($file = readdir($dirHandle))) {
                    if (strtolower(substr($file, -8)) == ".torrent") {
                        $file_name = stripslashes($file);
                        $file_name = str_replace(array("'", ","), "", $file_name);
                        $file_name = cleanFileName($file_name);
                        echo "Injecting and Starting " . $watchDir . $file . " as " . $file_name . " for user " . $cfg['user'] . "...";
                        if (is_file($watchDir . $file) && copy($watchDir . $file, $cfg["torrent_file_path"] . $file_name)) {
                            @unlink($watchDir . $file);
                            chmod($cfg["torrent_file_path"] . $file_name, 0644);
                            AuditAction($cfg["constants"]["file_upload"], $file_name);
                            // init stat-file
                            injectTorrent($file_name);
                            // file-prio
                            if ($cfg["enable_file_priority"]) {
                                include_once "setpriority.php";
                                // Process setPriority Request.
                                setPriority($file_name);
                            }
                            // queue
                            if ($cfg["AllowQueing"]) {
                                $_REQUEST['queue'] = 'on';
                            } else {
                                $_REQUEST['queue'] = 'off';
                            }
                            // start
                            include_once "ClientHandler.php";
                            $clientHandler = ClientHandler::getClientHandlerInstance($cfg);
                            $clientHandler->startTorrentClient($file_name, 0);
                            // just 2 secs..
                            sleep(2);
                            if ($clientHandler->status == 3) {
                                // hooray
                                echo " done\n";
                            } else {
                                // start failed
                                echo "\n ERROR : " . $clientHandler->messages . "\n";
                            }
                        } else {
                            echo "\n ERROR: File could not be found or could not be copied: " . $watchDir . $file . "\n";
                        }
                    }
                }
                closedir($dirHandle);
            }
        } else {
            echo "ERROR: " . $tpath . " is not a dir.\n";
            exit;
        }
    } else {
        printUsage();
    }
    exit;
}
/**
 * processUpload
 */
function dispatcher_processUpload()
{
    global $cfg;
    // check if files exist
    if (empty($_FILES)) {
        // log
        AuditAction($cfg["constants"]["error"], "no file in file-upload");
        // return
        return;
    }
    // action-id
    $actionId = tfb_getRequestVar('aid');
    // file upload
    $uploadMessages = array();
    // stack
    $tStack = array();
    // process upload
    while (count($_FILES) > 0) {
        $upload = array_shift($_FILES);
        if (is_array($upload['size'])) {
            foreach ($upload['size'] as $id => $size) {
                if ($size > 0) {
                    _dispatcher_processUpload($upload['name'][$id], $upload['tmp_name'][$id], $size, $actionId, $uploadMessages, $tStack);
                }
            }
        } else {
            if ($upload['size'] > 0) {
                _dispatcher_processUpload($upload['name'], $upload['tmp_name'], $upload['size'], $actionId, $uploadMessages, $tStack);
            }
        }
    }
    // instant action ?
    if ($actionId > 1 && !empty($tStack)) {
        foreach ($tStack as $transfer) {
            $ch = ClientHandler::getInstance(getTransferClient($transfer));
            switch ($actionId) {
                case 3:
                    $ch->start($transfer, false, true);
                    break;
                case 2:
                    $ch->start($transfer, false, false);
                    break;
            }
            if (count($ch->messages) > 0) {
                $uploadMessages = array_merge($uploadMessages, $ch->messages);
            }
        }
    }
    // messages
    if (count($uploadMessages) > 0) {
        @error("There were Problems", "", "", $uploadMessages);
    }
}
Esempio n. 24
0
 //XFER: update1: add upload/download stats to the xfer array
 if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
     @Xfer::update1($transfer, $transferowner, $settingsAry['client'], $settingsAry['hash'], $sf->uptotal, $sf->downtotal);
 }
 // ---------------------------------------------------------------------
 // injects new
 if (!file_exists($cfg["transfer_file_path"] . $transfer . ".stat")) {
     $transferRunning = 2;
     $sf->running = "2";
     $sf->size = getTransferSize($transfer);
     injectTransfer($transfer);
 }
 // totals-preparation
 // if downtotal + uptotal + progress > 0
 if ($settings[2] + $settings[3] + $settings[5] > 0) {
     $ch = ClientHandler::getInstance($settingsAry['client']);
     $transferTotals = $ch->getTransferTotalOP($transfer, $settingsAry['hash'], $sf->uptotal, $sf->downtotal);
 }
 // ---------------------------------------------------------------------
 // preprocess stat-file and get some vars
 $estTime = "&nbsp;";
 $statusStr = "&nbsp;";
 $show_run = true;
 switch ($transferRunning) {
     case 2:
         // new
         $statusStr = "New";
         $is_no_file = 1;
         break;
     case 3:
         // queued
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;
    }
}
Esempio n. 26
0
    if (isset($actionId)) {
        switch ($actionId) {
            case 3:
                $_REQUEST['queue'] = 'on';
            case 2:
                include_once "ClientHandler.php";
                foreach ($tStack as $torrent) {
                    // init stat-file
                    injectTorrent($torrent);
                    //
                    if ($cfg["enable_file_priority"]) {
                        include_once "setpriority.php";
                        // Process setPriority Request.
                        setPriority(urldecode($torrent));
                    }
                    $clientHandler = ClientHandler::getClientHandlerInstance($cfg);
                    $clientHandler->startTorrentClient($torrent, 0);
                    // just a sec..
                    sleep(1);
                }
                break;
        }
    }
    // back to index if no errors
    if (isset($messages) && $messages == "") {
        header("location: index.php");
        exit;
    }
}
displayHead(_MULTIPLE_UPLOAD);
?>