<?PHP
$development = true;

if($development){
  $timeparts1 = explode(' ', microtime());
  error_reporting(2047); // this needs to be set to 0 when releases are released
} else
  error_reporting(0);

/**
 * File: filemanage.php
 *
 * Bobb's File Management System
 */
  $version = '1.0.0 -beta';
/* An expansion on, and by the same makers of
 * Bobb's File List System (www.sourceforge.net/projects/filelist/)
 *
 * Read the README file. It is a must read for all admins and programmers that
 * use or intend to edit this program. If you read nothing else in that file,
 * read "Notes about security" near the bottom.
 *
 * Bobb's File Manage System is the legal property of its developers whose names
 * are listed in the COPYRIGHT file.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

  // assigns $php_version to an array, representing the version and sub versions
$php_version = explode('.', phpversion());

if($php_version[0] > 4 || ($php_version[0] == 4 && $php_version[1] >= 3)){ // must be version 4.3.0 or higher
  if(!extension_loaded('mbstring')) // if it is not already loaded
    if(!@dl('extensions/php_mbstring.dll')) // the default location for a Windows CGI install
      if(!@dl('ext/php_mbstring.dll')) // the default location for a Windows CGI install
        if(!@dl('php_mbstring.dll')) // next possible location for Windows CGI install
          if(!@dl('php_mbstring.so')) // unlikely, but possible solution/location for Unix-based installs
            @dl('mbstring.so');  // unlikely, but possible solution/location for Unix-based installs

  if(!extension_loaded('exif')) // if it is not already loaded
    if(!@dl('extensions/php_exif.dll')) // the default location for a Windows CGI install
      if(!@dl('ext/php_exif.dll')) // the default location for a Windows CGI install
        if(!@dl('php_exif.dll')) // next possible location for Windows CGI install
          if(!@dl('php_exif.so')) // unlikely, but possible solution/location for Unix-based installs
            @dl('exif.so'); // unlikely, but possible solution/location for Unix-based installs

  if(isset($_GET['showthumb']) && function_exists('exif_read_data')){ // if the program calls for the thumbnail and the extension is loaded
    $imgdat = @exif_thumbnail($_GET['image'], $width, $height, $type);
    header('Content-type: ' . image_type_to_mime_type($type));
    echo($imgdat);
    die();
  }
}

if(isset($_GET['prop']) || isset($_GET['editpv']) || isset($_GET['viewperms'])
|| isset($_GET['note']) || isset($_GET['create'])
|| isset($_GET['upldprgres']) || isset($_GET['forcedownloadfile'])
|| (isset($_GET['redirect']) && $_GET['redirect'] == 'login'))
  $dontdispheader = true;
else
  $dontdispheader = false;

  // loc1 is the path on the computer filelist's location
define('loc1', dirname(__FILE__), true); // default location is the directory where this File Manage file is located
//define('loc1', 'C:\yo\g', true); // you can actually put any directory with read access as loc1; some functionality will be lost
  // if you change loc1, it is highly recomended to disable show_all_stats, and maybe show_add_info, both of which can dampen performance greatly.

  // define a constant, phpSelf
define('phpSelf', $_SERVER['PHP_SELF'], true);
define('cur_filename', get_name(phpSelf), true);

  // cur_dir is the directory path from the web server
define('cur_dir', stripslashes(str_replace('/'.cur_filename, '', phpSelf)), true);

if(!@ini_get('magic_quotes_gpc'))
  define('magicQuotes', false, true);
else
  define('magicQuotes', true, true);

  // magic_quotes_runtime is bad :-)   it adds slashes to quotes from files, so I disabled it
if(get_magic_quotes_runtime())
  set_magic_quotes_runtime(0);

if(!is_dir(loc1 . '/filelist/'))
  mkdir(loc1 . '/filelist/') or die('Not enough permissions to create directory. File Manage\'s containing directory must have write permissions. On Linux, 777 permisions is suggested.</body></html>');

  // SETINGS:
/******************************************************/
// settings are now set by opening the console in File Manage while logged in as
// an admin.

  // the following system allows for the program to be updated without changing
  // the admin's settings. Any new settings added to file manage will
  // automatically be added with default setting when the program is updated.
if(is_file(loc1 . '/filelist/filelist-settings.php')){
  $setting_ar = file(loc1 . '/filelist/filelist-settings.php');
  if(trim(substr($setting_ar[1], 3)) <= getlastmod() || count($setting_ar) < 45){
    $get_sets        = true;
    $create_settings = true;
  } else {
    include_once(loc1 . '/filelist/filelist-settings.php');
    $get_sets        = false;
    $create_settings = false;
  }
} else {
  $get_sets        = false;
  $create_settings = true;
}

if($create_settings){

  $ar[] = '<?PHP';
  $ar[] = '// ' . time();
  $ar[] = NULL;

  if($get_sets)
    include(loc1 . '/filelist/filelist-settings.php');

    // the following is a list of the setting variables with default settings
  if(isset($display_new))
    if(!$display_new)
      $ar[] = '$display_new       = 0;';
    else
      $ar[] = '$display_new       = '. $display_new .';';
  else
    $ar[] = '$display_new       = true;';

  if(isset($display_updated))
    if(!$display_updated)
      $ar[] = '$display_updated   = 0;';
    else
      $ar[] = '$display_updated   = '. $display_updated .';';
  else
    $ar[] = '$display_updated   = true;';

  if(isset($new_time_secs))
    $ar[] = '$new_time_secs     = '. $new_time_secs .';';
  else
    $ar[] = '$new_time_secs     = '. (60 * 60 * 24 * 14) .';';

  if(isset($error_spacer))
    $ar[] = '$error_spacer      = '. $error_spacer .';';
  else
    $ar[] = '$error_spacer      = 0.5;';

  if(isset($error_spacer2))
    $ar[] = '$error_spacer2     = '. $error_spacer2 .';';
  else
    $ar[] = '$error_spacer2     = 0.3;';

  if(isset($show_all_stats))
    if(!$show_all_stats)
      $ar[] = '$show_all_stats    = 0;';
    else
      $ar[] = '$show_all_stats    = '. $show_all_stats .';';
  else
    $ar[] = '$show_all_stats    = false;';

  if(isset($organize_ord))
    if(!$organize_ord)
      $ar[] = '$organize_ord      = 0;';
    else
      $ar[] = '$organize_ord      = '. $organize_ord .';';
  else
    $ar[] = '$organize_ord      = true;';

  if(isset($show_add_info))
    if(!$show_add_info)
      $ar[] = '$show_add_info     = 0;';
    else
      $ar[] = '$show_add_info     = '. $show_add_info .';';
  else
    $ar[] = '$show_add_info     = true;';

  if(isset($add_getid3))
    if(!$add_getid3)
      $ar[] = '$add_getid3        = 0;';
    else
      $ar[] = '$add_getid3        = '. $add_getid3 .';';
  else
    $ar[] = '$add_getid3        = false;';

  if(isset($force_download))
    if(!$force_download)
      $ar[] = '$force_download    = 0;';
    else
      $ar[] = '$force_download    = '. $force_download .';';
  else
    $ar[] = '$force_download    = 2;';

  if(isset($show_file_time))
    if(!$show_file_time)
      $ar[] = '$show_file_time    = 0;';
    else
      $ar[] = '$show_file_time    = '. $show_file_time .';';
  else
    $ar[] = '$show_file_time    = false;';

  if(isset($file_time))
    $ar[] = '$file_time         = \''. $file_time .'\';';
  else
    $ar[] = '$file_time         = \'m\';';

  if(isset($file_time_date))
    $ar[] = '$file_time_date    = \''. $file_time_date .'\';';
  else
    $ar[] = '$file_time_date    = \'j M, Y H:i:s\';';

  if(isset($require_login))
    if(!$require_login)
      $ar[] = '$require_login     = 0;';
    else
      $ar[] = '$require_login     = '. $require_login .';';
  else
    $ar[] = '$require_login     = true;';

  if(isset($allow_anonymous))
    if(!$allow_anonymous)
      $ar[] = '$allow_anonymous   = 0;';
    else
      $ar[] = '$allow_anonymous   = '. $allow_anonymous .';';
  else
    $ar[] = '$allow_anonymous   = false;';

  if(isset($auto_anonym_login))
    if(!$auto_anonym_login)
      $ar[] = '$auto_anonym_login = 0;';
    else
      $ar[] = '$auto_anonym_login = '. $auto_anonym_login .';';
  else
    $ar[] = '$auto_anonym_login = true;';

  if(isset($anonym_perm))
    if(isset($anonym_perm_type) && $anonym_perm_type == 'hex')
      $ar[] = '$anonym_perm       = \''. $anonym_perm .'\';';
    else
      $ar[] = '$anonym_perm       = '. $anonym_perm .';';
  else
    $ar[] = '$anonym_perm       = 8;';

  if(isset($anonym_perm_type))
    $ar[] = '$anonym_perm_type  = \''. $anonym_perm_type .'\';';
  else
    $ar[] = '$anonym_perm_type  = \'basic\';';

  if(isset($line_break)){
    if($line_break == "\r")
      $ar[] = '$line_break        = "\\r";';
    elseif($line_break == "\r\n")
      $ar[] = '$line_break        = "\\r\\n";';
    else
      $ar[] = '$line_break        = "\\n";';
  } else
    $ar[] = '$line_break        = "\\n";';

  if(isset($auto_icon))
    if(!$auto_icon)
      $ar[] = '$auto_icon         = 0;';
    else
      $ar[] = '$auto_icon         = '. $auto_icon .';';
  else
    $ar[] = '$auto_icon         = true;';

  if(isset($logging_level))
    $ar[] = '$logging_level     = '. $logging_level .';';
  else
    $ar[] = '$logging_level     = 3;';

  if(isset($font_size))
    $ar[] = '$font_size         = \''. $font_size .'\';';
  else
    $ar[] = '$font_size         = \'-1\';';

  if(isset($name_length))
    $ar[] = '$name_length       = '. $name_length .';';
  else
    $ar[] = '$name_length       = 25;';

  if(isset($trunc_offset))
    $ar[] = '$trunc_offset      = '. $trunc_offset .';';
  else
    $ar[] = '$trunc_offset      = 7;';

  if(isset($recycle))
    if(!$recycle)
      $ar[] = '$recycle           = 0;';
    else
      $ar[] = '$recycle           = '. $recycle .';';
  else
    $ar[] = '$recycle           = true;';

  if(isset($altern_line_color))
    if(!$altern_line_color)
      $ar[] = '$altern_line_color = 0;';
    else
      $ar[] = '$altern_line_color = '. $altern_line_color .';';
  else
    $ar[] = '$altern_line_color = true;';

  if(isset($altern_color))
    $ar[] = '$altern_color      = \''. $altern_color .'\';';
  else
    $ar[] = '$altern_color      = \'#181818\';';

  if(isset($max_log_size))
    $ar[] = '$max_log_size      = '. $max_log_size .';';
  else
    $ar[] = '$max_log_size      = 250;'; // size in KB

  if(isset($upload_bar))
    if(!$upload_bar)
      $ar[] = '$upload_bar        = 0;';
    else
      $ar[] = '$upload_bar        = '. $upload_bar .';';
  else
    $ar[] = '$upload_bar        = false;';

  if(isset($all_upload_bar))
    if(!$all_upload_bar)
      $ar[] = '$all_upload_bar    = 0;';
    else
      $ar[] = '$all_upload_bar    = '. $all_upload_bar .';';
  else
    $ar[] = '$all_upload_bar    = false;';

  if(isset($allow_login_request))
    if(!$allow_login_request)
      $ar[] = '$allow_login_request = 0;';
    else
      $ar[] = '$allow_login_request = '. $allow_login_request .';';
  else
    $ar[] = '$allow_login_request = true;';

  if(isset($remember_org))
    if(!$remember_org)
      $ar[] = '$remember_org      = 0;';
    else
      $ar[] = '$remember_org      = '. $remember_org .';';
  else
    $ar[] = '$remember_org      = true;';

  if(isset($admin_see_hidden))
    if(!$admin_see_hidden)
      $ar[] = '$admin_see_hidden  = 0;';
    else
      $ar[] = '$admin_see_hidden  = '. $admin_see_hidden .';';
  else
    $ar[] = '$admin_see_hidden  = true;';

  if(isset($multi_upload))
    if(!$multi_upload)
      $ar[] = '$multi_upload      = 0;';
    else
      $ar[] = '$multi_upload      = '. $multi_upload .';';
  else
    $ar[] = '$multi_upload      = true;';

  if(isset($track_time))
    if(!$track_time)
      $ar[] = '$track_time        = 0;';
    else
      $ar[] = '$track_time        = '. $track_time .';';
  else
    $ar[] = '$track_time        = true;';

  if(isset($max_track_size))
    $ar[] = '$max_track_size    = '. $max_track_size .';';
  else
    $ar[] = '$max_track_size    = 150;'; // size in KB

  if(isset($show_dir_size))
    if(!$show_dir_size)
      $ar[] = '$show_dir_size     = 0;';
    else
      $ar[] = '$show_dir_size     = '. $show_dir_size .';';
  else
    $ar[] = '$show_dir_size     = false;';

  if(isset($force_server_sets))
    $ar[] = '$force_server_sets = '. $force_server_sets .';';
  else
    $ar[] = '$force_server_sets = 1;';

  if(isset($show_file_hash))
    if(!$show_file_hash)
      $ar[] = '$show_file_hash    = 0;';
    else
      $ar[] = '$show_file_hash    = '. $show_file_hash .';';
  else
    $ar[] = '$show_file_hash    = true;';

  if(isset($hash_size))
    $ar[] = '$hash_size         = '. $hash_size .';';
  else
    $ar[] = '$hash_size         = 5;'; // size in MB

  if(isset($show_exif_thumb))
    if(!$show_exif_thumb)
      $ar[] = '$show_exif_thumb   = 0;';
    else
      $ar[] = '$show_exif_thumb   = '. $show_exif_thumb .';';
  else
    $ar[] = '$show_exif_thumb   = true;';

  if(isset($strong_pw_enforce))
    if(!$strong_pw_enforce)
      $ar[] = '$strong_pw_enforce = 0;';
    else
      $ar[] = '$strong_pw_enforce = '. $strong_pw_enforce .';';
  else
    $ar[] = '$strong_pw_enforce   = true;';

  $tmp_ar = array('unlink(','rmdir(','fwrite(','fopen(','opendir(','readdir(','file(','file_get_contents(','rename(','copy(','$_SESSION[','session_id(','session_start(','session_regenerate_id(', 'include(', 'include_once(', 'glob(');
  if(isset($illegal_words)){
    $missing_ar = array_diff($tmp_ar, $illegal_words);
    if(count($missing_ar) > 0)
      $illegal_words = array_merge($illegal_words, $missing_ar);
    $ar[] = '$illegal_words     = array(\'' . implode('\',\'', $illegal_words) . '\');';
  } else
    $ar[] = '$illegal_words     = array(\'' . implode('\',\'', $tmp_ar) . '\'); // this array contains any words you do not want being submitted into the system. The default values are a good series to keep your system secure. This censor can be overridden by an admin passcode.';

  if(isset($accept))
    $ar[] = '$accept            = array(\''. implode('\',\'', $accept) .'\');';
  else
    $ar[] = NULL;

  if(isset($iconlink))
    $ar[] = '$iconlink          = array(\''. implode('\',\'', $iconlink) .'\');';
  else
    $ar[] = NULL;

  $ar[] = NULL;
  $ar[] = '?>';
  $ar[] = NULL;

    // write settings to the settings file
  $write = implode("\n", $ar);
  $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
  $fp = fwrite($fout, $write);
  fclose($fout);

  include(loc1 . '/filelist/filelist-settings.php');
}

if(loc1 != dirname(__FILE__))
  $force_download = 2;

if(!isset($timeparts1) && $track_time)
  $timeparts1 = explode(' ', microtime());

// If $auto_icon is enabled, you can ignore the $iconlink array.
// these two keys will match together to display
// the right icons with the filetype
if(!isset($accept))
  $accept = array(
    // acceptible file endings. for best result include the '.' in a desired file extension
    // if you add '' to the list, it will display all files.
    '.zip',  // Zip compression
    '.tar.gz',// Tar czip compression
    '.tgz',  // Tar gzip compression
    '.gz',   // Gzip compression
    '.7z',   // 7-zip compression
    '.7zip', // 7-zip compression
    '.rar',  // RarLabs compression
    '.z',    // Tar/taz compression
    '.exe',  // Windows binary executable
    '.msi',  // Microsoft installer
    '.html', // Hypertext markup language document
    '.htm',  // Hypertext markup language document
    '.shtml',// Hypertext markup language document w/server-side directives
    '.xhtml',// Extensible hypertext markup language document
    '.xml',  // Extensible markup language
    '.php',  // PHP: Hypertext preprocessor document
    '.php3', // PHP: Hypertext preprocessor document; php version 3
    '.php4', // PHP: Hypertext preprocessor document; php version 4
    '.php5', // PHP: Hypertext preprocessor document; php version 5
    '.phtml',// PHP: Hypertext preprocessor document
    '.asp',  // Active Server Page
    '.xls',  // Microsoft Office Excel document
    '.jpg',  // Jpeg/Jiff Image
    '.jpeg', // Jpeg/Jiff Image
    '.gif',  // Graphic interchange formated/CompuServe GIF image
    '.tiff', // Tagged image format file
    '.tif',  // Tagged image format file
    '.png',  // Portable/Public network graphic
    '.bmp',  // Windows bitmap image
    '.swf',  // Macromedia flash file
    '.swc',  // Macromedia flash file
    '.avi',  // Audio video interleave file
    '.asf',  // Advanced streaming format video
    '.mpg',  // MPEG layer 1/2 video
    '.mpeg', // MPEG layer 1/2 video
    '.wmv',  // Windows media video
    '.mov',  // Quicktime video
    '.mp4',  // MPEG Layer 4 video
    '.divx', // DivX encoded video
    '.dvx',  // DivX encoded video
    '.xvid', // Xvid encoded video
    '.rm',   // RealMedia streaming media
    '.ram',  // RealMedia metafile
    '.ogm',  // Ogg Vorbis compressed video file
    '.mpa',  // MPEG layer 1/2/3 audio/video stream
    '.mp3',  // MPEG layer 3 audio stream
    '.wma',  // Windows media audio
    '.m4a',  // MPEG-4 audio layer
    '.ogg',  // Ogg Vorbis codec compressed WAV file
    '.mp2',  // MPEG audio stream, layer II
    '.flac', // Free lossless audio codec
    '.vqf',  // Transform-domain weighted interleave vector quantization audio file
    '.ape',  // Monkey's audio lossless audio compression format
    '.au',   // AU audio file
    '.aac',  // MPEG-2 advanced audio coding file
    '.aiff', // Audio interchange file
    '.wav',  // WAV audio file
    '.psd',  // Photoshop document
    '.pmd',  // PageMaker document
    '.pmt',  // PageMaker template
    '.indd', // InDesign document
    '.doc',  // Microsoft Office Word document
    '.txt',  // Plain text document
    '.nfo',  // System info file
    '.list', // Plain text docuement
    '.cgi',  // Common gateway interface script
    '.tmpl', // Template file
    '.diz',  // Description in zip file (plain text)
    '.bin',  // Binary file
    '.dvi',  // Digital video interactive
    '.iso',  // ISO-9660 CD disc image/InstallShield uninstall file
    '.pdf',  // Adobe Acrobat portable document format
    '.js',   // Javascrip file
    '.css',  // Cascading style sheet document
    '.vbs',  // Visual Basic for applications script
    '.tar',  // Tape archive file
    '.tex',  // Plain text file/PaintShop Pro texture
    'core',  // Core Software Tech CORE IDC bitmap
    '.sql',  // Structured query language data (mySQL, SQL, etc)
    '.conf', // Configuration file (Linux/IRC/etc)
    '.sh',   // Unix shell script
    '.nsi',  // Nullsoft Installer System script
    '.shar', // UNIX shar archive file
    '.csh',  // UNIX csh shell script
    '.ksh',  // UNIX shell script
    '.tcl',  // Tool command language script
    '.uu',   // Compressed archive file
    '.for',  // FORTRAN source code
    '.pl',   // Linux shell executable binary/PERL program file
    '.py',   // Python script file
    '.c',    // C/C++ code file
    '.cpp',  // Visual C++ source code file/C++ Builder 6 file
    '.h',    // C program header file
    '.hpp',  // C++ program header file
    '.ai',   // Ai Archiver archive
    '.hqx',  // Macintosh BinHex 4 compressed archive
    'readme',// README file
    '.ini',  // Initialization/configuration file
    '.inf',  // Information or setup/autorun file
    '.reg',  // Registry data file
    '.java', // Java source code document
    '.asm',  // Assembler source language
    '.ppt',  // Microsoft Office PowerPoint document
    ''       // everything else
  );

// ignore this if $auto_icon is enabled or if popups are being shown
if(!$auto_icon && !$dontdispheader && !isset($iconlink)){
  $iconlink = array(
    // linked to src of image you want
    'icons/compressed.gif', // .zip
    'icons/compressed.gif', // .tar.gz
    'icons/compressed.gif', // .tgz
    'icons/compressed.gif', // .gz
    'icons/compressed.gif', // .7z
    'icons/compressed.gif', // .7zip
    'icons/compressed.gif', // .rar
    'icons/compressed.gif', // .z
    'icons/burst.gif',      // .exe
    'icons/comp.gray.gif',  // .msi
    'icons/layout.gif',     // .html
    'icons/layout.gif',     // .htm
    'icons/layout.gif',     // .shtml
    'icons/layout.gif',     // .xhtml
    'icons/layout.gif',     // .xml
    'icons/layout.gif',     // .php
    'icons/layout.gif',     // .php3
    'icons/layout.gif',     // .php4
    'icons/layout.gif',     // .php5
    'icons/layout.gif',     // .phtml
    'icons/layout.gif',     // .asp
    'icons/layout.gif',     // .xls
    'icons/image2.gif',     // .jpg
    'icons/image2.gif',     // .jpeg
    'icons/image2.gif',     // .gif
    'icons/image2.gif',     // .tiff
    'icons/image2.gif',     // .tif
    'icons/image2.gif',     // .png
    'icons/image2.gif',     // .bmp
    'icons/image3.gif',     // .swf
    'icons/image3.gif',     // .swc
    'icons/movie.gif',      // .avi
    'icons/movie.gif',      // .asf
    'icons/movie.gif',      // .mpg
    'icons/movie.gif',      // .mpeg
    'icons/movie.gif',      // .wmv
    'icons/movie.gif',      // .mov
    'icons/movie.gif',      // .mp4
    'icons/movie.gif',      // .divx
    'icons/movie.gif',      // .dvx
    'icons/movie.gif',      // .xvid
    'icons/movie.gif',      // .rm
    'icons/movie.gif',      // .ram
    'icons/movie.gif',      // .ogm
    'icons/sound2.gif',     // .mpa
    'icons/sound2.gif',     // .mp3
    'icons/sound2.gif',     // .wma
    'icons/sound2.gif',     // .m4a
    'icons/sound2.gif',     // .ogg
    'icons/sound2.gif',     // .mp2
    'icons/sound1.gif',     // .flac
    'icons/sound1.gif',     // .vqf
    'icons/sound1.gif',     // .ape
    'icons/sound1.gif',     // .au
    'icons/sound1.gif',     // .aac
    'icons/sound1.gif',     // .aiff
    'icons/sound1.gif',     // .wav
    'icons/image1.gif',     // .psd
    'icons/image1.gif',     // .pmd
    'icons/image1.gif',     // .pmt
    'icons/image1.gif',     // .indd
    'icons/text.gif',       // .doc
    'icons/text.gif',       // .txt
    'icons/text.gif',       // .nof
    'icons/text.gif',       // .list
    'icons/text.gif',       // .cgi
    'icons/text.gif',       // .tmpl
    'icons/text.gif',       // .diz
    'icons/binary.gif',     // .bin
    'icons/dvi.gif',        // .dvi
    'icons/diskimg.gif',    // .iso
    'icons/pdf.gif',        // .pdf
    'icons/script.gif',     // .js
    'icons/script.gif',     // .css
    'icons/script.gif',     // .vbs
    'icons/tar.gif',        // .tar
    'icons/tex.gif',        // .tex
    'icons/bomb.gif',       // core
    'icons/script.gif',     // .sql
    'icons/script.gif',     // .conf
    'icons/script.gif',     // .sh
    'icons/script.gif',     // .nsi
    'icons/script.gif',     // .shar
    'icons/script.gif',     // .csh
    'icons/script.gif',     // .ksh
    'icons/script.gif',     // .tcl
    'icons/uuencoded.gif',  // .uu
    'icons/f.gif',          // .for
    'icons/p.gif',          // .pl
    'icons/p.gif',          // .py
    'icons/c.gif',          // .c
    'icons/c.gif',          // .cpp
    'icons/c.gif',          // .h
    'icons/c.gif',          // .hpp
    'icons/a.gif',          // .ai
    'icons/binhex.gif',     // .hqx
    'icons/hand.right.gif', // .readme
    'icons/screw2.gif',     // .ini
    'icons/screw2.gif',     // .inf
    'icons/screw2.gif',     // .reg
    'icons/quill.gif',      // .java
    'icons/script.gif',     // .asm
    'icons/p.gif',          // .ppt
    'icons/unknown.gif'     // '' (everything else)
  );
}

/******************************************************/

if($line_break != "\r\n" && $line_break != "\r" && $line_break != "\n")
  $line_break = "\n";

  // if the array is setup to accept all extensions set vairable
if(in_array('', $accept))
  $accept_all = true;
else
  $accept_all = false;

hits(); // log hits/page views
del_tmp(); // delete generated temperary files
index_sec(); // adds index files to the filelist directory so no server index is made (better security)
index_sec('/filelist/.recycle/');
index_sec('/filelist/.recycle/cont/');
index_sec('/filelist/filelist-userdb/');
index_sec('/filelist/filelist-icons/');

  // if the create user variable is set, go to that page
if(isset($_GET['create']))
  make_user();

  // make sure there isn't an invalid number for anonymous permissions
if(($anonym_perm_type == 'basic' && ($anonym_perm > 9 || $anonym_perm < 1))
|| ($anonym_perm_type == 'hex' && (hexdec($anonym_perm) > 256 || hexdec($anonym_perm) < 1))){
  $anonym_perm = 9;
  $anonym_perm_type = 'basic';
}

if(is_file(loc1 . '/filelist/filelist-hiddenitems.list')){
  $hidden_items_ar = file(loc1 . '/filelist/filelist-hiddenitems.list');
  foreach($hidden_items_ar as $j => $hidden_item)
    $hidden_items_ar[$j] = trim($hidden_item);
}

  // use of $loc before loc is defined
if(!isset($_GET['loc']))
  $loc = './';
else
  if(magicQuotes)
    $loc = stripslashes($_GET['loc']);
  else
    $loc = $_GET['loc'];


  // if a note is going to be displayed
if(isset($_GET['note'])){
  $note = $_GET['note'];
  echo '<html><body bgcolor="#FFFFFF" text="#000000" vlink="#000000" alink="#000000" link="#000000">';
    // use this to display note 1 with a popup window size of 200 (width) x 300 (height)
  //note(1, 200, 300)

  switch($note){
    case 1:
      echo 'The way this system works is that an admin must create your user first.<br>A passcode is used to verify that the admin has contacted you and has allowed to you access their system as a normal user.';
      break;
    case 2:
      echo 'The path is determined by the path from the File Manage file. This does not include any additional path that the server may have, nor does it include the webserver\'s path. It\'s main use would be in the console.';
      break;
    case 3:
      echo 'Audio/Video information is gathered from the open source program <a target="_blank" href="http://www.sourceforge.net/projects/getid3/">getid3()</a>. ';
      break;
    case 4:
      echo 'Anonymous logins can be used when an admin does not care if unknown users view certain aspects of files.<br>Anonymous users generally have a lower number of abilities compared to registed users.';
      break;
    case 5:
      echo 'A search locates files and folders in the current directory with exact and similar matches (unless "Exact results only" is selected). Currently similar matches can be '. ($error_spacer * 100) .'% incorrect on a per word basis, and '. ($error_spacer2 * 100) .'% incorrect on a per phrase basis. Per phrase will include spaces and other chance word anomalies that would make it more likely to match, so it should be a lower value.';
      break;
    case 6:
      echo 'Email address will only be used by this program to send you your password if you forget what it is.';
      break;
    case 7:
      echo 'Your permissions level determins what you are able to do in this program. Click on the "View permissions" link to see each specific ability, and whether or not you are allowed to do it.';
      break;
    case 8:
      echo 'Permissions type is associated with the permissions level and uses the hex or basic (decimal) number to translate what abilities you are allowed to have.';
      break;
    case 9:
      echo 'When unchecked, the user will be assigned to "basic" permissions. This is not a downgrade, it is just a security system based on 10 available values. 0 is admin, 1 is a normal user with all viewing abilities. Each number higher is one less ability the user will have, up to 9, where the user has no abilities. When HEX is selected, users are put into a security matrix, which can allow specific abilities to be on or off depending on how the admin wants it. The easiest way to create the correct permissions (basic or hex) is to check or uncheck the checkboxes on the right.';
      break;
    case 10:
      echo 'A passcode is for creating a user without giving other people on the internet the ability to login when unwanted. It also means that the admin never sees a user\'s password for obvious security reasons.';
      break;
    case 11:
      echo 'Page views is every time any page is accessed on this program. The starting date is the first day that the File Manage program was run.';
      break;
    case 12:
      echo 'Unique visitors are an IP-based tracking system that only counts the number of unique IPs that have viewed any of the pages in this program.';
      break;
    case 13:
      echo 'This console is a command line that uses common Linux commands to control the File Manage system with greater power. Since only admins can access the console, users of the console can view and change system settings.';
      break;
    case 14:
      echo 'The flash type or power is a numerical value set by a camera to represent a flash setting. Each camera company (maybe even each camera) will have very different values for different flashes. Often 0 will represent the flash being off, and the higher the number the stronger the flash. Different ranges of numbers may represent a standard flash versus a red-eye flash.';
      break;
    case 15:
      echo 'Anonymous logins can be used when an admin does not care if unknown users view certain aspects of files.<br>Anonymous users generally have a lower number of abilities compared to registed users.<br>Disabling this will automatically disable "Automatically log users in as anonymous".<br>Anonymous users should never have a permission number lower than 6 (basic)!';
      break;
    case 16:
      echo 'Automatically logging users in as anonymous allows non-logged in users to skip the login page. This makes general use (of viewing files or directories) for many users quicker and easier. The "login" button is always available to all anonymous users at the top-right.';
      break;
    case 17:
      echo 'Original bit rate is the rate (quality) the source was first encoded at. A compresion codec is then used to help the overall filesize without greatly damaging the quality.';
      break;
    case 18:
      echo 'True bit rate is a calculated number based on the file size divided by the total length of a file (accurate to the frame). This value will likely differ from the displayed bit rate because this is not based in any codecs or tags.';
      break;
    case 19:
      echo 'The recycle bin mimics the recycle or trash bin of modern operating systems. Deleted files are placed in a separate, hidden, directory which only admins and users with specific abilities (dealing with deleting) have access to. From there the files can be perminently deleted (by admins only), moved to a new directory, or restored to their original locations.</font>';
      break;
    case 20:
      echo 'MD5 Hash: '.md5_file(loc1 . $_GET['file']).'<br>SHA1 Hash: '.sha1_file(loc1 . $_GET['file']);
      break;
    case 21:
      echo 'Censor passcode is a password which allows the program to skip the illegal_words check against the adding of possibly malicious code. The passcode can only be set by the user "admin" and by default is not set. When it is set only users with the passcode can indruduce files with an item in illegal_words.';
      break;
    case 22:
      echo 'The "Set Settings and Users to Default" button will set the default settings, just as the "Set Settings" button does. But this button will also erase all users\' settings files. This way, if you make a setting change (to an <i>italicized</i> setting) that you want applied to all users, you click this button. It is also necisarry to click this button if the "Force Server-Default Settings" setting is changed (else each users\' settings will remain the same until they adjust their "My Settings": "Visual Settings for File Manage").';
      break;
    case 23:
      echo 'The "Set All to Default" button will force all server default settings to the original system default settings as well as set each users\' settings to default.';
      break;
    case 24:
      echo 'The "Reset All to Default" button will remove any changes to the accept array or iconlink array. This means that all icon associations that have been changed will be set back to their defaults, and auto_icon will be enabled.';
      break;
    /*case 30:
      echo '';
      break;*/
    default:
      echo 'No note for this';
  }

  echo '<br><input type="button" onClick="JavaScript=window.close()" value="Close Window">';
} else



if($upload_bar && isset($_GET['upld']) && isset($_GET['progress'])){
  upload_popup();
} else



  // this program requires PHP 4.3.0 or newer
if(($require_login && logintest() && ($php_version[0] > 4 || ($php_version[0] == 4 && $php_version[1] >= 3)) && !isset($_GET['create'])) || !$require_login){

  if(is_file(loc1 . '/filelist/filelist-passcode.php')){
    $passcode_ar = file(loc1 . '/filelist/filelist-passcode.php');
    if(count($passcode_ar) < 3){
      $fout = fopen(loc1 . '/filelist/filelist-passcode.php', 'w');
      $fp = fwrite($fout, '<?PHP'.$line_break.trim($passcode_ar[0]).$line_break.'?>'.$line_break);
      fclose($fout);
    }
  }

    // clear login attempts if successful
  if($un != 'anonymous'){
    if(is_file(loc1 . '/filelist/filelist-loginattempts-IP.list') && isset($_SERVER['REMOTE_ADDR'])){
      $IP_ar = file(loc1 . '/filelist/filelist-loginattempts-IP.list');
      foreach($IP_ar as $IP_info){
        $sub_array = explode('~~~~~', trim($IP_info));
        if($_SERVER['REMOTE_ADDR'] != $sub_array[0])
          $new_IP_ar[] = $IP_info;
      }
      if(isset($new_IP_ar) && count($new_IP_ar) > 0){
        $fout = fopen(loc1 . '/filelist/filelist-loginattempts-IP.list', 'w');
        $fp = fwrite($fout, implode('', $new_IP_ar));
        fclose($fout);
      } else
        @unlink(loc1 . '/filelist/filelist-loginattempts-IP.list');
    }

    if(is_file(loc1 . '/filelist/filelist-loginattempts-un.list') && isset($un)){
      $array_of_users = file(loc1 . '/filelist/filelist-logins.list'); // file with all users
      foreach($array_of_users as $i => $user_name)
        $users_array[$i] = trim($user_name);
      $un_ar = file(loc1 . '/filelist/filelist-loginattempts-un.list');
      foreach($un_ar as $un_info){
        $sub_array = explode('~~~~~', trim($un_info));
        if($un != $sub_array[0] && trim($sub_array[0]) != '' && in_array($sub_array[0], $users_array))
          $new_un_ar[] = $un_info;
      }
      if(isset($new_un_ar) && count($new_un_ar) > 0){
        $fout = fopen(loc1 . '/filelist/filelist-loginattempts-un.list', 'w');
        $fp = fwrite($fout, implode('', $new_un_ar));
        fclose($fout);
      } else
        @unlink(loc1 . '/filelist/filelist-loginattempts-un.list');
    }
  }

  if($require_login && $un != 'anonymous')
    if(is_file(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php'))
      include(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php');

  if($name_length < 8)
    $name_length = 8;

  $trunc_offset1 = $trunc_offset + 3;
  if($trunc_offset1 > $name_length)
    $trunc_offset1 = $name_length;
  if($trunc_offset1 < 3)
    $trunc_offset1 = 3;

  if(isset($_GET['redirect']) && $_GET['redirect'] == 'login'){
    echo '<script language="JavaScript">';
    // the genius JavaScript function name below originally coined by Bradley Hart!
    echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes($loc).'\',1)';
    echo '</script>';
    die('<a href="'.phpSelf.'?loc='.$loc.'">Click here to continue</a></body></html>');
  }

    // if require_login is false, then set the user's permissions to the anonymous settings
  if(!$require_login){
    $login    = true;
    $admin    = false;
    $perm = $anonym_perm;
    $permtype = $anonym_perm_type;
    $useremail = '';
    $ul_value = 0;
    $anonymous_user = true;
    $un = 'anonymous';
    $pw = md5('anonymous');
  }

    // get array of user's abilities
  $current_user = get_perm($perm, $permtype);


  if(isset($_GET['forcedownloadfile']) && allowed($_GET['forcedownloadfile']) && $current_user['read']){

      /* source code for the following was found on http://www.elouai.com/force-download.php
      and was assumed public domain. It has been modified to fit File Manage's purposes. */

    if(magicQuotes)
      $filename = stripslashes($_GET['forcedownloadfile']);
    else
      $filename = $_GET['forcedownloadfile'];

    if($filename == "" || !file_exists(loc1 . $filename))
      exit;

    // required for IE, otherwise Content-disposition is ignored
    if(ini_get('zlib.output_compression'))
      ini_set('zlib.output_compression', 'Off');

    // addition by Jorg Weske
    $file_extension = strtolower(substr(strrchr($filename, "."), 1));

    switch($file_extension){
      case "pdf":
        $ctype = "application/pdf";
        break;
      case "exe":
        $ctype = "application/octet-stream";
        break;
      case "zip":
        $ctype = "application/zip";
        break;
      case "doc":
        $ctype = "application/msword";
        break;
      case "xls":
        $ctype = "application/vnd.ms-excel";
        break;
      case "ppt":
        $ctype = "application/vnd.ms-powerpoint";
        break;
      case "gif":
        $ctype = "image/gif";
        break;
      case "png":
        $ctype = "image/png";
        break;
      case "jpeg":
      case "jpg":
        $ctype = "image/jpg";
        break;
      default: $ctype = "application/force-download";
    }
    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false); // required for certain browsers
    header("Content-Type: $ctype");
    // change, added quotes to allow spaces in filenames, by Rajkumar Singh
    header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize(loc1 . $filename));
    readfile(loc1 . "$filename");
    exit();

  }


    // certain things should be displayed or thought through if popups are being shown
  if(!$dontdispheader){

      // this section is what breaks down console commands and puts the peices
      // in the correct spots.
    if(isset($_POST['cmd']) && $admin){
      if(magicQuotes)
        $cmd = stripslashes($_POST['cmd']);
      else
        $cmd = $_POST['cmd'];

      if(isset($_POST['prevcmd']))
        $prevcmd = $_POST['prevcmd'];
      else
        $prevcmd = array();

      if(magicQuotes)
        foreach($prevcmd as $i => $precmd)
          $prevcmd[$i] = stripslashes($precmd);

        // add the entered command to the list
      if(substr($cmd, 0, 6) == 'passwd')
        array_unshift($prevcmd, '> passwd ***');
      else
        array_unshift($prevcmd, '> ' . $cmd);
      if((strtolower($cmd) == 'y' || strtolower($cmd) == 'c' || strtolower($cmd) == 'n') && count($prevcmd) >= 3)
        $cmd = substr($prevcmd[2], 2);
      if(strpos($cmd, '"') === false)
        $cmdar = explode(' ', $cmd);
      else {
        $cmdar = array();
        $rest = $cmd;
        while(strlen($rest) > 0){
          if(substr($rest, 0, 1) == '"'){
            $rest = substr($rest, 1);
            $quo_pos2 = strpos($rest, '"');
            $rest2 = substr($rest, 0, $quo_pos2);
            array_push($cmdar, $rest2);
            $rest = substr($rest, $quo_pos2 + 1);
            $spc_pos1 = strpos($rest, ' ');
            $rest = substr($rest, $spc_pos1 + 1);
          } else {
            if(strpos($rest, ' ') !== false)
              $spc_pos2 = strpos($rest, ' ');
            else
              $spc_pos2 = strlen($rest);
            $rest2 = substr($rest, 0, $spc_pos2);
            array_push($cmdar, $rest2);
            $rest = substr($rest, $spc_pos2 + 1);
          }
        }
      }
    }

      // logout removes Session information on the user
    if(isset($_GET['logout']) || (isset($cmdar) && strtolower($cmdar[0]) == 'logout')){
      unset($_SESSION['username']);
      unset($_SESSION['password']);
      unset($_SESSION['IP']);
      unset($_SESSION['filepath']);
      if(isset($_COOKIE[session_name()]))
        setcookie(session_name(), '', time() - 36000, '/'); // attempt to remove the cookie
      session_destroy();
      if(!isset($_GET['loc']))
        $loc = './';
      else
        if(magicQuotes)
          $loc = stripslashes($_GET['loc']);
        else
          $loc = $_GET['loc'];
      echo '<script language="JavaScript">';
      // the genius JavaScript function name below originally coined by Bradley Hart!
      echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes($loc).'\',1)';
      echo '</script>';
      die('<a href="'.phpSelf.'?loc='.addslashes($loc).'">Click here to continute</a></body></html>');
    }

      // get info from file for all stats if it exists  
    $logFile = loc1 . '/filelist/filelist-last_update.list';
    if($show_all_stats && is_file($logFile)){
      $array_of_log_file = file($logFile);
      $number_of_dirs  = trim($array_of_log_file[1]);
      $number_of_files = trim($array_of_log_file[2]);
      $number_of_all   = $number_of_dirs + $number_of_files;
      $total_file_size = trim($array_of_log_file[3]);
      $last_update     = trim($array_of_log_file[0]);
    } else
      $number_of_all   = 10000;

      // max amount of time to wait before updating (with $noa ^ 2 / 5000, this will be about 5.6 hours)
    if($number_of_all > 10000)
      $number_of_all = 10000;

    /* A chart of times compared to number of files and directories:
      minutes | itmes
     (3) 0.05 |  122
     (6) 0.1  |  173
    (15) 0.25 |  274
    (30) 0.5  |  387
    (45) 0.75 |  474
          1   |  548
          2   |  774
          3   |  949
          4   | 1095
          5   | 1225
          7   | 1449
         10   | 1732
         15   | 2121
         20   | 2449
         30   | 3000
         45   | 3674
     (1) 60   | 4243
   (1.5) 90   | 5196
    (2) 120   | 6000
    (4) 240   | 8485
  (5.6) 333.3 |10000
    */

    $update_log_sec   = round($number_of_all * $number_of_all / 5000);          // how frequently to update number of files/filesize log
  }

    // if user can display sub directories
  if($current_user['subdir']){
      // $loc is the location (in filelist) to view files in $loc directory
    if(!isset($_GET['loc']) || $_GET['loc'] == '/' || strpos($_GET['loc'], '..') !== false || strpos(strtolower($_GET['loc']), 'filelist') !== false || strpos(strtolower($_GET['loc']), 'filemanage') !== false || substr(strtolower($_GET['loc']), 1, 6) == 'getid3')
      $loc = '/';
    else
      if(magicQuotes)
        $loc = stripslashes($_GET['loc']);
      else
        $loc = $_GET['loc'];

      // the next three tests make sure $loc is standardized to easier use
    if(substr($loc, 0, 1) == '.')
      $loc = substr($loc, 1);

    if(substr($loc, 0, 1) != '/')
      $loc = '/' . $loc;

    if(substr($loc, -1) != '/')
      $loc = $loc . '/';

  } else
    $loc = '/';

  if(!$admin && isset($hidden_items_ar)){
    if(in_array($loc, $hidden_items_ar))
      $loc = '/';
    else {
      $done = false;
      for($i = 0; $i < count($hidden_items_ar) && !$done; $i++)
        if(substr($loc, 0, strlen($hidden_items_ar[$i])) == $hidden_items_ar[$i]){
          $loc = '/';
          $done = true;
        }
    }
  }

    // set default of $parent_loc to the root directory
  $parent_loc  = phpSelf . '?loc=.';
  $parent_loc2 = '';
    // set $parent_loc to actual location parent directory
  $array_of_path = explode('/', substr($loc, 0, -1));
  for($i = 1; $i < count($array_of_path) - 1; $i++){
    $parent_loc  .= '/' . $array_of_path[$i];
    $parent_loc2 .= '/' . $array_of_path[$i];
  }
  $parent_loc2 .= '/';

  if(isset($cmdar)){
    if($cmdar[0] == 'cd'){
      if(count($cmdar) == 2){
        if(substr($cmdar[1], 0, 2) == '..')
          $loc = $parent_loc2;
        elseif(strpos(strtolower($cmdar[1]), 'filelist') === false && strpos(strtolower($cmdar[1]), 'getid3') === false){
          if($cmdar[1] != '.'){
            $add_loc = $cmdar[1];
            if(substr($add_loc, 0, 1) != '/')
              $add_loc = $loc . $add_loc;
            if(substr($add_loc, -1) != '/')
              $add_loc = $add_loc . '/';
            if(is_dir(loc1 . $add_loc))
              $loc = $add_loc;
            else
              array_unshift($prevcmd, 'Directory does not exist.');
          }
        }
      } else
        array_unshift($prevcmd, 'Insufficient arguments.');
    } else
    if($cmdar[0] == 'ls'){
      if(count($cmdar) == 1){
        echo '<script language="JavaScript">';
        // the genius JavaScript function name below originally coined by Bradley Hart!
        echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes($loc).'\',1)';
        echo '</script>';
      } else
      if(count($cmdar) == 2){
        $add_loc = $cmdar[1];
        if(substr($add_loc, 0, 1) != '/')
          $add_loc = $loc . $add_loc;
        if(is_dir(loc1 . $add_loc)){
          echo '<script language="JavaScript">';
          // the genius JavaScript function name below originally coined by Bradley Hart!
          echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes($add_loc).'\',1)';
          echo '</script>';
        } else
          array_unshift($prevcmd, 'Directory does not exist.');
      } else
        array_unshift($prevcmd, 'Insufficient arguments.');
    } else
    if($cmdar[0] == 'clear'){
      echo '<script language="JavaScript">';
      // the genius JavaScript function name below originally coined by Bradley Hart!
      echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes($loc).'&console=1\',1)';
      echo '</script>';
    } else
    if($cmdar[0] == 'exit'){
      echo '<script language="JavaScript">';
      // the genius JavaScript function name below originally coined by Bradley Hart!
      echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'\',1)';
      echo '</script>';
    }
  }

  if(is_dir(loc1 . $loc))
    define('loc', $loc, true);
  else
    define('loc', '/',  true);

  define('locenc', str_replace('&', '%26', loc), true);

    // get arangment type from the URL, if it doesn't exist, set to default
  if(isset($_GET['arange']))
    $arange = $_GET['arange'];
  else
    $arange = 'na';
  if($remember_org && $un != 'anonymous'){
    if(is_file(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-org.list')){
      $org_ar = file(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-org.list');
      $done = false;
      for($i = 0; $i < count($org_ar) && !$done; $i++){
        $sub_org_ar = explode('~~~~~', trim($org_ar[$i]));
        if($sub_org_ar[0] == loc){
          if(!isset($_GET['arange']))
            $arange = $sub_org_ar[1];
          elseif($_GET['arange'] == 'na')
            unset($org_ar[$i]);
          else
            $org_ar[$i] = loc.'~~~~~'.$_GET['arange'].$line_break;
          $done = true;
        }
      }
      if(isset($_GET['arange']) && !$done && $_GET['arange'] != 'na')
        $org_ar[] = loc.'~~~~~'.$_GET['arange'].$line_break;
    } elseif($arange != 'na')
      $org_ar[] = loc.'~~~~~'.$arange.$line_break;
    if(isset($_GET['arange'])){
      if(isset($org_ar) && count($org_ar) > 0){
        $fout = fopen(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-org.list', 'w');
        $fp = fwrite($fout, implode('', $org_ar));
        fclose($fout);
      } else
        @unlink(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-org.list');
    }
  }

    // split $arange into its two components
  $ar1 = substr($arange, 0, 1);
  if($ar1 != 'n' && $ar1 != 't' && $ar1 != 's')
    $ar1 = 'n';
  $ar2 = substr($arange, 1, 1);
  if($ar2 != 'a' && $ar2 != 'd')
    $ar2 = 'a';

    // if auto icon is enabled, this is not a popup, and the file does not exist or
    // has an older time than the update of this file, (re)create the icon list file
  if($auto_icon && (!$dontdispheader || ($admin && isset($_GET['re-auto_icon'])))){
    $autoicon_ud = false;
    if(is_file(loc1 . '/filelist/filelist-autoicon.list')){
      $autoicon_file = file(loc1 . '/filelist/filelist-autoicon.list');
      if(trim($autoicon_file[0]) <= getlastmod() || ($admin && isset($_GET['re-auto_icon'])))
        $autoicon_ud = true;
      else
        for($i = 1; $i < count($autoicon_file); $i++)
          $iconlink[$i - 1] = trim($autoicon_file[$i]);
    } else
      $autoicon_ud = true;

      // This section makes a new icon list if $autoicon_ud is true
      // It puts the '' at the end fo the array, then searches through and
      // matches up a predefined set of extensions with a set of icons
    if($autoicon_ud){
      if(in_array('',$accept)){
        if($accept[count($accept) - 1] != ''){
          $blkloc = array_search('', $accept);
          for($i = $blkloc; $i < count($accept); $i++)
            $accept[$i] = $accept[$i + 1];
          array_push($accept, '');
        }
      }

      $lst1 = array(
      '.zip','.tar.gz','.tgz','.gz','.7z','.7zip','.rar','.z','.exe','.msi',
      '.html','.htm','.shtml','.xhtml','.xml','.php','.php3','.php4','.php5',
      '.phtml','.asp','.xls','.jpg','.jpeg','.gif','.tiff','.tif','.png','.bmp',
      '.swf','.swc','.avi','.asf','.mpg','.mpeg','.wmv','.mov','.mp4','.divx',
      '.dvx','.xvid','.rm','.ram','.ogm','.mpa','.mp3','.wma','.m4a','.ogg',
      '.mp2','.flac','.vqf','.ape','.au','.aac','.aiff','.wav','.psd','.pmd',
      '.pmt','.indd','.doc','.txt','.nfo','.list','.cgi','.tmpl','.diz','.bin',
      '.dvi','.iso','.pdf','.js','.css','.vbs','.tar','.tex','core','.sql',
      '.conf','.sh','.nsi','.shar','.csh','.ksh','.tcl','.uu','.for','.pl',
      '.py','.c','.cpp','.h','.hpp','.ai','.hqx','readme','.ini','.inf','.reg',
      '.java','.asm','.ppt',''
      );

      $lst2 = array(
      'icons/compressed.gif','icons/compressed.gif','icons/compressed.gif',
      'icons/compressed.gif','icons/compressed.gif','icons/compressed.gif',
      'icons/compressed.gif','icons/compressed.gif','icons/burst.gif',
      'icons/comp.gray.gif','icons/layout.gif','icons/layout.gif',
      'icons/layout.gif','icons/layout.gif','icons/layout.gif',
      'icons/layout.gif','icons/layout.gif','icons/layout.gif',
      'icons/layout.gif','icons/layout.gif','icons/layout.gif',
      'icons/layout.gif','icons/image2.gif','icons/image2.gif',
      'icons/image2.gif','icons/image2.gif','icons/image2.gif',
      'icons/image2.gif','icons/image2.gif','icons/image3.gif',
      'icons/image3.gif','icons/movie.gif','icons/movie.gif',
      'icons/movie.gif','icons/movie.gif','icons/movie.gif',
      'icons/movie.gif','icons/movie.gif','icons/movie.gif',
      'icons/movie.gif','icons/movie.gif','icons/movie.gif',
      'icons/movie.gif','icons/movie.gif','icons/sound2.gif',
      'icons/sound2.gif','icons/sound2.gif','icons/sound2.gif',
      'icons/sound2.gif','icons/sound2.gif','icons/sound1.gif',
      'icons/sound1.gif','icons/sound1.gif','icons/sound1.gif',
      'icons/sound1.gif','icons/sound1.gif','icons/sound1.gif',
      'icons/image1.gif','icons/image1.gif','icons/image1.gif',
      'icons/image1.gif','icons/text.gif','icons/text.gif','icons/text.gif',
      'icons/text.gif','icons/text.gif','icons/text.gif','icons/text.gif',
      'icons/binary.gif','icons/dvi.gif','icons/diskimg.gif',
      'icons/pdf.gif','icons/script.gif','icons/script.gif',
      'icons/script.gif','icons/tar.gif','icons/tex.gif','icons/bomb.gif',
      'icons/script.gif','icons/script.gif','icons/script.gif',
      'icons/script.gif','icons/script.gif','icons/script.gif',
      'icons/script.gif','icons/script.gif','icons/uuencoded.gif',
      'icons/f.gif','icons/p.gif','icons/p.gif','icons/c.gif',
      'icons/c.gif','icons/c.gif','icons/c.gif',
      'icons/a.gif','icons/binhex.gif','icons/hand.right.gif',
      'icons/screw2.gif','icons/screw2.gif','icons/screw2.gif',
      'icons/quill.gif','icons/script.gif','icons/p.gif',
      'icons/unknown.gif'
      );

      foreach($accept as $i => $val){
        if(false !== ($aryky = array_search($val, $lst1)))
          $iconlink[$i] = $lst2[$aryky];
        else
          $iconlink[$i] = 'icons/unknown.gif';
      }

      $write = implode($line_break, $iconlink);
      $fout = fopen(loc1 . '/filelist/filelist-autoicon.list', 'w');
      $fp = fwrite($fout, time() . $line_break . $write . $line_break);
      fclose($fout);

    }
  }

    // if additional information can be displayed about the files, test for getid3
  if(is_file('getid3/getid3/getid3.php') && include_once('getid3/getid3/getid3.php')){
    if($add_getid3 && $show_add_info)
      $getid3_true = 1;
    else
      $getid3_true = 0;
    $getid3_true2 = 1;
  } else {
    $getid3_true = 0;
    $getid3_true2 = 0;
  }

    // get directory names aranged into $sup_dirs to display in title and the top of the page
  $dir_left = '.' . substr(loc, 0, -1);
  $sup_dirs[0] = $dir_left;
  while(substr($dir_left, 1) != ''){
    $array_of_path = explode('/', $dir_left);
    $lnk_num = count($sup_dirs);
    $sup_dirs[$lnk_num] = '.';
    for($i = 1; $i < count($array_of_path) - 1; $i++)
      $sup_dirs[$lnk_num] .= '/' . $array_of_path[$i];
    $dir_left = $sup_dirs[$lnk_num];
  }

    // search stuff
  if(isset($_GET['search_value']) && $_GET['search_value'] != '' && $_GET['search_value'] != 'Search'){
    if(magicQuotes)
      $search_value = stripslashes($_GET['search_value']);
    else
      $search_value = $_GET['search_value'];
    $count = 0;
    // not \ / ; * ? < > | #
    // characters 32-126 !35 !42 !47 !59 !60 !62 !63 !92 !124
    for($i = 32; $i <= 126; $i++)
      if($i != 35 && $i != 42 && $i != 47 && $i != 59 && $i != 60
      && $i != 62 && $i != 63 && $i != 92 && $i != 124){
        $chr_array[$count] = chr($i);
        $count++;
      }

      // make sure search does not have invalid characters
    for($i = 0; $i < strlen($search_value); $i++){
      $char = substr($search_value, $i, 1);
      $chr_done = false;
      for($j = 0; $j < count($chr_array) && !$chr_done; $j++)
        if($chr_array[$j] == $char)
          $chr_done = true;
      if(!$chr_done){
        echo '<font color="red">Search contains invalid character, "'. $char .'"</font><br>';
        $search_value = 'Search';
      }
    }
  } else
    $search_value = 'Search';
  if(isset($_GET['showsearch']) && $_GET['showsearch'] != '')
    $showsearch   = $_GET['showsearch'];
  else
    $showsearch = 0;
  if(isset($_GET['exactmatch']) && $_GET['exactmatch'] != '')
    $exactmatch   = $_GET['exactmatch'];
  else
    $exactmatch = 0;

  $adlnk = '';
  $adlnk2 = '';
  if($search_value != 'Search' && $search_value != ''){
    $adlnk2 .= '&search_value=' . $search_value;
    if(isset($showsearch))
      $adlnk2 .= '&showsearch=' . $showsearch;
    if(isset($exactmatch))
      $adlnk2 .= '&exactmatch=' . $exactmatch;
  } else
  if(isset($_GET['cpy'])){
    if(magicQuotes)
      $cpy = str_replace('&', '%26', stripslashes($_GET['cpy']));
    else
      $cpy = str_replace('&', '%26', $_GET['cpy']);
    $adlnk = '&cpy=' . $cpy;
  } else
  if(isset($_GET['cut'])){
    if(magicQuotes)
      $cut = str_replace('&', '%26', stripslashes($_GET['cut']));
    else
      $cut = str_replace('&', '%26', $_GET['cut']);
    $adlnk = '&cut=' . $cut;
  }
  if(isset($_GET['dcpy'])){
    if(magicQuotes)
      $dcpy = str_replace('&', '%26', stripslashes($_GET['dcpy']));
    else
      $dcpy = str_replace('&', '%26', $_GET['dcpy']);
    $adlnk = '&dcpy=' . $dcpy;
  } else
  if(isset($_GET['dcut'])){
    if(magicQuotes)
      $dcut = str_replace('&', '%26', stripslashes($_GET['dcut']));
    else
      $dcut = str_replace('&', '%26', $_GET['dcut']);
    $adlnk = '&dcut=' . $dcut;
  }

    // start the HTML
  echo '<html><head>';
  if(!isset($_GET['editpv'])){
    echo '<STYLE type=text/css><!--';
    echo 'A:link{color:#990000}';
    echo 'A:visited{color:#990000}';
    echo 'A:active{color:#F0F0F0}';
    echo 'A:hover{color:#E0E0E0;text-decoration:none}';
    echo '--></STYLE>';
  }
  echo '<title>List in root';

    // display the path of where file manage is currently pointing
  $array_of_path = explode('/', substr(loc, 0, -1));
  for($i = 1, $j = count($sup_dirs) - 2; $i < count($array_of_path); $i++, $j--)
    echo ' < ' . $array_of_path[$i];

  echo '</title>';

    // in edit preview mode colors need to be different
  if(!isset($_GET['editpv']) || !$current_user['append']){
    $bgcolor = '#FFFFFF';
    $text    = '#000000';
    $vlink   = '#000000';
    $alink   = '#000000';
    $link    = '#000000';
  } else {
    $bgcolor = '#FFFFFF';
    $text    = '#000000';
    $vlink   = '#000000';
    $alink   = '#000000';
    $link    = '#000000';
  }
  if(!isset($_GET['viewperms']))
    echo '</head><body name="howdy" bgcolor="'.$bgcolor.'" text="'.$text.'" vlink="'.$vlink.'" alink="'.$alink.'" link="'.$link.'">';
  else
    echo '</head><body bgcolor="'.$bgcolor.'" text="'.$text.'" vlink="'.$vlink.'" alink="'.$alink.'" link="'.$link.'">';
    // if popup, don't display this stuff
  if(!$dontdispheader){

    echo '<table width="100%" cellpadding="2" cellspacing="0" border="0"><tr><td>';
    echo '<font size="+2"><b>List in ';
    echo '<a title="Goto ./" href="'.phpSelf.'?loc=./'.$adlnk.'">root</a>';
      // display the path of where file manage is currently pointing
    for($i = 1, $j = count($sup_dirs) - 2; $i < count($array_of_path); $i++, $j--)
      echo ' &lt; <a title="Goto '.$sup_dirs[$j].'" href="'.phpSelf.'?loc='.str_replace('&', '%26', $sup_dirs[$j]).$adlnk.'">'.$array_of_path[$i].'</a>';

    echo '</b></font>';
    echo '</td><td align="right" width="300">';

      // build toolbar with apropriate abilities
    if($require_login){
      echo '<table cellpadding="3" cellspacing="0" border="1" bgcolor="FFFFFF" width="100%"><tr><td>';

      echo '<table cellpadding="2" cellspacing="0" border="1" align="center" width="100%"><tr><td align="center" colspan="5">';
      if($anonymous_user)
        echo 'Anonymous Toolbox';
      else
      if($admin)
        echo 'Admin Toolbox';
      else
      if($perm < 2 && $permtype != 'hex')
        echo 'Uber User Toolbox';
      else
      if($perm < 4 && $permtype != 'hex')
        echo 'Privileged User Toolbox';
      else
      if($perm < 6 || $permtype == 'hex')
        echo 'User Toolbox';
      else
      if($perm < 10 && $permtype != 'hex')
        echo 'Restricted User Toolbox';
      else
        echo 'Hacker toolbox'; // just in case some psycho does some weird thing

      echo '<hr></td></tr>';

      if($admin){
        if(is_file(loc1.'/filelist/filelistloginscount.list')){
          $num_of_users_pending = count(file(loc1.'/filelist/filelistloginscount.list'));
          if($num_of_users_pending > 1)
            $str = 's ('.$num_of_users_pending.')';
          elseif($num_of_users_pending > 0)
            $str = ' ('.$num_of_users_pending.')';
          else
            $str = NULL;
        } else
          $str = NULL;

        if(is_file(loc1 . '/filelist/filelist-recycle_db.list'))
          $recycle_files = count(file(loc1 . '/filelist/filelist-recycle_db.list'));

        echo '<tr><td width="32%" align="center"><font size="-1">';
        echo '<a title="A UI for changing system settings" href="'.phpSelf.'?loc='.locenc.'&settings=1">Settings</a><br>'; // a nice Ui to change system settings
        echo '<a title="Open command line console" href="'.phpSelf.'?loc='.locenc.'&console=1">Open Console</a><br>'; // allows an admin to use a commandline interface
        echo '<a title="Check logged events" href="'.phpSelf.'?loc='.locenc.'&log=1">Check Log</a>'; // logs of what has been happening
        echo '</font></td><td width="1" bgcolor="#000000"></td><td width="32%" align="center"><font size="-1">';
        echo '<a title="View and remove hidden files" href="'.phpSelf.'?loc='.locenc.'&hide=1">';
        if(isset($hidden_items_ar) && count($hidden_items_ar) > 0)
          echo '('.count($hidden_items_ar).')';
        echo 'Manage<br>Hidden Files</a><br>'; // manage/view files that are hidden
        echo '<a title="Manage your recycle bin" href="'.phpSelf.'?loc='.locenc.'&recycle=1">';
        if(isset($recycle_files) && $recycle_files > 0)
          echo '('.$recycle_files.')';
        echo 'Recycle Bin</a>'; // manage/view deleted files (in recycle bin)
        echo '</font></td><td width="1" bgcolor="#000000"></td><td width="36%" align="center"><font size="-1">';
        echo '<a title="Create a new user" href="'.phpSelf.'?loc='.locenc.'&manage=1&createuser=1">New User</a><br>';
        echo '<a title="View and manage user\'s information" href="'.phpSelf.'?loc='.locenc.'&manage=1">Manage Users</a><br>'; // manage any existing users (delete, adjust permissions, etc.)
        echo '<a title="Accept users who have requested a login" href="'.phpSelf.'?loc='.locenc.'&manage=1">Accept User'.$str.'</a>'; // accept a user that has requested an account

        echo '</font></td></tr><tr><td align="center" colspan="5"><hr>';
        echo '</td></tr>';
      }

      echo '<tr><td align="center"><font size="-1">';

        if(($current_user['delete'] && $current_user['write']) && !$admin && is_file(loc1 . '/filelist/filelist-recycle_db.list'))
          $recycle_files = count(file(loc1 . '/filelist/filelist-recycle_db.list'));

      if(!$current_user['write'] || $adlnk == ''){
        if($current_user['write'] && ini_get('file_uploads') && substr(ini_get('upload_max_filesize'), 0, -1) > 0)
          echo '<a title="Upload a file from your computer" href="'.phpSelf.'?loc='.locenc.'&upld=1">Upload File</a><br>';
        if($current_user['write'])
          echo '<a title="Start a text-based file" href="'.phpSelf.'?loc='.locenc.'&cfile=1">Create File</a><br>';
      } else {
        if((!isset($_GET['dcut']) && !isset($_GET['dcpy'])) || ((isset($_GET['dcut']) && substr(loc.'/', 0, strlen($_GET['dcut'].'/')) != $_GET['dcut'].'/') || (isset($_GET['dcpy']) && substr(loc.'/', 0, strlen($_GET['dcpy'].'/')) != $_GET['dcpy'].'/')))
          echo '<a title="Paste a cut or copied file" href="'.phpSelf.'?loc='.locenc.$adlnk.'&paste=1">Paste</a><br>';
        if($adlnk != '')
          echo '<a title="Clear cut/copy to see upload/create file again" href="'.phpSelf.'?loc='.locenc.'">Clear Copy/Cut</a>';
      }
      if($anonymous_user)
        echo '<a title="Login or create user to recieve your permissions" href="'.phpSelf.'?loc='.locenc.'&req_login=1">Login</a><br>';
      if($anonymous_user)
        echo '<a title="Create user to recieve your permissions" href="'.phpSelf.'?loc='.locenc.'&create=1">Create User</a>';
      echo '</font></td><td width="1" bgcolor="#000000"></td><td align="center"><font size="-1">';
      if($current_user['make'])
        echo '<a title="Create a new directory" href="'.phpSelf.'?loc='.locenc.'&crdir=1">New Directory</a><br>';
      if(($current_user['delete'] && $current_user['write']) && !$admin){
        echo '<a title="Manage recycle bin" href="'.phpSelf.'?loc='.locenc.'&recycle=1">Recycle Bin';
        if(isset($recycle_files) && $recycle_files > 0)
          echo '('.$recycle_files.')';
        echo '</a><br>';
      }
      echo '</font></td><td width="1" bgcolor="#000000"></td><td align="center"><font size="-1">';
      if(!$anonymous_user)
        echo '<a title="View your profile and settings" href="'.phpSelf.'?loc='.locenc.'&mysettings=1">My Settings</a><br>';
      if(!$anonymous_user || !$auto_anonym_login)
        echo '<a title="Logout of the File Manage system" href="'.phpSelf.'?loc='.locenc.'&logout=1">Logout</a><br>';

      echo '</font></td></tr></table></td></tr></table>';
    }
    echo '</td></tr></table><br>';

  }


    // displays properties of a file
  if(isset($_GET['prop']) && $current_user['read'] && $_GET['prop'] != '')
    if(magicQuotes)
      prop(stripslashes($_GET['prop']));
    else
      prop($_GET['prop']);
  else

  // if the associated variable is found in the URL and the user has permissions to do such thing then continue

    // view and edit user's settings/profile
  if(isset($_GET['mysettings']) && !$anonymous_user){

    if(!isset($_GET['editprofile'])){
      echo 'Username: ' . $un . '<br>';
      echo 'Email '.note(6, 160, 150).': <a href="mailto:' . $useremail . '">' . $useremail . '</a><br>';
      echo 'Permissions level '.note(7, 200, 220).': '.$perm.' <a href="'.phpSelf.'?loc='.locenc.'&perms=1\">View permissions</a><br>';
      echo 'Permissions type '.note(8, 200, 200).': '.$permtype .'<br>';
      if(isset($not_authorized))
        echo '<font color="red">You have not been officially accepted, you only have the same permissions as anonymous users.</font><br>';
      if($admin){
        echo note(21, 200, 300) . ' ';
        if(is_file(loc1 . '/filelist/filelist-passcode.php'))
          echo 'Censor passcode is set.<br>';
        else
          echo 'Censor passcode is not set.<br>';
      }
      echo '<br><a href="'.phpSelf.'?loc='.locenc.'&mysettings=1&editprofile=1">Edit my profile</a>';

      if(isset($_POST['defaults'])){
        @unlink(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php');
        include(loc1 . '/filelist/filelist-settings.php');
      }

      if(isset($_POST['setsettings'])){

        $settings_ar[] = '<?PHP';
        $settings_ar[] = NULL;

        if($force_server_sets <= 0 || $force_server_sets == 1){
          if(!isset($_POST['defdisplay_new']))
            $settings_ar[] = '$display_new = '.$_POST['setdisplay_new'].';';
          if(!isset($_POST['defdisplay_updated']))
            $settings_ar[] = '$display_updated = '.$_POST['setdisplay_updated'].';';
          if(!isset($_POST['deforganize_ord']))
            $settings_ar[] = '$organize_ord = '.$_POST['setorganize_ord'].';';
          if(!isset($_POST['deffont_size']))
            $settings_ar[] = '$font_size = \''.$_POST['setfont_size'].'\';';
          if(!isset($_POST['defname_length']) && (int)$_POST['setname_length'] > 8)
            $settings_ar[] = '$name_length = '.(int)$_POST['setname_length'].';';
          if(!isset($_POST['deftrunc_offset']) && (int)$_POST['settrunc_offset'] > 0 && (((int)$_POST['settrunc_offset'] < (int)$_POST['setname_length'] && !isset($_POST['defname_length']) && (int)$_POST['setname_length'] > 8) || ((int)$_POST['settrunc_offset'] < $name_length && isset($_POST['defname_length']) && $name_length)))
            $settings_ar[] = '$trunc_offset = '.(int)$_POST['settrunc_offset'].';';
          if(!isset($_POST['defaltern_line_color']))
            $settings_ar[] = '$altern_line_color = '.$_POST['setaltern_line_color'].';';
          if(!isset($_POST['defaltern_color'])){
              // only alpha-numerics and the "#" symbol
            for($i = 48; $i <= 122; $i++)
              if($i != 58 && $i != 59 && $i != 60 && $i != 61 && $i != 62 && $i != 63 && $i != 64
              && $i != 91 && $i != 92 && $i != 93 && $i != 94 && $i != 95 && $i != 96)
                $char_array[] = chr($i);
            $char_array[] = chr(35);
            $write = true;
            for($j = 0; $j < strlen($_POST['setaltern_color']) && $write; $j++){
              $done = false;
              for($i = 0; $i < count($char_array) && !$done; $i++){
                if(substr($_POST['setaltern_color'], $j, 1) == $char_array[$i])
                  $done = true;
              }
              if(!$done)
                $write = false;
            }
            if($write)
              $settings_ar[] = '$altern_color = \''.$_POST['setaltern_color'].'\';';
          }
        }
        if($force_server_sets <= 0 || $force_server_sets == 2){
          if(!isset($_POST['defshow_all_stats']))
            $settings_ar[] = '$show_all_stats = '.$_POST['setshow_all_stats'].';';
          if(!isset($_POST['defshow_add_info']))
            $settings_ar[] = '$show_add_info = '.$_POST['setshow_add_info'].';';
          if(!isset($_POST['defadd_getid3']))
            $settings_ar[] = '$add_getid3 = '.$_POST['setadd_getid3'].';';
          if(!isset($_POST['defshow_file_time']))
            $settings_ar[] = '$show_file_time = '.$_POST['setshow_file_time'].';';
          if(!isset($_POST['deffile_time']))
            $settings_ar[] = '$file_time = \''.$_POST['setfile_time'].'\';';
          if(!isset($_POST['deffile_time_date'])){
            if(magicQuotes)
              $settings_ar[] = '$file_time_date = \''.str_replace('\'', '\\\'', stripslashes($_POST['setfile_time_date'])).'\';';
            else
              $settings_ar[] = '$file_time_date = \''.str_replace('\'', '\\\'', $_POST['setfile_time_date']).'\';';
          }
          if(!isset($_POST['defremember_org']))
            $settings_ar[] = '$remember_org = '.$_POST['setremember_org'].';';
          if(!isset($_POST['defshow_exif_thumb']))
            $settings_ar[] = '$show_exif_thumb = '.$_POST['setshow_exif_thumb'].';';
        }

        if($admin && !isset($_POST['defadmin_see_hidden']))
          $settings_ar[] = '$admin_see_hidden = '.$_POST['setadmin_see_hidden'].';';

        $settings_ar[] = NULL;
        $settings_ar[] = '?>';
        $settings_ar[] = NULL;
        if(count($settings_ar) > 5){
/*
Cosmetic:
display_new; bool             //
display_updated; bool         //
organize_ord; bool            //
altern_line_color; bool       //
altern_color; bool            //
font_size; int                //
name_length; int              //
trunc_offset; int             //

Non-Cosmetic:
show_all_stats; bool          //
show_add_info; bool           //
add_getid3; bool              //
show_file_time; bool          //
file_time; m OR c             //
file_time_date; date() format //
remember_org; bool            //
show_exif_thumb; bool         //

Other:
admin_see_hidden; bool        //
*/

          $fout = fopen(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php', 'w');
          $fp = fwrite($fout, implode("\n", $settings_ar));
          fclose($fout);
          writelog('User updated their settings.', 'mysettings');

          include(loc1 . '/filelist/filelist-settings.php');
          include(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php');

        } else {
          @unlink(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php');
          include(loc1 . '/filelist/filelist-settings.php');
        }

      }
      $notdefault = array();
      if(is_file(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php')){
        $settings_ar = file(loc1 . '/filelist/filelist-userdb/filelist-'.$un.'-sets.php');// echo '<pre>'.print_r($_POST).'</pre>';  echo '<pre>'.print_r($settings_ar).'</pre>';
        for($i = 2; $i < count($settings_ar) - 2; $i++)
          $notdefault[substr($settings_ar[$i], 1, strpos($settings_ar[$i], ' ') - 1)] = true;
      }

      if($force_server_sets <= 2 || $admin){
        echo '<br><br><br><h3>Visual Settings for File Manage:</h2>';
        echo '<form method="post" name="settings" action="'.phpSelf.'?loc='.locenc.'&mysettings=1">';
        echo '<table cellpadding="3" cellspacing="0" border="1"><tr>';
        echo '<td><u><b>Setting</b></u></td>';
        echo '<td><u><b>Current value</b></u></td>';
        echo '<td><u><b>Default</b></u></td>';
        echo '<td><u><b>New value</b></u></td>';
        echo '<td><u><b>Possible values</b></u></td>';
        echo '<td><u><b>Description</b></u></td>';
        echo '</tr>';

        if($force_server_sets <= 0 || $force_server_sets == 1){
          echo '<tr><td colspan="5"></td></tr>';
          if($display_new) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Display New Flag:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defdisplay_new"';
          if(!isset($notdefault['display_new']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defdisplay_new.checked=false" type="radio" name="setdisplay_new" value="true"'; if($display_new) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defdisplay_new.checked=false" type="radio" name="setdisplay_new" value="false"'; if(!$display_new) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">This displays a coloumn next to the files and directories which states if the item is new.</font></td></tr>';

          if($display_updated) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Display Updated Flag:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defdisplay_updated"';
          if(!isset($notdefault['display_updated']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defdisplay_updated.checked=false" type="radio" name="setdisplay_updated" value="true"'; if($display_updated) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defdisplay_updated.checked=false" type="radio" name="setdisplay_updated" value="false"'; if(!$display_updated) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">This displays a column next to the files and directories to tell users if an item has been updated.</font></td></tr>';

            // JS function loosly based on a function in PHP Total Content Manament System (http://sourceforge.net/projects/phpttotalcms/)
          echo '<script type="text/javascript">
  function func_font_size(name){

    var char_ar = new Array(';
            // only numerics and "-" and "+" symbols
          for($i = 48; $i <= 56; $i++)
            echo '"'.addslashes(chr($i)).'",';
          echo '"'.addslashes(chr(43)).'",';
          echo '"'.addslashes(chr(45)).'",';
          echo '"'.addslashes(chr(57)).'"';

          echo ');
    for(var i = 0; i < name.value.length; i++){
      var done = false;
      for(var j = 0; j < char_ar.length && !done; j++){
        if(name.value.substr(i, 1) == char_ar[j]){
          done = true;
        } // if(char == ar)
      } // for(j)
      if(!done){
        document.getElementById(\'errordisplay4\').style.color = \'red\';
        document.getElementById(\'errordisplay4\').firstChild.nodeValue = \'Invalid character used: "\' + name.value.substr(i, 1) + \'".\';
        name.value = name.value.substr(0, i) + name.value.substr(i + 1);
        if((typeof name.selectionStart) != \'undefined\'){
          name.selectionStart = i;
          name.selectionEnd = i;
        }
        i--;
      }
    } // for(i)
    if(parseInt(document.settings.setfont_size.value) > 4){
      document.settings.setfont_size.value = "+4";
    }
    if(parseInt(document.settings.setfont_size.value) < -3){
      document.settings.setfont_size.value = "-3";
    }
  } // end of check_name()
</script>';

          echo '<tr><td>Long column text size:</td><td align="center">' . $font_size . '</td><td align="center"><input type="checkbox" name="deffont_size"';
          if(!isset($notdefault['font_size']))
            echo ' checked';
          echo '></td><td align="center"><font color="black" ID="errordisplay4">.</font><br><input onChange="document.settings.deffont_size.checked=false" name="setfont_size" type="text" onKeyUp="func_font_size(this)" value="'.$font_size.'" size="2" maxlength="2"></td><td><i>INT < 4 & > -3</i></td>';
          echo '<td><font size="-1">Change the font size of the Updated/New Time Column, Additional Info column, and the Actions Column (0 is standard size, please use a + or - when entering a font size).</font></td></tr>';

            // JS function loosly based on a function in PHP Total Content Manament System (http://sourceforge.net/projects/phpttotalcms/)
          echo '<script type="text/javascript">
  function func_name_length(name){

    var char_ar = new Array(';
            // only numerics
          for($i = 48; $i <= 56; $i++)
            echo '"'.addslashes(chr($i)).'",';
          echo '"'.addslashes(chr(57)).'"';

          echo ');
    for(var i = 0; i < name.value.length; i++){
      var done = false;
      for(var j = 0; j < char_ar.length && !done; j++){
        if(name.value.substr(i, 1) == char_ar[j]){
          done = true;
        } // if(char == ar)
      } // for(j)
      if(!done){
        document.getElementById(\'errordisplay1\').style.color = \'red\';
        document.getElementById(\'errordisplay1\').firstChild.nodeValue = \'Invalid character used: "\' + name.value.substr(i, 1) + \'".\';
        name.value = name.value.substr(0, i) + name.value.substr(i + 1);
        if((typeof name.selectionStart) != \'undefined\'){
          name.selectionStart = i;
          name.selectionEnd = i;
        }
        i--;
      }
    } // for(i)
    if(parseInt(document.settings.setname_length.value) < 8){
      document.settings.setname_length.value = 8;
    }
  } // end of check_name()
</script>';

          echo '<tr><td>Max File and Directory Name Length:</td><td align="center">' . $name_length . '</td><td align="center"><input type="checkbox" name="defname_length"';
          if(!isset($notdefault['name_length']))
            echo ' checked';
          echo '></td><td align="center"><font color="black" ID="errordisplay1">.</font><br><input onChange="document.settings.defname_length.checked=false" name="setname_length" type="text" onKeyUp="func_name_length(this)" value="'.$name_length.'" size="3" maxlength="3"></td><td><i>INT >= 8</i></td>';
          echo '<td><font size="-1">Sets the maximum number of characters of a file or directory to be displayed, if longer, the displayed name will be truncated with "...".</font></td></tr>';

            // JS function loosly based on a function in PHP Total Content Manament System (http://sourceforge.net/projects/phpttotalcms/)
          echo '<script type="text/javascript">
  function func_trunc_offset(name){

    var char_ar = new Array(';
            // only numerics
          for($i = 48; $i <= 56; $i++)
            echo '"'.addslashes(chr($i)).'",';
          echo '"'.addslashes(chr(57)).'"';

          echo ');
    for(var i = 0; i < name.value.length; i++){
      var done = false;
      for(var j = 0; j < char_ar.length && !done; j++){
        if(name.value.substr(i, 1) == char_ar[j]){
          done = true;
        } // if(char == ar)
      } // for(j)
      if(!done){
        document.getElementById(\'errordisplay2\').style.color = \'red\';
        document.getElementById(\'errordisplay2\').firstChild.nodeValue = \'Invalid character used: "\' + name.value.substr(i, 1) + \'".\';
        name.value = name.value.substr(0, i) + name.value.substr(i + 1);
        if((typeof name.selectionStart) != \'undefined\'){
          name.selectionStart = i;
          name.selectionEnd = i;
        }
        i--;
      }
    } // for(i)
    if(parseInt(document.settings.settrunc_offset.value) > parseInt(document.settings.setname_length.value)){
      document.settings.settrunc_offset.value = document.settings.setname_length.value;
    }
  } // end of check_name()
</script>';

          echo '<tr><td>File/Dir Name Truncation Location:</td><td align="center">' . $trunc_offset . '</td><td align="center"><input type="checkbox" name="deftrunc_offset"';
          if(!isset($notdefault['trunc_offset']))
            echo ' checked';
          echo '></td><td align="center"><font color="black" ID="errordisplay2">.</font><br><input onChange="document.settings.deftrunc_offset.checked=false" name="settrunc_offset" type="text" onKeyUp="func_trunc_offset(this)" value="'.$trunc_offset.'" size="3" maxlength="3"></td><td><i>INT < name_length & >= 0</i></td>';
          echo '<td><font size="-1">This value determines how many character to display <i>after</i> the truncation (0 will place the "..." at the end of the file/directory name).</font></td></tr>';


          echo '<script type="text/javascript">
  function func_altern_line_color(value){
    document.settings.setaltern_color.disabled = value;
  }
</script>';

          if($altern_line_color) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Alternate Line Color:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defaltern_line_color"';
          if(!isset($notdefault['altern_line_color']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defaltern_line_color.checked=false" type="radio" onClick="func_altern_line_color(false)" name="setaltern_line_color" value="true"'; if($altern_line_color) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defaltern_line_color.checked=false" type="radio" onClick="func_altern_line_color(true)" name="setaltern_line_color" value="false"'; if(!$altern_line_color) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">This option will make every other row in the file list a different color. This helps visual organization, especially on high resolution monitors.</font></td></tr>';

            // JS function loosly based on a function in PHP Total Content Manament System (http://sourceforge.net/projects/phpttotalcms/)
          echo '<script type="text/javascript">
  function func_altern_color(name){

    var char_ar = new Array(';
            // only alpha-numerics and the "#" symbol
          for($i = 48; $i <= 122; $i++)
            if($i != 58 && $i != 59 && $i != 60 && $i != 61 && $i != 62 && $i != 63 && $i != 64
            && $i != 91 && $i != 92 && $i != 93 && $i != 94 && $i != 95 && $i != 96)
              echo '"'.addslashes(chr($i)).'",';
          echo '"'.addslashes(chr(35)).'"';

          echo ');
    for(var i = 0; i < name.value.length; i++){
      var done = false;
      for(var j = 0; j < char_ar.length && !done; j++){
        if(name.value.substr(i, 1) == char_ar[j]){
          done = true;
        } // if(char == ar)
      } // for(j)
      if(!done){
        document.getElementById(\'errordisplay3\').style.color = \'red\';
        document.getElementById(\'errordisplay3\').firstChild.nodeValue = \'Invalid character used: "\' + name.value.substr(i, 1) + \'".\';
        name.value = name.value.substr(0, i) + name.value.substr(i + 1);
        if((typeof name.selectionStart) != \'undefined\'){
          name.selectionStart = i;
          name.selectionEnd = i;
        }
        i--;
      }
    } // for(i)
  } // end of check_name()
</script>';

          echo '<tr><td>Alternate Line Color:</td><td align="center" bgcolor="'.$altern_color.'">' . htmlspecialchars($altern_color) . '</td><td align="center"><input type="checkbox" name="defaltern_color"';
          if(!isset($notdefault['altern_color']))
            echo ' checked';
          echo '></td><td align="center"><font color="black" ID="errordisplay3">.</font><br><input onChange="document.settings.defaltern_color.checked=false" name="setaltern_color" type="text" onKeyUp="func_altern_color(this)" value="'.htmlspecialchars($altern_color).'" size="7" maxlength="64"'; if(!$altern_line_color) echo ' disabled'; echo ' /></td><td><i>valid HTML color</i></td>';
          echo '<td><font size="-1">This is the color that the "other" row (enabled above) will be. It is best to keep it to a low contrast, but enough to be visible on all monitors.</font></td></tr>';

          if($organize_ord) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Organize without "the" and "a":</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="deforganize_ord"';
          if(!isset($notdefault['organize_ord']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.deforganize_ord.checked=false" type="radio" name="setorganize_ord" value="true"'; if($organize_ord) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.deforganize_ord.checked=false" type="radio" name="setorganize_ord" value="false"'; if(!$organize_ord) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">When organizing the files and directories in the main list, "the", "a", and "an" are ignored.</font></td></tr>';

        }

        if($force_server_sets <= 0 || $force_server_sets == 2){
          if($show_all_stats) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Show All Statistics:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defshow_all_stats"';
          if(!isset($notdefault['show_all_stats']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defshow_all_stats.checked=false" type="radio" name="setshow_all_stats" value="true"'; if($show_all_stats) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defshow_all_stats.checked=false" type="radio" name="setshow_all_stats" value="false"'; if(!$show_all_stats) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">At the bottom of the page, a summary of the files and directories in the system is displayed. Disabling this feature may vastly improve performance and server strain on servers with 3000+ files and directories.</font></td></tr>';

          echo '<script type="text/javascript">
  function func_show_add_info(value){
    document.settings.setadd_getid3[0].disabled = value;
    document.settings.setadd_getid3[1].disabled = value;
  }
</script>';

          if($show_add_info) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Show Additional Info Column:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defshow_add_info"';
          if(!isset($notdefault['show_add_info']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defshow_add_info.checked=false" type="radio" onClick="func_show_add_info(false)" name="setshow_add_info" value="true"'; if($show_add_info) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defshow_add_info.checked=false" type="radio" onClick="func_show_add_info(true)" name="setshow_add_info" value="false"'; if(!$show_add_info) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">A column is added with quick glance information on compatible files. With GetID3 installed on server, many media files have much more information. Disabling this feature may vastly improve performance and server strain on servers with GetID3.</font></td></tr>';

          if($add_getid3) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Show media info in Additional Info column:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defadd_getid3"';
          if(!isset($notdefault['add_getid3']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defadd_getid3.checked=false" type="radio" name="setadd_getid3" value="true"'; if($add_getid3) echo ' checked'; if(!$show_add_info) echo ' disabled'; echo ' /></td><td width="1"></td><td align="center"><input onChange="document.settings.defadd_getid3.checked=false" type="radio" name="setadd_getid3" value="false"'; if(!$add_getid3) echo ' checked'; if(!$show_add_info) echo ' disabled'; echo ' /></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">The Additional Info Column will display media information for media files. This is only for systems with GetID3 installed. Disabling this feature may vastly improve performance and server strain. When disabled, or enabled, media information will be available in the properties window. <b>(GetID3 is ';
          if(!$getid3_true2)
            echo 'not ';
          echo 'installed)</font></td></tr>';

          echo '<script type="text/javascript">
  function func_show_file_time(value){
    document.settings.setfile_time[0].disabled = value;
    document.settings.setfile_time[1].disabled = value;
    document.settings.setfile_time_date.disabled = value;
  }
</script>';

          if($show_file_time) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Show Update/New Time Column:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defshow_file_time"';
          if(!isset($notdefault['show_file_time']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defshow_file_time.checked=false" type="radio" onClick="func_show_file_time(false)" name="setshow_file_time" value="true"'; if($show_file_time) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defshow_file_time.checked=false" type="radio" onClick="func_show_file_time(true)" name="setshow_file_time" value="false"'; if(!$show_file_time) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">A column is added to the file information to tell the date and/or time of creation or the time of the last update (set below).</font></td></tr>';

          if($file_time == 'c') $tmp = 'created'; else $tmp = 'updated';
          echo '<tr><td>Show Update or New Time:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="deffile_time"';
          if(!isset($notdefault['file_time']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">created</td><td width="1"></td><td align="center">updated</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.deffile_time.checked=false" type="radio" name="setfile_time" value="c"'; if($file_time == 'c') echo ' checked'; if(!$show_file_time) echo ' disabled'; echo ' /></td><td width="1"></td><td align="center"><input onChange="document.settings.deffile_time.checked=false" type="radio" name="setfile_time" value="m"'; if($file_time != 'c') echo ' checked'; if(!$show_file_time) echo ' disabled'; echo ' /></td></tr></table></td><td>created updated</td>';
          echo '<td><font size="-1">Set whether the added column (above) shows when the file was last updated or when it was created.</font></td></tr>';

          $tmp = date($file_time_date, 100000);
          echo '<tr><td>Update or New Time Format:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="deffile_time_date"';
          if(!isset($notdefault['file_time_date']))
            echo ' checked';
          echo '></td><td align="center"><input onChange="document.settings.deffile_time_date.checked=false" name="setfile_time_date" type="text" value="'.htmlspecialchars($file_time_date).'" size="20" maxlength="128"'; if(!$show_file_time) echo ' disabled'; echo ' /></td><td><i>PHP <a target="_blank" href="http://www.php.net/manual/en/function.date.php">date()</a> format</i></td>';
          echo '<td><font size="-1">The format of the added column (above) date and time. Use PHP\'s <a target="_blank" href="http://www.php.net/manual/en/function.date.php">date()</a> function format.</font></td></tr>';

          if($remember_org) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Remember directory organization:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defremember_org"';
          if(!isset($notdefault['remember_org']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defremember_org.checked=false" type="radio" name="setremember_org" value="true"'; if($remember_org) echo ' checked'; echo ' /></td><td width="1"></td><td align="center"><input onChange="document.settings.defremember_org.checked=false" type="radio" name="setremember_org" value="false"'; if(!$remember_org) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">When you change a directory\'s organization (organize by name, size, or type), the next time you visit that directory, the organization will have been remembered, and will display the same.</font></td></tr>';

          if($show_exif_thumb) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>Show Exif Thumbnails in List:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defshow_exif_thumb"';
          if(!isset($notdefault['show_exif_thumb']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defshow_exif_thumb.checked=false" type="radio" name="setshow_exif_thumb" value="true"'; if($show_exif_thumb) echo ' checked'; echo ' /></td><td width="1"></td><td align="center"><input onChange="document.settings.defshow_exif_thumb.checked=false" type="radio" name="setshow_exif_thumb" value="false"'; if(!$show_exif_thumb) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">This setting will affect whether or not any Exif-embeded thumbnails will display in the file list. The thumbnails will be avialable either way, via the Properties window.</font></td></tr>';

        }

        if($admin){
          if($admin_see_hidden) $tmp = 'true'; else $tmp = 'false';
          echo '<tr><td>See hidden files and folders:</td><td align="center">' . $tmp . '</td><td align="center"><input type="checkbox" name="defadmin_see_hidden"';
          if(!isset($notdefault['admin_see_hidden']))
            echo ' checked';
          echo '></td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center">';
          echo '<input onChange="document.settings.defadmin_see_hidden.checked=false" type="radio" name="setadmin_see_hidden" value="true"'; if($admin_see_hidden) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input onChange="document.settings.defadmin_see_hidden.checked=false" type="radio" name="setadmin_see_hidden" value="false"'; if(!$admin_see_hidden) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
          echo '<td><font size="-1">Enabling this will allow you to see files and directories that have been hidden by admins. They will not thave the "Hide" action available.</font></td></tr>';
        }


        echo '</table>';
        echo '<input type="submit" value="Set Settings" name="setsettings"> ';
        echo '<input type="reset" value="Reset" name="reset"> ';
        echo '<input type="submit" value="Set to server defaults" name="defaults"> ';

        echo '</form>';
      }


    } else {
      if(isset($_POST['uemail'])){
        $uemail = $_POST['uemail'];
        if(strlen($uemail) > 5 && strpos($uemail, '@') !== false && strpos($uemail, '.') !== false){
          $array_of_user = file(loc1 . '/filelist/filelist-'. $un .'.php');
          $array_of_user[6] = $uemail . $line_break;
          if($un != $_POST['password']){
            if(isset($_POST['cpassword']) && $_POST['password'] != ''){
              if($_POST['password'] != '**********'){
                if(!$strong_pw_enforce || strong_password($_POST['password'])){
                  $password  = $_POST['password'];
                  $cpassword = $_POST['cpassword'];
                  if($password == $cpassword){
                    $array_of_user[3] = md5($password) . $line_break;
                    $_SESSION['password'] = md5($password);
                  } else
                    echo '<font color="red">Passwords do not match. (Password not updated)</font><br>';
                } else
                  echo '<font color="red">Password is not a strong password. Password must be at least 8 characters long and use at least two types of characters (uppercase, lowercase, numbers, or symbols). (Password not updated)</font><br>';
              }
            }
          } else
            echo '<font color="red">Password cannot be the same as user name. (Password not updated)</font><br>';
          $write = implode('', $array_of_user);
          $fout = fopen(loc1 . '/filelist/filelist-'. $un .'.php', 'w');
          $fp = fwrite($fout, $write);
          fclose($fout);
          if($admin)
            $this1 = 4;
          else
            $this1 = 3;
          writelog('User changed their profile', 'profile', 'none', $this1);
          echo '<br>Settings changed, <a href="'.phpSelf.'?loc='.locenc.'&mysettings=1">Click here to continue.</a><br><br>';
        } else
          echo '<br><font color="red">Invalid email address.</font><br><br>';
        if($un == 'admin' && isset($_POST['passcode']) && isset($_POST['cpasscode']) && $_POST['passcode'] != '**********'){
          $passcode  = $_POST['passcode'];
          $cpasscode = $_POST['cpasscode'];
          if($passcode == $cpasscode){
            if($passcode == ''){
              @unlink(loc1 . '/filelist/filelist-passcode.php');
              echo 'Passcode removed.';
              writelog('Admin removed the censor passcode', 'profile');
            } else {
              $fout = fopen(loc1 . '/filelist/filelist-passcode.php', 'w');
              $fp = fwrite($fout, '<?PHP'.$line_break.md5($passcode).$line_break.'?>'.$line_break);
              fclose($fout);
              echo 'Passcode changed.';
              if(!strong_password($passcode))
                echo ' <font color="red">WARNING: Passcode is not a strong password!</font>';
              writelog('Admin updated the censor passcode', 'profile');
            }
          } else
            echo '<font color="red">Passcodes do not match.</font><br>';
        }
      } else
        echo '<br><br><br>';
      if(!isset($username))
        $username = $un;
      if(!isset($uemail))
        $uemail = $useremail;
      $password = '**********';
      if($un == 'admin' && $admin)
        $passcode = '**********';
      echo '<div align="center"><font size="+1"><b>Edit Profile</b></font></div>';
      echo '<br><form name="profile" method="post" action="'.phpSelf.'?loc='.locenc.'&mysettings=1&editprofile=1">';
      echo '<table cellpadding="3" cellspacing="0" border="0" align="center">';
      echo '<tr><td align="right">My email:</td><td><input type="text" name="uemail" size="30" value="'.htmlspecialchars($uemail).'"></td></tr>';
      echo '<tr><td colspan="2"></td></tr>';
      echo '<tr><td align="right">Password:</td><td><input type="password" name="password" size="30" value="'.$password.'"></td></tr>';
      echo '<tr><td align="right">Confirm password:</td><td><input type="password" name="cpassword" size="30" value=""></td></tr>';
      echo '<tr><td colspan="2"></td></tr>';
      if($un == 'admin' && $admin){
        echo '<tr><td align="right">Censor passcode:</td><td><input type="password" name="passcode" size="30" value="'.$passcode.'"></td></tr>';
        echo '<tr><td align="right">Confirm passcode:</td><td><input type="password" name="cpasscode" size="30" value=""></td></tr>';
      }
      echo '<tr><td colspan="2" align="center"><input type="submit" size="150" value="Commit Edit"> ';
      echo '<input type="button" size="150" value="Cancel" onClick="JavaScript:location.href=\''.phpSelf.'?loc='.addslashes(loc).'&mysettings=1\'"></td></tr>';
      echo '</table></form>';
    }

  } else


    // if the settings page is opened
  if(isset($_GET['settings']) && $admin){

    include(loc1 . '/filelist/filelist-settings.php');

    if(isset($_POST['setpg']) && ($_POST['setpg'] == 's' || $_POST['setpg'] == 'm'))
      $setpg = $_POST['setpg'];
    else
      $setpg = 'c';

    if(isset($_POST['setsettings']) || isset($_POST['hiddensubmit']) || isset($_POST['setsetsanduserdefs'])){
      $settings_ar = file(loc1 . '/filelist/filelist-settings.php');// echo '<pre>'.print_r($_POST).'</pre>';  echo '<pre>'.print_r($settings_ar).'</pre>';
      $settings_ar[0] = '<?PHP';
      $settings_ar[1] = '// ' . time();
      $settings_ar[2] = NULL;
      for($i = 2; $i < count($settings_ar) - 2; $i++){
        if(trim($settings_ar[$i]) != ''){
          $setting_name = trim(substr($settings_ar[$i], 1, strpos($settings_ar[$i], ' ')));
          if(isset($_POST['set'.$setting_name])){
            if($setting_name == 'line_break'){
              if(magicQuotes)
                $settings_ar[$i] = '$'.$setting_name.' = "\\' . stripslashes($_POST['set'.$setting_name]) . '";';
              else
                $settings_ar[$i] = '$'.$setting_name.' = "\\' . $_POST['set'.$setting_name] . '";';
            } else
            if($setting_name == 'file_time' || $setting_name == 'altern_color' || $setting_name == 'font_size'){
              if(magicQuotes)
                $settings_ar[$i] = '$'.$setting_name.' = \'' . stripslashes($_POST['set'.$setting_name]) . '\';';
              else
                $settings_ar[$i] = '$'.$setting_name.' = \'' . $_POST['set'.$setting_name] . '\';';
            } else
            if($setting_name == 'file_time_date'){
              if(magicQuotes)
                $settings_ar[$i] = '$'.$setting_name.' = \'' . $_POST['set'.$setting_name] . '\';';
              else
                $settings_ar[$i] = '$'.$setting_name.' = \'' . addslashes($_POST['set'.$setting_name]) . '\';';
            } else
            if($setting_name == 'error_spacer' || $setting_name == 'error_spacer2'){
              if(magicQuotes)
                $settings_ar[$i] = '$'.$setting_name.' = ' . stripslashes(((int)$_POST['set'.$setting_name] / 100)) . ';';
              else
                $settings_ar[$i] = '$'.$setting_name.' = ' . ((int)$_POST['set'.$setting_name] / 100) . ';';
            } elseif($setting_name == 'illegal_words' && $_POST['set'.$setting_name] != ''){
              $_POST['set'.$setting_name] = str_replace(' ', '', $_POST['set'.$setting_name]);
              $_POST['set'.$setting_name] = str_replace(';;', ';', $_POST['set'.$setting_name]);
              if(substr($_POST['set'.$setting_name], -1) == ';')
                $_POST['set'.$setting_name] = substr($_POST['set'.$setting_name], 0, -1);
              if(substr($_POST['set'.$setting_name], 0, 1) == ';')
                $_POST['set'.$setting_name] = substr($_POST['set'.$setting_name], 1);
              if(magicQuotes)
                $settings_ar[$i] = '$'.$setting_name.' = array(\'' . str_replace(';', '\',\'', str_replace('\'', "\'", stripslashes($_POST['set'.$setting_name]))) . '\');';
              else
                $settings_ar[$i] = '$'.$setting_name.' = array(\'' . str_replace(';', '\',\'', str_replace('\'', "\'", $_POST['set'.$setting_name])) . '\');';
            } else
              $settings_ar[$i] = '$'.$setting_name.' = ' . $_POST['set'.$setting_name] . ';';
          } else
            $settings_ar[$i] = trim($settings_ar[$i]);
        }
      }
      $settings_ar[$i] = NULL;
      $settings_ar[$i + 1] = '?>';
      $settings_ar[$i + 2] = NULL;

      $writesettings = implode("\n", $settings_ar);
      $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w') or die('no read/write permissions');
      $fp = fwrite($fout, $writesettings) or die('no read/write permissions');
      fclose($fout);

      if(isset($_POST['setsetsanduserdefs'])){
        $user_sets_ar = glob(loc1 . '/filelist/filelist-userdb/filelist-*-sets.php');
        foreach($user_sets_ar as $user_sets)
          @unlink($user_sets);
        writelog('Admin updated system settings and set users\' settings to default.', 'settings');
      } else
        writelog('Admin updated system settings.', 'settings');
      include(loc1 . '/filelist/filelist-settings.php');

    } elseif(isset($_POST['setdefault'])){
      @unlink(loc1 . '/filelist/filelist-settings.php');
      $user_sets_ar = glob(loc1 . '/filelist/filelist-userdb/filelist-*-sets.php');
      foreach($user_sets_ar as $user_sets)
        @unlink($user_sets);
      writelog('Admin reset all settings.', 'settings');
      include(loc1 . '/filelist/filelist-settings.php');
    }


    if($track_time || $development){
      $fitness_ar = file(loc1 . '/filelist/filelist-fitness.log');
      $min = 1000000;
      $max = 0;
      foreach($fitness_ar as $fitness){
        $sub_time_ar = explode('~~~~~', trim($fitness));
        if($sub_time_ar[2] == 1){
          $time_ar[] = $sub_time_ar[0];
          if($sub_time_ar[0] > $max)
            $max = $sub_time_ar[0];
          if($sub_time_ar[0] < $min)
            $min = $sub_time_ar[0];
        }
      }
      $avg = round(array_sum($time_ar) / count($time_ar), 4);
      echo 'Average page load time is '.$avg.' seconds - '.avg_load_stats($avg).'<br>';
      echo 'Minimum load time: '.$min.' seconds - '.min_load_stats($min).'<br>';
      echo 'Maximum load time: '.$max.' seconds - '.max_load_stats($max).'<br>';
      echo 'Tracking file size: '.filesz(filesize(loc1 . '/filelist/filelist-fitness.log')).', limit: '.filesz($max_track_size * 1024).'<br>';
      echo '<a href="'.phpSelf.'?loc='.locenc.'&fitness=1">Click here to get more tracking info.</a><br><br>';
    }

/*
display_new
display_updated
new_time_secs
error_spacer
error_spacer2
show_all_stats
organize_ord
show_add_info
add_getid3
show_file_time
file_time
file_time_date
upload_bar
all_upload_bar
require_login
allow_login_request
remember_org
force_download
admin_see_hidden
line_break
auto_icon
logging_level
font_size
name_length
trunc_offset
recycle
altern_line_color
altern_color
multi_upload
track_time
show_dir_size
force_server_sets
show_file_hash
hash_size
show_exif_thumb
strong_pw_enforce
illegal_words
*/
    echo '<form method="post" name="settings" action="'.phpSelf.'?loc='.locenc.'&settings=1">';

echo '<script language="JavaScript" type="text/javascript">
function gotopage(page){
  document.settings.setpg.value = page;
  document.settings.hiddensubmit.disabled = false;
  document.settings.submit();
}
</script>';

    echo '<input type="hidden" name="setpg" />';
    echo '<input type="hidden" name="hiddensubmit" disabled />';

    echo '<table cellpadding="3" Cellspacing="0" border="1"><tr><td><font size="+1">';
    if($setpg == 's')
      echo '<b>';
    echo '<a onclick="submit" href="javascript:gotopage(\'s\')">System Intensive</a>';
    if($setpg == 's')
      echo '<b>';
    echo '</font></td><td><font size="+1">';
    if($setpg == 'c')
      echo '<b>';
    echo '<a onclick="submit" href="javascript:gotopage(\'c\')">Cosmetic</a>';
    if($setpg == 'c')
      echo '<b>';
    echo '</font></td><td><font size="+1">';
    if($setpg == 'm')
      echo '<b>';
    echo '<a onclick="submit" href="javascript:gotopage(\'m\')">Miscellaneous</a>';
    if($setpg == 'm')
      echo '<b>';
    echo '</font></td></tr>';
    echo '<table cellpadding="3" cellspacing="0" border="1"><tr>';
    echo '<td><u><b>Setting</b></u></td>';
    echo '<td><u><b>Current value</b></u></td>';
    echo '<td><u><b>New value</b></u></td>';
    echo '<td><u><b>Possible values</b></u></td>';
    echo '<td><u><b>Description</b></u></td>';
    echo '</tr>';
    if($setpg != 's')
      echo '<tr><td colspan="5"><i>Italicized settings may be changed by individual users to fit their own preferences (change the users\' customizability with the Miscellaneous::Force Server-Default Settings setting.)</i></td></tr>';

    if($setpg == 's'){

      if($line_break == "\r\n") $lb = '\r\n'; elseif($line_break == "\r") $lb = '\r'; else $lb = '\n';
      echo '<tr><td>Line break:</td><td>' . $lb . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">\n</td><td width="1"></td><td align="center">\r\n</td><td width="1"></td><td align="center">\r</td></tr><tr><td align="center"><input type="radio" name="setline_break" value="n"'; if($lb == '\n') echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setline_break" value="rn"'; if($lb == '\r\n') echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setline_break" value="r"'; if($lb == '\r') echo ' checked'; echo '></td></tr></table></td><td>\n \r\n \r</td>';
      echo '<td><font size="-1">"\n" is general default, some Windows programs prefer "\r\n", while MacOS < 10 prefers "\r".</font></td></tr>';

      if($require_login) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Enable Login:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setrequire_login" value="true"'; if($require_login) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setrequire_login" value="false"'; if(!$require_login) echo ' checked'; echo ' disabled></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This setting enables or disables the ability to login to the File Manage system. This can only be disabled in the console.</font></td></tr>';

      if($allow_login_request) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Allow Login Requests:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setallow_login_request" value="true"'; if($allow_login_request) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setallow_login_request" value="false"'; if(!$allow_login_request) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">With this enabled, users are able to request a login. They must enter their email and desired username. The admin can then accept them or deny them. If allow_anonymous is enabled, the user will be able to login with anonym_perm permission until they are accepted/denied.</font></td></tr>';

      if($logging_level <= -1) $tmp = 'Off'; else $tmp = $logging_level;
      echo '<tr><td>Logging Level:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="1" border="0"><tr><td align="center">Off</td><td align="center">0</td><td align="center">1</td><td align="center">2</td><td align="center">3</td><td align="center">4</td></tr><tr><td align="center"><input type="radio" name="setlogging_level" value="-1"'; if($logging_level <= -1) echo ' checked'; echo '></td><td align="center"><input type="radio" name="setlogging_level" value="0"'; if($logging_level == 0) echo ' checked'; echo '></td><td align="center"><input type="radio" name="setlogging_level" value="1"'; if($logging_level == 1) echo ' checked'; echo '></td><td align="center"><input type="radio" name="setlogging_level" value="2"'; if($logging_level == 2) echo ' checked'; echo '></td><td align="center"><input type="radio" name="setlogging_level" value="3"'; if($logging_level == 3) echo ' checked'; echo '></td><td align="center"><input type="radio" name="setlogging_level" value="4"'; if($logging_level >= 4) echo ' checked'; echo '></td></tr></table></td><td>Off 0 1 2 3 4</td>';
      echo '<td><font size="-1">The higher the number the more logs generated. 0 - system mandatory, 1 - important logs like errors, 2 - common log points, 3 - a few non-critical items, or 4 - anything of even minor interest.</font></td></tr>';

      if($recycle) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Enable Recycle Bin:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setrecycle" value="true"'; if($recycle) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setrecycle" value="false"'; if(!$recycle) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">The recycle bin stores files that users have deleted. They can then be permanently deleted or moved to another location.</font></td></tr>';

    } elseif($setpg == 'c'){

      echo '<script type="text/javascript">
  function func_display_new_updated(){
    if(document.settings.setdisplay_new[1].checked
    && document.settings.setdisplay_updated[1].checked){
      document.settings.setnew_time_secs.disabled = true;
    } else {
      document.settings.setnew_time_secs.disabled = false;
    }
  }
</script>';

      if($display_new) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Display New Flag:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_display_new_updated()" name="setdisplay_new" value="true"'; if($display_new) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_display_new_updated()" name="setdisplay_new" value="false"'; if(!$display_new) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This displays a coloumn next to the files and directories which states if the item is new.</font></td></tr>';

      if($display_updated) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Display Updated Flag:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_display_new_updated()" name="setdisplay_updated" value="true"'; if($display_updated) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_display_new_updated()" name="setdisplay_updated" value="false"'; if(!$display_updated) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This displays a column next to the files and directories to tell users if an item has been updated.</font></td></tr>';

      echo '<tr><td>New/Update Time:</td><td>' . $new_time_secs . '</td><td align="center"><input name="setnew_time_secs" type="text" value="'.$new_time_secs.'" size="20" maxlength="256"'; if(!$display_new && !$display_new) echo ' disabled'; echo ' /></td><td><i>INT or MATH</td>';
      echo '<td><font size="-1">This value determines, in seconds, at what point either of the above flags will be disabled (eg: if set to 60, a file will display as "new" or "updated" --depending-- for one minute).</font></td></tr>';

      if($show_all_stats) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Show All Statistics:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setshow_all_stats" value="true"'; if($show_all_stats) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setshow_all_stats" value="false"'; if(!$show_all_stats) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">At the bottom of the page, a summary of the files and directories in the system is displayed. Disabling this feature may vastly improve performance and server strain on servers with 3000+ files and directories.</font></td></tr>';

      if($show_dir_size) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Display Directory Size:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setshow_dir_size" value="true"'; if($show_dir_size) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setshow_dir_size" value="false"'; if(!$show_dir_size) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">As the file list lists directories it will scan the directory and display the directory\'s volume. And if the Additional Info Column is enabled, it will display the number of files and directories. With this enabled, the Show All Statistics information will be more accurate if the root directory is accessed often. Show all Statistics will not contain statistics on hidden directories. This feature will slow page load times on large file system, thus it is <i>not</i> recommended for systems with 1000+ files and directories. This will also slow page load times on File Systems with less than 1000, if Show All Statistics is disabled.</font></td></tr>';

      echo '<script type="text/javascript">
  function func_show_add_info(value){
    document.settings.setadd_getid3[0].disabled = value;
    document.settings.setadd_getid3[1].disabled = value;
  }
</script>';

      if($show_add_info) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Show Additional Info Column:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_show_add_info(false)" name="setshow_add_info" value="true"'; if($show_add_info) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_show_add_info(true)" name="setshow_add_info" value="false"'; if(!$show_add_info) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">A column is added with quick glance information on compatible files. With GetID3 installed (read ReadMe), many media files have much more information.</font></td></tr>';

      if($add_getid3) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Show media info in Additional Info Column:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setadd_getid3" value="true"'; if($add_getid3) echo ' checked'; if(!$show_add_info) echo ' disabled'; echo ' /></td><td width="1"></td><td align="center"><input type="radio" name="setadd_getid3" value="false"'; if(!$add_getid3) echo ' checked'; if(!$show_add_info) echo ' disabled'; echo ' /></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">The Additional Info Column will display media information for media files. This is only for systems with GetID3 installed (read README for installing information). Disabling this feature may vastly improve performance and server strain. When disabled, or enabled, media information will be available in the properties window. <b>(GetID3 is ';
      if(!$getid3_true2)
        echo 'not ';
      echo 'installed)</b></font></td></tr>';

      echo '<script type="text/javascript">
  function func_show_file_time(value){
    document.settings.setfile_time[0].disabled = value;
    document.settings.setfile_time[1].disabled = value;
    document.settings.setfile_time_date.disabled = value;
  }
</script>';

      if($show_file_time) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Show Update/New Time Column:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_show_file_time(false)" name="setshow_file_time" value="true"'; if($show_file_time) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_show_file_time(true)" name="setshow_file_time" value="false"'; if(!$show_file_time) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">A column is added to the file information to tell the date and/or time of creation or the time of the last update (set below).</font></td></tr>';

      if($file_time == 'c') $tmp = 'created'; else $tmp = 'updated';
      echo '<tr><td><i>Show Update or New Time:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">created</td><td width="1"></td><td align="center">updated</td></tr><tr><td align="center"><input type="radio" name="setfile_time" value="c"'; if($file_time == 'c') echo ' checked'; if(!$show_file_time) echo ' disabled'; echo ' /></td><td width="1"></td><td align="center"><input type="radio" name="setfile_time" value="m"'; if($file_time != 'c') echo ' checked'; if(!$show_file_time) echo ' disabled'; echo ' /></td></tr></table></td><td>created updated</td>';
      echo '<td><font size="-1">Set whether the added column (above) shows when the file was last updated or when it was created.</font></td></tr>';

      $tmp = date($file_time_date, 100000);
      echo '<tr><td><i>Update or New Time Format:</i></td><td>' . $tmp . '</td><td align="center"><input name="setfile_time_date" type="text" value="'.$file_time_date.'" size="20" maxlength="128"'; if(!$show_file_time) echo ' disabled'; echo ' /></td><td><i>PHP <a target="_blank" href="http://www.php.net/manual/en/function.date.php">date()</a> format</i></td>';
      echo '<td><font size="-1">The format of the added column (above) date and time. Use PHP\'s <a target="_blank" href="http://www.php.net/manual/en/function.date.php">date()</a> function format.</font></td></tr>';

      echo '<tr><td><i>Long column text size:</i></td><td>' . $font_size . '</td><td align="center"><input name="setfont_size" type="text" value="'.$font_size.'" size="2" maxlength="2"></td><td><i>INT < 4 & > -3</i></td>';
      echo '<td><font size="-1">Change the font size of the Updated/New Time Column, Additional Info column, and the Actions Column (0 is standard size, please use a + or - when entering a font size).</font></td></tr>';

      echo '<tr><td><i>Max File and Directory Name Length:</i></td><td>' . $name_length . '</td><td align="center"><input name="setname_length" type="text" value="'.$name_length.'" size="3" maxlength="3"></td><td><i>INT >= 8</i></td>';
      echo '<td><font size="-1">Sets the maximum number of characters of a file or directory to be displayed, if longer, the displayed name will be truncated with "...".</font></td></tr>';

      echo '<tr><td><i>File/Dir Name Truncation Location:</i></td><td>' . $trunc_offset . '</td><td align="center"><input name="settrunc_offset" type="text" value="'.$trunc_offset.'" size="3" maxlength="3"></td><td><i>INT < name_length & > 0</i></td>';
      echo '<td><font size="-1">This value determines how many character to display <i>after</i> the truncation (0 will place the "..." at the end of the file/directory name).</font></td></tr>';

      echo '<script type="text/javascript">
  function func_altern_line_color(value){
    document.settings.setaltern_color.disabled = value;
  }
</script>';

      if($altern_line_color) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Alternate Line Color:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_altern_line_color(false)" name="setaltern_line_color" value="true"'; if($altern_line_color) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_altern_line_color(true)" name="setaltern_line_color" value="false"'; if(!$altern_line_color) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This option will make every other row in the file list a different color. This helps visual organization, especially on high resolution monitors.</font></td></tr>';

      echo '<tr><td><i>Alternative Line Color:</i></td><td bgcolor="'.$altern_color.'">' . $altern_color . '</td><td align="center"><input name="setaltern_color" type="text" value="'.$altern_color.'" size="7" maxlength="64"'; if(!$altern_line_color) echo ' disabled'; echo ' /></td><td><i>valid HTML color</i></td>';
      echo '<td><font size="-1">This is the color that the "other" row (enabled above) will be. It is best to keep it to a low contrast, but enough to be visible on all monitors.</font></td></tr>';

      if($show_exif_thumb) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Show Exif Thumbnails in List:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setshow_exif_thumb" value="true"'; if($show_exif_thumb) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setshow_exif_thumb" value="false"'; if(!$show_exif_thumb) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This setting will affect whether or not to display any Exif-embeded thumbnails in the file list. The thumbnails will be available either way, via the Properties window. Disabling this may save some server bandwidth, and help page load times slightly.</font></td></tr>';

    } else {

      if($force_download == 0) $tmp = 'Browser Default'; elseif($force_download == 1) $tmp = 'Default and Download'; else $tmp = 'Force Download';
      echo '<tr><td>Download instead of opening files:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">def</td><td width="1"></td><td align="center">def/dl</td><td width="1"></td><td align="center">dl</td></tr><tr><td align="center"><input type="radio" name="setforce_download" value="0"'; if($force_download == 0) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setforce_download" value="1"'; if($force_download == 1) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setforce_download" value="2"'; if($force_download != 0 && $force_download != 1) echo ' checked'; echo '></td></tr></table></td><td>"Browser Default" "Default and Download" "Force Download"</td>';
      echo '<td><font size="-1">When set to "Force Download", clicking on a file, or its icon, in the file list will cause the file to be downloaded. "Default and Download" will leave the option open to the user. Clicking the file name will use the browser default, while clicking the icon will download the file. "Browser Default" is where the browser will attempt to open the file, if that fails, it then may be downloaded. "Force Download" adds some security, as some files may be security risks if executed on the server. This is also the required setting if loc1 has been altered from "__FILE__".</font></td></tr>';

      echo '<script type="text/javascript">
  function func_upload_bar(value){
    document.settings.setall_upload_bar[1].disabled = value;
  }
</script>';

      if($upload_bar) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Upload Progress Bar:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_upload_bar(false)" name="setupload_bar" value="true"'; if($upload_bar) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_upload_bar(true)" name="setupload_bar" value="false"'; if(!$upload_bar) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1"><b>READ THIS BEFORE ENABLING!</b> Read the README file to learn how to allow this feature to work -- it is more complex than just enabling the feature.<br>For admins, on the upload page, a progress bar will pop up when files are being uploaded. It shows size, estimated time to completion and other information. This feature requires Perl with the CGI module to be installed. The progress bar is very experimental, and insecurities arise with upload bar use with non-admins (see below setting).</font></td></tr>';

      if($all_upload_bar) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Upload Progress Bar for all users:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setall_upload_bar" value="true"'; if($all_upload_bar) echo ' checked'; echo ' disabled></td><td width="1"></td><td align="center"><input type="radio" name="setall_upload_bar" value="false"'; if(!$all_upload_bar) echo ' checked'; if(!$upload_bar) echo ' disabled'; echo ' /></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This setting enables the Upload Progress Bar for all users (not just admins). This is not recommended as there are security holes for non-admin users of the progress bar. The progress bar is very experimental, and insecurities arise because limited use of the upload progress bar cannot be enforced. This setting can only be enabled in the Console.</font></td></tr>';

      if($multi_upload) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Multiple Uploads at One Time:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setmulti_upload" value="true"'; if($multi_upload) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setmulti_upload" value="false"'; if(!$multi_upload) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This will display multiple lines on the upload page to allow up to 10 files to be uploaded at once. This makes uploading much more convenient. When disabled, only one file can be uploaded at a time. Enabled, or disabled, maximum file size for all files uploaded at one time remain the same.</font></td></tr>';

      if($remember_org) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Remember directory organization:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setremember_org" value="true"'; if($remember_org) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setremember_org" value="false"'; if(!$remember_org) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">When a user changes the directory organization (organize by name, size, or type), the next time they visit that directory, the organization will have been remembered, and will display the same.</font></td></tr>';

      $tmp = round($error_spacer * 100);
      echo '<tr><td>Word Search Grace:</td><td>' . $tmp . '%</td><td align="center"><input name="seterror_spacer" type="text" value="'.$tmp.'" size="2" maxlength="2">%</td><td><i>INT < 100</i></td>';
      echo '<td><font size="-1">When a search is done, this is the percentage a word in the name of the file or directory that has to be correct (e.g.: 50% means that 4 characters out of "howdieman" can be moved or changed and still show up as a search hit).</font></td></tr>';

      $tmp = round($error_spacer2 * 100);
      echo '<tr><td>Phrase Search Grace:</td><td>' . $tmp . '%</td><td align="center"><input name="seterror_spacer2" type="text" value="'.$tmp.'" size="2" maxlength="2">%</td><td><i>INT < 100</i></td>';
      echo '<td><font size="-1">When a search is done, this is the percentage of a phrase in the name of the file or directory that has to be correct (e.g.: 30% means that 3 characters out of "howdy man" can be moved or changed and still show up as a search hit).</font></td></tr>';

      if($organize_ord) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Organize without "the" and "a":</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setorganize_ord" value="true"'; if($organize_ord) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setorganize_ord" value="false"'; if(!$organize_ord) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">When organizing the files and directories in the main list, "the", "a", and "an" are ignored.</font></td></tr>';

      echo '<tr><td>Maximum Log Size:</td><td>' . filesz($max_log_size * 1024) . '</td><td align="center"><input name="setmax_log_size" type="text" value="'.$max_log_size.'" size="4" maxlength="4">KB</td><td><i>Any Number > 0</i></td>';
      echo '<td><font size="-1">The size in kilobytes that the log file will not exceed. If it does exceed this size, entries to the log will be removed starting from the oldest logs. Current log size is: '.filesz(filesize(loc1 . '/filelist/filemanagelog.log')).'.</font></td></tr>';

    echo '<script type="text/javascript">
  function func_track_time(value){
    document.settings.setmax_track_size.disabled = value;
  }
</script>';

      if($track_time) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>System Fitness Tracking:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_track_time(false)" name="settrack_time" value="true"'; if($track_time) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_track_time(true)" name="settrack_time" value="false"'; if(!$track_time) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This feature will track load times in directories and on pages. Then, at the top of this page, a fitness rating will be listed to help you determine what settings may need to be changed. This should be enabled for about 1000 visits before the statistics will be very accurate.</font></td></tr>';

      echo '<tr><td>Maximum Fitness Tracking File Size:</td><td>' . filesz($max_track_size * 1024) . '</td><td align="center"><input name="setmax_track_size" type="text" value="'.$max_track_size.'" size="4" maxlength="4"'; if(!$track_time) echo ' disabled'; echo ' />KB</td><td><i>Any Number > 0</i></td>';
      echo '<td><font size="-1">This limits the Fitness log file to a size (in kilobytes). Current log size is: '.filesz(filesize(loc1 . '/filelist/filelist-fitness.log')).'. It is recommended to set this value up so the fitness log will display the statistics for the last week or two (you can go longer or shorter based on the server\'s needs).</font></td></tr>';

      if($admin_see_hidden) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td><i>Admins see hidden files and folders:</i></td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setadmin_see_hidden" value="true"'; if($admin_see_hidden) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setadmin_see_hidden" value="false"'; if(!$admin_see_hidden) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">Enabling this will allow admins to see files and directories that have been hidden by admins. They will not have the "Hide" action available.</font></td></tr>';

      echo '<script type="text/javascript">
  function func_show_file_hash(value){
    document.settings.sethash_size.disabled = value;
  }
</script>';

      if($show_file_hash) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Display File Hashes in Properties:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_show_file_hash(false)" name="setshow_file_hash" value="true"'; if($show_file_hash) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" onClick="func_show_file_hash(true)" name="setshow_file_hash" value="false"'; if(!$show_file_hash) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This feature enables or disables the display of MD5 and SHA1 hashes in properties window. These hashes are often used for file verification, to make sure the file being downloaded or accessed is, without a doubt, the correct file.</font></td></tr>';

      echo '<tr><td>Max File Size to Display Hashes:</td><td>' . filesz($hash_size * 1024 * 1024) . '</td><td align="center"><input name="sethash_size" type="text" value="'.($hash_size).'" size="3" maxlength="3"'; if(!$show_file_hash) echo ' disabled'; echo ' />MB</td><td><i>Any Number >= 0</i></td>';
      echo '<td><font size="-1">When file hashes in Properties is enabled, this limits the size for which they will be involuntarily displayed. If the file\'s size is larger than this, the user will be required to click another link to get the hashes. This helps server load as large files take some time to collect a file to display a hash of.</font></td></tr>';

      if($strong_pw_enforce) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Enforce Strong Passwords:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" name="setstrong_pw_enforce" value="true"'; if($strong_pw_enforce) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setstrong_pw_enforce" value="false"'; if(!$strong_pw_enforce) echo ' checked'; echo '></td></tr></table></td><td>true false</td>';
      echo '<td><font size="-1">This setting will force any user who is requesting a login to have a "strong password". What this entails is a password that is at least 8 characters long, and uses at least two of the following types of characters: uppercase letters, lowercase letters, numbers, or symbols.</font></td></tr>';

      if($force_server_sets <= 0) $tmp = 'None'; elseif($force_server_sets == 1) $tmp = 'Non-Cosmetic'; elseif($force_server_sets == 2) $tmp = 'Cosmetic'; else $tmp = 'All';
      echo '<tr><td>Force Server-Default Settings:</td><td>' . $tmp . '</td><td align="center" colspan="2"><table cellpadding="2" cellspacing="0" border="0"><tr><td align="center">None</td><td width="1"></td><td align="center">Non-Cosmetic</td><td width="1"></td><td align="center">Cosmetic</td><td width="1"></td><td align="center">All</td></tr><tr><td align="center"><input type="radio" name="setforce_server_sets" value="0"'; if($force_server_sets <= 0) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setforce_server_sets" value="1"'; if($force_server_sets == 1) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setforce_server_sets" value="2"'; if($force_server_sets == 2) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setforce_server_sets" value="3"'; if($force_server_sets >= 3) echo ' checked'; echo '></td></tr></table>';
      echo '<td><font size="-1">With this set to "None", users can change all the <i>italicized</i> setting in their "My Settings". When this setting is set to "Non-Cosmetic", any setting that may slow page load times are removed from the users\' "My Settings" pages. When set to "Cosmetic" all cosmetic (non-server-slowing settings) are forced to these (above) server-defaults. When set to "All", both cosmetic and non-cosmetic changes are removed from each User\'s "My Settings" page.</font></td></tr>';

      $tmp = implode('; ', $illegal_words);
      echo '<tr><td>Banned words:</td><td align="center" colspan="3"><input name="setillegal_words" type="text" value="'.$tmp.'" size="70" maxlength="1024"></td>';
      echo '<td><font size="-1">These values are values that will not be allowed when a text file is created or uploaded. Separate each value you want blocked by a semicolon (";"). It is highly recommended to only add to the list, and never take any items  from the original list out. If items are added to this list, every time File Manage is updated or code changed, this list should be checked to make sure all desired words are present.</font></td></tr>';

      echo '<script type="text/javascript">
    function func_auto_icon(value){
      document.settings.setaccept_all[0].disabled = value;
      document.settings.setaccept_all[1].disabled = value;
      if(document.settings.setaccept_all[0].checked)
        document.settings.setaccept.disabled = true;
      else
        document.settings.setaccept.disabled = false;
    }
  </script>';

      if($auto_icon) $tmp = 'true'; else $tmp = 'false';
      echo '<tr><td>Automatic Icon Association:</td><td>' . $tmp . '</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">true</td><td width="1"></td><td align="center">false</td></tr><tr><td align="center"><input type="radio" onClick="func_auto_icon(false)" name="setauto_icon" value="true"'; if($auto_icon) echo ' checked'; echo '></td><td width="1"></td><td align="center"><input type="radio" name="setauto_icon" value="false"'; if(!$auto_icon) echo ' checked'; echo ' disabled></td></tr></table></td><td>true false</td>';
      echo '<td>';
      if(!$auto_icon)
        echo '<font color="red">This should not be changed if Custom Icons Setup has been used. If enabled, any Custom Icon setup will be set back to default.</font>';
      echo '<font size="-1">This is highly recommended unless you are using custom icons with the system. This will only change something if the accept or iconlink arrays are changed. This feature can only be disabled in the console or by using the Custom Icons Setup.</font></td></tr>';

      echo '<tr><td>Custom Icons Setup:</td><td colspan="3"><a href="'.phpSelf.'?loc='.locenc.'&customicon=1">Click here to setup custom icon associations.</a></td><td><font size="-1">Use this page to upload custom icons, and to setup each file type with an icon.</font></td></tr>';

      $tmp = implode('; ', $accept); if($accept[count($accept) - 1] == '') $tmp2 = 'All'; else $tmp2 = 'Specific';
      echo '<tr><td>File types to display:</td><td align="center"><table cellpadding="2" border="0"><tr><td align="center">All</td><td width="1"></td><td align="center">Specific</td></tr><tr><td align="center"><input onClick="document.settings.setaccept.disabled=true" type="radio" name="setaccept_all" value="true"'; if($tmp2 == 'All') echo ' checked'; if(!$auto_icon) echo ' disabled'; echo ' /></td><td width="1"></td><td align="center"><input onClick="document.settings.setaccept.disabled=false" type="radio" name="setaccept_all" value="false"'; if($tmp2 == 'Specific') echo ' checked'; if(!$auto_icon) echo ' disabled'; echo ' /></td></tr></table></td><td align="center" colspan="2"><input name="setaccept" type="text" value="'.$tmp.'" size="50" maxlength="1024"';
      if($tmp2 == 'All' || !$auto_icon)
        echo ' disabled';
      echo '></td>';
      echo '<td><font size="-1">If "All" is selected, all file types will be displayed. If "Specific" is selected, the list of file types is editable. Files will only display if the end of the name of the file (including the extension) ends with one of the items in the list.</font></td></tr>';

    }

    echo '</table>';
    echo '<input type="submit" value="Set Settings" name="setsettings"> ';
    echo '<input type="submit" value="Set Settings and Users to Default" name="setsetsanduserdefs">'.note(22, 270, 320).' ';
    echo '<input type="reset" value="Reset" name="reset"> ';
    echo '<input type="submit" value="Set All to Default" name="setdefault">'.note(23, 170, 200);

    echo '</form>';

  } else



    // if the command-line console is opened for commands
  if(isset($_GET['console']) && $admin){

    if(isset($cmd)){

      if(substr($cmd, 0, 6) == 'passwd')
        writelog('Admin issued console command (passwd ***).', 'console', 'none', 3);
      else
        writelog('Admin issued console command ('.$cmd.').', 'console');

        // file command displays list of files with their paths
      if($cmdar[0] == 'file'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          $files_ar = wild_card($stloc0);
          if(count($files_ar) > 0)
            foreach($files_ar as $file)
              if(file_exists(loc1 . $file))
                array_unshift($prevcmd, $file);
              else
                array_unshift($prevcmd, 'File/directory ('.$file.') does not exist.');
          else
            array_unshift($prevcmd, 'No files or directories exist under that wildcard.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // cp command copies files or directory
      if($cmdar[0] == 'cp'){
        if(count($cmdar) == 3 || count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          if(substr($stloc0, 0, -1) != '/' && (strpos($stloc0, '*') !== false || is_file(loc1 . $stloc0))){
            if(count($cmdar) == 3){
              if(substr($cmdar[2], 0, 1) == '/')
                if(substr($cmdar[2], -1) == '/')
                  $stloc1 = $cmdar[2];
                else
                  $stloc1 = $cmdar[2] .'/';
              else
                if(substr($cmdar[2], -1) == '/')
                  $stloc1 = loc . $cmdar[2];
                else
                  $stloc1 = loc . $cmdar[2] .'/';
            } else
              $stloc1 = loc;

            $files_ar = wild_card($stloc0, false);
            //echo '<pre>'.print_r($files_ar).'</pre>';
            foreach($files_ar as $file)
              if(is_file(loc1 . $file))
                cpy($file, $stloc1);
          } elseif(is_dir(loc1 . $stloc0)){
            if(substr($stloc0, 0, -1) != '/')
              $stloc0 .= '/';
            if(strtolower($_POST['cmd']) != 'c'){
              $name = substr($stloc0, strrpos(substr($stloc0, 0, -1), '/') + 1, -1);
              if(count($cmdar) == 3 && $cmdar[2] != substr($stloc0, strrpos(substr($stloc0, 0, -1), '/'))){
                if(substr($cmdar[2], 0, 1) == '/')
                  if(substr($cmdar[2], -1) == '/')
                    $dest_loc = $cmdar[2];
                  else
                    $dest_loc = $cmdar[2] .'/';
                else
                  if(substr($cmdar[2], -1) == '/')
                    $dest_loc = loc . $cmdar[2];
                  else
                    $dest_loc = loc . $cmdar[2] .'/';
                $stloc1 = $dest_loc . $name;

                echo $stloc0 . ' -- '. $stloc1 . '<br>';
                if(is_dir(loc1 . $dest_loc)){
                  if(!is_dir(loc1 . $stloc1) || strtolower($_POST['cmd']) == 'y' || strtolower($_POST['cmd']) == 'n'){
                    if(!is_dir(loc1 . $stloc1))
                      mkdir(loc1 . $stloc1);
                    if(strpos(strtolower($stloc0), 'filelist') === false && strpos(strtolower($stloc0), 'getid3') === false){
                      if(strpos(strtolower($stloc1), 'filelist') === false && strpos(strtolower($stloc1), 'getid3') === false){
                        if(strtolower($_POST['cmd']) == 'y')
                          dircpy($stloc0, $stloc1, true);
                        else
                          dircpy($stloc0, $stloc1);
                        writelog('Admin copied a directory', 'dircpy', $stloc0.' - '.$stloc1);
                        array_unshift($prevcmd, 'Directory copied.');
                      } else
                        array_unshift($prevcmd, 'Invalid destination directory.');
                    } else
                      array_unshift($prevcmd, 'Invalid source directory.');
                  } else
                    array_unshift($prevcmd, 'Directory already exists,'."\n".'[y] Merge directories/overwrite files'."\n".'[n] Merge directories do not overwrite files'."\n".'[c] Cancel');
                } else
                  array_unshift($prevcmd, 'Target: "'.$dest_loc.'" is not a valid directory.');
              } else {
                if(strpos(strtolower($stloc0), 'filelist') === false && strpos(strtolower($stloc0), 'getid3') === false){
                  if(!isset($stloc1) || (strpos(strtolower($stloc1), 'filelist') === false && strpos(strtolower($stloc1), 'getid3') === false)){
                    if(file_exists(loc1 . loc . '/'. $name)){
                      $cpy2 = 'Copy of ' . $name;
                      if(file_exists(loc1 . loc . $cpy2)){
                        $done = false;
                        $num = 2;
                        while(!$done){
                          $cpy2 = 'Copy ('. $num .') of ' . $name;
                          if(!file_exists(loc1 . loc . $cpy2))
                            $done = true;
                          $num++;
                        }
                      }
                      $name = $cpy2;
                    }
                    $stloc1 = loc . $name . '/';
                    mkdir(loc1 . $stloc1);
                    dircpy($stloc0, $stloc1);
                    array_unshift($prevcmd, 'Directory copied.');
                  } else
                    array_unshift($prevcmd, 'Invalid destination directory.');
                } else
                  array_unshift($prevcmd, 'Invalid source directory.');
              }
            }
          } else
            array_unshift($prevcmd, 'Source file or directory does not exist.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // mv command moves files
      if($cmdar[0] == 'mv'){
        if(count($cmdar) == 3){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          if(substr($cmdar[2], 0, 1) == '/')
            if(substr($cmdar[2], -1) == '/')
              $stloc1 = $cmdar[2];
            else
              $stloc1 = $cmdar[2] .'/';
          else
            if(substr($cmdar[2], -1) == '/')
              $stloc1 = loc . $cmdar[2];
            else
              $stloc1 = loc . $cmdar[2] .'/';
          if(substr($stloc0, 0, -1) != '/' && (strpos($stloc0, '*') !== false || is_file(loc1 . $stloc0))){
            $files_ar = wild_card($stloc0, false);
            foreach($files_ar as $file)
              move($file, $stloc1);
          } elseif(is_dir(loc1 . $stloc0)){
            if(substr($stloc0, 0, -1) != '/')
              $stloc0 .= '/';
            if(strtolower($_POST['cmd']) != 'c'){
              $name = substr($stloc0, strrpos(substr($stloc0, 0, -1), '/') + 1, -1);
              if(count($cmdar) == 3 && $cmdar[2] != substr($stloc0, strrpos(substr($stloc0, 0, -1), '/'))){
                if(substr($cmdar[2], 0, 1) == '/')
                  if(substr($cmdar[2], -1) == '/')
                    $dest_loc = $cmdar[2];
                  else
                    $dest_loc = $cmdar[2] .'/';
                else
                  if(substr($cmdar[2], -1) == '/')
                    $dest_loc = loc . $cmdar[2];
                  else
                    $dest_loc = loc . $cmdar[2] .'/';
                $stloc1 = $dest_loc . $name;

                echo $stloc0 . ' -- '. $stloc1 . '<br>';
                if(is_dir(loc1 . $dest_loc)){
                  if(!is_dir(loc1 . $stloc1) || strtolower($_POST['cmd']) == 'y' || strtolower($_POST['cmd']) == 'n'){
                    if(!is_dir(loc1 . $stloc1))
                      mkdir(loc1 . $stloc1);
                    if(strpos(strtolower($strloc0), 'filelist') === false && strpos(strtolower($strloc0), 'getid3') === false){
                      if(strpos(strtolower($strloc1), 'filelist') === false && strpos(strtolower($strloc1), 'getid3') === false){
                        if(strtolower($_POST['cmd']) == 'y')
                          dirmv($stloc0, $stloc1, true);
                        else
                          dirmv($stloc0, $stloc1);
                        @rmdir(loc1 . $stloc0);
                        writelog('Admin moved a directory', 'dircpy', $stloc0.' - '.$stloc1);
                        array_unshift($prevcmd, 'Directory movied.');
                      } else
                        array_unshift($prevcmd, 'Invalid destination directory.');
                    } else
                      array_unshift($prevcmd, 'Invalid source directory.');
                  } else
                    array_unshift($prevcmd, 'Directory already exists,'."\n".'[y] Merge directories/overwrite files'."\n".'[n] Merge directories do not overwrite files'."\n".'[c] Cancel');
                } else
                  array_unshift($prevcmd, 'Target: "'.$dest_loc.'" is not a valid directory.');
              }
            }
          } else
            array_unshift($prevcmd, 'Source file does not exist.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // wget downloads internet files
      if($cmdar[0] == 'wget'){
        if(count($cmdar) == 2)
          $cmdar[2] = get_name($cmdar[1]);
        if(count($cmdar) == 3){
          if(substr($cmdar[1], 0, 7) == 'http://' || substr($cmdar[1], 0, 8) == 'https://'
          || substr($cmdar[1], 0, 6) == 'ftp://'){
            $gfile = false;
            if($webfile = @file_get_contents(str_replace(' ', '%20', htmlspecialchars($cmdar[1]))))
              $gfile = true;
            if($gfile){
              if(substr($cmdar[2], 0, 1) == '/')
                $stloc1 = $cmdar[2];
              else
                $stloc1 = loc . $cmdar[2];
              if(!is_file(loc1 . $stloc1)){
                $fout = fopen(loc1 . $stloc1, 'w');
                $fp = fwrite($fout, $webfile);
                fclose($fout);
              } else
                array_unshift($prevcmd, 'The file "'.$stloc1.'" already exists.');
            } else
              array_unshift($prevcmd, 'Cannot access webfile.');
          } else
            array_unshift($prevcmd, 'Not a webfile. Address must start with http:// https:// or ftp://.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // rm deletes files
      if($cmdar[0] == 'rm'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          $rmerror = false;
          $files_ar = wild_card($stloc0, false);
          if(strtolower($_POST['cmd']) != 'y' && strtolower($_POST['cmd']) != 'c'){
            $size = 0;
            foreach($files_ar as $file)
              if(is_file(loc1 . $file))
                $size += filesize(loc1 . $file);
              else
                if(count($files_ar) == 1){
                  $rmerror = true;
                  array_unshift($prevcmd, 'File does not exist.');
                }
            if(!$rmerror)
              if($recycle)
                array_unshift($prevcmd, 'Delete file(s)? Files in recycle bin with same name will be'."\n".'perminantly deleted. File size: '.filesz($size).', are you sure?'."\n".'(Y/N/C -- C perminantly deletes the file now)');
              else
                array_unshift($prevcmd, 'Perminantly delete file(s)? File size: '.filesz($size).', are you sure? (Y/N)');
          } else {
            foreach($files_ar as $file){
              if($recycle && strtolower($_POST['cmd']) != 'c')
                move_recycle($file, '/filelist/.recycle/'.recycle_db('add', $file), true);
              else
                del($file);
            }
          }
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // rmdir deletes directories
      if($cmdar[0] == 'rmdir'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          if(strpos(strtolower($stloc0), 'filelist') === false && strpos(strtolower($stloc0), 'getid3') === false){
            //$files_ar = wild_card($stloc0, true, false);
            if(strtolower($_POST['cmd']) != 'y' && strtolower($_POST['cmd']) != 'c'){
              $number_of_dirs3  = 0;
              $number_of_files3 = 0;
              //foreach($files_ar as $file){
                clearscandir();
                scanfulldir(loc1 . $stloc0);
                $number_of_dirs3  += $number_of_dirs;
                $number_of_files3 += $number_of_files;
              //}
              if($number_of_dirs3 > 0 || $number_of_files3 > 0)
                if($recycle)
                  array_unshift($prevcmd, 'Directory is not empty, move all files and subdirectories to Recycle'."\n".'Bin? (Y/N/C -- C perminantly deletes the directory now)');
                else
                  array_unshift($prevcmd, 'Directory is not empty, delete all files and subdirectories? (Y/N)');
              else {
                //foreach($files_ar as $file)
                ddel($stloc0);
              }
            } else {
              //foreach($files_ar as $file)
              if($recycle && strtolower($_POST['cmd']) != 'c'){
                dirmv($stloc0, '/filelist/.recycle/'.recycle_db('add', $stloc0, true), true, true);
                @rmdir(loc1 . $stloc0);
              } else
                ddel($stloc0);
            }
          } else
            array_unshift($prevcmd, 'Invalid directory.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // ren renames files
      if($cmdar[0] == 'ren'){
        if(count($cmdar) == 3){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          if(strpos($cmdar[2], '/') === false && strpos($cmdar[2], '\\') === false){
            $stloc1 = $cmdar[2];
            ren($stloc0, $stloc1);
          } else
            array_unshift($prevcmd, 'Second argument must be a filename, not a path.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // mkdir creates directories
      if($cmdar[0] == 'mkdir'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          cdir($stloc0);
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

      if($cmdar[0] == 'prop'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          prop($stloc0);
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // set sets values to settings
      if($cmdar[0] == 'set'){
        if(count($cmdar) == 3){
          $settings_ar = file(loc1 . '/filelist/filelist-settings.php');
          $cmdar[1] = str_replace(' ', '_', trim($cmdar[1]));
          $done = false;
          if($cmdar[1] == 'line_break')
            $cmdar[2] = '"' . $cmdar[2] . '"';
          if($cmdar[1] == 'anonym_perm' && cont_non_num(trim($cmdar[2])))
            $cmdar[2] = '\''.trim($cmdar[2]).'\'';
          if($cmdar[1] == 'anonym_perm_type' && (substr(trim($cmdar[2]), 0, 1) != '\'' || substr(trim($cmdar[2]), -1) != '\'')){
            if(substr(trim($cmdar[2]), 0, 1) != '\'')
              $cmdar[2] = '\''.trim($cmdar[2]);
            if(substr(trim($cmdar[2]), -1) != '\'')
              $cmdar[2] = trim($cmdar[2]).'\'';
          }
          if($cmdar[1] == 'file_time' || $cmdar[1] == 'file_time_date' || $cmdar[1] == 'font_size' || $cmdar[1] == 'altern_color')
            $cmdar[2] = '\''.trim($cmdar[2]).'\'';
          for($i = 3; $i < count($settings_ar) - 1 && !$done; $i++){
            if(substr($settings_ar[$i], 1, strlen($cmdar[1])) == $cmdar[1] && substr($settings_ar[$i], strlen($cmdar[1]) + 1, 1) == ' '){
              $settings_ar[1] = '// ' . time() . "\n";
              $settings_ar[$i] = '$' . $cmdar[1] . ' = ' . trim($cmdar[2]) . ";\n";
              $done = true;
            }
          }
          if($done){
            $write = implode('', $settings_ar);
            $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
            $fp = fwrite($fout, $write);
            fclose($fout);
          } else
            array_unshift($prevcmd, 'No settings changed, check name or value.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // save saves the console log to a file
      if($cmdar[0] == 'save'){
        if(count($cmdar) == 2)
          $cmdar[2] = 'w';
        if(count($cmdar) == 3){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          if($cmdar[2] != 'a')
            $cmdar[2] = 'w';
          if($cmdar[2] == 'w' && is_file(loc1 . $stloc0))
            array_unshift($prevcmd, 'A file by this name already exists.');
          else {
            $write = implode($line_break, $prevcmd);
            $fout = fopen(loc1 . $stloc0, $cmdar[2]);
            $fp = fwrite($fout, $write . $line_break . $line_break);
            fclose($fout);
          }
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // view logged events
      if($cmdar[0] == 'viewlog'){
        if(count($cmdar) == 2){
          if($cmdar[1] < 1)
            $cmdar[1] = 1;
          $cmdar[2] = $cmdar[1];
        }
        if(count($cmdar) == 3){
          if(is_file(loc1 . '/filelist/filemanagelog.log')){
            $log_array = file(loc1 . '/filelist/filemanagelog.log');
            settype($cmdar[1], 'integer');
            settype($cmdar[2], 'integer');
            if($cmdar[1] > $cmdar[2]){
              $tmp = $cmdar[1];
              $cmdar[1] = $cmdar[2];
              $cmdar[2] = $tmp;
            }
            if($cmdar[2] > count($log_array))
              $cmdar[2] = count($log_array);
            for($i = $cmdar[1]; $i <= $cmdar[2]; $i++){
              $sub_array = explode('~~~~~', $log_array[$i - 1]);
              $lognum = 'Log#'.($i);
              while(strlen($lognum) < 10)
                $lognum .= ' ';
              $logdate = date("M d Y H:i", $sub_array[0]);
              while(strlen($logdate) < 18)
                $logdate .= ' ';
              $logipport = $sub_array[1];
              while(strlen($logipport) < 21)
                $logipport .= ' ';
              $log_file = 'File:'.$sub_array[5];
              if(strlen($log_file) > 32)
                $log_file = substr($log_file, 0, 30). '..';
              else
                while(strlen($log_file) < 32)
                  $log_file .= ' ';
              $loguser = 'User:'.$sub_array[2];
              if(strlen($loguser) > 16)
                $loguser = substr($loguser, 0, 14). '..';
              else
                while(strlen($loguser) < 16)
                  $loguser .= ' ';
              $logdesc = $sub_array[3];
              if(strlen($logdesc) > 64)
                $logdesc = substr($logdesc, 0, 62). '..';
              else
                while(strlen($logdesc) < 64)
                  $logdesc .= ' ';
              array_unshift($prevcmd, $lognum.$logdate.$logipport.$loguser.$log_file.$logdesc);
            }
          } else
            array_unshift($prevcmd, 'No logged events.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // view list of users and their info
      if($cmdar[0] == 'userlist'){
        if(count($cmdar) == 1){
          if(is_file(loc1 . '/filelist/filelist-logins.list')){
            $array_of_users = file(loc1 . '/filelist/filelist-logins.list');
            $num_of_users = count($array_of_users);
            //foreach($array_of_users as $user_name){
            for($i = $num_of_users - 1; $i >= 0; $i--){
              $user = trim($array_of_users[$i]);
              if(is_file(loc1 . '/filelist/filelist-'. $user .'.php')){
                $sub_array = file(loc1 . '/filelist/filelist-'. $user .'.php');
                $loguser = $user;
                if(strlen($loguser) > 31)
                  $loguser = substr($loguser, 0, 29). '..';
                else
                  while(strlen($loguser) < 31)
                    $loguser .= ' ';
                if(strlen(trim($sub_array[6])) > 0)
                  $logemail = trim($sub_array[6]);
                else
                  $logemail = 'Not Registered';
                if(strlen($logemail) > 32)
                  $logemail = substr($logemail, 0, 30). '..';
                else
                  while(strlen($logemail) < 32)
                    $logemail .= ' ';
                $logperms = trim($sub_array[4]);
                while(strlen($logperms) < 4)
                  $logperms .= ' ';
                $logpermt = trim($sub_array[5]);
                while(strlen($logpermt) < 5)
                  $logpermt .= ' ';
                array_unshift($prevcmd, $loguser.$logemail.$logperms.$logpermt);
              }
            }
            array_unshift($prevcmd, 'There are a total of '.$num_of_users.' users');
          } else
            array_unshift($prevcmd, 'Problem with user database.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // check if file(s) is an image via getimagesize()
      if($cmdar[0] == 'isimage'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          $files_ar = wild_card($stloc0, false);
          foreach($files_ar as $file){
            $ftype = get_ftype(loc1 . $file);
            if(($ftype == 'gif' || $ftype == 'jpg' || $ftype == 'jpeg'
            || $ftype == 'png' || $ftype == 'swf' || $ftype == 'swc'
            || $ftype == 'psd' || $ftype == 'tiff' || $ftype == 'bmp'
            || $ftype == 'iff' || $ftype == 'jp2' || $ftype == 'jpx'
            || $ftype == 'jb2' || $ftype == 'jpc' || $ftype == 'xbm'
            || $ftype == 'wbmp' || $ftype == 'tif' || $ftype == 'ico')){
              if(@getimagesize(loc1 . $file) !== false){
                if(function_exists('exif_read_data') && strpos($file, '\'') === false)
                  if(@exif_read_data(loc1 . $file, 'ANY_TAG') !== false)
                    array_unshift($prevcmd, $file . ' is an image and has EXIF data');
                  else
                    array_unshift($prevcmd, $file . ' is an image');
              } else
                array_unshift($prevcmd, $file . ' is NOT an image');
            }
          }
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // check if web file(s) is a PHP file by searching for PHP initiate and denitiate
      if($cmdar[0] == 'isphp'){
        if(count($cmdar) == 2){
          if(substr($cmdar[1], 0, 1) == '/')
            $stloc0 = $cmdar[1];
          else
            $stloc0 = loc . $cmdar[1];
          $files_ar = wild_card($stloc0, false);
          foreach($files_ar as $file){
            $ftype = get_ftype($file);
            if($ftype == 'php' || $ftype == 'php3' || $ftype == 'php4'
            || $ftype == 'php5' || $ftype == 'phtml' || $ftype == 'htm'
            || $ftype == 'html'){
              $filecont = file_get_contents(loc1 . $file);
              if(strpos($filecont, '<?PHP') !== false && strpos($filecont, '?>') !== false)
                array_unshift($prevcmd, $file . ' is PHP');
              else
                array_unshift($prevcmd, $file . ' is NOT PHP');
            }
          }
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // change user's password
      if($cmdar[0] == 'passwd'){
        if(count($cmdar) == 3 || count($cmdar) == 4){
          if(md5($cmdar[1]) == $pw){
            if(count($cmdar) == 3 || $cmdar[2] == $cmdar[3]){
              $array_of_user = file(loc1 . '/filelist/filelist-'. $un .'.php');
              $array_of_user[3] = md5($cmdar[2]) . $line_break;
              $write = implode('', $array_of_user);
              $fout = fopen(loc1 . '/filelist/filelist-'. $un .'.php', 'w');
              $fp = fwrite($fout, $write);
              fclose($fout);
              $_SESSION['password'] = md5($cmdar[2]);
              array_unshift($prevcmd, 'New password is set.');
            } else
              array_unshift($prevcmd, 'Arguments 2 and 3 do not match.');
          } else
            array_unshift($prevcmd, 'Argument 1 does not match current password.');
        } else {
          array_unshift($prevcmd, 'if password has quotes, the value cannot be changed in console).');
          array_unshift($prevcmd, 'Insufficient arguments (if password has spaces use quotes,');
        }
      } else

        // change user's email
      if($cmdar[0] == 'email'){
        if(count($cmdar) == 2){
          if(trim($cmdar[1]) != ''){
            $array_of_user = file(loc1 . '/filelist/filelist-'. $un .'.php');
            $array_of_user[6] = trim($cmdar[1]) . $line_break;
            $write = implode('', $array_of_user);
            $fout = fopen(loc1 . '/filelist/filelist-'. $un .'.php', 'w');
            $fp = fwrite($fout, $write);
            fclose($fout);
            array_unshift($prevcmd, 'New email is set.');
          } else
            array_unshift($prevcmd, 'Email address must have a value.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else

        // make File Manage like File List was
      if($cmdar[0] == 'makefilelist'){
        if(count($cmdar) == 2 && $cmdar[1] == 'c'){
          $settings_ar = file(loc1 . '/filelist/filelist-settings.php');
          $settings_ar[1] = '// ' . time() . "\n";
          for($i = 3; $i < count($settings_ar) - 1; $i++){
            if(substr($settings_ar[$i], 1, strlen('recycle')) == 'recycle' && substr($settings_ar[$i], strlen('recycle') + 1, 1) == ' ')
              $settings_ar[$i] = '$recycle = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('upload_bar')) == 'upload_bar' && substr($settings_ar[$i], strlen('upload_bar') + 1, 1) == ' ')
              $settings_ar[$i] = '$upload_bar = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('add_getid3')) == 'add_getid3' && substr($settings_ar[$i], strlen('add_getid3') + 1, 1) == ' ')
              $settings_ar[$i] = '$add_getid3 = 1;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('anonym_perm')) == 'anonym_perm' && substr($settings_ar[$i], strlen('anonym_perm') + 1, 1) == ' ')
              $settings_ar[$i] = '$anonym_perm = 6;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('name_length')) == 'name_length' && substr($settings_ar[$i], strlen('name_length') + 1, 1) == ' ')
              $settings_ar[$i] = '$name_length = 255;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('remember_org')) == 'remember_org' && substr($settings_ar[$i], strlen('remember_org') + 1, 1) == ' ')
              $settings_ar[$i] = '$remember_org = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('require_login')) == 'require_login' && substr($settings_ar[$i], strlen('require_login') + 1, 1) == ' ')
              $settings_ar[$i] = '$require_login = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('show_add_info')) == 'show_add_info' && substr($settings_ar[$i], strlen('show_add_info') + 1, 1) == ' ')
              $settings_ar[$i] = '$show_add_info = 1;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('force_download')) == 'force_download' && substr($settings_ar[$i], strlen('force_download') + 1, 1) == ' ')
              $settings_ar[$i] = '$force_download = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('show_file_time')) == 'show_file_time' && substr($settings_ar[$i], strlen('show_file_time') + 1, 1) == ' ')
              $settings_ar[$i] = '$show_file_time = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('allow_anonymous')) == 'allow_anonymous' && substr($settings_ar[$i], strlen('allow_anonymous') + 1, 1) == ' ')
              $settings_ar[$i] = '$allow_anonymous = 0;' . "\n";
            if(substr($settings_ar[$i], 1, strlen('anonym_perm_type')) == 'anonym_perm_type' && substr($settings_ar[$i], strlen('anonym_perm_type') + 1, 1) == ' ')
              $settings_ar[$i] = '$anonym_perm_type = \'basic\';' . "\n";
            if(substr($settings_ar[$i], 1, strlen('allow_login_request')) == 'allow_login_request' && substr($settings_ar[$i], strlen('allow_login_request') + 1, 1) == ' ')
              $settings_ar[$i] = '$allow_login_request = 0;' . "\n";
          }
          $write = implode('', $settings_ar);
          $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
          $fp = fwrite($fout, $write);
          fclose($fout);
        } else {
          array_unshift($prevcmd, 'To reverse this, you will need to manually open the'."\n".'/filelist/filelist-settings.php file and change the value of'."\n".'$require_login to 1.');
          array_unshift($prevcmd, 'This will prevent anyone from being able to login. Which means that all'."\n".'admin abilities and special features will also be unavailable.'."\n".'If you are sure you want to do this, type "makefilelist c".');
          //array_unshift($prevcmd, 'To not see this prompt next time, use "makefilelist c", all settings'."\n".'will be changed without this prompt.');
        }
      } else

        // getsettings displays current settings' values
      if($cmdar[0] == 'getsettings'){
        if(count($cmdar) == 1){
          array_unshift($prevcmd, '========================');
          array_unshift($prevcmd, 'display_new = ' . $display_new);
          array_unshift($prevcmd, 'display_updated = ' . $display_updated);
          array_unshift($prevcmd, 'new_time_secs = ' . $new_time_secs);
          array_unshift($prevcmd, 'error_spacer = ' . $error_spacer);
          array_unshift($prevcmd, 'error_spacer2 = ' . $error_spacer2);
          array_unshift($prevcmd, 'show_all_stats = ' . $show_all_stats);
          array_unshift($prevcmd, 'organize_ord = ' . $organize_ord);
          array_unshift($prevcmd, 'show_add_info = ' . $show_add_info);
          array_unshift($prevcmd, 'add_getid3 = ' . $add_getid3);
          array_unshift($prevcmd, 'force_download = ' . $force_download);
          array_unshift($prevcmd, 'show_file_time = ' . $show_file_time);
          array_unshift($prevcmd, 'file_time = ' . $file_time);
          array_unshift($prevcmd, 'file_time_date = ' . $file_time_date);
          array_unshift($prevcmd, 'require_login = ' . $require_login);
          array_unshift($prevcmd, 'allow_anonymous = ' . $allow_anonymous);
          array_unshift($prevcmd, 'auto_anonym_login = ' . $auto_anonym_login);
          array_unshift($prevcmd, 'anonym_perm = ' . $anonym_perm);
          array_unshift($prevcmd, 'anonym_perm_type = \'' . $anonym_perm_type . '\'');
          if($line_break == "\r\n") $lb = '\r\n'; elseif($line_break == "\r")
            $lb = '\r'; else $lb = '\n';
          array_unshift($prevcmd, 'line_break = ' . $lb);
          array_unshift($prevcmd, 'auto_icon = ' . $auto_icon);
          array_unshift($prevcmd, 'logging_level = ' . $logging_level);
          array_unshift($prevcmd, 'font_size = ' . $font_size);
          array_unshift($prevcmd, 'name_length = ' . $name_length);
          array_unshift($prevcmd, 'trunc_offset = ' . $trunc_offset);
          array_unshift($prevcmd, 'recycle = ' . $recycle);
          array_unshift($prevcmd, 'altern_line_color = ' . $altern_line_color);
          array_unshift($prevcmd, 'altern_color = ' . $altern_color);
          array_unshift($prevcmd, 'max_log_size = ' . $max_log_size);
          array_unshift($prevcmd, 'upload_bar = ' . $upload_bar);
          array_unshift($prevcmd, 'all_upload_bar = ' . $all_upload_bar);
          array_unshift($prevcmd, 'allow_login_request = ' . $allow_login_request);
          array_unshift($prevcmd, 'remember_org = ' . $remember_org);
          array_unshift($prevcmd, 'admin_see_hidden = ' . $admin_see_hidden);
          array_unshift($prevcmd, 'track_time = ' . $track_time);
          array_unshift($prevcmd, 'max_track_size = ' . $max_track_size);
          array_unshift($prevcmd, 'show_dir_size = ' . $show_dir_size);
          array_unshift($prevcmd, 'show_file_hash = ' . $show_file_hash);
          array_unshift($prevcmd, 'hash_size = ' . $hash_size);
          array_unshift($prevcmd, 'show_exif_thumb = ' . $show_exif_thumb);
          array_unshift($prevcmd, 'strong_pw_enforce = ' . $strong_pw_enforce);
          array_unshift($prevcmd, 'illegal_words = \'' . implode('\',\'',$illegal_words) . '\'');
          array_unshift($prevcmd, '========================');
          array_unshift($prevcmd, 'If value is blank, it is set to false.');
/*$display_new
$display_updated
$new_time_secs
$error_spacer
$error_spacer2
$show_all_stats
$organize_ord
$show_add_info
force_download
$require_login
$allow_anonymous
$auto_anonym_login
$anonym_perm
$anonym_perm_type
$line_break
$auto_icon
$logging_level
$illegal_words
$font_size
$name_length
upload_bar
all_upload_bar
allow_login_request
remember_org
admin_see_hidden
track_time
max_track_size
show_dir_size
show_file_hash
hash_size
show_exif_thumb
strong_pw_enforce
$trunc_offset*/
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else
        // getsettings displays current settings' values
      if($cmdar[0] == 'settingshelp'){
        if(count($cmdar) == 1){
          array_unshift($prevcmd, '========================');
          array_unshift($prevcmd, 'display_new; bool: display when a file is new');
          array_unshift($prevcmd, 'display_updated; bool: display when a file is updated');
          array_unshift($prevcmd, 'new_time_secs; int/math: time in seconds for a file to be new/updated');
          array_unshift($prevcmd, 'error_spacer; float: grace for a word search');
          array_unshift($prevcmd, 'error_spacer2; float: grace for a phrase search');
          array_unshift($prevcmd, 'show_all_stats; bool: show/update statistics listed at bottom of page');
          array_unshift($prevcmd, 'organize_ord; bool: when organizing, remove "a"/"an"/"the" from start of name');
          array_unshift($prevcmd, 'show_add_info; bool: show extra file information when available');
          array_unshift($prevcmd, 'add_getid3; bool: Media information will get displayed for media files in the Additional Info column when GetID3 is installed');
          array_unshift($prevcmd, 'force_download; bool: 0 - browser default; 1 - icon download, name/link is default; 2 - force download');
          array_unshift($prevcmd, 'show_file_time; bool: show the updated or created time of files or directories');
          array_unshift($prevcmd, 'file_time; m OR c: m shows modified time of files and directories, c show created time');
          array_unshift($prevcmd, 'file_time_date; date() format: http://www.php.net/manual/en/function.date.php for instructions');
          array_unshift($prevcmd, 'require_login; bool: disabling removes all login features (can only be re-enabled with direct access to settings file)');
          array_unshift($prevcmd, 'allow_anonymous; bool: allow users to have limited access without loggin in');
          array_unshift($prevcmd, 'auto_anonym_login; bool: when first visiting, users is automatically logged in as anonmyous');
          array_unshift($prevcmd, 'anonym_perm; int/hex: permission value for anonymous users');
          array_unshift($prevcmd, 'anonym_perm_type; str: \'basic\' or \'hex\'');
          array_unshift($prevcmd, 'line_break; line break str: "\n", "\r", or "\r\n" -- line break type');
          array_unshift($prevcmd, 'auto_icon; bool: use File Manage\'s automoatic icon matcher');
          array_unshift($prevcmd, 'logging_level; int: -1, 0, 1, 2, 3, or 4 -- higher value, more logs generated');
          array_unshift($prevcmd, 'font_size; int: font size for additional info and tools');
          array_unshift($prevcmd, 'name_length; int: max length of file and directory names before truncation');
          array_unshift($prevcmd, 'trunc_offset; int: number of letters after truncation of file/dir name');
          array_unshift($prevcmd, 'recycle; bool: when files are "deleted" are that moved to the recycle bin (false will perminantly delete them)');
          array_unshift($prevcmd, 'altern_line_color; bool: turn off and on the alternating line color');
          array_unshift($prevcmd, 'max_log_size; int KB: The size in KB that the log file will not excede');
          array_unshift($prevcmd, 'upload_bar; bool: this enables the Perl upload progress bar for admins, Perl must be installed with the CGI module');
          array_unshift($prevcmd, 'all_upload_bar; bool: this enables the Perl upload progress bar for non-admin users (requires upload_bar)');
          array_unshift($prevcmd, 'allow_login_request; bool: this makes it possible for users who are not registered users to request to become one');
          array_unshift($prevcmd, 'remember_org; bool: allows users\' organization preferences to be remembered next time they visit the same directory');
          array_unshift($prevcmd, 'admin_see_hidden; bool; changes the display of hidden files/dirs to admins (they can see them either way when they manage them)');
          array_unshift($prevcmd, 'track_time; bool: setting controlls the Fitness tracking to help assess performance problems');
          array_unshift($prevcmd, 'max_track_size; int KB: The size in KB that the Fitness tracking log can be');
          array_unshift($prevcmd, 'show_dir_size; bool; Display directory volume in file list and display number of files and directories in additional info column');
          array_unshift($prevcmd, 'show_file_hash; bool: Display or don\'t display the MD5 and SHA1 hashes in the properites window');
          array_unshift($prevcmd, 'hash_size; int MB: Up to what file size to display the hashes involuntarily in the properties window');
          array_unshift($prevcmd, 'show_exif_thumb; bool: In file list, show exif thumbnails is available');
          array_unshift($prevcmd, 'strong_pw_enforce; bool: require new users to have a "strong password", at least 8 characters and two types of characters');
          array_unshift($prevcmd, 'illegal_words; array: list of unacceptable words when uploading/editing');
          array_unshift($prevcmd, '========================');
          array_unshift($prevcmd, '"bool" actually refers to "bool or int" where int is 0 for false, and any other value is true.');
        } else
          array_unshift($prevcmd, 'Insufficient arguments.');
      } else
        // displays some info :-)
      if(strtolower($cmdar[0]) == 'bobb' || strtolower($cmdar[0]) == 'bob' || strtolower($cmdar[0]) == 'fwed' || strtolower($cmdar[0]) == 'creator'){
        array_unshift($prevcmd, 'Brandon Nimon (AKA Bobb Bob Fwed) bobbfwed@comcast.net');
        echo '<br><br><br>';
      } else
        // help displays list of commands with description
      if(strtolower($cmdar[0]) == 'help'){
        array_unshift($prevcmd, 'Available commands:');
        array_unshift($prevcmd, 'cd           -- change directory');
        array_unshift($prevcmd, 'clear        -- clear the console log');
        array_unshift($prevcmd, 'cp           -- copy a file or directory');
        array_unshift($prevcmd, 'email        -- change your email');
        array_unshift($prevcmd, 'exit         -- exit console (back to list)');
        array_unshift($prevcmd, 'file         -- displays file path');
        array_unshift($prevcmd, 'getsettings  -- view current system settings');
        array_unshift($prevcmd, 'help2        -- view commands with syntax');
        array_unshift($prevcmd, 'isimage      -- check if file is an image');
        array_unshift($prevcmd, 'isphp        -- check if web file is a PHP file');
        array_unshift($prevcmd, 'logout       -- logout');
        array_unshift($prevcmd, 'ls           -- view list in directory');
        array_unshift($prevcmd, 'makefilelist -- removes features so it beheives like File List');
        array_unshift($prevcmd, 'mkdir        -- create a directory');
        array_unshift($prevcmd, 'mv           -- move a file or directory');
        array_unshift($prevcmd, 'passwd       -- change your password');
        array_unshift($prevcmd, 'prop         -- get properties of a file');
        array_unshift($prevcmd, 'ren          -- rename file or directory');
        array_unshift($prevcmd, 'rm           -- delete a file');
        array_unshift($prevcmd, 'rmdir        -- delete a directory');
        array_unshift($prevcmd, 'save         -- save current console log to file');
        array_unshift($prevcmd, 'set          -- change a system setting');
        array_unshift($prevcmd, 'settingshelp -- view explaination of setting variables');
        array_unshift($prevcmd, 'userlist     -- get list of current users and their info');
        array_unshift($prevcmd, 'viewlog      -- view a range of logged event');
        array_unshift($prevcmd, 'wget         -- download a file from the internet');
      } else
        // help2 displays list of commands with syntax
      if(strtolower($cmdar[0]) == 'help2'){
        array_unshift($prevcmd, 'Available commands:');
        array_unshift($prevcmd, '("[]" are not typed; "[dir]" and "[file]" can represent a path)');
        array_unshift($prevcmd, 'cd [dir]');
        array_unshift($prevcmd, 'clear');
        array_unshift($prevcmd, 'cp [dir or file] [dir] -- [dir] is optional');
        array_unshift($prevcmd, 'email [new email]');
        array_unshift($prevcmd, 'exit');
        array_unshift($prevcmd, 'file [file]');
        array_unshift($prevcmd, 'getsettings');
        array_unshift($prevcmd, 'isimage [file]');
        array_unshift($prevcmd, 'isphp [file]');
        array_unshift($prevcmd, 'logout');
        array_unshift($prevcmd, 'ls [dir] -- [dir] is optional');
        array_unshift($prevcmd, 'makefilelist [conf] -- [conf] only enter this if you have run this function before');
        array_unshift($prevcmd, 'mkdir [dir]');
        array_unshift($prevcmd, 'mv [dir or file] [dir]');
        array_unshift($prevcmd, 'passwd [old password] [new password] [confirm new password] -- confirmation is optional');
        array_unshift($prevcmd, 'prop [dir or file]');
        array_unshift($prevcmd, 'ren [file] [new name]');
        array_unshift($prevcmd, 'rm [file]');
        array_unshift($prevcmd, 'rmdir [dir]');
        array_unshift($prevcmd, 'save [file] [a/w] -- [a/w] is optional and stands for append or write (new file)');
        array_unshift($prevcmd, 'set [setting name] [new value]');
        array_unshift($prevcmd, 'settingshelp');
        array_unshift($prevcmd, 'userlist');
        array_unshift($prevcmd, 'viewlog -- viewlog [range start] [range end] -- [range end] is optional');
        array_unshift($prevcmd, 'wget [web file] [file] -- [file] is optional');
        echo '<br><br><br>';
      } elseif(is_file(loc1 . '/filelist/console_'.strtolower($cmdar[0]).'.php')){
        echo '<hr><i>Executing '.strtolower($cmdar[0]).'</i><br>';
        include(loc1 . '/filelist/console_'.strtolower($cmdar[0]).'.php');
        echo '<hr><br>';
      } else {
          // if these commands are used don't display "unknown command"
        if($cmdar[0] != 'cd' && $cmdar[0] != 'ls' && strlen($_POST['cmd']) > 1)
          array_unshift($prevcmd, 'Unknown command or invalid console expansion ('. $cmdar[0] .'), type "help" for available commands');
      }
    } else
      $cmd = NULL;

      // when the page loads put focus on the command line (so you don't have to click on it)
    echo '<body onLoad="document.console.cmd.focus();">';

    echo 'File Manage console '.note(13, 200, 220);
    echo '<form name="console" method="post" action="'.phpSelf.'?loc='.locenc.'&console=1">';
    echo '<input type="text" size="60" maxsize="255" name="cmd" onKeyUp="hidepasswd(this)" value=""><br>';
    echo '<script type="text/JavaScript">
  function hidepasswd(input){
    if(input.value.substr(0, 7) == "passwd "){
      document.console.cmd.type = "password";
    } else {
      if(document.console.cmd.type == "password"){
        document.console.cmd.type = "text";
      }
    }
  }
</script>';
    echo '<input type="submit" value="Send Command"><br>';
    echo '<textarea readonly cols="70" rows="20" wrap="off">';
    if(isset($prevcmd) && is_array($prevcmd))
      foreach($prevcmd as $pcmd)
        echo htmlspecialchars($pcmd) . "\n";
      echo '</textarea><br>';
    if(isset($prevcmd) && is_array($prevcmd)){
        // 75 is the number commands to save
      if(count($prevcmd) > 75)
        $oldcmds = 75;
      else
        $oldcmds = count($prevcmd);
      for($i = 0; $i < $oldcmds; $i++)
        echo '<input type="hidden" value="'.htmlspecialchars($prevcmd[$i]).'" name="prevcmd[]">';
    }
    echo '</form>';

  } else



    // manage icon associations
  if(isset($_GET['customicon']) && $admin){

    if(isset($_POST['commit'])){
      $settings_ar = file(loc1 . '/filelist/filelist-settings.php');

      foreach($_POST as $type => $src){
        if(substr($type, 0, 3) == 'set'){
          $type = substr($type, 3);
          $type = str_replace('_', '.', $type);
          if(magicQuotes){
            $new_accept[] = stripslashes($type);
            $new_iconlink[] = stripslashes($src);
          } else {
            $new_accept[] = $type;
            $new_iconlink[] = $src;
          }
        }
      }

      $j = count($settings_ar);
      $settings_ar[$j - 4] = '$accept            = array(\''. implode('\',\'', $new_accept) .'\');' . "\n";
      $settings_ar[$j - 3] = '$iconlink          = array(\''. implode('\',\'', $new_iconlink) .'\');' . "\n";

      if($auto_icon){
        $done = false;
        for($i = 3; $i < $j - 3 && !$done; $i++){
          if(substr($settings_ar[$i], 0, strlen('$auto_icon ')) == '$auto_icon '){
            $settings_ar[$i] = '$auto_icon = 0;'."\n";
            $done = true;
          }
        }
      }

      $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
      $fp = fwrite($fout, implode('', $settings_ar));
      fclose($fout);

      writelog('Admin updated the custom icon list.', 'icon', 'none');

      echo '<script language="JavaScript">';
      // the genius JavaScript function name below originally coined by Bradley Hart!
      echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes(loc).'&customicon=1\',1)';
      echo '</script>';
      die();
    } elseif(isset($_GET['add'])){

      if(isset($_POST['addext'])){
        $addext_str = $_POST['addext'];
        $src_str = $_POST['src'];
        if($addext_str != '.' && ($addext_str != '' || !$accept_all) && $src_str != ''){
          $settings_ar = file(loc1 . '/filelist/filelist-settings.php');

          if($addext_str != ''){
            $found = false;
            for($i = 0; $i < count($accept); $i++){
              if($found){
                $new_accept[] = $accept[$i];
                $new_iconlink[] = $iconlink[$i];
              } else {
                if($_GET['add'] != $accept[$i]){
                  $new_accept[] = $accept[$i];
                  $new_iconlink[] = $iconlink[$i];
                } else {
                  $new_accept[] = $addext_str;
                  $new_iconlink[] = $src_str;
                  $found = true;
                  $i--;
                }
              }
            }
          } else {
            $new_accept = $accept;
            $new_iconlink = $iconlink;
            array_push($new_accept, '');
            array_push($new_iconlink, $src_str);
          }

          $j = count($settings_ar);
          $settings_ar[$j - 4] = '$accept            = array(\''. implode('\',\'', $new_accept) .'\');' . "\n";
          $settings_ar[$j - 3] = '$iconlink          = array(\''. implode('\',\'', $new_iconlink) .'\');' . "\n";

          if($auto_icon){
            $done = false;
            for($i = 3; $i < $j - 3 && !$done; $i++){
              if(substr($settings_ar[$i], 0, strlen('$auto_icon ')) == '$auto_icon '){
                $settings_ar[$i] = '$auto_icon = 0;'."\n";
                $done = true;
              }
            }
          }

          $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
          $fp = fwrite($fout, implode('', $settings_ar));
          fclose($fout);

          writelog('Admin added an extension ('.$addext_str.') to the accept array.', 'icon', 'none');

          echo '<script language="JavaScript">';
          // the genius JavaScript function name below originally coined by Bradley Hart!
          echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes(loc).'&customicon=1&add='.addslashes($_GET['add']).'&added=1\',1)';
          echo '</script>';
          die();
        } else
          echo '<font color="red">You need to fill out the form completely.</font><br>';
      }

      if(isset($_GET['added']))
        echo '<font color="red">Extension has been added</font><br>';

      if(!isset($addext_str))
        $addext_str = '.';
      if(!isset($src_str))
        $src_str = 'icons/unknown.gif';

      echo '<form name="addext" method="post" action="'.phpSelf.'?loc='.locenc.'&customicon=1&add='.$_GET['add'].'">';
      echo '<table cellpadding="3" cellspacing="0" border="0"><tr><td>Extension</td><td>Icon SRC</td><td></td><td></td></tr>';
      echo '<tr><td><input type="text" size="20" maxlength="128" name="addext" value="'.$addext_str.'"></td>';
      echo '<td><input type="text" size="30" maxlength="1024" name="src" value="'.htmlspecialchars($src_str).'"></td>';
      echo '<td><input type="submit" name="submit" value="Add Extension"></td>';
      echo '<td><input type="button" onClick="javascript:location.href=\''.phpSelf.'?loc='.locenc.'&customicon=1\'" value="';
      if(isset($_POST['addext']))
        echo 'Done';
      else
        echo 'Cancel';
      echo '"></td></tr>';
      echo '</table></form><br><br>';

    } elseif(isset($_GET['del'])){

      $settings_ar = file(loc1 . '/filelist/filelist-settings.php');

      foreach($accept as $i => $type){
        if($_GET['del'] != $type){
          $new_accept[] = $type;
          $new_iconlink[] = $iconlink[$i];
        }
      }

      $j = count($settings_ar);
      $settings_ar[$j - 4] = '$accept            = array(\''. implode('\',\'', $new_accept) .'\');' . "\n";
      $settings_ar[$j - 3] = '$iconlink          = array(\''. implode('\',\'', $new_iconlink) .'\');' . "\n";

      if($auto_icon){
        $done = false;
        for($i = 3; $i < $j - 3 && !$done; $i++){
          if(substr($settings_ar[$i], 0, strlen('$auto_icon ')) == '$auto_icon '){
            $settings_ar[$i] = '$auto_icon = 0;'."\n";
            $done = true;
          }
        }
      }

      $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
      $fp = fwrite($fout, implode('', $settings_ar));
      fclose($fout);

      writelog('Admin deleted an extension from the accept array.', 'icon', 'none');

      echo '<script language="JavaScript">';
      // the genius JavaScript function name below originally coined by Bradley Hart!
      echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes(loc).'&customicon=1\',1)';
      echo '</script>';
      die();
    } elseif(isset($_GET['default'])){
      if(!isset($_GET['conf'])){
        echo '<div align="center"><font color="red">Are you sure you want to reset all extensions and their icons back to default?</font><br>';
        echo '<table cellpadding="3" cellspacing="0" border="0" width="200"><tr>';
        echo '<td><a href="'.phpSelf.'?loc='.locenc.'&customicon=1&default=1&conf=1">Yes</a></td><td align="right"><a href="'.phpSelf.'?loc='.locenc.'&customicon=1">No</a></td></tr></table></div>';
      } else {
        $settings_ar = file(loc1 . '/filelist/filelist-settings.php');

        $j = count($settings_ar);
        $settings_ar[$j - 4] = "\n";
        $settings_ar[$j - 3] = "\n";

        if(!$auto_icon){
          $done = false;
          for($i = 3; $i < $j - 3 && !$done; $i++){
            if(substr($settings_ar[$i], 0, strlen('$auto_icon ')) == '$auto_icon '){
              $settings_ar[$i] = '$auto_icon = 1;'."\n";
              $done = true;
            }
          }
        }

        $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
        $fp = fwrite($fout, implode('', $settings_ar));
        fclose($fout);

        writelog('Admin set all icons and extensions back to default.', 'icon', 'none');

        echo '<script language="JavaScript">';
        // the genius JavaScript function name below originally coined by Bradley Hart!
        echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes(loc).'&customicon=1\',1)';
        echo '</script>';
        die();
      }
    }

    echo '<h3>Setup Custom Icon Association</h3>';
    echo '<u>Instructions:</u><br>';
    echo 'The column on the left is the current list of acceptable extensions to display in the file list. If there is a blank cell for the very last entry (which, currently, is';
    if(!$accept_all)
      echo ' not';
    echo ' the case) then if the extension is not listed, it will be displayed anyway. A blank cell will make it so all extensions are acceptable. When a file appears in the file list, it will use the icon associated with it (in this list), and if it is not found in the list, it will use the blank cell\'s icon.<br>';
    echo 'On the right are a couple lists of available icons for use. You can upload icons, or if you enter the correct icon directory path (relative or absolute), there will be a list of the server\'s icons which are available. To change an extension\'s icon association, just enter in the icon\'s correct path (relative to the File Manage file). You can copy and paste the "Icon SRC" path from the columns on the right into the "New SRC" column on the left.<br>';
    echo 'You can add more extensions to associate icons with by clicking the "Add" link, which will add an extension above the row in which it was clicked. Also you can delete extensions by clicking the "Del" link in the row you want to delete.<br><br>';
    echo '<table cellpadding="5" cellspacing="0" border="0" align="center"><tr><th rowspan="2" valign="top">';
    echo '<form name="customicon" method="post" action="'.phpSelf.'?loc='.locenc.'&customicon=1">';
    echo '<table cellpadding="3" cellspacing="0" border="1" bgcolor="#50ff50"><tr><td></td><td>Type</td><td>Icon SRC</td><td>Icon</td><td>New SRC</td><td>Action</td></tr>';
    foreach($accept as $i => $type){
      echo '<tr><td>'.($i + 1).'</td><td>'.$type.'</td><td>'.htmlspecialchars($iconlink[$i]).'</td><td align="center"><img src="'.$iconlink[$i].'" /></td>';
      echo '<td><input type="text" size="15" maxlength="1024" name="set'.htmlspecialchars($type).'" value="'.htmlspecialchars($iconlink[$i]).'" /></td>';
      echo '<td><a title="Delete extension from list" href="'.phpSelf.'?loc='.locenc.'&customicon=1&del='.$type.'">Del</a> ';
      echo '<a title="Add extension to list (above this one)" href="'.phpSelf.'?loc='.locenc.'&customicon=1&add='.$type.'">Add</a></td></tr>';
    }
    echo '</table>';
    echo '<input type="submit" value="Commit Changes" name="commit"> ';
    echo '<input type="reset" value="Reset Values"> ';
    echo '<input type="button" onClick="javascript:location.href=\''.phpSelf.'?loc='.locenc.'&customicon=1&default=1\'" value="Reset All to Default">'.note(24, 180, 260);
    echo '</form>';
    echo '</th><td width="40"></td><td align="right" valign="top">';

    echo '<form name="uploaddata" enctype="multipart/form-data" action="'.phpSelf.'?loc='.locenc.'&customicon=1" method="post">';
    if(!is_dir('filelist/filelist-icons/'))
      mkdir('filelist/filelist-icons/');
    if(isset($_FILES['userfile_0'])){
      for($i = 0; $i < 5; $i++){
        if(isset($_FILES['userfile_'.$i]) && trim($_FILES['userfile_'.$i]['name'] != '')){
          $filename = $_POST['filename_'.$i];

          if($_FILES['userfile_'.$i]['name'] != '' && $_FILES['userfile_'.$i]['size'] > 0){
            if($filename == '' || check_name($filename)){
              if($filename == '' && strlen($_FILES['userfile_'.$i]['name']) < 255 && check_name($_FILES['userfile_'.$i]['name']))
                $filename = $_FILES['userfile_'.$i]['name'];
              if(magicQuotes)
                $filename = stripslashes($filename);
              if($filename != '' && !is_file('filelist/filelist-icons/' . $filename)){
                $ftype = get_ftype($filename);
                if($_FILES['userfile_'.$i]['type'] == 'image/jpeg' || $_FILES['userfile_'.$i]['type'] == 'image/jpg' || $_FILES['userfile_'.$i]['type'] == 'image/gif'){
                  if($ftype == 'gif' || $ftype == 'jpg' || $ftype == 'jpeg'){
                    $tmp_file = file_get_contents($_FILES['userfile_'.$i]['tmp_name']);
                    if(move_uploaded_file($_FILES['userfile_'.$i]['tmp_name'], 'filelist/filelist-icons/' . $filename)){
                      echo '<font color="red">File ('.$filename.') successfully uploaded.</font><br>';
                      writelog('Admin uploaded an icon', 'icon', 'filelist/filelist-icons/' . $filename, 3);
                    } else {
                      echo '<font color="red">The file ('.$filename.') could not be uploaded. This may be due to permission problems or the file is too large.</font><br>';
                      writelog('<font color="red">Admin tried to upload an icon, but it failed (may be due to permission problems or the file is too large)</font>', 'icon', 'filelist/filelist-icons/' . $filename);
                    }
                  } else
                    echo $filename.' has invalid extension.<br>';
                } else
                  echo $_FILES['userfile_'.$i]['type'].' type is not supported.<br>';
              } else
               echo '<font color="red">A file with file name '.$filename.' already exists.</font><br>';
            } else
              echo 'File name ('.$filename.') is not acceptable.<br>';
          } else {
            echo '<font color="red">Invalid file. Invalid name or size. ('.$filename.')</font><br>';
            writelog('<font color="red">Admin tried to upload an icon, but it failed (Invalid file. Invalid name or size)</font>', 'icon', 'filelist/filelist-icons/' . $filename);
          }
        } // if(isset($_FILES['userfile_'.$i]) && trim($_FILES['userfile_'.$i]['name'] != ''))
      } // for($i = 0; $i < 5; $i++)
    } // if(isset($_FILES['userfile_0']))

    $max_ul_sizemb = 0;
    $max_ul_sizekb = 0;

    $umfs = ini_get('upload_max_filesize');
    if(strtolower(substr($umfs, -1)) == 'm'){
      $max_ul_sizemb = substr($umfs, 0, -1);
      $max_ul_sizekb = $max_ul_sizemb * 1024;
    } else
    if(strtolower(substr($umfs, -1)) == 'k'){
      $max_ul_sizekb = substr($umfs, 0, -1);
      $max_ul_sizemb = round(($max_ul_sizekb / 1024), 2);
    }
    if($max_ul_sizekb != 0)
      $max_ul_sizebt = $max_ul_sizekb * 1024 - 1;
    else
      $max_ul_sizebt = 0;

    if(!isset($filename_0))
      $filename_0 = NULL;

    echo '<input type="hidden" name="MAX_FILE_SIZE" value="'.$max_ul_sizebt.'"><br>';
    echo '<table cellpadding="3" cellspacing="0" border="0"><tr><td>File location.</td><td>Change file name<br>(include extension)</td></tr>';
    for($i = 0; $i < 5; $i++){
      echo '<tr><td><input name="userfile_'.$i.'" size="20" type="file"></td>';
      echo '<td><input type="text" size="15" maxlength="255" name="filename_'.$i.'" value=""></td></tr>';
    }
    echo '</table>';
    echo '<br><font size="-1">Total file size must be less than '.$max_ul_sizekb.' KB ('.$max_ul_sizemb.' MB)</font><br>';
    echo '<font size="-1">Needs to be a .jpg, .jpeg, or .gif file with the correct mime type.<br>It must be less than 32 pixels tall and wide.</font><br>';
    echo '<input type="submit" value="Upload File(s)"><br><br>';

      // end of OSP code
    echo '</form>';

    if(isset($_GET['delicon'])){
      $del = $_GET['delicon'];
      if(is_file($del)){
        if(unlink($del)){
          echo '<font color="red">File has been deleted.</font>';
          writelog('Admin deleted an icon.', 'icon', 'filelist/filelist-icons/' . $del);
        } else {
          echo '<font color="red">File could not be deleted, may be a permissions problem.</font>';
          writelog('<font color="red">Admin tried to deleted an icon, but it failed. Likely a permissions problem.</font>', 'icon', 'filelist/filelist-icons/' . $del, 1);
        }
      } else
        echo '<font color="red">File does not exist, it may have already been deleted.</font><br>';
    }

    if(is_dir('filelist/filelist-icons/')){
      $icons_ar = glob('filelist/filelist-icons/*.gif');
      $icons_ar = array_merge($icons_ar, glob('filelist/filelist-icons/*.jpg'));
      $icons_ar = array_merge($icons_ar, glob('filelist/filelist-icons/*.jpeg'));
      $icons_ar = array_merge($icons_ar, glob('filelist/filelist-icons/*.GIF'));
      $icons_ar = array_merge($icons_ar, glob('filelist/filelist-icons/*.JPG'));
      $icons_ar = array_merge($icons_ar, glob('filelist/filelist-icons/*.JPEG'));
      if(count($icons_ar) > 0){
        echo '<table cellpadding="3" cellspacing="0" border="1" bgcolor="#505050"><tr><td>Icon SRC</td><td>Icon</td><td>Action</td></tr>';
        foreach($icons_ar as $icon){
          if($imageinfo = @getimagesize($icon)){
            if($imageinfo[0] < 32 && $imageinfo[1] < 32 && ($imageinfo[2] == 1 || $imageinfo[2] == 2) && ($imageinfo['channels'] == 3 || $imageinfo['channels'] == 2))
              echo '<tr><td>'.htmlspecialchars($icon).'</td><td align="center"><img src="'.$icon.'" /></td><td><a title="Delete custom icon" href="'.phpSelf.'?loc='.locenc.'&customicon=1&delicon='.$icon.'">Del</a></td></tr>';
            else {
              echo '<font color="red">Image ('.$icon.') file<br>removed because it did not meet specifications.</font><br>';
              @unlink($icon);
            }
          } else {
            echo '<font color="red">File ('.$icon.') removed because it did not have image information.</font><br>';
            @unlink($icon);
          }
        }
        echo '</table><br><br>';
      }
    }
    echo '</td></tr><tr><td width="40"></td><td valign="top" align="right">';

    if(isset($_POST['icondir'])){
      if(realpath($_POST['icondir'])){
        if(magicQuotes)
          $icon_loc = stripslashes(trim($_POST['icondir']));
        else
          $icon_loc = trim($_POST['icondir']);
        $fout = fopen(loc1 . '/filelist/filelist-icondir.list', 'w');
        $fp = fwrite($fout, $icon_loc . "\n");
        fclose($fout);
      } else {
        echo 'The directory, '.trim($_POST['icondir']).', does not exist.<br>';
        $icon_loc = '';
      }
    } elseif(is_file(loc1 . '/filelist/filelist-icondir.list')){
      $icon_loc_file = file(loc1 . '/filelist/filelist-icondir.list');
      $icon_loc = trim($icon_loc_file[0]);
    } else {
      if(is_dir('../../../icons/'))    // automaticall detect if two directories up...
        $icon_loc = '../../../icons/'; // e.g.: Apache/htdocs/1/2/filemanage.php will find icons dir
      else if(is_dir('./icons/'))    // automaticall detect if one directories down...
        $icon_loc = './icons/'; // e.g.: Apache/htdocs/1/2/filemanage.php will find icons dir
      elseif(is_dir('../../icons/')) // automaticall detect if one directories up...
        $icon_loc = '../../icons/';  // e.g.: Apache/htdocs/1/filemanage.php will find icons dir
      elseif(is_dir('../icons/')) // automaticall detect if in root directory...
        $icon_loc = '../icons/';  // e.g.: Apache/htdocs/filemanage.php will find icons dir
      elseif(is_dir('icons/')) // automaticall detect if in ?same director?...
        $icon_loc = 'icons/';  // e.g.: Apache/filemanage.php will find icons dir
      else
        $icon_loc = '';
    }

    echo '<form name="icondir" method="post" action="'.phpSelf.'?loc='.locenc.'&customicon=1">';
    echo 'If this is not the correct icons directory,<br>please enter the correct one instead.<br>';
    echo '<input type="text" size="30" name="icondir" maxlength="1024" value="'.$icon_loc.'" />';
    echo '<input type="submit" value="Change Dir" name="icon_loc_submit" />';
    echo '</form>';
    if(trim($icon_loc) != ''){
      $real_path = realpath(trim($icon_loc));
      echo 'List in '.$real_path;
      $icons_ar = glob(realpath($icon_loc).'/*.gif');
      array_push($icons_ar, glob(realpath($icon_loc).'/*.jpg'));
      if(count($icons_ar) > 0){
        echo '<table cellpadding="3" cellspacing="0" border="1" bgcolor="#505050"><tr><td>Icon SRC</td><td>Icon</td></tr>';
        foreach($icons_ar as $icon){
          if($imageinfo = @getimagesize($icon)){
            $icon = 'icons'.str_replace($real_path, '', $icon);
            /*echo '<pre>';
            print_r($imageinfo);
            echo '</pre>';*/
            if($imageinfo[0] < 32 && $imageinfo[1] < 32 && ($imageinfo[2] == 1 || $imageinfo[2] == 2) && ($imageinfo['channels'] == 3 || $imageinfo['channels'] == 2))
              echo '<tr><td>'.htmlspecialchars($icon).'</td><td align="center"><img src="'.$icon.'" /></td></tr>';
          }
        }
        echo '</table>';
      }
    }
    echo '</td></tr></table>';

  } else



    // manage and create users
  if(isset($_GET['manage']) && $admin){

    if(!isset($_GET['createuser']) && !isset($_GET['edituser']) && !isset($_POST['user'])){

        // if new username exists and it is valid...
      if(isset($_POST['cusername']) && check_user($_POST['cusername'])){
        $cusername = strtolower($_POST['cusername']);

        if(isset($_POST['passcode']) && isset($_POST['cpasscode']) && $_POST['passcode'] != '**********'){
          $passcode  = $_POST['passcode'];
          $cpasscode = $_POST['cpasscode'];
          if(isset($_POST['hexperm']))
            $permstype = 'hex';
          else {
            $permstype = 'basic';
            settype($_POST['perms'], 'integer');
          }
          if($passcode == $cpasscode){
            if(($_POST['perms'] <= 9 && $_POST['perms'] >= 0 && $permstype == 'basic')
            || (hexdec($_POST['perms']) <= 256 && $_POST['perms'] >= 0 && $permstype == 'hex')){
                // put together a blank user
              $array_of_user[0] = '';
              $array_of_user[1] = '<?PHP';
              $array_of_user[2] = $cusername;
              $array_of_user[3] = '';
              $array_of_user[4] = $_POST['perms'];
              $array_of_user[5] = $permstype;
              $array_of_user[6] = '';
              $array_of_user[7] = md5($passcode);
              $array_of_user[8] = '?>' . $line_break;
              $write = implode($line_break, $array_of_user);
              $fout = fopen(loc1 . '/filelist/filelist-'. $cusername .'.php', 'w');
              $fp = fwrite($fout, $write);
              fclose($fout);
              $fout = fopen(loc1 . '/filelist/filelist-logins.list', 'a');
              $fp = fwrite($fout, $cusername . $line_break);
              fclose($fout);
              echo '<br>User successfully added. <a href="'.phpSelf.'?loc='.locenc.'&manage=1">Click here to continue</a>.';
              if(!strong_password($passcode))
                  echo ' <font color="red">WARNING: Passcode is not a strong password!</font>';
              echo '<br><br>';
              writelog("Admin created user $cusername with permissions ".$_POST['perms']." ($permstype)", 'create user');
            } else
              echo '<br><font color="red">Invalid value for permissions.</font><br><br>';
          } else
            echo '<br><font color="red">Passcodes do not match.</font><br><br>';
        } else
          echo '<br><font color="red">Ivalid passcode.</font><br><br>';
      }


      if(isset($_GET['deleteuser'])){
        $delete = $_GET['deleteuser'];
        if(is_file(loc1 . '/filelist/filelist-'. $delete .'.php')){
          $sub_array = file(loc1 . '/filelist/filelist-'. $delete .'.php');
          if((((trim($sub_array[4]) != 0 || trim($sub_array[5]) == 'hex') && (hexdec(trim($sub_array[4])) != 0)) || $un == 'admin')
          && $delete != 'admin'){

            $users_array = file(loc1 . '/filelist/filelist-logins.list'); // file with all users
            $done = false;
            for($i = 0; $i < count($users_array) && !$done; $i++){
              if(isset($_GET['confirm'])){
                if($delete != trim($users_array[$i]))
                  $new_users_array[] = $users_array[$i];
              }
              if($delete == trim($users_array[$i]) && !isset($_GET['confirm'])){
                echo '<div align="center"><font color="red">Are you sure you want to remove this user ('.$delete.')?</font>';
                echo '<table cellpadding="5" cellspacing="0" border="0" width="200"><tr><td><a href="'.phpSelf.'?loc='.locenc.'&manage=1&deleteuser='.$delete.'&confirm=1">Yes</a></td>';
                echo '<td align="right"><a href="'.phpSelf.'?loc='.locenc.'&manage=1">No</a></td></tr></table></div>';
                $done = true;
              }
            }
            if(isset($_GET['confirm'])){
              if(trim($sub_array[7]) == 'Pending Admin Authorization'){
                $logincount_ar = file(loc1 . '/filelist/filelistloginscount.list');
                array_shift($logincount_ar);
                if(count($logincount_ar) > 0){
                  $fout = fopen(loc1 . '/filelist/filelistloginscount.list', 'w');
                  $fp = fwrite($fout, implode('', $logincount_ar));
                  fclose($fout);
                } else
                  @unlink(loc1 . '/filelist/filelistloginscount.list');
              }
              @unlink(loc1 . '/filelist/filelist-userdb/filelist-'.$delete.'-sets.list');
              @unlink(loc1 . '/filelist/filelist-userdb/filelist-'.$delete.'-org.list');
              @unlink(loc1 . '/filelist/filelist-'.$delete.'.php');
              $fout = fopen(loc1 . '/filelist/filelist-logins.list', 'w');
              $fp = fwrite($fout, implode('', $new_users_array));
              fclose($fout);
              echo '<font color="red">User has been removed.</font>';
              writelog('Admin has removed a user ('.$delete.') from the File Manage system.', 'manage');
            }
          }
        } else {
          $users_array = file(loc1 . '/filelist/filelist-logins.list'); // file with all users
          for($i = 0; $i < count($users_array); $i++)
            if($delete != trim($users_array[$i]))
              $new_users_array[] = $users_array[$i];
          @unlink(loc1 . '/filelist/filelist-userdb/filelist-'.$delete.'-sets.list');
          $fout = fopen(loc1 . '/filelist/filelist-logins.list', 'w');
          $fp = fwrite($fout, implode('', $new_users_array));
          fclose($fout);
          echo '<div align="center"><font color="red">User has been removed because the user did not have a file.</font></div>';
          writelog('<font color="red">Admin removed a user ('.$delete.') who didn\'t have a login file.</font>', 'manage', 'none', 1);
        }
      }


        // must be user "admin" to ban and unban people.
      if($un == 'admin'){
        if(isset($_GET['addban'])){
          if(isset($_POST['ban'])){
            if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] == trim($_POST['ban']))
              echo '<br><font color="red">It is recommended to not ban yourself (ban canceled).</font><br><br>';
            else {
              $validip = true;

              $subIP_ar = explode('.', trim($_POST['ban']));
              if(count($subIP_ar) != 4)
                $validip = false;

              if($validip){
                foreach($subIP_ar as $i => $sub){
                  $sub += 0; // make integer since change type doesn't always work
                  if($sub < 0 || $sub > 255)
                    $validip = false;
                  else
                    $subIP_ar[$i] = $sub;
                }
              }

              $ban_this_ip = implode('.', $subIP_ar);

              if(is_file(loc1 . '/filelist/filelist-bannedIPs.list') || isset($banned_ar)){
                if(!isset($banned_ar))
                  $banned_ar = file(loc1 . '/filelist/filelist-bannedIPs.list');
                    for($i = 0; $i < count($banned_ar) && $validip; $i++)
                      if($ban_this_ip == trim($banned_ar[$i]))
                        $validip = false;
              }

              if($validip){
                $fout = fopen(loc1 . '/filelist/filelist-bannedIPs.list', 'a');
                $fp = fwrite($fout, $ban_this_ip . "\n");
                fclose($fout);
                $banned_ar[] = $ban_this_ip;
                writelog('Admin added a banned IP ('.$ban_this_ip.').', 'manage', 'none');
              } else
                echo '<br><font color="red">IP is not valid or has already been added.</font><br><br>';
            }
          } else {
            echo '<br><font color="red">Add IP to banned list:</font>';
            echo '<br><form name="banip" method="post" action="'.phpSelf.'?loc='.locenc.'&manage=1&addban=1">';
            echo '<input type="text" name="ban" size="15" maxlength="15">';
            echo '<input type="submit" value="Ban IP">';
            echo '<input type="button" onClick="javascript:location.href=\''.phpSelf.'?loc='.addslashes(loc).'&manage=1\'" value="Cancel">';
            echo '</form><br><br>';
          }
        } elseif(isset($_GET['delban'])){
          $delban = $_GET['delban'];
          if(is_file(loc1 . '/filelist/filelist-bannedIPs.list') || isset($banned_ar)){
            if(!isset($banned_ar))
              $banned_ar = file(loc1 . '/filelist/filelist-bannedIPs.list');
            foreach($banned_ar as $ban)
              if($delban != trim($ban))
                $new_banned_ar[] = trim($ban);

            writelog('Admin deleted a banned IP ('.$delban.').', 'manage', 'none');

            if(isset($new_banned_ar) && count($new_banned_ar) > 0){
              $fout = fopen(loc1 . '/filelist/filelist-bannedIPs.list', 'w');
              $fp = fwrite($fout, implode("\n", $new_banned_ar));
              fclose($fout);
              $banned_ar = $new_banned_ar;
            } else {
              @unlink(loc1 . '/filelist/filelist-bannedIPs.list');
              unset($banned_ar);
            }
          } else
            echo '<br><font color="red">No banned IPs exist. All IPs may have already been deleted.</font><br><br>';
        }
      }


      $array_of_users = file(loc1 . '/filelist/filelist-logins.list');
      $num_of_users = count($array_of_users);
      for($i = $num_of_users - 1; $i >= 1; $i--)
        $array_of_users[$i + 1] = $array_of_users[$i];
      $array_of_users[1] = 'anonymous';

      if(is_file(loc1.'/filelist/filelistloginscount.list')){
        $num_of_users_pending = count(file(loc1.'/filelist/filelistloginscount.list'));
        if($num_of_users_pending > 0)
          $str = ' ('.$num_of_users_pending.' pending)';
        else
          $str = NULL;
      } else
        $str = NULL;

      echo '<div align="right"><a href="'.phpSelf.'?loc='.locenc.'&manage=1&createuser=1">Create new user</a></div><br>';
      echo 'Total users: ' . $num_of_users . $str .'<br>';
      echo '<table cellpadding="4" cellspacing="0" border="1"><tr>';
      echo '<td><u>User\'s Name</u></td>';
      echo '<td><u>Email</u></td>';
      echo '<td><u><acronym title="Level of permissions">Permissions</acronym></u></td>';
      echo '<td><u><acronym title="Whether on HEX or Basic permissions system">Perm Type</acronym></u></td>';
      echo '<td><u></u></td>';
      echo '<td><u>Action</u></td>';
      echo '</tr>';

      foreach($array_of_users as $user_name){
        $user = trim($user_name);
        if($user != 'anonymous' || is_file(loc1 . '/filelist/filelist-'. $user .'.php')){
          $sub_array = file(loc1 . '/filelist/filelist-'. $user .'.php');
          echo '<tr><td>' . $user . '</td>';
          if(strlen(trim($sub_array[6])) > 0)
            echo '<td><a href="mailto:' . trim($sub_array[6]) . '">' . trim($sub_array[6]) . '</a></td>';
          else
            echo '<td>Not registered</td>';
          echo '<td>' . trim($sub_array[4]) . '</td>';
          echo '<td>' . trim($sub_array[5]) . '</td>';
          if($un != $user)
            if(((trim($sub_array[4]) != 0 || trim($sub_array[5]) == 'hex') && (hexdec(trim($sub_array[4])) != 0)) || $un == 'admin')
              echo '<td><a href="'.phpSelf.'?loc='.locenc.'&manage=1&edituser='.$user.'">Edit</a></td>';
            else
              echo '<td></td>';
          else
            echo '<td><a href="'.phpSelf.'?loc='.locenc.'&mysettings=1&editprofile=1">Edit</a></td>';
          echo '<td>';
          if(trim($sub_array[7]) == 'Pending Admin Authorization')
            echo '<a href="'.phpSelf.'?loc='.locenc.'&manage=1&edituser='.$user.'&accept=1">Accept User</a><br>';
          if((((trim($sub_array[4]) != 0 || trim($sub_array[5]) == 'hex') && (hexdec(trim($sub_array[4])) != 0)) || $un == 'admin')
          && $user != 'admin')
            echo '<a href="'.phpSelf.'?loc='.locenc.'&manage=1&deleteuser='.$user.'">Delete user</a>';
          echo '</td></tr>';
        } elseif($user == 'anonymous'){
          echo '<tr><td colspan="2"><i>anonymous (';
          if($allow_anonymous)
            echo '<b>Enabled</b>';
          else
            echo '<i>Disabled</i>';
          echo ')</i></td><td>'.$anonym_perm.'</td><td>'.$anonym_perm_type.'</td>';
          echo '<td colspan="2"><a href="'.phpSelf.'?loc='.locenc.'&manage=1&edituser=anonymous">Edit/Manage</a></td></tr>';
        }
      }
      echo '</table><br><br>';

      if($un == 'admin')
        echo '<div align="right"><a href="'.phpSelf.'?loc='.locenc.'&manage=1&addban=1">Ban an IP</a></div>';
      if(is_file(loc1 . '/filelist/filelist-bannedIPs.list') || isset($banned_ar)){
        if(!isset($banned_ar))
          $banned_ar = file(loc1 . '/filelist/filelist-bannedIPs.list');
        if(count($banned_ar) > 0){
          echo 'Total bans: '.count($banned_ar).'<br>';
          echo '<table cellpadding="3" cellspacing="0" border="1"><tr><td>Banned IP</td><td>Action</td></tr>';
          foreach($banned_ar as $ban){
            echo '<tr><td>'.trim($ban).'</td><td>';
            if($un == 'admin')
              echo '<a href="'.phpSelf.'?loc='.locenc.'&manage=1&delban='.trim($ban).'">Delete</a>';
            echo '</td></tr>';
          }
          echo '</table>';
        }
      }

    } else {
      if(isset($_POST['user']) && $_POST['user'] != 'anonymous'){
        $perms = $_POST['perms'];
        $user  = $_POST['user'];
        $sub_array = file(loc1 . '/filelist/filelist-'. $user .'.php');

        if(isset($_POST['hexperm'])){
          $sub_array[5] = 'hex' . $line_break;
          $perms = strtoupper(dechex(hexdec($perms)));
        } else {
          $sub_array[5] = 'basic' . $line_break;
          settype($perms, 'integer');
        }
          // for some reason this catches very few differences, but if I use
          // !== it seems to think everything is different (unless in hex).
          // Dunno what's up.
        if($perms != $_POST['perms'])
          echo '<font color="red">The permissions value has changed due to invalid entry, please confirm the value is desired.</font>';
        if((!isset($_POST['hexperm']) && $perms <= 9 && ($perms > 0 || $perms === 0))
        || (isset($_POST['hexperm']) && hexdec($perms) <= 256 && hexdec($perms) >= 0)){
          //if(isset($_POST['perms'])){


          $sub_array[4] = $perms . $line_break;
          if(isset($_POST['accept']) && trim($sub_array[7]) == 'Pending Admin Authorization'){
            $sub_array[7] = $line_break;
            $logincount_ar = file(loc1 . '/filelist/filelistloginscount.list');
            array_shift($logincount_ar);
            if(count($logincount_ar) > 0){
              $fout = fopen(loc1 . '/filelist/filelistloginscount.list', 'w');
              $fp = fwrite($fout, implode('', $logincount_ar));
              fclose($fout);
            } else
              @unlink(loc1 . '/filelist/filelistloginscount.list');
          }
          $fout = fopen(loc1 . '/filelist/filelist-'. $user .'.php', 'w');
          $fp = fwrite($fout, implode('', $sub_array));
          fclose($fout);
          echo '<br>User\'s settings successfully changed. <a href="'.phpSelf.'?loc='.locenc.'&manage=1">Click here to continue</a><br><br>';
          writelog('Admin updated user '.$user.'\'s settings', 'manage', 'none', 3);
        } else
          echo '<br><font color="red">Invalid value for permissions.</font><br><br>';

      } elseif(isset($_POST['user']) && $_POST['user'] == 'anonymous'){
        $perms = $_POST['perms'];
        $user  = 'anonymous';
        if(isset($_POST['hexperm'])){
          $anonym_perm_type = 'hex';
          $anonym_perm = strtoupper(dechex(hexdec($perms)));
        } else {
          $anonym_perm_type = 'basic';
          settype($perms, 'integer');
          $anonym_perm = $perms;
        }

        $settings_ar = file(loc1 . '/filelist/filelist-settings.php');
        $done1 = false;
        $done2 = false;
        $done3 = false;
        $done4 = false;
        for($i = 3; $i < count($settings_ar) - 1 && (!$done1 || !$done2 || !$done3 || !$done4); $i++){
          if(!$done1 && substr($settings_ar[$i], 0, strlen('$anonym_perm ')) == '$anonym_perm '){
            if($anonym_perm_type == 'hex')
              $settings_ar[$i] = '$anonym_perm = \'' . $perms . "';\n";
            else
              $settings_ar[$i] = '$anonym_perm = ' . $perms . ";\n";
            $done1 = true;
          }
          if(!$done2 && substr($settings_ar[$i], 0, strlen('$anonym_perm_type ')) == '$anonym_perm_type '){
            $settings_ar[$i] = '$anonym_perm_type = \'' . $anonym_perm_type . "';\n";
            $done2 = true;
          }
          if(!$done3 && substr($settings_ar[$i], 0, strlen('$allow_anonymous ')) == '$allow_anonymous '){
            if(isset($_POST['enableanonym'])){
              $settings_ar[$i] = '$allow_anonymous = 1' . ";\n";
              $allow_anonymous = 1;
            } else {
              $settings_ar[$i] = '$allow_anonymous = 0' . ";\n";
              $allow_anonymous = 0;
            }
            $done3 = true;
          }
          if(!$done4 && substr($settings_ar[$i], 0, strlen('$auto_anonym_login ')) == '$auto_anonym_login '){
            if(isset($_POST['enableautoanonym'])){
              $settings_ar[$i] = '$auto_anonym_login = 1' . ";\n";
              $auto_anonym_login = 1;
            } else {
              $settings_ar[$i] = '$auto_anonym_login = 0' . ";\n";
              $auto_anonym_login = 0;
            }
            $done4 = true;
          }
        }
        if($done1 && $done2 && $done3 && $done4){
          $settings_ar[1] = '// ' . time() . "\n";
          $write = implode('', $settings_ar);
          $fout = fopen(loc1 . '/filelist/filelist-settings.php', 'w');
          $fp = fwrite($fout, $write);
          fclose($fout);
          echo '<br>Anonymous user settings successfully changed. <a href="'.phpSelf.'?loc='.locenc.'&manage=1">Click here to continue</a><br><br>';
          writelog('Admin updated Anonymous user settings', 'manage', 'none', 3);
        } else
          echo 'Error.';

      } else
        echo '<br><br><br>';

      if(isset($_GET['accept']) || isset($_POST['accept']))
        $accept = true;
      else
        $accept = false;

      if(!isset($_GET['createuser'])){
        if((!isset($user) && (isset($_POST['edituser']) || isset($_GET['edituser']))) || isset($user)){
          if(!isset($user)){
            if(isset($_GET['edituser']))
              $user = $_GET['edituser'];
            elseif(isset($_POST['edituser']))
              $user = $_POST['edituser'];
          }
          if($user == 'anonymous'){
            $perms = $anonym_perm;
            $permstype = $anonym_perm_type;
            $str = 'Edit Anonymous';
            echo '<body onLoad="document.profile.perms.focus();">';
          } else {
            $sub_array = file(loc1 . '/filelist/filelist-'. $user .'.php');
            $perms = trim($sub_array[4]);
            $permstype = trim($sub_array[5]);
            if($accept)
              $str = 'Accept';
            else
              $str = 'Edit';
            echo '<body onLoad="document.profile.perms.focus();">';
          }
        }
      } else {
        echo '<body onLoad="document.profile.cusername.focus();">';
        $str = 'Create';
        $perms = 6;
        $permstype = 'basic';
      }

      if(isset($_POST['edituser']) && $un != 'admin' && (($perms == 0 && $permstype != 'hex') || hexdec($perms) == 0)){
        echo '<script language="JavaScript">';
        // the genius JavaScript function name below originally coined by Bradley Hart!
        echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes(loc).'&manage=1\',1)';
        echo '</script>';
        die('<a href="'.phpSelf.'?loc='.addslashes(loc).'&manage=1">Click here to continue</a>');
      }

      if(isset($_GET['createuser']) || (!isset($_GET['createuser']) && ($un == 'admin' || $user == 'anonymous' || (($perms != 0 || $permstype == 'hex') && (hexdec($perms) != 0))))){

        $perms1 = array('read','list','subdir','write','make','append','delete','ddelete');
        $perms2 = array('View files in root directory','View a list of subdirectories',
        'View files in subdirectories','Create, upload, and copy/paste files',
        'Create, copy/paste subdirectories','Edit and rename files','Delete, cut/paste (move) files',
        'Delete, cut/paste (move) directories');

        $array = get_perm($perms, $permstype);

          // here is some nice, fun JS -- I don't like JS. But the feature this
          // adds is very nice: automation of permissions numbers, so people
          // other than me are able to use the HEX system.
        echo '<script type="text/JavaScript">
  <!--

    /*******************************************************
    CONVERSIONS (the following three conversion functions)
    By Ryan Parman
    There are minor adaptations to this script by Brandon Nimon
    Distributed according to SkyGPL 2.1, http://www.skyzyx.com/license/
    *******************************************************/
    function decimal(dec){
    	this.dec = dec;
    	this.toBinary = function(){
        return this.dec.toString(2);
      }
    	this.toHex = function(){
        return this.dec.toString(16).toUpperCase();
      }
    }
    function binary(bin){
    	this.bin = bin;
    	this.toDecimal = function(){
        return parseInt(this.bin, 2);
      }
    	this.toHex = function(){
        return this.toDecimal().toString(16).toUpperCase();
      }
    }
    function hex(hex){
    	this.hex = hex;
    	this.toDecimal = function(){
        return parseInt(this.hex, 16);
      }
    	this.toBinary = function(){
        return this.toDecimal().toString(2);
      }
    }
    /****************** END OF "CONVERSIONS" by: RYAN PARMAN ******************/


    function changepermschecks(){
      if(document.profile.hexperm.checked){
        var numbout = new decimal(256 - parseInt(new hex(document.profile.perms.value).toDecimal())).toBinary();
        while(numbout.length < 8){
          numbout = "0" + numbout;
        }'."\n";

        foreach($perms1 as $i => $permss)
          echo '        if(numbout.substr('.$i.', 1) == "0"){ document.viewperms.a'.$i.'.checked = false; } else { document.viewperms.a'.$i.'.checked = true; }'."\n";

        echo '      } else {
        var numbhere = 9 - parseInt(document.profile.perms.value);

        numbout = "";
        for(var i = 0; i < '.count($perms1).'; i++){
          if(numbhere > 0){
            numbout = numbout + "1";
            numbhere--;
          } else {
            numbout = numbout + "0";
          }
        }'."\n";

        foreach($perms1 as $i => $permss)
          echo '        if(numbout.substr('.$i.', 1) == "0"){ document.viewperms.a'.$i.'.checked = false; } else { document.viewperms.a'.$i.'.checked = true; }'."\n";

        echo '      }
    }

    function changevalue(){

      var numbin = "";'."\n";
        foreach($perms1 as $i => $permss)
          echo '      if(document.viewperms.a'.$i.'.checked){ numbin = numbin + "1"; } else { numbin = numbin + "0"; }'."\n";

        echo '      continuous = 1;
      var done = 0;
      if(numbin.substr(0, 1) == "0"){
        for(var i = 0; i < '.count($perms1).' && done == 0; i++){
          if(numbin.substr(i, 1) != 0){
            continuous = 0;
            done = 1;
          }
        }
      } else {
        if(continuous == 1){
          var here = 0;
          var done = 0;
          for(var i = 0; i < '.count($perms1).' && done == 0; i++){
            if(numbin.substr(i, 1) == 1){
              if(i > here){
                continuous = 0;
                done = 1;
              }
              here++;
            }
          }
        }
      }

      if(continuous == 1){
        var basnumb = 1;
        for(var i = 0; i < '.count($perms1).'; i++){
          if(numbin.substr(i, 1) == 0){
            basnumb++;
          }
        }
        document.profile.hexperm.checked = false;
        document.profile.perms.value = basnumb;
      } else {
        numbin = new decimal(256 - parseInt(new binary(numbin).toDecimal())).toHex();
        //if(numbin.length == 1){ numbin = "0" + numbin }
        document.profile.hexperm.checked = true;
        document.profile.perms.value = numbin;
      }
    }
  // -->
</script>';

        if(isset($_GET['createuser']) && !isset($cusername))
          $cusername = '';
        echo '<div align="center"><font size="+1"><b>'.$str.' User</b></font></div>';
        echo '<table cellpadding="8" cellspacing="0" border="0" align="center"><tr><td>';
        echo '<br><form name="profile" method="post" action="'.phpSelf.'?loc='.locenc.'&manage=1">';
        if(@$user == 'anonymous'){
          echo '<body onLoad="if(!document.profile.enableanonym.checked){document.profile.enableautoanonym.checked=false;document.profile.enableautoanonym.disabled=true}else{document.profile.enableautoanonym.disabled=false}">';
          echo '<input type="checkbox" name="enableanonym" ';
          if($allow_anonymous)
            echo 'checked ';
          echo ' onClick="if(!document.profile.enableanonym.checked){document.profile.enableautoanonym.checked=false;document.profile.enableautoanonym.disabled=true}else{document.profile.enableautoanonym.disabled=false}" /> Allow anonymous users '.note(15, 240, 300).'<br>';
          echo '<input type="checkbox" name="enableautoanonym" ';
          if($auto_anonym_login)
            echo 'checked ';
          echo '/> Automatically log users in as anonymous '.note(16, 200, 240).'<br><br>';
        }
        echo '<table cellpadding="3" cellspacing="0" border="0" align="center">';
        echo '<td align="right">User\'s Name:</td>';
        if(!isset($_GET['createuser']))
          echo '<td>'.$user.'</td>';
        else
          echo '<td><input type="text" name="cusername" size="30" maxlength="64" value="'.$cusername.'"></td>';
        echo '</tr><tr><td colspan="2"></td></tr>';
        echo '<tr><td align="right">Permissions:</td><td><input type="text" name="perms" onKeyUp="changepermschecks()" maxlength="3" size="3" value="'.$perms.'">';
        echo '</td></tr>';
        echo '<tr><td align="right">HEX Permissions:</td><td><input type="checkbox" name="hexperm" onClick="changepermschecks()"';
        if($permstype == 'hex')
          echo ' checked';
        echo '>'.note(9, 280, 340).'</td></tr>';
        echo '</tr><tr><td colspan="2"></td></tr>';
        if(isset($_GET['createuser'])){
          echo '<tr><td align="right">User passcode:</td><td><input type="password" name="passcode" size="30" value="">'.note(10, 200, 200).'</td></tr>';
          echo '<tr><td align="right">Confirm passcode:</td><td><input type="password" name="cpasscode" size="30" value=""></td></tr>';
        } else {
          echo '<input type="hidden" name="user" value="'.$user.'">';
          echo '<input type="hidden" name="edituser" value="'.$user.'">';
          if($accept)
            echo '<input type="hidden" name="accept" value="1">';
        }
        echo '<tr><td colspan="2" align="center"><input type="submit" size="150" value="'.$str.' User"> ';
        echo '<input type="button" size="150" value="Cancel" onClick="JavaScript:location.href=\''.phpSelf.'?loc='.addslashes(loc).'&manage=1\'"></td></tr>';
        echo '</table></form>';

        echo '</td><td>';

        echo '<br><form name="viewperms" method="post" action="'.phpSelf.'?viewperms=1">';
        echo '<br><table cellpadding="4" cellspacing="0" border="1" align="center">';
        echo '<tr><td colspan="2">Available Permissions</td></tr>';
        foreach($perms1 as $i => $permss){
          echo '<tr><td>';
          if($array[$permss])
            echo '<input type="checkbox" name="a'.$i.'" onClick="changevalue()" checked>';
          else
            echo '<input type="checkbox" name="a'.$i.'" onClick="changevalue()">';
          echo '</td><td>' . $perms2[$i] . '</td></tr>';
        }
        echo '</table></form>';

        echo '</td></tr></table>';
      } else
        echo 'Nice try.';
    }

  } else



    // if an admin wants to view the log file
  if(isset($_GET['log']) && $admin){
    if(!isset($_GET['fitnesslog'])){
      $log_array = file(loc1 . '/filelist/filemanagelog.log');

      if(isset($_GET['lgdel'])){
        $lgdel = $_GET['lgdel'];

        if(!isset($_GET['lgdelconf'])){
          echo '<br><div align="center"><font size="+1" color="red">Are you sure you want to delete all log entries on and prior to<br>'. date("F d, Y H:i (O)", $lgdel) .'?</font><br>';
          echo '<table border="0" width="200"><tr>';
          echo '<td><a href="'.phpSelf.'?loc='.locenc.'&log=1&lgdel='.$lgdel.'&lgdelconf=1">Yes</a></td>';
          echo '<td align="right"><a href="'.phpSelf.'?loc='.locenc.'&log=1">No</a></td></table></div>';
        } else {

          foreach($log_array as $log){
            $sub_array = explode('~~~~~', trim($log));
            if($sub_array[0] > $lgdel)
              $new_array[] = $log;
          }
          //$new_array = array_slice($log_array, ($lgdel + 1));
          $fout = fopen(loc1 . '/filelist/filemanagelog.log', 'w');
          $fp = fwrite($fout, implode('', $new_array));
          fclose($fout);
          writelog('Admin deleted log entries from '. date("F d, Y H:i (O)", $lgdel) .' and prior.', 'log');

          echo '<font color="red">Log entries deleted successfully.</font><br>';

          $log_array = $new_array;
        }
      }

      $array_of_hits = file(loc1 . '/filelist/filelist-hits.list');
      $array_of_view = file(loc1 . '/filelist/filelist-pageviews.list');

      echo '<br><table cellpadding="5" cellspacing="0" border="0" align="center"><tr>';
      echo '<td align="center">Total page views '.note(11, 200, 170).'</td><td></td>';
      echo '<td align="center">Total unique visitors '.note(12, 200, 170).'</td></tr>';
      echo '<tr><td align="center"><u>'. trim($array_of_view[0]) .'</u> since <u>'. date("F d, Y", trim($array_of_view[1])) .'</u></td>';
      echo '<td></td><td align="center"><u>'. (count($array_of_hits) - 1) .'</u> since <u>'. date("F d, Y", trim($array_of_hits[0])) .'</u></td></tr></table><br>';

      if($track_time)
        echo '<div align="right"><a href="'.phpSelf.'?loc='.locenc.'&log=1&fitnesslog=1">View Fitness Log</a></div>';

      $total_logs = count($log_array);
      echo 'Total log entries: '. $total_logs . '<br>';
      echo 'Total file size: '. filesz(filesize(loc1 . '/filelist/filemanagelog.log')) . ', limit: '.filesz($max_log_size * 1024).'<br>';
      echo '<table cellpadding="2" cellspacing="0" border="1"><tr>';
      echo '<td>No.</td>';
      echo '<td>Date/Time</td>';
      echo '<td>IP:port</td>';
      echo '<td>User</td>';
      echo '<td>Description</td>';
      echo '<td>File</td>';
      echo '<td>Locale</td>';
      echo '<td>Lvl</td>';
      echo '<td>Del</td></tr>';

      for($i = $total_logs - 1; $i >= 0 ; $i--){
        $sub_array = explode('~~~~~', trim($log_array[$i]));
        echo '<tr><td align="center"><font size="-1">'.($i + 1).'</font></td>';
        echo '<td><font size="-1">'.date("F d, Y H:i (O)", $sub_array[0]).'</font></td>';
        echo '<td><font size="-1">'.$sub_array[1].'</font></td>';
        echo '<td><font size="-1">'.$sub_array[2].'</font></td>';
        echo '<td><font size="-1">'.$sub_array[3].'</font></td>';
        if(magicQuotes)
          $sub_array[5] = stripslashes($sub_array[5]);
        echo '<td><font size="-1">'.$sub_array[5].'</font></td>';
        echo '<td><font size="-1">'.$sub_array[4].'</font></td>';
        echo '<td align="center"><font size="-1">'.$sub_array[6].'</font></td>';
        echo '<td align="center"><font size="-1"><a href="'.phpSelf.'?loc='.locenc.'&log=1&lgdel='.$sub_array[0].'">Del</a></tr>';
      }
      echo '</table>';

    } elseif($track_time){

      $log_array = file(loc1 . '/filelist/filelist-fitness.log');

      if(isset($_GET['lgdel'])){
        $lgdel = $_GET['lgdel'];

        if(!isset($_GET['lgdelconf'])){
          echo '<br><div align="center"><font size="+1" color="red">Are you sure you want to delete all log entries on and prior to<br>'. date("F d, Y H:i (O)", $lgdel) .'?</font><br>';
          echo '<table border="0" width="200"><tr>';
          echo '<td><a href="'.phpSelf.'?loc='.locenc.'&log=1&fitnesslog=1&lgdel='.$lgdel.'&lgdelconf=1">Yes</a></td>';
          echo '<td align="right"><a href="'.phpSelf.'?loc='.locenc.'&log=1&fitnesslog=1">No</a></td></table></div>';
        } else {

          foreach($log_array as $log){
            $sub_array = explode('~~~~~', trim($log));
            if($sub_array[1] > $lgdel)
              $new_array[] = $log;
          }
          //$new_array = array_slice($log_array, ($lgdel + 1));
          $fout = fopen(loc1 . '/filelist/filelist-fitness.log', 'w');
          $fp = fwrite($fout, implode('', $new_array));
          fclose($fout);
          writelog('Admin deleted log entries from '. date("F d, Y H:i (O)", $lgdel) .' and prior.', 'log');

          echo '<font color="red">Log entries deleted successfully.</font><br>';

          $log_array = $new_array;
        }
      }

      echo '<div align="right"><a href="'.phpSelf.'?loc='.locenc.'&log=1">View System Log</a></div>';

      $total_logs = count($log_array);
      echo 'Total log entries: '. $total_logs . '<br>';
      echo 'Total file size: '. filesz(filesize(loc1 . '/filelist/filelist-fitness.log')) . ', limit: '.filesz($max_track_size * 1024).'<br>';
      echo '<table cellpadding="2" cellspacing="0" border="1"><tr>';
      echo '<td>No.</td>';
      echo '<td>Date/Time</td>';
      echo '<td>User</td>';
      echo '<td>Load Time</td>';
      echo '<td>Locale</td>';
      echo '<td>Incld</td>';
      echo '<td>Del</td></tr>';

      for($i = $total_logs - 1; $i >= 0 ; $i--){
        $sub_array = explode('~~~~~', trim($log_array[$i]));
        echo '<tr><td align="center"><font size="-1">'.($i + 1).'</font></td>';
        echo '<td><font size="-1">'.date("F d, Y H:i (O)", $sub_array[1]).'</font></td>';
        echo '<td><font size="-1">'.$sub_array[3].'</font></td>';
        echo '<td><font size="-1"';
        if($sub_array[0] > 3.5 && $sub_array[2])
          echo ' color="red"';
        elseif($sub_array[0] > 0.7 && $sub_array[2])
          echo ' color="yellow"';
        elseif($sub_array[2])
          echo ' color="green"';
        echo '>'.$sub_array[0].'</font></td>';
        echo '<td><font size="-1">'.$sub_array[4].'</font></td>';
        if($sub_array[2])
          $tmp = 'Yes';
        else
          $tmp = 'No';
        echo '<td><font size="-1">'.$tmp.'</font></td>';
        echo '<td align="center"><font size="-1"><a href="'.phpSelf.'?loc='.locenc.'&log=1&fitnesslog=1&lgdel='.$sub_array[1].'">Del</a></tr>';
      }
      echo '</table>';

    }

  } else



  if(isset($_GET['recycle']) && (($current_user['delete'] && $current_user['write']) || $admin)){

    echo '<font size="+2">Recycle Bin</font> '.note(19, 230, 280).'<br>';

    if(is_file(loc1 . '/filelist/filelist-recycle_db.list')){
      $recycle_db = file(loc1 . '/filelist/filelist-recycle_db.list');

      echo '<a href="'.phpSelf.'?loc='.locenc.'&recycle=1&empty=1">Empty recycle bin</a><br><br>';
      //echo 'Restore all<br>';


      if(isset($_GET['move']) && (!isset($_POST['dest']) || (strpos($_POST['dest'], 'filelist') === false && strpos($_POST['dest'], 'getid3') === false))){
        if(magicQuotes)
          $move = stripslashes($_GET['move']);
        else
          $move = $_GET['move'];
        if(isset($_POST['dest'])){
          if(magicQuotes)
            $dest = stripslashes($_POST['dest']);
          else
            $dest = $_POST['dest'];

          if(substr($dest, 0, 1) != '/')
            $dest = '/'.$dest;
          if(substr($dest, -1) != '/')
            $dest .= '/';

          $name = get_name(recycle_db('none', $move));
          if(move_recycle('/filelist/.recycle/'.$move, $dest . $name))
            recycle_db('rem', $move);
          writelog('User moved an item out of the Recycle Bin', 'rec', $move . ' - ' . $dest . $name);
        } else {
          echo '<form name="move_recycle" method="post" action="'.phpSelf.'?loc='.locenc.'&recycle=1&move='.str_replace('&', '%26', $move).'">';
          echo 'Move this file to what directory?<br>';
          echo '<input type="text" name="dest" value="/" />';
          echo '<input type="submit" value="Move"></form>';
        }
      }


      if(isset($_GET['movedir']) && (!isset($_POST['dest']) || ($current_user['make'] && $current_user['ddelete'] && strpos($_POST['dest'], 'filelist') === false && strpos($_POST['dest'], 'getid3') === false))){
        if(magicQuotes)
          $movedir = stripslashes($_GET['movedir']);
        else
          $movedir = $_GET['movedir'];

        if(isset($_POST['dest'])){
          if(magicQuotes)
            $dest = stripslashes($_POST['dest']);
          else
            $dest = $_POST['dest'];

          if(substr($dest, 0, 1) != '/')
            $dest = '/'.$dest;
          if(substr($dest, -1) == '/')
            $dest = substr($dest, 0, -1);

          if(is_dir(loc1 . $dest)){
            if(!file_exists(loc1 . $dest . '/'.get_name(recycle_db('none', $movedir)))){
              dirmv('/filelist/.recycle/'.$movedir, $dest . '/'.get_name(recycle_db('none', $movedir)), false, true);
              rmdir(loc1 . '/filelist/.recycle/'.$movedir);
              echo '<font color="red">Directory moved successfully.</font>';
              writelog('User moved a directory.', 'rec', $movedir.' ('.get_name(recycle_db('none', $movedir)).') - '.recycle_db('none', $movedir), 3);
              recycle_db('rem', $movedir);
            } else
              echo '<font color="red">A file or directory with that name already exists in destination directory.</font>';

          } else
            echo '<font color="red">Destination directory does not exist.</font><br>';

        } else {
          echo '<form name="move_recycle" method="post" action="'.phpSelf.'?loc='.locenc.'&recycle=1&movedir='.str_replace('&', '%26', $movedir).'">';
          echo 'Move this directory to what directory?<br>';
          echo '<input type="text" name="dest" value="/" />';
          echo '<input type="submit" value="Move"></form>';
        }
      }


      if(isset($_GET['dirrestore']) && $current_user['ddelete']){
        if(magicQuotes)
          $movedir = stripslashes($_GET['dirrestore']);
        else
          $movedir = $_GET['dirrestore'];

        $name = get_name(recycle_db('none', $movedir));
        $dest = $pre_ex;

        if(is_dir(loc1 . $dest)){
          if(!file_exists(loc1 . $dest . $name)){
            dirmv('/filelist/.recycle/'.$movedir, $dest . $name, false, true);
            rmdir(loc1 . '/filelist/.recycle/'.$movedir);
            echo '<font color="red">Directory restored successfully.</font>';
            writelog('User restored a directory.', 'rec', $movedir.' ('.get_name(recycle_db('none', $movedir)).') - '.recycle_db('none', $movedir), 3);
            recycle_db('rem', $movedir);
          } else
            echo '<font color="red">A file or directory with that name already exists in destination directory.</font>';

        } else
          echo '<font color="red">Destination directory does not exist.</font><br>';
      }


      if(isset($_GET['restore'])){
        if(magicQuotes)
          $move = stripslashes($_GET['restore']);
        else
          $move = $_GET['restore'];

        $name = get_name(recycle_db('none', $move));
        $dest = $pre_ex;

        if(is_dir(loc1 . $dest)){
          if(!file_exists(loc1 . $dest . $name)){
            if(move_recycle('/filelist/.recycle/'.$move, $dest . $name)){
              writelog('User restored a file', 'rec', $move . ' - ' . $dest . $name);
              recycle_db('rem', $move);
            }
          } else
            echo '<font color="red">A file or directory with that name already exists in destination directory.</font>';

        } else
          echo '<font color="red">Destination directory does not exist.</font><br>';
      }


      if(isset($_GET['del']) && $admin){
        if(magicQuotes)
          $del = stripslashes($_GET['del']);
        else
          $del = $_GET['del'];
        if(is_file(loc1 . '/filelist/.recycle/'.$del)){
          if(unlink(loc1 . '/filelist/.recycle/'.$del)){
            echo '<font color="red">File deleted successfully.</font>';
            writelog('Admin deleted a file from recycle bin', 'rec', $del);
            recycle_db('rem', $del);
          } else {
            echo '<font color="red">Unable to delete file (' . $del . '), may be a permissions problem.</font>';
            writelog('<font color="red">Admin tried to delete a file, but it failed (may be a permissions problem)</font>', 'rec', $del, 1);
          }
        } else
          echo '<font color="red">File does not exist. It may have already been deleted or moved. This may have been caused by hitting the refresh button.</font>';
      }


      if(isset($_GET['ddel']) && $admin){
        if(magicQuotes)
          $ddel = stripslashes($_GET['ddel']);
        else
          $ddel = $_GET['ddel'];
        if(is_dir(loc1 . '/filelist/.recycle/'.$ddel.'/')){
          if(remdir('/filelist/.recycle/'.$ddel.'/')){
            echo '<font color="red">Directory deleted successfully.</font>';
            writelog('Admin deleted a directory from recycle bin', 'rec', $ddel);
            recycle_db('rem', $ddel);
          } else {
            echo '<font color="red">Unable to delete directory (' . $ddel . '), may be a permissions problem.</font>';
            writelog('<font color="red">Admin tried to delete a directory, but it failed (may be a permissions problem)</font>', 'rec', $ddel, 1);
          }
        } else
          echo '<font color="red">File does not exist. It may have already been deleted or moved. This may have been caused by hitting the refresh button.</font>';
      }


      if(isset($_GET['empty']) && $admin){
        if(remdir('/filelist/.recycle/')){
          echo '<font color="red">All files and directories in Recycle Bin have been perminantly deleted.</font>';
          writelog('Admin removed all items from Recycle Bin', 'rec');
        } else {
          echo '<font color="red">Not all files or directories in Recycle Bin could be deleted.</font>';
          writelog('<font color="red">Admin tried to removed all items from Recycle Bin but it failed (may be a permissions problem)</font>', 'rec', 'none', 1);
        }
        @unlink(loc1 . '/filelist/filelist-recycle_db.list');
        $recycle_db = array();
      }

      index_sec('/filelist/.recycle/');

      $recycle_files = 0;
      $recycle_dirs = 0;
      $recycle_size = 0;

      echo '<br><br><table cellpadding="2" cellspacing="0" border="0"><tr><td></td><td><u>File Name</u></td><td><u>Size</u></td><td><u>Date Deleted</u></td><td><u>Action</u></td></tr>';
      if(isset($recycle_db) && count($recycle_db) > 0){
        foreach($recycle_db as $recycle_db_entry){
          $sub_recycle = explode('~~~~~', trim($recycle_db_entry));
          if(file_exists(loc1 . '/filelist/.recycle/'.$sub_recycle[1])){
            if($sub_recycle[4] == 1){
              if($admin || ($current_user['make'] && $current_user['ddelete'])){
                echo '<tr><td><img border="0" alt="Directory" src="icons/folder.gif"></td><td>'.$sub_recycle[0].'</td>';
                echo '<td>'.filesz($sub_recycle[3]).'</td>';
                echo '<td>'.date('j M, Y H:i:s', $sub_recycle[5]).'</td>';
                echo '<td><table cellpadding="2" cellspacing="0" border="0"><tr>';
                echo '<td><a href="'.phpSelf.'?loc='.locenc.'&recycle=1&movedir='.str_replace('&', '%26', $sub_recycle[1]).'">Move</a></td>';
                echo '<td><a href="'.phpSelf.'?loc='.locenc.'&recycle=1&dirrestore='.str_replace('&', '%26', $sub_recycle[1]).'">Restore</a></td>';
                if($admin)
                  echo '<td><a href="'.phpSelf.'?loc='.locenc.'&recycle=1&ddel='.str_replace('&', '%26', $sub_recycle[1]).'">Delete</a></td>';
                echo '</tr></table></td></tr>';
              }
              $recycle_dirs++;
            } else {
              echo '<tr><td><img border="0" alt="File" src="icons/unknown.gif"></td><td>'.$sub_recycle[0].'</td>';
              echo '<td>'.filesz($sub_recycle[3]).'</td>';
              echo '<td>'.date('j M, Y H:i:s', $sub_recycle[5]).'</td>';
              echo '<td><table cellpadding="2" cellspacing="0" border="0"><tr>';
              echo '<td><a href="'.phpSelf.'?loc='.locenc.'&recycle=1&move='.str_replace('&', '%26', $sub_recycle[1]).'">Move</a></td>';
              echo '<td><a href="'.phpSelf.'?loc='.locenc.'&recycle=1&restore='.str_replace('&', '%26', $sub_recycle[1]).'">Restore</a></td>';
              if($admin)
                echo '<td><a href="'.phpSelf.'?loc='.locenc.'&recycle=1&del='.str_replace('&', '%26', $sub_recycle[1]).'">Delete</a></td>';
              echo '</tr></table></td></tr>';
              $recycle_files++;
            }
            $recycle_size += $sub_recycle[3];
          }
        }
      }

      echo '</table><br>';

      echo 'Files in recycle bin: '.$recycle_files.'<br>';
      echo 'Directories in recycle bin: '.$recycle_dirs.'<br>';
      echo 'Total file size: '.filesz($recycle_size);

    } else
      echo 'No items in recycle bin.';
  } else



  if(isset($_GET['fitness']) && $admin && ($track_time || $development)){
    $fitness_ar = file(loc1 . '/filelist/filelist-fitness.log');
    $user1_ar = file(loc1 . '/filelist/filelist-logins.list');
    foreach($user1_ar as $i => $user)
      $user1_ar[$i] = trim($user);
    $min = 1000000;
    $max = 0;
    foreach($fitness_ar as $fitness){
      $sub_time_ar = explode('~~~~~', trim($fitness));
      if($sub_time_ar[2] == 1){
        $time_ar[] = $sub_time_ar[0];
        if($sub_time_ar[0] > $max)
          $max = $sub_time_ar[0];
        if($sub_time_ar[0] < $min)
          $min = $sub_time_ar[0];
        if($sub_time_ar[3] != '*none*' && ($sub_time_ar[3] == 'anonymous' || in_array($sub_time_ar[3], $user1_ar)))
          $user_ar[$sub_time_ar[3]][] = $sub_time_ar[0];
        if(!isset($date_avg_ar[date('Y-m-d', $sub_time_ar[1])])){
          $date_min_ar[date('Y-m-d', $sub_time_ar[1])] = 1000000;
          $date_max_ar[date('Y-m-d', $sub_time_ar[1])] = 0;
        }
        $date_avg_ar[date('Y-m-d', $sub_time_ar[1])][] = $sub_time_ar[0];
        if($sub_time_ar[0] > $date_max_ar[date('Y-m-d', $sub_time_ar[1])])
          $date_max_ar[date('Y-m-d', $sub_time_ar[1])] = $sub_time_ar[0];
        if($sub_time_ar[0] < $date_min_ar[date('Y-m-d', $sub_time_ar[1])])
          $date_min_ar[date('Y-m-d', $sub_time_ar[1])] = $sub_time_ar[0];
        if($sub_time_ar[4] != '*none*' && is_dir(loc1 . $sub_time_ar[4]))
          $loc_ar[$sub_time_ar[4]][] = $sub_time_ar[0];
      } else
        $time2_ar[] = $sub_time_ar[0];
    }

    echo '<a href="#overall">View Overall Statistics</a><br>';
    echo '<a href="#user">View Statistics Organized by User</a><br>';
    echo '<a href="#location">View Statistics Organized by Location</a><br>';
    echo '<a href="#date">View Statistics Organized by Date</a><br><br>';
    echo '<a href="'.phpSelf.'?loc='.locenc.'&log=1&fitnesslog=1">View Statistics In Log Form</a><br><br>';

    echo 'Tracking file size: '.filesz(filesize(loc1 . '/filelist/filelist-fitness.log')).', limit: '.filesz($max_track_size * 1024).'<br>';

    $visits = count($time_ar);
    $avg = round(array_sum($time_ar) / $visits, 4);
    echo '<table cellpadding="3" cellspacing="0" border="1">';
    echo '<tr><td><a name="overall">Overall</a> average page load time</td><td>'.$avg.' seconds</td><td>'.avg_load_stats($avg).'</td></tr>';
    echo '<tr><td>Overall minimum load time</td><td>'.$min.' seconds</td><td>'.min_load_stats($min).'</td></tr>';
    echo '<tr><td>Overall maximum load time</td><td>'.$max.' seconds</td><td>'.max_load_stats($max).'</td></tr>';
    echo '</table>';
    echo 'Total visits in statistics: '.$visits.'<br><br>';

    if(isset($time2_ar) && $development)
    echo 'Other pages: Average load times: '.round(array_sum($time2_ar) / count($time2_ar), 4).' seconds.';
    echo '<br><br>';

    echo '<table cellpadding="3" cellspacing="0" border="1"><tr><td><a name="user">User</a></td><td>Average load times</td><td>Rating</td><td>Visits</td></tr>';
    foreach($user_ar as $user => $ar){
      $visits = count($ar);
      $avg = round(array_sum($ar) / $visits, 4);
      echo '<tr><td>'.$user.'</td><td>'.$avg.' seconds</td><td>'.avg_load_stats($avg).'</td><td>'.$visits.'</td></tr>';
    }
    echo '</table><br>';

    echo '<table cellpadding="3" cellspacing="0" border="1"><tr><td><a name="location">Location</a></td><td>Average load times</td><td>Rating</td><td>Visits</td><td>Files/Dirs</td><td>Recomendation</td></tr>';
    foreach($loc_ar as $dir => $ar){
      $visits = count($ar);
      $avg = round(array_sum($ar) / $visits, 4);
      $num_of_files = count(glob(loc1 . $dir . '*'));
      if($num_of_files > 0)
        $avg2 = round(($avg - $min) / $num_of_files, 4); // this is load time per file
      else
        $avg2 = 0;
      echo '<tr><td><a title="Goto this directory" href="'.phpSelf.'?loc='.str_replace('&', '%26', $dir).'">'.$dir.'</a></td><td>'.$avg.' seconds</td><td>'.avg_load_stats($avg).'</td><td>'.$visits.'</td><td>'.$num_of_files.'</td><td>';
      if($avg > 1){
        if($num_of_files > 100)
          echo 'Remove files immediately! Specifically media or image files (if any).';
        else
          echo 'Try removing media or image files (if any).';
        if($avg2 > 0.02)
          echo ' If Show Media Info (add_getdi3) is enabled by default in settings, try disabling it.';
      }
      echo '</td></tr>';
    }
    echo '</table><br>';

    echo '<table cellpadding="3" cellspacing="0" border="1"><tr><td><a name="date">Date</a></td><td>Average load times</td><td>Minimum load time</td><td>Maximum load time</td><td>Rating</td><td>Visists</td></tr>';
    foreach($date_avg_ar as $date => $ar){
      $visits = count($ar);
      $avg = round(array_sum($ar) / $visits, 4);
      echo '<tr><td>'.$date.'</td><td>'.$avg.' seconds</td><td>'.$date_min_ar[$date].' seconds</td><td>'.$date_max_ar[$date].' seconds</td><td>'.avg_load_stats($avg).'</td><td>'.$visits.'</td></tr>';
    }
    echo '</table>';

  } else



    // if file is being previewed
  if(isset($_GET['editpv']) && $current_user['append'] && is_file(loc1 . $_GET['editpv']) && allowed($_GET['editpv'])){
    $edit = $_GET['editpv'];
    echo '<a href="JavaScript:window.close()">Close window</a><br>';
    highlight_file(loc1 . $edit);
    echo '<br><a href="JavaScript:window.close()">Close window</a>';
  } else



    // displays user's permissions
  if(isset($_GET['perms'])){

    writelog('User viewed their own permissions', 'perms', 'none', 4);

    $perms1 = array('read','list','subdir','write','make','append','delete','ddelete');
    $perms2 = array('View files in root directory','View a list of subdirectories',
    'View files in subdirectories','Create, upload, and copy/paste files',
    'Create, copy/paste subdirectories','Edit and rename files','Delete, cut/paste (move) files',
    'Delete, cut/paste (move) directories');

    echo '<br><table cellpadding="4" cellspacing="0" border="1" align="center">';
    echo '<tr><td colspan="2">Available Permissions</td></tr>';
    foreach($perms1 as $i => $permss){
      echo '<tr><td>';
      if($current_user[$permss])
        echo 'Yes';
      else
        echo 'No';
      echo '</td><td>' . $perms2[$i] . '</td></tr>';
    }
    echo '</table>';




  } else {



      // manage hidden files and directories (hide more files/dirs or show hidden files/dirs)
    if(isset($_GET['hide']) && $admin){

      if(isset($_GET['addhide'])){
        $showform = true;
        if(isset($_POST['hidethis'])){
          $hidethis = $_POST['hidethis'];

          $items_ar = array();
          getarrayofmatching($hidethis);

          $fout = fopen(loc1 . '/filelist/filelist-hiddenitems.list', 'a');
          $fp = fwrite($fout, implode("\n", $items_ar) . "\n");
          fclose($fout);

          if(isset($hidden_items_ar))
            $hidden_items_ar = array_merge($hidden_items_ar, $items_ar);
          else
            $hidden_items_ar = $items_ar;

          echo '<font color="red">'.count($items_ar).' items have been hidden.</font><br>';

        }
        if($showform){
          if(!isset($hidethis))
            $hidethis = NULL;
          echo '<form name="hidenewitem" method="post" action="'.phpSelf.'?loc='.locenc.'&hide=1&addhide=1">';
          echo '<font color="red">This will hide items in all directories!</font><br>';
          echo '<input type="text" name="hidethis" size="30" value="'.$hidethis.'" />';
          echo '<input type="submit" name="hidethissubmit" value="Hide" />';
          echo '<input type="button" onClick="javascript:location.href=\''.phpSelf.'?loc='.addslashes(loc).'&hide=1\'" value="Cancel"><br>';
          echo '<table cellpadding="2" cellspacing="0" border="0">';
          echo '<tr><td>Hide currently existing files</td><td width="5"></td><td>Hide future files too</td></tr>';
          echo '<tr><td align="center"><input type="radio" name="hidetype" value="now"';
          if((isset($hidetype) && $hidetype == 'now') || !isset($hidetype))
            echo ' checked';
          echo ' /></td><td></td>';
          echo '<td align="center"><input type="radio" name="hidetype" value="all"';
          if(isset($hidetype) && $hidetype == 'all')
            echo ' checked';
          echo ' disabled /></td></tr></table>';
          echo '</form>';
        }
      }

      if(isset($_GET['hideitem'])){
        if(magicQuotes)
          $hideitem = stripslashes($_GET['hideitem']);
        else
          $hideitem = $_GET['hideitem'];
        if(!isset($hidden_items_ar) || !in_array($hideitem, $hidden_items_ar)){
          if(is_dir(loc1 . $hideitem)){
            $write = $hideitem.'/';
            $hidden_items_ar[] = $hideitem.'/';
          } else {
            $write = $hideitem;
            $hidden_items_ar[] = $hideitem;
          }
          $fout = fopen(loc1 . '/filelist/filelist-hiddenitems.list', 'a');
          $fp = fwrite($fout, $write . "\n");
          fclose($fout);

          if(is_dir(loc1 . $hideitem))
            writelog('Admin hid a directory.', 'hide', $hideitem . '/');
          else
            writelog('Admin hid a file.', 'hide', $hideitem);
        } else
          echo '<font color="red">Item should already be hidden.</font>';
      }

      if(isset($hidden_items_ar)){
        if(isset($_GET['unhide'])){
          if(magicQuotes)
            $unhide = stripslashes($_GET['unhide']);
          else
            $unhide = $_GET['unhide'];
          foreach($hidden_items_ar as $hidden_item)
            if($hidden_item != $unhide)
              $new_hidden_items_ar[] = $hidden_item;

          if(!isset($new_hidden_items_ar) || !is_array($new_hidden_items_ar) || count($new_hidden_items_ar) <= 0){
            @unlink(loc1 . '/filelist/filelist-hiddenitems.list');
            unset($hidden_items_ar);
          } else {
            $fout = fopen(loc1 . '/filelist/filelist-hiddenitems.list', 'w');
            $fp = fwrite($fout, implode("\n", $new_hidden_items_ar)."\n");
            fclose($fout);
            $hidden_items_ar = $new_hidden_items_ar;
          }
          writelog('Admin un-hid an item.', 'hide', $unhide);
        }
        if(isset($_GET['unhideall'])){
          @unlink(loc1 . '/filelist/filelist-hiddenitems.list');
          unset($hidden_items_ar);
          writelog('Admin un-hid all items.', 'hide');
        }
      }

      if(!isset($_GET['addhide']))
      echo '<a href="'.phpSelf.'?loc='.locenc.'&hide=1&addhide=1">Add items to hide by name</a><br>';

      if(isset($hidden_items_ar)){
        echo '<br><a href="'.phpSelf.'?loc='.locenc.'&hide=1&unhideall=1">Unhide All</a><br>';
        echo '<table cellpadding="4" cellspacing="0" border="1">';
        echo '<tr><td colspan="2"><b><a href="'.phpSelf.'?loc='.locenc.'&hide=1&hdar=';
        if(isset($_GET['hdar']) && $_GET['hdar'] == 'd')
          echo 'a';
        else
          echo 'd';
        echo '">File(s)</a></b></td></tr>';
        if(!isset($_GET['hdar']) || $_GET['hdar'] == 'a')
          array_multisort($hidden_items_ar, SORT_STRING, SORT_ASC);
        else
          array_multisort($hidden_items_ar, SORT_STRING, SORT_DESC);
        foreach($hidden_items_ar as $hidden_item){
          $fileenc = str_replace('&', '%26', $hidden_item);
          echo '<tr><td>'.trim($hidden_item).'</td><td><a href="'.phpSelf.'?loc='.locenc.'&hide=1&unhide='.$fileenc.'">Unhide</a></td></tr>';
        }
        echo '</table><br><br>';
      } else
        echo 'There are no hidden files.';

    }



      // if a file is being editeo
    if(isset($_GET['edit'])){
      if(magicQuotes)
        $edit = stripslashes($_GET['edit']);
      else
        $edit = $_GET['edit'];

      if($current_user['append'] && is_file(loc1 . $edit) && allowed($edit)){
        $ftype = get_ftype($edit);
        if(isset($_GET['force']) || $ftype == 'txt' || $ftype == 'list' || $ftype == 'nfo' || $ftype == 'log'
        || $ftype == 'diz' || $ftype == 'php' || $ftype == 'php3' || $ftype == 'phtml' || $ftype == 'php5'
        || $ftype == 'php4' || $ftype == 'js' || $ftype == 'htm' || $ftype == 'html' || $ftype == 'xhtml'
        || $ftype == 'xml' || $ftype == 'ini' || $ftype == 'inf' || $ftype == 'reg' || $ftype == 'c'
        || $ftype == 'cpp' || $ftype == 'h' || $ftype == 'hpp' || $ftype == 'sh' || $ftype == 'vbs'
        || $ftype == 'readme' || $ftype == 'shtml' || $ftype == 'nsi' || $ftype == 'asp' || $ftype == 'cgi'
        || $ftype == 'tmpl' || $ftype == 'sql'){
          $showform = true;
          $edit2 = str_replace('&', '%26', $edit);
          echo '<form name="edfile" method="post" action="'.phpSelf.'?loc='.locenc.'&edit='.$edit2;
          if(isset($_GET['force']))
            echo '&force=1';
          echo '">';

          if(isset($_POST['commit']) && !isset($_POST['pv'])){
            if(magicQuotes)
              $efcont = stripslashes($_POST['efcont']);
            else
              $efcont = $_POST['efcont'];
            if(check_contents($efcont)){
              $fout = fopen(loc1 . $edit, 'w');
              $fp = fwrite($fout, $efcont);
              fclose($fout);
              writelog('User edited a file', 'edit', $edit);
              echo '<font color="red">Successfully edited.</font>';
              $showform = false;
            } else
              if(is_file(loc1 . '/filelist/filelist-passcode.php'))
                echo 'Enter correct passcode: <input name="overridepasscode" type="password" size="30" /><input name="commit" type="submit" size="150" value="Go"><br>';
          }
          if(isset($_POST['save'])){
            if(magicQuotes)
              $efcont = stripslashes($_POST['efcont']);
            else
              $efcont = $_POST['efcont'];
            if(check_contents($efcont)){
              $fout = fopen(loc1 . $edit, 'w');
              $fp = fwrite($fout, $efcont);
              fclose($fout);
              echo '<font color="red">Successfully saved.</font>';
              writelog('User edited a file', 'edit', $edit);
            } else
              if(is_file(loc1 . '/filelist/filelist-passcode.php'))
                echo 'Enter correct passcode: <input name="overridepasscode" type="password" size="30" /><input name="save" type="submit" size="150" value="Go"><br>';
          }
          if(isset($_POST['pv'])){
            if(magicQuotes)
              $efcont = stripslashes($_POST['efcont']);
            else
              $efcont = $_POST['efcont'];
            if(check_contents($efcont)){
              if(is_file(loc1 . '/filelist/filelist-tmpfiles.list')){
                $tmpfiles = file(loc1 . '/filelist/filelist-tmpfiles.list');
                foreach($tmpfiles as $i => $file)
                  $tmpfiles[$i] = trim($file);
                $randfile = 'filelist-tmp' . mt_rand(0,999999999) . '.php'; // 1:277777 chance of file name colide if a file is created every second in an hour
                while(in_array($randfile, $tmpfiles))
                  $randfile = 'filelist-tmp' . mt_rand(0,999999999) . '.php';
              } else
                $randfile = 'filelist-tmp' . mt_rand(0,999999999) . '.php';
              $fout = fopen(loc1 . '/filelist/filelist-tmpfiles.list', 'a');
              $fp = fwrite($fout, $randfile . '~~' . time() . $line_break);
              fclose($fout);
              $fout = fopen(loc1 . '/filelist/' . $randfile, 'w');
              $fp = fwrite($fout, $efcont . $line_break .
              '<br><br><i>This preview file will expire in an hour</i><br><a href="JavaScript:window.close()">Close window.</a>' . $line_break .
              '<!-- This is a temperary file generated by Bobb\'s File Manage Software for preview of a file and will expire in one hour from UNIX timestamp at start of file. -->');
              fclose($fout);
              writelog('One hour temperary file was created for preview', 'edit', $randfile, 3);

              echo '<script language="JavaScript">';
              echo "window.open('filelist/$randfile','tmp_generated_file','location=no,menubar=no,status=yes,resizable=yes')";
              echo '</script>';
            } else
              if(is_file(loc1 . '/filelist/filelist-passcode.php'))
                echo 'Enter correct passcode: <input name="overridepasscode" type="password" size="30" /><input name="pv" type="submit" size="150" value="Go"><br>';
          }

          if($showform){
            echo '<br><font size="+1"><b>Editing file "'.$edit.'"</b></font><br><br>';
            echo '<a target="_blank" href="'.phpSelf.'?editpv='.$edit2.'">View last save of file in separate window (source)</a><br>';
            echo '<a target="_blank" href="'.cur_dir.$edit2.'">View last save of file in separate window (HTML/PHP)</a><br>';
            echo '<input type="submit" name="pv" size="150" value="Preview current (HTML/PHP) --must allow popup!">';
            //PREM//
            echo '<div align="center"><textarea cols="105" rows="50" name="efcont">';
            if(!isset($_POST['efcont']))
              $editfile = file_get_contents(loc1 . $edit);
            else
              if(magicQuotes)
                $editfile = stripslashes($_POST['efcont']);
              else
                $editfile = $_POST['efcont'];
              echo htmlspecialchars($editfile);
            echo '</textarea></div>';
            echo '<input type="submit" name="commit" size="150" value="Commit Edit">';
            echo '<input type="submit" name="save" size="150" value="Save and Continue Editing"> ';
            echo '<input type="button" value="Close (don\'t save)" onClick="JavaScript:location.href=\''.phpSelf.'?loc='.addslashes(loc).'\'"> ';
            echo '<input type="button" value="Reload Last Saved" onClick="JavaScript:location.href=\''.phpSelf.'?loc='.addslashes(loc).'&edit='.addslashes(str_replace('&', '%26', $edit2));
            if(isset($_GET['force']))
              echo '&force=1';
            echo '\'"> ';
            //if(isset($_POST['overridepasscode']) && $_POST['overridepasscode'] != '')
            //  echo '<input type="hidden" name="overridepasscode" value="'.$_POST['overridepasscode'].'">';
            echo '</form>';
          }

        } else {
          echo '<br><div align="center"><b><font color="red">This does not appear to be a text-based file extension.</font></b><br><br>';
          echo '<table border="0" width="300"><tr><td align="left"><a href="'.phpSelf.'?loc='.locenc.'&edit='.$edit.'&force=1">Force edit</a></td>';
          echo '<td align="right"><a href="'.phpSelf.'?loc='.locenc.'">Cancel</a></td></tr></table></div><br><br>';
        }
      }
    }


      // if a file is being deleted
    if(isset($_GET['del']) && $current_user['delete'] && $_GET['del'] != ''){
      if(magicQuotes)
        $del = stripslashes($_GET['del']);
      else
        $del = $_GET['del'];
      if(isset($_GET['delconf']))
        if($recycle && (!$admin || !isset($_GET['fastdel'])))
          move_recycle($del, '/filelist/.recycle/'.recycle_db('add', $del), true);
        else
          del($del);
      else {
        $del2 = str_replace('&', '%26', $del);
        $del_file_size = filesz(filesize(loc1 . $del));
        echo '<br><br><div align="center"><table cellpadding="0" border="0" cellspacing="0" width="45%"><tr><td colspan="3" align="center"><font size="+1" color="red"><b>Are you sure you want to delete this file?</font></td></tr>';
        echo '<tr><td colspan="3" align="center"><b>'.$del.'</b></td></tr>';
        echo '<tr><td colspan="3" align="center">File is '.$del_file_size.'</td></tr>';
        echo '<tr><td width="33%"><a href="'.phpSelf.'?loc='.locenc.'&del='.$del2.'&delconf=1">Yes</a></td><td align="center" width="34%">';
        if($admin && $recycle)
          echo '<a title="Delete instantly, no Recycle Bin" href="'.phpSelf.'?loc='.locenc.'&del='.$del2.'&delconf=1&fastdel=1">Delete Now';
        echo '</td><td align="right" width="33%"><a href="'.phpSelf.'?loc='.locenc.'">Cancel</a></td></tr></table></div><br>';
      }
    }

      // if a folder is being deleted
    if(isset($_GET['ddel']) && $current_user['ddelete'] && $_GET['ddel'] != ''){
      if(magicQuotes)
        $ddel = stripslashes($_GET['ddel']);
      else
        $ddel = $_GET['ddel'];
      if(strpos(strtolower($ddel), 'filelist') === false && strpos(strtolower($ddel), 'getid3') === false){
        if(isset($_GET['delconf']))
          if($recycle && (!$admin || !isset($_GET['fastdel']))){
            dirmv($ddel, '/filelist/.recycle/'.recycle_db('add', $ddel, true), true, true);
            rmdir(loc1 . $ddel);
          } else
            ddel($ddel);
        else {
          clearscandir();
          scanfulldir(loc1 . $ddel);
          $ddel2 = str_replace('&', '%26', $ddel);
          $ddel_file_size = filesz($total_file_size);
          echo '<br><br><div align="center"><table cellpadding="3" cellspacing="0" border="0" width="45%"><tr><td colspan="3" align="center"><font size="+1" color="red"><b>Are you sure you want to delete this directory?</font></td></tr>';
          echo '<tr><td colspan="3" align="center"><b>'.$ddel.'</b></td></tr>';
          echo '<tr><td colspan="3" align="center">It contains '.$number_of_dirs.' directories, '.$number_of_files.' files which is a total file size of '. $ddel_file_size.'</td></tr>';
          echo '<tr><td width="33%"><a href="'.phpSelf.'?loc='.locenc.'&ddel='.$ddel2.'&delconf=1">Yes</a></td><td width="34%" align="center">';
          if($admin && $recycle)
            echo '<a title="Delete instantly, no Recycle Bin" href="'.phpSelf.'?loc='.locenc.'&ddel='.$ddel2.'&delconf=1&fastdel=1">Delete Now';
          echo '<td align="right" width="33%"><a href="'.phpSelf.'?loc='.locenc.'">Cancel</a></td></tr></table></div><br>';
        }
      } else
        echo '<font color="red">Directory invalid.</font>';
    }

      // if a file or folder is being renamed
    if(isset($_GET['ren'])
    && ($current_user['append'] && ((magicQuotes && is_file(loc1 . stripslashes($_GET['ren']))) || (!magicQuotes && is_file(loc1 . $_GET['ren'])))
    || ($current_user['make'] && ((magicQuotes && is_dir(loc1 . stripslashes($_GET['ren']))) || (!magicQuotes && is_dir(loc1 . $_GET['ren'])))))){
      $req_ren2 = false;
      if(magicQuotes)
        $ren = stripslashes($_GET['ren']);
      else
        $ren = $_GET['ren'];

      $renb = str_replace('&', '%26', $ren); // for URI reasons the & has to be changed into it's HTML special
      echo '<form name="ren2_req" method="post" action="'.phpSelf.'?loc='.locenc.'&ren='.$renb.'">';

      if(isset($_POST['ren2'])){
        if(magicQuotes)
          $ren2 = stripslashes($_POST['ren2']);
        else
          $ren2 = $_POST['ren2'];
        if(!ren($ren, $ren2))
          $req_ren2 = true;
      } else
        $req_ren2 = true;


      if($req_ren2){
        if(!isset($ren2))
          $ren2 = get_name($ren);
        echo '<body onLoad="document.ren2_req.ren2.focus();">';
        echo '<br>Enter a new name';
        echo '<input type="text" name="ren2" size="25" value="'. htmlspecialchars($ren2) .'">';
        echo '<input type="submit" size="150" value="Rename">';
        echo '<input type="button" onClick="location.href=\''.phpSelf.'?loc='.addslashes(loc).'\'" value="Cancel" />';
      }
      echo '</form>';
    }



      // create a directory
    if(isset($_GET['crdir']) && $current_user['make'] && $_GET['crdir'] != ''){
      $req_cdir = false;
      if(isset($_POST['cdir'])){
        if(magicQuotes)
          $cdir = stripslashes($_POST['cdir']);
        else
          $cdir = $_POST['cdir'];
        if(!cdir(loc . $cdir))
          $req_cdir = true;
      } else
        $req_cdir = true;

      if($req_cdir){
        if(!isset($cdir))
          $cdir = '';
        echo '<body onLoad="document.cdir_req.cdir.focus();">';
        echo '<br>Enter the name of the folder that you want to create';
        echo '<form name="cdir_req" method="post" action="'.phpSelf.'?loc='.locenc.'&crdir=1">';
        echo '<input type="text" name="cdir" size="25" value="'. htmlspecialchars($cdir) .'">';
        echo '<input type="submit" size="150" value="Create Directory">';
        echo '</form>';
        echo '<a href="'.phpSelf.'?loc='.locenc.'">Cancel</a>';
      }
    }



      // if a file is being copied
    if(isset($_GET['cpy']) && $current_user['write'] && isset($_GET['paste']))
      if(magicQuotes)
        cpy(stripslashes($_GET['cpy']), loc);
      else
        cpy($_GET['cpy'], loc);



      // if a file is being moved
    if(isset($_GET['cut']) && $current_user['delete'] && $current_user['write'] && isset($_GET['paste']))
      if(magicQuotes)
        move(stripslashes($_GET['cut']), loc);
      else
        move($_GET['cut'], loc);



      // if a file is being copied
    if(isset($_GET['dcpy']) && $current_user['make'] && $current_user['write'] && isset($_GET['paste'])){
      if(magicQuotes)
        $dcpy = stripslashes($_GET['dcpy']);
      else
        $dcpy = $_GET['dcpy'];

      if(is_dir(loc1 . $dcpy)){
        if(strpos(strtolower($dcpy), 'filelist') === false && strpos(strtolower($dcpy), 'getid3') === false){
          if(substr($dcpy, 0, -1) != '/')
            $dcpy .= '/';
          $name = substr($dcpy, strrpos(substr($dcpy, 0, -1), '/') + 1, -1);
          if(loc != substr($dcpy, 0, strrpos(substr($dcpy, 0, -1), '/') + 1)){
            $dest = loc . $name;

            //echo $dcpy . ' -- '. $dest . '<br>';
            //echo loc . ' -- ' . substr($dcpy, strrpos(substr($dcpy, 0, -1), '/')) . ' -- ' . substr($dcpy, 0, 9) . '<br>';
            if(!is_dir(loc1 . $dest) || (isset($_GET['conf']) && (strtolower($_GET['conf']) == 'y' || strtolower($_GET['conf']) == 'n'))){
              if(!is_dir(loc1 . $dest))
                mkdir(loc1 . $dest);
              if(isset($_GET['conf']) && strtolower($_GET['conf']) == 'y')
                dircpy($dcpy, $dest, true);
              else
                dircpy($dcpy, $dest);
              writelog('User copied a directory', 'dircp', $dcpy.' - '.$dest);
              echo '<font color="red">Directory copied.</font>';
            } else {
              echo '<div align="center"><font size="+1"><b>Directory already exists,</b></font><br>What do you want to do?';
              echo '<table cellpadding="4" cellspacing="0" border="0" align="center">';
              echo '<tr><td><a href="'.phpSelf.'?loc='.locenc.$adlnk.'&paste=1&conf=y">Merge directories and overwrite files</a></td></tr>';
              echo '<tr><td><a href="'.phpSelf.'?loc='.locenc.$adlnk.'&paste=1&conf=n">Merge directories, but do not overwrite files</a></td></tr>';
              echo '<tr><td><a href="'.phpSelf.'?loc='.locenc.$adlnk.'">Cancel</a></td></tr>';
              echo '</table></div>';
            }

          } else {
            if(file_exists(loc1 . loc . '/'. $name)){
              $cpy2 = 'Copy of ' . $name;
              if(file_exists(loc1 . loc . $cpy2)){
                $done = false;
                $num = 2;
                while(!$done){
                  $cpy2 = 'Copy ('. $num .') of ' . $name;
                  if(!file_exists(loc1 . loc . $cpy2))
                    $done = true;
                  $num++;
                }
              }
              $name = $cpy2;
            }
            $dest = loc . $name . '/';
            mkdir(loc1 . $dest);
            dircpy($dcpy, $dest);
            writelog('User copied a directory', 'dircp', $dcpy.' - '.$dest);
            echo '<font color="red">Directory copied.</font>';
          }
        } else
          echo '<font color="red">Invalid source directory.</font>';
      }
    }



      // if a file is being moved
    if(isset($_GET['dcut']) && $current_user['ddelete'] && $current_user['make'] && $current_user['write'] && isset($_GET['paste'])){
      if(strpos(strtolower($_GET['dcut']), 'filelist') === false && strpos(strtolower($_GET['dcut']), 'getid3') === false){
        if(magicQuotes)
          dirmv(stripslashes($_GET['dcut']), substr(loc, 0, -1));
        else
          dirmv($_GET['dcut'], substr(loc, 0, -1));
        @rmdir(loc1 . $_GET['dcut']);
      } else
        echo '<font color="red">Invalid source directory.</a>';
    }



      // if a file is being created
    if(isset($_GET['cfile']) && $current_user['write']){
      $show_form = true;
      echo '<form name="crfile" method="post" action="'.phpSelf.'?loc='.locenc.'&cfile=1">';

      if(isset($_POST['cfname'])){

        if(magicQuotes)
          $cfname = stripslashes($_POST['cfname']);
        else
          $cfname = $_POST['cfname'];
        if(magicQuotes)
          $cfcont = stripslashes($_POST['cfcont']);
        else
          $cfcont = $_POST['cfcont'];

        if(check_name($cfname)){
          if(check_contents($cfcont)){
            if(!is_file(loc1 . loc . $cfname) && !is_dir(loc1 . loc . $cfname)){
              if(allowed($cfname, true, true, false)){
                $fout = fopen(loc1 . loc . $cfname, 'w');
                $fp = fwrite($fout, $cfcont);
                fclose($fout);
                echo '<font color="red">File successfully created.</font>';
                writelog('User created a file', 'cfile', loc . $cfname);
                if(isset($_POST['cedit'])){
                  echo '<script language="JavaScript">';
                  // the genius JavaScript function name below originally coined by Bradley Hart!
                  echo 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'?loc='.addslashes(locenc).'&edit='.addslashes(locenc.str_replace('&', '%26', $cfname)).'\',1)';
                  echo '</script>';
                }
                $show_form = false;
              } else
                echo '<font color="red">The file name "' . $cfname . '" has an invalid extension, is being created in an invalid directory, or is otherwise blocked.</font><br>';
            } else
              echo '<font color="red">A file or directory with that name already exists.</font><br>';
          } else
            if(is_file(loc1 . '/filelist/filelist-passcode.php'))
              echo 'Enter correct passcode: <input name="overridepasscode" type="password" size="30" /><input type="submit" size="150" value="Go"><br>';
        }

      } else {
        $cfname = '';
        $cfcont = '';
      }

      if($show_form){
        echo '<body onLoad="document.crfile.cfname.focus();">';
        echo '<br>Enter the name of the file that you want to create:<br>';
        echo '<input type="text" name="cfname" size="25" value="'.htmlspecialchars($cfname).'">';
        echo "<br><br>File contents:";
        echo '<div align="center"><textarea cols="70" rows="20" name="cfcont">';
        echo htmlspecialchars($cfcont);
        echo '</textarea></div>';
        echo '<input type="submit" size="150" value="Create File">';
        if($current_user['append'])
          echo '<input type="submit" name="cedit" size="150" value="Create File and Continue Editing"> ';
        echo '<input type="button" size="150" value="Cancel" onClick="JavaScript:location.href=\''.phpSelf.'?loc='.addslashes(locenc).'\'">';

      }
      echo '</form>';
    }



      // if uploading a file
    if(isset($_GET['upld']) && $current_user['write']){

      if(!$upload_bar || (!$admin && !$all_upload_bar)){

        echo '<form name="uploaddata" enctype="multipart/form-data" action="'.phpSelf.'?loc='.locenc.'&upld=1" method="post">';
        if(isset($_FILES['userfile_0'])){
          for($i = 0; $i < 10; $i++){
            if(isset($_FILES['userfile_'.$i]) && trim($_FILES['userfile_'.$i]['name'] != '')){
              $filename = $_POST['filename_'.$i];

              if($_FILES['userfile_'.$i]['name'] != '' && $_FILES['userfile_'.$i]['size'] > 0){
                if($filename == '' || check_name($filename)){
                  if($filename == '' && strlen($_FILES['userfile_'.$i]['name']) < 255 && check_name($_FILES['userfile_'.$i]['name']))
                    $filename = $_FILES['userfile_'.$i]['name'];
                  if(magicQuotes)
                    $filename = stripslashes($filename);
                  writelog('User attemped to upload a file', 'upld', loc . $filename, 3);
                  if($filename != '' && !is_file(loc1 . loc . $filename)){
                    if(allowed($filename, true, true, false)){
                      $ftype = get_ftype($filename);
                      if(strpos($_FILES['userfile_'.$i]['type'], 'text') !== false || strpos($_FILES['userfile_'.$i]['type'], 'txt') !== false || $ftype == 'php' || $ftype == 'php3' || $ftype == 'php4' || $ftype == 'php5' || $ftype == 'phtml')
                        $tmp_file = file_get_contents($_FILES['userfile_'.$i]['tmp_name']);
                      else
                        $tmp_file = '';
                      if(check_contents($tmp_file)){
                        if(move_uploaded_file($_FILES['userfile_'.$i]['tmp_name'], loc1 . loc . $filename)){
                          echo '<font color="red">File ('.$filename.') successfully uploaded.</font><br>';
                          if(strpos($_FILES['userfile_'.$i]['type'], 'text') !== false || strpos($_FILES['userfile_'.$i]['type'], 'txt') !== false || $ftype == 'php' || $ftype == 'php3' || $ftype == 'php4' || $ftype == 'php5' || $ftype == 'phtml')
                            writelog('User uploaded a text-based file', 'upld', loc . $filename);
                          else
                            writelog('<font color="yellow">User uploaded a file with type "'.$_FILES['userfile_'.$i]['type'].'". If this is a suspicous type, check the file immediately!', 'upld', loc . $filename);
                        } else {
                          echo '<font color="red">The file ('.$filename.') could not be uploaded. This may be due to permission problems or the file is too large.</font><br>';
                          writelog('<font color="red">User tried to upload a file, but it failed (may be due to permission problems or the file is too large)</font>', 'upld', $filename, 1);
                        }
                      } else
                        if(is_file(loc1 . '/filelist/filelist-passcode.php'))
                          echo 'Enter correct passcode: <input name="overridepasscode" type="password" size="30" /><input type="submit" size="150" value="Go"><br><b><i>For security reasons, you will need to enter the file ('.$filename.') location again.</i></b><br>';
                    } else
                      echo '<font color="red">The file name "' . $filename . '" has an invalid extension, is being created in an invalid directory, or is otherwise blocked.</font><br>';
                  } else
                    echo '<font color="red">A file with that name already exists.</font><br>';
                }
              } else {
                echo '<font color="red">Invalid file. Invalid name or size.</font><br>';
                writelog('<font color="red">User tried to upload a file, but it failed (Invalid file. Invalid name or size)</font>', 'upld', loc . $filename, 1);
              }
            } // if(isset($_FILES['userfile_'.$i]) && trim($_FILES['userfile_'.$i]['name'] != ''))
          } // for($i = 0; $i < 10; $i++)
        } // if(isset($_FILES['userfile_0']))

          // Some ideas and lines of code taken from OutSide Photos
          // (www.sourceforge.net/projects/outside-photos/) copyright 2004-2005 by
          // OutSide Photos Development Team under the GNU General Public License,
          // redistibution is allowed under the same licese. View the file LICENSE that
          // was packaged with this file, or download a copy at
          // www.opensource.org/licenses/gpl-license.php
        if(is_file(loc1 . '/filelist-loading.gif') && is_file(loc1 . '/filelist-blank.gif')){
          echo '<script language="JavaScript">'."\n";
          echo 'function newImage(arg){ ';
          echo   'if(document.images){ ';
          echo     'rslt = new Image(); ';
          echo     'rslt.src = arg; ';
          echo     'return rslt; ';
          echo   '} ';
          echo '} ';

          echo 'function changeImages(){ ';
          echo   'if(document.images && (preloadFlag == true)){ ';
          echo     'for(var i = 0; i < changeImages.arguments.length; i += 2){ ';
          echo       'document[changeImages.arguments[i]].src = changeImages.arguments[i + 1]; ';
          echo     '} ';
          echo   '} ';
          echo '} ';

          echo 'var preloadFlag = false; ';
          echo 'function preloadImages(){ ';
          echo   'if(document.images){ ';
          echo     'loading_click = newImage("filelist-loading.gif"); ';
          echo     'preloadFlag = true; ';
          echo   '} ';
          echo '} ';
          echo '</script>'."\n";
          $image_exists = true;
        } else
          $image_exists = false;

        $max_ul_sizemb = 0;
        $max_ul_sizekb = 0;

        $umfs = ini_get('upload_max_filesize');
        if(strtolower(substr($umfs, -1)) == 'm'){
          $max_ul_sizemb = substr($umfs, 0, -1);
          $max_ul_sizekb = $max_ul_sizemb * 1024;
        } else
        if(strtolower(substr($umfs, -1)) == 'k'){
          $max_ul_sizekb = substr($umfs, 0, -1);
          $max_ul_sizemb = round(($max_ul_sizekb / 1024),2);
        }
        if($max_ul_sizekb != 0)
          $max_ul_sizebt = $max_ul_sizekb * 1024 - 1;
        else
          $max_ul_sizebt = 0;

        if(!isset($filename_0))
          $filename_0 = NULL;


        echo '<input type="hidden" name="MAX_FILE_SIZE" value="'.$max_ul_sizebt.'"><br>';
        if($multi_upload){
          echo '<body onLoad="document.uploaddata.filename_0.focus();">';
          echo '<table cellpadding="3" cellspacing="0" border="0"><tr><td>File location.</td><td>File name (include extension)</td></tr>';
          for($i = 0; $i < 10; $i++){
            echo '<tr><td><input name="userfile_'.$i.'" size="50" type="file"></td>';
            echo '<td><input type="text" size="35" maxlength="255" name="filename_'.$i.'" value=""></td></tr>';
          }
          echo '</table>';
          echo '<br><font size="-1">Total file size must be less than '.$max_ul_sizekb.' KB ('.$max_ul_sizemb.' MB)</font><br>';
        } else {
          echo '<body onLoad="document.uploaddata.filename.focus();">';
          echo 'File location (click the browse button to find the file you wish to upload):';
          echo '<br><input name="userfile_0" size="50" type="file">';
          echo '<br><font size="-1">Filesize must be less than '.$max_ul_sizekb.' KB ('.$max_ul_sizemb.' MB)</font><br>';
          echo '<br><br>File Name: <input type="text" size="35" maxlength="255" name="filename_0" value="'. htmlspecialchars($filename_0) .'">(include extension)<br><font size="-1">If you leave the file name blank, the uploaded file\'s name will be used as the name.</font><br><br>';
        }
        echo '<input type="submit"';

        if($image_exists)
          echo ' onClick="changeImages(\'loading\', \'filelist-loading.gif\')"';
        echo ' value="Upload File';
        if($multi_upload)
          echo '(s)';
        echo '"><br><br>';
        if($image_exists)
          echo '<br><img name="loading" SRC="filelist-blank.gif" onload="preloadImages()" border="0"><br>';

          // end of OSP code
        echo '</form>';

      } else {

  /* the following is largly 98% based on uber_uploader (https://sourceforge.net/projects/uber-uploader/)
    some changes have been made to make it work with File Manage */

        $tmp_sid = md5(uniqid(rand(), true));                      // SID used by cgi for the temp directory

        if(!isset($_POST['upload_range'])){
          if($multi_upload)
            $_POST['upload_range'] = 10;
          else
            $_POST['upload_range'] = 1;
        }


        echo '<script language="javascript" type="text/javascript">
var check_file_extentions = false;                        // Change to false to skip file extention check
var check_null_file_count = true;                         // Change to false to skip null file upload
var check_duplicate_file_count = true;                    // Change to false to skip duplicate file upload check
var imbedded_progress_bar = false;                        // Change to true to use an imbedded progress bar.
var upload_range = '.$_POST['upload_range'].';

//////////////////////////////////////////////////////////////////////
// Disallow uploading files by extention (DO NOT REMOVE .sh OR .php)
//
// If you want prevent users from uploading a file based on extention
// simply modify the regular exression eg.
// var re = /(\.php)|(\.sh)|(\.gif)|(.jpg)$/i;
// would prevent anyone from uploading .php, .sh, .gif, .jpg files.
// Also, make sure the extra extentions are added to line 109 in
// uber_uploader.cgi for added security.
//////////////////////////////////////////////////////////////////////
function checkFileExtentions(){
	if(check_file_extentions == false){
    return false;
  }
          //m/(\.php)|(\.sh)$/i
	//var re = /(\.php)|(\.sh)$/i;   //Change line 109 in uber_uploader.cgi to match

	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements[\'upfile_\' + i].value != ""){
			//if(document.form_upload.elements[\'upfile_\' + i].value.match(re)){
				var string = document.form_upload.elements[\'upfile_\' + i].value;
				var num_of_last_slash = string.lastIndexOf("\\\\");
				if(num_of_last_slash < 1){
          num_of_last_slash = string.lastIndexOf("/");
        }
				var file_name = string.slice(num_of_last_slash + 1, string.length);
				var file_extention = file_name.slice(file_name.indexOf(".")).toLowerCase();
				alert(\'Sorry, uploading a file with the extention "\' + file_extention + \'" is not allowed.\');
				return true;
			//}
		}
	}
	return false;
}

///////////////////////////////////////////////////////
// Make sure user selected at least one file to upload
///////////////////////////////////////////////////////
function checkNullFileCount(){
	if(check_null_file_count == false){
    return false;
  }
	var null_file_count = 0;
	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements[\'upfile_\' + i].value == ""){
      null_file_count++;
    }
	}
	if(null_file_count == upload_range){
		alert("Please Choose A File To Upload.");
		return true;
	} else {
    return false;
  }
}

////////////////////////////////////////////////////////
// Make sure user did not select duplicate file uploads
////////////////////////////////////////////////////////
function checkDuplicateFileCount(){
	if(check_duplicate_file_count == false){
    return false;
  }

	var duplicate_flag = false;
	var file_count = 0;
	var duplicate_msg = "Duplicate Upload Files Detected.\n\n";
	var file_name_array = new Array();

	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements[\'upfile_\' + i].value != ""){
			var string = document.form_upload.elements[\'upfile_\' + i].value;
			var num_of_last_slash = string.lastIndexOf("\\\\");
			if(num_of_last_slash < 1){
        num_of_last_slash = string.lastIndexOf("/");
      }
			var file_name = string.slice(num_of_last_slash + 1, string.length);
			file_name_array[i] = file_name;
		}
	}
	for(var i = 0; i < file_name_array.length; i++){
		for(var j = 0; j < file_name_array.length; j++){
			if(file_name_array[i] == file_name_array[j] && file_name_array[i] != null){
        file_count++;
      }
		}
		if(file_count > 1){
			duplicate_msg += \'Duplicate file "\' + file_name_array[i] + \'" detected in slot \' + (i + 1) + ".\n";
			duplicate_flag = true;
		}
		file_count = 0;
	}
	if(duplicate_flag){
		alert(duplicate_msg);
		return true;
	} else {
    return false;
  }
}

//////////////////////////////////////////////////////
// Check files, submit upload and pop up progress bar
//////////////////////////////////////////////////////
function postIt(){
	if(checkFileExtentions()){
    return false;
  }
	if(checkNullFileCount()){
    return false;
  }
	if(checkDuplicateFileCount()){
    return false;
  }
	document.progress_bar.upload_button.disabled = true;

	if(imbedded_progress_bar){
    document.form_upload.imbedded_progress_bar.value = 1;
  } else {
    document.form_upload.imbedded_progress_bar.value = 0;
  }
	document.form_upload.submit();

	if(imbedded_progress_bar){
		// If you are using an imbedded progress bar you must append your values here.
		// eg. var progress_link = "uber_uploader_progress.php?tmp_sid=<? print $tmp_sid; ?>&my_var=5";
		// They can be accessed in the progress bar with $_GET[\'my_var\']
		var progress_link = "'.$_SERVER['PHP_SELF'].'?tmp_sid='.$tmp_sid.'&upld=1&progress=1";
		frames[\'progress_frame\'].location.href = progress_link;
		document.getElementById(\'progress_frame\').style.display = "";
		//We\'ve opened the progress bar in an iframe so we return false to prevent the progress form from posting
		return false;
	} else {
		var upWin = window.open(\'\',\'uploadWin\',\'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=no,width=420,height=230,left=350,top=250\');
		if(upWin){
      upWin.focus();
    }
		return true;
	}
}

////////////////////////////////////////
// User has selected a new upload range
////////////////////////////////////////
function submitRefreshForm(){
	var r_index = document.form_upload.upload_range.selectedIndex;
	document.form_refresh.upload_range.value = document.form_upload.upload_range.options[\'r_index\'].value
	document.form_refresh.submit();
	return true;
}

////////////////////////////////////////
// Reset the file upload page
////////////////////////////////////////
function resetForm(){
	for(var i = 0; i < upload_range; i++){
    document.form_upload.elements[\'upfile_\' + i].value = "";
  }
	document.progress_bar.upload_button.disabled = false;
	document.getElementById(\'progress_frame\').style.display = "none";
}

</script>';
        echo '<!-- TMP_SID: '.$tmp_sid." -->\n<br>";

        if(isset($_GET['sucsess'])){
          echo '<font color="red">Upload was successful.</font>';
          if($admin)
            writelog('Admin uploaded a file with the progress bar.', 'upld');
          else
            writelog('<font color="yellow">User uploaded a file with the progress bar, check for suspicious files!</font>', 'upld', 'unknown', 1);
        }
        echo '<div align="center">
  <!-- If using https put a blank.html file in your directory -->
  <!-- and point the src to it. This will stop that annoying IE warning pop up -->
  <!-- eg. <iframe src="https://www.yoursite.com/blank.html" ... -->
  <iframe id="progress_frame" name="progress_frame" style="display: none;" frameborder="0" height="250" scrolling="no" width="500"></iframe>
<br>
<form name="form_upload" method="post" enctype="multipart/form-data"  action="/cgi-bin/upload.cgi?tmp_sid='.$tmp_sid.'" style="margin: 0px; padding: 0px;">
<input type="hidden" name="imbedded_progress_bar" value="0">
<!-- Include extra values you want passed to the upload script here. -->
<!-- eg. <input type="text" name="email" value="5"> -->
<!-- Access the value in the cgi with $query->param(\'email\'); -->
<!-- DO NOT USE "upfile_" for any of your values. -->
<input type="hidden" name="upload_range" value="'.$_POST['upload_range'].'">
<input type="hidden" name="uplddir" value="'.loc1.loc.'">
<input type="hidden" name="flredirect" value="'.phpSelf.'?loc='.locenc.'&upld=1">
<table cellpadding="0" cellspacing="2" width="100%">';
        if($multi_upload)
          echo '<tr><td><div align="center"><h3>Upload up to 10 files:</h3></div></td></tr>';
        else
          echo '<tr><td><div align="center"><h3>Upload a file:</h3></div></td></tr>';

        for($i = 0; $i < $_POST['upload_range']; $i++){
        	echo '<tr>';
        	echo '  <td align="center"><input type="file" name="upfile_'.$i.'" size="90"></td>';
        	echo '</tr>';
        }

        echo '    <tr>
    <td>&nbsp;</td>
  </tr>
</table>
</form>
<font color="red"><i>Warning: If a file already exists in this directory with the same name as one of the files being uploaded, it will be overwritten.</i></font>
<form name="progress_bar" target="uploadWin" method="post" action="'.phpSelf.'?tmp_sid='.$tmp_sid.'&upld=1&progress=1" onsubmit="return postIt();" style="margin: 0px; padding: 0px;">
  <input type="submit" name="upload_button" value="Upload File';
        if($multi_upload)
          echo '(s)';
        echo '"><br><br><br>
  <!-- Include extra values you want passed to the progress script here. (ONLY FOR POP UP)-->
  <!-- eg. <input type="hidden" name="my_var" value="5"> -->
  <!-- Access the value in the progress script with $_POST[\'my_var\']-->
</form>
<form name="form_refresh" method="post" action="'.phpSelf.'" style="margin: 0px; padding: 0px;">
    <input type="hidden" name="upload_range" value="">
</form>
</div>';


  /* end of code based on uber-uploader */

      }
    }



      // display search form
    echo '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td align="left">';
    if(loc != '/'){
      if(substr($parent_loc2, -1) == '/' && $parent_loc2 != '/')
        $parent_loc3 = substr($parent_loc2, 0, -1);
      else
        $parent_loc3 = $parent_loc2;
      echo '<img src="icons/folder.open.gif"><a title="Goto .'.$parent_loc3.'" href="'.$parent_loc.$adlnk.'">Parent Directory</a>';
    }

    echo '</td><td align="right">Search this directory '.note(5, 250, 280).': <form action="'.phpSelf.'" method="get">';
    echo '<input type="text" size="25" maxlength="255" value="'.htmlspecialchars($search_value).'" name="search_value" onFocus="if(this.value==\'Search\')this.value=\'\';" onBlur="if(this.value==\'\')this.value=\'Search\';"><br>';
    if($showsearch)
      echo '<input type="checkbox" name="showsearch" value="1" checked>Show only the search results?<br>';
    else
      echo '<input type="checkbox" name="showsearch" value="1">Show only the search results?<br>';
    if($exactmatch)
      echo '<input type="checkbox" name="exactmatch" value="1" checked>Show exact results only?<br>';
    else
      echo '<input type="checkbox" name="exactmatch" value="1">Show exact results only?<br>';
    echo '<input type="hidden" name="loc" value="'.loc.'">';
    if($search_value != 'Search')
      echo '<input type="button" value="Clear Search" onClick="JavaScript:location.href=\''.phpSelf.'?loc='.addslashes(locenc).'\'"> ';
    echo '<input type="submit" value="Search"></form>';
    echo '</td></tr></table>';

    if($search_value != 'Search')
      echo 'Search results are <b>bold</b>.<br><br>';

    echo '<table cellpadding="2" cellspacing="0" border="0">';

      // column headers to make them organizable
    echo '<tr><td></td><td><b>';
    if(is_file('filelist-dec.gif') && is_file('filelist-asc.gif')){
      if($ar1 == 'n')
        if($ar2 == 'd')
          echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=na"><img src="filelist-dec.gif" border="0">File Name</img></a>';
        else
          echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=nd"><img src="filelist-asc.gif" border="0">File Name</img></a>';
      else
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=na">File Name</a>';
      echo '</b></td>';

      echo '<td align="center"><b>';
      if($ar1 == 's')
        if($ar2 == 'a')
          echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=sd"><img src="filelist-asc.gif" border="0">Size</img></a>';
        else
          echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=sa"><img src="filelist-dec.gif" border="0">Size</img></a>';
      else
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=sa">Size</a>';
      echo '</b></td>';

      echo '<td align="center" width="50"><b>';
      if($ar1 == 't')
        if($ar2 == 'a')
          echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=td"><img src="filelist-asc.gif" border="0">Type</img></a>';
        else
          echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=ta"><img src="filelist-dec.gif" border="0">Type</img></a>';
      else
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=ta">Type</a>';
      echo '</b></td><td></td>';
    } else {
      if($ar1 == 'n' && $ar2 == 'a')
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=nd">File Name</a>';
      else
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=na">File Name</a>';
      echo '</b></td>';

      echo '<td align="center"><b>';
      if($ar1 == 's' && $ar2 == 'a')
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=sd">Size</a>';
      else
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=sa">Size</a>';
      echo '</b></td>';

      echo '<td align="center"><b>';
      if($ar1 == 't' && $ar2 == 'a')
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=td">Type</a>';
      else
        echo '<a href="'.phpSelf.'?loc='.locenc.$adlnk.$adlnk2.'&arange=ta">Type</a>';
      echo '</b></td><td></td>';
    }

    if($show_file_time)
      if($file_time == 'c')
        echo '<td><b>File Created</b></td>';
      else
        echo '<td><b>File Updated</b></td>';

    if($show_add_info)
      echo '<td><b>Additional Info</b></td>';

    echo '<td></td>';

    echo '</tr>';

    $array_of_dirs = array();
    $array_of_files = array();

    $i = 0;
    $j = 0;

      // open the current directory
    if($handle = opendir(loc1 . loc)){
      while(false !== ($file = readdir($handle))){

          // though this is kind of weird, I had the variables set up this way. I may change it in the future to get rid of one more line of code (mm optimization, tasty?)
        $file2 = $file;
        $file  = loc .  $file;

        if($current_user['read'] && is_file(loc1 . $file) && substr($file2, 0, 1) != '.'
        && strpos(strtolower($file), 'filelist') === false && strpos(strtolower($file), 'filemanage') === false && strpos($file, '..') === false && strpos($file, '#') === false && $file2 != cur_filename){

          $display_this_item = true;
          if(isset($hidden_items_ar) && (!$admin || ($admin && !$admin_see_hidden))){
            if(in_array($file, $hidden_items_ar))
              $display_this_item = false;
            else {
              $item_done = false;
              for($l = 0; $l < count($hidden_items_ar) && !$item_done; $l++)
                if(substr($file, 0, strlen($hidden_items_ar[$l])) == $hidden_items_ar[$l]){
                  $display_this_item = false;
                  $item_done = true;
                }
            }
          }
          if($display_this_item){

              // set use this to default, for whence it becomes true the loop will end
            $use_this = false;
              // run through each acceptable extension
            for($k = 0; $k < count($accept) && !$use_this; $k++){
                // if the file has the correct extension, continue
              if(strtolower($accept[$k]) == strtolower(substr($file2, strlen($file2) - strlen($accept[$k]), strlen($accept[$k])))){

                  // $organize_ord organizes the file names ignoring any leading 'the's and 'a's. With or without $organize_ord, the files are organized ignoring anything but letters and numbers
                if($organize_ord && strtolower(substr($file2, 0, 4)) == 'the ')
                  $orgn = ereg_replace("[^[:alnum:]]", '', strtolower(trim(substr($file2, 3))));
                elseif($organize_ord && strtolower(substr($file2, 0, 2)) == 'a ')
                  $orgn = ereg_replace("[^[:alnum:]]", '', strtolower(trim(substr($file2, 1))));
                elseif($organize_ord && strtolower(substr($file2, 0, 3)) == 'an ')
                  $orgn = ereg_replace("[^[:alnum:]]", '', strtolower(trim(substr($file2, 2))));
                else
                  $orgn = ereg_replace("[^[:alnum:]]", '', strtolower(trim($file2)));

                $ftype = get_ftype($file2);

                  // store file size (in bytes)
                $size = filesize(loc1 . $file);

                  // the organization type determines the order in which the variables are stored
                if($ar1 == 'n'){
                  $array_of_files[$j]['orgn']   = $orgn;
                  $array_of_files[$j]['ftype']  = $ftype;
                  $array_of_files[$j]['size']   = $size;
                } else
                if($ar1 == 't'){
                  $array_of_files[$j]['ftype']  = $ftype;
                  $array_of_files[$j]['orgn']   = $orgn;
                  $array_of_files[$j]['size']   = $size;
                } else
                if($ar1 == 's'){
                  $array_of_files[$j]['size']   = $size;
                  $array_of_files[$j]['orgn']   = $orgn;
                  $array_of_files[$j]['ftype']  = $ftype;
                }

                  // these variables are last since they don't affect organization
                $array_of_files[$j]['file']   = $file;
                $array_of_files[$j]['file2']  = $file2;
                $array_of_files[$j]['extkey'] = $k;

                $j++;
                  // get the heck out of the loop
                $use_this = true;
              } // if(strtolower($accept[$k]) == strtolower(substr($file2, ...
            } // for($k = 0; $k < count($accept) && $use_this != 1; $k++)
          } // if($display_this_item)
        } // if(is_file(loc1 . $file) && substr($file2, 0, 8) != 'filelist' && ...
        elseif($current_user['list'] && is_dir(loc1 . $file) && substr($file2, 0, 1) != '.'
        && strpos(strtolower($file2), 'filelist') === false && strpos(strtolower($file2), 'filemanage') === false
        && strpos(strtolower($file2), 'getid3') === false && strpos($file2, '#') === false && strpos($file, '..') === false){

          $display_this_item = true;
          if(isset($hidden_items_ar) && (!$admin || ($admin && !$admin_see_hidden))){
            if(in_array($file.'/', $hidden_items_ar))
              $display_this_item = false;
            else {
              $item_done = false;
              for($l = 0; $l < count($hidden_items_ar) && !$item_done; $l++)
                if(substr($file.'/', 0, strlen($hidden_items_ar[$l])) == $hidden_items_ar[$l]){
                  $display_this_item = false;
                  $item_done = true;
                }
            }
          }
          if($display_this_item){
              // $organize_ord organizes the directory names ignoring any leading 'the's and 'a's. With or without $organize_ord, the directories are organized ignoring anything but letters and numbers
            if($organize_ord && strtolower(substr($file2, 0, 4)) == 'the ')
              $array_of_dirs[$i]['orgn'] = ereg_replace("[^[:alnum:]]", '', strtolower(trim(substr($file2, 3))));
            elseif($organize_ord && strtolower(substr($file2, 0, 2)) == 'a ')
              $array_of_dirs[$i]['orgn'] = ereg_replace("[^[:alnum:]]", '', strtolower(trim(substr($file2, 1))));
            elseif($organize_ord && strtolower(substr($file2, 0, 2)) == 'an ')
              $array_of_dirs[$i]['orgn'] = ereg_replace("[^[:alnum:]]", '', strtolower(trim(substr($file2, 2))));
            else
              $array_of_dirs[$i]['orgn'] = ereg_replace("[^[:alnum:]]", '', strtolower(trim($file2)));

              // store directory name to array
            $array_of_dirs[$i]['file'] = $file;
            $array_of_dirs[$i]['file2'] = $file2;

            $i++;
          } // if($display_this_item)
        } // if(is_dir(loc1 . $file) && substr($file2, 0, 1) != '.' && ...
      } // while(false !== ($file = readdir($handle)))
        // close out of the directory
      closedir($handle);
    } // if($handle = opendir(loc1 . loc))

      // if any directories were found, store them to $array_of_all
    if(isset($array_of_dirs) && is_array($array_of_dirs) && count($array_of_dirs) > 0){
      sort($array_of_dirs);
      $array_of_all = $array_of_dirs;
    }
      // if any files were found store that info to $array_of_all
    if(isset($array_of_files) && is_array($array_of_files) && count($array_of_files) > 0){
      if($ar2 == 'a')
        sort($array_of_files);
      else
        rsort($array_of_files);
        // if directories were already stored to $array_of_all, then store each file key to $array_of_all
      if(count($array_of_dirs) > 0){
        for($i = 0; $i < count($array_of_files); $i++){
          $j = count($array_of_all);
          $array_of_all[$j]['file']   = $array_of_files[$i]['file'];
          $array_of_all[$j]['file2']  = $array_of_files[$i]['file2'];
          $array_of_all[$j]['extkey'] = $array_of_files[$i]['extkey'];
          $array_of_all[$j]['size']   = $array_of_files[$i]['size'];
          $array_of_all[$j]['ftype']  = $array_of_files[$i]['ftype'];
        }
      } else
        $array_of_all = $array_of_files;
          // if no directories were stored, just store the files to $array_of_all
    }

      // if no files or folders in this directory set to none
    if(!isset($array_of_all))
      $array_of_all = array();

    $row_clr = 0; // for alternating row colors

    $all_number_of_files = 0;
    $all_number_of_dirs = 0;
    $all_total_file_size = 0;

      // ready to display all the crap that was just stored
    foreach($array_of_all as $j => $file){

      $file   = $array_of_all[$j]['file'];
      $file2  = $array_of_all[$j]['file2'];

        // this section is for files, later is for directories
      if(is_file(loc1 . $file)){
          // nice long test, so that it only does the things it needs to do, when it needs to do it; and if only the finds are to be shown, only they will be
        if(($showsearch == 1 && isclosematch($file2, $search_value, $exactmatch, 0)) || $showsearch != 1 || $search_value == 'Search'){

          $extkey = $array_of_all[$j]['extkey'];

          $ftype  = $array_of_all[$j]['ftype'];
          $size   = $array_of_all[$j]['size'];

            // if there is a file type then get the file's name (no extension)
          if($ftype != 'none')
            $name2 = substr($file2, 0, strlen($file2) - strlen($ftype) - 1);
          else
            $name2 = $file2;

            // if additional info is enabled, test each file to see if it can extract any info from it
          if($show_add_info){
            $add_info = '';
              // if the file is a text file, display some of it's contents
            if($ftype == 'txt' || $ftype == 'list' || $ftype == 'nfo' || $ftype == 'log'
            || $ftype == 'diz' || $ftype == 'php' || $ftype == 'php3' || $ftype == 'phtml' || $ftype == 'php5'
            || $ftype == 'php4' || $ftype == 'js' || $ftype == 'xhtml' || $ftype == 'asp'
            || $ftype == 'xml' || $ftype == 'ini' || $ftype == 'inf' || $ftype == 'reg' || $ftype == 'c'
            || $ftype == 'cpp' || $ftype == 'h' || $ftype == 'hpp' || $ftype == 'sh' || $ftype == 'vbs'
            || $ftype == 'readme' || $ftype == 'shtml' || $ftype == 'nsi' || $ftype == 'cgi' || $ftype == 'tmpl'
            || $ftype == 'sql'){
              $contents  = file(loc1 . $file);
              if(magicQuotes)
                $contents2 = stripslashes($contents[0] . @$contents[1] . @$contents[2] . rtrim(@$contents[3]));
              else
                $contents2 = $contents[0] . @$contents[1] . @$contents[2] . rtrim(@$contents[3]);
              $contlen = strlen($contents2);
              if($contlen > 40){
                $contlen = 40;
                $contover = true;
              } else
                $contover = false;
              $add_info = 'Number of lines: ' . count($contents) . '; <b>Contents:</b> ' . str_replace("\n", ' :: ', str_replace("\r", '', htmlspecialchars(substr($contents2, 0, $contlen))));
              if($contover)
                $add_info .= '...';
            } else
              // if the file is an HMTL file, display it's title, or body, or contents
            if($ftype == 'htm' || $ftype == 'html'){
              $titover = false;
              $bodover = false;
              $conover = false;
              $contents = file_get_contents(loc1 . $file);
              if(magicQuotes)
                $contents = stripslashes($contents);

              $contents2 = strtolower($contents);
              if(strpos($contents2, '<title>') !== false){
                $titlepos1 = 7 + strpos($contents2, '<title>');
                $contents2 = substr($contents2, $titlepos1);
                if(strpos($contents2, '</title>') !== false){
                  $titlepos2 = strpos($contents2, '</title>');
                  if($titlepos2 > 40){
                    $titlepos2 = 40;
                    $titover = true;
                  }
                  $add_info = '<b>Title:</b> ' . htmlspecialchars(substr($contents, $titlepos1, $titlepos2));
                  if($titover)
                    $add_info .= '...';
                }
              } else
              if(strpos($contents2, '<body') !== false){
                $bodypos1 = 5 + strpos($contents2, '<body');
                $contents2 = substr($contents2, $bodypos1);
                $bodypos3 = 1 + strpos($contents2, '>');
                $contents2 = substr($contents2, $bodypos3);
                if(strpos($contents2, '</body>') !== false){
                  $bodypos2 = strpos($contents2, '</body>');
                  if($bodypos2 > 40){
                    $bodypos2 = 40;
                    $bodover = true;
                  }
                  $bodycont = substr($contents, $bodypos1 + $bodypos3, $bodypos2);
                  $add_info = '<b>Body:</b> ' . str_replace("\n", ' :: ', str_replace("\r", '', htmlspecialchars($bodycont)));
                  if($bodover)
                    $add_info .= '...';
                }
              } else {
                $cont_len = strlen($contents);
                if($cont_len > 40){
                  $cont_len = 40;
                  $conover = true;
                }
                $add_info = '<b>Contents:</b> ' . str_replace("\n", ' :: ', str_replace("\r", '', htmlspecialchars(substr($contents, 0, $cont_len))));
                if($conover)
                  $add_info .= '...';
              }
            } else

             // supported by 4.3.2: GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP, IFF, JP2, JPX, JB2, JPC, XBM, and WBMP
            if($php_version[0] > 4 || ($php_version[0] == 4 && $php_version[1] > 3) || ($php_version[0] == 4 && $php_version[1] == 3 && $php_version[2] >= 2)){
              if($ftype == 'gif' || $ftype == 'jpg' || $ftype == 'jpeg'
              || $ftype == 'png' || $ftype == 'swf' || $ftype == 'swc'
              || $ftype == 'psd' || $ftype == 'tiff' || $ftype == 'bmp'
              || $ftype == 'iff' || $ftype == 'jp2' || $ftype == 'jpx'
              || $ftype == 'jb2' || $ftype == 'jpc' || $ftype == 'xbm'
              || $ftype == 'wbmp' || $ftype == 'tif' || $ftype == 'ico')
                if($tmp = @getimagesize(loc1 . $file))
                  $add_info = 'Resolution: ' . $tmp[0] . 'x' . $tmp[1];
            } else {
                // supported by 4.3.0: GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP, and IFF
              if($ftype == 'gif' || $ftype == 'jpg' || $ftype == 'jpeg'
              || $ftype == 'png' || $ftype == 'swf' || $ftype == 'swc'
              || $ftype == 'psd' || $ftype == 'tiff' || $ftype == 'bmp'
              || $ftype == 'iff' || $ftype == 'tif' || $ftype == 'ico')
                if($tmp = @getimagesize(loc1 . $file))
                  $add_info = 'Resolution: ' . $tmp[0] . 'x' . $tmp[1];
            }
          }

            // if getid3 is going to be called, set up $filename, then get info
          if($show_add_info && $getid3_true && ($add_info == '' || !isset($add_info))){
            $filename = loc1 . $file;
            $getID3 = new getID3;
            $fileinfo = $getID3->analyze($filename);

            $add_info = '';

            if($getid3_true && isset($fileinfo['video']['resolution_x'])){
              if(isset($fileinfo['bitrate']))
                $file_br = $fileinfo['bitrate'];
              if(isset($fileinfo['playtime_string']))
                $add_info = 'Length: ' . $fileinfo['playtime_string'] . ';';
              $add_info .= ' Resolution: ' . $fileinfo['video']['resolution_x'] . 'x' . $fileinfo['video']['resolution_y'] . ';';
              if(isset($file_br))
                $add_info .= ' Bit rate: ' . round($file_br / 1000) . ' kbps;';
              if(isset($fileinfo['video']['codec']))
                $add_info .= ' Codec: ' . $fileinfo['video']['codec'];
            } else
            if($getid3_true && isset($fileinfo['audio']['bitrate'])){
              $file_br = $fileinfo['bitrate'];
              $add_info = 'Length: ' . $fileinfo['playtime_string'] . '; Bit rate: ' . round($file_br / 1000) . ' kbps';
              if($ftype == 'wma')
                $add_info .= ' (MP3 equiv: ' . round($file_br / 600) . ' kbps)';
            }
          }

          $file_size1 = filesize(loc1 . $file);
          $file_size = filesz($file_size1);
          if($show_dir_size){
            $all_number_of_files++;
            $all_total_file_size += $file_size1;
          }
          echo "\n".'<tr';
          if($altern_line_color)
            if($row_clr <= 0){
              echo ' bgcolor="'.$altern_color.'"';
              $row_clr++;
            } else
              $row_clr--;
          echo '><td align="right"><a title="Open file '.$file.' in separate window" ';
          $fileenc = str_replace('&', '%26', $file);
          if($force_download != 0)
            echo 'href="'.phpSelf.'?forcedownloadfile='.$fileenc.'">';
          else
            echo 'target="_blank" href="'.cur_dir.$fileenc.'">';
          $disp_def = true;
          if($show_exif_thumb && strpos($file, '\'') === false && ($ftype == 'jpeg' || $ftype == 'jpg' || $ftype == 'tiff' || $ftype == 'tif') && function_exists('exif_read_data')){
            $image = loc1 . $file;
            if($image_info = @getimagesize($image)){
              if($image_info[0] < $image_info[1]){
                $ratio = $image_info[0] / $image_info[1];
                $thumb_height = 32;
                $thumb_width = round($thumb_height * $ratio);
              } else {
                $ratio = $image_info[1] / $image_info[0];
                $thumb_width = 32;
                $thumb_height = round($thumb_width * $ratio);
              }
              $exif = @exif_read_data($image, 'THUMBNAIL', true);
              if($exif !== false){
                echo '<img width="'.$thumb_width.'" height="'.$thumb_height.'" border="0" src="'.phpSelf.'?showthumb=1&image='.$image.'"></a><br><br>';
                $disp_def = false;
              }
            }
          }
          if($disp_def && isset($iconlink[$extkey]))
            echo '<img border="0" src="'.$iconlink[$extkey].'">';
          echo '</a></td><td><a title="Open file '.$file.'" href="';
          if($force_download != 1 && $force_download != 0)
            echo phpSelf.'?forcedownloadfile='.$fileenc.'">';
          else
            echo cur_dir.$fileenc.'">';
          if(strlen($name2) > $name_length)
            $name2 = substr($name2, 0, $name_length - $trunc_offset1) . '...' . substr($name2, strlen($name2) - ($trunc_offset1 - 3));
            // if there is a search occuring, and the test of the search string in the isclosematch() function returns true; then bold the name so it can be seen
          if($search_value != 'Search' && isclosematch($file2, $search_value, $exactmatch, !$exactmatch))
            echo '<b>'.$name2.'</b>';
          else
            echo $name2;
          echo '</a></td><td align="center" width="75">';
          echo $file_size . '</td>';
          echo '<td align="center">';
          echo $ftype . '</td><td align="center">';
            // if the file's creation time is newer than the current time - the "new time" deadline (set above in seconds) then display "new"
          if($display_new && filectime(loc1 . $file) > time() - $new_time_secs)
            echo '<font color="red">New</font>';
          elseif($display_updated && filemtime(loc1 . $file) > time() - $new_time_secs)
            echo '<font color="yellow">Updated</font>';
          echo '</td>';
          if($show_file_time){
            echo '<td><font size="'.$font_size.'">';
            if($file_time == 'c')
              echo date($file_time_date, filectime(loc1 . $file));
            else
              echo date($file_time_date, filemtime(loc1 . $file));
            echo '</font></td>';
          }
          if($show_add_info)
            echo '<td><font size="'.$font_size.'">' . $add_info . '</font></td>';
          echo '<td><table cellpadding="2" cellspacing="0" border="0"><tr><td>';
          if($current_user['delete'])
            echo '<font size="'.$font_size.'"><a title="Delete file" href="'.phpSelf.'?loc='.locenc.'&del='.$fileenc.'">Del</a></font>';
          echo '</td><td>';
          if($current_user['write'])
            echo '<font size="'.$font_size.'"><a title="Copy file" href="'.phpSelf.'?loc='.locenc.'&cpy='.$fileenc.'">Copy</a></font>';
          echo '</td><td>';
          if($current_user['write'] && $current_user['delete'])
            echo '<font size="'.$font_size.'"><a title="Cut (move) file" href="'.phpSelf.'?loc='.locenc.'&cut='.$fileenc.'">Cut</a></font>';
          echo '</td></tr><tr><td>';
          if($current_user['append'])
            echo '<font size="'.$font_size.'"><a title="Edit text-based file" href="'.phpSelf.'?loc='.locenc.'&edit='.$fileenc.'">Edit</a></font>';
          echo '</td><td>';
          if($current_user['read'])
            echo '<font size="'.$font_size.'"><u><a title="Click to get properties of file" onMouseOver="this.style.cursor=\'move\'" onClick="JavaScript:window.open(\''.phpSelf.'?loc='.addslashes(locenc).'&prop='.addslashes($fileenc).'\',\'properties\',\'width=450,height=580,dependent=yes,location=no,scrollbars=yes,menubar=no,status=no,resizable=yes\')">Prop</a></u></font>';
          echo '</td><td>';
          if($current_user['append'])
            echo '<font size="'.$font_size.'"><a title="Rename file" href="'.phpSelf.'?loc='.locenc.'&ren='.$fileenc.'">Ren</a></font>';
          echo '</td><td>';
          //if($admin && (!isset($hidden_items_ar) || !in_array($file, $hidden_items_ar)))
          //  echo '<font size="'.$font_size.'"><a title="Hide file" href="'.phpSelf.'?loc='.locenc.'&hide=1&hideitem='.$fileenc.'">Hide</a></font>';

          if($admin){
            $display_this_item = true;
            if(isset($hidden_items_ar)){
              if(in_array($file, $hidden_items_ar))
                $display_this_item = false;
              else {
                $item_done = false;
                for($i = 0; $i < count($hidden_items_ar) && !$item_done; $i++)
                  if(substr($file, 0, strlen($hidden_items_ar[$i])) == $hidden_items_ar[$i]){
                    $display_this_item = false;
                    $item_done = true;
                  }
              }
            }
            if($display_this_item)
              echo '<font size="'.$font_size.'"><a title="Hide file" href="'.phpSelf.'?loc='.locenc.'&hide=1&hideitem='.$fileenc.'">Hide</a></font>';
            else {
              echo '<font size="'.$font_size.'"><a title="Unhide file" href="'.phpSelf.'?loc='.locenc.'&hide=1&unhide='.$fileenc.'">Unhide</a></font>';
              if($show_dir_size){
                $all_number_of_files--;
                $all_total_file_size -= $file_size1;
              }
            }
          }
          echo '</td></tr></table></td></tr>';
        }

      } else
        // this section is for directories, previous was for files; also, exclude the '.' and '..' directories
      if(is_dir(loc1 . $file)){
          // if there is a search occuring, and the test of the search string in the isclosematch() function returns true, or not only search results are being displayed, or there is no search; then continue, so the results can be displayed
        if(($showsearch == 1 && isclosematch($file2, $search_value, $exactmatch, 0)) || $showsearch != 1 || $search_value == 'Search'){
          if(strlen($file2) > $name_length)
            $name2 = substr($file2, 0, $name_length - $trunc_offset1) . '...' . substr($file2, strlen($file2) - ($trunc_offset1 - 3));
          else
            $name2 = $file2;
          echo "\n".'<tr';
          if($altern_line_color)
            if($row_clr <= 0){
              echo ' bgcolor="'.$altern_color.'"';
              $row_clr++;
            } else
              $row_clr--;
          $fileenc = str_replace('&', '%26', $file);
          echo '><td align="right"><a title="Open directory '.$file.' in separate window" target="_blank" href="'.phpSelf.'?loc=.'.$fileenc.$adlnk.'"><img border="0" src="icons/folder.gif"></a></td><td><a title="Open directory '.$file.'" href="'.phpSelf.'?loc=.'.$fileenc.$adlnk.'">';
            // if there is a search occuring, and the test of the search string in the isclosematch() function returns true; then bold the name so it can be seen
          if($search_value != 'Search' && isclosematch($file2, $search_value, $exactmatch, !$exactmatch))
            echo "<b>$name2</b>";
          else
            echo $name2;
          echo '</a></td>';
          if($show_dir_size){
            clearscandir();
            scanfulldir(loc1 . $file);
            $all_number_of_files += $number_of_files;
            $all_number_of_dirs += $number_of_dirs + 1;
            $all_total_file_size += $total_file_size;
            echo '<td>'.filesz($total_file_size).'</td><td align="center">Dir';
          } else
            echo '<td colspan="2" align="center">Directory';
          echo '</td><td>';
            // if the directory has been modified since the deadline, then display it, if the directory is new, then display so, if not, then display "updated"
          if($display_new && filectime(loc1 . $file) > time() - $new_time_secs)
            echo '<font color="red">New</font>';
          elseif($display_updated && filemtime(loc1 . $file) > time() - $new_time_secs)
            echo '<font color="yellow">Updated</font>';

          echo '</td>';
          if($show_file_time){
            echo '<td><font size="'.$font_size.'">';
            if($file_time == 'c')
              echo date($file_time_date, filectime(loc1 . $file));
            else
              echo date($file_time_date, filemtime(loc1 . $file));
            echo '</font></td>';
          }
          if($show_add_info){
            echo '<td>';
            if($show_dir_size)
              echo 'Files: '.$number_of_files.'; Directories: '.$number_of_dirs;
            echo '</td>';
          }
          echo '<td><table cellpadding="2" cellspacing="0" border="0"><tr><td>';
          if($current_user['ddelete'])
            echo '<font size="'.$font_size.'"><a title="Delete directory" href="'.phpSelf.'?loc='.locenc.'&ddel='.$fileenc.'">Del</a></font>';
          echo '</td><td>';
          if($current_user['make'] && $current_user['write'])
            echo '<font size="'.$font_size.'"><a title="Copy directory" href="'.phpSelf.'?loc='.locenc.'&dcpy='.$fileenc.'">Copy</a></font>';
          echo '</td><td>';
          if($current_user['ddelete'] && $current_user['delete'] && $current_user['make'] && $current_user['write'])
            echo '<font size="'.$font_size.'"><a title="Cut (move) directory" href="'.phpSelf.'?loc='.locenc.'&dcut='.$fileenc.'">Cut</a></font>';
          echo '</td>';
          echo '<td></td>';
          echo '</tr><tr><td align="center">';
          if($admin){
            $display_this_item = true;
            if(isset($hidden_items_ar)){
              if(in_array($file.'/', $hidden_items_ar))
                $display_this_item = false;
              else {
                $item_done = false;
                for($i = 0; $i < count($hidden_items_ar) && !$item_done; $i++)
                  if(substr($file.'/', 0, strlen($hidden_items_ar[$i])) == $hidden_items_ar[$i]){
                    $display_this_item = false;
                    $item_done = true;
                  }
              }
            }
            if($display_this_item)
              echo '<font size="'.$font_size.'"><a title="Hide directory" href="'.phpSelf.'?loc='.locenc.'&hide=1&hideitem='.$fileenc.'">Hide</a></font>';
            else {
              echo '<font size="'.$font_size.'"><a title="Unhide directory" href="'.phpSelf.'?loc='.locenc.'&hide=1&unhide='.$fileenc.'/">Unhide</a></font>';
              if($show_dir_size){
                $all_number_of_files -= $number_of_files;
                $all_number_of_dirs -= $number_of_dirs + 1;
                $all_total_file_size -= $total_file_size;
              }
            }
          }
          echo '</td><td>';
          if($current_user['list'])
            echo '<font size="'.$font_size.'"><u><a title="Get properties of directory" onMouseOver="this.style.cursor=\'move\'" onClick="JavaScript:window.open(\''.phpSelf.'?loc='.addslashes(locenc).'&prop='.addslashes($fileenc).'\',\'properties\',\'width=430,height=450,dependent=yes,location=no,scrollbars=yes,menubar=no,status=no,resizable=yes\')">Prop</a></u></font>';
          echo '</td><td>';
          if($current_user['make'])
            echo '<font size="'.$font_size.'"><a title="Rename directory" href="'.phpSelf.'?loc='.locenc.'&ren='.$fileenc.'">Ren</a></font>';
          echo '</td><td>';
          if($adlnk != '' && $current_user['write'] && ((!isset($_GET['dcut']) && !isset($_GET['dcpy'])) || ((isset($_GET['dcut']) && substr($file.'/', 0, strlen($_GET['dcut'].'/')) != $_GET['dcut'].'/') || (isset($_GET['dcpy']) && substr($file.'/', 0, strlen($_GET['dcpy'].'/')) != $_GET['dcpy'].'/'))))
            echo '<font size="'.$font_size.'"><a title="Paste file/directory into this directory" href="'.phpSelf.'?loc='.$fileenc.$adlnk.'&paste=1">Paste</a></font>';

          echo '</td></tr></table></td></tr>';
        }
      }

    }

    echo '</table><br><br>';
    if(loc != '/')
      echo '<img src="icons/folder.open.gif"><a title="Goto .'.$parent_loc3.'" href="'.$parent_loc.$adlnk.'">Parent Directory</a>';

    if($show_all_stats && $show_dir_size && loc == '/' && $current_user['list']){
      echo '<br><br>There is a total of '.$all_number_of_dirs.' directories, containing '.$all_number_of_files.' files, with a total file size of '.filesz($all_total_file_size)."\n";
      $fout = fopen($logFile, 'w');
      $fp = fwrite($fout, time() . $line_break . $all_number_of_dirs . $line_break . $all_number_of_files . $line_break . $all_total_file_size . $line_break);
      fclose($fout);
    }
      // this area scans all subdirectories and stores the amount of files, directories, filesize, and time stamp into a file for access later
      // depending on the amount of files and directories, this could be a very long processes, so it doesn't happen every time a page loads
      // based on a variable set at the beginning of this file, it makes this refresh based on the amount of files and directories
      // this all boils down to the custom recursive scanfulldir() function. View that furthur down to see what is actually happening
      // it then takes all this information and displays it at the bottom of the page
    if($show_all_stats){
      $get_new_info = false;

      if(!is_file($logFile))
        $get_new_info = true;
      else {
        $array_of_log_file = file($logFile);
        if(trim($array_of_log_file[0]) < time() - $update_log_sec && !$show_dir_size)
          $get_new_info = true;
        else {
          $last_update     = trim($array_of_log_file[0]);
          $number_of_dirs  = trim($array_of_log_file[1]);
          $number_of_files = trim($array_of_log_file[2]);
          $total_file_size = trim($array_of_log_file[3]);
        }
      }

      if($get_new_info && !$show_dir_size){

        clearscandir();
        scanfulldir(loc1);

        $fout = fopen($logFile, 'w');
        $fp = fwrite($fout, time() . $line_break . $number_of_dirs . $line_break . $number_of_files . $line_break . $total_file_size . $line_break);
        fclose($fout);
        $last_update = time();
      }

      if(($show_dir_size && loc != '/') || !$show_dir_size || !$current_user['list'])
        echo '<br><br>As of ' . date("F d, Y H:i (O)", $last_update) . ' there is a total of '.$number_of_dirs.' directories, containing '.$number_of_files.' files, with a total file size of '.filesz($total_file_size)."\n";
    }
  }
} else {

  if(!isset($_GET['create'])){
    echo '<html><head><title>File Manage</title>';
    echo '</head><body bgcolor="#FFFFFF" text="#000000" vlink="#000000" alink="#000000" link="#000000">';
  }

  if($php_version[0] < 4 || ($php_version[0] == 4 && $php_version[1] < 3)){
    echo 'Server\'s PHP version is too old. It must be at least 4.3.0.<br>';
    echo 'Visit <a href="http://www.php.net">PHP.net</a> to get the newest version.';
  } else {

    // if the user is not logged in, make them.

    if(isset($lockout) && $lockout !== true){
      echo '<font color="red"><b>ERROR: Too many login attempts on this IP or username. You have been locked out for 3 minutes';

      echo '<script language="JavaScript">
  /*
  Author: Robert Hashemian
  http://www.hashemian.com/

  You can use this code in any manner so long as the author\'s
  name, Web address and this disclaimer is kept intact.
  *********************************************************/

  function calcage(secs, num1, num2){
    s = ((Math.floor(secs/num1)) % num2).toString();
    if(s.length < 2){
      s = "0" + s;
    }
    return "<b>" + s + "</b>";
  }

  function CountBack(secs){
    if(secs < 0){
      ';
      if(isset($_GET['loc']))
        echo 'location.href=\''.phpSelf.'?loc='.addslashes($_GET['loc']).'&req_login=1\';';
      else
        echo 'location.href=\''.phpSelf.'?loc=/&req_login=1\';';
      echo '      return;
    }
    var DisplayStr = DisplayFormat.replace(/%%M%%/g, calcage(secs,60,60));
    DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));

    document.getElementById("cntdwn").innerHTML = DisplayStr;
    if(CountActive){
      setTimeout("CountBack(" + (secs + CountStepper) + ")", SetTimeOutPeriod);
    }
  }

  function putspan(){
    document.write("<span id=\'cntdwn\' style=\'background-color:WHITE; color:red\'></span>");
  }

  var CountActive = true;
  var TargetDate = "'.date('m/d/Y h:i:s A', $lockout + (3 * 60)).'";
  var DisplayFormat = " (%%M%%:%%S%% minutes remain)";
  var CountStepper = -1;

  CountStepper = Math.ceil(CountStepper);
  var SetTimeOutPeriod = (Math.abs(CountStepper) - 1) * 1000 + 990;
  putspan();
  var dthen = new Date(TargetDate);
  var dnow = new Date("'.date('m/d/Y h:i:s A').'");
  var ddiff = new Date(dthen - dnow);
  var gsecs = Math.floor(ddiff.valueOf() / 1000);
  CountBack(gsecs);
</script>';

      echo '.</b></font><br>';
      writelog('<font color="red">User has been locked out for too many login attempts</font>', 'Login');
    } elseif(isset($lockout) && $lockout === true)
      echo '<font color="red"><b>ERROR: You have been perminantly banned.</b></font><br>';
    else {

      if(isset($_POST['loginsubmit'])){
        echo '<font color="red"><b>ERROR: Incorrect username or password.<br><br>Please try again.</b></font><br>';
        writelog('<font color="red">User failed to login</font>', 'Login');

          // prevent brute force login attempts
        $fout = fopen(loc1 . '/filelist/filelist-loginattempts-IP.list', 'a');
        $fp = fwrite($fout, $_SERVER['REMOTE_ADDR'].'~~~~~'.time()."\n");
        fclose($fout);

        $fout = fopen(loc1 . '/filelist/filelist-loginattempts-un.list', 'a');
        $fp = fwrite($fout, $un.'~~~~~'.time()."\n");
        fclose($fout);
      }

      if(!isset($_GET['create']))
        loginpage();

    }
  }

}

  // always display this info for obvious legal reasons
echo '<br><br><br><font size="-1"><a target="_blank" href="http://www.sourceforge.net/projects/filemanage/">Bobb\'s File Manage System</a> version ' . $version . '.<br>';
echo '&copy; 2004-2006 Bobb\'s File Manage System Development Team.<br>';
echo 'These pages are licensed under the <a href="http://www.opensource.org/licenses/gpl-license.php" target="_blank">GNU General Public License</a>.<br>';
echo 'These pages and the software that generates them are NOT covered by any kind of warranty, either expressed or implied.<br>';
echo 'Redistribution is permitted under the same license.</font>';

echo '</body></html>';

if($track_time || $development){
  $timeparts2 = explode(' ', microtime());
  $starttime1 = $timeparts1[1].substr($timeparts1[0], 1);
  $endtime1 = $timeparts2[1].substr($timeparts2[0], 1);
  $time_elapsed1 = bcsub($endtime1, $starttime1, 4);
  echo "\n".'<!-- Took '.$time_elapsed1.' seconds to load page -->'."\n";

  if(!isset($_GET['settings']) && !isset($_GET['fitness']) && !isset($_GET['console']) && !isset($_GET['log']) && !isset($_GET['recycle']) && !isset($_GET['manage']) && !isset($_GET['mysettings']) && !isset($_GET['paste']) && !isset($_GET['prop']) && !isset($_GET['req_login']) && !isset($_GET['customicon']))
    $ok = '1';
  else
    $ok = '0';

  if($ok || $development){

    if(!isset($un))
      $un = '*none*';

    if(defined('loc'))
      $loc = loc;
    elseif(isset($loc))
      $loc = '*none*';

    $fout = fopen(loc1 . '/filelist/filelist-fitness.log', 'a');
    $fp = fwrite($fout, $time_elapsed1.'~~~~~'.time().'~~~~~'.$ok.'~~~~~'.$un.'~~~~~'.$loc."\n");
    fclose($fout);

    if(filesize(loc1 . '/filelist/filelist-fitness.log') > $max_track_size * 1024){ // if the log file is larger than max_log_size
      $log_size = filesize(loc1 . '/filelist/filelist-fitness.log');
      $log_file_ar = file(loc1 . '/filelist/filelist-fitness.log');
      $removed_size = 0; // the value is the size in bytes that will be removed once the file is written again
      while($removed_size < $log_size - ($max_track_size * 1024)){
        $removed_size += strlen($log_file_ar[0]); // store the size of the line being removed
        array_shift($log_file_ar); // kick off the line being removed
      }
      $fout = fopen(loc1 . '/filelist/filelist-fitness.log', 'w');
      $fp = fwrite($fout, implode('', $log_file_ar));
      fclose($fout);
    }
  }

}



/******************************************************************************
 *     Below here are all the functions called by all the previous code.      *
 ******************************************************************************/



  // this function tests to see if first of all, filemanage logins exist; second
  // to see if the user is logged in on a valid login.
  // Some ideas and lines of code taken from OutSide Photos
  // (www.sourceforge.net/projects/outside-photos/) copyright 2004-2005 by
  // OutSide Photos Development Team under the GNU General Public License,
  // redistibution is allowed under the same licese. View the file LICENSE that
  // was packaged with this file, or download a copy at
  // www.opensource.org/licenses/gpl-license.php
  // bool logintest( void )
function logintest(){

    // make global so the rest of the program can access them
  global $un;
  global $pw;
  global $useremail;
  global $login;
  global $admin;
  global $perm;
  global $permtype;
  global $anonymous_user;
  global $uip;
  global $fp;
  $line_break = $GLOBALS['line_break'];
  $php_version = $GLOBALS['php_version'];

  $admin = false;
  $anonymous_user = false;

    // if either one of these files do not exist, some tampering has occured (or filelist is being run for the first time), reset all logins
  if(!is_file(loc1 . '/filelist/filelist-logins.list') || !is_file(loc1 . '/filelist/filelist-admin.php')){

    writelog('Login list or admin login file does not exist, creating one', 'nowhere', 'none', 0);

    $filename  = loc1 . '/filelist/filelist-admin.php';
    $filename2 = loc1 . '/filelist/filelist-logins.list';
    @unlink($filename);
    @unlink($filename2);

    $input_array[0] = $line_break . '<?PHP';
    $input_array[1] = 'admin';
    $input_array[2] = md5('password');  // "password" is the default password for the admin, this can be changed; it is stored and accessed in an md5 hash, so no one no where can find out what it is
    $input_array[3] = 0;                // this value is what actually makes the admin (or anyone) an admin
    $input_array[4] = 'basic';          // this is the permisstions tpye. It doesn't matter too much for admin, since he no 0 no matter what
    $input_array[5] = 'email@email.email'; // email needs to be changed in admin's profile
    $input_array[6] = '?>' . $line_break;

      // compile the string to be written to $filename
    $insertline = implode($line_break, $input_array);

      // this will be written to $filename2
    $insertline2 = 'admin';

      // write to file, if it fails, error out
    if(!$handle = fopen($filename2, 'a')){
      echo "Cannot open file ($filename2). Likely to be a permissions problem.";
      exit;
    }
    if(fwrite($handle, $insertline2 . $line_break) === FALSE){
      echo "Cannot write to file ($filename2). Likely to be a permissions problem.";
      exit;
    }
    fclose($handle);

      // write to file, if it fails, error out
    if(!$handle = fopen($filename, 'a')){
      echo "Cannot open file ($filename). Likely to be a permissions problem.";
      exit;
    }
    if(fwrite($handle, $insertline) === FALSE){
      echo "Cannot write to file ($filename). Likely to be a permissions problem.";
      exit;
    }
    fclose($handle);

    $login    = false;
    $admin    = false;
    $useremail = '';
    $perm     = 10;
    $permtype = 'basic';
    return false;

  } else {

    if(is_file(loc1 . '/filelist/filelist-bannedIPs.list') && isset($_SERVER['REMOTE_ADDR'])){
      $GLOBALS['banned_ar'] = file(loc1 . '/filelist/filelist-bannedIPs.list');
      $done = false;
      for($i = 0; $i < count($GLOBALS['banned_ar']) && !$done; $i++){
        if($_SERVER['REMOTE_ADDR'] == trim($GLOBALS['banned_ar'][$i])){
          $login    = false;
          $admin    = false;
          $useremail = '';
          $perm     = 10;
          $permtype = 'basic';
          $GLOBALS['lockout'] = true;
          return false;
        }
      }
    }

    if(is_file(loc1 . '/filelist/filelist-loginattempts-IP.list') || is_file(loc1 . '/filelist/filelist-loginattempts-un.list')){
      if(is_file(loc1 . '/filelist/filelist-loginattempts-IP.list') && isset($_SERVER['REMOTE_ADDR'])){
        $IP_ar = file(loc1 . '/filelist/filelist-loginattempts-IP.list');
        $i = 0;
        foreach($IP_ar as $IP_info){
          $sub_array = explode('~~~~~', trim($IP_info));
          if($_SERVER['REMOTE_ADDR'] == $sub_array[0]){
            $time = $sub_array[1];
            $i++;
          }
        }
        if($i >= 5 && time() - (3 * 60) < $time){
          $login    = false;
          $admin    = false;
          $useremail = '';
          $perm     = 10;
          $permtype = 'basic';
          $GLOBALS['lockout'] = $time;
          return false;
        }
      }

      if(is_file(loc1 . '/filelist/filelist-loginattempts-un.list') && isset($_POST['un'])){
        $un_ar = file(loc1 . '/filelist/filelist-loginattempts-un.list');
        $i = 0;
        foreach($un_ar as $un_info){
          $sub_array = explode('~~~~~', trim($un_info));
          if($_POST['un'] == $sub_array[0]){
            $time = $sub_array[1];
            $i++;
          }
        }
        if($i >= 5 && time() - (3 * 60) < $time){
          $login    = false;
          $admin    = false;
          $useremail = '';
          $perm     = 10;
          $permtype = 'basic';
          $GLOBALS['lockout'] = $time;
          return false;
        }
      }
    }

      // set default (guilty until proven innocent)
    $need_cookie = false;

      // if the form was submitted, store username and password to variable and set $need_cookie to true so one will be created
    if(isset($_POST['loginsubmit'])){
      $un = $_POST['un'];
      $pw = md5($_POST['pw']);
      $fp = phpSelf;
      $need_cookie = true;
    } else
      // if a session already exists, store it's contents to variables, if it is an anonymous login, let them through
    if(@session_start() && !@is_null($_SESSION['username']) && !isset($_GET['anonymous'])){
      @$un  = $_SESSION['username'];
      @$pw  = $_SESSION['password'];
      @$uip = $_SESSION['IP'];
      @$fp  = $_SESSION['filepath'];

      if($GLOBALS['allow_anonymous'] && $un == 'anonymous' && $pw == md5('anonymous') && !isset($_GET['req_login'])){
        $login    = true;
        $admin    = false;
        $perm     = $GLOBALS['anonym_perm'];
        $permtype = $GLOBALS['anonym_perm_type'];
        $useremail = '';
        $ul_value = 0;
        $anonymous_user = true;
        return true;
      } else
      if($uip != $_SERVER['REMOTE_ADDR']){
        $login    = false;
        $admin    = false;
        $perm     = 10;
        $permtype = 'basic';
        $useremail = '';
        $ul_value = 0;
        return false;
      }
    } else {
      if($GLOBALS['allow_anonymous'] && !isset($_GET['req_login'])
      && ($GLOBALS['auto_anonym_login'] || isset($_GET['anonymous']))){
        $un = 'anonymous';
        $pw = md5('anonymous');
        session_id($un);
        @session_start();
        if($php_version[0] > 4 || ($php_version[0] == 4 && $php_version[1] > 3) || ($php_version[0] == 4 && $php_version[1] == 3 && $php_version[2] >= 2))
          session_regenerate_id();
        $_SESSION['username'] = $un;
        $_SESSION['password'] = $pw;
        $_SESSION['filepath'] = phpSelf;
        writelog('Anonymous user logged in', 'Login', 'none', 3);
        $login    = true;
        $admin    = false;
        $perm     = $GLOBALS['anonym_perm'];
        $permtype = $GLOBALS['anonym_perm_type'];
        $useremail = '';
        $ul_value = 0;
        $anonymous_user = true;
        return true;
      } else {
        $login    = false;
        $admin    = false;
        $perm     = 10;
        $permtype = 'basic';
        $useremail = '';
        $ul_value = 0;
        return false;
      }
    }

      // if the function hasn't ended yet, go through the username and password variables to test their authenticity
    $user_list = file(loc1 . '/filelist/filelist-logins.list');
    foreach($user_list as $all_users){
      if(strtolower($un) == strtolower(trim($all_users))){
        if(!is_file(loc1 . '/filelist/filelist-' . $un . '.php')){
          $login    = false;
          $admin    = false;
          $perm     = 10;
          $permtype = 'basic';
          $useremail = '';
          return false;
        } else {
          $array_of_users_file = file(loc1 . '/filelist/filelist-' . $un . '.php');
          if($pw == trim($array_of_users_file[3]) && $fp == phpSelf){// echo trim($array_of_users_file[5]);
            if(trim($array_of_users_file[7]) != 'Pending Admin Authorization' || (trim($array_of_users_file[7]) == 'Pending Admin Authorization' && $GLOBALS['allow_anonymous'] && $GLOBALS['anonym_perm'] == trim($array_of_users_file[4]) && $GLOBALS['anonym_perm_type'] == trim($array_of_users_file[5]))){
              if(trim($array_of_users_file[7]) == 'Pending Admin Authorization' && $GLOBALS['allow_anonymous'] && $GLOBALS['anonym_perm'] == trim($array_of_users_file[4]) && $GLOBALS['anonym_perm_type'] == trim($array_of_users_file[5]))
                $GLOBALS['not_authorized'] = 1;
              $login = true;
              $perm = trim($array_of_users_file[4]);
              $permtype = trim($array_of_users_file[5]);
              $useremail = trim($array_of_users_file[6]);
              if((($perm == 0 && $permtype != 'hex') || (hexdec($perm) == 0)) || $un == 'admin')
                $admin = true;
              if($un == 'admin')
                $perm = 0;
              if($need_cookie){
                session_id($un);
                @session_start();
                if($php_version[0] > 4 || ($php_version[0] == 4 && $php_version[1] > 3) || ($php_version[0] == 4 && $php_version[1] == 3 && $php_version[2] >= 2))
                  session_regenerate_id();
                $_SESSION['username'] = $un;
                $_SESSION['password'] = $pw;
                $_SESSION['IP']       = $_SERVER['REMOTE_ADDR'];
                $_SESSION['filepath'] = phpSelf;
                setcookie('filelist-user', $un, time() + 60 * 60 * 24 * 30); // remember username for 30 days
                writelog('User logged in', 'Login', 'none', 4);
              }
              return true;
            } else
              if(trim($array_of_users_file[7]) == 'Pending Admin Authorization')
                $GLOBALS['not_authorized'] = 1;
          }
        } // if(is_file(loc1 . '/filelist/filelist-' . $un . '.php'))
      } // if(strtolower($un) == strtolower(trim($user_list[$i])))
    } // foreach($user_list as $all_users)
  } // if(!is_file(loc1 . '/filelist/filelist-logins.list') ...

    // if the functions still hasn't ended, "no login for you!"
  $login    = false;
  $admin    = false;
  $perm     = 10;
  $permtype = 'basic';
  $useremail = '';
  $ul_value = 0;
  return false;
} // end of logintest()



  // this displays the form that users use to login to the File Manage system
  // void loginpage( void )
function loginpage(){

    // if admin has not authorized this user, deny them, but tell them why
  if(isset($GLOBALS['not_authorized']) && $GLOBALS['not_authorized'] == 1){
    echo '<script language="JavaScript">';
    echo 'alert("An admin has not authorized you yet. Please try again later");';
    echo '</script>';
  }

  if(!isset($_GET['loc']))
    $loc = '/';
  else
    if(magicQuotes)
      $loc = stripslashes($_GET['loc']);
    else
      $loc = $_GET['loc'];

  if(isset($_COOKIE['filelist-user'])){
    echo '<body onLoad="document.login.pw.focus();">';
    $cookieuser = $_COOKIE['filelist-user'];
  } else {
    echo '<body onLoad="document.login.un.focus();">';
    $cookieuser = '';
  }

  echo '<br><form name="login" method="post" action="'.phpSelf.'?redirect=login&loc='.$loc.'">';
  echo '<table cellpadding="4" cellspacing="0" border="0" align="center">';
  echo '<tr><td>Username:</td>';
  echo '<td><p align=center><input type="text" maxlength="64" name="un" size="18" value="'.$cookieuser.'"></p></td>';
  echo '<td>Password:</td>';
  echo '<td><p align="center"><input type="password" name="pw" size="18" value=""></p></td>';
  echo '<td><p align="center"><input type="submit" size="150" name="loginsubmit" value="Log In"></p></td>';
  echo '</tr>';
  echo '<tr><td colspan="2" valign="bottom" align="left">';
  if($GLOBALS['allow_anonymous'])
    echo '<br><a href="'.phpSelf.'?redirect=login&loc='.$loc.'&anonymous=1">[Login Anonymously]</a> '.note(4, 250, 210);
  echo '</td>';
  echo '<td colspan="3" valign="bottom" align="right"><br><a href="'.phpSelf.'?create=1">[Create an Account]</a></td>';
  echo '</tr>';
  echo '</table></form>';

  $_GET['req_login'] = $loc;

} // end of loginpage()



  // this function checks if the user name uses a correct character set
  // then checks to see whether or not the username is already in use.
  // bool check_user( str 'user' )
function check_user($user){
  $user = strtolower($user);
  if(strpos($user, 'admin') !== false || strpos($user, 'anonymous') !== false || $user == 'settings' || $user == 'passcode'){
    echo '<br><font color="red">Invalid username.</font><br><br>';
    return false;
  }

  if(strlen($user) < 5){
    echo '<br><font color="red">Username must be at least five characters long.</font><br><br>';
    return false;
  }

  $array_of_users = file(loc1 . '/filelist/filelist-logins.list'); // file with all users
  foreach($array_of_users as $i => $user_name)
    $users_array[$i] = trim($user_name);
  if(in_array($user, $users_array)){
    echo '<br><font color="red">User already exists.</font><br><br>';
    return false;
  }

    // characters 48-57, 65-90, 97-122 (alpha numerics)
  for($i = 48; $i <= 57; $i++)
    $chr_array[] = chr($i);
  for($i = 65; $i <= 90; $i++)
    $chr_array[] = chr($i);
  for($i = 97; $i <= 122; $i++)
    $chr_array[] = chr($i);
  $chr_array[] = chr(45);
  $chr_array[] = chr(95);

  for($i = 0; $i < strlen($user); $i++){
    $char = substr($user, $i, 1);
    $chr_done = false;
    for($j = 0; $j < count($chr_array) && !$chr_done; $j++)
      if($chr_array[$j] == $char)
        $chr_done = true;
    if(!$chr_done){
      echo '<font color="red">Username contains invalid character, "'. $char .'"</font><br>';
      return false;
    }
  }

  return true;
} // end of check_user()



  // this function is for when a user logs in as a new users (that the admin has
  // already created)
  // void make_user( void )
function make_user(){

  echo '<html><head><title>File Manage - create user</title>';
  echo '</head><body bgcolor="#FFFFFF" text="#000000" vlink="#000000" alink="#000000" link="#000000">';

  $line_break = $GLOBALS['line_break'];
  $loc = './';

  if(!isset($_GET['priv'])){

    $showform = true;

    if(isset($_POST['profile'])){
      $uemail = trim($_POST['uemail']);
      $user = strtolower($_POST['user']);
      $password  = $_POST['password'];
      if(strlen($uemail) > 5 && strpos($uemail, '@') !== false && strpos($uemail, '.') !== false){
        $array_of_users = file(loc1 . '/filelist/filelist-logins.list');
        $done = false;
        for($i = 0; $i < count($array_of_users) && !$done; $i++){
          if($user == trim($array_of_users[$i]) && is_file(loc1 . '/filelist/filelist-'. $user .'.php')){
            $array_of_user = file(loc1 . '/filelist/filelist-'. $user .'.php');
            if(trim($array_of_user[3]) == ''){
              if(md5($_POST['passcode']) == trim($array_of_user[7])){
                $array_of_user[6] = $uemail . $line_break;
                if($user != $password){
                  if(!$GLOBALS['strong_pw_enforce'] || strong_password($password)){
                    if(isset($_POST['cpassword']) && $password != ''){
                      if($password != '**********'){
                        $cpassword = $_POST['cpassword'];
                        if($password == $cpassword){
                          $array_of_user[3] = md5($password) . $line_break;
                          $array_of_user[7] = '';
                          $write = implode('', $array_of_user);
                          $fout = fopen(loc1 . '/filelist/filelist-'. $user .'.php', 'w');
                          $fp = fwrite($fout, $write);
                          fclose($fout);
                          echo '<br>User created, <a href="'.phpSelf.'">Click here to continue.</a><br><br>';
                          $showform = false;
                          writelog('User ('.$user.') registered their profile', 'create');
                        } else
                          echo '<br><font color="red">Passwords do not match.</font><br><br>';
                      } else
                        echo '<br><font color="red">Password is an invalid value.</font><br><br>';
                    }
                  } else
                    echo '<br><font color="red">Password is not a strong password. Password must be at least 8 characters long and use at least two types of characters (uppercase, lowercase, numbers, or symbols).</font><br><br>';
                } else
                  echo '<br><font color="red">Password cannot be the same as user name.</font><br><br>';
              } else
                echo '<br><font color="red">Passcode is invalid.</font><br><br>';
            } else
              echo '<br><font color="red">Username is invalid. Admin has not submitted this username to logins.</font><br><br>';
            $done = true;
          }
        }
        if(!$done)
          echo '<br><font color="red">Username is invalid. Admin has not submitted this username to logins.</font><br><br>';

      } else
        echo '<br><font color="red">You must enter a valid email address.</font><br><br>';
    } elseif(isset($_POST['request']) && $GLOBALS['allow_login_request']){
      $uemail = trim($_POST['uemail']);
      $user = strtolower(trim($_POST['user']));
      $password  = $_POST['password'];
      if(strlen($uemail) > 5 && strpos($uemail, '@') !== false && strpos($uemail, '.') !== false){
        if(check_user($user)){
          if($user != $password){
            if(!$GLOBALS['strong_pw_enforce'] || strong_password($password)){
              if(isset($_POST['cpassword']) && $password != ''){
                if($password != '**********'){

                  $cpassword = $_POST['cpassword'];
                  if($password == $cpassword){

                    $array_of_user[0] = NULL;
                    $array_of_user[1] = '<?PHP';
                    $array_of_user[2] = $user;
                    $array_of_user[3] = md5($password);
                    $array_of_user[4] = $GLOBALS['anonym_perm'];
                    $array_of_user[5] = $GLOBALS['anonym_perm_type'];
                    $array_of_user[6] = $uemail;
                    $array_of_user[7] = 'Pending Admin Authorization';
                    $array_of_user[8] = '?>';
                    $array_of_user[9] = NULL;

                    $fout = fopen(loc1 . '/filelist/filelist-'. $user .'.php', 'w');
                    $fp = fwrite($fout, implode($line_break, $array_of_user));
                    fclose($fout);

                    $fout = fopen(loc1 . '/filelist/filelist-logins.list', 'a');
                    $fp = fwrite($fout, $user . $line_break);
                    fclose($fout);

                    $fout = fopen(loc1 . '/filelist/filelistloginscount.list', 'a');
                    $fp = fwrite($fout, '1' . $line_break);
                    fclose($fout);
                    echo '<br>User created, <a href="'.phpSelf.'">Click here to continue.</a><br><br>';
                    $showform = false;
                    writelog('User ('.$user.') created their profile', 'create', 'none', 1);
                  } else
                    echo '<br><font color="red">Passwords do not match.</font><br><br>';
                } else
                  echo '<br><font color="red">Password is an invalid value.</font><br><br>';
              }
            } else
              echo '<br><font color="red">Password is not a strong password. Password must be at least 8 characters long and use at least two types of characters (uppercase, lowercase, numbers, or symbols).</font><br><br>';
          } else
            echo '<br><font color="red">Password cannot be the same as user name.</font><br><br>';
        } else
          echo '<br><font color="red">Username is invalid.</font><br><br>';
      } else
        echo '<br><font color="red">You must enter a valid email address.</font><br><br>';
    } else
      echo '<br><br><br>';
    if($showform){
      if(!isset($user))
        $user = '';
      if(!isset($uemail))
        $uemail = '';

      if($GLOBALS['allow_login_request']){
        echo '<table cellpadding="8" cellspacing="0" border="1"><tr><td>';

        echo 'Create an account for the File Manage System. ';
        if($GLOBALS['allow_anonymous'])
          echo 'This server allows anonymous users, so you will be able to log in right away with the same permissions as the anonymous users. Once the admin accepts you, you may be given higher permissions.';
        else
          echo 'This does not mean you can log in right away. An admin must accept you before you are allowed to login. At that point you will be given a set of permissions.';
        echo '<div align="center"><font size="+1"><b>Create Profile</b></font></div>';
        echo '<br><form name="request" method="post" action="'.phpSelf.'?loc='.$loc.'&create=1\">';
        echo '<table cellpadding="3" cellspacing="0" border="0" align="center">';
        echo '<tr><td align="right">Username:</td><td><input type="text" name="user" size="30" value="'.htmlspecialchars($user).'"></td></tr>';
        echo '<tr><td align="right">My email:</td><td><input type="text" name="uemail" size="30" value="'.htmlspecialchars($uemail).'"></td></tr>';
        echo '<tr><td colspan="2"></td></tr>';
        echo '<tr><td align="right">My Password:</td><td><input type="password" name="password" size="30" value=""></td></tr>';
        echo '<tr><td align="right">Confirm password:</td><td><input type="password" name="cpassword" size="30" value=""></td></tr>';
        echo '<tr><td colspan="2" align="center"><input type="submit" name="request" size="150" value="Create My Account"> ';
        echo '<input type="button" size="150" value="Cancel" onClick="JavaScript:location.href=\''.phpSelf.'\'"></td></tr>';
        echo '</table></form>';

        echo '</td><td>';
      }

      echo 'This is for users that an admin has already created. The admin should have given you a passcode to authorize your login name creation. If the admin did not, please contact the admin again. Without the passcode you will be unable to log in. '.note(1, 200, 200).'<br>';
      echo '<div align="center"><font size="+1"><b>Create Profile</b></font></div>';
      echo '<br><form name="profile" method="post" action="'.phpSelf.'?loc='.$loc.'&create=1\">';
      echo '<table cellpadding="3" cellspacing="0" border="0" align="center">';
      echo '<tr><td align="right">Admin suplied username:</td><td><input type="text" name="user" size="30" value="'.htmlspecialchars($user).'"></td></tr>';
      echo '<tr><td align="right">My email:</td><td><input type="text" name="uemail" size="30" value="'.htmlspecialchars($uemail).'"></td></tr>';
      echo '<tr><td colspan="2"></td></tr>';
      echo '<tr><td align="right">Admin suplied passcode:</td><td><input type="password" name="passcode" size="30" value=""></td></tr>';
      echo '<tr><td colspan="2"></td></tr>';
      echo '<tr><td align="right">My Password:</td><td><input type="password" name="password" size="30" value=""></td></tr>';
      echo '<tr><td align="right">Confirm password:</td><td><input type="password" name="cpassword" size="30" value=""></td></tr>';
      echo '<tr><td colspan="2" align="center"><input type="submit" name="profile" size="150" value="Create My Account"> ';
      echo '<input type="button" size="150" value="Cancel" onClick="JavaScript:location.href=\''.phpSelf.'\'"></td></tr>';
      echo '</table></form>';

      if($GLOBALS['allow_login_request'])
        echo '</td></tr></table>';

      echo '<br><div align="center"><input type="button" value="View security notes" onClick="JavaScript:window.open(\''.phpSelf.'?create=1&priv=1\',\'privacy\',\'width=660,height=580,dependent=yes,location=no,scrollbars=yes,menubar=no,status=no,resizable=yes\')"></div>';
    }
  } else {
    echo '<b><u>Notes about File Manage security:</u></b><br>';
    echo 'Passcodes and user\'s passwords are at no time stored as is. As soon as they are posted to the File Manage program they are changed to a MD5 hash.';
    echo 'This hash is what is stored to the database. So absolutely no one has access to a password (not even this program).';
    echo 'What the program does when a user logs in is tests the entered password\'s MD5 hash against the stored one.';
    echo 'Again no one will be able to see what was entered. This should give users confidence against malintensioned admins.<br><br>';
    echo '<b><u>Note about your email:</u></b><br>';
    echo 'Only this program and the admin(s) have access to your email. Your email address is only needed by this program if you forget your password. A new, randomly generated password will be created and emailed to the email address submitted.';
    echo '<br><font size="-1">(this feature is not yet available in the program, but will become available in the future)</font><br><br>';
    echo '<b><u>Note about creating a password:</u></b><br>';
    echo 'MD5 hashes are still crackable by the most basic of "brute force" hacks. Under this type of hacking, the longer the password, and the more types of characters (lowercase and uppercase letters, numbers, and symbols) used, the better the security. Passwords longer than eight characters, using at least three types of characters is suggested.<br><br>';
    echo '<b><u>If you are having problems with the login:</u></b><br>';
    echo 'If you are unable to login. This could be for obvious reasons (wrong username or password), so please double check you are entering those correctly. The password <i>is</i> case sensitive, but the username is not.<br>';
    echo 'Due to security handling, if you have an ISP, router/firewall, or some other system that changes your IP address after every connection, you will be prompted to enter your username and password after everything you click on. You will be unable to use any of the enhanced functionality of this program. You must disable that, or if you are the admin, disable logins to be able to use this program correctly.';
    echo '<br><br><a href="JavaScript:window.close()">Click here to close this window</a>';
  }

} // end of make_user()



function strong_password($pass){

  if(strlen($pass) < 8)
    return false;

  $lower = 0;
  $upper = 0;
  $numer = 0;
  $symbl = 0;

  for($i = 97; $i <= 122; $i++)
    $lower_ar[] = chr($i);
  for($i = 65; $i <= 90; $i++)
    $upper_ar[] = chr($i);
  for($i = 48; $i <= 57; $i++)
    $numer_ar[] = chr($i);

  $done = false;
  for($i = 0; $i < strlen($pass) && !$done; $i++){
    if(in_array(substr($pass, $i, 1), $lower_ar))
      $lower = 1;
    elseif(in_array(substr($pass, $i, 1), $upper_ar))
      $upper = 1;
    elseif(in_array(substr($pass, $i, 1), $numer_ar))
      $numer = 1;
    elseif(substr($pass, $i, 1) != ' ')
      $symbl = 1;
  }

  if($lower + $upper + $numer + $symbl >= 2)
    return true;

  return false;
} // end of strong_password()



  // this function is 99% based on Uber Uploader (https://sourceforge.net/projects/uber-uploader/)
  // some changes have been made to make it work with File Manage
  // void upload_popup( void )
function upload_popup(){

  if(isset($_GET['close_pop']) && $_GET['close_pop'] == 1){
    echo '<html>
  <head><script language="javascript" type="text/javascript">self.close();</script></head>
  <body></body>
</html>';
    exit;
  }

  $temp_dir = "/tmp/";                      //ATTENTION: this variable must be the same as the $temp_dir set in uber_uploader.cgi
  $temp_dir .= $_GET['tmp_sid'];            //Directory CGI.pm is using to write the temp files.
  $flength_file = $temp_dir . "/flength";   //Path to flength file $temp_dir/$tmp_sid/flength
  $flength_file_exists = false;
  $total_upload_size = 0;                   // Total size of the upload in bytes that we read from the flength file
  $cmd_line_exec_dl = false;                // Set to true if you want to use command line exec `rm -rf $temp_dir`
  $bRead = 0;
  $old_percent = 0;
  $old_time = 0;
  $old_size = 0;
  $first_loop = true;

  // Keep trying to read the flength file for 15 secs
  for($i = 0; $i < 20; $i++){
  	if(file_exists($flength_file) && $fp = fopen($flength_file, "r")){
  		$flength_file_exists = true;
  		$total_upload_size = fread($fp, filesize($flength_file)); //Read the size of the upload from the flength file
  		fclose($fp);

  		clearstatcache();
  		break;
  	} else
      sleep(1); //Couldn't find the flength file so wait 1 second and try again

  	clearstatcache();
  }

  /////////////////////////////////////////////////////////////////////////////////////////////
  // Ok, we couldn't find the flength file after 10 seconds. This means
  //
  // a. The upload was so fast the flength file was deleted before it could be read.
  // b. The flength file does not exist because the script is not set up properly
  // c. The flength file exists but this script could not find it. Maybe wrong $temp_dir path
  //
  // So, issue "Upload Finished ???" and exit. Upload may succeed anyway.
  /////////////////////////////////////////////////////////////////////////////////////////////
  if(!$flength_file_exists)
    echo "Upload Finished ???";

  //////////////////////////////////////////////////////////////////////
  // Found the flength file but it contains the max file upload error.
  // Delete the temp directory, issue error and exit.
  //////////////////////////////////////////////////////////////////////
  if(strpos($total_upload_size, "ERROR") !== false){
  	deleteTempDir($temp_dir, $cmd_line_exec_dl);
  	DisplayMessage($total_upload_size);
  }

  // Found the flength file and everything is cool so we continue
  $start_time = time();
  $totalKB = round($total_upload_size / 1024);    //Total upload size in Kilobytes

  echo '  <head>
    <title>File Upload Status</title>
    <meta http-equiv=content-type content="text/html; charset=iso-8859-1" >
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="CACHE-CONTROL" content="no-cache">
    <meta http-equiv="expires" content="-1">
    <script language="javascript" type="text/javascript">
    function SP(percent, cx, time, remain, speed){
	document.getElementById(\'upload_status\').style.width = percent+\'%\';
	document.getElementById(\'percent\').innerHTML = percent+\'%\';
	document.getElementById(\'current\').innerHTML = cx;
	document.getElementById(\'time\').innerHTML = time;
	document.getElementById(\'remain\').innerHTML = remain;
	document.getElementById(\'speed\').innerHTML = speed;
    }

    function Message(msg){ document.getElementById(\'message\').innerHTML = msg; }

    function Transfer(){
    	document.getElementById(\'transfer\').style.display = "block";
    	document.getElementById(\'upload_status_wrap\').style.display = "none";
    	document.getElementById(\'upload_status\').style.display = "none";
    }
    </script>
    <style>
	.data {background-color: #FFFFFF; border: 1px solid #898989; width: 90%}
	.data TR TD {background-color: #dddddd; font: 13px Arial;}
    	.bar1 {border:1px solid #505050; background-color: #ffffff; text-align:left; vertical-align:middle; height:20px; width: 80%}
	.bar2 {width: 0%; background-color: #FFFFFF; height: 20px; text-align: left;}
	.message {font: 18px Arial;}
    </style>
  </head>
    <div align="center"><font class="message" id="message"></font></div>
    <div>&nbsp;</div>
    <div align="center" id="transfer" style="display:none; width:100%;">
      <table width="200" border="0" align="center" cellpadding="1" cellspacing="0" bgcolor="#333333">
        <tr>
          <td>
            <table width="100%" border="0" cellpadding="5" cellspacing="0" bgcolor="#F2FCFF">
              <tr>
                <td height="50" bgcolor="#F7F7F7"><div align="left" style="font-size:8pt;"><b>Transferring Files ...</b><br>Please wait for the file upload page to refresh.</div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </div>
    <div align="center">
      <div class="bar1" id="upload_status_wrap" align="center">
        <div class="bar2" id="upload_status"></div>
      </div>
    </div>
    <div>&nbsp;</div>
    <div align="center">
      <table cellpadding=3 cellspacing=1 class="data">
        <tr>
          <td width="35%" nowrap><b>Percent Complete:</b></td>
          <td align="center"><font id="percent">0%</font></td>
        </tr>
        <tr>
          <td><b>Current Position:</b></td>
          <td align="center"><font id="current">0</font> / '.$totalKB.' Kbytes</td>
        </tr>
        <tr>
          <td><b>Elapsed time:</b></td>
          <td align="center"><font id="time">0</font></td>
        </tr>
        <tr>
          <td><b>Est Time Left:</b></td>
          <td align="center"><font id="remain">0</font></td>
        </tr>
        <tr>
          <td><b>Est Speed:</b></td>
          <td align="center"><font id="speed">0</font> Kbytes/Sec.</td>
        </tr>
      </table>
    </div>
    <script language="javascript" type="text/javascript">Message(\'Upload In Progress\');</script>';

  echo str_pad('',4096)."\n";
  flush();

  /////////////////////////////////////////////////////////////////
  // Return the current size of the $temp_dir - flength file size.
  // This version does not depend on the DU command.
  /////////////////////////////////////////////////////////////////
  function GetBytesRead($tmp_dir){
  	$bytesRead = 0;
  	if(is_dir($tmp_dir)){
  		if($handle = opendir($tmp_dir)){
  			while(false !== ($file = readdir($handle))){
  				if($file != '.' && $file != '..' && $file != 'flength')
            $bytesRead += filesize($tmp_dir . "/" . $file);
  				clearstatcache();
  			}
  			closedir($handle);
  		}
  	}
  	$bytesRead = trim($bytesRead);
  	return $bytesRead;
  }

  //////////////////////////////////////////////////////////////
  // Keep reading the temp_dir while the flength file exists and
  // the total size of (temp_dir - flength_file) is less than the
  // total upload size.
  //////////////////////////////////////////////////////////////
  while(is_dir($temp_dir) && file_exists($flength_file) && $bRead < $total_upload_size){
  	clearstatcache();
  	sleep(1);

  	$bRead = GetBytesRead($temp_dir);
  	$curr_time = time();

  	if($first_loop){
  		$modif_time = time();
  		$first_loop = false;
  	}

  	// Calculate elapsed time and format for display
  	$lapsed = $curr_time - $start_time;
  	$lapsed_sec = ($lapsed % 60);
  	$lapsed_min = ((($lapsed - $lapsed_sec) % 3600) / 60);
  	$lapsed_hours = (((($lapsed - $lapsed_sec) - ($lapsed_min * 60)) % 86400) / 3600);

  	// Gets number of hours; assuming that we won't be going into days!
  	if($lapsed_sec < 10)
      $lapsed_sec = "0$lapsed_sec";
  	if($lapsed_min < 10)
      $lapsed_min = "0$lapsed_min";
  	if($lapsed_hours < 10)
      $lapsed_hours = "0$lapsed_hours";

  	$lapsedf = "$lapsed_hours:$lapsed_min:$lapsed_sec"; // display as 00:00:00

  	// Calculate time remaining and format for display
    	$bSpeed = 0;

  	if($lapsed > 0)
      $bSpeed = $bRead / $lapsed;

  	$remaining = 0;

  	if($bSpeed > 0)
      $remaining = (($total_upload_size - $bRead) / $bSpeed);

  	$remaining = round($remaining);
  	$remaining_sec = ($remaining % 60);
  	$remaining_min = ((($remaining - $remaining_sec) % 3600) / 60);
  	$remaining_hours = (((($remaining - $remaining_sec) - ($remaining_min * 60)) % 86400) / 3600);

  	if($remaining_sec < 10)
      $remaining_sec = "0$remaining_sec";
  	if($remaining_min < 10)
      $remaining_min = "0$remaining_min";
  	if($remaining_hours < 10)
      $remaining_hours = "0$remaining_hours";

  	$remainingf = "$remaining_hours:$remaining_min:$remaining_sec";
  	$percent = round(100 * $bRead / $total_upload_size);

  	if($old_percent != $percent || $old_time != $curr_time){
  		$old_percent = $percent;
  		$old_time = $curr_time;

  		if($old_size != $bRead)
        $modif_time = $curr_time;

  		$old_size = $bRead;
  		$time = $curr_time - $start_time;
  		$speed = $time ? round($bRead / $time) : 0;
  		$speed = round($speed / 1024);
  		$bRead = round($bRead /= 1024);
  		echo "<script language=\"javascript\" type=\"text/javascript\">SP($percent, $bRead, '$lapsedf', '$remainingf', $speed);</script>\n";
  		echo str_pad('',4096)."\n";
  		flush();
  	}
  	if($curr_time - $modif_time > 300){  //(300 seconds) 5 minutes without $temp_dir modification means upload probably failed.
  		echo "<script language=\"javascript\" type=\"text/javascript\">Message('Upload Failed');</script>\n";
  		echo str_pad('',4096)."\n";
  		flush();
  		exit;
  	}
  }

  ///////////////////////////////////////////////////////////////////
  // Keep checking for the existance of the flength file for 10 secs.
  // The flength file will be erased when uber_uploader.cgi is
  // finished transfering the files to the upload_dir. So we keep
  // looping for 10 secs until it is gone.
  ///////////////////////////////////////////////////////////////////
  $upload_success = false;

  for($i = 0; $i < 20; $i++){
  	if(!file_exists($flength_file)){
  		$upload_success = true;

  		echo "<script language=\"javascript\" type=\"text/javascript\">SP(100, $totalKB, '$lapsedf', '00:00:00', $speed); Message('Upload Complete');</script>\n";
  		echo "<script language=\"javascript\" type=\"text/javascript\">Transfer();</script>\n";
  		echo str_pad('',4096)."\n";
  		flush();
  		break;
  	} else {
  		echo "<script language=\"javascript\" type=\"text/javascript\">Message('Verifying Upload');</script>\n";
  		echo str_pad('',4096)."\n";
  		flush();
  		sleep(1);
  	}

  	clearstatcache();
  }

  if(!$upload_success){
  	echo "<script language=\"javascript\" type=\"text/javascript\">Message('Upload Failed!');</script>\n";
  	echo str_pad('',4096)."\n";
  	flush();
  }

  echo "</body></html>\n";
  echo str_pad('',4096)."\n";
  flush();


  ///////////////////////////////////////////////////////////////
  // Delete the temp dir and everything in it. The only
  // way this function is called is if the user tried
  // to upload a file > $max_upload defined in uber_uploader.cgi
  //////////////////////////////////////////////////////////////
  function deleteTempDir($tmp_dir, $cmd_exec){
  	if($cmd_exec)
      $output = `rm -rf $tmp_dir`;
  	else {
  		if($handle = opendir($tmp_dir)){
  			while(false !== ($file_name = readdir($handle))){
  				if($file_name != "." && $file_name != "..")
            unlink($tmp_dir . '/' . $file_name);
  				clearstatcache();
  			}
  			closedir($handle);
  		}
  		rmdir($tmp_dir);
  	}
  }

  /////////////////////////////////////////////////////////////////
  //  Something unexpected has happened so issue a message and exit
  /////////////////////////////////////////////////////////////////
  function DisplayMessage($msg){
    echo '<html>
  <head>
  <title>File upload status</title>
  <meta http-equiv=content-type content="text/html; charset=iso-8859-1" >
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="CACHE-CONTROL" content="no-cache">
  <meta http-equiv="expires" content="-1">
  </head>
  <body style="background-color: #FFFFFF; color: #184B86; font-family: arial, helvetica, sans_serif;">
    <div align="center">
      <h4>'.$msg.'</h4>
    </div>';
    exit;
  }

} // end of upload_popup()



  // function writes to a log file the items inputted; returns false if log
  // point is not a high enough level ($logging_level < $lvl) or for some reason
  // $_SERVER['REMOTE_ADDR'] is not set
  // It also checks to make sure the log file has not exceded the max_log_size,
  // if it has, it deleted the oldest entries in the log first.
  // bool writelog( str 'log message', str 'location of occurance' [, str 'file associated' [, int 'level of log']] )
function writelog($message, $location, $file = 'none', $lvl = 2){

  if($GLOBALS['logging_level'] >= $lvl){
    $bk = '~~~~~';

    // time, IP:port, user, message, location, file

    if(!isset($GLOBALS['un']))
      $un = 'no one';
    else
      $un = $GLOBALS['un'];
    $write = time() . $bk;
    if(isset($_SERVER['REMOTE_ADDR']))
      $write .= $_SERVER['REMOTE_ADDR'];
    if(isset($_SERVER['REMOTE_PORT']))
      $write .= ':' . $_SERVER['REMOTE_PORT'];
    $write .= $bk . $un . $bk  . $message . $bk . $location . $bk . $file . $bk . $lvl . $GLOBALS['line_break'];
    $fout = fopen(loc1 . '/filelist/filemanagelog.log', 'a') or die('no read/write permissions');
    $fp = fwrite($fout, $write) or die('no read/write permissions');
    fclose($fout);

    if(filesize(loc1 . '/filelist/filemanagelog.log') > $GLOBALS['max_log_size'] * 1024){ // if the log file is larger than max_log_size
      $log_size = filesize(loc1 . '/filelist/filemanagelog.log');
      $log_file_ar = file(loc1 . '/filelist/filemanagelog.log');
      $removed_size = 0; // the value is the size in bytes that will be removed once the file is written again
      while($removed_size < $log_size - ($GLOBALS['max_log_size'] * 1024)){
        $removed_size += strlen($log_file_ar[0]); // store the size of the line being removed
        array_shift($log_file_ar); // kick off the line being removed
      }
      $fout = fopen(loc1 . '/filelist/filemanagelog.log', 'w');
      $fp = fwrite($fout, implode('', $log_file_ar));
      fclose($fout);
    }
    return true;
  } else
    return false;
} // end of writelog()



  // function keeps track of page views and unique hits and logs them in a file
  // so they can be accessed later for statistics.
  // Some ideas and lines of code taken from OutSide Photos
  // (www.sourceforge.net/projects/outside-photos/) copyright 2004-2005 by
  // OutSide Photos Development Team under the GNU General Public License,
  // redistibution is allowed under the same licese. View the file LICENSE that
  // was packaged with this file, or download a copy at
  // www.opensource.org/licenses/gpl-license.php
  // void hits( void )
function hits(){

    // this keeps track of all the page views
  $pageviewsfile = loc1 . '/filelist/filelist-pageviews.list';
  if(is_file($pageviewsfile)){
    $array_of_pageviews = file($pageviewsfile);
    $number_of_pageviews = $array_of_pageviews[0] + 1;
    $pageviewdate = $array_of_pageviews[1];
  } else {
    $number_of_pageviews = 1;
    $pageviewdate = time();
  }
    // fopen is set to w (instead of a) so that it will overwrite the previous value
  $fout = fopen($pageviewsfile, 'w');
  $fp = fwrite($fout, $number_of_pageviews . $GLOBALS['line_break'] . $pageviewdate);
  fclose($fout);

    // this keeps track of all unique hits
  if(isset($_SERVER['REMOTE_ADDR'])){
    $hitsfile = loc1 . '/filelist/filelist-hits.list';
    if(is_file($hitsfile)){
      $array_of_hits = file($hitsfile);
      for($i = 1; $i < count($array_of_hits); $i++)
        $array_of_hits[$i - 1] = trim($array_of_hits[$i]);
      if(!in_array($_SERVER['REMOTE_ADDR'], $array_of_hits, true)){
        $fout = fopen($hitsfile, 'a');
        $fp = fwrite($fout, $_SERVER['REMOTE_ADDR'] . $GLOBALS['line_break']);
        fclose($fout);
      }
    } else {
      $fout = fopen($hitsfile, 'a');
      $fp = fwrite($fout, time() . $GLOBALS['line_break'] . $_SERVER['REMOTE_ADDR'] . $GLOBALS['line_break']);
      fclose($fout);
    }
  }

} // end of hits()



  // this function deletes the temperary files created for previews of pages
  // void del_tmp( void )
function del_tmp(){
  if(is_file(loc1 . '/filelist/filelist-tmpfiles.list')){
    $temp_files = file(loc1 . '/filelist/filelist-tmpfiles.list');
    $fout = fopen(loc1 . '/filelist/filelist-tmpfiles.list', 'w');
    $count = 0;
    foreach($temp_files as $file){
      $file_ar = explode('~~', trim($file));
      if(time() - $file_ar[1] >= 3600){
        if(!unlink(loc1 . '/filelist/' . $file_ar[0])){
          writelog('<font color="red"><b>System</b> tried to delete temp file and failed.</font>', 'none', $file, 1);
          $fp = fwrite($fout, $file);
        } else
          $count++;
      } else
        $fp = fwrite($fout, $file);
      $count--;
    }
    fclose($fout);
    if($count == 0)
      @unlink(loc1 . '/filelist/filelist-tmpfiles.list');
  }
} // end of del_tmp()



  // this function just does a test to see if an inputed value contains
  // non-numerics. This may be used to test wether or not to add quotes around a
  // value. Returns true if non-numerics are found, returns false if only
  // numerics are found.
  // bool cont_non_num( str 'any value' )
function cont_non_num($input){
  for($i = 0; $i < strlen($input); $i++){
    $ord_val = ord(substr($input, $i, 1));
    if($ord_val < 48 || $ord_val > 57)
      return true;
  }
  return false;
} // end of cont_non_num()



  // this function adds the most common index files so that the server does not
  // create an index of the files in the filelist directory.
  // void index_sec( [str 'directory path'] )
function index_sec($dir = '/filelist/'){
  if(substr($dir, -1) != '/')
    $dir .= '/';

  if(!is_dir(loc1 . $dir))
    mkdir(loc1 . $dir) or die('Unable to create directory ('.$dir.'). Requires write permissions, on Linux 777 permissions is suggested.');

  $write = '<html><script language="JavaScript">';
  // the genius JavaScript function name below originally coined by Bradley Hart!
  $write .= 'var gotothispagenow=window.setTimeout(location.href=\''.phpSelf.'\',1)';
  $write .= '</script><body><!-- Nice try --><h2>Not permitted</h2></body></html>';

  if(!is_file(loc1 . $dir . 'index.php')){
    $fout = fopen(loc1 . $dir . 'index.php', 'w');
    $fp = fwrite($fout, $write);
    fclose($fout);
  }
  if(!is_file(loc1 . $dir . 'index.html')){
    $fout = fopen(loc1 . $dir . 'index.html', 'w');
    $fp = fwrite($fout, $write);
    fclose($fout);
  }
  if(!is_file(loc1 . $dir . 'index.htm')){
    $fout = fopen(loc1 . $dir . 'index.htm', 'w');
    $fp = fwrite($fout, $write);
    fclose($fout);
  }
  if(!is_file(loc1 . $dir . 'default.htm')){
    $fout = fopen(loc1 . $dir . 'default.htm', 'w');
    $fp = fwrite($fout, $write);
    fclose($fout);
  }
} // end of index_sec()



  // gets $path and returns an array with all files which return true to the
  // wild card
  // array 'list of matching files' wild_card( str 'path of searched directory' [, bool 'search dir names' [, bool 'search file names']] )
function wild_card($path, $dirs = true, $files = true){

  $path = str_replace('\\', '/', $path);
  $file_ar = array();
  if(strpos($path, '*') !== false){
    if(substr($path, 0, 1) == '/')
      $path = substr($path, 1);
    $file_ar1 = glob(loc1 . '/' . $path);
    /*echo '<pre>';
    print_r($file_ar1);
    echo '</pre>';*/
    if(count($file_ar1) > 0){
      foreach($file_ar1 as $file){
        if(substr($file, 0, 1) != '.' && ($dirs && is_dir($file)) || ($files && is_file($file))
        && allowed(str_replace(loc1, '', $file), false, false, false)){
          if(is_dir($file))
            $file .= '/';
          $file_ar[] = str_replace(loc1, '', $file);
        }
      }
    }
  } elseif(($dirs && is_dir(loc1 . $path)) || ($files && is_file(loc1 . $path)))
    $file_ar[] = $path;
    
  return($file_ar);

} // end of wild_card()



  // str '(?) link' note( int 'note number', int 'width of popup window', int 'height')
function note($note, $width, $height){
  return '<u><a onMouseOver="this.style.cursor=\'move\'" onClick="JavaScript:window.open(\''.phpSelf.'?note='.$note.'\',\'note\',\'width='.$width.',height='.$height.',dependent=yes,location=no,scrollbars=yes,menubar=no,status=no,resizable=yes\')">(?)</a></u>';
} // end of note()



  // takes $name and returns just the name of the file, no directories
  // also outputs $pre_ex as global for other uses
  // str 'file name of $name' get_name( str 'path of a file' ) *str 'path to file' $pre_ex
function get_name($name){
  $GLOBALS['pre_ex'] = str_replace('//', '/', str_replace('\\', '/', dirname($name) . '/'));
  return basename($name);
} // end of get_name()



  // input file, returns the extension
  // str 'extension of $file' get_ftype( str 'file name' )
function get_ftype($file){
  $info = pathinfo($file);
  if(!isset($info['extension']))
    $info['extension'] = 'none';
  return strtolower($info['extension']);
} // end of get_ftype()



  // this function returns an array of permissions based on $perm
  // $hex will make the function test it based on HEX or Basic permissions
  // array 'int of each ability' get_perm( int/str 'dec/hex of permissions', str 'permissions type -- dec or hex' )
function get_perm($perms, $permstype){

  $perms1 = array('read','list','subdir','write','make','append','delete','ddelete');

  if($permstype == 'hex'){
    $dec = hexdec($perms);

    if($dec >= 0 && $dec <= 256){
      $bin = strrev(decbin($dec - 1));
      for($i = 0; $i < count($perms1); $i++){
        if(substr($bin, $i, 1) == 1 && $dec != 0)
          $current_user[$perms1[7 - $i]] = 0;
        else
          $current_user[$perms1[7 - $i]] = 1;
      }
      return($current_user);
    } else {
      echo '<font color="red">Number too low or too high. Range: 0-100 (hex).</font>';
      return false;
    }
  } else {
    if($perms >= 0 && $perms <= 9){
      $user_value = 9 - $perms;
      foreach($perms1 as $prms){
        if($user_value >= 1)
          $current_user[$prms]      = 1;
        else
          $current_user[$prms]      = 0;
        $user_value = $user_value - $current_user[$prms];
      }
      return($current_user);
    } else {
      echo '<font color="red">Number is invalid, or the value is too low or too high. Range: 0-10.</font>';
      return false;
    }
  }
  return false;
} // end of get_perm()



  // this function checks the contents of files (uploaded, edited, or created)
  // and returns false if it contains words that are "illegal", there is a
  // customizable list in the settings to adjust what to block. This won't help
  // against anyone with a good brain in PHP, at least it will weed out the
  // idiots that are trying to get into stuff they shouldn't.
  // bool check_contents( str 'contents of anything' )
function check_contents($contents){

  if(!isset($_POST['overridepasscode']) || $_POST['overridepasscode'] == ''){
    $illegal_words = $GLOBALS['illegal_words'];
    array_unshift($illegal_words, 'filelist');
    array_unshift($illegal_words, 'filemanage');

    $contents = strtolower($contents);

      // quick test, so for larger files, there is a chance to not wait so long
    if(strpos($contents, 'filelist') !== false || strpos($contents, 'file list') !== false){
      echo '<font color="red">File contains invalid word or word composit: "filelist". Please fix.</font><br>';
      writelog('User attempted to submit file with a illegal word or word composit (filelist)', 'unknown', 'unknown');
      return false;
    }
    if(strpos($contents, 'filemanage') !== false || strpos($contents, 'file manage') !== false){
      echo '<font color="red">File contains invalid word or word composit: "filemanage". Please fix.</font><br>';
      writelog('User attempted to submit file with a illegal word or word composit (filemanage)', 'unknown', 'unknown');
      return false;
    }

      // nice long regex sting getting rid of any '.' or "." and spaces for better testing
      // it's my first homemade regex string, I learned the basics in about 5 minutes and
      // wrote this, so there is probably a more effecient way to do what this does.
    $contents1 = preg_replace(array("/\s/","/(('|\")(\.)('|\"))|((('|\")(\.))|((\.)('|\")))/"), array('',''), strtolower($contents));
    //$contents2 = ereg_replace("[^[:alnum:]]", '', $contents);  // remove everything but numbers and letters -- the default illegal_words will be skipped with this. I'm getting rid of it to speed things up, and there is a very small chance it was actually doing anything.

    foreach($illegal_words as $illegal_word)
      if(strpos($contents1, strtolower($illegal_word)) !== false){
        echo '<font color="red">File contains invalid word or word composit: "'.$illegal_word.'". Please fix.</font><br>';
        writelog('User attempted to submit file with a illegal word or word composit ('.$illegal_word.')', 'unknown', 'unknown');
        return false;
      }
  } else {
    $passcode = file(loc1 . '/filelist/filelist-passcode.php');
    $passcode = trim($passcode[1]);
    if(md5($_POST['overridepasscode']) == $passcode)
      return true;
    else {
      echo '<font color="red">Passcode was incorrect.</font><br>';
      return false;
    }
  }
  return true;
} // end of check_contents()



  // this function checks $name for common filename errors. It can't be null, it
  // can't be longer than 255 characters long, it can't contain certain symbols
  // and it can't contain 'filelist', if it did, the file would then become
  // inaccessible
  // returns true if all criteria are met, false if not
  // bool check_name( str 'file name' )
function check_name($name){
  if($name == '')
    return false;
  if(strlen($name) >= 255){
    echo '<font color="red">Name too long</font><br>';
    return false;
  }

  if(strpos(strtolower($name), 'filelist') !== false){
    echo '<font color="red">Name contains an invalid word "filelist"</font><br>';
    return false;
  }
  if(strpos(strtolower($name), 'filemanage') !== false){
    echo '<font color="red">Name contains an invalid word "filemanage"</font><br>';
    return false;
  }

  if(strpos($name, '..') !== false){
    echo '<font color="red">Name is invalid. Name contains ".."</font><br>';
    return false;
  }

  // not \ / ; * ? " < > | #
  // characters 32-126 !34 !35 !42 !47 !59 !60 !62 !63 !92 !124
  for($i = 32; $i <= 126; $i++)
    if($i != 34 && $i != 35 && $i != 42 && $i != 47 && $i != 59
    && $i != 60 && $i != 62 && $i != 63 && $i != 92 && $i != 124)
      $chr_array[] = chr($i);

  for($i = 0; $i < strlen($name); $i++){
    $char = substr($name, $i, 1);
    $chr_done = false;
    for($j = 0; $j < count($chr_array) && !$chr_done; $j++){
      if($chr_array[$j] == $char)
        $chr_done = true;
    }
    if(!$chr_done){
      echo '<font color="red">Name is invalid. Name contains "'. $char .'"</font><br>';
      return false;
    }
  }

  return true;
} // end of check_name()



  // Is this an acceptable file to do anything with? Does it comply with all
  // needs such as accepted extension and is not the current file. Does it have
  // anything to do with filelist?
  // returns true/false based on results
  // bool allowed( str 'file path' [, bool 'is new file' [, bool  'write to log' [, bool 'display error' [, bool 'display continue link']]]] )
function allowed($file, $new_file = false, $write_log = true, $dis_allowed_error = true, $dis_allowed_cont = false){

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(defined('loc'))
    $loc = loc;
  else
    $loc = $GLOBALS['loc'];

  if(!$GLOBALS['admin'] && isset($GLOBALS['hidden_items_ar']) && (in_array($loc, $GLOBALS['hidden_items_ar']))){
    if($dis_allowed_error)
      if($echo) echo '<font color="red">This file ('.$file.') is off limits. If you believe this is in error, please contact the administrator of this site immidiately.</font><br><br>'; else array_unshift($GLOBALS['prevcmd'], 'This file ('.$file.') is off limits.');
    if($dis_allowed_cont && $echo)
      echo '<a href="' . phpSelf . '?loc=' . $loc . '">Click here to go back</a>';
    if($write_log)
      writelog('<font color="red">User tried to access a forbidden file</font>', 'unknown', $file, 1);
    return false;
  }

  if(substr($file, 0, 2) == './')
    $file = substr($file, 1);
  if(substr($file, 0, 1) != '/')
    $file = $loc . $file;

  if(!$GLOBALS['admin'] && isset($GLOBALS['hidden_items_ar'])){
    if(in_array($file, $GLOBALS['hidden_items_ar'])){
      if($dis_allowed_error)
        if($echo) echo '<font color="red">This file ('.$file.') is off limits. If you believe this is in error, please contact the administrator of this site immidiately.</font><br><br>'; else array_unshift($GLOBALS['prevcmd'], 'This file ('.$file.') is off limits.');
      if($dis_allowed_cont && $echo)
        echo '<a href="' . phpSelf . '?loc=' . $loc . '">Click here to go back</a>';
      if($write_log)
        writelog('<font color="red">User tried to access a forbidden file</font>', 'unknown', $file, 1);
      return false;
    }
    for($i = 0; $i < count($GLOBALS['hidden_items_ar']); $i++)
      if(substr($file, 0, strlen($GLOBALS['hidden_items_ar'][$i])) == $GLOBALS['hidden_items_ar'][$i]){
        if($dis_allowed_error)
          if($echo) echo '<font color="red">This file ('.$file.') is off limits. If you believe this is in error, please contact the administrator of this site immidiately.</font><br><br>'; else array_unshift($GLOBALS['prevcmd'], 'This file ('.$file.') is off limits.');
        if($dis_allowed_cont && $echo)
          echo '<a href="' . phpSelf . '?loc=' . $loc . '">Click here to go back</a>';
        if($write_log)
          writelog('<font color="red">User tried to access a forbidden file</font>', 'unknown', $file, 1);
        return false;
      }
  }

  if((is_file(loc1 . $file) || $new_file)
  && strpos(strtolower($file), 'filelist') === false && strpos(strtolower($file), 'filemanage') === false && strpos($file, '../') === false && strpos($file, '..\\') === false && strpos($file, '#') === false && $file != phpSelf)
    if($GLOBALS['accept_all'])
      return true;
    else {
      foreach($GLOBALS['accept'] as $exts)
        if(strtolower($exts) == strtolower(substr($file, strlen($file) - strlen($exts), strlen($exts))))
            // get the heck out of the function
          return true;
    } // if(!$accept_all)

  if($dis_allowed_error)
    if($echo) echo '<font color="red">This file ('.$file.') is off limits. If you believe this is in error, please contact the administrator of this site immidiately.</font><br><br>'; else array_unshift($GLOBALS['prevcmd'], 'This file ('.$file.') is off limits.');
  if($dis_allowed_cont && $echo)
    echo '<a href="' . phpSelf . '?loc=' . $loc . '">Click here to go back</a>';

  if($write_log)
    writelog('<font color="red">User tried to access a forbidden file</font>', 'unknown', $file, 1);

  return false;
} // end of allowed()



  // function returns a string of the filesize with proper denominator
  // returns false if number is not greater than 0 or $size does not contain
  // numbers
  // str 'formmated file size' filesz( int 'number in bytes' [, bool 'is bytes?' [, int 'number of decimal places' ]] )
function filesz($size, $bytes = true, $decs = 2){
  $size += 0; // set to int (since settype() doesn't seem to work correctly always)
  if($size >= 0){
    if($bytes){
      if($size < 980)
        return round($size, 0)                      . ' bytes';
      else
      if($size < 1000000)
        return round($size / 1024, $decs)           . ' KB';
      else
      if($size < 1020000000)
        return round($size / 1048576, $decs)        . ' MB';
      else
        return round($size / 1073741824, $decs + 1) . ' GB';
    } else {
      if($size < 1000)
        return round($size, 0)                      . ' bits';
      else
      if($size < 1000000)
        return round($size / 1000, $decs)           . ' Kb';
      else
      if($size < 1000000000)
        return round($size / 1000000, $decs)        . ' Mb';
      else
        return round($size / 1000000000, $decs + 1) . ' Gb';
    }
  }
  return false;
} // end of filesz()




  // this is a function to determine if the entered search is at least close to
  // the file's name
  // bool isclosematch( str 'name of file', str 'search string', bool 'exact matches only', bool 'display "exact match:"' )
function isclosematch($name, $search, $exact, $disp){

    // if the file name contains the search, then return "exact match"
  if(strpos(strtolower($name), strtolower($search)) !== false){
      // if display is not supressed, then display
    if($disp != 0)
      echo 'Exact match: ';
    return true;
  } else
      // if exact matches are the only returned true, then return all else false
    if($exact == 1)
      return false;


    // error spectrum that will be allowed, 1 = all should return true, 0 = must be exact match
    // these numbers are used so that the shorter the word the more strict it is (per letter) and visa versa
  $error_spacer  = $GLOBALS['error_spacer'];  // for per word errors
  $error_spacer2 = $GLOBALS['error_spacer2']; // for per segment errors

    // number of characters errors allowed (calculated from the numbers above and the length of the word)
  $num_of_error_chars  = strlen($search) * $error_spacer;  // for per word errors
  $num_of_error_chars2 = strlen($search) * $error_spacer2; // for per segment errors

    // rounded down integer of the number of letters that can be different from the file and and search
  $real_num_of_error_chars = floor(strlen($search) * $error_spacer2);

    // if the whole file name is less than $num_of_error_chars from the search then return true
  if(levenshtein(strtolower($name), strtolower($search)) <= $num_of_error_chars)
    return true;

    // split all the words of the file into an array to sort through
  $array_of_words = explode(' ', strtolower($name));

    // if a word in the file name is less than $num_of_error_chars from the search then return true
  foreach($array_of_words as $word)
    if(levenshtein($word, strtolower($search)) <= $num_of_error_chars)
      return true;

    // if a segment of the file name is less than $num_of_error_chars from the search then return true
  for($i = 0; $i < strlen($name) - strlen($search) + $real_num_of_error_chars; $i++)
    for($j = 0 - $real_num_of_error_chars; $j <= $real_num_of_error_chars; $j++){
      $name1 = substr($name, $i, strlen($search) + $j);
      if(levenshtein(strtolower($name1), strtolower($search)) <= $num_of_error_chars2)
        return true;
    }

    // all else fails: return false
  return false;
} // end of isclosematch()



  // get properties of a file or directory
  // bool prop( str 'file path' )
function prop($prop){

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(is_file(loc1 . $prop) && $GLOBALS['current_user']['read'] && allowed($prop)){

    $getid3_true2 = $GLOBALS['getid3_true2'];

    writelog('User viewed properties of a file', 'prop', $prop, 4);

    $ftype = get_ftype($prop);

    switch($ftype){
      case 'txt':
      case 'list':
        $is_txt = true;
        $txt_type = 'Plain text/list/flat-database';
        break;
      case 'diz':
        $is_txt = true;
        $txt_type = 'Plain text/zip nfo file';
        break;
      case 'nfo':
        $is_txt = true;
        $txt_type = 'Plain text/information/help file';
        break;
      case 'log':
        $is_txt = true;
        $txt_type = 'Plain text/list/log file';
        break;
      case 'php':
      case 'php3':
      case 'phtml':
      case 'php4':
      case 'php5':
        $is_txt = true;
        $txt_type = 'Plain text/PHP program/HTML-PHP mix';
        break;
      case 'htm':
      case 'html':
      case 'js':
      case 'xhtml':
      case 'xml':
      case 'shtml':
        $is_txt = true;
        $txt_type = 'Plain text/HTML/XML/JavaScript/web file';
        break;
      case 'cgi':
        $is_txt = true;
        $txt_type = 'Plain text/CGI script';
        break;
      case 'tmpl':
        $is_txt = true;
        $txt_type = 'Plain text/Template file';
        break;
      case 'c':
      case 'cpp':
      case 'h':
      case 'hpp':
        $is_txt = true;
        $txt_type = 'Plain text/C/C++ programming file';
        break;
      case 'ini':
      case 'inf':
      case 'reg':
        $is_txt = true;
        $txt_type = 'Plain text/INI/Setup/Settings file';
        break;
      case 'sh':
        $is_txt = true;
        $txt_type = 'Plain text/Unix shell script';
        break;
      case 'vbs':
        $is_txt = true;
        $txt_type = 'Plain text/Visual Basic script';
        break;
      case 'readme':
        $is_txt = true;
        $txt_type = 'Plain text/README file';
        break;
      case 'nsi':
        $is_txt = true;
        $txt_type = 'Plain text/NSIS script file';
        break;
      case 'asp':
        $is_txt = true;
        $txt_type = 'Plain text/Active Server Page file';
        break;
      case 'sql':
        $is_txt = true;
        $txt_type = 'Plain text/SQL data';
        break;
      default:
        $is_txt = false;
    }


      // if getid3 is going to be called, set up $filename, then get info
    if(!$is_txt && $getid3_true2){
      $filename = loc1 . $prop;
      $getID3 = new getID3;
      $fileinfo = $getID3->analyze($filename);
    }

    if(isset($fileinfo['error'][0]) && (count($fileinfo['error']) > 1 || $fileinfo['error'][0] != 'unable to determine file format')){
      echo '<font color="red">More info may be available if getid3 was configured correctly.</font><br>';
      if(!isset($_GET['showerror']) && (($GLOBALS['perm'] == 0 && $GLOBALS['permtype'] != 'hex') || hexdec($GLOBALS['perm']) == 0))
        echo '<a href="'.phpSelf.'?loc='.locenc.'&prop='.$prop.'&showerror=1">Show error(s)</a>';
      if(isset($_GET['showerror'])){
        echo '<pre>';
        print_r($fileinfo['error']);
        echo '</pre>';
      }
    }

    if($echo) echo '<div align="center"><font size="+1"><b>File Properties</b></font></div><br>'; else array_unshift($GLOBALS['prevcmd'], 'File Properties');
    if($echo) echo '<table cellpadding="4" cellspacing="0" border="1" align="center">';
    if($echo){ echo '<tr><td align="right">File name</td><td><a ';
    if($GLOBALS['force_download'] != 0)
      echo 'title="Download file" href="'.phpSelf.'?forcedownloadfile='.$prop.'">';
    else
      echo 'title="Open file in separate window" target="_blank" href="'.cur_dir.$prop.'">';
    echo get_name($prop) .'</a></td></tr>'; } else array_unshift($GLOBALS['prevcmd'], 'File name: ' . get_name($prop));
    if($echo) echo '<tr><td align="right">'.note(2, 220, 190).' File path</td><td>'. $prop .'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'File path: ' . $prop);
    $file_size = filesize(loc1 . $prop);
    if($echo) echo '<tr><td align="right">File size</td><td>'; else array_unshift($GLOBALS['prevcmd'], 'File size: ' . $file_size . ' bytes');
    if($file_size > 980 && $echo)
      echo filesz($file_size) . ', ';
    if($echo) echo $file_size .' bytes</td></tr>';
    if($GLOBALS['show_file_hash']){
      if($file_size < $GLOBALS['hash_size'] * 1024 * 1024){
        if($echo) echo '<tr><td align="right">MD5 Hash</td><td>'.md5_file(loc1 . $prop).'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'MD5 Hash: '.md5_file(loc1 . $prop));
        if($echo) echo '<tr><td align="right">SHA1 Hash</td><td>'.sha1_file(loc1 . $prop).'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'SHA1 Hash: '.sha1_file(loc1 . $prop));
      } else
        echo '<tr><td colspan="2">Hashes for this file have been hidden due to the size of the file, <u><a onMouseOver="this.style.cursor=\'move\'" onClick="JavaScript:window.open(\''.phpSelf.'?note=20&file='.$prop.'\',\'note\',\'width=450,height=60,dependent=yes,location=no,scrollbars=yes,menubar=no,status=no,resizable=yes\')">click here to view hashes.</a></u> It may take a few seconds to generate.';
    }
    if($echo) echo '<tr><td align="right">File created</td><td>'. date("F d, Y H:i (O)", filectime(loc1 . $prop)) .' </td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'File created: ' . date("F d, Y H:i (O)", filectime(loc1 . $prop)));
    if($echo) echo '<tr><td align="right">File modified</td><td>'. date("F d, Y H:i (O)", filemtime(loc1 . $prop)) .'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'File modified: ' . date("F d, Y H:i (O)", filemtime(loc1 . $prop)));
    if($echo) echo '<tr><td align="right">File accessed</td><td>'. date("F d, Y H:i (O)", fileatime(loc1 . $prop)) .'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'File accessed: ' . date("F d, Y H:i (O)", fileatime(loc1 . $prop)));

    if($echo && ($ftype == 'gif' || $ftype == 'jpg' || $ftype == 'jpeg'
    || $ftype == 'png' || $ftype == 'swf' || $ftype == 'swc'
    || $ftype == 'psd' || $ftype == 'tiff' || $ftype == 'bmp'
    || $ftype == 'iff' || $ftype == 'jp2' || $ftype == 'jpx'
    || $ftype == 'jb2' || $ftype == 'jpc' || $ftype == 'xbm'
    || $ftype == 'wbmp' || $ftype == 'tif' || $ftype == 'ico'))
      @$image_info = getimagesize(loc1 . $prop);
    if(isset($image_info[2])){

      $image_type_array = array(NULL,'GIF','JPEG','PNG','Flash','Photoshop','BitMap','TIFF(intel byte order)',
      'TIFF(motorola byte order)','JPC','JP2','JPX','JB2','SWC','IFF','WBMP','XBM');
      $image_channel_array = array(NULL,' (gray scale)',NULL,' (RGB)',' (CMYK)');

      echo '<tr><td align="right">Image info:</td><td>';
      echo 'Image resolution: '. $image_info[0] .'x'. $image_info[1] .'<br>';
      echo 'Image type: '. $image_type_array[$image_info[2]] .'<br>';
      if(isset($image_info['bits']))
        echo 'Image depth: '. $image_info['bits'] .'-bit<br>';
      if(isset($image_info['channels']))
        echo 'Image channels: '. $image_info['channels'] . $image_channel_array[$image_info['channels']] .'<br>';
      if(($ftype == 'jpeg' || $ftype == 'jpg' || $ftype == 'tiff' || $ftype == 'tif')){
        if(function_exists('exif_read_data') && strpos($prop, '\'') === false){
          $image = loc1 . $prop;
          if($image_info = @getimagesize($image)){
            $exif = @exif_read_data($image, 'ANY_TAG', true);
            if($exif !== false){
              function reduce($numb){
                if(strpos($numb, '/') === false)
                  return $numb;

                $exp = explode('/', $numb);
                $num = (int)$exp[0];
                $den = (int)$exp[1];

                if($den == $num)
                  return '1';
                if($den == 1)
                  return $num;
                if($num == 1)
                  return '1/'.$den;
                if($den > $num)
                  return '1/'.($den / $num);
                else
                  return ($num / $den);
              }
              if(isset($exif['EXIF']['ColorSpace']) && $exif['EXIF']['ColorSpace'] > 1)
                echo 'Colors: '.$exif['EXIF']['ColorSpace'].'<br>';
              if(isset($exif['IFD0']['Software']))
                echo 'Created by: '.$exif['IFD0']['Software'].'<br>';
              if(isset($exif['IFD0']['Make']))
                echo 'Make: '.$exif['IFD0']['Make'].'<br>';
              if(isset($exif['IFD0']['Model']))
                echo 'Model: '.$exif['IFD0']['Model'].'<br>';
              if(isset($exif['EXIF']['DateTimeOriginal']))
                echo 'Date/Time taken: '.$exif['EXIF']['DateTimeOriginal'].'<br>';
              if(isset($exif['IFD0']['DateTime']))
                echo 'Date/Time downloaded/edited: '.$exif['IFD0']['DateTime'].'<br>';
              if(isset($exif['EXIF']['ExposureTime']))
                echo 'Exposure time: '.reduce($exif['EXIF']['ExposureTime']).'"<br>';
              if(isset($exif['COMPUTED']['ApertureFNumber']))
                echo 'Aperture: '.$exif['COMPUTED']['ApertureFNumber'].'<br>';
              if(isset($exif['EXIF']['DigitalZoomRatio']))
                echo 'Digital zoom: '.reduce($exif['EXIF']['DigitalZoomRatio']).'x<br>';
              elseif(isset($exif['IFD0']['DigitalZoomRatio']))
                echo 'Digital zoom: '.reduce($exif['IFD0']['DigitalZoomRatio']).'x<br>';
              if(isset($exif['EXIF']['FocalLengthIn35mmFilm']))
                echo 'Approx. focal distance (in 35mm): '.round($exif['EXIF']['FocalLengthIn35mmFilm'] * 0.7).'mm ('.$exif['EXIF']['FocalLengthIn35mmFilm'].'mm)<br>';
              elseif(isset($exif['IFD0']['FocalLengthIn35mmFilm']))
                echo 'Approx. focal distance (in 35mm): '.round($exif['IFD0']['FocalLengthIn35mmFilm'] * 0.7).'mm ('.$exif['IFD0']['FocalLengthIn35mmFilm'].'mm)<br>';
              //if(isset($exif['EXIF']['FocalLength']))
              //  echo 'Focus distance: '.reduce($exif['EXIF']['FocalLength']).'m<br>';
              if(isset($exif['EXIF']['Flash']))
                echo 'Flash type or power '.note(14, 220, 300).': '.$exif['EXIF']['Flash'].'<br>';
              //$exif = @exif_read_data($image, 'THUMBNAIL', true);
              if(isset($exif['THUMBNAIL']))
                echo '<div align="center"><img border="1" src="'.phpSelf.'?showthumb=1&image='.$image.'"></div>';
              /*echo '<pre>';
              print_r($exif); // lots of info for digital photographs
              echo '</pre>';*/
            } elseif(!function_exists('exif_read_data'))
              echo '<br>Much more information is available if EXIF support was available (read the README to learn how to enable EXIF support).';
          }
        }
      }
      echo '</td></tr>';
    } else

    if($echo && $is_txt){
      echo '<tr><td align="right">Additional info:</td><td>';
      echo 'Number of lines: '.count(file(loc1 . $prop)).'<br>';
      echo 'Text type: '. $txt_type . '<br>';

        // if the file is a text file, display some of it's contents
      if($ftype == 'txt' || $ftype == 'list' || $ftype == 'nfo' || $ftype == 'log'
      || $ftype == 'diz' || $ftype == 'php' || $ftype == 'php3' || $ftype == 'phtml' || $ftype == 'php5'
      || $ftype == 'php4' || $ftype == 'js' || $ftype == 'xhtml' || $ftype == 'asp'
      || $ftype == 'xml' || $ftype == 'ini' || $ftype == 'inf' || $ftype == 'reg' || $ftype == 'c'
      || $ftype == 'cpp' || $ftype == 'h' || $ftype == 'hpp' || $ftype == 'sh' || $ftype == 'vbs'
      || $ftype == 'readme' || $ftype == 'shtml' || $ftype == 'nsi' || $ftype == 'cgi' || $ftype == 'tmpl'
      || $ftype == 'sql'){
        $contents  = file(loc1 . $prop);
        if(magicQuotes)
          $contents2 = stripslashes($contents[0] . @$contents[1] . @$contents[2] . rtrim(@$contents[3]));
        else
          $contents2 = $contents[0] . @$contents[1] . @$contents[2] . rtrim(@$contents[3]);
        $contlen = strlen($contents2);
        if($contlen > 60){
          $contlen = 60;
          $contover = true;
        } else
          $contover = false;
        echo 'Contents: ' . str_replace("\n", ' :: ', str_replace("\r", '', htmlspecialchars(substr($contents2, 0, $contlen))));
        if($contover)
          echo '...';
      } else
        // if the file is an HMTL file, display it's title, or body, or contents
      if($ftype == 'htm' || $ftype == 'html'){
        $titover = false;
        $bodover = false;
        $conover = false;
        $contents = file_get_contents(loc1 . $prop);
        if(magicQuotes)
          $contents = stripslashes($contents);

        $contents2 = strtolower($contents);
        $contents3 = $contents;
        $contents4 = $contents2;
        $show_cont = true;
        if(strpos($contents2, '<title>') !== false){
          $titlepos1 = 7 + strpos($contents2, '<title>');
          $contents2 = substr($contents2, $titlepos1);
          if(strpos($contents2, '</title>') !== false){
            $titlepos2 = strpos($contents2, '</title>');
            if($titlepos2 > 60){
              $titlepos2 = 60;
              $titover = true;
            }
            echo 'Title: ' . htmlspecialchars(substr($contents, $titlepos1, $titlepos2)) . '<br>';
            if($titover)
              echo '...';
            $show_cont = false;
          }
        }
        $contents = $contents3;
        $contents2 = $contents4;
        if(strpos($contents2, '<body') !== false){
          $bodypos1 = 5 + strpos($contents2, '<body');
          $contents2 = substr($contents2, $bodypos1);
          $bodypos3 = 1 + strpos($contents2, '>');
          $contents2 = substr($contents2, $bodypos3);
          if(strpos($contents2, '</body>') !== false){
            $bodypos2 = strpos($contents2, '</body>');
            if($bodypos2 > 60){
              $bodypos2 = 60;
              $bodover = true;
            }
            $bodycont = substr($contents, $bodypos1 + $bodypos3, $bodypos2);
            echo 'Page body: ' . str_replace("\n", ' :: ', str_replace("\r", '', htmlspecialchars($bodycont))) . '<br>';
            if($bodover)
              echo '...';
            $show_cont = false;
          }
        }
        if($show_cont){
          $cont_len = strlen($contents);
          if($cont_len > 60){
            $cont_len = 60;
            $conover = true;
          }
          echo 'Page contents: ' . str_replace("\n", ' :: ', str_replace("\r", '', htmlspecialchars(substr($contents, 0, $cont_len)))) . '<br>';
          if($conover)
            echo '...';
        }
      }

      echo '</td></tr>';
    } else

      // get a heck of a lot of ID3 info here, dang!
    if($echo && $getid3_true2 && isset($fileinfo['fileformat']) && $fileinfo['fileformat'] != 'zip'){
      echo '<tr><td align="right">'.note(3, 175, 150).' Audio/Video Info</td><td>';
      echo 'Format: '. $fileinfo['fileformat'] .'<br>';
      echo 'Length: '. $fileinfo['playtime_string'] .'<br>';
      if(!isset($fileinfo['video']) && isset($fileinfo['audio']['compression_ratio']))
        echo 'Bit rate (true '.note(18, 200, 220).') (original '.note(17, 180, 200).'): '. round($fileinfo['bitrate'] / 1000) .' Kbps ('.filesz($file_size * 8 / $fileinfo['playtime_seconds'], false, 3).'ps) ('.filesz($fileinfo['audio']['bitrate'] / $fileinfo['audio']['compression_ratio'], false, 3).'ps)<br>';
      elseif(isset($fileinfo['video']) && isset($fileinfo['video']['compression_ratio']))
        echo 'Bit rate (true '.note(18, 200, 220).') (original '.note(17, 180, 200).'): '. round($fileinfo['bitrate'] / 1000) .' Kbps ('.filesz($file_size * 8 / $fileinfo['playtime_seconds'], false, 3).'ps) ('.filesz($fileinfo['video']['bitrate'] / $fileinfo['video']['compression_ratio'], false, 3).'ps)<br>';
      else
        echo 'Bit rate (true '.note(18, 200, 220).'): '. round($fileinfo['bitrate'] / 1000) .' Kbps ('.filesz($file_size * 8 / $fileinfo['playtime_seconds'], false, 3).'ps)<br>';
      //echo 'True bit rate: '.filesz($file_size * 8 / $fileinfo['playtime_seconds'], false, 5).'ps<br>';
      if(isset($fileinfo['video']['codec']))
        echo 'Video codec: '. $fileinfo['video']['codec'] .'<br>';
      if(isset($fileinfo['audio']['codec']))
        echo 'Audio codec: '. $fileinfo['audio']['codec'] .'<br>';
      elseif(isset($fileinfo['audio']['streams'][0]['codec']))
        echo 'Audio codec: '. $fileinfo['audio']['streams'][0]['codec'] .'<br>';
      if(isset($fileinfo['video']) && isset($fileinfo['audio']['bitrate'])){
        if(isset($fileinfo['audio']['compression_ratio']))
          echo 'Audio bit rate (original '.note(17, 180, 200).'): '. filesz($fileinfo['audio']['bitrate'], false) .'ps ('.filesz($fileinfo['audio']['bitrate'] / $fileinfo['audio']['compression_ratio'], false, 3).'ps)<br>';
        else
          echo 'Audio bit rate: '. filesz($fileinfo['audio']['bitrate'], false) .'ps';
      } elseif(isset($fileinfo['video']) && isset($fileinfo['audio']['streams'][0]['bitrate'])){
        if(isset($fileinfo['audio']['streams'][0]['compression_ratio']))
          echo 'Audio bit rate (original '.note(17, 180, 200).'): '. filesz($fileinfo['audio']['streams'][0]['bitrate'], false) .'ps ('.filesz($fileinfo['audio']['streams'][0]['bitrate'] / $fileinfo['audio']['streams'][0]['compression_ratio'], false, 3).'ps)<br>';
        else
          echo 'Audio bit rate: '. filesz($fileinfo['audio']['streams'][0]['bitrate'], false) .'ps';
      }

      if(isset($fileinfo['audio']['channels']) && isset($fileinfo['audio']['channelmode']))
        echo 'Audio channels: '. $fileinfo['audio']['channels'] .' ('. $fileinfo['audio']['channelmode'] .')<br>';
      elseif(isset($fileinfo['audio']['channels']))
        echo 'Audio channels: '. $fileinfo['audio']['channels'] .'<br>';
      if(isset($fileinfo['audio']['sample_rate']))
        echo 'Audio sample rate: '. $fileinfo['audio']['sample_rate'] .' Hz<br>';
      if(isset($fileinfo['audio']['bits_per_sample']))
        echo 'Audio sample size: '. $fileinfo['audio']['bits_per_sample'] .' bits<br>';

      if(isset($fileinfo['tags']['id3v1']) || isset($fileinfo['tags']['id3v2'])){
        if(isset($fileinfo['tags']['id3v1']['title'][0]))
          echo 'Song title: '. $fileinfo['tags']['id3v1']['title'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v1']['artist'][0]))
          echo 'Song artist: '. $fileinfo['tags']['id3v1']['artist'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v1']['album'][0]))
          echo 'Song album: '. $fileinfo['tags']['id3v1']['album'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v2']['genre'][0]))
          echo 'Song genre: '. $fileinfo['tags']['id3v2']['genre'][0] .'<br>';
        elseif(isset($fileinfo['tags']['id3v1']['genre'][0]))
          echo 'Song genre: '. $fileinfo['tags']['id3v1']['genre'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v1']['track'][0]))
          echo 'Song track: '. $fileinfo['tags']['id3v1']['track'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v1']['year'][0]))
          echo 'Song year: '. $fileinfo['tags']['id3v1']['year'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v2']['composer'][0]))
          echo 'Song composer: '. $fileinfo['tags']['id3v2']['composer'][0] .'<br>';
        if(isset($fileinfo['tags']['id3v2']['publisher'][0]))
          echo 'Song publisher: '. $fileinfo['tags']['id3v2']['publisher'][0] .'<br>';
      } else
      if(isset($fileinfo['tags'][$fileinfo['fileformat']])){
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['title'][0]))
          echo 'Song title: '. $fileinfo['tags'][$fileinfo['fileformat']]['title'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['artist'][0]))
          echo 'Song artist: '. $fileinfo['tags'][$fileinfo['fileformat']]['artist'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['album'][0]))
          echo 'Song album: '. $fileinfo['tags'][$fileinfo['fileformat']]['album'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['genre'][0]))
          echo 'Song genre: '. $fileinfo['tags'][$fileinfo['fileformat']]['genre'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['track'][0]))
          echo 'Song track: '. $fileinfo['tags'][$fileinfo['fileformat']]['track'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['year'][0]))
          echo 'Song year: '. $fileinfo['tags'][$fileinfo['fileformat']]['year'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['composer'][0]))
          echo 'Song composer: '. $fileinfo['tags'][$fileinfo['fileformat']]['composer'][0] .'<br>';
        if(isset($fileinfo['tags'][$fileinfo['fileformat']]['publisher'][0]))
          echo 'Song publisher: '. $fileinfo['tags'][$fileinfo['fileformat']]['publisher'][0] .'<br>';
      }

      if(isset($fileinfo['video']['resolution_x']))
        echo 'Video resolution: '. $fileinfo['video']['resolution_x'] . 'x' . $fileinfo['video']['resolution_y'] .'<br>';
      if(isset($fileinfo['video']['frame_rate']))
        echo 'Video frame rate: '. $fileinfo['video']['frame_rate'] .'<br>';
      if(isset($fileinfo['video']['bits_per_sample']))
        echo 'Video sample size: '. $fileinfo['video']['bits_per_sample'] .' bits<br>';
      if(isset($fileinfo[$fileinfo['fileformat']]['video']['color_depth']))
        echo 'Video color depth: '. $fileinfo[$fileinfo['fileformat']]['video']['color_depth'] .'-bit<br>';
      if(isset($fileinfo['tags_html'][$fileinfo['fileformat']]['author'][0]))
        echo 'Video author: '. $fileinfo['tags_html'][$fileinfo['fileformat']]['author'][0] .'<br>';
      if($fileinfo['fileformat'] == 'mp4' && isset($fileinfo['error'][0]))
        echo '<font color="red">MP4 format is not fully supported by 1.7.4, some information may be incorrect or missing</font>';

      /*echo '<pre>';
      print_r($fileinfo);
      echo '</pre>';*/

      echo '</td></tr>';
    }
    if($echo) echo '</table>';
    if($echo) echo '<a href="JavaScript:window.close()">Click here to close this window.</a>';
    return true;
  } else

  if(is_dir(loc1 . $prop) && $GLOBALS['current_user']['list'] && substr($prop, 0, 1) != '.' && strpos(strtolower($prop), 'filelist') === false && strpos(strtolower($prop), 'filemanage') === false && substr($prop, 1, 6) != 'getid3' && $prop != '/'){
    if($echo) echo '<div align="center"><font size="+1"><b>Directory Properties</b></font></div><br>'; else array_unshift($GLOBALS['prevcmd'], 'Directory Properties');
    if($echo) echo '<table cellpadding="4" cellspacing="0" border="1" align="center">';
    $ar = explode('/', $prop);
    $dir_nm = $ar[count($ar) - 1];
    if($echo) echo '<tr><td align="right">Directory name</td><td><a target="blank" title="Open directory" href="' . phpSelf . '?loc=' . $prop .'">'. $dir_nm .'</a></td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'Directory name: ' . $dir_nm);
    if($echo) echo '<tr><td align="right">'.note(2, 220, 190).' Directory path</td><td>'. $prop .'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'Directory path: ' . $prop);
    clearscandir();
    scanfulldir(loc1 . $prop);
    $total_file_size = $GLOBALS['total_file_size'];
    if($echo) echo '<tr><td align="right">Directory volume</td><td>'; else array_unshift($GLOBALS['prevcmd'], 'Directory volume: ' . $total_file_size . ' bytes');
    if($total_file_size > 980 && $echo)
      echo filesz($total_file_size) . ', ';
    if($echo) echo $total_file_size .' bytes</td></tr>';
    if($echo) echo '<tr><td align="right">Directory created</td><td>'. date("F d, Y H:i (O)", filectime(loc1 . $prop)) .'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'Directory created: ' . date("F d, Y H:i (O)", filectime(loc1 . $prop)));
    if($echo) echo '<tr><td align="right">Directory modified</td><td>'. date("F d, Y H:i (O)", filemtime(loc1 . $prop)) .'</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'Directory modified: ' . date("F d, Y H:i (O)", filemtime(loc1 . $prop)));
    if($echo) echo '<tr><td align="right">Contains</td><td>'. $GLOBALS['number_of_files'] .' files, '. $GLOBALS['number_of_dirs'] .' directories</td></tr>'; else array_unshift($GLOBALS['prevcmd'], 'Contains: ' . $GLOBALS['number_of_files'] .' files, '. $GLOBALS['number_of_dirs'] .' directories');
    if($echo) echo '</table>';
    return true;
  } else {
    if($echo) echo '<font color="red">File or directory is not accessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File or directory is not accessible.');
    return false;
  }
} // end of prop()



  // this function scans a directory and all subdirectories and returns some stats on them
  // it scans all files, instead of just accepted ones.
  // void scanfulldir( str 'directory path' ) *int 'number of directories counted' $number_of_dirs *int 'number of files counted' $number_of_files *int 'total size of files counted' $total_file_size
function scanfulldir($dir){

  if(!isset($GLOBALS['number_of_dirs']))
    $GLOBALS['number_of_dirs'] = 0;
  if(!isset($GLOBALS['number_of_files']))
    $GLOBALS['number_of_files'] = 0;
  if(!isset($GLOBALS['total_file_size']))
    $GLOBALS['total_file_size'] = 0;

  if(is_dir($dir)){

    if($handle = opendir($dir)){           // if the folder exploration is sucsessful, continue
      while(false !== ($file = readdir($handle))){ // as long as storing the next file to $file is successful, continue
        $path = $dir . '/' . $file;

        if(is_file($path)){
          $GLOBALS['number_of_files']++;
          $GLOBALS['total_file_size'] += filesize($path);
        } else
        if(is_dir($path) && substr($file, 0, 1) != '.'){
          $GLOBALS['number_of_dirs']++;
          scanfulldir($path);
        }
      }
      closedir($handle); // close the folder exploration
    }

  }

} // end of scanfulldir()



  // this function just clears the values set by scanfulldir() so it can be used again
  // void clearscandir( void )
function clearscandir(){
  unset($GLOBALS['number_of_files']);
  unset($GLOBALS['number_of_dirs']);
  unset($GLOBALS['total_file_size']);
} // end of clearscandir()



  // function returns all files or directories matching the $search parameter
  // (with wild cards)
  // void getarrayofmatching( str 'str to match' [, bool 'include dirs?' [, bool 'include files?' [, str 'current function location' ]]] )
function getarrayofmatching($search, $dirs = true, $files = true, $dir = loc1){

  if($GLOBALS['php_version'][0] > 4 || ($GLOBALS['php_version'][0] == 4 && $GLOBALS['php_version'][1] > 3) || ($GLOBALS['php_version'][0] == 4 && $GLOBALS['php_version'][1] == 3 && $GLOBALS['php_version'][2] >= 3))
    $dir_list = glob($dir . '/'.'*', GLOB_ONLYDIR); // /* is split for code highlighting program problems
  else
    $dir_list = glob($dir . '/'.'*'); // /* is split for code highlighting program problems
  $tmp_items_ar = glob($dir . '/' . $search);

  foreach($tmp_items_ar as $item){
    if($dirs)
      if(is_dir($item))
        $tmp_items_ar1[] = str_replace(loc1, '', $item . '/');

    if($files)
      if(is_file($item))
        $tmp_items_ar1[] = str_replace(loc1, '', $item);
  }

  if(isset($tmp_items_ar1) && count($tmp_items_ar1) > 0)
    $GLOBALS['items_ar'] = array_merge($GLOBALS['items_ar'], $tmp_items_ar1);

  foreach($dir_list as $item){
    $item1 = str_replace(loc1, '', $item);
    if(is_dir($item) && strpos($item1, 'filelist') === false && strpos($item1, 'filemanage') === false && strpos($item1, 'getid3') === false)
      getarrayofmatching($search, $dirs, $files, $item);
  }
} // end of getarrayofmatching()



function max_load_stats($max){
  if($max > 15)
    return '<font color="red">Morbidly slow!</font>';
  elseif($max > 13)
    return '<font color="red">Pitifully slow!</font>';
  elseif($max > 11)
    return '<font color="red">Extremely slow!</font>';
  elseif($max > 9)
    return '<font color="yellow">Pretty slow.</font>';
  elseif($max > 7)
    return '<font color="yellow">Slow.</font>';
  elseif($max > 5)
    return '<font color="yellow">Average.</font>';
  elseif($max > 3)
    return '<font color="green">Above average.</font>';
  elseif($max > 2)
    return '<font color="green">Fast.</font>';
  elseif($max > 1)
    return '<font color="green">Extremely fast!</font>';
  else
    return '<font color="green">Unbelievably fast!</font>';
} // end of max_load_stats()



function min_load_stats($min){
  if($min > 0.5)
    return '<font color="red">Morbidly slow!</font>';
  elseif($min > 0.25)
    return '<font color="red">Pitifully slow!</font>';
  elseif($min > 0.15)
    return '<font color="red">Extremely slow!</font>';
  elseif($min > 0.08)
    return '<font color="yellow">Pretty slow.</font>';
  elseif($min > 0.03)
    return '<font color="yellow">Slow.</font>';
  elseif($min > 0.018)
    return '<font color="yellow">Average.</font>';
  elseif($min > 0.01)
    return '<font color="green">Above average.</font>';
  elseif($min > 0.006)
    return '<font color="green">Fast.</font>';
  elseif($min > 0.003)
    return '<font color="green">Extremely fast!</font>';
  else
    return '<font color="green">Unbelievably fast!</font>';
} // end of min_load_stats()



function avg_load_stats($avg){
  if($avg > 7)
    return '<font color="red">Morbidly slow!</font>';
  elseif($avg > 5)
    return '<font color="red">Pitifully slow!</font>';
  elseif($avg > 3.5)
    return '<font color="red">Extremely slow!</font>';
  elseif($avg > 1.7)
    return '<font color="yellow">Pretty slow.</font>';
  elseif($avg > 1)
    return '<font color="yellow">Slow.</font>';
  elseif($avg > 0.7)
    return '<font color="yellow">Average.</font>';
  elseif($avg > 0.4)
    return '<font color="green">Above average.</font>';
  elseif($avg > 0.2)
    return '<font color="green">Fast.</font>';
  elseif($avg > 0.1)
    return '<font color="green">Very fast!</font>';
  elseif($avg > 0.05)
    return '<font color="green">Extremely fast!</font>';
  else
    return '<font color="green">Unbelievably fast!</font>';
} // end of avg_load_stats()



  // this function deletes all files and sub directories directories in a directory
  // bool remdir( str 'directory path' )
function remdir($dir){

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(!isset($GLOBALS['remerror']))
    $GLOBALS['remerror'] = false;

  if($handle = opendir(loc1 . $dir)){           // if the folder exploration is sucsessful, continue
    while (false !== ($file = readdir($handle))){ // as long as storing the next file to $file is successful, continue
      $path = $dir . '/' . $file;
      if(is_file(loc1 . $path)){
        if(!unlink(loc1 . $path)){
          if($echo) echo '<u><font color="red">"' . $path . '" could not be deleted. This may be due to a permissions problem.</u><br>Directory cannot be deleted until all files are deleted.</font><br>'; else array_unshift($GLOBALS['prevcmd'], $path . '" could not be deleted. Directory cannot be deleted until it is empty.');
          writelog('<font color="red">User tried to delete a directory, but deleting a file in it failed (may be a permissions problem)</font>', 'ren', $path .' in '. $dir, 1);
          $GLOBALS['remerror'] = true;
          return false;
        }
      } else
      if(is_dir(loc1 . $path) && substr($file, 0, 1) != '.'){
        remdir($path);
        @rmdir(loc1 . $path);
      }
    }
    closedir($handle); // close the folder exploration
  }

  if(!$GLOBALS['remerror']) // if no errors occured, delete the now empty directory.
    if(!@rmdir(loc1 . $dir)){
      if($echo) echo '<b><font color="red">Could not remove directory "' . $dir . '". This may be due to a permissions problem.</font></b><br>'; else array_unshift($GLOBALS['prevcmd'], 'Could not remove directory "' . $dir . '".');
      writelog('<font color="red">User tried to delete a directory, but it failed (may be a permissions problem)</font>', 'ddel', $dir, 1);
      return false;
    } else
      return true;

  return false;
} // end of remdir()



  // rename file or directory
  // bool ren( str 'path to file/dir', str 'new name' )
function ren($ren, $ren2){
  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if((is_file(loc1 . $ren) && allowed($ren))
  || (is_dir(loc1 . $ren) && strpos($ren, '..') === false && strpos(strtolower($ren), 'filelist') === false
  && strpos(strtolower($ren), 'filemanage') === false && $ren != '/')){

    $req_ren2 = true;
    if(check_name($ren2)){

      get_name($ren);
      $pre_ex = $GLOBALS['pre_ex'];

      $was_file = false;
      $was_dir  = false;

      if(is_file(loc1 . $ren)){
        $was_file = true;
        if(!is_file(loc1 . '/' . $pre_ex . $ren2)){
          if(allowed($ren2, true, true, false)){
            $ftype1 = get_ftype($ren);
            $ftype2 = get_ftype($ren2);
            if($ftype1 != 'php' && $ftype1 != 'php3' && $ftype1 != 'php4' && $ftype1 != 'php5' && $ftype1 != 'phtml' && ($ftype2 == 'php' || $ftype2 == 'php3' || $ftype2 == 'php4' || $ftype2 == 'php5' || $ftype2 == 'phtml'))
              $filecont = file_get_contents(loc1 . $ren);
            else
              $filecont = '';
            if(check_contents($filecont)){
              if(!rename(loc1 . $ren, loc1 . '/' . $pre_ex . $ren2)){
                if($echo) echo '<b><font color="red">The file ('. $ren .') could not be renamed. This could be a permissions problem.</font></b><br>'; else array_unshift($GLOBALS['prevcmd'], 'The file ('. $ren .') could not be renamed. This could be a permissions problem.');
                writelog('<font color="red">User tried to rename a file, but it failed (may be a permissions problem)</font>', 'ren', $ren .' - '. $pre_ex . $ren2, 1);
                return false;
              }
            } else {
              if($echo) echo '<b><font color="red">The file is being renamed to a PHP extension, and it previously was not.</font></b>'; else array_unshift($GLOBALS['prevcmd'], 'The file is being renamed to a PHP extension, and it previously was not.');
              if($echo && is_file(loc1 . '/filelist/filelist-passcode.php'))
                echo '<br>Enter correct passcode: <input name="overridepasscode" type="password" size="30" /><input type="submit" size="150" value="Go"><br>';
              writelog('<font color="red">User tried to rename a file to a PHP when it wasn\'t previously.</font>', 'ren', $ren .' - '. $pre_ex . $ren2, 1);
            }
          } else {
            if($echo) echo '<b><font color="red">The file name "'. $ren2 .'" has an invalid extension, is being created in an invalid directory, or is otherwise blocked.</font></b><br>'; else array_unshift($GLOBALS['prevcmd'], 'The file name "'. $ren2 .'" has a invalid extension.');
            return false;
          }
        } else {
          if($echo) echo '<b><font color="red">A file named "'. $ren2 .'" already exists. Try a different name.</font></b><br>'; else array_unshift($GLOBALS['prevcmd'], 'A file named "'. $ren2 .'" already exists.');
          return false;
        }
      } else
      if(is_dir(loc1 . $ren)){
        $was_dir = true;
        if(!is_dir(loc1 . '/' . $pre_ex . $ren2)){
          if(!rename(loc1 . $ren, loc1 . '/' . $pre_ex . $ren2)){
            if($echo) echo '<b><font color="red">The directory (' . $ren . ') could not be renamed. This could be a permissions problem.</font></b>'; else array_unshift($GLOBALS['prevcmd'], 'The directory ('. $ren .') could not be renamed. This could be a permissions problem.');
            writelog('<font color="red">User tried to rename a directory, but it failed (may be a permissions problem)</font>', 'ren', $ren .' - '. $pre_ex . $ren2, 1);
            return false;
          }
        } else {
          if($echo) echo '<b><font color="red">A directory named "'. $ren2 .'" already exists. Try a different name.</font></b>'; else array_unshift($GLOBALS['prevcmd'], 'A directory named "'. $ren2 .'" already exists.');
          return false;
        }
      }

    } else
      return false;

    if((is_file(loc1 . '/' . $pre_ex . $ren2) && $was_file) || (is_dir(loc1 . '/' . $pre_ex . $ren2) && $was_dir)){
      if($echo) echo '<font color="red">Renamed successfully.</font>';
      writelog('User renamed an item', 'ren', $ren .' - '. $pre_ex . $ren2);
      return true;
    } else {
      if($echo) echo '<b><font color="red">This item ('. $ren .') could not be renamed. This may be a permissions problem.</font></b>'; else array_unshift($GLOBALS['prevcmd'], 'The file ('. $ren .') could not be renamed. This could be a permissions problem.');
      writelog('<font color="red">User tried to rename an item, but it failed (may be a permissions problem)</font>', 'ren', $ren .' - '. $pre_ex . $ren2, 1);
      return false;
    }
  } else
    if($echo) echo '<font color="red">File/Directory is inaccessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File/Directory is inaccessible.');

  return false;
} // end of ren()



  // create a directory
  // bool cdir( str 'path to new dir' )
function cdir($cdir){
  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(check_name(get_name($cdir))){
    if(strpos($cdir, '..') === false && substr($cdir, 0, 1) != '.' && strpos(strtolower($cdir), 'filelist') === false && strpos(strtolower($cdir), 'filemanage') === false && substr(strtolower($cdir), 0, 6) != 'getid3'){
      if(!is_dir(loc1 . $cdir)){
        if(!mkdir(loc1 . $cdir)){
          if($echo) echo '<b><font color="red">The directory ('. $cdir .') could not be made. This may be a permissions problem1.</font></b>'; else array_unshift($GLOBALS['prevcmd'], 'The directory ('. $cdir .') could not be made. This may be a permissions problem.');
          writelog('<font color="red">User tried to create a directory, but it failed (may be a permissions problem)</font>', 'cdir', loc . $cdir, 1);
          return false;
        }
      } else {
        if($echo) echo '<b><font color="red">A directory named "'. $cdir .'" already exists. Try a different name.</font></b>'; else array_unshift($GLOBALS['prevcmd'], 'A directory named '. $cdir .' alredy exists.');
        return false;
      }

    } else {
      if($echo) echo '<font color="red">The directory name, "'. $cdir .'", is invalid. Try a different name.</font>'; else array_unshift($GLOBALS['prevcmd'], 'The directory name "'. $cdir .'" is invalid.');
      return false;
    }
  } else
    return false;

  if(is_dir(loc1 . $cdir)){
    if($echo) echo '<font color="red">Directory created successfully.</font>';
    writelog('User created a directory', 'cdir', $cdir);
    return true;
  } else {
    if($echo) echo '<font color="red">The directory ('. $cdir .') could not be made. This may be a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'The directory ('. $cdir .') could not be made. This may be a permissions problem.');
    writelog('<font color="red">User tried to create a directory, but it failed (may be a permissions problem)</font>', 'cdir', $cdir, 1);
    return false;
  }

} // end of cdir()



  // copy a file
  // bool cpy( str 'path to file to copy', str 'path of dir to copy to' )
function cpy($cpy, $loc){

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(is_file(loc1 . $cpy) && allowed($cpy)){

    $name = get_name($cpy);
    if(is_dir(loc1 . $loc)){
      if(file_exists(loc1 . $loc . $name)){
        $cpy2 = 'Copy of ' . $name;
        if(file_exists(loc1 . $loc . $cpy2)){
          $done = false;
          $num = 2;
          while(!$done){
            $cpy2 = 'Copy ('. $num .') of ' . $name;
            if(!file_exists(loc1 . loc . $cpy2))
              $done = true;
            $num++;
          }
        }
        $name = $cpy2;
      }
      if(!copy(loc1 . $cpy, loc1 . $loc . $name)){
        if($echo) echo '<font color="red">File ('.$cpy.') cannot be copied. May be a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$cpy.') cannot be copied. May be a permissions problem.');
        writelog('<font color="red">File could not be copied (may be a permissions problem)</font>', 'cpy', $cpy .' - '. $loc, 1);
        return false;
      } else {
        if($echo) echo '<font color="red">File copied successfully.</font>';
        writelog('User copied a file', 'cpy', $cpy .' - '. $loc);
        return true;
      }
    } else {
      if($echo) echo '<font color="red">Destination is not a valid directory.</font>'; else array_unshift($GLOBALS['prevcmd'], 'Destination is not a valid directory.');
      writelog('File could not be copied, destination not valid', 'cpy', $cpy .' - '. $loc, 4);
    }
  } else
    if($echo) echo '<font color="red">File not accessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File not accessible.');

  return false;
} // end of cpy()



  // delete a file
  // bool del( str 'path to file' )
function del($del){
  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(is_file(loc1 . $del) && allowed($del)){
      // try to delete file
    if(unlink(loc1 . $del)){
      if($echo) echo '<font color="red">File deleted successfully.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$del.') deleted successfully.');
      writelog('User deleted a file', 'del', $del);
      $return = true;
    } else {
      if($echo) echo 'Unable to delete file (' . $del . '), may be a permissions problem.'; else array_unshift($GLOBALS['prevcmd'], 'Unable to delete file (' . $del . '), may be a permissions problem.');
      writelog('<font color="red">User tried to delete a file, but it failed (may be a permissions problem)</font>', 'del', $del, 1);
      $return = false;
    }
    return($return);
  } else
    if($echo) echo '<font color="red">File is not accessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File is not accessible.');
  return false;
} // end of del()



  // delete a directory
  // bool ddel( str 'path to directory' )
function ddel($ddel){
  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(is_dir(loc1 . $ddel) && strpos(strtolower($ddel), 'filelist') === false && strpos(strtolower($ddel), 'filemanage') === false && substr(strtolower($ddel), 1, 6) != 'getid3' && $ddel != '/'){
      // try to delete directory
    remdir($ddel);
    if(!$GLOBALS['remerror'])
      if(!is_dir(loc1 . $ddel)){
        if($echo) echo '<font color="red">Directory deleted successfully.</font>'; else array_unshift($GLOBALS['prevcmd'], 'Directory deleted successfully.');
        writelog('User deleted a directory', 'ddel', $ddel);
        return true;
      } else {
        if($echo) echo '<font color="red">Unable to delete directory ('. $ddel .'), either the directory does not exist, or the webhosting server does not have permisions to delete the directory or the files contained in the directory.</font>'; else array_unshift($GLOBALS['prevcmd'], 'Unable to delete directory.');
        writelog('<font color="red">User tried to delete a directory, but it failed (may be a permissions problem)</font>', 'ddel', $ddel, 1);
        return false;
      }
    else {
      if($echo) echo '<font color="red">Unable to delete directory ('. $ddel .'), either the directory does not exist, or the webhosting server does not have permisions to delete the directory or the files contained in the directory.<font>'; else array_unshift($GLOBALS['prevcmd'], 'Unable to delete directory.');
      writelog('<font color="red">User tried to delete a directory but failed (may be a permissions problem)</font>', 'ddel', $ddel, 1);
      return false;
    }

  } else
    if($echo) echo '<font color="red">Directory is inaccessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'Directory is inaccessible.');
  return false;
} // end of ddel()



  // this function adds lines to the recycle database (/filelist/recycle_db.list)
  // to keep track of the files in the recycle bin. It can also remove lines for
  // when files are deleted or moved from the recycle bin
  // recycle_db(
function recycle_db($action, $item, $dir = false){

  if($action == 'add'){

    if($dir){
      clearscandir();
      scanfulldir(loc1 . $item);
      $size = $GLOBALS['total_file_size'];
    } else {
      $size = filesize(loc1 . $item);
      $dir = 0;
    }

    $name = get_name($item);
    if(is_file(loc1 . '/filelist/filelist-recycle_db.list') && file_exists(loc1 . '/filelist/.recycle/'.$name)){
      $recycle_db = file(loc1 . '/filelist/filelist-recycle_db.list');
      for($i = 0; $i < count($recycle_db); $i++){
        $sub_recycle = explode('~~~~~', trim($recycle_db[$i]));
        if($sub_recycle[0] == $name){
          $name2 = NULL;
          if(file_exists(loc1 . '/filelist/.recycle/cont/'.$name)){
            while(file_exists(loc1 . '/filelist/.recycle/cont/'.$name.$name2))
              $name2 .= mt_rand(0, 9);
          }
          $fout = fopen(loc1 . '/filelist/filelist-recycle_db.list', 'a');
          $fp = fwrite($fout, $name . '~~~~~cont/' . $name.$name2 . '~~~~~' . $item . '~~~~~' . $size . '~~~~~' . $dir . '~~~~~' . time() . $GLOBALS['line_break']);
          fclose($fout);
          writelog('User moved an item to the Recycle Bin', 'rec', 'cont/'.$name.$name2);
          return 'cont/'.$name.$name2;
        }
      }
    }
    $fout = fopen(loc1 . '/filelist/filelist-recycle_db.list', 'a');
    $fp = fwrite($fout, $name . '~~~~~' . $name . '~~~~~' . $item . '~~~~~' . $size . '~~~~~' . $dir . '~~~~~' . time() . $GLOBALS['line_break']);
    fclose($fout);
    $GLOBALS['recycle_db'][] = $name . '~~~~~' . $name . '~~~~~' . $item . '~~~~~' . $size . '~~~~~' . $dir . '~~~~~' . time() . $GLOBALS['line_break'];
    writelog('User moved an item to the Recycle Bin', 'rec', $name);
    return $name;

  } elseif($action == 'rem'){
    if(is_file(loc1 . '/filelist/filelist-recycle_db.list')){
      $recycle_db = file(loc1 . '/filelist/filelist-recycle_db.list');
      foreach($recycle_db as $recycle_entry){
        $sub_recycle = explode('~~~~~', trim($recycle_entry));
        if($sub_recycle[1] == $item){
          $return_dest = $sub_recycle[2];
        } else
          $new_recycle_db[] = $recycle_entry;
      }
      if(isset($new_recycle_db) && count($new_recycle_db) > 0){
        $fout = fopen(loc1 . '/filelist/filelist-recycle_db.list', 'w');
        $fp = fwrite($fout, implode('', $new_recycle_db));
        fclose($fout);
        $GLOBALS['recycle_db'] = $new_recycle_db;
      } else {
        unset($GLOBALS['recycle_db']);
        @unlink(loc1 . '/filelist/filelist-recycle_db.list');
      }
      return $return_dest;
    } else
      return false;
  } elseif($action == 'none'){
    if(is_file(loc1 . '/filelist/filelist-recycle_db.list')){
      $recycle_db = file(loc1 . '/filelist/filelist-recycle_db.list');
      foreach($recycle_db as $recycle_entry){
        $sub_recycle = explode('~~~~~', trim($recycle_entry));
        if($sub_recycle[1] == $item)
          return $sub_recycle[2];
      }
    } else
      return false;
  } else
    return false;
} // end of recycle_db()



  // copy a directory and all subdirectories and files (recursive)
  // void dircpy( str 'source directory', str 'destination directory' [, bool 'overwrite existing files'] )
function dircpy($source, $dest, $overwrite = false){

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if($handle = opendir(loc1 . $source)){         // if the folder exploration is sucsessful, continue
    while(false !== ($file = readdir($handle))){ // as long as storing the next file to $file is successful, continue
      if($file != '.' && $file != '..'){
        $path = $source . '/' . $file;
        if(is_file(loc1 . $path)){
          if(!is_file(loc1 . $dest . '/' . $file) || $overwrite)
            if(!@copy(loc1 . $path, loc1 . $dest . '/' . $file)){
              if($echo) echo '<font color="red">File ('.$path.') could not be copied, likely a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$path.') could not be copied, likely a permissions problem.');
              writelog('<font color="red">File could not be copied.</font>', 'dircpy', $path . ' - ' . $dest .'/'.$file, 1);
            }
        } elseif(is_dir(loc1 . $path)){
          if(!is_dir(loc1 . $dest . '/' . $file))
            mkdir(loc1 . $dest . '/' . $file); // make subdirectory before subdirectory is copied
          dircpy($path, $dest . '/' . $file, $overwrite); //recurse!
        }
      }
    }
    closedir($handle);
  }
} // end of dircpy()



  // move a file
  // bool move_recycle( str 'path to file to move', str 'path of dir to move to' )
function move_recycle($mv, $loc, $overwrite = false){

  if($GLOBALS['current_user']['delete'] || $admin){

    if(isset($GLOBALS['prevcmd']))
      $echo = false;
    else
      $echo = true;

    if(is_file(loc1 . $mv)){

      $name = get_name($loc);
      if(is_dir(loc1 . dirname($loc))){
        $cont = true;
        if(is_file(loc1 . $loc)){
          $cont = false;
          if($overwrite){
            if(!unlink(loc1 . $loc)){
              if($echo) echo '<font color="red">A file named "'.$name.'" already exists in destination directory, and it cannot be deleted.</font>'; else array_unshift($GLOBALS['prevcmd'], 'A file named "'.$name.'" already exists'."\n".'in destination directory, and it cannot be deleted.');
              writelog('File in destination directory could not be deleted', 'move', $mv .' - '. $loc);
              return false;
            } else
              $cont = true;
          } else {
            if($echo) echo '<font color="red">A file named "'.$name.'" already exists in destination directory.</font>'; else array_unshift($GLOBALS['prevcmd'], 'A file named "'.$name.'" already exists in destination directory.');
            return false;
          }
        }
        if($cont){
          if(!rename(loc1 . $mv, loc1 . $loc)){
            if($echo) echo '<font color="red">File ('.$mv.') cannot be moved. May be a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$mv.') cannot be moved. May be a permissions problem.');
            writelog('<font color="red">File could not be moved (may be a permissions problem)</font>', 'move', $mv .' - '. $loc, 1);
            return false;
          } else {
            if($echo) echo '<font color="red">File deleted/moved successfully.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File deleted/moved successfully.');
            writelog('User moved a file', 'move', $mv .' - '. $loc);
            return true;
          }
        }
      } else {
        if($echo) echo '<font color="red">Destination is not a valid directory.</font>'; else array_unshift($GLOBALS['prevcmd'], 'Destination is not a valid directory.');
        writelog('File could not be moved, destination not valid', 'move', $mv .' - '. $loc, 3);
      }
    } else
      if($echo) echo '<font color="red">File not accessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File not accessible.');

  }

  return false;
} // end of move_recycle()



  // move a file
  // bool move( str 'path to file to move', str 'path of dir to move to' )
function move($mv, $loc){

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if(is_file(loc1 . $mv) && allowed($mv)){

    $name = get_name($mv);
    if(is_dir(loc1 . $loc)){
      if(!is_file(loc1 . $loc . $name)){
        if(!rename(loc1 . $mv, loc1 . $loc . $name)){
          if($echo) echo '<font color="red">File ('.$mv.') cannot be moved. May be a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$mv.') cannot be moved. May be a permissions problem.');
          writelog('<font color="red">File could not be moved (may be a permissions problem)</font>', 'move', $mv .' - '. $loc, 1);
          return false;
        } else {
          if($echo) echo '<font color="red">File moved successfully.</font>';
          writelog('User moved a file', 'move', $mv .' - '. $loc);
          return true;
        }
      } else
        if($echo) echo '<font color="red">A file named "'.$name.'" already exists in destination directory.</font>'; else array_unshift($GLOBALS['prevcmd'], 'A file named "'.$name.'" already exists in destination directory.');
    } else {
      if($echo) echo '<font color="red">Destination is not a valid directory.</font>'; else array_unshift($GLOBALS['prevcmd'], 'Destination is not a valid directory.');
      writelog('File could not be moved, destination not valid', 'move', $mv .' - '. $loc, 3);
    }
  } else
    if($echo) echo '<font color="red">File not accessible.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File not accessible.');

  return false;
} // end of move()



  // move a directory and all subdirectories and files (recursive)
  // void dirmv( str 'source directory', str 'destination directory' [, bool 'overwrite existing files' [, bool 'if the destination contains the dir name too' [, str 'location within the directory (for recurse)']] )
function dirmv($source, $dest, $overwrite = false, $inc_name = false, $funcloc = NULL){

  if(substr($dest, 0, strlen($source)) == $source)
    return false;

  if(is_null($funcloc)){
    if(!$inc_name)
      $dest .= '/' . strrev(substr(strrev($source), 0, strpos(strrev($source), '/')));
    else
      if(substr($dest, -1) != '/')
        $dest .= '/';
    $funcloc = '/';
  }

  if(!is_dir(loc1 . $dest . $funcloc))
    mkdir(loc1 . $dest . $funcloc); // make subdirectory before subdirectory is copied

  if(isset($GLOBALS['prevcmd']))
    $echo = false;
  else
    $echo = true;

  if($handle = opendir(loc1 . $source . $funcloc)){ // if the folder exploration is sucsessful, continue
    while(false !== ($file = readdir($handle))){ // as long as storing the next file to $file is successful, continue
      if($file != '.' && $file != '..'){
        $path  = $source . $funcloc . $file;
        $path2 = $dest . $funcloc . $file;

        if(is_file(loc1 . $path)){
          if(!is_file(loc1 . $path2)){
            if(!@rename(loc1 . $path, loc1 . $path2)){
              if($echo) echo '<font color="red">File ('.$path.') could not be moved/deleted, likely a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$path.') could not be moved, likely a permissions problem.');
              writelog('<font color="red">File could not be moved.</font>', 'dirmv', $path . ' - ' . $path2, 1);
            }
          } elseif($overwrite){
            if(!@unlink(loc1 . $path2)){
              if($echo) echo 'Unable to overwrite file ("'.$path2.'"), likely to be a permissions problem.'; else array_unshift($GLOBALS['prevcmd'], 'Unable to overwrite file ("'.$path2.'"), likely to be a permissions problem.');
              writelog('<font color="red">Unable to overwrite (delete) file.</font>', 'dirmv', $dest .'/'.$file, 1);
            } else {
              if(!@rename(loc1 . $path, loc1 . $path2)){
                if($echo) echo '<font color="red">File ('.$path.') could not be moved/deleted after overwriting, likely a permissions problem.</font>'; else array_unshift($GLOBALS['prevcmd'], 'File ('.$path.') could not be moved after overwriting, likely a permissions problem.');
                writelog('<font color="red">File could not be moved after overwritting.</font>', 'dirmv', $path . ' - ' . $path2, 1);
              }
            }
          }
        } elseif(is_dir(loc1 . $path)){
          dirmv($source, $dest, $overwrite, false, $funcloc . $file . '/'); //recurse!
          @rmdir(loc1 . $path);
        }
      }
    }
    closedir($handle);
  }
  return true;
} // end of dirmv()

?>
