/**
 * File Prio Form
 *
 * @param $transfer
 * @param $withForm
 * @return string
 */
function getFilePrioForm($transfer, $withForm = false)
{
    global $cfg;
    $prioFileName = $cfg["transfer_file_path"] . $transfer . ".prio";
    require_once 'inc/classes/BDecode.php';
    $retVal = "";
    // theme-switch
    if (strpos($cfg["theme"], '/') === false) {
        $retVal .= '<link rel="StyleSheet" href="themes/' . $cfg["theme"] . '/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/' . $cfg["theme"] . '/images/dtree/";</script>';
    } else {
        $retVal .= '<link rel="StyleSheet" href="themes/tf_standard_themes/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/tf_standard_themes/images/dtree/";</script>';
    }
    $retVal .= '<script type="text/javascript" src="js/dtree.js"></script>';
    $ftorrent = $cfg["transfer_file_path"] . $transfer;
    $fp = @fopen($ftorrent, "rd");
    $alltorrent = @fread($fp, @filesize($ftorrent));
    @fclose($fp);
    $btmeta = @BDecode($alltorrent);
    $torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
    $dirnum = array_key_exists('files', $btmeta['info']) ? count($btmeta['info']['files']) : 0;
    if (@is_readable($prioFileName)) {
        $prio = explode(',', @file_get_contents($prioFileName));
        $prio = array_splice($prio, 1);
    } else {
        $prio = array();
        for ($i = 0; $i < $dirnum; $i++) {
            $prio[$i] = -1;
        }
    }
    $tree = new dir("/", $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1);
    if (array_key_exists('files', $btmeta['info'])) {
        foreach ($btmeta['info']['files'] as $filenum => $file) {
            $depth = count($file['path']);
            $branch =& $tree;
            for ($i = 0; $i < $depth; $i++) {
                if ($i != $depth - 1) {
                    $d =& $branch->findDir($file['path'][$i]);
                    if ($d) {
                        $branch =& $d;
                    } else {
                        $dirnum++;
                        $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1));
                        $branch =& $d;
                    }
                } else {
                    $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $prio[$filenum]));
                }
            }
        }
    }
    $retVal .= "<table><tr>";
    $retVal .= "<tr><td width=\"110\">Metainfo File:</td><td>" . $transfer . "</td></tr>";
    $retVal .= "<tr><td>Directory Name:</td><td>" . $btmeta['info']['name'] . "</td></tr>";
    $retVal .= "<tr><td>Announce URL:</td><td>" . $btmeta['announce'] . "</td></tr>";
    if (array_key_exists('comment', $btmeta)) {
        $retVal .= "<tr><td valign=\"top\">Comment:</td><td>" . tfb_htmlencode($btmeta['comment']) . "</td></tr>";
    }
    $retVal .= "<tr><td>Created:</td><td>" . date("F j, Y, g:i a", $btmeta['creation date']) . "</td></tr>";
    $retVal .= "<tr><td>Torrent Size:</td><td>" . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")</td></tr>";
    $retVal .= "<tr><td>Chunk size:</td><td>" . $btmeta['info']['piece length'] . " (" . @formatBytesTokBMBGBTB($btmeta['info']['piece length']) . ")</td></tr>";
    if (array_key_exists('files', $btmeta['info'])) {
        $retVal .= "<tr><td>Selected size:</td><td id=\"sel\">0</td></tr>";
        $retVal .= "</table><br>\n";
        if ($withForm) {
            $retVal .= "<form name=\"priority\" action=\"dispatcher.php?action=setFilePriority&riid=_referer_\" method=\"POST\" >";
            $retVal .= "<input type=\"hidden\" name=\"transfer\" value=\"" . $transfer . "\" >";
        }
        $retVal .= "<script type=\"text/javascript\">\n";
        $retVal .= "var sel = 0;\n";
        $retVal .= "d = new dTree('d');\n";
        $retVal .= $tree->draw(-1);
        $retVal .= "document.write(d);\n";
        $retVal .= "sel = getSizes();\n";
        $retVal .= "drawSel();\n";
        $retVal .= "</script>\n";
        $retVal .= "<input type=\"hidden\" name=\"filecount\" value=\"" . count($btmeta['info']['files']) . "\">";
        $retVal .= "<input type=\"hidden\" name=\"count\" value=\"" . $dirnum . "\">";
        $retVal .= "<br>";
        if ($withForm) {
            $retVal .= '<input type="submit" value="Save" >';
            $retVal .= "<br>";
            $retVal .= "</form>";
        }
    } else {
        $retVal .= "</table><br>";
        $retVal .= $btmeta['info']['name'] . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")";
    }
    // return
    return $retVal;
}
function showMetaInfo($torrent, $allowSave = false)
{
    global $cfg;
    if (empty($torrent) || !file_exists($cfg["torrent_file_path"] . $torrent)) {
        echo _NORECORDSFOUND;
    } elseif ($cfg["enable_file_priority"]) {
        $prioFileName = $cfg["torrent_file_path"] . getAliasName($torrent) . ".prio";
        require_once 'BDecode.php';
        echo '<link rel="StyleSheet" href="dtree.css" type="text/css" /><script type="text/javascript" src="dtree.js"></script>';
        $ftorrent = $cfg["torrent_file_path"] . $torrent;
        $fp = fopen($ftorrent, "rd");
        if (!$fp) {
            // Not able to open file
            echo _NORECORDSFOUND;
        } else {
            $alltorrent = fread($fp, filesize($ftorrent));
            fclose($fp);
            $btmeta = BDecode($alltorrent);
            $torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
            if (array_key_exists('files', $btmeta['info'])) {
                $dirnum = count($btmeta['info']['files']);
            } else {
                $dirnum = 0;
            }
            if (is_readable($prioFileName)) {
                $prio = split(',', file_get_contents($prioFileName));
                $prio = array_splice($prio, 1);
            } else {
                $prio = array();
                for ($i = 0; $i < $dirnum; $i++) {
                    $prio[$i] = -1;
                }
            }
            $tree = new dir("/", $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1);
            if (array_key_exists('files', $btmeta['info'])) {
                foreach ($btmeta['info']['files'] as $filenum => $file) {
                    $depth = count($file['path']);
                    $branch =& $tree;
                    for ($i = 0; $i < $depth; $i++) {
                        if ($i != $depth - 1) {
                            $d =& $branch->findDir($file['path'][$i]);
                            if ($d) {
                                $branch =& $d;
                            } else {
                                $dirnum++;
                                $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1));
                                $branch =& $d;
                            }
                        } else {
                            $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $prio[$filenum]));
                        }
                    }
                }
            }
            echo "<table><tr>";
            echo "<tr><td width=\"110\">Metainfo File:</td><td>" . $torrent . "</td></tr>";
            echo "<tr><td>Directory Name:</td><td>" . htmlentities($btmeta['info']['name'], ENT_QUOTES) . "</td></tr>";
            echo "<tr><td>Announce URL:</td><td>" . htmlentities($btmeta['announce'], ENT_QUOTES) . "</td></tr>";
            if (array_key_exists('comment', $btmeta)) {
                echo "<tr><td valign=\"top\">Comment:</td><td>" . htmlentities($btmeta['comment'], ENT_QUOTES) . "</td></tr>";
            }
            echo "<tr><td>Created:</td><td>" . date("F j, Y, g:i a", $btmeta['creation date']) . "</td></tr>";
            echo "<tr><td>Torrent Size:</td><td>" . $torrent_size . " (" . formatBytesToKBMGGB($torrent_size) . ")</td></tr>";
            echo "<tr><td>Chunk size:</td><td>" . $btmeta['info']['piece length'] . " (" . formatBytesToKBMGGB($btmeta['info']['piece length']) . ")</td></tr>";
            if (array_key_exists('files', $btmeta['info'])) {
                echo "<tr><td>Selected size:</td><td id=\"sel\">0</td></tr>";
                echo "</table><br>\n";
                if ($allowSave) {
                    echo "<form name=\"priority\" action=\"index.php\" method=\"POST\" >";
                    echo "<input type=\"hidden\" name=\"torrent\" value=\"" . $torrent . "\" >";
                    echo "<input type=\"hidden\" name=\"setPriorityOnly\" value=\"true\" >";
                }
                echo "<script type=\"text/javascript\">\n";
                echo "var sel = 0;\n";
                echo "d = new dTree('d');\n";
                $tree->draw(-1);
                echo "document.write(d);\n";
                echo "sel = getSizes();\n";
                echo "drawSel();\n";
                echo "</script>\n";
                echo "<input type=\"hidden\" name=\"filecount\" value=\"" . count($btmeta['info']['files']) . "\">";
                echo "<input type=\"hidden\" name=\"count\" value=\"" . $dirnum . "\">";
                echo "<br>";
                if ($allowSave) {
                    echo '<input type="submit" value="Save" >';
                    echo "<br>";
                }
                echo "</form>";
            } else {
                echo "</table><br>";
                echo htmlentities($btmeta['info']['name'] . $torrent_size . " (" . formatBytesToKBMGGB($torrent_size) . ")", ENT_QUOTES);
            }
        }
    } else {
        $result = shell_exec("cd " . $cfg["torrent_file_path"] . "; " . $cfg["pythonCmd"] . " -OO " . $cfg["btshowmetainfo"] . " " . escapeshellarg($torrent));
        echo "<pre>";
        echo htmlentities($result, ENT_QUOTES);
        echo "</pre>";
    }
}
/**
 * File Prio Form
 *
 * @param $transfer
 * @param $withForm
 * @return string
 */
function getFilePrioForm($transfer, $withForm = false)
{
    /*
    	global $cfg;
    	$prioFileName = $cfg["transfer_file_path"].$transfer.".prio";
    	require_once('inc/classes/BDecode.php');
    	$retVal = "";
    	// theme-switch
    	if ((strpos($cfg["theme"], '/')) === false) {
    		$retVal .= '<link rel="StyleSheet" href="themes/'.$cfg["theme"].'/css/dtree.css" type="text/css" />';
    		$retVal .= '<script type="text/javascript">var dtree_path_images = "themes/'.$cfg["theme"].'/images/dtree/";</script>';
    	} else {
    		$retVal .= '<link rel="StyleSheet" href="themes/tf_standard_themes/css/dtree.css" type="text/css" />';
    		$retVal .= '<script type="text/javascript">var dtree_path_images = "themes/tf_standard_themes/images/dtree/";</script>';
    	}
    	$retVal .= '<script type="text/javascript" src="js/dtree.js"></script>';
    	$ftorrent = $cfg["transfer_file_path"].$transfer;
    	$fp = @fopen($ftorrent, "rd");
    	$alltorrent = @fread($fp, @filesize($ftorrent));
    	@fclose($fp);
    	$btmeta = @BDecode($alltorrent);
    	$torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
    	$dirnum = (array_key_exists('files',$btmeta['info'])) ? count($btmeta['info']['files']) : 0;
    	if (@is_readable($prioFileName)) {
    		$prio = explode(',', @file_get_contents($prioFileName));
    		$prio = array_splice($prio,1);
    	} else {
    		$prio = array();
    		for ($i=0; $i<$dirnum; $i++)
    			$prio[$i] = -1;
    	}
    */
    global $cfg;
    require_once 'inc/classes/BDecode.php';
    $retVal = "";
    // theme-switch
    if (strpos($cfg["theme"], '/') === false) {
        $retVal .= '<link rel="StyleSheet" href="themes/' . $cfg["theme"] . '/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/' . $cfg["theme"] . '/images/dtree/";</script>';
    } else {
        $retVal .= '<link rel="StyleSheet" href="themes/tf_standard_themes/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/tf_standard_themes/images/dtree/";</script>';
    }
    $retVal .= '<script type="text/javascript" src="js/dtree.js"></script>';
    $isTransmissionTorrent = false;
    if ($cfg["transmission_rpc_enable"]) {
        require_once 'inc/functions/functions.rpc.transmission.php';
        $isTransmissionTorrent = isTransmissionTransfer($transfer);
    }
    $files = array();
    if ($isTransmissionTorrent) {
        $allFilesResponse = getTransmissionTransfer($transfer, array('files'));
        $allFiles = $allFilesResponse['files'];
        $wantedFilesResponse = getTransmissionTransfer($transfer, array('wanted'));
        $wantedFiles = $wantedFilesResponse['wanted'];
        $dirnum = count($allFiles);
        // make sure this is in here otherwhise you will loose alot of time debugging your code on what is missing (the filetree selection is not displayed)
        $tree = new dir("/", $dirnum, -1);
        foreach ($allFiles as $file) {
            $fileparts = explode("/", $file[name]);
            $filesize = $file[length];
            $fileprops = array('length' => $filesize, 'path' => $fileparts);
            array_push($files, $fileprops);
        }
        $filescount = count($files);
        foreach ($files as $filenum => $file) {
            $depth = count($file['path']);
            $branch =& $tree;
            for ($i = 0; $i < $depth; $i++) {
                if ($i != $depth - 1) {
                    $d =& $branch->findDir($file['path'][$i]);
                    if ($d) {
                        $branch =& $d;
                    } else {
                        $dirnum++;
                        $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, -1));
                        $branch =& $d;
                    }
                } else {
                    $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $wantedFiles[$filenum] == 1 ? 1 : -1));
                }
            }
        }
        $aTorrent = getTransmissionTransfer($transfer, array("pieceCount", "pieceSize", "totalSize", "dateCreated", "downloadDir", "comment"));
        #$torrent_size = $aTorrent[pieceSize] * $aTorrent[pieceCount];
        $torrent_size = $aTorrent['totalSize'];
        $torrent_chunksize = $aTorrent['pieceSize'];
        $torrent_directoryname = $aTorrent['downloadDir'];
        $torrent_announceurl = $aTorrent['comment'];
        $torrent_creationdate = $aTorrent['dateCreated'];
        $torrent_filescount = $filescount;
    } else {
        $prioFileName = $cfg["transfer_file_path"] . $transfer . ".prio";
        $ftorrent = $cfg["transfer_file_path"] . $transfer;
        $fp = @fopen($ftorrent, "rd");
        $alltorrent = @fread($fp, @filesize($ftorrent));
        @fclose($fp);
        $btmeta = @BDecode($alltorrent);
        $torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
        $dirnum = array_key_exists('files', $btmeta['info']) ? count($btmeta['info']['files']) : 0;
        if (@is_readable($prioFileName)) {
            $prio = explode(',', @file_get_contents($prioFileName));
            $prio = array_splice($prio, 1);
        } else {
            $prio = array();
            for ($i = 0; $i < $dirnum; $i++) {
                $prio[$i] = -1;
            }
        }
        $tree = new dir("/", $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1);
        if (array_key_exists('files', $btmeta['info'])) {
            foreach ($btmeta['info']['files'] as $filenum => $file) {
                $depth = count($file['path']);
                $branch =& $tree;
                for ($i = 0; $i < $depth; $i++) {
                    if ($i != $depth - 1) {
                        $d =& $branch->findDir($file['path'][$i]);
                        if ($d) {
                            $branch =& $d;
                        } else {
                            $dirnum++;
                            $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1));
                            $branch =& $d;
                        }
                    } else {
                        $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $prio[$filenum]));
                    }
                }
            }
        }
        $torrent_chunksize = $btmeta[info]['piece length'];
        $torrent_directoryname = $btmeta[info][name];
        $torrent_announceurl = $btmeta[announce];
        $torrent_creationdate = $btmeta['creation date'];
        $torrent_filescount = count($btmeta['info']['files']);
    }
    $retVal .= "<table><tr>";
    $retVal .= "<tr><td width=\"110\">Metainfo File:</td><td>" . $transfer . "</td></tr>";
    $retVal .= "<tr><td>Directory Name:</td><td>" . $torrent_directoryname . "</td></tr>";
    $retVal .= "<tr><td>Announce URL:</td><td>" . $torrent_announceurl . "</td></tr>";
    if (array_key_exists('comment', $btmeta)) {
        $retVal .= "<tr><td valign=\"top\">Comment:</td><td>" . tfb_htmlencode($btmeta['comment']) . "</td></tr>";
    }
    $retVal .= "<tr><td>Created:</td><td>" . ($torrent_creationdate == 0 ? 'n/a' : date("F j, Y, g:i a", $torrent_creationdate)) . "</td></tr>";
    $retVal .= "<tr><td>Torrent Size:</td><td>" . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")</td></tr>";
    $retVal .= "<tr><td>Chunk size:</td><td>" . $torrent_chunksize . " (" . @formatBytesTokBMBGBTB($torrent_chunksize) . ")</td></tr>";
    if (array_key_exists('files', $btmeta['info']) || count($files) > 0) {
        $retVal .= "<tr><td>Selected size:</td><td id=\"sel\">0</td></tr>";
        $retVal .= "</table><br>\n";
        if ($withForm) {
            $retVal .= "<form name=\"priority\" action=\"dispatcher.php?action=setFilePriority&riid=_referer_\" method=\"POST\" >";
            $retVal .= "<input type=\"hidden\" name=\"transfer\" value=\"" . $transfer . "\" >";
        }
        $retVal .= "<script type=\"text/javascript\">\n";
        $retVal .= "var sel = 0;\n";
        $retVal .= "d = new dTree('d');\n";
        $retVal .= $tree->draw(-1);
        $retVal .= "document.write(d);\n";
        $retVal .= "sel = getSizes();\n";
        $retVal .= "drawSel();\n";
        $retVal .= "</script>\n";
        $retVal .= "<input type=\"hidden\" name=\"filecount\" value=\"" . $torrent_filescount . "\">";
        $retVal .= "<input type=\"hidden\" name=\"count\" value=\"" . $dirnum . "\">";
        $retVal .= "<br>";
        if ($withForm) {
            $retVal .= '<input type="submit" value="Save" >';
            $retVal .= "<br>";
            $retVal .= "</form>";
        }
    } else {
        $retVal .= "</table><br>";
        $retVal .= $btmeta['info']['name'] . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")";
    }
    // return
    return $retVal;
}