/**
 * 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);
}
/**
 * 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);
}
function getTransferList()
{
    global $cfg, $db;
    include_once "AliasFile.php";
    $kill_id = "";
    $lastUser = "";
    $arUserTorrent = array();
    $arListTorrent = array();
    // settings
    $settings = convertIntegerToArray($cfg["index_page_settings"]);
    // sortOrder
    $sortOrder = getRequestVar("so");
    if ($sortOrder == "") {
        $sortOrder = $cfg["index_page_sortorder"];
    }
    // t-list
    $arList = getTransferArray($sortOrder);
    foreach ($arList as $entry) {
        // ---------------------------------------------------------------------
        // init some vars
        $displayname = $entry;
        $show_run = true;
        $torrentowner = getOwner($entry);
        $owner = IsOwner($cfg["user"], $torrentowner);
        if (strlen($entry) >= 47) {
            // needs to be trimmed
            $displayname = substr($entry, 0, 44);
            $displayname .= "...";
        }
        if ($cfg["enable_torrent_download"]) {
            $torrentfilelink = "<a href=\"maketorrent.php?download=" . urlencode($entry) . "\"><img src=\"images/down.gif\" width=9 height=9 title=\"Download Torrent File\" border=0 align=\"absmiddle\"></a>";
        } else {
            $torrentfilelink = "";
        }
        // ---------------------------------------------------------------------
        // alias / stat
        $alias = getAliasName($entry) . ".stat";
        if (substr(strtolower($entry), -8) == ".torrent") {
            // this is a torrent-client
            $btclient = getTorrentClient($entry);
            $af = AliasFile::getAliasFileInstance($cfg["torrent_file_path"] . $alias, $torrentowner, $cfg, $btclient);
        } else {
            if (substr(strtolower($entry), -4) == ".url") {
                // this is wget. use tornado statfile
                $btclient = "wget";
                $alias = str_replace(".url", "", $alias);
                $af = AliasFile::getAliasFileInstance($cfg["torrent_file_path"] . $alias, $cfg['user'], $cfg, 'tornado');
            } else {
                $btclient = "tornado";
                // this is "something else". use tornado statfile as default
                $af = AliasFile::getAliasFileInstance($cfg["torrent_file_path"] . $alias, $cfg['user'], $cfg, 'tornado');
            }
        }
        // cache running-flag in local var. we will access that often
        $transferRunning = (int) $af->running;
        // cache percent-done in local var. ...
        $percentDone = $af->percent_done;
        // more vars
        $detailsLinkString = "<a style=\"font-size:9px; text-decoration:none;\" href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\">";
        // ---------------------------------------------------------------------
        //XFER: add upload/download stats to the xfer array
        if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
            if ($btclient != "wget") {
                $torrentTotalsCurrent = getTorrentTotalsCurrentOP($entry, $btclient, $af->uptotal, $af->downtotal);
            } else {
                $torrentTotalsCurrent["uptotal"] = $af->uptotal;
                $torrentTotalsCurrent["downtotal"] = $af->downtotal;
            }
            $sql = 'SELECT 1 FROM tf_xfer WHERE date = ' . $db->DBDate(time());
            $newday = !$db->GetOne($sql);
            showError($db, $sql);
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'total');
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'month');
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'week');
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'day');
            //XFER: if new day add upload/download totals to last date on record and subtract from today in SQL
            if ($newday) {
                $newday = 2;
                $sql = 'SELECT date FROM tf_xfer ORDER BY date DESC';
                $lastDate = $db->GetOne($sql);
                showError($db, $sql);
                // MySQL 4.1.0 introduced 'ON DUPLICATE KEY UPDATE' to make this easier
                $sql = 'SELECT 1 FROM tf_xfer WHERE user_id = "' . $torrentowner . '" AND date = "' . $lastDate . '"';
                if ($db->GetOne($sql)) {
                    $sql = 'UPDATE tf_xfer SET download = download+' . ($torrentTotalsCurrent["downtotal"] + 0) . ', upload = upload+' . ($torrentTotalsCurrent["uptotal"] + 0) . ' WHERE user_id = "' . $torrentowner . '" AND date = "' . $lastDate . '"';
                    $db->Execute($sql);
                    showError($db, $sql);
                } else {
                    showError($db, $sql);
                    $sql = 'INSERT INTO tf_xfer (user_id,date,download,upload) values ("' . $torrentowner . '","' . $lastDate . '",' . ($torrentTotalsCurrent["downtotal"] + 0) . ',' . ($torrentTotalsCurrent["uptotal"] + 0) . ')';
                    $db->Execute($sql);
                    showError($db, $sql);
                }
                $sql = 'SELECT 1 FROM tf_xfer WHERE user_id = "' . $torrentowner . '" AND date = ' . $db->DBDate(time());
                if ($db->GetOne($sql)) {
                    $sql = 'UPDATE tf_xfer SET download = download-' . ($torrentTotalsCurrent["downtotal"] + 0) . ', upload = upload-' . ($torrentTotalsCurrent["uptotal"] + 0) . ' WHERE user_id = "' . $torrentowner . '" AND date = ' . $db->DBDate(time());
                    $db->Execute($sql);
                    showError($db, $sql);
                } else {
                    showError($db, $sql);
                    $sql = 'INSERT INTO tf_xfer (user_id,date,download,upload) values ("' . $torrentowner . '",' . $db->DBDate(time()) . ',-' . ($torrentTotalsCurrent["downtotal"] + 0) . ',-' . ($torrentTotalsCurrent["uptotal"] + 0) . ')';
                    $db->Execute($sql);
                    showError($db, $sql);
                }
            }
        }
        // ---------------------------------------------------------------------
        // injects
        if (!file_exists($cfg["torrent_file_path"] . $alias)) {
            $transferRunning = 2;
            $af->running = "2";
            $af->size = getDownloadSize($cfg["torrent_file_path"] . $entry);
            $af->WriteFile();
        }
        // ---------------------------------------------------------------------
        // preprocess alias-file and get some vars
        $estTime = "&nbsp;";
        $statusStr = "&nbsp;";
        switch ($transferRunning) {
            case 2:
                // new
                // $statusStr
                $statusStr = $detailsLinkString . "<font color=\"#32cd32\">New</font></a>";
                break;
            case 3:
                // queued
                // $statusStr
                $statusStr = $detailsLinkString . "Queued</a>";
                // $estTime
                $estTime = "Waiting...";
                break;
            default:
                // running
                // increment the totals
                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($af->up_speed);
                $cfg["total_download"] = $cfg["total_download"] + GetSpeedValue($af->down_speed);
                // $estTime
                if ($af->time_left != "" && $af->time_left != "0") {
                    $estTime = $af->time_left;
                }
                // $lastUser
                $lastUser = $torrentowner;
                // $show_run + $statusStr
                if ($percentDone >= 100) {
                    if (trim($af->up_speed) != "" && $transferRunning == 1) {
                        $statusStr = $detailsLinkString . 'Seeding</a>';
                    } else {
                        $statusStr = $detailsLinkString . 'Done</a>';
                    }
                    $show_run = false;
                } else {
                    if ($percentDone < 0) {
                        $statusStr = $detailsLinkString . "Stopped</a>";
                        $show_run = true;
                    } else {
                        $statusStr = $detailsLinkString . "Leeching</a>";
                    }
                }
                break;
        }
        // totals-preparation
        // if downtotal + uptotal + progress > 0
        if ($settings[2] + $settings[3] + $settings[5] > 0) {
            if ($btclient != "wget") {
                $torrentTotals = getTorrentTotalsOP($entry, $btclient, $af->uptotal, $af->downtotal);
            } else {
                $torrentTotals["uptotal"] = $af->uptotal;
                $torrentTotals["downtotal"] = $af->downtotal;
            }
        }
        // ---------------------------------------------------------------------
        // output-string
        $output = "<tr>";
        // ========================================================== led + meta
        $output .= '<td valign="bottom" align="center">';
        // led
        $hd = getStatusImage($af);
        if ($transferRunning == 1) {
            $output .= "<a href=\"JavaScript:ShowDetails('downloadhosts.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\">";
        }
        $output .= "<img src=\"images/" . $hd->image . "\" width=\"16\" height=\"16\" title=\"" . $hd->title . $entry . "\" border=\"0\" align=\"absmiddle\">";
        if ($transferRunning == 1) {
            $output .= "</a>";
        }
        // meta
        $output .= $torrentfilelink;
        $output .= "</td>";
        // ================================================================ name
        $output .= "<td valign=\"bottom\">" . $detailsLinkString . $displayname . "</a></td>";
        // =============================================================== owner
        if ($settings[0] != 0) {
            $output .= "<td valign=\"bottom\" align=\"center\"><a href=\"message.php?to_user="******"\"><font class=\"tiny\">" . $torrentowner . "</font></a></td>";
        }
        // ================================================================ size
        if ($settings[1] != 0) {
            $output .= "<td valign=\"bottom\" align=\"right\" nowrap>" . $detailsLinkString . formatBytesToKBMGGB($af->size) . "</a></td>";
        }
        // =========================================================== downtotal
        if ($settings[2] != 0) {
            $output .= "<td valign=\"bottom\" align=\"right\" nowrap>" . $detailsLinkString . formatBytesToKBMGGB($torrentTotals["downtotal"] + 0) . "</a></td>";
        }
        // ============================================================= uptotal
        if ($settings[3] != 0) {
            $output .= "<td valign=\"bottom\" align=\"right\" nowrap>" . $detailsLinkString . formatBytesToKBMGGB($torrentTotals["uptotal"] + 0) . "</a></td>";
        }
        // ============================================================== status
        if ($settings[4] != 0) {
            $output .= "<td valign=\"bottom\" align=\"center\">" . $detailsLinkString . $statusStr . "</a></td>";
        }
        // ============================================================ progress
        if ($settings[5] != 0) {
            $graph_width = 1;
            $progress_color = "#00ff00";
            $background = "#000000";
            $bar_width = "4";
            $percentage = "";
            if ($percentDone >= 100 && trim($af->up_speed) != "") {
                $graph_width = -1;
                $percentage = @number_format($torrentTotals["uptotal"] / $af->size * 100, 2) . '%';
            } else {
                if ($percentDone >= 1) {
                    $graph_width = $percentDone;
                    $percentage = $graph_width . '%';
                } else {
                    if ($percentDone < 0) {
                        $graph_width = round($percentDone * -1 - 100, 1);
                        $percentage = $graph_width . '%';
                    } else {
                        $graph_width = 0;
                        $percentage = '0%';
                    }
                }
            }
            if ($graph_width == 100) {
                $background = $progress_color;
            }
            $output .= "<td valign=\"bottom\" align=\"center\" nowrap>";
            if ($graph_width == -1) {
                $output .= $detailsLinkString . '<strong>' . $percentage . '</strong></a>';
            } else {
                if ($graph_width > 0) {
                    $output .= $detailsLinkString . '<strong>' . $percentage . '</strong></a>';
                    $output .= "<br>";
                    $output .= "<table width=\"100\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr>";
                    $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/progressbar.gif\" bgcolor=\"" . $progress_color . "\">" . $detailsLinkString . "<img src=\"images/blank.gif\" width=\"" . $graph_width . "\" height=\"" . $bar_width . "\" border=\"0\"></a></td>";
                    $output .= "<td bgcolor=\"" . $background . "\">" . $detailsLinkString . "<img src=\"images/blank.gif\" width=\"" . (100 - $graph_width) . "\" height=\"" . $bar_width . "\" border=\"0\"></a></td>";
                    $output .= "</tr></table>";
                } else {
                    if ($transferRunning == 2) {
                        $output .= '&nbsp;';
                    } else {
                        $output .= $detailsLinkString . '<strong>' . $percentage . '</strong></a>';
                        $output .= "<br>";
                        $output .= "<table width=\"100\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr>";
                        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/progressbar.gif\" bgcolor=\"" . $progress_color . "\">" . $detailsLinkString . "<img src=\"images/blank.gif\" width=\"" . $graph_width . "\" height=\"" . $bar_width . "\" border=\"0\"></a></td>";
                        $output .= "<td bgcolor=\"" . $background . "\">" . $detailsLinkString . "<img src=\"images/blank.gif\" width=\"" . (100 - $graph_width) . "\" height=\"" . $bar_width . "\" border=\"0\"></a></td>";
                        $output .= "</tr></table>";
                    }
                }
            }
            $output .= "</td>";
        }
        // ================================================================ down
        if ($settings[6] != 0) {
            $output .= '<td valign="bottom" align="right" class="tiny" nowrap>';
            if ($transferRunning == 1) {
                $output .= $detailsLinkString;
                if (trim($af->down_speed) != "") {
                    $output .= $af->down_speed;
                } else {
                    $output .= '0.0 kB/s';
                }
                $output .= '</a>';
            } else {
                $output .= '&nbsp;';
            }
            $output .= '</td>';
        }
        // ================================================================== up
        if ($settings[7] != 0) {
            $output .= '<td valign="bottom" align="right" class="tiny" nowrap>';
            if ($transferRunning == 1) {
                $output .= $detailsLinkString;
                if (trim($af->up_speed) != "") {
                    $output .= $af->up_speed;
                } else {
                    $output .= '0.0 kB/s';
                }
                $output .= '</a>';
            } else {
                $output .= '&nbsp;';
            }
            $output .= '</td>';
        }
        // =============================================================== seeds
        if ($settings[8] != 0) {
            $output .= '<td valign="bottom" align="right" class="tiny" nowrap>';
            if ($transferRunning == 1) {
                $output .= $detailsLinkString;
                $output .= $af->seeds;
                $output .= '</a>';
            } else {
                $output .= '&nbsp;';
            }
            $output .= '</td>';
        }
        // =============================================================== peers
        if ($settings[9] != 0) {
            $output .= '<td valign="bottom" align="right" class="tiny" nowrap>';
            if ($transferRunning == 1) {
                $output .= $detailsLinkString;
                $output .= $af->peers;
                $output .= '</a>';
            } else {
                $output .= '&nbsp;';
            }
            $output .= '</td>';
        }
        // ================================================================= ETA
        if ($settings[10] != 0) {
            $output .= "<td valign=\"bottom\" align=\"center\">" . $detailsLinkString . $estTime . "</a></td>";
        }
        // ============================================================== client
        if ($settings[11] != 0) {
            switch ($btclient) {
                case "tornado":
                    $output .= "<td valign=\"bottom\" align=\"center\">B</a></td>";
                    break;
                case "transmission":
                    $output .= "<td valign=\"bottom\" align=\"center\">T</a></td>";
                    break;
                case "wget":
                    $output .= "<td valign=\"bottom\" align=\"center\">W</a></td>";
                    break;
                default:
                    $output .= "<td valign=\"bottom\" align=\"center\">U</a></td>";
            }
        }
        // =============================================================== admin
        $output .= "<td><div align=center>";
        $torrentDetails = _TORRENTDETAILS;
        if ($lastUser != "") {
            $torrentDetails .= "\n" . _USER . ": " . $lastUser;
        }
        $output .= "<a href=\"details.php?torrent=" . urlencode($entry);
        if ($transferRunning == 1) {
            $output .= "&als=false";
        }
        $output .= "\"><img src=\"images/properties.png\" width=18 height=13 title=\"" . $torrentDetails . "\" border=0></a>";
        if ($owner || IsAdmin($cfg["user"])) {
            if ($percentDone >= 0 && $transferRunning == 1) {
                $output .= "<a href=\"index.php?alias_file=" . $alias . "&kill=" . $kill_id . "&kill_torrent=" . urlencode($entry) . "\"><img src=\"images/kill.gif\" width=16 height=16 title=\"" . _STOPDOWNLOAD . "\" border=0></a>";
                $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 border=0>";
                if ($cfg['enable_multiops'] != 0) {
                    $output .= "<input type=\"checkbox\" name=\"torrent[]\" value=\"" . urlencode($entry) . "\">";
                }
            } else {
                if ($torrentowner == "n/a") {
                    $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
                } else {
                    if ($transferRunning == 3) {
                        $output .= "<a href=\"index.php?alias_file=" . $alias . "&dQueue=" . $kill_id . "&QEntry=" . urlencode($entry) . "\"><img src=\"images/queued.gif\" width=16 height=16 title=\"" . _DELQUEUE . "\" border=0></a>";
                    } else {
                        if (!is_file($cfg["torrent_file_path"] . $alias . ".pid")) {
                            // Allow Avanced start popup?
                            if ($cfg["advanced_start"] != 0) {
                                if ($show_run) {
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=" . urlencode($entry) . "')\"><img src=\"images/run_on.gif\" width=16 height=16 title=\"" . _RUNTORRENT . "\" border=0></a>";
                                } else {
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=" . urlencode($entry) . "')\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\"" . _SEEDTORRENT . "\" border=0></a>";
                                }
                            } else {
                                // Quick Start
                                if ($show_run) {
                                    $output .= "<a href=\"" . $_SERVER['PHP_SELF'] . "?torrent=" . urlencode($entry) . "\"><img src=\"images/run_on.gif\" width=16 height=16 title=\"" . _RUNTORRENT . "\" border=0></a>";
                                } else {
                                    $output .= "<a href=\"" . $_SERVER['PHP_SELF'] . "?torrent=" . urlencode($entry) . "\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\"" . _SEEDTORRENT . "\" border=0></a>";
                                }
                            }
                        } else {
                            // pid file exists so this may still be running or dieing.
                            $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\"" . _STOPPING . "\">";
                        }
                    }
                }
                if (!is_file($cfg["torrent_file_path"] . $alias . ".pid")) {
                    $deletelink = $_SERVER['PHP_SELF'] . "?alias_file=" . $alias . "&delfile=" . urlencode($entry);
                    $output .= "<a href=\"" . $deletelink . "\" onclick=\"return ConfirmDelete('" . $entry . "')\"><img src=\"images/delete_on.gif\" width=16 height=16 title=\"" . _DELETE . "\" border=0></a>";
                    if ($cfg['enable_multiops'] != 0) {
                        $output .= "<input type=\"checkbox\" name=\"torrent[]\" value=\"" . urlencode($entry) . "\">";
                    }
                } else {
                    // pid file present so process may be still running. don't allow deletion.
                    $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 title=\"" . _STOPPING . "\" border=0>";
                    if ($cfg['enable_multiops'] != 0) {
                        $output .= "<input type=\"checkbox\" name=\"torrent[]\" value=\"" . urlencode($entry) . "\">";
                    }
                }
            }
        } else {
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
            $output .= "<input type=\"checkbox\" disabled=\"disabled\">";
        }
        $output .= "</div>";
        $output .= "</td>";
        $output .= "</tr>\n";
        // ---------------------------------------------------------------------
        // Is this torrent for the user list or the general list?
        if ($cfg["user"] == getOwner($entry)) {
            array_push($arUserTorrent, $output);
        } else {
            array_push($arListTorrent, $output);
        }
    }
    //XFER: if a new day but no .stat files where found put blank entry into the DB for today to indicate accounting has been done for the new day
    if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
        if (isset($newday) && $newday == 1) {
            $sql = 'INSERT INTO tf_xfer (user_id,date) values ( "",' . $db->DBDate(time()) . ')';
            $db->Execute($sql);
            showError($db, $sql);
        }
        getUsage(0, 'total');
        $month_start = date('j') >= $cfg['month_start'] ? date('Y-m-') . $cfg['month_start'] : date('Y-m-', strtotime('-1 Month')) . $cfg['month_start'];
        getUsage($month_start, 'month');
        $week_start = date('Y-m-d', strtotime('last ' . $cfg['week_start']));
        getUsage($week_start, 'week');
        $day_start = date('Y-m-d');
        getUsage($day_start, 'day');
    }
    // -------------------------------------------------------------------------
    // build output-string
    $output = '<table bgcolor="' . $cfg["table_data_bg"] . '" width="100%" bordercolor="' . $cfg["table_border_dk"] . '" border="1" cellpadding="3" cellspacing="0" class="sortable" id="transfer_table">';
    if (sizeof($arUserTorrent) > 0) {
        $output .= getTransferTableHead($settings, $sortOrder, $cfg["user"] . " : ");
        foreach ($arUserTorrent as $torrentrow) {
            $output .= $torrentrow;
        }
    }
    $boolCond = true;
    if ($cfg['enable_restrictivetview'] == 1) {
        $boolCond = IsAdmin();
    }
    if ($boolCond && sizeof($arListTorrent) > 0) {
        $output .= getTransferTableHead($settings, $sortOrder);
        foreach ($arListTorrent as $torrentrow) {
            $output .= $torrentrow;
        }
    }
    $output .= "</tr></table>\n";
    return $output;
}
/**
 * bulk
 *
 * @param $op
 */
function dispatcher_bulk($op)
{
    global $cfg;
    // is enabled ?
    if ($cfg["enable_bulkops"] != 1) {
        AuditAction($cfg["constants"]["error"], "ILLEGAL ACCESS: " . $cfg["user"] . " tried to use " . $op);
        @error("bulkops are disabled", "", "");
    }
    // messages
    $dispatcherMessages = array();
    // op-switch
    switch ($op) {
        case "stop":
            $transferList = getTransferArray();
            foreach ($transferList as $transfer) {
                if (isTransferRunning($transfer)) {
                    if ($cfg['isAdmin'] || IsOwner($cfg["user"], getOwner($transfer))) {
                        $ch = ClientHandler::getInstance(getTransferClient($transfer));
                        $ch->stop($transfer);
                        if (count($ch->messages) > 0) {
                            $dispatcherMessages = array_merge($dispatcherMessages, $ch->messages);
                        }
                    }
                }
            }
            break;
        case "resume":
            $transferList = getTransferArray();
            $sf = new StatFile("");
            foreach ($transferList as $transfer) {
                $sf->init($transfer);
                if (trim($sf->running) == 0 && !isTransferRunning($transfer)) {
                    if ($cfg['isAdmin'] || IsOwner($cfg["user"], getOwner($transfer))) {
                        $ch = ClientHandler::getInstance(getTransferClient($transfer));
                        $ch->start($transfer, false, false);
                        if (count($ch->messages) > 0) {
                            $dispatcherMessages = array_merge($dispatcherMessages, $ch->messages);
                        }
                    }
                }
            }
            break;
        case "start":
            $transferList = getTransferArray();
            foreach ($transferList as $transfer) {
                if (!isTransferRunning($transfer)) {
                    if ($cfg['isAdmin'] || IsOwner($cfg["user"], getOwner($transfer))) {
                        $ch = ClientHandler::getInstance(getTransferClient($transfer));
                        $ch->start($transfer, false, false);
                        if (count($ch->messages) > 0) {
                            $dispatcherMessages = array_merge($dispatcherMessages, $ch->messages);
                        }
                    }
                }
            }
            break;
    }
    // error if messages
    if (count($dispatcherMessages) > 0) {
        @error("There were Problems", "", "", $dispatcherMessages);
    }
}
/**
 * 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;
}
function getDirList($dirName)
{
    global $cfg, $db;
    include_once "AliasFile.php";
    $lastUser = "";
    $arUserTorrent = array();
    $arListTorrent = array();
    // sortOrder
    $sortOrder = getRequestVar("so");
    if ($sortOrder == "") {
        $sortOrder = $cfg["index_page_sortorder"];
    }
    // t-list
    $arList = getTransferArray($sortOrder);
    foreach ($arList as $entry) {
        $output = "";
        $displayname = $entry;
        $show_run = true;
        $torrentowner = getOwner($entry);
        $owner = IsOwner($cfg["user"], $torrentowner);
        $kill_id = "";
        $estTime = "&nbsp;";
        // alias / stat
        $alias = getAliasName($entry) . ".stat";
        if (substr(strtolower($entry), -8) == ".torrent") {
            // this is a torrent-client
            $btclient = getTorrentClient($entry);
            $af = AliasFile::getAliasFileInstance($dirName . $alias, $torrentowner, $cfg, $btclient);
        } else {
            if (substr(strtolower($entry), -4) == ".url") {
                // this is wget. use tornado statfile
                $alias = str_replace(".url", "", $alias);
                $af = AliasFile::getAliasFileInstance($dirName . $alias, $cfg['user'], $cfg, 'tornado');
            } else {
                // this is "something else". use tornado statfile as default
                $af = AliasFile::getAliasFileInstance($dirName . $alias, $cfg['user'], $cfg, 'tornado');
            }
        }
        //XFER: add upload/download stats to the xfer array
        if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
            $torrentTotalsCurrent = getTorrentTotalsCurrentOP($entry, $btclient, $af->uptotal, $af->downtotal);
            $sql = 'SELECT 1 FROM tf_xfer WHERE date = ' . $db->DBDate(time());
            $newday = !$db->GetOne($sql);
            showError($db, $sql);
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'total');
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'month');
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'week');
            sumUsage($torrentowner, $torrentTotalsCurrent["downtotal"] + 0, $torrentTotalsCurrent["uptotal"] + 0, 'day');
            //XFER: if new day add upload/download totals to last date on record and subtract from today in SQL
            if ($newday) {
                $newday = 2;
                $sql = 'SELECT date FROM tf_xfer ORDER BY date DESC';
                $lastDate = $db->GetOne($sql);
                showError($db, $sql);
                // MySQL 4.1.0 introduced 'ON DUPLICATE KEY UPDATE' to make this easier
                $sql = 'SELECT 1 FROM tf_xfer WHERE user_id = "' . $torrentowner . '" AND date = "' . $lastDate . '"';
                if ($db->GetOne($sql)) {
                    $sql = 'UPDATE tf_xfer SET download = download+' . ($torrentTotalsCurrent["downtotal"] + 0) . ', upload = upload+' . ($torrentTotalsCurrent["uptotal"] + 0) . ' WHERE user_id = "' . $torrentowner . '" AND date = "' . $lastDate . '"';
                    $db->Execute($sql);
                    showError($db, $sql);
                } else {
                    showError($db, $sql);
                    $sql = 'INSERT INTO tf_xfer (user_id,date,download,upload) values ("' . $torrentowner . '","' . $lastDate . '",' . ($torrentTotalsCurrent["downtotal"] + 0) . ',' . ($torrentTotalsCurrent["uptotal"] + 0) . ')';
                    $db->Execute($sql);
                    showError($db, $sql);
                }
                $sql = 'SELECT 1 FROM tf_xfer WHERE user_id = "' . $torrentowner . '" AND date = ' . $db->DBDate(time());
                if ($db->GetOne($sql)) {
                    $sql = 'UPDATE tf_xfer SET download = download-' . ($torrentTotalsCurrent["downtotal"] + 0) . ', upload = upload-' . ($torrentTotalsCurrent["uptotal"] + 0) . ' WHERE user_id = "' . $torrentowner . '" AND date = ' . $db->DBDate(time());
                    $db->Execute($sql);
                    showError($db, $sql);
                } else {
                    showError($db, $sql);
                    $sql = 'INSERT INTO tf_xfer (user_id,date,download,upload) values ("' . $torrentowner . '",' . $db->DBDate(time()) . ',-' . ($torrentTotalsCurrent["downtotal"] + 0) . ',-' . ($torrentTotalsCurrent["uptotal"] + 0) . ')';
                    $db->Execute($sql);
                    showError($db, $sql);
                }
            }
        }
        $timeStarted = "";
        $torrentfilelink = "";
        if (!file_exists($dirName . $alias)) {
            $af->running = "2";
            // file is new
            $af->size = getDownloadSize($dirName . $entry);
            $af->WriteFile();
        }
        if (strlen($entry) >= 47) {
            // needs to be trimmed
            $displayname = substr($entry, 0, 44);
            $displayname .= "...";
        }
        if ($cfg["enable_torrent_download"]) {
            $torrentfilelink = "<a href=\"maketorrent.php?download=" . urlencode($entry) . "\"><img src=\"images/down.gif\" width=9 height=9 title=\"Download Torrent File\" border=0 align=\"absmiddle\"></a>";
        }
        //
        $hd = getStatusImage($af);
        $output .= "<tr>";
        $detailsLinkString = "<a style=\"font-size:9px; text-decoration:none;\" href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\">";
        // ========================================================== led + meta
        $output .= '<td valign="bottom" align="center">';
        // led
        $hd = getStatusImage($af);
        if ($af->running == 1) {
            $output .= "<a href=\"JavaScript:ShowDetails('downloadhosts.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\">";
        }
        $output .= "<img src=\"images/" . $hd->image . "\" width=\"16\" height=\"16\" title=\"" . $hd->title . $entry . "\" border=\"0\" align=\"absmiddle\">";
        if ($af->running == 1) {
            $output .= "</a>";
        }
        // meta
        $output .= $torrentfilelink;
        $output .= "</td>";
        // ================================================================ name
        $output .= "<td valign=\"bottom\">";
        $output .= $detailsLinkString;
        $output .= $displayname;
        $output .= "</a>";
        $output .= "</td>";
        $output .= "<td align=\"right\"><font class=\"tiny\">" . formatBytesToKBMGGB($af->size) . "</font></td>";
        $output .= "<td align=\"center\"><a href=\"message.php?to_user="******"\"><font class=\"tiny\">" . $torrentowner . "</font></a></td>";
        $output .= "<td valign=\"bottom\"><div align=\"center\">";
        if ($af->running == "2") {
            $output .= "<i><font color=\"#32cd32\">" . _NEW . "</font></i>";
        } elseif ($af->running == "3") {
            $estTime = "Waiting...";
            $qDateTime = '';
            if (is_file($dirName . "queue/" . $alias . ".Qinfo")) {
                $qDateTime = date("m/d/Y H:i:s", strval(filectime($dirName . "queue/" . $alias . ".Qinfo")));
            }
            $output .= "<i><font color=\"#000000\" onmouseover=\"return overlib('" . _QUEUED . ": " . $qDateTime . "<br>', CSSCLASS);\" onmouseout=\"return nd();\">" . _QUEUED . "</font></i>";
        } else {
            if ($af->time_left != "" && $af->time_left != "0") {
                $estTime = $af->time_left;
            }
            $sql_search_time = "Select time from tf_log where action like '%Upload' and file like '" . $entry . "%'";
            $result_search_time = $db->Execute($sql_search_time);
            list($uploaddate) = $result_search_time->FetchRow();
            $lastUser = $torrentowner;
            $sharing = $af->sharing . "%";
            $graph_width = 1;
            $progress_color = "#00ff00";
            $background = "#000000";
            $bar_width = "4";
            $popup_msg = _ESTIMATEDTIME . ": " . $af->time_left;
            $popup_msg .= "<br>" . _DOWNLOADSPEED . ": " . $af->down_speed;
            $popup_msg .= "<br>" . _UPLOADSPEED . ": " . $af->up_speed;
            $popup_msg .= "<br>" . _SHARING . ": " . $sharing;
            $popup_msg .= "<br>Seeds: " . $af->seeds;
            $popup_msg .= "<br>Peers: " . $af->peers;
            $popup_msg .= "<br>" . _USER . ": " . $torrentowner;
            $eCount = 0;
            foreach ($af->errors as $key => $value) {
                if (strpos($value, " (x")) {
                    $curEMsg = substr($value, strpos($value, " (x") + 3);
                    $eCount += substr($curEMsg, 0, strpos($curEMsg, ")"));
                } else {
                    $eCount += 1;
                }
            }
            $popup_msg .= "<br>" . _ERRORSREPORTED . ": " . strval($eCount);
            $popup_msg .= "<br>" . _UPLOADED . ": " . date("m/d/Y H:i:s", $uploaddate);
            if (is_file($dirName . $alias . ".pid")) {
                $timeStarted = "<br>" . _STARTED . ": " . date("m/d/Y H:i:s", strval(filectime($dirName . $alias . ".pid")));
            }
            // incriment the totals
            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($af->up_speed);
            $cfg["total_download"] = $cfg["total_download"] + GetSpeedValue($af->down_speed);
            if ($af->percent_done >= 100) {
                if (trim($af->up_speed) != "" && $af->running == "1") {
                    $popup_msg .= $timeStarted;
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" style=\"font-size:7pt;\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\">seeding (" . $af->up_speed . ") " . $sharing . "</a>";
                } else {
                    $popup_msg .= "<br>" . _ENDED . ": " . date("m/d/Y H:i:s", strval(filemtime($dirName . $alias)));
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=red>" . _DONE . "</font></i></a>";
                }
                $show_run = false;
            } else {
                if ($af->percent_done < 0) {
                    $popup_msg .= $timeStarted;
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=\"#989898\">" . _INCOMPLETE . "</font></i></a>";
                    $show_run = true;
                } else {
                    $popup_msg .= $timeStarted;
                    if ($af->percent_done > 1) {
                        $graph_width = $af->percent_done;
                    }
                    if ($graph_width == 100) {
                        $background = $progress_color;
                    }
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\">";
                    $output .= "<font class=\"tiny\"><strong>" . $af->percent_done . "%</strong> @ " . $af->down_speed . "</font></a><br>";
                    $output .= "<table width=\"100\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
                    $output .= "<tr><td background=\"themes/" . $cfg["theme"] . "/images/progressbar.gif\" bgcolor=\"" . $progress_color . "\"><img src=\"images/blank.gif\" width=\"" . $graph_width . "\" height=\"" . $bar_width . "\" border=\"0\"></td>";
                    $output .= "<td bgcolor=\"" . $background . "\"><img src=\"images/blank.gif\" width=\"" . (100 - $graph_width) . "\" height=\"" . $bar_width . "\" border=\"0\"></td>";
                    $output .= "</tr></table>";
                }
            }
        }
        $output .= "</div></td>";
        $output .= "<td><div class=\"tiny\" align=\"center\">" . $estTime . "</div></td>";
        $output .= "<td><div align=center>";
        $torrentDetails = _TORRENTDETAILS;
        if ($lastUser != "") {
            $torrentDetails .= "\n" . _USER . ": " . $lastUser;
        }
        $output .= "<a href=\"details.php?torrent=" . urlencode($entry);
        if ($af->running == 1) {
            $output .= "&als=false";
        }
        $output .= "\"><img src=\"images/properties.png\" width=18 height=13 title=\"" . $torrentDetails . "\" border=0></a>";
        if ($owner || IsAdmin($cfg["user"])) {
            if ($af->percent_done >= 0 && $af->running == 1) {
                $output .= "<a href=\"index.php?alias_file=" . $alias . "&kill=" . $kill_id . "&kill_torrent=" . urlencode($entry) . "\"><img src=\"images/kill.gif\" width=16 height=16 title=\"" . _STOPDOWNLOAD . "\" border=0></a>";
                $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 border=0>";
                if ($cfg['enable_multiops'] == 1) {
                    $output .= "<input type=\"checkbox\" name=\"torrent[]\" value=\"" . urlencode($entry) . "\">";
                }
            } else {
                if ($torrentowner == "n/a") {
                    $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
                } else {
                    if ($af->running == "3") {
                        $output .= "<a href=\"index.php?alias_file=" . $alias . "&dQueue=" . $kill_id . "&QEntry=" . urlencode($entry) . "\"><img src=\"images/queued.gif\" width=16 height=16 title=\"" . _DELQUEUE . "\" border=0></a>";
                    } else {
                        if (!is_file($cfg["torrent_file_path"] . $alias . ".pid")) {
                            // Allow Avanced start popup?
                            if ($cfg["advanced_start"] != 0) {
                                if ($show_run) {
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=" . urlencode($entry) . "')\"><img src=\"images/run_on.gif\" width=16 height=16 title=\"" . _RUNTORRENT . "\" border=0></a>";
                                } else {
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=" . urlencode($entry) . "')\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\"" . _SEEDTORRENT . "\" border=0></a>";
                                }
                            } else {
                                // Quick Start
                                if ($show_run) {
                                    $output .= "<a href=\"" . $_SERVER['PHP_SELF'] . "?torrent=" . urlencode($entry) . "\"><img src=\"images/run_on.gif\" width=16 height=16 title=\"" . _RUNTORRENT . "\" border=0></a>";
                                } else {
                                    $output .= "<a href=\"" . $_SERVER['PHP_SELF'] . "?torrent=" . urlencode($entry) . "\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\"" . _SEEDTORRENT . "\" border=0></a>";
                                }
                            }
                        } else {
                            // pid file exists so this may still be running or dieing.
                            $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\"" . _STOPPING . "\">";
                        }
                    }
                }
                if (!is_file($cfg["torrent_file_path"] . $alias . ".pid")) {
                    $deletelink = $_SERVER['PHP_SELF'] . "?alias_file=" . $alias . "&delfile=" . urlencode($entry);
                    $output .= "<a href=\"" . $deletelink . "\" onclick=\"return ConfirmDelete('" . $entry . "')\"><img src=\"images/delete_on.gif\" width=16 height=16 title=\"" . _DELETE . "\" border=0></a>";
                    if ($cfg['enable_multiops'] == 1) {
                        $output .= "<input type=\"checkbox\" name=\"torrent[]\" value=\"" . urlencode($entry) . "\">";
                    }
                } else {
                    // pid file present so process may be still running. don't allow deletion.
                    $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 title=\"" . _STOPPING . "\" border=0>";
                    if ($cfg['enable_multiops'] == 1) {
                        $output .= "<input type=\"checkbox\" name=\"torrent[]\" value=\"" . urlencode($entry) . "\">";
                    }
                }
            }
        } else {
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
            $output .= "<input type=\"checkbox\" disabled=\"disabled\">";
        }
        $output .= "</div>";
        $output .= "</td>";
        $output .= "</tr>\n";
        // Is this torrent for the user list or the general list?
        if ($cfg["user"] == getOwner($entry)) {
            array_push($arUserTorrent, $output);
        } else {
            array_push($arListTorrent, $output);
        }
    }
    //XFER: if a new day but no .stat files where found put blank entry into the DB for today to indicate accounting has been done for the new day
    if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
        if (isset($newday) && $newday == 1) {
            $sql = 'INSERT INTO tf_xfer (user_id,date) values ( "",' . $db->DBDate(time()) . ')';
            $db->Execute($sql);
            showError($db, $sql);
        }
        getUsage(0, 'total');
        $month_start = date('j') >= $cfg['month_start'] ? date('Y-m-') . $cfg['month_start'] : date('Y-m-', strtotime('-1 Month')) . $cfg['month_start'];
        getUsage($month_start, 'month');
        $week_start = date('Y-m-d', strtotime('last ' . $cfg['week_start']));
        getUsage($week_start, 'week');
        $day_start = date('Y-m-d');
        getUsage($day_start, 'day');
    }
    // Now spit out the junk
    //XFER: return the junk as a string instead
    $output = '<table bgcolor="' . $cfg["table_data_bg"] . '" width="100%" bordercolor="' . $cfg["table_border_dk"] . '" border="1" cellpadding="3" cellspacing="0" class="sortable" id="transfer_table">';
    if (sizeof($arUserTorrent) > 0) {
        $output .= "<tr>";
        // first
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">";
        switch ($sortOrder) {
            case 'da':
                // sort by date ascending
                $output .= '<a href="?so=dd"><font class="adminlink">#</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=dd"><img src="images/s_down.gif" width="9" height="9" border="0"></a>';
                break;
            case 'dd':
                // sort by date descending
                $output .= '<a href="?so=da"><font class="adminlink">#</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=da"><img src="images/s_up.gif" width="9" height="9" border="0"></a>';
                break;
            default:
                $output .= '<a href="?so=dd"><font class="adminlink">#</font></a>';
                break;
        }
        $output .= "</div></td>";
        // name
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">";
        switch ($sortOrder) {
            case 'na':
                // sort alphabetically by name ascending
                $output .= '<a href="?so=nd"><font class="adminlink">' . $cfg["user"] . ": " . _TORRENTFILE . '</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=nd"><img src="images/s_down.gif" width="9" height="9" border="0"></a>';
                break;
            case 'nd':
                // sort alphabetically by name descending
                $output .= '<a href="?so=na"><font class="adminlink">' . $cfg["user"] . ": " . _TORRENTFILE . '</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=na"><img src="images/s_up.gif" width="9" height="9" border="0"></a>';
                break;
            default:
                $output .= '<a href="?so=na"><font class="adminlink">' . $cfg["user"] . ": " . _TORRENTFILE . '</font></a>';
                break;
        }
        $output .= "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">Size</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _USER . "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _STATUS . "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ESTIMATEDTIME . "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ADMIN . "</div></td>";
        $output .= "</tr>\n";
        foreach ($arUserTorrent as $torrentrow) {
            $output .= $torrentrow;
        }
    }
    // "Only Admin can see other user torrents"
    $boolCond = true;
    if ($cfg['enable_restrictivetview'] == 1) {
        $boolCond = IsAdmin();
    }
    if ($boolCond && sizeof($arListTorrent) > 0) {
        // "Only Admin can see other user torrents"
        $output .= "<tr>";
        // first
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">";
        switch ($sortOrder) {
            case 'da':
                // sort by date ascending
                $output .= '<a href="?so=dd"><font class="adminlink">#</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=dd"><img src="images/s_down.gif" width="9" height="9" border="0"></a>';
                break;
            case 'dd':
                // sort by date descending
                $output .= '<a href="?so=da"><font class="adminlink">#</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=da"><img src="images/s_up.gif" width="9" height="9" border="0"></a>';
                break;
            default:
                $output .= '<a href="?so=dd"><font class="adminlink">#</font></a>';
                break;
        }
        $output .= "</div></td>";
        // name
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">";
        switch ($sortOrder) {
            case 'na':
                // sort alphabetically by name ascending
                $output .= '<a href="?so=nd"><font class="adminlink">' . _TORRENTFILE . '</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=nd"><img src="images/s_down.gif" width="9" height="9" border="0"></a>';
                break;
            case 'nd':
                // sort alphabetically by name descending
                $output .= '<a href="?so=na"><font class="adminlink">' . _TORRENTFILE . '</font></a>';
                $output .= '&nbsp;';
                $output .= '<a href="?so=na"><img src="images/s_up.gif" width="9" height="9" border="0"></a>';
                break;
            default:
                $output .= '<a href="?so=na"><font class="adminlink">' . _TORRENTFILE . '</font></a>';
                break;
        }
        $output .= "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">Size</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _USER . "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _STATUS . "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ESTIMATEDTIME . "</div></td>";
        $output .= "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ADMIN . "</div></td>";
        $output .= "</tr>\n";
        foreach ($arListTorrent as $torrentrow) {
            $output .= $torrentrow;
        }
    }
    return $output;
}
Example #7
0
 $displayname = preg_replace('#(_torrent)$#i', "", $displayname);
 $arToClean = array("http_", "_www_", "isohunt");
 $displayname = str_ireplace($arToClean, "", $displayname);
 $displayname = str_replace('_', ".", $displayname);
 $displayname = str_replace('..', ".", $displayname);
 $displayname = trim($displayname, '.');
 $displayname = strlen($displayname) > 53 ? substr($displayname, 0, 50) . "..." : $displayname;
 if ($displayname == 'download.php') {
     //must fix $transfer torrent filename before...
     //$name = getTransferFromHash($hash);
     $displayname = 'dup:' . $mtimecrc;
     addGrowlMessage('[dup]', 'This torrent has already been downloaded');
 }
 // owner
 $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($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";
/**
 * 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;
}
/**
 * deletes data of a transfer
 *
 * @param $transfer name of the transfer
 * @return array
 */
function deleteTransferData($transfer)
{
    global $cfg, $transfers;
    $msgs = array();
    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;
}
function getDirList($dirName)
{
    global $cfg, $db;
    include_once "AliasFile.php";
    include_once "RunningTorrent.php";
    $runningTorrents = getRunningTorrents();
    $arList = array();
    $file_filter = getFileFilter($cfg["file_types_array"]);
    if (is_dir($dirName)) {
        $handle = opendir($dirName);
    } else {
        // nothing to read
        if (IsAdmin()) {
            echo "<b>ERROR:</b> " . $dirName . " Path is not valid. Please edit <a href='admin.php?op=configSettings'>settings</a><br>";
        } else {
            echo "<b>ERROR:</b> Contact an admin the Path is not valid.<br>";
        }
        return;
    }
    $lastUser = "";
    $arUserTorrent = array();
    $arListTorrent = array();
    while ($entry = readdir($handle)) {
        if ($entry != "." && $entry != "..") {
            if (is_dir($dirName . "/" . $entry)) {
                // don''t do a thing
            } else {
                if (ereg($file_filter, $entry)) {
                    $key = filemtime($dirName . "/" . $entry) . md5($entry);
                    $arList[$key] = $entry;
                }
            }
        }
    }
    // sort the files by date
    krsort($arList);
    foreach ($arList as $entry) {
        $output = "";
        $displayname = $entry;
        $show_run = true;
        $torrentowner = getOwner($entry);
        $owner = IsOwner($cfg["user"], $torrentowner);
        $kill_id = "";
        $estTime = "&nbsp;";
        $alias = getAliasName($entry) . ".stat";
        $af = new AliasFile($dirName . $alias, $torrentowner);
        $timeStarted = "";
        $torrentfilelink = "";
        if (!file_exists($dirName . $alias)) {
            $af->running = "2";
            // file is new
            $af->size = getDownloadSize($dirName . $entry);
            $af->WriteFile();
        }
        if (strlen($entry) >= 47) {
            // needs to be trimmed
            $displayname = substr($entry, 0, 44);
            $displayname .= "...";
        }
        // find out if any screens are running and take their PID and make a KILL option
        foreach ($runningTorrents as $key => $value) {
            $rt = new RunningTorrent($value);
            if ($rt->statFile == $alias) {
                if ($kill_id == "") {
                    $kill_id = $rt->processId;
                } else {
                    // there is more than one PID for this torrent
                    // Add it so it can be killed as well.
                    $kill_id .= "|" . $rt->processId;
                }
            }
        }
        // Check to see if we have a pid without a process.
        if (is_file($cfg["torrent_file_path"] . $alias . ".pid") && empty($kill_id)) {
            // died outside of tf and pid still exists.
            @unlink($cfg["torrent_file_path"] . $alias . ".pid");
            if ($af->percent_done < 100 && $af->percent_done >= 0) {
                // The file is not running and the percent done needs to be changed
                $af->percent_done = ($af->percent_done + 100) * -1;
            }
            $af->running = "0";
            $af->time_left = "Torrent Died";
            $af->up_speed = "";
            $af->down_speed = "";
            // write over the status file so that we can display a new status
            $af->WriteFile();
        }
        if ($cfg["enable_torrent_download"]) {
            $torrentfilelink = "<a href=\"maketorrent.php?download=" . urlencode($entry) . "\"><img src=\"images/down.gif\" width=9 height=9 title=\"Download Torrent File\" border=0 align=\"absmiddle\"></a>";
        }
        $hd = getStatusImage($af);
        $output .= "<tr><td class=\"tiny\"><img src=\"images/" . $hd->image . "\" width=16 height=16 title=\"" . $hd->title . $entry . "\" border=0 align=\"absmiddle\">" . $torrentfilelink . $displayname . "</td>";
        $output .= "<td align=\"right\"><font class=\"tiny\">" . formatBytesToKBMGGB($af->size) . "</font></td>";
        $output .= "<td align=\"center\"><a href=\"message.php?to_user="******"\"><font class=\"tiny\">" . $torrentowner . "</font></a></td>";
        $output .= "<td valign=\"bottom\"><div align=\"center\">";
        if ($af->running == "2") {
            $output .= "<i><font color=\"#32cd32\">" . _NEW . "</font></i>";
        } elseif ($af->running == "3") {
            $estTime = "Waiting...";
            $qDateTime = '';
            if (is_file($dirName . "queue/" . $alias . ".Qinfo")) {
                $qDateTime = date("m/d/Y H:i:s", strval(filectime($dirName . "queue/" . $alias . ".Qinfo")));
            }
            $output .= "<i><font color=\"#000000\" onmouseover=\"return overlib('" . _QUEUED . ": " . $qDateTime . "<br>', CSSCLASS);\" onmouseout=\"return nd();\">" . _QUEUED . "</font></i>";
        } else {
            if ($af->time_left != "" && $af->time_left != "0") {
                $estTime = $af->time_left;
            }
            $sql_search_time = "Select time from tf_log where action like '%Upload' and file like '" . $entry . "%'";
            $result_search_time = $db->Execute($sql_search_time);
            list($uploaddate) = $result_search_time->FetchRow();
            $lastUser = $torrentowner;
            $sharing = $af->sharing . "%";
            $graph_width = 1;
            $progress_color = "#00ff00";
            $background = "#000000";
            $bar_width = "4";
            $popup_msg = _ESTIMATEDTIME . ": " . $af->time_left;
            $popup_msg .= "<br>" . _DOWNLOADSPEED . ": " . $af->down_speed;
            $popup_msg .= "<br>" . _UPLOADSPEED . ": " . $af->up_speed;
            $popup_msg .= "<br>" . _SHARING . ": " . $sharing;
            $popup_msg .= "<br>Seeds: " . $af->seeds;
            $popup_msg .= "<br>Peers: " . $af->peers;
            $popup_msg .= "<br>" . _USER . ": " . $torrentowner;
            $eCount = 0;
            foreach ($af->errors as $key => $value) {
                if (strpos($value, " (x")) {
                    $curEMsg = substr($value, strpos($value, " (x") + 3);
                    $eCount += substr($curEMsg, 0, strpos($curEMsg, ")"));
                } else {
                    $eCount += 1;
                }
            }
            $popup_msg .= "<br>" . _ERRORSREPORTED . ": " . strval($eCount);
            $popup_msg .= "<br>" . _UPLOADED . ": " . date("m/d/Y H:i:s", $uploaddate);
            if (is_file($dirName . $alias . ".pid")) {
                $timeStarted = "<br>" . _STARTED . ": " . date("m/d/Y H:i:s", strval(filectime($dirName . $alias . ".pid")));
            }
            // incriment the totals
            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($af->up_speed);
            $cfg["total_download"] = $cfg["total_download"] + GetSpeedValue($af->down_speed);
            if ($af->percent_done >= 100) {
                if (trim($af->up_speed) != "" && $af->running == "1") {
                    $popup_msg .= $timeStarted;
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" style=\"font-size:7pt;\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\">seeding (" . $af->up_speed . ") " . $sharing . "</a>";
                } else {
                    $popup_msg .= "<br>" . _ENDED . ": " . date("m/d/Y H:i:s", strval(filemtime($dirName . $alias)));
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=red>" . _DONE . "</font></i></a>";
                }
                $show_run = false;
            } else {
                if ($af->percent_done < 0) {
                    $popup_msg .= $timeStarted;
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=\"#989898\">" . _INCOMPLETE . "</font></i></a>";
                    $show_run = true;
                } else {
                    $popup_msg .= $timeStarted;
                    if ($af->percent_done > 1) {
                        $graph_width = $af->percent_done;
                    }
                    if ($graph_width == 100) {
                        $background = $progress_color;
                    }
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=" . $alias . "&torrent=" . urlencode($entry) . "')\" onmouseover=\"return overlib('" . $popup_msg . "<br>', CSSCLASS);\" onmouseout=\"return nd();\">";
                    $output .= "<font class=\"tiny\"><strong>" . $af->percent_done . "%</strong> @ " . $af->down_speed . "</font></a><br>";
                    $output .= "<table width=\"100\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
                    $output .= "<tr><td background=\"themes/" . $cfg["theme"] . "/images/progressbar.gif\" bgcolor=\"" . $progress_color . "\"><img src=\"images/blank.gif\" width=\"" . $graph_width . "\" height=\"" . $bar_width . "\" border=\"0\"></td>";
                    $output .= "<td bgcolor=\"" . $background . "\"><img src=\"images/blank.gif\" width=\"" . (100 - $graph_width) . "\" height=\"" . $bar_width . "\" border=\"0\"></td>";
                    $output .= "</tr></table>";
                }
            }
        }
        $output .= "</div></td>";
        $output .= "<td><div class=\"tiny\" align=\"center\">" . $estTime . "</div></td>";
        $output .= "<td><div align=center>";
        $torrentDetails = _TORRENTDETAILS;
        if ($lastUser != "") {
            $torrentDetails .= "\n" . _USER . ": " . $lastUser;
        }
        $output .= "<a href=\"details.php?torrent=" . urlencode($entry);
        if ($af->running == 1) {
            $output .= "&als=false";
        }
        $output .= "\"><img src=\"images/properties.png\" width=18 height=13 title=\"" . $torrentDetails . "\" border=0></a>";
        if ($owner || IsAdmin($cfg["user"])) {
            if ($kill_id != "" && $af->percent_done >= 0 && $af->running == 1) {
                $output .= "<a href=\"index.php?alias_file=" . $alias . "&kill=" . $kill_id . "&kill_torrent=" . urlencode($entry) . "\"><img src=\"images/kill.gif\" width=16 height=16 title=\"" . _STOPDOWNLOAD . "\" border=0></a>";
                $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 border=0>";
            } else {
                if ($torrentowner == "n/a") {
                    $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
                } else {
                    if ($af->running == "3") {
                        $output .= "<a href=\"index.php?alias_file=" . $alias . "&dQueue=" . $kill_id . "&QEntry=" . urlencode($entry) . "\"><img src=\"images/queued.gif\" width=16 height=16 title=\"" . _DELQUEUE . "\" border=0></a>";
                    } else {
                        if (!is_file($cfg["torrent_file_path"] . $alias . ".pid")) {
                            // Allow Avanced start popup?
                            if ($cfg["advanced_start"]) {
                                if ($show_run) {
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=" . urlencode($entry) . "')\"><img src=\"images/run_on.gif\" width=16 height=16 title=\"" . _RUNTORRENT . "\" border=0></a>";
                                } else {
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=" . urlencode($entry) . "')\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\"" . _SEEDTORRENT . "\" border=0></a>";
                                }
                            } else {
                                // Quick Start
                                if ($show_run) {
                                    $output .= "<a href=\"" . $_SERVER['PHP_SELF'] . "?torrent=" . urlencode($entry) . "\"><img src=\"images/run_on.gif\" width=16 height=16 title=\"" . _RUNTORRENT . "\" border=0></a>";
                                } else {
                                    $output .= "<a href=\"" . $_SERVER['PHP_SELF'] . "?torrent=" . urlencode($entry) . "\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\"" . _SEEDTORRENT . "\" border=0></a>";
                                }
                            }
                        } else {
                            // pid file exists so this may still be running or dieing.
                            $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\"" . _STOPPING . "\">";
                        }
                    }
                }
                if (!is_file($cfg["torrent_file_path"] . $alias . ".pid")) {
                    $deletelink = $_SERVER['PHP_SELF'] . "?alias_file=" . $alias . "&delfile=" . urlencode($entry);
                    $output .= "<a href=\"" . $deletelink . "\" onclick=\"return ConfirmDelete('" . $entry . "')\"><img src=\"images/delete_on.gif\" width=16 height=16 title=\"" . _DELETE . "\" border=0></a>";
                } else {
                    // pid file present so process may be still running. don't allow deletion.
                    $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 title=\"" . _STOPPING . "\" border=0>";
                }
            }
        } else {
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\"" . _NOTOWNER . "\">";
        }
        $output .= "</div>";
        $output .= "</td>";
        $output .= "</tr>\n";
        // Is this torrent for the user list or the general list?
        if ($cfg["user"] == getOwner($entry)) {
            array_push($arUserTorrent, $output);
        } else {
            array_push($arListTorrent, $output);
        }
    }
    closedir($handle);
    // Now spit out the junk
    echo "<table bgcolor=\"" . $cfg["table_data_bg"] . "\" width=\"100%\" bordercolor=\"" . $cfg["table_border_dk"] . "\" border=1 cellpadding=3 cellspacing=0>";
    if (sizeof($arUserTorrent) > 0) {
        echo "<tr><td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . $cfg["user"] . ": " . _TORRENTFILE . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">Size</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _USER . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _STATUS . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ESTIMATEDTIME . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ADMIN . "</div></td>";
        echo "</tr>\n";
        foreach ($arUserTorrent as $torrentrow) {
            echo $torrentrow;
        }
    }
    if (sizeof($arListTorrent) > 0) {
        echo "<tr><td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _TORRENTFILE . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">Size</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _USER . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _STATUS . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ESTIMATEDTIME . "</div></td>";
        echo "<td background=\"themes/" . $cfg["theme"] . "/images/bar.gif\" bgcolor=\"" . $cfg["table_header_bg"] . "\"><div align=center class=\"title\">" . _ADMIN . "</div></td>";
        echo "</tr>\n";
        foreach ($arListTorrent as $torrentrow) {
            echo $torrentrow;
        }
    }
}