<?php
/*---------------------------------------------------+
| PHP-Fusion 6 Content Management System
+----------------------------------------------------+
| Copyright  2002 - 2005 Nick Jones
| http://www.php-fusion.co.uk/
+----------------------------------------------------+
| Released under the terms & conditions of v2 of the
| GNU General Public License. For details refer to
| the included gpl.txt file or visit http://gnu.org
+----------------------------------------------------*/
require_once "../../maincore.php";
require_once THEMES."templates/header.php";

if(iGUEST) redirect(BASEDIR."restricted.php");

opentable("Downloads");

$version = "3.2.2";

/*****************************************************************************\
 * myExplorer                                                                *
 * http://www.bmitt.com/files/webauthoring/php/                              *
 * ------------------------------------------------------------------------- *
 * written by      : Bernhard Mitterer @: admin@bmitt.com                    *
 * last modified   : 2005-12-21                                              *
 *****************************************************************************

 CHANGES:

    2.2
        - support for special chars in path and filenames

    2.3
        - fixed problem with special chars (htmlentities)
        - validates against XHTML 1.0
        - validates against CSS 2

    2.4
        - added possibility to print statistics
          (filecount, dircount, total filesize )

    2.5
        - different icons for filetypes
        - AAA Bobby Approved

    2.6
        - fixed problem with urlcoding (special chars again)
        - added possibility to handle files depending on their extension

    2.7
        - redesign of code to support userdefined sorting
        - significant performance enhancements
        - ability to benchmark the script

    3.1
        - possibility to enter path directly in addressbar
        - icons updated
        - added toolbar
        - redesign of code to support multiple views
          (added icon view)

    3.2
        - changed descending sort to print files before folders
        - changed look to Windows Explorer Style


 ADDONS

    + myExplorer Redirector
        just an index-file which can be copied in each listed directory
        to redirect the user who tries to access the folders directly to
        the corresponding folder in myExplorer

    + myExplorer Download
        script to finetune the behavior when link to file is clicked
        (show inline, show download dialog, count downloads,...)


 USAGE:

    1. adapt the Configuration-Section to your needs
    2. thats it!


 CONFIGURATION:

     bool $cfg['su'] (= false)
        su stands for SuperUser and enables
           - relative paths upwards ('../') and
           - going above $cfg['rootDir']

     string $cfg['rootDir'] (= '')
        use this attribute to specify the root-directory
        of myExplorer relative to this file (the one you
        are reading). it is not possible to view
        directories above $cfg['rootDir'].
        eg. $cfg['rootDir'] = 'files';

     string $cfg['indexDir'] (= '')
        use this attribute to specify the directory
        (relativ to $cfg['rootDir']) which myExplorer should
        show when opening this page.
        if you want myExplorer to start in "files/mp3"
        and $cfg['rootDir'] is set to "files" you should set
        $cfg['indexDir'] to 'mp3'.
        if you want myExplorer to start in $cfg['rootDir']
        you do not have to set this attribute

     string $cfg['imgDir'] (= 'img')
        this attribute specifies the path to the icon-files
        ($cfg['imgDir'] is prepended to the filenames specified in
        $cfg['filetypes'], $cfg['picUp'] and $cfg['picFolder'])

     string $cfg['referer'] (= $_SERVER['PHP_SELF'])
        this attibute specifies the url to this page.
        you only will have to set this attribute if
        you have already query-strings in this url
        eg. $cfg['referer'] = 'index.php?pageID=234'

     string $cfg['defView'] (= 'detail')
        this attribute specifies the default view.
        possible values are 'icon' and 'detail'

     bool $cfg['showToolBar'] (= true)
        this attribute specifies if the toolbar
        should be shown (above the table)

     bool $cfg['showAddrBar'] (= true)
        this attribute specifies if the current directory
        should be shown (above the table)

     bool $cfg['disableAddrBar'] (= false)
        this attribute specifies whether the Address Bar is
        writable (false) or not (true)

     bool $cfg['showStat'] (= true)
        this attribute specifies if filecount, dircount
        and total filesize should be shown (at the bottom
        of the table)

     bool $cfg['benchmark'] (= false)
        this attribute specifies if the processing time of
        the script is measured an printed at the bottom

     int $cfg['maxStrlen'] (= 20)
        this attribute applies only to icon view and specifies
        the max. number of shown filename characters.
        if filename is longer, the rest of the charakters is
        replaced by '...'

     string $cfg['dateFormat'] (= 'Y-m-d H:i')
        this attribute specifies the format of the
        'Last Modified'-Timestamp. For possible values look at
        'http://www.php.net/date'  (Table 1)

     string $cfg['hName']    (= 'Name')
     string $cfg['hSize']    (= 'Size')
     string $cfg['hType']    (= 'Type')
     string $cfg['hLastMod'] (= 'Last Modified')
        these attributes specify the column-headers
        of the table

     bool $cfg['showSize']    (= true)
     bool $cfg['showType']    (= false)
     bool $cfg['showLastMod'] (= true)
        these attributes specify which columns to show

     string $cfg['showFiles']   (= '*')
     string $cfg['hideFiles']   (= '.*,index*,*.php')
     string $cfg['showFolders'] (= '*')
     string $cfg['hideFolders'] (= '.*,img')
        specify which files/folders should be shown
        default is 'implicit show'.
        * (asterisk) is the only wildcard allowed and
                     stands for "at least one charakter"

     bool $cfg['fastSort'] (= false)
        true:  the directory content is ALWAYS sorted
               ascending by filename. This option allows
               faster sorting for large directory listings
        false: sorts depending on the choosen column

     string $cfg['sortC'] (= 'N')
        defines default sort-column
          N: names of files/folders
          S: size of files/folders
          M: last modified of files/folders

     string $cfg['sortO'] (= 'A')
        defines default sort-order
          A: ascending
          D: descending

     bool $cfg['showSortPic'] (= true)
        true:  image showing sort direction is shown
               next to the column name
        false: no sort direction is shown

     string $cfg['sortPicAsc']    (= 'sortasc.gif')
     string $cfg['sortPicDesc']   (= 'sortdesc.gif')
        define image names for sort direction

     string $cfg['picUp']     (= 'folderup.gif')
     string $cfg['picFolder'] (= 'folder.gif')
        these attributes specify the names of the folder-icons

     bool $cfg['picFile']   (= 'true')
        true:  enables different icons for different filetypes
               icons are specified in $picIcons
        false: shows the default icon ( $cfg['filetypes']['.*'] )

     string $cfg['picHome']        (= 'home.gif')
     string $cfg['picUpEnabled']   (= 'folderup.gif')
     string $cfg['picUpDisabled']  (= 'folderup_disabled.gif')
     string $cfg['picReload']      (= 'reload.gif')
     string $cfg['picDetailView']  (= 'detailview.gif')
     string $cfg['picIconView']    (= 'iconview.gif')
     string $cfg['picSep']         (= 'separator.gif')
        these attributes specify the names of the toolbar-icons

     int $cfg['xAction'] (= false)
     string $cfg['xFilename'] (= 'dofile.php')
        if this attrib $cfg['xAction'] = false you can ignore the
        attrib $cfg['xFilename']. if you want to do something
        special when clicking on a file, set $cfg['xAction'] = true
        the script specified in $cfg['xFilename'] gets the
        path and filename of the selected file in the
        variable $_GET['file']

     array $cfg['filetypes']
        each line has the following format:
        '<extension>,<tab><iconfile>,<tab><description>,<tab><xAction>,<tab><xFilename>',

        <extension>   is the filename extension including the point
        <iconfile>    is the name of the icon-file related with <extension>
        <type>        filetype description shown when $cfg['showType'] = true
        <xAction>     if true the filename is given by Method GET to the
                      php-script specified in ...
        <xFilename>.

        - each line has to be bordered by single quotes (')
        - each line has to be terminated by a comma (,)
        - a comma has to separate the fields

        Defaults:
            description, xaction and xfilename are OPTIONAL
            if empty the following values are assumed
            <description> = <ext> File  (eg. 'TXT File)'
            <xaction>     = $cfg['xAction']
            <xfilename>   = $cfg['xFilename']


\*****************************************************************************/

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de-at" lang="de-at">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta http-equiv="Content-Language" content="de-at" />
  <meta http-equiv="expires" content="0" />
  <meta name="author" content="Bernhard Mitterer" />

  <title>Datei Manager</title>

  <style type="text/css">
  <!--

    /*************************************************************************\
     * Global Styles                                                         *
    \*************************************************************************/

    #explorer * { font:11px Tahoma,sans-serif; margin:0; padding:0; border-width:0; }

    #explorer table { width:90%; }

    #explorer a { color:black; text-decoration:none; }
    #explorer a span { padding:2px; }
    #explorer a:hover { text-decoration:none; }
    #explorer a:hover * { color:#009; text-decoration:underline; }
    #explorer a:focus span { background-color:#009; color:white; }
    #explorer a:active span { background-color:#009; color:white; }


    /*************************************************************************\
     * Styles for Detail View                                                *
    \*************************************************************************/

    #detailview { width:100%; border-spacing:0; }

    #detailview #sortasc  a { background-image:url('img/sortasc.gif'); background-repeat:no-repeat; background-position:right;padding-right:12px; }
    #detailview #sortdesc a { background-image:url('img/sortdesc.gif'); background-repeat:no-repeat; background-position:right;padding-right:12px; }

    #detailview th { background-color:#eed; padding:2px 5px 2px 9px; text-align:left; border-bottom:1px solid #ccb; }
    #detailview th { background-image:url('img/bg_header_sep.gif'); background-repeat:no-repeat; background-position:right;}

    #detailview td { padding:1px 5px; }

    #detailview *.name    { ; }
    #detailview *.size    { width:120px; text-align:right; }
    #detailview *.type    { width:120px; }
    #detailview *.lastmod { width:160px; }

    #detailview td.name img { margin:0 2px; vertical-align:text-bottom; width:16px; height:16px; }


    /*************************************************************************\
     * Styles for Icon View                                                  *
    \*************************************************************************/

    #iconview { width:100%; border-spacing:0; }

    #iconview img { margin:3px; }

    #iconview div.folder { float:left; width:100px; height:65px; text-align:center; margin:7px; }
    #iconview div.file   { float:left; width:100px; height:65px; text-align:center; margin:7px; }


    /*************************************************************************\
     * Styles for Framework (Menubars, Statistik, Benchmark)                 *
    \*************************************************************************/

    #explorer { border:1px outset #777; }

    #toolbar { padding:0 3px; border-bottom:1px solid #ccb; border-top:1px solid white; background-color:#eed; border-spacing:0; }
    #toolbar td.iconbar { width:190px; }
    #toolbar td.addrbar { padding-right:3px; }

    #iconbar img { padding:2px; vertical-align:middle; border:1px solid #eed; width:24px; height:24px; }
    #iconbar img.separator { width:1px; height:27px; }
    #iconbar img.active { border:1px inset #ace; background-color:#ffe; }

    #iconbar a:hover img { border:1px outset #ace;  background-color:#ffe; }
    #iconbar a:focus img { border:1px outset #ace;  background-color:#ffe; }
    #iconbar a:active img { border:1px inset #ace;  background-color:#ffe; }

    #addrbar { padding:2px; border:1px solid #79b; background-color:white; color:black; }
    #addrbar input { width:90%; }
    #addrbar input { background-image:url('img/bg_addrbar.gif'); background-repeat:no-repeat; background-position:left; padding-left:20px; }

    #errmsg { margin:1px; border:1px solid #b00; background-color:#ffa; color:#b00; height:18px; }
    #errmsg span { float:left; width:85%; padding:2px 5px; }
    #errmsg img { float:right; width:14px; height:14px; padding:2px; }

    #content { border:1px solid #79b; padding:1px; }

    #statusbar { padding:2px 5px; clear:both; text-align:right; border-top:1px solid #998; border-bottom:1px solid #ccb; background-color:#eed; }

    #benchmark { padding:5px; }

  -->
  </style>
</head>
<body>

<?php

/*****************************************************************************\
 * Configuration (adapt this section to your needs)                          *
\*****************************************************************************/

$cfg['su']             = false;
# paths
$cfg['rootDir']        = 'dateien';
$cfg['indexDir']       = '';
$cfg['imgDir']         = 'img';
$cfg['referer']        = $_SERVER['PHP_SELF'];
# appearance
$cfg['defView']        = 'detail';    // detail or icon
$cfg['showToolBar']    = true;
$cfg['showAddrBar']    = true;
$cfg['disableAddrBar'] = false;
$cfg['showStatBar']    = true;
$cfg['benchmark']      = false;
$cfg['maxStrlen']      = 20;
$cfg['dateFormat']     = 'd.m.Y G:i';
# labels for tableheader (detail view)
$cfg['hName']          = 'Navn';
$cfg['hSize']          = 'Strrelse';
$cfg['hType']          = 'Type';
$cfg['hLastMod']       = 'Sidst ndret';
# show attributes (detail view)
$cfg['showName']       = true;    // makes no sense to hide filename
$cfg['showSize']       = true;
$cfg['showType']       = true;
$cfg['showLastMod']    = true;
# filter
$cfg['showFiles']      = '*';
$cfg['hideFiles']      = '.*,index*,*.php';
$cfg['showFolders']    = '*';
$cfg['hideFolders']    = '.*,img';
# sort options
$cfg['fastSort']       = false;
$cfg['sortC']          = 'N';
$cfg['sortO']          = 'A';
$cfg['showSortPic']    = true;
$cfg['sortPicAsc']     = 'sortasc.gif';
$cfg['sortPicDesc']    = 'sortdesc.gif';
# pic-names
$cfg['picUp']          = 'folderup.gif';
$cfg['picFolder']      = 'folder.gif';
$cfg['picFile']        = true;
# toolbar
$cfg['picHome']        = 'home.gif';
$cfg['picUpEnabled']   = 'folderup.gif';
$cfg['picUpDisabled']  = 'folderup_disabled.gif';
$cfg['picReload']      = 'reload.gif';
$cfg['picDetailView']  = 'detailview.gif';
$cfg['picIconView']    = 'iconview.gif';
$cfg['picSep']         = 'separator.gif';
# mode
$cfg['xAction']        = false;
$cfg['xFilename']      = 'download.php';
# filetypes
$cfg['filetypes']      = array(
#   Extension   Icon (Pic)      Description (Type)      xAction     xFilename
#   ----------------------------------------------------------------------------------
#   '.ext',     extfile.gif,    EXT-Fil,               1,          download.php',      <-- EXAMPLE
    '.*,        file.gif,       Ukendt Filtype,                 ,                      ',
    '.bat,      batfile.gif,    Batchfile,               ,                      ',
    '.bmp,      bmpfile.gif,    Bitmap,                  ,                      ',
    '.bz2,      rarfile.gif,    BZ2 Archive,             ,                      ',
    '.c,        cfile.gif,      C Sourcefil,            ,                      ',
    '.chm,      chmfile.gif,    Helpfile,                ,                      ',
    '.cpp,      cppfile.gif,    C++ Sourcefil,          ,                      ',
    '.css,      cssfile.gif,    Cascading Style Sheet,   ,                      ',
    '.doc,      docfile.gif,    Word Dokument,           ,                      ',
    '.eml,      emlfile.gif,    E-Mail Fil,             ,                      ',
    '.exe,      exefile.gif,    Executable,              ,                      ',
    '.gif,      giffile.gif,    GIF Image,               ,                      ',
    '.gz,       zipfile.gif,    GZ Archive,              ,                      ',
    '.h,        hfile.gif,      C/C++ Headerfil,        ,                      ',
    '.hlp,      hlpfile.gif,    Helpfile,                ,                      ',
    '.htm,      htmfile.gif,    HTML Dokument,           ,                      ',
    '.html,     htmfile.gif,    HTML Dokument,           ,                      ',
    '.jpg,      jpgfile.gif,    JPG Image,               ,                      ',
    '.js,       jsfile.gif,     JavaScript Fil,         ,                      ',
#    '.m,        mfile.gif,      Matlab Fil,             ,                      ',
    '.mp3,      mp3file.gif,    MP3 Lydfil,           ,                      ',
    '.mpg,      mp3file.gif,    MPG Videofil,           ,                      ',
    '.pdf,      pdffile.gif,    PDF Fil,               ,                      ',
    '.png,      giffile.gif,    PNG Image,               ,                      ',
    '.pps,      pptfile.gif,    PowerPoint Show,         ,                      ',
    '.ppt,      pptfile.gif,    PowerPoint Fil,         ,                      ',
    '.rar,      rarfile.gif,    RAR Fil,             ,                      ',
#    '.rtf,      rtffile.gif,    Rich Text Format,        ,                      ',
#    '.swf,      swffile.gif,    Flash Object,            ,                      ',
    '.txt,      txtfile.gif,    Tekstfil,                ,                      ',
    '.wmv,      mp3file.gif,    Windows Media Fil       ,                      ',
    '.xls,      xlsfile.gif,    Excel Chart,             ,                      ',
    '.zip,      zipfile.gif,    ZIP-fil,             ,                      ',
);


/*****************************************************************************\
 * prepare variables                                                         *
\*****************************************************************************/

// Report all errors except E_NOTICE and E_WARNING
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

// Benchmark START
if( $cfg['benchmark'] )
    $g_time_start = getmicrotime();

// Check Path Formats ---------------------------------------------------------
$cfg['rootDir']    = formatDir($cfg['rootDir'],true,true);
$cfg['indexDir']   = formatDir($cfg['indexDir']);
$cfg['referer']    = addLinker($cfg['referer']);
$cfg['imgDir']     = formatDir($cfg['imgDir'],true);
// ----------------------------------------------------------------------------

// Create Filetype Array ------------------------------------------------------
$cfg['filetypes'] = parseFiletypeConfig( $cfg['filetypes'] );
// ----------------------------------------------------------------------------

// Handle (given) Directory ---------------------------------------------------
# initialize
$g_dir = $cfg['indexDir'];

# make lokal variable from HTTP_GET_VARS
if(isset($_GET['dir']))
    $g_dir = formatDir(rawParam('dir'));

# check given directory if it is valid/allowed
if( !isValidDir($cfg['rootDir'].$g_dir) ) {
    $g_err = array(
        "errmsg"  => "Invalid Directory",
        "errinfo" => $g_dir
    );
    $g_dir = $cfg['indexDir'];
}

# real path ($g_dir is just fake [relative to $cfg['rootDir']] for display)
$g_ldir = formatDir($cfg['rootDir'].$g_dir,true);
$g_dirsize = 0;
// ----------------------------------------------------------------------------

// Handle (given) View --------------------------------------------------------
$g_view = $cfg['defView'];

if(isset($_GET['view']) && in_array($_GET['view'],array('detail','icon'))) {
    $g_view = $_GET['view'];
}
// ----------------------------------------------------------------------------

// Get Directory Content ------------------------------------------------------
$g_files = array();
$g_folders = array();

# unfiltered directory content
getDirContent( $g_ldir);

# filter arrays
$g_files = filterArray( $g_files, $cfg['showFiles'], $cfg['hideFiles'] );
$g_folders = filterArray( $g_folders, $cfg['showFolders'], '.,..,'.$cfg['hideFolders'] );

# sort only by name
if( $cfg['fastSort'] ) {
    natcasesort( $g_files );
    natcasesort( $g_folders );
}

# get file properties
$g_files   = getFileAttr( $g_files );
$g_folders = getFolderAttr( $g_folders );
// ----------------------------------------------------------------------------

// Sort Directory Content -----------------------------------------------------
# parse sort criteria
if    ( $cfg['fastSort'] )         { $g_C = 'N'; $g_O = 'A';       }
#elseif( isset($_GET['D']) ) { $g_C = 'D'; $g_O = $_GET[$g_C]; }
elseif( isset($_GET['M']) ) { $g_C = 'M'; $g_O = $_GET[$g_C]; }
elseif( isset($_GET['S']) ) { $g_C = 'S'; $g_O = $_GET[$g_C]; }
elseif( isset($_GET['N']) ) { $g_C = 'N'; $g_O = $_GET[$g_C]; }
else                        { $g_C = $cfg['sortC']; $g_O = $cfg['sortO']; }

# sort
if( !$cfg['fastSort'] ) {
    usort( $g_files, 'cmp' );
    usort( $g_folders, 'cmp' );
}

# get new order of columns (array)
$g_neworder = newOrder( $g_C, $g_O );

# get sort pic
$g_sortpic = array('N'=>'','S'=>'','M'=>'','D'=>'');
$g_sort = array('N'=>'','S'=>'','M'=>'','D'=>'');
if( $cfg['showSortPic'] ) {
    $g_img = ($g_O=='D') ? $cfg['sortPicAsc'] : $cfg['sortPicDesc'];
    $g_sortpic[$g_C] = '<img src="'.$cfg['imgDir'].$g_img.'" alt="" />';
    $g_sort[$g_C] = ' id="'.(($g_O=='D') ? 'sortasc' : 'sortdesc').'"';
}
// ----------------------------------------------------------------------------

// Prepare Path Template ------------------------------------------------------
$g_tpl_target = $cfg['referer'].$g_C.'='.$g_O.'&amp;view='.$g_view.'&amp;dir=';
// ----------------------------------------------------------------------------

// handle up-button -----------------------------------------------------------
$g_up = getUpTarget($g_dir);
if( $cfg['su'] || ($g_dir && ($g_up!==false)) ) {
    $g_uptarget = $g_tpl_target.rawurlencode($g_up);
}
// ----------------------------------------------------------------------------


/*****************************************************************************\
 * prepare templates                                                         *
\*****************************************************************************/

// Iconbar --------------------------------------------------------------------
$tb_imgdir    = $cfg['imgDir'].'24/';
$tb_separator = '<img src="'.$tb_imgdir.$cfg['picSep'].'" alt="|" class="separator" />';

$g_iconbar = ''.
    '<div id="iconbar">'."\n".
    '  <a href="'.$g_tpl_target.rawurlencode($cfg['indexDir']).'" title="Tilbage til start"><img src="'.$tb_imgdir.$cfg['picHome'].'" border="0" alt="Tilbage til start" /></a>'."\n".
    '  <a href="'.$g_tpl_target.rawurlencode($g_dir).'" title="Opdater"><img src="'.$tb_imgdir.$cfg['picReload'].'" border="0" alt="Opdater" /></a>'."\n".
  (($g_uptarget) ? (
    '  <a href="'.$g_uptarget.'" title="Op"><img src="'.$tb_imgdir.$cfg['picUpEnabled'].'" border="0" alt="Op" /></a>'."\n"
  ):(
    '  <img src="'.$tb_imgdir.$cfg['picUpDisabled'].'" border="0" alt="Op" />'."\n"
  )).
    '  '.$tb_separator."\n".
    '  <a href="'.$cfg['referer'].$g_C.'='.$g_O.'&amp;view=detail&amp;dir='.rawurlencode($g_dir).'" title="Detaljeret visning"><img src="'.$tb_imgdir.$cfg['picDetailView'].'"'.(($g_view=='detail') ? ' class="active"' : '').' border="0" alt="Detaljeret visning" /></a>'."\n".
    '  <a href="'.$cfg['referer'].$g_C.'='.$g_O.'&amp;view=icon&amp;dir='.rawurlencode($g_dir).'" title="ikon visning"><img src="'.$tb_imgdir.$cfg['picIconView'].'"'.(($g_view=='icon') ? ' class="active"' : '').' border="0" alt="Ikon visning" /></a>'."\n".
    '  '.$tb_separator."\n".
    '</div>'."\n";
// ----------------------------------------------------------------------------

// Addressbar -----------------------------------------------------------------
$imgdir = $cfg['imgDir'].'16/';

$g_addrbar = ''.
    '<form method="get" action="'.$cfg['referer'].'">'."\n".
    '  <div id="addrbar">'."\n".
    '    <input type="hidden" name="'.$g_C.'" value="'.$g_O.'" />'."\n".
    '    <input type="hidden" name="view" value="'.$g_view.'" />'."\n".
    '    <input name="dir" type="text" tabindex="1" value="/'.htmlentities($g_dir).'"'.(($cfg['disableAddrBar'] && !$cfg['su'])?' readonly="readonly"':'').' />'."\n".
    '  </div>'."\n".
    '</form>'."\n";
// ----------------------------------------------------------------------------

// Toolbar --------------------------------------------------------------------
$g_toolbar = ''.
    '<table id="toolbar" cellspacing="0" summary="Toolbar">'."\n".
    '  <tr>'."\n".
    '    <td class="iconbar">'."\n\n".
    $g_iconbar."\n".
    '    </td>'."\n".
    '    <td class="addrbar">'."\n\n".
    $g_addrbar."\n".
    '    </td>'."\n".
    '  </tr>'."\n".
    '</table>'."\n";
// ----------------------------------------------------------------------------

// Error Msg ------------------------------------------------------------------
$g_errmsg = ''.
    '<div id="errmsg">'.
      '<span>'.$g_err['errmsg'].' <em>"/'.htmlentities($g_err['errinfo']).'"</em></span>'.
      '<a href="'.$g_tpl_target.rawurlencode($g_dir).'" title=""><img src="'.$cfg['imgDir'].'close.gif" alt="x" /></a>'.
    '</div>';
// ----------------------------------------------------------------------------

// Detail View ----------------------------------------------------------------
$th_tpl_target = $cfg['referer'].'view='.$g_view.'&amp;dir='.rawurlencode($g_dir).'&amp;';
$col_count = ($cfg['showName']+$cfg['showSize']+$cfg['showType']+$cfg['showLastMod']);
$imgdir = $cfg['imgDir'].'16/';

$tpl['detail']['header'] = "\n".
    '<table id="detailview" cellspacing="0" summary="Content of /'.htmlentities($g_dir).'">'."\n".
    '  <tr>'."\n".
  ($cfg['showName']    ? '    <th class="name"'.$g_sort['N'].'><a href="'.$th_tpl_target.'N='.$g_neworder['N'].'">'.$cfg['hName'].'</a></th>'."\n" : '').
  ($cfg['showSize']    ? '    <th class="size"'.$g_sort['S'].'><a href="'.$th_tpl_target.'S='.$g_neworder['S'].'">'.$cfg['hSize'].'</a></th>'."\n" : '').
  ($cfg['showLastMod'] ? '    <th class="lastmod"'.$g_sort['M'].'><a href="'.$th_tpl_target.'M='.$g_neworder['M'].'">'.$cfg['hLastMod'].'</a></th>'."\n" : '').
  ($cfg['showType']    ? '    <th class="type"'.$g_sort['D'].'><a href="'.$th_tpl_target.'M='.$g_neworder['D'].'">'.$cfg['hType'].'</a></th>'."\n" : '').
    '  </tr>'."\n";

$tpl['detail']['up'] = ''.
    '  <tr class="folder">'."\n".
  ($cfg['showName']    ? '    <td class="name"><a href="'.$g_uptarget.'" title="'.$g_uptarget.'"><img src="'.$imgdir.$cfg['picUp'].'" border="0" alt="up" /><span>..</span></a></td>'."\n" : '').
  ($cfg['showSize']    ? '    <td class="size">&nbsp;</td>'."\n" : '').
  ($cfg['showLastMod'] ? '    <td class="lastmod">&nbsp;</td>'."\n" : '').
  ($cfg['showType']    ? '    <td class="type">Up</td>'."\n" : '').
    '  </tr>'."\n";

$tpl['detail']['folder'] = ''.
    '  <tr class="folder">'."\n".
  ($cfg['showName']    ? '    <td class="name"><a href="{HREF}" title=""><img src="'.$imgdir.$cfg['picFolder'].'" border="0" alt="dir" /><span>{NAME}</span></a></td>'."\n" : '').
  ($cfg['showSize']    ? '    <td class="size">&nbsp;</td>'."\n" : '').
  ($cfg['showLastMod'] ? '    <td class="lastmod">{LASTMOD}</td>'."\n" : '').
  ($cfg['showType']    ? '    <td class="type">{TYPE}</td>'."\n" : '').
    '  </tr>'."\n";

$tpl['detail']['file'] = ''.
    '  <tr class="file">'."\n".
  ($cfg['showName']    ? '    <td class="name"><a href="{HREF}" title="{TOOLTIP}"><img src="'.$imgdir.'{IMG}" border="0" alt="file" /><span>{NAME}</span></a></td>'."\n" : '').
  ($cfg['showSize']    ? '    <td class="size">{SIZE}</td>'."\n" : '').
  ($cfg['showLastMod'] ? '    <td class="lastmod">{LASTMOD}</td>'."\n" : '').
  ($cfg['showType']    ? '    <td class="type">{TYPE}</td>'."\n" : '').
    '  </tr>'."\n";

$tpl['detail']['footer'] = ''.
    '  <tr class="vspace"><td colspan="'.$col_count.'">&nbsp;</td></tr>'."\n".
    '</table>'."\n";
// ----------------------------------------------------------------------------

// Icon View ------------------------------------------------------------------
$imgdir = $cfg['imgDir'].'32/';

$tpl['icon']['header'] = "\n".
    '<table id="iconview" cellspacing="0" summary="Content of /'.htmlentities($g_dir).'">'."\n".
    '  <tr>'."\n".
    '    <td>'."\n";

$tpl['icon']['up'] = "\n".
    '<div class="folder">'."\n".
    '  <a href="'.$g_uptarget.'" title="'.$g_uptarget.'">'."\n".
    '    <img src="'.$imgdir.$cfg['picUp'].'" border="0" alt="up" /><br />'."\n".
    '    <span class="name">..</span>'."\n".
    '  </a>'."\n".
    '</div>'."\n";

$tpl['icon']['folder'] = "\n".
    '<div class="folder">'."\n".
    '  <a href="{HREF}" title="">'."\n".
    '    <img src="'.$imgdir.$cfg['picFolder'].'" border="0" alt="dir" title="" /><br />'."\n".
    '    <span class="name">{SHORT_NAME}</span>'."\n".
    '  </a>'."\n".
    '</div>'."\n";

$tpl['icon']['file'] = "\n".
    '<div class="file">'."\n".
    '  <a href="{HREF}" title="{TOOLTIP}">'."\n".
    '    <img src="'.$imgdir.'{IMG}" border="0" alt="file" title="{TOOLTIP}" /><br />'."\n".
    '    <span class="name">{SHORT_NAME}</span>'."\n".
    '  </a>'."\n".
    '</div>'."\n";

$tpl['icon']['footer'] = "\n".
    '    </td>'."\n".
    '  </tr>'."\n".
    '  <tr class="vspace"><td>&nbsp;</td></tr>'."\n".
    '</table>'."\n";
// ----------------------------------------------------------------------------


/*****************************************************************************\
 * Output                                                                    *
\*****************************************************************************/

printExplorer();



/*****************************************************************************\
 * Functions                                                                 *
\*****************************************************************************/

// ----------------------------------------------------------------------------
// printExplorer() Main Output Function
function printExplorer()
{
    global $cfg, $tpl;
    global $g_toolbar, $g_addrbar, $g_errmsg;
    global $g_folders, $g_files, $g_dirsize;
    global $g_dir, $g_ldir, $g_err;
    global $g_tpl_target, $g_uptarget;
    global $g_view, $g_O, $g_time_start;

    # Frame
    echo '<div id="explorer">'."\n\n";

    # Toolbar
    if($cfg['showToolBar']) {
        echo $g_toolbar."\n";
    }
    # Addressbar
    if($cfg['showAddrBar'] && !$cfg['showToolBar']) {
        echo $g_addrbar."\n";
    }
    # Error Message
    if($g_err) {
        echo $g_errmsg."\n";
    }

    // ----------------------------------------------------------------------------
    // print Content
    echo '<div id="content">'."\n";

    # Header
    echo $tpl[$g_view]['header'];

    # UP-Button
    if( !$cfg['showToolBar'] && $g_uptarget ) {
        echo $tpl[$g_view]['up'];
    }

    # directory listing
    if( $g_O == 'A' ) {
        echo FolderListing().FileListing();
    } else {
        echo FileListing().FolderListing();
    }
    # Footer
    echo $tpl[$g_view]['footer'];

    echo "\n".'</div>'."\n\n";
    // ----------------------------------------------------------------------------

    # Statusbar
    if($cfg['showStatBar']) {
        echo "\n".'<div id="statusbar"><span id="stats">'.getStatMsg().'</span></div>'."\n";
    }
    # Frame END
    echo "\n".'</div>'."\n\n";

    # Benchmark
    if( $cfg['benchmark'] ) {
        printf("\n".'<div id="benchmark">processing time: %.3f seconds</div>'."\n", getmicrotime()-$g_time_start);
    }
    return 0;
}

// ----------------------------------------------------------------------------
// FolderListing() returns Folder Listing for $g_view
function FolderListing()
{
    global $cfg, $tpl;
    global $g_view, $g_folders, $g_dir;
    global $g_tpl_target;

    $ret = '';
    foreach ($g_folders as $folder)
    {
        # shorten foldername
        $foldername = $folder['name'];
        if( strlen($folder['name']) >= $cfg['maxStrlen'] ) {
            $foldername = substr($folder['name'], 0, $cfg['maxStrlen']-3).'...';
        }
        $tmp = array();
        $tmp['from'] = array( '{HREF}','{NAME}','{SHORT_NAME}','{LASTMOD}','{TYPE}' );
        $tmp['to'] = array(
            $g_tpl_target.rawurlencode($g_dir.'/'.$folder['name']),
            htmlentities($folder['name']),
            htmlentities($foldername),
            date($cfg['dateFormat'],$folder['lmod']),
            htmlentities($folder['type']),
        );
        $ret .= str_replace( $tmp['from'], $tmp['to'], $tpl[$g_view]['folder'] );
    }
    return $ret;
}

// ----------------------------------------------------------------------------
// FileListing() returns File Listing for $g_view
function FileListing()
{
    global $cfg, $tpl;
    global $g_view, $g_files, $g_dirsize, $g_ldir;

    $ret = '';
    foreach ($g_files as $file)
    {
        $g_dirsize += $file['size'];              // total filesize in current dir

        $target = getTarget($g_ldir.$file[name]);
        $size = ceil($file['size']/1024);         // convert from byte to kilobyte
        $size = "$size KB";                       // add unit
        $lastmod = date($cfg['dateFormat'],$file['lmod']);

        # shorten filename
        $filename = $file['name'];
        if( strlen($file['name']) >= $cfg['maxStrlen'] ) {
            $filename = substr($file['name'], 0, $cfg['maxStrlen']-3).'...';
        }

        $tooltip  = ' '.$file['name']." \n";
        $tooltip .= ' Type: '.$file['type']." \n";
        $tooltip .= ' Last Modified: '.$lastmod." \n";
        $tooltip .= ' Size: '.$size;

        $tmp = array();
        $tmp['from'] = array( '{HREF}','{IMG}','{NAME}','{SHORT_NAME}','{SIZE}','{LASTMOD}','{TYPE}','{TOOLTIP}' );
        $tmp['to'] = array(
            getTarget($g_ldir.$file['name']),
            getIcon($file['name']),
            htmlentities($file['name']),
            htmlentities($filename),
            $size,
            $lastmod,
            htmlentities($file['type']),
            htmlentities($tooltip),
        );
        $ret .= str_replace( $tmp['from'], $tmp['to'], $tpl[$g_view]['file'] );
    }
    return $ret;
}

// ----------------------------------------------------------------------------
// getStatMsg() returns Statistik Message
function getStatMsg( )
{
    global $g_folders, $g_files, $g_dirsize;

    $folder_count = count($g_folders);
    $file_count   = count($g_files);
    $total_size   = ceil($g_dirsize/1024);

    $msg  = $folder_count.' '.($folder_count==1?'Mappe':'Mapper').' | ';
    $msg .= $file_count.' '.($file_count==1?'Fil':'Filer').' | ';
    $msg .= $total_size.' KB I alt';

    return $msg;
}

// ----------------------------------------------------------------------------
// getUpTarget() returns target directory for UP button
function getUpTarget( $dir )
{
    global $cfg;

    if( $cfg['su'] && (!$dir || (substr($dir,-2)=='..')) )
        $target = formatDir($dir,true).'..';
    else
        $target = substr($dir,0,strrpos($dir,'/'));

    return $target;
}

// ----------------------------------------------------------------------------
// getDirContent() fills, filter and sort Arrays of files and folders
function getDirContent($dir)
{
    global $g_files, $g_folders;

    # fill arrays
    $handle = @opendir($dir);
    while( $file = readdir($handle) ) {
        if( is_dir("$dir/$file") )
            $g_folders[] = $file;
        elseif( is_file("$dir/$file") )
            $g_files[] = $file;
    }
    @closedir($handle);
}

// ----------------------------------------------------------------------------
// addLinker()    adds '?' or '&' to the referer
function addLinker($referer)
{
    // assume that last char is not '?' or '&'
    return strchr($referer,'?') ? "$referer&amp;" : "$referer?";
}

// ----------------------------------------------------------------------------
// formatDir()    skip trailing and leading "/" in given $dir-string and
//                add slashes depending on params
function formatDir($dir, $trailing=false, $leading=false)
{
    $dir = trim($dir,' /');
    if( $trailing && $dir )
        $dir = "$dir/";
    if( $leading ) #&& ($dir[0]!='/') )
        $dir = "./$dir";

    return $dir;
}

// ----------------------------------------------------------------------------
// filterArray()   make regular expression from $filter-string
function filterArray( $arr, $allow, $hide )
{
    $allow = makeRegex($allow);
    $hide  = makeRegex($hide);

    // preg_grep is available since PHP 4.2.0
#    $tmp = preg_grep( "/$allow/", $arr );
#    $tmp = preg_grep( "/$hide/",  $tmp, PREG_GREP_INVERT );
    // for PHP < 4.2.0
    $tmp = array();
    foreach( $arr as $val )
        if( preg_match("/$allow/",$val) && !preg_match("/$hide/",$val) )
            $tmp[] = $val;

    return $tmp;
}

// ----------------------------------------------------------------------------
// makeRegex()   make regular expression from $filter-string
function makeRegex( $filter )
{
    $regex = str_replace('.', '\.', $filter);
    $regex = str_replace('/', '\/', $regex);
    $regex = str_replace('*', '.+', $regex);
    $regex = str_replace(',', '$|^', $regex);

    return "^$regex$";
}

// ----------------------------------------------------------------------------
// isValidDir()   return true if directory is valid/allowed
function isValidDir( $dir )
{
    global $cfg;

    // check if folder exists (when manipulated manually)
    if( !is_dir($dir) ) return false;
    // No Restrictions are applied to Superuser
    if( $cfg['su'] ) return true;
    // prevent cd with relative path '../'
    return !(strpos($dir,'..')!==false);
}

// ----------------------------------------------------------------------------
// rawParam()
function rawParam( $param )
{
    return ini_get('magic_quotes_gpc') ? stripslashes($_GET[$param]) : $_GET[$param];
}

// ----------------------------------------------------------------------------
// getAttributes()   returns array with fileproperties
//                   (name, size, lastmod and desc)
function getFileAttr( $obj )
{
    global $g_ldir;

    $tmp = array();
    foreach( $obj as $file ) {
        $tmp[] = array(
            'name' => $file,
            'size' => filesize("$g_ldir$file"),    // get 'size of file' in bytes
            'lmod' => filemtime("$g_ldir$file"),   // get 'last modified date'
            'type' => getTyp("$file")             // get 'file description'
        );
    }
    return $tmp;
}

// ----------------------------------------------------------------------------
// getFolderAttributes()   returns array with fileproperties (name, size and lastmod)
function getFolderAttr( $obj )
{
    global $g_ldir;

    $tmp = array();
    foreach( $obj as $folder ) {
        $tmp[] = array(
            'name' => $folder,
            'size' => '',
            'lmod' => filemtime("$g_ldir$folder"),   // get 'last modified date'
            'type' => 'Fil-mappe'
        );
    }
    return $tmp;
}

// ----------------------------------------------------------------------------
// compare()
function cmp($a, $b) {

    global $g_C, $g_O;

    $sortKey   = array( 'N'=>'name', 'S'=>'size', 'M'=>'lmod', 'D'=>'type' );
    $sortOrder = array( 'A'=> 1, 'D'=> -1 );

    // sort by main criteria ($g_C)
    $ret = $sortOrder[$g_O] * strnatcasecmp($a[$sortKey[$g_C]], $b[$sortKey[$g_C]]);
    // sort equal values by filename
    if( $ret == 0 && $g_C != 'N' )
        $ret = $sortOrder[$g_O] * strnatcasecmp($a[$sortKey['N']], $b[$sortKey['N']]);

    return $ret;
}

// ----------------------------------------------------------------------------
// parseFiletypeConfig()   returns 2-dim array from given config-array
function parseFiletypeConfig( $picIcons )
{
    global $cfg;

    foreach( $picIcons as $type ) {
        $tmp = spliti( '[[:blank:]]*,[[:blank:]]*', $type );
        if( $tmp[4]=='' ) $tmp[4] = $cfg['xFilename'];
        if( $tmp[3]=='' ) $tmp[3] = $cfg['xAction'];

        $ret[$tmp[0]] = array(
            'icon' => $tmp[1],
            'type' => $tmp[2],
            'xact' => $tmp[3],
            'xfn'  => $tmp[4]
        );
    }
    return $ret;
}

// ----------------------------------------------------------------------------
// newOrder()   return order of $C for the next klick
function newOrder( $C, $O )
{
    $tmp = array(
        'N' => 'A',
        'S' => 'A',
        'M' => 'A',
        'D' => 'A'
    );
    // reverse order of current column
    $tmp[$C] = ($O=='D') ? 'A' : 'D';

    return $tmp;
}

// ----------------------------------------------------------------------------
// getTarget()   return target of click
function getTarget( $filename )
{
    global $cfg;

    // extract filename extension
    $ext = strtolower( strrchr( $filename, '.' ) );
    // handle unknown extensions
    if( !array_key_exists($ext,$cfg['filetypes']) )
        $ext = '.*';
    // format/encode url
    $filename = str_replace('%2F', '/', rawurlencode($filename));

    // return matching target
    return $cfg['filetypes'][$ext]['xact'] ? $cfg['filetypes'][$ext]['xfn']."?file=$filename" : $filename;
}

// ----------------------------------------------------------------------------
// getIcon()   return icon-image based on filename extension
function getIcon( $filename )
{
    global $cfg;

    // extract filename extension
    $ext = strtolower( strrchr( $filename, '.' ) );
    // return default image if $cfg['picFile'] = false or extension is unknown
    if( !$cfg['picFile'] || !array_key_exists($ext,$cfg['filetypes']) )
        return $cfg['filetypes']['.*']['icon'];

    // return matching image
    return $cfg['filetypes'][$ext]['icon'];
}

// ----------------------------------------------------------------------------
// getTyp()   return type-description based on filename extension
function getTyp( $filename )
{
    global $cfg;

    // extract filename extension
    $ext = strtolower( strrchr( $filename, '.' ) );
    // handle files without extension
    if( !$ext )
        return 'unknown';
    // return default description if extension is unknown
    if( !$cfg['filetypes'][$ext]['type'] )
        return substr(strtoupper($ext),1).' File';

    // return matching description
    return $cfg['filetypes'][$ext]['type'];
}

// ----------------------------------------------------------------------------
// getmicrotime()   return float value of unix timestamp in seconds
function getmicrotime()
{
   list($usec, $sec) = explode(" ",microtime());
   return ((float)$usec + (float)$sec);
}

closetable();

require_once THEMES."templates/footer.php";
?>
