array_push($week_list, array('user_id' => $username, 'month' => $_month, 'week' => date('Y-m-d', strtotime($start)), 'start' => $start, 'downloadstr' => formatFreeSpace($download / 1048576), 'uploadstr' => formatFreeSpace($upload / 1048576), 'totalstr' => formatFreeSpace(($download + $upload) / 1048576)));
         }
         $download = $row[0];
         $upload = $row[1];
         $start = $newstart;
     } else {
         $download += $row[0];
         $upload += $row[1];
     }
 }
 if ($upload + $download != 0) {
     array_push($week_list, array('user_id' => $username, 'month' => $_month, 'week' => date('Y-m-d', strtotime($start)), 'start' => $start, 'downloadstr' => formatFreeSpace($download / 1048576), 'uploadstr' => formatFreeSpace($upload / 1048576), 'totalstr' => formatFreeSpace(($download + $upload) / 1048576)));
 }
 $tmpl->setloop('week_list', $week_list);
 // daily stats
 $xferStats = $wstart ? Xfer::getUsageByDate($username, $wstart, $wend) : Xfer::getUsageByDate($username);
 $start = '';
 $download = 0;
 $upload = 0;
 $day_list = array();
 foreach ($xferStats as $row) {
     $rtime = strtotime($row[2]);
     $newstart = $row[2];
     if ($row[2] == date('Y-m-d')) {
         if ($user_id == '%') {
             $row[0] = $xfer_total['day']['download'];
             $row[1] = $xfer_total['day']['upload'];
         } else {
             $row[0] = $xfer[$username]['day']['download'];
             $row[1] = $xfer[$username]['day']['upload'];
         }
 /**
  * xfer update 2
  */
 function update2()
 {
     global $instanceXfer;
     // initialize if needed
     if (!isset($instanceXfer)) {
         Xfer::initialize();
     }
     // call instance-method
     $instanceXfer->instance_update2();
 }
 /**
  * init xfer stats
  * note : this can only be used after a call to update transfer-values in cfg-
  *        array (eg by getTransferListArray)
  */
 function _initXferStats()
 {
     global $cfg;
     // init labels
     $this->_xferLabels = array('Server : ' . $cfg['_TOTALXFER'], 'Server : ' . $cfg['_MONTHXFER'], 'Server : ' . $cfg['_WEEKXFER'], 'Server : ' . $cfg['_DAYXFER'], 'User : '******'_TOTALXFER'], 'User : '******'_MONTHXFER'], 'User : '******'_WEEKXFER'], 'User : '******'_DAYXFER']);
     $this->_xferStats = Xfer::getStatsFormatted();
 }
/**
 * maintenance
 *
 * @param $action
 */
function sa_maintenance($action = "")
{
    global $cfg, $error, $statusImage, $statusMessage, $htmlTitle, $htmlTop, $htmlMain;
    if ($action == "") {
        return;
    }
    buildPage("m");
    switch ($action) {
        case "0":
            // Maintenance-main
            $htmlTitle = "Maintenance";
            $htmlMain .= '<p>Select the maintenance task you wish to perform below:<br><br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=1"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Main" border="0"> Main</a> - clean up stale files; resume stalled transfers';
            $htmlMain .= '<p>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=2"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Kill" border="0"> Kill</a> - kill rebel processes';
            $htmlMain .= '<p>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=3"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Clean" border="0"> Clean</a> - clean up stale cache/pid/template files';
            $htmlMain .= '<p>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=4"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Repair" border="0"> Repair</a> - check for erroneous stat/pid files, fix bad db entries, prune old db items';
            $htmlMain .= '<p>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=5"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Reset" border="0"> Reset</a> - reset transfer totals, xfer stats and personal settings';
            $htmlMain .= '<p>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=6"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Lock" border="0"> Lock</a> - lock access to the frontend';
            $htmlMain .= '<br><br>';
            break;
        case "1":
            // Maintenance: Main
            $htmlTitle = "Maintenance - Main";
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Standard</strong><br>';
            $htmlMain .= 'Standard Maintenance Run - same as on index-page and automatic called on every login<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=11"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Standard Maintenance-Run" border="0"> Standard Maintenance Run</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Extended</strong><br>';
            $htmlMain .= 'Extended Maintenance Run - like a standard run but will also restart all dead transfers.<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=12"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="vlc-kill" border="0"> Extended Maintenance Run</a>';
            $htmlMain .= '<br><br>';
            break;
        case "11":
            // Maintenance: Main: Standard Maintenance-Run
            $htmlTitle = "Maintenance - Main - Standard Maintenance Run";
            $htmlMain .= '<br>';
            $htmlMain .= 'Standard Maintenance Run: ';
            require_once "inc/classes/MaintenanceAndRepair.php";
            MaintenanceAndRepair::maintenance(MAINTENANCEANDREPAIR_TYPE_STD);
            $htmlMain .= ' <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            break;
        case "12":
            // Maintenance: Main
            $htmlTitle = "Maintenance - Main - Extended Maintenance Run";
            $htmlMain .= '<br>';
            $htmlMain .= 'Extended Maintenance Run: ';
            require_once "inc/classes/MaintenanceAndRepair.php";
            MaintenanceAndRepair::maintenance(MAINTENANCEANDREPAIR_TYPE_EXT);
            $htmlMain .= ' <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            break;
        case "2":
            // Maintenance-Kill
            $htmlTitle = "Maintenance - Kill";
            $htmlMain .= '<br>';
            $htmlMain .= '<font color="red"><strong>DON\'T</strong> do this or you will screw up things for sure!</font><br><br>';
            $htmlMain .= 'This is only meant as emergency \'last resort\' if things have already gone terribly wrong already.<br>Please use this only if you know what you are doing.<br><br><hr><strong>ALL the selected process types will be killed, not just those related to torrentflux-b4rt!!!</strong><hr><br>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>PHP</strong><br>';
            $htmlMain .= 'Kill all PHP processes:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=21"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="php-kill" border="0"> PHP Kill</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Python</strong><br>';
            $htmlMain .= 'Kill all python processes:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=22"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="python-kill" border="0"> Python Kill</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Perl</strong><br>';
            $htmlMain .= 'Kill all perl processes:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=23"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="perl-kill" border="0"> Perl Kill</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Transmissioncli</strong><br>';
            $htmlMain .= 'Kill all transmissioncli processes:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=24"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="transmissioncli-kill" border="0"> Transmissioncli Kill</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Wget</strong><br>';
            $htmlMain .= 'Kill all wget processes:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=25"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="wget-kill" border="0"> Wget Kill</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>VLC</strong><br>';
            $htmlMain .= 'Kill all VLC processes:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=26"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="vlc-kill" border="0"> VLC Kill</a>';
            $htmlMain .= '<br><br>';
            break;
        case "21":
            // Maintenance-Kill: php
            $htmlTitle = "Maintenance - Kill - PHP";
            $htmlMain .= '<br>';
            $htmlMain .= 'Kill all PHP processes: <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            $htmlMain .= '<strong>Process list (filtered) before call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " php | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            $callResult = trim(shell_exec("killall -9 php 2> /dev/null"));
            if (isset($callResult) && $callResult != "") {
                $htmlMain .= '<br>';
                $htmlMain .= 'Call Result: <br>';
                $htmlMain .= '<pre>' . tfb_htmlencode($callResult) . '</pre>';
                $htmlMain .= '<br>';
            }
            sleep(2);
            // just 2 sec
            $htmlMain .= '<strong>Process list (filtered) after call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " php | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            break;
        case "22":
            // Maintenance-Kill: python
            $htmlTitle = "Maintenance - Kill - Python";
            $htmlMain .= '<br>';
            $htmlMain .= 'Kill all python processes: <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            $htmlMain .= '<strong>Process list (filtered) before call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " python | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            $callResult = trim(shell_exec("killall -9 python 2> /dev/null"));
            if (isset($callResult) && $callResult != "") {
                $htmlMain .= '<br>';
                $htmlMain .= 'Call Result: <br>';
                $htmlMain .= '<pre>' . tfb_htmlencode($callResult) . '</pre>';
                $htmlMain .= '<br>';
            }
            sleep(2);
            // just 2 sec
            $htmlMain .= '<strong>Process list (filtered) after call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " python | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            break;
        case "23":
            // Maintenance-Kill: perl
            $htmlTitle = "Maintenance - Kill - Perl";
            $htmlMain .= '<br>';
            $htmlMain .= 'Kill all perl processes: <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            $htmlMain .= '<strong>Process list (filtered) before call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " perl | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            $callResult = trim(shell_exec("killall -9 perl 2> /dev/null"));
            if (isset($callResult) && $callResult != "") {
                $htmlMain .= '<br>';
                $htmlMain .= 'Call Result: <br>';
                $htmlMain .= '<pre>' . tfb_htmlencode($callResult) . '</pre>';
                $htmlMain .= '<br>';
            }
            sleep(2);
            // just 2 sec
            $htmlMain .= '<strong>Process list (filtered) after call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " perl | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            break;
        case "24":
            // Maintenance-Kill: transmissioncli
            $htmlTitle = "Maintenance - Kill - Transmissioncli";
            $htmlMain .= '<br>';
            $htmlMain .= 'Kill all transmissioncli processes: <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            $htmlMain .= '<strong>Process list (filtered) before call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " transmissioncli | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            $callResult = trim(shell_exec("killall -9 transmissioncli 2> /dev/null"));
            if (isset($callResult) && $callResult != "") {
                $htmlMain .= '<br>';
                $htmlMain .= 'Call Result: <br>';
                $htmlMain .= '<pre>' . tfb_htmlencode($callResult) . '</pre>';
                $htmlMain .= '<br>';
            }
            sleep(2);
            // just 2 sec
            $htmlMain .= '<strong>Process list (filtered) after call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " transmissioncli | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            break;
        case "25":
            // Maintenance-Kill: wget
            $htmlTitle = "Maintenance - Kill - Wget";
            $htmlMain .= '<br>';
            $htmlMain .= 'Kill all wget processes: <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            $htmlMain .= '<strong>Process list (filtered) before call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " wget | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            $callResult = trim(shell_exec("killall -9 wget 2> /dev/null"));
            if (isset($callResult) && $callResult != "") {
                $htmlMain .= '<br>';
                $htmlMain .= 'Call Result: <br>';
                $htmlMain .= '<pre>' . tfb_htmlencode($callResult) . '</pre>';
                $htmlMain .= '<br>';
            }
            sleep(2);
            // just 2 sec
            $htmlMain .= '<strong>Process list (filtered) after call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " wget | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            break;
        case "26":
            // Maintenance-Kill: vlc
            $htmlTitle = "Maintenance - Kill - VLC";
            $htmlMain .= '<br>';
            $htmlMain .= 'Kill all VLC processes: <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            $htmlMain .= '<strong>Process list (filtered) before call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " vlc | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            $callResult = trim(shell_exec("killall -9 vlc 2> /dev/null"));
            if (isset($callResult) && $callResult != "") {
                $htmlMain .= '<br>';
                $htmlMain .= 'Call Result: <br>';
                $htmlMain .= '<pre>' . tfb_htmlencode($callResult) . '</pre>';
                $htmlMain .= '<br>';
            }
            sleep(2);
            // just 2 sec
            $htmlMain .= '<strong>Process list (filtered) after call:</strong><br>';
            $htmlMain .= '<pre>';
            $htmlMain .= tfb_htmlencode(trim(shell_exec("ps auxww | " . $cfg['bin_grep'] . " vlc | " . $cfg['bin_grep'] . " -v grep")));
            $htmlMain .= '</pre>';
            $htmlMain .= '<br>';
            break;
        case "3":
            // Maintenance-Clean
            $htmlTitle = "Maintenance - Clean";
            $htmlMain .= '<br>Select the action to perform below:<br><hr><strong>Please stop any running transfers BEFORE cleaning the PID or cache files!!!</strong><hr><br>';
            $htmlMain .= '<strong>Process ID (PID) File Leftovers</strong><br>';
            $htmlMain .= 'Delete stale PID files from deleted transfers:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=31"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="pid-file-clean" border="0"> PID File Clean</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>BitTornado</strong><br>';
            $htmlMain .= 'Delete the BitTornado cache:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=32"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="tornado-clean" border="0"> BitTornado Clean</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Transmission</strong><br>';
            $htmlMain .= 'Delete Transmission cache:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=33"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="transmission-clean" border="0"> Transmission Clean</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>BitTorrent Mainline</strong><br>';
            $htmlMain .= 'Delete BitTorrent Mainline cache:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=34"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="mainline-clean" border="0"> BitTorrent Mainline Clean</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Template Cache</strong><br>';
            $htmlMain .= 'Delete the Torrentflux-b4rt template cache:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=35"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="template-cache-clean" border="0"> Template Cache Clean</a>';
            $htmlMain .= '<br><br>';
            break;
        case "31":
            // Maintenance-Clean: pid-file-clean
            $htmlTitle = "Maintenance - Clean - PID Files";
            $htmlMain .= '<br><strong>Cleaning stale PID files:</strong><br>';
            $result = "";
            $transferList = getTransferArrayFromDB();
            if ($dirHandle = @opendir($cfg["transfer_file_path"])) {
                while (false !== ($file = readdir($dirHandle))) {
                    if (strlen($file) > 3 && substr($file, -4, 4) == ".pid") {
                        $tname = substr($file, 0, -4);
                        if (!in_array($tname, $transferList)) {
                            // transfer not in db. delete pid-file.
                            $result .= tfb_htmlencode($file) . "\n";
                            @unlink($cfg["transfer_file_path"] . $file);
                        }
                    }
                }
                closedir($dirHandle);
            }
            if (strlen($result) > 0) {
                $htmlMain .= '<br>Deleted stale PID files: <br><pre>' . $result . '</pre><br>';
            } else {
                $htmlMain .= '<br>No stale PID files found.<br><br>';
            }
            break;
        case "32":
            // Maintenance-Clean: tornado-clean
            $htmlTitle = "Maintenance - Clean - BitTornado";
            $htmlMain .= '<br><strong>Cleaning BitTornado cache:</strong><br>';
            $result = "";
            $result .= cleanDir($cfg["path"] . '.BitTornado/datacache');
            $result .= cleanDir($cfg["path"] . '.BitTornado/torrentcache');
            $result .= cleanDir($cfg["path"] . '.BitTornado/piececache');
            $result .= cleanDir($cfg["path"] . '.BitTornado/icons');
            if (strlen($result) > 0) {
                $htmlMain .= '<br>Deleted cache: <br><pre>' . $result . '</pre><br>';
            } else {
                $htmlMain .= '<br>Nothing found.<br><br>';
            }
            break;
        case "33":
            // Maintenance-Clean: transmission-clean
            $htmlTitle = "Maintenance - Clean - Transmission";
            $htmlMain .= '<br><strong>Cleaning Transmission cache:</strong><br>';
            $result = "";
            $hashes = array();
            $transferList = getTransferArray();
            foreach ($transferList as $transfer) {
                array_push($hashes, getTransferHash($transfer));
            }
            if ($dirHandle = @opendir($cfg["path"] . ".transmission/cache/")) {
                while (false !== ($file = readdir($dirHandle))) {
                    if ($file[0] == "r") {
                        $thash = substr($file, -40);
                        if (!in_array($thash, $hashes)) {
                            // torrent not in db. delete cache-file.
                            $result .= tfb_htmlencode($file) . "\n";
                            @unlink($cfg["path"] . ".transmission/cache/resume." . $thash);
                        }
                    }
                }
                closedir($dirHandle);
            }
            if (strlen($result) > 0) {
                $htmlMain .= '<br>Deleted cache: <br><pre>' . $result . '</pre><br>';
            } else {
                $htmlMain .= '<br>Nothing found.<br><br>';
            }
            break;
        case "34":
            // Maintenance-Clean: mainline-clean
            $htmlTitle = "Maintenance - Clean - BitTorrent Mainline";
            $htmlMain .= '<br><strong>Cleaning BitTorrent Mainline cache:</strong><br>';
            $result = "";
            $result .= cleanDir($cfg["path"] . '.bittorrent/console/resume');
            $result .= cleanDir($cfg["path"] . '.bittorrent/console/metainfo');
            $result .= cleanDir($cfg["path"] . '.bittorrent/console/torrents');
            $result .= cleanDir($cfg["path"] . '.bittorrent/mutex');
            if (strlen($result) > 0) {
                $htmlMain .= '<br>Deleted cache: <br><pre>' . $result . '</pre><br>';
            } else {
                $htmlMain .= '<br>Nothing found.<br><br>';
            }
            break;
        case "35":
            // Maintenance-Clean:template-cache-clean
            $htmlTitle = "Maintenance - Clean - Template Cache";
            $htmlMain .= '<br><strong>Cleaning Torrentflux-b4rt Template Cache:</strong><br>';
            $result = cleanDir($cfg["path"] . '.templateCache');
            if (strlen($result) > 0) {
                $htmlMain .= '<br>Deleted compiled templates: <br><pre>' . $result . '</pre><br>';
            } else {
                $htmlMain .= '<br>No compiled templates found.<br><br>';
            }
            break;
        case "4":
            // Maintenance: Repair
            $htmlTitle = "Maintenance - Repair";
            $htmlMain .= '<br>';
            $htmlMain .= '<hr><font color="red"><strong>DON\'T</strong> do this if your system is running as it should. You WILL break something.</font><hr>';
            $htmlMain .= '<br>The \'Repair\' action will attempt to repair any problems such as out of synch stat files, erroneous PID files, bad hash entries in the database as well as pruning the database.<br><br>Only use this after a server-reboot, if transfers were killed or if there are other problems with the webapp that can\'t be resolved another way.<br>';
            $htmlMain .= '<br><a href="' . _FILE_THIS . '?m=41"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Repair" border="0"> Repair</a>';
            $htmlMain .= '<br><br>';
            break;
        case "41":
            // Maintenance: Repair
            $htmlTitle = "Maintenance - Repair";
            $htmlMain .= '<br>';
            $htmlMain .= 'Repairing Torrentflux-b4rt:';
            require_once "inc/classes/MaintenanceAndRepair.php";
            MaintenanceAndRepair::repair();
            $htmlMain .= ' <font color="green">done</font>';
            $htmlMain .= '<br><br>';
            break;
        case "5":
            // Maintenance: Reset
            $htmlTitle = "Maintenance - Reset";
            $htmlMain .= '<br>Select the item you wish to reset below:<br><br>';
            $htmlMain .= '<strong>Transfer Totals</strong><br>';
            $htmlMain .= 'Reset the transfer totals (totals uploaded/downloaded in the transfer list):<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=51"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="transfer-totals" border="0"> Reset Transfer Totals</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Xfer Stats</strong><br>';
            $htmlMain .= 'Reset the transfer statistics:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=52"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="xfer-stats" border="0"> Reset Xfer Stats</a>';
            $htmlMain .= '<p>';
            $htmlMain .= '<strong>Personal Settings</strong><br>';
            $htmlMain .= 'Reset the personal settings of all users:<br>';
            $htmlMain .= '<a href="' . _FILE_THIS . '?m=53"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="personal-settings" border="0"> Reset Personal Settings</a>';
            $htmlMain .= '<br><br>';
            break;
        case "51":
            // Maintenance: Reset - transfer-totals
            $htmlTitle = "Maintenance - Reset - Transfer Totals";
            $htmlMain .= '<br>';
            $htmlMain .= 'Resetting transfer totals:<br>';
            $result = resetAllTransferTotals();
            $htmlMain .= $result === true ? ' <font color="green">Done</font>' : '<br><font color="red">Error:</font><br>' . $result;
            $htmlMain .= '<br><br>';
            break;
        case "52":
            // Maintenance: Reset - xfer
            $htmlTitle = "Maintenance - Reset - Transfer Statistics";
            $htmlMain .= '<br>';
            $htmlMain .= 'Resetting xfer stats:<br>';
            $result = Xfer::resetStats();
            $htmlMain .= $result === true ? ' <font color="green">Done</font>' : '<br><font color="red">Error:</font><br>' . $result;
            $htmlMain .= '<br><br>';
            break;
        case "53":
            // Maintenance: Reset - personal-settings
            $htmlTitle = "Maintenance - Reset - Personal Settings";
            $htmlMain .= '<br>';
            $htmlMain .= 'Resetting personal settings:<br>';
            $result = deleteAllUserSettings();
            $htmlMain .= $result === true ? ' <font color="green">Done</font>' : '<br><font color="red">Error:</font><br>' . $result;
            $htmlMain .= '<br><br>';
            break;
        case "6":
            // Maintenance: Lock
            $htmlTitle = "Maintenance - Lock Torrentflux-b4rt Frontend";
            $htmlMain .= '<br>Lock/unlock access to the Torrentflux-b4rt frontend.  Only the superadmin can access the locked frontend.<br><br><hr>';
            switch ($cfg['webapp_locked']) {
                case 0:
                    $htmlMain .= '<strong><font color="green">Frontend currently unlocked.</font></strong>';
                    break;
                case 1:
                    $htmlMain .= '<strong><font color="red">Frontend currently locked.</font></strong>';
                    break;
            }
            $htmlMain .= '<hr><p>';
            $htmlMain .= '<br><a href="' . _FILE_THIS . '?m=61"><img src="themes/' . $cfg["theme"] . '/images/arrow.gif" width="9" height="9" title="Repair" border="0"> ';
            $htmlMain .= $cfg['webapp_locked'] == 1 ? 'Unlock' : 'Lock';
            $htmlMain .= ' Frontend</a>';
            $htmlMain .= '<br><br>';
            break;
        case "61":
            // Maintenance: lock/unlock
            $htmlTitle = "Maintenance - Lock";
            $htmlMain .= '<br>';
            switch ($cfg['webapp_locked']) {
                case 0:
                    $result = setWebappLock(1);
                    $htmlMain .= "Locking frontend:<br>";
                    $htmlMain .= $result === true ? '<font color="green">Done</font>' : '<br><font color="red">Error:</font><br>' . $result;
                    break;
                case 1:
                    $result = setWebappLock(0);
                    $htmlMain .= "Unlocking frontend:<br>";
                    $htmlMain .= $result === true ? '<font color="green">Done</font>' : '<br><font color="red">Error:</font><br>' . $result;
                    break;
            }
            $htmlMain .= '<br><br>';
            break;
    }
    printPage();
    exit;
}
 /**
  * Xfer Shutdown
  *
  * @param $delta
  * @return mixed
  */
 function _xfer($delta)
 {
     global $cfg, $db;
     // check xfer
     if ($cfg['enable_xfer'] != 1) {
         $this->_outputError("xfer must be enabled.\n");
         return false;
     }
     // check arg
     if ($delta != "all" && $delta != "total" && $delta != "month" && $delta != "week" && $delta != "day") {
         $this->_outputMessage('invalid delta : "' . $delta . '"' . "\n");
         return false;
     }
     $this->_outputMessage('checking xfer-limit(s) for "' . $delta . '" ...' . "\n");
     // set xfer-realtime
     $cfg['xfer_realtime'] = 1;
     // set xfer-newday
     Xfer::setNewday();
     // getTransferListArray to update xfer-stats
     $transferList = @getTransferListArray();
     // get xfer-totals
     $xfer_total = Xfer::getStatsTotal();
     // check if break needed
     // total
     if ($delta == "total" || $delta == "all") {
         // only do if a limit is set
         if ($cfg["xfer_total"] > 0) {
             if ($xfer_total['total']['total'] >= $cfg["xfer_total"] * 1048576) {
                 // limit met, stop all Transfers now.
                 $this->_outputMessage('Limit met for "total" : ' . formatFreeSpace($xfer_total['total']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_total"]) . "\n");
                 return $this->_transfersStop();
             } else {
                 $this->_outputMessage('Limit not met for "total" : ' . formatFreeSpace($xfer_total['total']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_total"]) . "\n");
             }
         } else {
             $this->_outputMessage('no limit set for "total"' . "\n");
         }
     }
     // month
     if ($delta == "month" || $delta == "all") {
         // only do if a limit is set
         if ($cfg["xfer_month"] > 0) {
             if ($xfer_total['month']['total'] >= $cfg["xfer_month"] * 1048576) {
                 // limit met, stop all Transfers now.
                 $this->_outputMessage('Limit met for "month" : ' . formatFreeSpace($xfer_total['month']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_month"]) . "\n");
                 return $this->_transfersStop();
             } else {
                 $this->_outputMessage('Limit not met for "month" : ' . formatFreeSpace($xfer_total['month']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_month"]) . "\n");
             }
         } else {
             $this->_outputMessage('no limit set for "month"' . "\n");
         }
     }
     // week
     if ($delta == "week" || $delta == "all") {
         // only do if a limit is set
         if ($cfg["xfer_week"] > 0) {
             if ($xfer_total['week']['total'] >= $cfg["xfer_week"] * 1048576) {
                 // limit met, stop all Transfers now.
                 $this->_outputMessage('Limit met for "week" : ' . formatFreeSpace($xfer_total['week']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_week"]) . "\n");
                 return $this->_transfersStop();
             } else {
                 $this->_outputMessage('Limit not met for "week" : ' . formatFreeSpace($xfer_total['week']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_week"]) . "\n");
             }
         } else {
             $this->_outputMessage('no limit set for "week"' . "\n");
         }
     }
     // day
     if ($delta == "day" || $delta == "all") {
         // only do if a limit is set
         if ($cfg["xfer_day"] > 0) {
             if ($xfer_total['day']['total'] >= $cfg["xfer_day"] * 1048576) {
                 // limit met, stop all Transfers now.
                 $this->_outputMessage('Limit met for "day" : ' . formatFreeSpace($xfer_total['day']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_day"]) . "\n");
                 return $this->_transfersStop();
             } else {
                 $this->_outputMessage('Limit not met for "day" : ' . formatFreeSpace($xfer_total['day']['total'] / 1048576) . " / " . formatFreeSpace($cfg["xfer_day"]) . "\n");
             }
         } else {
             $this->_outputMessage('no limit set for "day"' . "\n");
         }
     }
     // done
     $this->_outputMessage("done.\n");
     return true;
 }
Exemple #6
0
 if (!array_key_exists("total_upload", $cfg)) {
     $cfg["total_upload"] = 0;
 }
 // xfer
 if ($cfg['enable_xfer'] != 0 && $cfg['xfer_realtime'] != 0) {
     $tmpl->setvar('_SERVERXFERSTATS', $cfg['_SERVERXFERSTATS']);
     $tmpl->setvar('_TOTALXFER', $cfg['_TOTALXFER']);
     $tmpl->setvar('_MONTHXFER', $cfg['_MONTHXFER']);
     $tmpl->setvar('_WEEKXFER', $cfg['_WEEKXFER']);
     $tmpl->setvar('_DAYXFER', $cfg['_DAYXFER']);
     $tmpl->setvar('_YOURXFERSTATS', $cfg['_YOURXFERSTATS']);
     $tmpl->setvar('totalxfer1', @formatFreeSpace($xfer_total['total']['total'] / 1048576));
     $tmpl->setvar('monthxfer1', @formatFreeSpace($xfer_total['month']['total'] / 1048576));
     $tmpl->setvar('weekxfer1', @formatFreeSpace($xfer_total['week']['total'] / 1048576));
     $tmpl->setvar('dayxfer1', @formatFreeSpace($xfer_total['day']['total'] / 1048576));
     $xfer = Xfer::getStats();
     $tmpl->setvar('total2', @formatFreeSpace($xfer[$cfg["user"]]['total']['total'] / 1048576));
     $tmpl->setvar('month2', @formatFreeSpace($xfer[$cfg["user"]]['month']['total'] / 1048576));
     $tmpl->setvar('week2', @formatFreeSpace($xfer[$cfg["user"]]['week']['total'] / 1048576));
     $tmpl->setvar('day2', @formatFreeSpace($xfer[$cfg["user"]]['day']['total'] / 1048576));
 }
 // queue
 if (FluxdQmgr::isRunning()) {
     $tmpl->setvar('_QUEUEMANAGER', $cfg['_QUEUEMANAGER']);
     $tmpl->setvar('runningTransferCount', getRunningTransferCount());
     $tmpl->setvar('countQueuedTransfers', FluxdQmgr::countQueuedTransfers());
     $tmpl->setvar('limitGlobal', $cfg["fluxd_Qmgr_maxTotalTransfers"]);
     $tmpl->setvar('limitUser', $cfg["fluxd_Qmgr_maxUserTransfers"]);
 }
 // other
 $tmpl->setvar('_OTHERSERVERSTATS', $cfg['_OTHERSERVERSTATS']);
/**
 * 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 a transfer
  *
  * @return boolean
  */
 function _delete()
 {
     global $cfg;
     // delete
     if ($cfg["user"] == $this->owner || $cfg['isAdmin']) {
         // XFER: before deletion save upload/download xfer data to SQL
         if ($cfg['enable_xfer'] == 1) {
             $transferTotals = $this->getTransferCurrent($this->transfer);
             Xfer::save($this->owner, $transferTotals["downtotal"], $transferTotals["uptotal"]);
         }
         // update totals
         $this->_updateTotals();
         // remove settings from db
         deleteTransferSettings($this->transfer);
         // client-cache
         $this->deleteCache($this->transfer);
         // command-clean
         CommandHandler::clean($this->transfer);
         // remove meta-file
         if (@file_exists($this->transferFilePath)) {
             @unlink($this->transferFilePath);
         }
         // remove stat-file
         if (@file_exists($this->transferFilePath . ".stat")) {
             @unlink($this->transferFilePath . ".stat");
         }
         // if exist remove pid file
         if (@file_exists($this->transferFilePath . ".pid")) {
             @unlink($this->transferFilePath . ".pid");
         }
         // if exist remove log-file
         if (@file_exists($this->transferFilePath . ".log")) {
             @unlink($this->transferFilePath . ".log");
         }
         // if exist remove prio-file
         if (@file_exists($this->transferFilePath . ".prio")) {
             @unlink($this->transferFilePath . ".prio");
         }
         AuditAction($cfg["constants"]["delete_transfer"], $this->transfer);
         return true;
     } else {
         AuditAction($cfg["constants"]["error"], "ILLEGAL DELETE: " . $this->transfer);
         return false;
     }
 }
        $cfg["theme"] = CheckandSetUserTheme();
    }
    // Run internal maintenance regularly
    if (!empty($_SESSION['next_int_maintenance']) && $_SESSION['next_int_maintenance'] < time()) {
        require_once "inc/classes/MaintenanceAndRepair.php";
        MaintenanceAndRepair::maintenance(MAINTENANCEANDREPAIR_TYPE_INT);
        $_SESSION['next_int_maintenance'] = null;
    }
}
// schedule next internal maintenance if needed
if (empty($_SESSION['next_int_maintenance'])) {
    $_SESSION['next_int_maintenance'] = time() + 2 * 3600 + mt_rand(-1200, 1200);
}
// 2h (+/- 20m)
// free space in MB var
$cfg["free_space"] = @disk_free_space($cfg["path"]) / 1048576;
// drive space var
$cfg['driveSpace'] = getDriveSpace($cfg["path"]);
// free space formatted var
$cfg['freeSpaceFormatted'] = formatFreeSpace($cfg["free_space"]);
// Fluxd
Fluxd::initialize();
// Qmgr
FluxdServiceMod::initializeServiceMod('Qmgr');
// xfer
if ($cfg['enable_xfer'] == 1 && $cfg['xfer_realtime'] == 1) {
    // set xfer-newday
    Xfer::setNewday();
}
// vlib
require_once "inc/lib/vlib/vlibTemplate.php";
/**
 * sets vars for the user section
 */
function tmplSetUserSection()
{
    global $cfg, $db, $tmpl;
    // xfer-prepare
    $tmpl->setvar('enable_xfer', $cfg["enable_xfer"]);
    if ($cfg['enable_xfer'] == 1) {
        $tmpl->setvar('userSection_colspan', 8);
        // getTransferListArray to update xfer-stats
        // xfer-init
        if ($cfg['xfer_realtime'] == 0) {
            $cfg['xfer_realtime'] = 1;
            // set xfer-newday
            Xfer::setNewday();
        }
        @getTransferListArray();
    } else {
        $tmpl->setvar('userSection_colspan', 7);
    }
    // activity-prepare
    $total_activity = GetActivityCount();
    $sql = "SELECT user_id, hits, last_visit, time_created, user_level, state FROM tf_users ORDER BY user_id";
    $result = $db->Execute($sql);
    if ($db->ErrorNo() != 0) {
        dbError($sql);
    }
    // user-details
    $user_details_list = array();
    while (list($user_id, $hits, $last_visit, $time_created, $user_level, $user_state) = $result->FetchRow()) {
        // disk-usage
        $disk_usage = "0";
        $tDir = $cfg["path"] . $user_id . "/";
        if (is_dir($tDir)) {
            switch ($cfg["_OS"]) {
                case 1:
                    //Linux
                    $dudir = shell_exec($cfg['bin_du'] . " -sk -h -D " . tfb_shellencode($tDir));
                    break;
                case 2:
                    //BSD
                    $dudir = shell_exec($cfg['bin_du'] . " -sk -h -L " . tfb_shellencode($tDir));
                    break;
            }
            $dusize = explode("\t", $dudir);
            $disk_usage = array_shift($dusize);
        }
        // xfer-usage
        $xfer_usage = $cfg['enable_xfer'] == 1 ? Xfer::getUsage($user_id) : 0;
        // activity
        $user_activity = GetActivityCount($user_id);
        $user_percent = $user_activity == 0 ? 0 : number_format($user_activity / $total_activity * 100);
        // online
        $user_icon = "themes/" . $cfg['theme'] . "/images/user_offline.gif";
        if (IsOnline($user_id)) {
            $user_icon = "themes/" . $cfg['theme'] . "/images/user.gif";
        }
        // level
        $user_image = "themes/" . $cfg['theme'] . "/images/user.gif";
        $type_user = $cfg['_NORMALUSER'];
        if ($user_level == 1) {
            $user_image = "themes/" . $cfg['theme'] . "/images/admin_user.gif";
            $type_user = $cfg['_ADMINISTRATOR'];
        }
        if ($user_level == 2) {
            $user_image = "themes/" . $cfg['theme'] . "/images/superadmin.gif";
            $type_user = $cfg['_SUPERADMIN'];
        }
        $is_superadmin = $user_level <= 1 || IsSuperAdmin() ? 1 : 0;
        // add to list
        array_push($user_details_list, array('is_user' => IsUser($user_id), 'user_id' => $user_id, 'user_icon' => $user_icon, 'hits' => $hits, 'disk_usage' => $disk_usage, 'xfer_usage' => $xfer_usage, 'user_percent' => $user_percent, 'user_percent2' => $user_percent * 2, 'user_percent3' => 200 - $user_percent * 2, 'time_created' => date($cfg['_DATEFORMAT'], $time_created), 'last_visit' => date($cfg['_DATETIMEFORMAT'], $last_visit), 'user_image' => $user_image, 'type_user' => $type_user, 'user_level' => $user_level, 'user_state' => $user_state, 'is_superadmin' => $is_superadmin));
    }
    // set vars
    $tmpl->setvar('_USERDETAILS', $cfg['_USERDETAILS']);
    $tmpl->setvar('_USER', $cfg['_USER']);
    $tmpl->setvar('_HITS', $cfg['_HITS']);
    $tmpl->setvar('_UPLOADACTIVITY', $cfg['_UPLOADACTIVITY']);
    $tmpl->setvar('_JOINED', $cfg['_JOINED']);
    $tmpl->setvar('_LASTVISIT', $cfg['_LASTVISIT']);
    $tmpl->setvar('_ADMIN', $cfg['_ADMIN']);
    $tmpl->setvar('_DAYS', $cfg['_DAYS']);
    $tmpl->setvar('_SENDMESSAGETO', $cfg['_SENDMESSAGETO']);
    $tmpl->setvar('_WARNING', $cfg['_WARNING']);
    $tmpl->setvar('_ABOUTTODELETE', $cfg['_ABOUTTODELETE']);
    $tmpl->setvar('_USERSACTIVITY', $cfg['_USERSACTIVITY']);
    $tmpl->setvar('_EDIT', $cfg['_EDIT']);
    $tmpl->setvar('_DELETE', $cfg['_DELETE']);
    $tmpl->setvar('table_admin_border', $cfg["table_admin_border"]);
    $tmpl->setvar('days_to_keep', $cfg["days_to_keep"]);
    $tmpl->setloop('user_details_list', $user_details_list);
}