<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<?php
    error_reporting(0);
    $subroot=$_SERVER['DOCUMENT_ROOT'];
    $root=""; // ie.: "folder1/folder2/" from "document_root/"
              // set in dl.php as here
              // set in .htaccess ie.: RewriteRule ^(.*)$ /folder1/folder2/index.php?p=$1 [NC,L]
              // place files in s/

    include($subroot."/".$root."php/setup.php");
    include($subroot."/".$root."php/file.php");
    include($subroot."/".$root."php/colortime.php");

    $path=preg_replace("/\.+\//","",stripslashes(htmlspecialchars($_GET['p'])));

    $path=str_replace("&amp;","&",$path);

    while(!is_dir($loc.$path) && !is_file($loc.$path) && $path<>"") {
        if(substr($path,strlen($substr)-1)=="/") {
            $path=substr($path,0,strlen($path)-1);
        } else {
            $path=substr($path,0,strrpos($path,"/"));
        }
    }
    if(substr($path,strlen($path)-1)!="/" && is_dir($loc.$path) && $path<>"") $path.="/";

    $fpath=$loc.$path;
    $vpath="";
    $dpath="";
    $fname="";
    $view=false;
    if(is_file($fpath)) {           // Preparing file preview
        if(strpos($path,"/")) {
            $path=substr($path,0,strrpos($path,"/")+1);
        } else {
            $path="";
        }
        $vpath=$fpath;
        $fname=substr($vpath,strrpos($vpath,"/")+1);
        $fpath=substr($fpath,0,strrpos($fpath,"/")+1);
        $dpath=$dl.$path.$fname;
        $view=true;

        if(strpos($path.$fname,"secrets")==false) {
            appendf($analytics,time()."\v".$path.$fname."\n");
        }
    }

    $farr=array();
    $darr=array();

    if($handle=opendir($fpath)) {   // List current directory
        while(false!==($entry=readdir($handle))) {
            if($entry!="." && $entry!="..") {
                if(is_dir($fpath.$entry)) {
                    array_push($darr,$entry);
                } else {
                    array_push($farr,$entry);
                }
            }
        }
    }
    closedir($handle);

    $items=count($darr)+count($farr);
    $items.=($items>1)?" items":" item";

    sort($darr);
    sort($farr);

    session_set_cookie_params(["SameSite" => "Strict"]); //none, lax, strict
    session_set_cookie_params(["Secure" => "true"]); //false, true
    session_set_cookie_params(["HttpOnly" => "true"]); //false, true
    session_start();                // Visit counter
    $visits=intval(readf($visitpath));
    if(!$_SESSION['visited']) {
        $_SESSION['visited']=true;
        $visits++;
        if($visits>1) writef($visitpath,$visits);
    }
?>
<!--

    Author: Twily                                2015-2022
    http://twily.info/

    Syntax Highlighting
    https://highlightjs.org/
    https://github.com/wcoder/highlightjs-line-numbers.js/

    Flattr Icons
    https://github.com/NitruxSA/flattr-icons

    Twilight Vector
    http://racer437.deviantart.com/art/Twilight-Sparkle-Vector-321236369

    Other Sources:
    http://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click
    http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active
    http://stackoverflow.com/questions/260857/changing-website-favicon-dynamically

-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="<?php echo $description; ?>">
<meta name="keywords" content="<?php echo $keywords; if($view && is_file($fpath.$fname)) { echo ",".$fname; } ?>">
<title><?php echo $title." ~/".$path.$fname; ?></title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<meta name='viewport' content='width=device-width,initial-scale=1'>

<link id="favicon" rel="shortcut icon" href="/favicon.ico?v=2" />
<link rel="stylesheet" type="text/css" href="/<?php echo $root; ?>css/style.css?v=2.94" />
<?php if($view) echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"/".$root."css/highlight.css?v=5\" />\n"; ?>
<script type="text/javascript">
var smallscreen=false;
</script>
<script type="text/javascript" src="/<?php echo $root; ?>js/main.js?v=1.93"></script>

</head>
<body onload="init();">

<div id="twily"></div>

<div id="container" onmousedown="bodytouch();" ontouchstart="bodytouch();"<?php if($_SESSION['embed']) { echo " class=\"embed\""; } ?>>
<a class="btn bb<?php if($path=="") echo " selected"; ?>" href="/<?php echo $root; ?>" target="_self">~</a><?php
    $lpath=explode("/",$path);
    for($i=0;$i<count($lpath)-1;$i++) {
        $lpath_url="/".$root;
        $selected="";
        for($j=0;$j<=$i;$j++) $lpath_url.=$lpath[$j]."/";
        if($i==count($lpath)-2) $selected=" selected";
        echo "<a class=\"btn bb".$selected."\" href=\"".$lpath_url."\" target=\"_self\">".$lpath[$i]."</a>";
    }
?>

<div class="action" id="dirbtn2"<?php if($view) echo " style=\"display: none;\""; ?>>
    <span class="items"><?php echo $items; ?></span>
<?php if($path<>"") { ?>
 • <a class="btn bb" href="<?php echo "/".$root.$dl.$path; ?>" target="_blank">Download ./*</a>
<?php } ?>
</div>
<hr />
<div class="action" id="dirbtn">
    <span class="items"><?php echo $items; ?></span>
<?php if($path<>"") { ?>
 • <a class="btn bb" href="<?php echo "/".$root.$dl.$path; ?>" target="_blank">Download ./*</a>
<?php } ?>
</div>
<div style="clear: both;"></div>
<br />
<div id="browse">
<?php
    //$upath=$root.$path;
    //$up=substr($upath,0,strrpos($upath,"/"));
    //$up=substr($upath,0,strrpos($up,"/"));
    $upath=explode("/",$root.$path);
    $up="";
    for($i=0;$i<count($upath)-2;$i++) {
        $up.="/".$upath[$i];
    }
    if($up<>"") $up.="/";
    else        $up="/";
    echo "    <a class=\"dir\" href=\"".$up."\" target=\"_self\"><div class=\"icon\"><img src=\"/".$root."img/folder-up.png\" onload=\"this.style.visibility='visible';\" /></div>..</a>\n";

    $bad=array("%","!","?","&","#"," ","+");
    $good=array("%25","%21","%3F","%26","%23","%20","%2B");

    for($i=0;$i<count($darr);$i++) {    // Create directories
        $hidden="";
        $cutn="";
        $dimg="folder.png";
        if(substr($darr[$i],0,1)==".")  $hidden=" hid";
        if(strlen($darr[$i])>$fnamelen) $cutn="...";
        if($path.$darr[$i]=="stuff") $dimg="desktop.png";
        if($darr[$i]!="secrets") {
            echo "    <a class=\"dir".$hidden."\" href=\"/".$root.str_replace($bad,$good,$path.$darr[$i])."/\" target=\"_self\"><div class=\"icon\"><img src=\"/".$root."img/".$dimg."\" onload=\"this.style.visibility='visible';\" /></div>".substr($darr[$i],0,$fnamelen).$cutn."</a>\n";
        }
    }

    for($i=0;$i<count($farr);$i++) {    // Create files
        $info=pathinfo($fpath.$farr[$i]);
        $img="unknown.png";
        $skip=false;
        $tmb=false;
        $mtyp="";
        switch(strtolower($info['extension'])) {    // Detect filetype by extension
        case "png": case "jpg": case "jpeg": case "bmp": case "gif": case "xbm": case "ico": case "webp": case "svg":
                $img="image.png";
                $thash=md5($path.$farr[$i][1]);
                //$img=md5($path.$farr[$i][1]);
                if(file_exists($root."thumbs/".$thash.".jpg")) {
                    $img="thumbs/".$thash.".jpg";
                    $tmb=true;
                }
                $mtyp=" mimg";
                break;
            case "wav": case "wma": case "mp3": case "ogg": case "flac": case "midi":
                $img="audio.png";       break;
            case "avi": case "mp4": case "mkv": case "webm":
                $img="video.png";
                $thash=md5($path.$farr[$i][1]);
                if(file_exists($root."/thumbs/".$thash.".jpg")) {
                    $img="thumbs/".$thash.".jpg";
                    $tmb=true;
                }
                $mtyp=" mvid";
                break;
            case "zip": case "7z": case "tar": case "gz": case "rar":
                $img="archive.png";     break;
            case "xml": case "xhtml": case "html": case "php":
                $img="xml.png";         break;
            case "txt": case "log": case "conf":
                $img="text.png";        break;
            case "otf": case "pcf": case "ttf":
                $img="font.png";        break;
            case "c": case "cpp":
                $img="c.png";           break;
            case "pl":
                $img="perl.png";        break;
            case "py":
                $img="python.png";      break;
            case "sh":
                $img="script.png";      break;
            case "css":
                $img="css.png";         break;
            case "js":
                $img="js.png";          break;
            case "url":
                $img="url.png";         break;
            case "$":
                $img="info.png";        break;
            case "meta":
                $skip=true;             break;
            case "prefab":
                $img="flattr_extended/application-x-perl.png";
                break;
            case "mat":
                $img="flattr_extended/application-x-designer.png";
                break;
            case "fbx":
                $img="flattr_extended/text-x-cmake.png";
                break;
            case "cs":
                $img="flattr_extended/text-csharp.png";
                break;
            case "blend": case "blend1":
                $img="flattr_extended/blender.png";
                break;
            default:
                $img="unknown.png";
        }
        if(!$skip) {
        if($img=="unknown.png") {       // Dig deeper; regex first line
            //$line=(new SplFileObject($fpath.$farr[$i]))->fgets();
            $fh=fopen($fpath.$farr[$i],'r');
            $line=fread($fh,64);
            fclose($fh);
            switch($line) {
                case (preg_match('/#!.*sh.*/',$line)?true:false):       // script match
                    $img="script.png";  break;
                case (preg_match('/[^\x00-\x7F]/',$line)?true:false):   // binary match
                    $img="application.png";  break;
                case (preg_match('/[ -~]/',$line)?true:false):          // ascii match
                    $img="text.png";    break;
                default:
                    $img="unknown.png";
            }
        }

        $selected="";
        $hidden="";
        $cutn="";
        $new="";
        if(time()-filemtime($fpath.$farr[$i])<$oldafter) { $new=" new"; }
        if($view) if($fname==$farr[$i]) $selected=" selected";
        if(substr($farr[$i],0,1)==".")  $hidden=" hid";
        if(strlen($farr[$i])>$fnamelen) $cutn="...";

        $target="_self";
        $href="".str_replace($bad,$good,$path.$farr[$i])."#view";   // Standard local file link
        /* Make *.url files open the links directly */
        /*if($info['extension']=="url") {                              // .url file - link contained url instead
            $target="_blank";
            $href=str_replace("\n","",readf($fpath.$farr[$i]));      // just in case the .url file contains newline
        }*/

    $limg="img/";
    if($tmb) {
        $limg="";
    }

    echo "    <a class=\"file".$selected.$hidden.$new.$mtyp."\" href=\"/".$root.$href."\" target=\"".$target."\"><div class=\"icon\"><img src=\"/".$root.$limg.$img."\" onload=\"this.style.visibility='visible';\" /></div>".substr($farr[$i],0,$fnamelen).$cutn."</a>\n";
        } // skip
    }
?>
</div>
<div id="view"></div>
<br /><hr />
<?php
    if($view) {                                 // File preview
        if(file_exists($vpath)) {
            $mtime=filemtime($vpath);
            $timestamp=date($dformat,$mtime);
            $mtime=time()-$mtime;
            list($mtime,$color)=colortime($mtime);

            $data=explode("\n",readf($analytics));
            $fviews=0;
            for($i=0;$i<count($data);$i++) {
                $dna=explode("",$data[$i]);
                if($dna[1]==$path.$fname) $fviews++;
            }
            /*$fh=fopen($analytics,'r');
            if(flock($fh,LOCK_EX)) {
                while(!feof($fh)) {
                    $line=explode("\v",stream_get_line($fh,4096));
                    //$line=explode("\v",fgetc($fh,4096));
                    if($line[1]==$path.$fname) $fviews++;
                }
                flock($fh,LOCK_UN);
            }
            fclose($fh);*/

            $lpath=explode("/",$path);
            for($i=count($lpath)-2;$i<count($lpath)-1;$i++) {
                $lpath_url="#";
                if(count($lpath)<2) $lpath[$i]="~";
                if($lpath[$i]<>"") echo "<a class=\"btn bt\" href=\"".$lpath_url."\" target=\"_self\">".$lpath[$i]."</a>";
            }
            $fs_get=filesize($vpath);

            if($fs_get>(1024*1024*1024)) {//gb
                $fs_get=round($fs_get/1024/1024/1024,1)." GB";
            } else if($fs_get>(1024*1024)) {//mb
                $fs_get=round($fs_get/1024/1024,1)." MB";
            } else if($fs_get>(1024)) {// kb
                $fs_get=round($fs_get/1024)." KB";
            } else {
                $fs_get=$fs_get." B";
            }

            echo "<a class=\"btn bt selected\" href=\"/".$root.$path.$fname."#view\" target=\"_self\">".$fname."</a>\n"
                ."<div class=\"action\">\n"
                ."<span class=\"statsf2\">"
                ."<span class=\"fsize\">".$fs_get."</span>•&nbsp;"
                ."<span class=\"fviews\">".number_format($fviews,0,","," ")."</span>•&nbsp; "
                ."<span class=\"lastm\" style=\"color: ".$color.";\" title=\"Last modified ".$timestamp."\">".$mtime."</span>•&nbsp; "
                ."</span>\n"
                ."<a class=\"btn bt\" href=\"/".$root.$dpath."\" target=\"_blank\">Download</a>"
                ."<a class=\"btn bt\" href=\"/".$root."s/".$path.$fname."\" target=\"_blank\">Raw</a>"
                ."<a class=\"btn bt\" href=\"/".$root.$path."\" target=\"_self\">Close</a>\n"
                ."</div>\n"
                ."<div style=\"clear: both;\"></div>\n"
                ."<div class=\"statsf\">\n"
                ."<span class=\"lastm\" style=\"color: ".$color.";\" title=\"Last modified ".$timestamp."\">".$mtime."</span>•&nbsp; "
                ."<span class=\"fviews\">".number_format($fviews,0,","," ")."</span>\n"
                ."</div>\n";

            $info=pathinfo($vpath);
            $bprev="";
            $prev="";
            switch(strtolower($info['extension'])) {        // Detect best way to preview by file extension
                case "png": case "jpg": case "jpeg": case "bmp": case "gif": case "ico": case "webp": case "svg":
                    $prev="<br /><br /><img id=\"text\" class=\"media\" onmouseover=\"zindex(this.id);\" src=\"/".str_replace($bad,$good,$root."s/".$path.$fname)."\" /><br /><br />\n";
                    break;
                case "wav": case "mp3": case "ogg":
                    $prev="<br /><br /><audio id=\"text\" class=\"media\" onmouseover=\"zindex(this.id);\" autoplay controls loop onvolumechange=\"saveVol('text','audio');\" style=\"height: 50px; min-width: 500px;\"><source src=\"/".str_replace($bad,$good,$root."s/".$path.$fname)."\"></audio><script>loadVol('text','audio');</script></br /><br />\n";
                    break;
                case "fbx":
                    $prev="<iframe src='/three-fbx-loader/examples/index.php?p=s/".$path.$fname."' class='ifrm' frameborder='0'></iframe>";
                    break;
                case "mp4": case "webm":
                    $prev="<br /><br /><video id=\"text\" class=\"media\" onmouseover=\"zindex(this.id);\" autoplay controls loop muted onvolumechange=\"saveVol('text','video');\"><source src=\"/".str_replace($bad,$good,$root."s/".$path.$fname)."\"></video><script>loadVol('text','video');</script><br /><br />\n";
                    break;
                case "url":
                    $fc=readf($vpath);
                    $fctarget="_blank";
                    $fclnk="";
                    $fchref=$fc;
                    if(substr($fc,0,1)=="/") { // inside link
                        $fctarget="_self";
                        $fclnk="~";
                        $fchref="/".$root.substr($fc,1);
                    }
                    $prev="<br /><br /><br /><a class=\"btn\" href=\"".$fchref."\" target=\"".$fctarget."\">".$fclnk.$fc."</a><br /><br /><br /><br />\n";
                    break;
                case "$":
                    echo "<br /><br /><div id=\"text\" onmouseover=\"zindex(this.id);\">\n";
                    if(is_file($vpath)) include($vpath);
                    echo "</div><br /><br />\n";
                    break;
                default:
                    $bad=array("&","<",">");
                    $good=array("&amp;","&lt;","&gt;");

                    $prev=true;
                    $prev=true;
                    if(filesize($vpath)>(1024*1024*75)) {
                        $prev=false;
                    } else {

                    $fc=readf($vpath);
                    $tmp=explode("\n",$fc);
                    if(preg_match('/[^\x00-\x7F]/',$tmp[0])) { // Detect binary file
                        $prev=false;
                    }
                    if($info['extension']=='apk' || 
                        $info['extension']=='dex' || 
                        $info['extension']=='res' || 
                        $info['extension']=='jar' || 
                        $info['extension']=='idsig') {
                        $prev=false;
                    }
                    }
                    if($prev) {
                        $fc=str_replace($bad,$good,$fc);
                        $bprev="<br /><a class=\"btn bt\" href=\"javascript:selectText();\" target=\"_self\">{}</a>";
                        $prev="<pre id=\"text\" onmouseover=\"zindex(this.id);\" onclick=\"zindex(this.id);\"><code id=\"code\">".$fc."</code></pre><br />\n";
                        //$prev.="<br /><pre id=\"text\" onmouseover=\"zindex(this.id);\" onclick=\"zindex(this.id);\"><code id=\"code\" onmousedown=\"selectText(event,1);\" onmouseup=\"selectText(event,2);\">".$fc."</code></pre><br />\n";
                    } else {
                        $prev="<br /><br />&lt;no preview&gt;<br /><br /><br />\n";   
                    }
?>
<script type="text/javascript" src="/<?php echo $root; ?>js/highlight.min.js?v=1"></script>
<script type="text/javascript" src="/<?php echo $root; ?>js/highlightjs-line-numbers.min.js?v=1"></script>
<script type="text/javascript">
//hljs.configure({useBR: true,tabReplace: '    ',classPrefix: ''});
//hljs.initHighlightingOnLoad();
//hljs.initLineNumbersOnLoad();
if(typeof hljs!=='undefined') {
    hljs.configure({forceLineNumberOnSingleLine: true,tabReplace: '    ',classPrefix: ''});
}
</script>
<?php
            }

            echo $bprev."<center>\n".$prev."\n<a class=\"btn bb\" id=\"top\" href=\"#\" target=\"_self\">Top</a>\n<hr />\n</center>\n";
        }
    }
?>
<script type="text/javascript">function contact(x) { window.location.href='mailto:'+x.replace(' at ','@').replace(' dot ','.'); }</script>
<div id="copyleft"><span class="cleft"><a class="btn bb" href="https://en.wikipedia.org/wiki/Copyleft" target="_blank">©</a></span><a class="btn bt" href="/<?php echo $root; ?>" target="_self"><?php echo $copyl; ?></div>
<div id="contact"><a class="btn bt" href="javascript:contact('<?php echo $email; ?>');" target="_self"><?php echo $email; ?></a></div>
<?php
    if($view) {
        echo "<br /><br /><br /><iframe src=\"/".$root."comment/?f=".hash('sha256',$path.$fname)."\" id=\"comment\" onload=\"loadCmt('comment');\"></iframe>";
    }
?>
<div id="visits"><?php echo number_format($visits,0,","," "); ?> visits</div>
</div>

<script type="text/javascript">
var root="<?php echo $root; ?>";

var lt,l=true;
function createChat() {
    var i=document.createElement("iframe");
    i.id="chat";
    i.src="/"+root+"chat/";
    i.scrolling="no";
    i.onmouseover=function() { zindex(i.id); };
    i.onload=function() {
        i.style.visibility="visible";
<?php if(!$_SESSION['activated']) { ?>
        if(l) {
            clearTimeout(lt);
            lt=setTimeout(function() { i.src=i.src; l=false; },1000);
        }
<?php $_SESSION['activated']=true; } ?>
    };
<?php if($_SESSION['embed']) { ?>
    i.style.height="100%";
<?php } ?>
    document.body.appendChild(i);
}

if(window.addEventListener) window.addEventListener("load",createChat,false);
else if(window.attachEvent) window.attachEvent("onload",createChat);
else                        window.onload=createChat;

function restore_chat() {
    $('chat').contentWindow.document.getElementById('nick').value="/exit";
    $('chat').contentWindow.post();
    document.getElementsByTagName('body')[0].removeChild($('chat'));
    createChat();
}
</script>
<a id="chat_restore" class="btn" href="javascript:restore_chat();" target="_self">...</a>

<a id="top_arrow" class="btn arrow bt" href="#view" target="_self">^</a>
<a id="bot_arrow" class="btn arrow bb" href="#comment" target="_self">v</a>

<div id="control" onmouseenter="showBar();" onmouseleave="hideBar();" style="/*display: none;*/ z-index: 4000;">
    <label>Auto-scroll</label>
    <input type="button" value="Up" id="btnScrollU" onclick="toggleScroll('Up');" />
    <input type="button" value="Down" id="btnScrollD" onclick="toggleScroll('Down');" />
    <input type="button" value="-" onclick="changeSpeed(-1);" />
    <input type="button" value="+" onclick="changeSpeed(1);" />
    <span id="scrollSpeed" style="display: none;"></span>
    <!--<div style="float: right;">
        <input type="range" min="0" max="200" value="0" onchange="changeBorder(this.value);" />
    </div>-->
</div>


<script type="text/javascript">
setTimeout(async function() {
    if(typeof hljs!=='undefined') {
        var blocks=document.getElementsByTagName('code');
        if(blocks.length>0) {
            hljs.highlightBlock(blocks[0]);
            hljs.lineNumbersBlock(blocks[0]);
        }
    }
});
<?php if(!isset($_SESSION['firstload'])) {
    $_SESSION['firstload']=1;
?>
setTimeout(function() { hideBar(); },1000);
<?php } else { ?>
hideBar();
<?php } ?>
</script>

<script type="text/javascript">
var tabTime=0;
var tabRefS=60*60*4; // seconds in background inactive before a force refresh trigger on re-entry
document.addEventListener("visibilitychange", function() {
   if (document.hidden){
        //console.log("Browser tab is hidden")
        tabTime=new Date().getTime();
   } else {
        //console.log("Browser tab is visible")
        var nTime=new Date().getTime();
        if(nTime-tabTime>(tabRefS*1000) && tabTime!=0) {
            location.reload();
        } else {
            tabTime=0;
        }
   }
});
</script>

</body>
</html>
