#!/usr/bin/perl -wT

# F*EX CGI for document exchange
#
# Author: Ulli Horlacher <framstag@rus.uni-stuttgart.de>
#

BEGIN { ($ENV{PERLINIT}||'') =~ /(.+)/s and eval $1 }

use strict qw(vars subs);

use File::Basename;
use Digest::MD5	qw(md5_hex);
use Cwd		qw(abs_path getcwd);
use POSIX	qw(strftime locale_h);
use Fcntl 	qw(:flock :seek :mode);

# POSIX time format needed for HTTP header
setlocale(LC_TIME,'POSIX');

# add fex lib
(our $FEXLIB) = $ENV{FEXLIB} =~ /(.+)/;
die "$0: no $FEXLIB\n" unless -d $FEXLIB;

our $error = 'F*EX document ERROR';

# import from fex.pp and fex.ph
our ($spooldir,$docdir,$tmpdir,$akeydir,$akey,$charset,$binarymode);
our ($admin,$hostname,$sender_from,$sendmail,$bcc,@remote_domains,@durl);
our ($vp,$mrx,$bs,$timeout,$mdomain,$document_exchange,$xpixel);
our ($userlog);
our ($convert,$pdftoppm,$jpgreduce,$imgtype);
our ($FEXHOME,$MB,$RA);
our (@extra_header,@download_hosts);

# load common code, local config : $HOME/lib/fex.ph
require "$FEXLIB/fex.pp" or die "$0: cannot load $FEXLIB/fex.pp - $!\n";

our $head = "$ENV{SERVER_NAME} F*EX DOcument eXchange";

our $SYSTEMLOG;

&redirect_stderr;

my $log = 'dox.log';
my $QS = $ENV{QUERY_STRING} || '';
my $uri = $ENV{PATH_INFO} || '';
my $http_client = $ENV{HTTP_USER_AGENT} || '';
my $referer = $ENV{HTTP_REFERER} || '';
my $owner = '';
my $user = 'anonymous';
my $file = '';
my $hfile = '';
my $folder = '';
my $http_auth = '';
my $realm = '';
my $submit = '';
my $action = '';
my $mirror = '';
my $directory = '';
my $parentdir = '';
my $uploaddir = '';
my $newdir = '';
my $newfolder = '';
my $newpreview = '';
my $destination = '';
my $allowpublish = '';
my $userupload = '';
my $filedata = '';
my $description = '';
my $pkey = '';
my $utypes = 'gif|jpg|png|avi|mp\d|flv|m4v|ogg|tar|tgz|zip|7z|gz|bz2|rar|iso';
my $back = '<a href="javascript:history.back()">back</a>';
my $scroll = '<script>window.scrollTo(0,document.body.scrollHeight);</script>';
my $delete = '<font color="red">delete</font>';
my $deleteall = '<font color="red">DELETE</font>';
my $stdn = 'style="text-decoration:none"';
my $al = 'align="left"';
my $ar = 'align="right"';
my $sp = ' &nbsp; ';
my @files = ();
my @images = ();
my @renamefrom = ();
my @renameto = ();
my %exclude = ();
my %PARAM = ();
my $DOX = $ENV{SCRIPT_NAME};
my $hosturl = "$ENV{PROTO}://$hostname";
my ($gallery_test,$move_from,$move_to);

$stdn = ''; # not necessary any more;

$ENV{PATH} = $ENV{FEXHOME}.'/bin:'.$ENV{PATH};

$xpixel ||= 1600;

# $QS =~ s/%([\dA-F]{2})/unpack("a",pack("H2",$1))/ge;
$QS = decode_utf8(urldecode($QS));

if (@download_hosts and not ipin($RA,@download_hosts)) {
  http_die(
    "Downloads from your host ($RA) are not allowed.",
    "Contact $ENV{SERVER_ADMIN} for details."
  );
}

if (($ENV{HTTP_AUTHORIZATION}||'') =~ /Basic\s+(\S+)/) {
  $http_auth = decode_b64($1);
}

$uri =~ s:%3F:/?/:g; # escape '?' for URL-decoding
$uri =~ s/%([\dA-F]{2})/unpack("a",pack("H2",$1))/ge;
$uri =~ s:/\?/:%3F:g; # deescape '?'
$uri =~ s://+:/:;
$uri =~ s:^/::;
$uri =~ s:/\.\./:/__/:g;

$akey = $ENV{AKEY}||'';

&check_maint;

# look for CGI parameters
&parse_request;

if ($uri =~ m:(.+?)/pkey=(\w+)/(.+):) {
  $owner = $1;
  $pkey = $2;
  $file = $3;
  $folder = $file;
  $folder =~ s:/.*::;
} elsif ($uri =~ m:(.+?)/(.+):) {
  $owner = $1;
  $file = $2;
  $folder = $file;
  $folder =~ s:/.*::;
} else {
  $owner = $uri;
}

$owner =~ s:/::g;
$owner =~ s:^\.+::;
$file  =~ s:^/+::;
$file  =~ s:/+$::;
$folder = normalize_folder($folder);

if ("/$file/" =~ m:/\.\./:) { http_die('illegal file name') }

$hfile = htmlencode($file);

$akey = '' unless -f "$akeydir/$akey/@";
if ($akey and readlink_("$akeydir/$akey") =~ m:.*/(.+):) {
  my $a = $1;
  if ($owner) {
    if ($a ne $owner) {
      $akey = '';
      # redirect("/$DOX");
    }
  } else {
    $owner = $a;
  }
} else {
  $akey = '';
}

my $doxo = "$DOX/$owner";
my $doxurl = "$hosturl/$doxo/";

unless ($owner) {
  redirect("/fup?forward=/$DOX");
}

unless (-f "$owner/@") {
  http_die("unknown user $owner");
}

# user client ip allowed?
if (length($folder) and not $akey) {
  my $access = "$owner/DOX/$folder/.fexdox/access";
  if (-s $access and open $access,$access) {
    my $noaccess = 1;
    while (<$access>) {
      /^#/ and next;
      s/\s//g;
      if (ipin($RA,$_)) {
        $noaccess = 0;
        last;
      }
    }
    close $access;
    if ($noaccess) {
      errorlog("access denied to $owner/DOX/$folder");
      http_error(403);
    }
  }
}

if ($pkey) {
  chdir "$owner/DOX" or http_die("$owner : no documents available");
  my $pkf = $file;
  $pkf =~ s:/:/.pkeys/:;
  if ((readline1($pkf)||'') eq $pkey and -f $file) {
    http_output($file);
  } else {
    http_die(htmlencode($file).' is not available');
  }
  exit;
}

# zip archive can be downloaded without authentication
if ($file =~ /^[^\/]+\.zip$/) {
  chdir "$owner/DOX" or http_die("$owner : no documents available");
  if (-s $file) {
    http_output($file) and unlink $file;
  } else {
    http_die("$owner : ".htmlencode($file)." not available");
  }
  exit;
}

my $useraccess = '';

if (length($folder) and
    (not $akey or readlink_("$akeydir/$akey") !~ m:\Q/$owner\E$:))
{
  if ((slurp("$owner/DOX/$folder/.fexdox/users")||'') =~ /^[^\s#]+:\S/m) {
    $useraccess = 'yes';
  }
  if (open my $fdc,"$owner/DOX/$folder/.fexdox/config") {
    while (<$fdc>) {
      s/#.*//;
      $useraccess = lc $1 if /^\s*useraccess\s*=\s*(\w+)/;
    }
    close $fdc;
  } elsif ($folder eq 'public') {
    $useraccess = 'anonymous';
  }
  if ($useraccess ne 'yes' and $useraccess ne 'anonymous') {
    http_header('200 OK');
    print html_header($head);
    pq(qq(
      '<h3>Access to folder /$folder is restricted to'
      '<a href="/fup?from=$owner?forward=/$doxo">$owner</a></h3>'
    ));
    exit;
  }
}

&check_auth;

if (-f "$owner/\@ALLOWED_RECIPIENTS") {
  http_die("$owner is a restricted user and cannot use document exchange");
}

if ($akey) {
  my $doxua = lc readlink_("$owner/\@DOCUMENT_EXCHANGE");
  if ($doxua eq 'yes' or not $doxua and $document_exchange) {
    my $pg = "$owner/DOX/public/gallery";
    mkdirp($pg) unless -d $pg;
  }
}

chdir "$owner/DOX" or http_die("DOX not available for $owner");
mkdir "$owner/.log";

if ($file) {
  if (not -d $file and -d "$file!backup") {
    $file = "$file!backup";
  } elsif ("/$file/" =~ m:\Q/$folder/UPLOAD/:) {
    if ($akey) {
      $file =~ s:/UPLOAD.*:/.upload:;
      redirect("/$doxo/$file/");
    } elsif (-d "$folder/.upload/$user") {
      $file =~ s:\Q$folder\E/UPLOAD:$folder/.upload/$user:;
      $userupload = $file;
      mkdirp($userupload);
    }
  }
  mkdir $file if $file =~ m:^\Q$folder/.upload\E$:;

  # force binary download? # not in use any more!
  $binarymode = ($file =~ s/!$//);

  if (not -e $file) {
    $file =~ s:(_$vp)/:$1!backup/:;
    unless (-e $file or $QS =~ /ACTION=edit/) {
      $file =~ s:!backup::;
      http_die("$owner : /".htmlencode($file)." does not exist");
    }
  }
}

if (length($folder)) {
  mkfexdox($folder);
  foreach ('.*','#*','*~') {
    $exclude{$_} = shp2prx($_);
  }
  if (open my $fdx,"$folder/.fexdox/private") {
    while (<$fdx>) {
      next if /^#/;
      s/[\r\n]//g;
      s://+:/:;
      s:^/\Q$folder:/:;
      s:/$::;
      $exclude{$_} = shp2prx($_) if length;
    }
    close $fdx;
  }
  if (open my $fdc,"$folder/.fexdox/config") {
    while (<$fdc>) {
      s/#.*//;
      $charset = $1 if /^\s*charset\s*=\s*(\S+)/;
    }
    close $fdc;
  }
}

if (-d $file and not $akey) {
  my $dir = $file;
  $dir =~ s:.+/::;
  if (excluded($dir)) {
    errorlog("access denied to $owner/DOX/$file");
    http_error(403);
  }
}

$gallery_test = $file =~ m:/gallery/test$:;
if ($gallery_test and not ($akey or $QS or $ENV{REQUEST_METHOD} eq 'POST')) {
  my $uri = $ENV{REQUEST_URI};
  $uri =~ s:/+$::;
  redirect("$uri?ACTION=preview");
  &reexec;
}

if ($action =~ /^(preview|pview|gallery)(:\d+)?$/) {
  userdoxlog('GALLERY',$file);
  $akey = '' if $action eq 'pview';
  gallery($file);
  exit;
}

if ($action eq 'okey' and -d $file) {
  okey($file);
  exit;
}

# if ($action and $referer !~ m:/dox/:) { http_error(403) }

if ($action eq 'listit' and -d $file) {
  userdoxlog('LIST',$file);
  list($file);
  exit;
}

# not in use any more
if ($action eq 'userlist' and -d $file) {
  userdoxlog('LIST',$file);
  userlist($file);
  exit;
}

if ($action eq 'zipit' and -d $file) {
  userdoxlog('ZIP',$file);
  zipdir($file);
  exit;
}

if ($action eq 'syncit' and -d $file) {
  userdoxlog('SYNC',$file);
  syncdir($file);
  exit;
}

if ($action eq 'streamit' and -d $file) {
  userdoxlog('STREAM',$file);
  streamdir($file);
  exit;
}

if ($action =~ /^browseit:?(\d+)?$/ and -d $file) {
  userdoxlog('BROWSE',$file);
  browsedir($file,$1||1);
  exit;
}

if ($action =~ /^browseitfull:?(\d+)?$/ and -d $file) {
  userdoxlog('BROWSE',$file);
  browsedirfull($file,$1||1);
  exit;
}

if ($action eq 'fexit' and -d $file) {
  userdoxlog('FEX',$file);
  fexdir($file,$user);
  exit;
}

if ($submit eq 'fex it' and -d $file and @files) {
  fexfiles(@files,$user);
  exit;
}

if ($submit eq 'zip it' and -d $file and @files) {
  zipfiles(@files);
  exit;
}

if ($akey or $gallery_test) {

  if (-d $file and $newpreview) {
    gallery($file);
    exit;
  }
  
  if ($action =~ /^editit:?(\d+)?$/ and -d $file) {
    edit_description($file,$1||1);
    userdoxlog('EDIT',$file);
    exit;
  }


  if ($action =~ /^moveup:(\d+)$/ and -d $file) {
    userdoxlog('MOVE',$file);
    moveup($file,$1);
    exit;
  }

  if ($action =~ /^movedown:(\d+)$/ and -d $file) {
    userdoxlog('MOVE',$file);
    movedown($file,$1);
    exit;
  }

  if ($move_from and $move_to and -d $file) {
    userdoxlog('MOVE',$file);
    movefromto($file);
    exit;
  }

  if ($action =~ /^(del|rleft|rright):(\d+)$/ and -d $file) {
    my $mod = $1;
    if (my $i = $2) {
      my $dir = $file;
      my $file = mod_img($mod,$dir,$i);
      userdoxlog(uc($mod),"$dir/$file");
      my $uri = $ENV{REQUEST_URI};
      if ($referer =~ /ACTION=preview/) {
        $uri =~ s/ACTION=.*/ACTION=preview:$i/;
      } else {
        $uri =~ s/ACTION=.*/ACTION=browseit:$i/;
      }
      redirect($uri);
      &reexec;
    } else {
      http_die("illegal number 0");
    }
  }

  if ($description) {
    save_description($uri);
    exit;
  }

  if ($action eq 'paselect' and -d $file) {
    # http_die('function not yet implemented');
    paselect($file);
    exit;
  }

  if ($action eq 'pucreate') {
    unless (-f $file) {
      http_die(htmlencode($file).' does not exist');
    }
    # http_die("function not yet implemented [$file]");
    pucreate($file);
    exit;
  }

  if ($action eq 'pulist') {
    pulist();
    exit;
  }

  if ($action eq 'puremove') {
    unless (-f $file) {
      http_die(htmlencode($file).' does not exist');
    }
    # http_die("function not yet implemented [$file]");
    puremove($file);
    exit;
  }

  if ($submit eq 'delete' and -d $file and @files) {
    delfiles(@files);
    doxdu($owner,$folder);
    my $dir = $file;
    unless ($akey) {
      $dir =~ s:\Q/.upload/$user:/UPLOAD:;
    }
    # $dir = urlencode($dir);
    redirect("$doxurl$dir/");
  }

  if ($submit eq 'publish' and @files) {
    publish(@files);
    my $dir = $file;
    $dir =~ s:/\.upload/[^/]+::;
    redirect("$doxurl$dir/");
  }

  if ($submit eq 'copy' and -d $file and -d $destination and @files) {
    copyfiles(@files);
    redirect("$doxurl$destination/");
  }

  if ($submit eq 'move' and -d $file and -d $destination and @files) {
    movefiles(@files);
    redirect($doxurl.urlencode($file).'/');
  }

  if ($submit eq 'rename' and -d $file and @files) {
    queryrename(@files);
    exit;
  }

  if (@renamefrom and @renameto) {
    renamefiles(@files);
    redirect($doxurl.urlencode($file).'/');
  }

  if ($submit eq 'save') {
    $filedata .= "\n" if length($filedata) and $filedata !~ /\n$/;
    savefile($file);
    my $url = $doxurl.urlencode(dirname($file)).'/';
    if ($url =~ m:/$DOX/\S+/public/gallery/:) {
      redirect("$url?ACTION=preview");
    } else {
      redirect($url);
    }
  }

  if (-d $file and $user and $action eq 'sendfile') {
    sendfile($file,$filedata);
    &reexec;
  }

  if ($user and $action eq 'notify') {
    notify_owner();
    exit;
  }

  if ($mirror) {
    mirror();
    exit;
  }

  if ($allowpublish) {
    redirect("/$DOX") unless $akey;
    my $user = $allowpublish;
    my $dir = "$folder/.upload/$user";
    unless (-d $dir) {
      http_die("$dir does not exist");
    }
    my $publish = "$folder/.upload/$user!publish";
    open $publish,'>',$publish or http_die("$publish - $!");
    print {$publish} "# User $user can publish his uploads (move to /$folder/)\n";
    close $publish;
    redirect("/$doxo/$folder/.upload/");
  }

  if ($QS =~ /ACTION=edit/) {
    edit($file);
    exit;
  }

  if ($QS =~ /ACTION=logview/) {
    logview($file);
    exit;
  }

  if ($file =~ /\.zip$/i) {
    if ($QS =~ /ACTION=extract/) {
      extract($file);
      exit;
    }
    if ($QS =~ /ACTION=ziplist/) {
      ziplist($file);
      exit;
    }
  }

  if ($file and $QS eq 'ACTION=publishall') {
    publish_all($file);
    redirect("/$doxo/$folder/");
    exit;
  }

}

if ($parentdir and $newdir) {
  if ($akey) {
    my $dir = "$parentdir/$newdir";
    mkdir $dir or http_die("cannot mkdir $dir - $!");
    update_folder($1) if $dir =~ m:([^/]+):;
    redirect("/$doxo/$parentdir/");
  } else {
    if ($parentdir !~ m:^\Q$folder/.upload/$user:) {
      http_die("illegal parentdir $parentdir");
    }
    my $dir = "$parentdir/$newdir";
    mkdir $dir or http_die("cannot mkdir $dir - $!");
    $dir = $parentdir;
    $dir =~ s:\Q/.upload/$user:/UPLOAD:;
    redirect("/$doxo/$dir/");
  }
}

if ($submit and $uploaddir) {
  redirect("/$DOX") unless $akey;
  my $dir = "$folder/.upload/$uploaddir";
  mkdirp($dir);
  redirect("/$doxo/$folder/.upload/");
}

if ($newfolder) {
  redirect("/$DOX") unless $akey;
  if (-d $newfolder) {
    http_die("$newfolder does already exist");
  }
  my @d = localtime time;
  my $nv = sprintf(
    '%s_%d%02d%02d_%02d%02d%02d',
    $newfolder,$d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]
  );
  mkdir $nv or http_die("cannot mkdir $nv - $!");
  symlink $nv,$newfolder or http_die("cannot symlink $nv - $!");
  redirect("/$DOX");
}

if ($QS =~ /ACTION=logout/) {
  unlink "$akeydir/$akey" if $akey;
  redirect("/$DOX");
}

if ($file and $QS eq 'ACTION=backup') {
  redirect("/$DOX") unless $akey;
  $folder = normalize_folder(basename($file));
  if (-d $folder and my $ov = untaint(readlink_($folder))) {
    my @d = localtime time;
    my $nv = sprintf(
      '%s_%d%02d%02d_%02d%02d%02d',
      $folder,$d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]
    );
# fex@tandem:~/spool/hahahannes@flupp.org/DOX: find Singlesia_20240317_093109 | wc -l
#   67225
#   
# fex@tandem:~/spool/hahahannes@flupp.org/DOX: time cp -al Singlesia_20240317_093109 Singlesia_20240317_093109.tmp
# real    0m36.362s
#   
# fex@tandem:~/spool/hahahannes@flupp.org/DOX: du3 -s Singlesia_20240317_093109*
#       96,673,824 Singlesia_20240317_093109
#           19,260 Singlesia_20240317_093109.tmp
    my $backup = "$ov!backup";
    if (-d $backup and lmtime($folder) > lmtime($backup)) {
      rmrf($backup);
    }
    unless (-d $backup) {
      $_ = `cp -al $ov $backup 2>&1`;
      http_die($_) if $?;
    }
    backup_cleanup($folder);
    redirect("/$DOX");
  } else {
    http_die("unknown folder /$folder");
  }
} elsif ($file and $QS eq 'ACTION=restore') {
  redirect("/$DOX") unless $akey;
  $file =~ s:/::;
  if (-d $file and $file =~ /(.+)_$vp(!backup)?$/ and -l $1) {
    $folder = normalize_folder($1);
    if ($file =~ s/!backup$//) {
    } else {
      $_ = `cp -al $file $file!backup 2>&1`;
      http_die($_) if $?;
    }
    unlink $folder;
    symlink $file,$folder;
    backup_cleanup($folder);
    redirect("/$DOX");
  } else {
    http_die("unknown backup /$file");
  }
} elsif ($file and $QS eq 'ACTION=delete') {
  redirect("/$DOX") unless $akey;
  if ($file !~ m:/:) {
    if (-l $file) {
      # delete all versions, backup and stream
      if (my @v = grep /^\Q$file\E_$vp(!\S+)?$/,glob "${file}_*") {
        foreach my $v (@v) {
          rmrf(untaint($v));
        }
      }
    } elsif (-d $file and $file =~ /(.+)_$vp$/) {
      $folder = normalize_folder($1);
      if (-l $folder and my @v = grep /^\Q$folder\E_$vp$/,glob "${folder}_*") {
        if (scalar(@v) == 1) {
          unlink $folder;
        } elsif (readlink_($folder) eq $file) {
          unlink $folder;
          if ($v[-1] ne $file) {
            symlink untaint($v[-1]),$folder;
          } else {
            symlink untaint($v[-2]),$folder;
          }
        }
      }
    }
  }
  rmrf($file);
  doxdu($owner,$folder);
  redirect("/$DOX/".dirname($uri));
} elsif ($file =~ m:([^/]+): and -d $1) { # folder exists?
  if ($akey and $file eq "$folder/.fexdox" and not -d $file) {
    mkfexdox($folder);
  }
  if (-d $file) {
    if ($uri !~ m:/$:) {
      if ($QS) {
        redirect("/$DOX/$uri/?$QS");
      } else {
        redirect("/$DOX/$uri/");
      }
    } else {
      if (not $akey and $file =~ m:/gallery/:) {
        gallery($file);
      } else {
        showindex($file);
      }
    }
  } elsif (-f $file) {
    sleep(1);
    http_output($file);
  } else {
    http_die("$owner : ".htmlencode($file)." is not available");
  }
} elsif ($akey) {
  showindex('/');
} else {
  http_die("$owner : ".htmlencode($file)." is not available");
}

&reexec;
exit;

sub check_auth {
  my $id = readline1("$spooldir/$owner/@")||'';
  my ($users);
  my (%pw,%access);

  if ($akey) {
    if (-f "$akeydir/$akey/@") {
      $user = $owner;
      return;
    } else {
      $akey = '';
    }
  }

  if ($http_auth =~ /^(fexmaster.*):/) {
    my $fm = $1;
    $fm .= '@'.$mdomain if $mdomain and $fm !~ /@/;
    $id = readline1("$spooldir/$fm/@")||'';
    if ($http_auth =~ /:$id$/) {
      $akey = 'fexmaster';
      if ($folder) {
        $realm = "/$owner/$folder";
      } else {
        $realm = "/$owner";
      }
      return;
    }
  }

  if ($folder) {
    $realm = "/$owner/$folder";
  } else {
    if ($QS =~ /^realm=([^\s\'\"]+)/) {
      http_header(
        '401 Authorization Required',
        "WWW-Authenticate: Basic realm=\"$1\"",
        'Content-Length: 0',
      );
      &reexec;
    } else {
      redirect("/fup?from=$owner?forward=/$doxo");
    }
  }

  # does not work any more with encrypted auth-ID
  if ($http_auth eq "$owner:$id") {
    $user = $owner;
    return;
  }

  return if $useraccess eq 'anonymous';

  if (open $users,"$spooldir/$owner/DOX/$folder/.fexdox/users") {
    while (<$users>) {
      /^#/ and next;
      s/\s//g;
      my ($user,$pw) = split ':';
      $pw{lc($user)} = $pw if $pw;
    }
    close $users;
  }

  if ($http_auth =~ /(.+):(.+)/) {
    my $u = lc $1;
    my $p = $2;
    if ($pw{$u} and $pw{$u} eq $p) {
      $user = $u;
      return;
    }
  }

  http_header(
    '401 Authorization Required',
    "WWW-Authenticate: Basic realm=\"$realm\"",
    'Content-Length: 0',
  );
  &reexec;
}


sub http_output {
  my $file = shift;
  my ($filename,$size,$total_size,$range,$log);
  my ($data,$type);
  my ($var,$env,$con);
  my @files;
  my @s;
  my $s = 0;
  my $b = 0;
  my $seek = 0;
  my $stop = 0;
  local $_;

  if (-l $file or not -f $file or $file =~ m:/\.: and not $akey) {
    http_error(404);
  }

  # reget?
  if ($range = $ENV{HTTP_RANGE}) {
    $seek = $1 if $range =~ /^bytes=(\d+)-/i;
    $stop = $1 if $range =~ /^bytes=\d*-(\d+)/i;
  }

  if (not $akey and excluded($file)) {
    http_die("no access for /".htmlencode($file));
  }

  if ($file =~ m:^/: or "/$file/" =~ m:\Q/../:) {
    http_die("illegal file name ".htmlencode($file));
  }

  open $file,'<',$file or http_error(400);

  userdoxlog('ACCESS',$file);

  if ($binarymode) {
    # not in use any more!
    $type = 'application/x-unknown';
    unshift @extra_header,"Content-Disposition: attachment; filename=".
                          basename($file);
  } else {
    $type = 'application/octet-stream';
    my $fn = $file;
    $fn =~ s/#\d+$//;
    if    ($fn =~ /\.html?$/i)	{ $type = 'text/html' }
    elsif ($fn =~ /\.css$/)	{ $type = 'text/css' }
    elsif ($fn =~ /\.js$/)	{ $type = 'text/javascript' }
    elsif ($fn =~ /\.txt$/i)	{ $type = 'text/plain' }
    elsif ($fn =~ /\.ps$/i)	{ $type = 'application/postscript' }
    elsif ($fn =~ /\.pdf$/i)	{ $type = 'application/pdf' }
    elsif ($fn =~ /\.mp3$/i)	{ $type = 'audio/mpeg' }
    elsif ($fn =~ /\.mp4$/i)	{ $type = 'video/mp4' }
    elsif ($fn =~ /\.avi$/i)	{ $type = 'video/x-msvideo' }
    elsif ($fn =~ /\.jpe?g$/i)	{ $type = 'image/jpeg' }
    elsif ($fn =~ /\.png$/i)	{ $type = 'image/png' }
    elsif ($fn =~ /\.tiff?$/i)	{ $type = 'image/tiff' }
    elsif ($fn =~ /\.gif$/i)	{ $type = 'image/gif' }
    elsif ($fn =~ /\.bmp$/i)	{ $type = 'image/bmp' }
    elsif ($fn =~ /\.ico$/i)	{ $type = 'image/vnd.microsoft.icon' }
    elsif ($fn !~ /\.(tar|tgz|zip|jar|rar|arj|7z|bz2?|gz)$/i) {
      my $qfile = shellquote(untaint($file));
      $_ = `file $qfile 2>/dev/null`;
      if (/:.*HTML/) {
        $type = 'text/html';
      } elsif (/:.*text/i and not -x $file) {
        $type = 'text/plain';
        if    (/\sASCII\s/)    { $type .= "; charset=us-ascii" }
        elsif (/(ISO-[\w-]+)/) { $type .= "; charset=".lc($1) }
        else                   { $type .= "; charset=utf-8" }
      }
    }

    if ($type eq 'text/html') {
      my $allowhtml = '';
      if (open my $fdc,"$folder/.fexdox/config") {
        while (<$fdc>) {
          s/#.*//;
          $allowhtml = $1 if /^\s*allowhtml\s*=\s*(y)/i;
        }
        close $fdc;
      }
      if (not $allowhtml and $file !~ m:/gallery/.+/\.?preview/index\.html$:) {
        $type = 'text/plain';
      }
    }
  }

  $total_size = -s $file || 0;
  $size = $total_size - $seek - ($stop ? $total_size-$stop-1 : 0);

  if ($size < 0) {
    http_header('416 Requested Range Not Satisfiable');
    exit;
  }

  alarm($timeout*10);

  if ($seek or $stop) {
    my $range;
    if ($stop) {
      $range = sprintf("bytes %s-%s/%s",$seek,$stop,$total_size);
    } else {
      $range = sprintf("bytes %s-%s/%s",$seek,$total_size-1,$total_size);
    }
    nvt_print(
      'HTTP/1.1 206 Partial Content',
      'Server: fexsrv',
      "Content-Length: $size",
      "Content-Range: $range",
      "Content-Type: $type",
    );
  } else {
    my $date = http_date($file);
    nvt_print(
      'HTTP/1.1 200 OK',
      'Server: fexsrv',
      "Last-Modified: $date",
      "Expires: 0",
      "Content-Length: $size",
      "Content-Type: $type",
    );
  }
  nvt_print($_) foreach(@extra_header);
  nvt_print('');

  # binary data # can be stream!
  seek $file,$seek,0 if $seek;
  while ($bs and $b = read($file,$data,$bs)) {
    if ($stop and $s+$b > $size) {
      $b = $size-$s;
      $data = substr($data,0,$b);
      $bs = 0;
    }
    $s += $b;
    alarm($timeout*10);
    print $data or last;
  }
  doxlog(sprintf "%s %s/%s",hexencode($file),$s,$size) if $s;

  alarm(0);
  close $file;
  return($s+$seek == $total_size);
}


# show directory index
sub showindex {
  my $dir = shift;
  my ($htmldoc,$size,$hdir,$path);
  my $pathhref = '';
  my @links = ();
  my @dirs = ();
  my %versions = ();
  my %folder = ();
  my @files = ();
  my @users = ();
  my $uid = randstring(8);
  my $js = slurp("$docdir/DOX/dox.js");
  my ($allowed,$showdel,$style,$v);
  local $_;

  $dir =~ s://+:/:;
  $dir =~ s:^/::;
  $dir =~ s:/$::;
  $dir ||= '.' if $akey;

  my $udir = urlencode($dir);

  $js =~ s/\$RANDOM\$/$uid/g;

  $htmldoc = html_header($head);
  $htmldoc .= qqq(qq(
    '<script>'
    'function toggle_checkboxes(cb) {'
    '  for (let checkbox of document.getElementsByName("file"))'
    '    checkbox.checked = cb.checked;'
    '}'
    '</script>'
  ));

  if ($akey and $dir eq '.') {

    # toplevel folders view

    mkdirp('public/gallery') unless -d 'public/gallery';

    if (-d 'public' and not -l 'public') {
      my @d = localtime(mtime('public'));
      my $nv = sprintf(
        'public_%d%02d%02d_%02d%02d%02d',
        $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]
      );
      rename 'public',$nv or http_die("cannot create $nv - $!");
      symlink $nv,'public' or http_die("cannot symlink $nv - $!");
    }

    opendir $dir,$dir or http_die("$dir - $!");
    while (defined($_ = readdir $dir)) {
      next if /^[.#]/;
      if ($v = readlink and $v =~ /$vp$/) {
        $folder{$v} = $_;
      }
      if (-d and /((.+_$vp)_backup)$/ and not -d $2) {
        # superfluous backup - bug?!
        rmrf($1);
        next;
      }
      if (-d and /((.+_$vp)!backup)$/ and not -d $2) {
        rename $1,$2 and s/!backup$//;
      }
      if (-d and /(.+)_($vp(!backup)?)$/) {
        push @{$versions{$1}},$2;
      }
    }
    closedir $dir;

    $style = qqq(qq(
      'table {'
      '  border-collapse: collapse;'
      '}'
      'th,td {'
      '  border: 1px solid black;'
      '  padding: 10px;'
      '}'
    ));
    $htmldoc .= qq'<script>\n$js</script>\n';
    $htmldoc .= '<h2>';
    if ($akey eq 'fexmaster') {
      $htmldoc .= "DOX of $owner ($akey access)\n";
    } else {
      $htmldoc .= "DOX of $owner\n";
    }
    $htmldoc .= '</h2>';
    my $logout = button("/$DOX?ACTION=logout",'logout');
    $htmldoc .= qqq(qq(
      '<style>'
      '$style'
      '</style>'
      '$logout'
      '&nbsp;'
      '[<a href="/DOX/index.html">documentation</a>]'
      '<p>'
      '<table border="1">'
      '<tr><th>folder<th>size<th>last modification<th>backup versions<th>folder actions</tr>'
    ));
    foreach my $d (asort(keys %versions)) {
      my $kb = readlink(".$d.du")||0;
      my ($mb,$date);
      $mb = int($kb/1024) || '<1';
      $showdel = 'a';
      if (open my $fdc,"$d/.fexdox/config") {
        while (<$fdc>) {
          s/#.*//;
          $showdel = ''  if /^\s*showdelete\s*=\s*no/;
          $showdel = 'a' if /^\s*showdelete\s*=\s*all/;
          $showdel = 'b' if /^\s*showdelete\s*=\s*backup/;
        }
        close $fdc;
      }
      $date = isodate(lmtime($d));
      $htmldoc .= qq'<tr><td><a href="/$doxo/$d/"><b>/$d</b></a>';
      $htmldoc .= qq'<td align="right">$mb MB<td>$date<td>';
      @{$versions{$d}} = sort @{$versions{$d}};
      foreach (reverse @{$versions{$d}}) {
        my $vd = my $v = $_; local $_;
        my $dv = $d.'_'.$v;
        $vd = "$1-$2-$3 $4:$5:$6" if $v =~ /(\d\d\d\d)(\d\d)(\d\d)_(\d\d)(\d\d)(\d\d)/;
        next if $folder{$dv};
        if ($v =~ s/!backup//g) {
          next if readlink_($d) !~ /$v$/;
          my $href = "javascript:alert('folder $d version is already $v')";
          my $sv = $d.'_'.$v;
          $htmldoc .= qq'<a href="/$doxo/$sv/"><code>$v</code></a> '.
                      button($href,'restore');
        } else {
          my $sv = $d.'_'.$v;
          $htmldoc .= qq'<a href="/$doxo/$sv/"><code>$v</code></a> '.
                      button("/$doxo/$dv?ACTION=restore",'restore');
        }
        if ($showdel =~ /^[ab]/) {
          $htmldoc .= ' '.button("/$doxo/$dv?ACTION=delete",$delete);
        }
        $htmldoc .= '<br>';
      }
      $htmldoc .= qq'<td>';
      my $bmt = mtime(readlink_($d).'!backup');
      if ($bmt and $bmt == lmtime($d)) {
        my $href = "javascript:alert('backup of folder $d is up to date')";
        $htmldoc .= button($href,'backup');
      } else {
        $htmldoc .= button("/$doxo/$d?ACTION=backup",'backup');
      }
      if ($showdel eq 'a') {
        $htmldoc .= ' ' . button("/$doxo/$d?ACTION=delete",$deleteall);
      }
      $htmldoc .= "</tr>\n";
    }
    $htmldoc .= "</table>\n<p>\n";
    $htmldoc .= qqq(qq(
      '<p>'
      '<ul>'
      '<li><form name="newfolder"'
      '  action="/$DOX"'
      '  method="POST"'
      '  accept-charset="$charset"'
      '  enctype="multipart/form-data">'
      '  <input type="submit" value="Create">'
      '  new (empty) folder <input type="text" name="newfolder" size="40" value="NEWFOLDER">'
      '</form>'
      '<p><hr><p>'
      '<li><form name="upload"'
      '  action="/fup"'
      '  method="POST"'
      '  accept-charset="$charset"'
      '  enctype="multipart/form-data"'
      '  onsubmit="return showstatus()">'
      '  <input type="hidden" name="from"       value="$owner">'
      '  <input type="hidden" name="to"         value=".">'
      '  <input type="hidden" name="uid"        value="$uid">'
      '  <input type="hidden" name="comment"    value="DOX:SAVE=/">'
      '  <input type="hidden" name="keep"       value="1">'
      '  <input type="hidden" name="autodelete" value="YES">'
      '  <input type="hidden" name="filesize"   value="">'
      '  <a id="uploadselect">'
      '    Select a'
      '    <button onclick="showfileupload(\'.zip\')">local zip file for upload</button>'
#      '    or select a'
#      '    <button onclick="showdirectoryupload()">local directory for upload</button>'
      '    to create a new folder with content.'
      '  </a>'
      '  <a id="submit"></a>'
      '</form>'
      '</ul>'
    ));

  } elsif ($akey and $dir eq "$folder/.upload") {

    $htmldoc .= "<h2>";
    $htmldoc .= qq'<a href="/$doxo/">DOX of $owner</a> ';
    $htmldoc .= $akey eq 'fexmaster' ?
                "($akey access)":
                "(logged in as owner)";
    $htmldoc .= "</h2>\n";

    opendir $dir,$dir or http_die("$dir - $!");
    while (defined($_ = readdir $dir)) {
      next if /^\.\.?$/;
      next if /\n/;
      next if /^.pkeys$/;
      next if -l "$dir/$_";
      if (lstat "$dir/$_") {
        if (-d _) {
          push @dirs,$_;
        } elsif (-f _) {
          push @files,$_;
          push @images,$_ if -s _ and /\.($imgtype)(#\d+)?$/i;
        }
      }
    }
    closedir $dir;


    my $action = "/$doxo/".urlencode($dir)."?ACTION";
    my $pathhref = qq'<a href="/$doxo/$folder/">$folder</a>/.upload';

    if (@dirs or @files) {
      $htmldoc .=       button("$action=listit",'list it');
      $htmldoc .= $sp . button("$action=zipit",'zip it');
      $htmldoc .= $sp . button("$action=fexit",'fex it');
      $htmldoc .= $sp . button("$action=syncit",'sync it') if $akey;
      $htmldoc .= $sp . button("$action=streamit",'stream it');
      $htmldoc .= $sp . button("$action=browseit",'browse it') if $#images>1;
    }
    $htmldoc .= $sp . button("/$doxo/$file",'reload');
#   $htmldoc .= $sp . button("/$doxo$realm",'folders overview');
    $htmldoc .= $sp . button("/$DOX?ACTION=logout",'logout');
    $htmldoc .= $sp;
    $htmldoc .= qq'[<a href="/DOX/index.html">documentation</a>]\n';
    $htmldoc .= qqq(qq(
      '<h2><tt><a href="/$doxo/">/DOX</a>/$pathhref/</tt></h2>'
      '<p><hr><p>'
    ));

    $htmldoc .= "<ul><li>";
    $htmldoc .= button("/$doxo/$folder/.fexdox/users?ACTION=edit",
                       'Add or edit');
    $htmldoc .= " users</ul>";


    my @users = ();
    if (open my $users,"$folder/.fexdox/users") {
      while (<$users>) {
        s/#.*//;
        s/\s//g;
        push @users,$1 if /^([^\/]+?@[\w.-]+):./;
      }
      close $users;
    }
    my $selection = '<select name="uploaddir" size="1">';
    foreach (@users) {
      unless (-d "$folder/.upload/$_") {
        $selection .= '<option>'.htmlquote($_).'</option>';
      }
    }
    $selection .= "</select>";
    if ($selection =~ /<option>/) {
      $htmldoc .= qqq(qq(
        '<p>'
        '<ul><li><form name="newuploaddir"'
        '  action="/$doxo/$file"'
        '  method="POST"'
        '  accept-charset="$charset"'
        '  enctype="multipart/form-data">'
        '  <input type="submit" name="submit" value="Create">'
        '  an upload directory for user $selection'
        '</form></ul>'
      ));
    }

    # first the user upload directories
    if (@dirs) {
      $htmldoc .= qqq(qq(
        '<h3>Upload directories of your users</h3>'
        '<form name="files"'
        '  action="/$doxo/$file"'
        '  method="POST"'
        '  accept-charset="$charset"'
        '  enctype="multipart/form-data">'
        '<pre>'
      ));
      my $format = "%9s files # <b><a href=\"%s\"><em>%s/</em></a></b>\n";
      foreach my $d (asort(@dirs)) {
        my $ud = urlencode($d);
        my $hd = htmlencode($d);
        $htmldoc .= qq'<input type="checkbox" name="file" value="$ud"> ';
        $htmldoc .= sprintf $format,d3(countfiles("$dir/$d")),$ud,$hd;
      }
      $htmldoc .= qqq(qq(
        '</pre>'
        '&nbsp; &#8627; Action for selected directories:'
        '<input type="submit" name="submit" value="delete">'
        '</form>'
      ));
    }

    # then the files
    if (my $n = scalar(@files)) {
      $htmldoc .= qqq(qq(
        '<h3>Files ($n)</h3>'
        '<form name="files"'
        '  action="/$doxo/$file"'
        '  method="POST"'
        '  accept-charset="$charset"'
        '  enctype="multipart/form-data">'
        '<pre>'
      ));
      my $format = "%s %20s bytes # <a href=\"%s\"><em>%s</em></a>\n";
      foreach my $f (asort(@files)) {
        next if $f eq 'log';
        my $uf = urlencode($f);
        my $hf = htmlencode($f);
        $htmldoc .= qq'<input type="checkbox" name="file" value="$uf"> ';
        $htmldoc .= sprintf $format,
                    isodate(mtime("$dir/$f")),d3(-s "$dir/$f"||0),$uf,$hf;
      }
      if (-f "$dir/log") {
        $htmldoc .= qq'\n<input type="checkbox"> ';
        $htmldoc .= sprintf $format,
                    isodate(mtime("$dir/log")),d3(-s "$dir/log"||0),
                    'log?ACTION=logview','log';
      }
      $htmldoc .= qqq(qq(
        '</pre>'
        '&nbsp; &#8627; Action for selected files:'
        '<input type="submit" name="submit" value="delete">'
        '</form>'
      ));

      my $selection = '<select name="allowpublish" size="1">';
      foreach (@dirs) {
        if (/^$mrx$/ and not -f ("$dir/$_!publish")) {
          $selection .= '<option>'.htmlquote($_).'</option>';
        }
      }
      $selection .= "</select>";
      if ($selection =~ /<option>/) {
        $htmldoc .= qqq(qq(
          '<p>'
          '<ul><li><form name="allowpublish"'
          '  action="/$doxo/$folder"'
          '  method="POST"'
          '  accept-charset="$charset"'
          '  enctype="multipart/form-data">'
          '  <input type="submit" value="Allow">'
          '  user $selection to publish uploads'
          '  (move to <code>/$folder/</code>)'
          '</form></ul>'
        ));
      }
    }

    my $url = $ENV{REQUEST_URL};
    $url =~ s:/\.upload.*::;
    $htmldoc .= qqq(qq(
      '<p><hr><p>'
      'URL for your users:<br>'
      '$url/'
    ));

  } else {

    if (not $akey and $file !~ /^\Q$userupload/ and excluded($dir)) {
      http_die("no access for /$dir");
    }

    opendir $dir,$dir or http_die("$dir - $!");
    while (defined($_ = readdir $dir)) {
      next if /^\.\.?$/;
      next if /\n/;
      next if -l "$dir/$_";
      next if /^.pkeys$/;
      next if not ($akey or $dir =~ m:/\.upload($|/):) and excluded("$dir/$_");
      if (lstat "$dir/$_") {
        if (-d _) {
          push @dirs,$_;
        } elsif (-f _) {
          push @files,$_;
          push @images,$_ if -s _ and /\.($imgtype)(#\d+)?$/i;
        }
      }
    }
    closedir $dir;

    if ($akey and $dir !~ m:/: and not grep /^\.fexdox$/,@dirs) {
      push @dirs,'.fexdox';
    }

    $showdel = 'a';
    if ($akey and open my $fdc,"$folder/.fexdox/config") {
      while (<$fdc>) {
        s/#.*//;
        $showdel = ''  if /^\s*showdelete\s*=\s*no/;
        $showdel = 'a' if /^\s*showdelete\s*=\s*all/;
        $showdel = 'b' if /^\s*showdelete\s*=\s*backup/;
        $showdel = 'd' if /^\s*showdelete\s*=\s*dir/;
      }
      close $fdc;
    }

#    $htmldoc .= "<h1>[$ENV{PATH_INFO}]</h1>\n";
    $path = urldecode($ENV{PATH_INFO});
#    $htmldoc .= "<h1>[$path]</h1>\n";
    $path =~ s:/.+?/::; # remove owner
    $path =~ s:!backup/:/:;
    $pathhref = htmlencode(basename($path));

    while ($path =~ s:(.+)/.+:$1:) {
      my $dir = htmlencode(basename($path));
      my $upath = urlencode($path);
      $pathhref = qq'<a href="/$doxo/$upath/">$dir</a>/$pathhref';
    }

    $realm = "?realm=$realm" if $realm;

    $htmldoc .= "<h2>";
    if ($akey) {
      $htmldoc .= qq'<a href="/$doxo$realm">DOX of $owner</a> ';
      $htmldoc .= $akey eq 'fexmaster' ? "($akey access)" : "(logged in as owner)";
    } else {
      $htmldoc .= "DOX of $owner (user: $user)";
    }
    $htmldoc .= "</h2>\n";

    if ($userupload) {
      my $okey = randstring(8);
      my $okeyd = "$spooldir/$owner/\@OKEY";
      mkdir $okeyd;
      symlink $user,"$okeyd/$okey"
        or http_die("cannot create OKEY $okeyd/$okey - $!");

      if (countfiles("$folder/.upload/$user")) {
        $htmldoc .= "<script>\n$js</script>\n";
        my $action = "/$doxo/".urlencode($file)."?ACTION";
        $htmldoc .= button("$action=notify",'notify owner');
        if (-f "$folder/.upload/$user!publish" and
            $file =~ m:(\Q$folder/.upload/\E[^/]+)$:)
        {
          $htmldoc .= $sp;
          $htmldoc .= button("$action=publishall",'publish all');
        }
        $htmldoc .= $sp;
        $htmldoc .= qq'[<a href="/DOX/user.html">documentation</a>]\n'
      }
      $htmldoc .= qqq(qq(
        '<h2><tt>/$pathhref/</tt></h2>'
        '<p><hr><p>'
        '<form name="files"'
        '  action="/$doxo/$file"'
        '  method="POST"'
        '  accept-charset="$charset"'
        '  enctype="multipart/form-data">'
        '<pre>'
      ));

      # first the (sub)directories
      foreach my $d (asort(@dirs)) {
        my $ud = urlencode($d);
        my $hd = htmlquote($d);
        $htmldoc .= qq'<input type="checkbox" name="file" value="$ud"> ';
        $htmldoc .= sprintf qq'%9s files <b><a href="%s/">%s/</a></b>\n',
                    d3(countfiles("$dir/$d")),$ud,$hd;
      }
      $htmldoc .= "\n";

      # then the files
      foreach my $f (asort(@files)) {
        $htmldoc .= sprintf '<input type="checkbox" name="file" value="%s"> ',
                    urlencode($f);
        $htmldoc .= sprintf "%s %20s bytes %s\n",
                    isodate(mtime("$dir/$f")),d3(-s "$dir/$f"||0),
                    htmlencode($f);
      }

      $htmldoc .= "</pre>\n";
      if (@dirs or @files) {
        $htmldoc .= qqq(qq(
          '<input type="checkbox" onClick="toggle_checkboxes(this)">'
          '(De)select all files and directories<br>'
          '&nbsp; &#8627; Action for selected files and directories:'
          '<input type="submit" name="submit" value="delete">'
        ));
      }
      $htmldoc .= qqq(qq(
        '</form>'
        '<p><hr><p>'
        '<ul><li><form name="upload"'
        '  action="/fup"'
        '  method="POST"'
        '  accept-charset="$charset"'
        '  enctype="multipart/form-data"'
        '  onsubmit="return showstatus()">'
        '  <input type="hidden" name="from"       value="$user">'
        '  <input type="hidden" name="to"         value="$owner">'
        '  <input type="hidden" name="uid"        value="$uid">'
        '  <input type="hidden" name="okey"       value="$okey">'
        '  <input type="hidden" name="comment"    value="DOX:SAVE=$udir">'
	'  <input type="hidden" name="keep"	  value="1">'
        '  <input type="hidden" name="autodelete" value="YES">'
        '  <input type="hidden" name="filesize"   value="">'
        '  <a id="uploadselect">'
        '    Select a'
        '    <button onclick="showfileupload()">local file for upload</button><br>'
#        '    or select a'
#        '    <button onclick="showdirectoryupload()">local directory for upload</button><br>'
        '    <br>(If you upload a file named <code>dox.zip</code> it will be extracted)'
        '  </a>'
        '  <a id="submit"></a>'
        '</form></ul>'
        '<p>'
        '<ul><li><form name="newdir"'
        '  action="/$doxo/$file"'
        '  method="POST"'
        '  accept-charset="$charset"'
        '  enctype="multipart/form-data">'
        '  <input type="hidden" name="parentdir" value="$udir">'
        '  <input type="submit" value="Create"> directory'
        '  <input type="text" name="newdir" size="40" value="NEWDIRECTORY">'
        '</form></ul>'
      ));

    } else {

      if ($akey) {
        # https://stackoverflow.com/questions/710089/how-do-i-make-an-html-link-look-like-a-button
        $htmldoc .= qqq(qq(
          '<style>'
          '  .button {'
          '    font: bold 11px Arial;'
          '    text-decoration: none;'
          '    background-color: #EEEEEE;'
          '    color: #333333;'
          '    padding: 2px 6px 2px 6px;'
          '    border: 1px solid black;'
          '  }'
          '</style>'
        ));
        $htmldoc .= "<script>\n$js</script>\n" if $folder !~ /_$vp$/;
      }

      $path = $ENV{PATH_INFO};
      $path =~ s:/+$::;
      my $action = "/$DOX$path?ACTION";
      if ($akey and $file =~ m:(\Q$folder/.upload/\E[^/]+)$:) {
        if (countfiles($1)) {
          $htmldoc .= button("$action=publishall",'pubish all');
          $htmldoc .= $sp;
        }
      }
      if (@dirs or @files) {
        $htmldoc .=       button("$action=listit",'list it');
        $htmldoc .= $sp . button("$action=zipit",'zip it');
        if ($user =~ /@/ and checkaddress($user) and "/$dir" !~ /\/\./) {
          $htmldoc .= $sp . button("$action=fexit",'fex it');
        }
        if ($akey or $dir eq $folder) {
          $htmldoc .= $sp . button("$action=syncit",'sync it');
        }
        $htmldoc .= $sp . button("$action=streamit",'stream it');
        if ("/$dir" !~ /\/\./) {
          $htmldoc .= $sp . button("$action=browseit",'browse it') if $#images>1;
          $htmldoc .= $sp . button("$action=preview",'gallery') if $convert;
        }
        $htmldoc .= $sp . button("/$doxo/$file",'reload');
      }
      if ($akey) {
#       $htmldoc .= $sp . button("/$doxo$realm",'folders overview');
        $htmldoc .= $sp . button("/$DOX?ACTION=logout",'logout');
        $htmldoc .= $sp;
        $htmldoc .= qq'[<a href="/DOX/index.html">documentation</a>]'
      } elsif ($user =~ /@/ and checkaddress($user)) {
        $htmldoc .= $sp;
        my $wopen = "window.open(this.href,'fup','width=1024,height=768');".
                    "return false;";
        $htmldoc .= qq'<a href="$action=sendfile" onclick="$wopen" $stdn>'.
                      '<button>send file</button></a>';
        if (-d "$folder/.upload/$user") {
          $htmldoc .= $sp;
          $htmldoc .= qq'<a href="/$doxo/$folder/UPLOAD">'.
                        '<button>upload</button></a>';
        }
        $htmldoc .= $sp;
        $htmldoc .= qq'[<a href="/DOX/user.html">documentation</a>]'
      } else {
        $htmldoc .= $sp;
        $htmldoc .= button("/fup?from=$owner?forward=/$doxo/$udir",'login');
        $htmldoc .= $sp;
        $htmldoc .= qq'[<a href="/DOX/user.html">documentation</a>]'
      }
      $htmldoc .= "\n";
      if ($akey) {
        $htmldoc .= qq'<h2><a href="/$doxo/">/DOX</a><tt>/$pathhref/</tt></h2>\n';
      } else {
        $htmldoc .= qq'<h2><tt>/$pathhref/</tt></h2>\n';
      }
      $htmldoc .= "<p><hr><p>\n";

      $path = urldecode($ENV{PATH_INFO});
      $path =~ s:/.+?/::; # remove owner
      $path =~ s:/+$::;
      # $htmldoc .= "<h2>$path</h2>\n";
      if ($_ = slurp("$path/.#.html")||slurp("$path/#.html")) {
        s:</body.*::si;
        s:</html.*::si;
        s:<(script):&lt;$1:g;
        $htmldoc .= $_."\n<p><hr><p>\n";
      }

      if (@files or @dirs) {
        if ($akey) {
          # $htmldoc .= "(see below for action on selected files or directories)\n";
        } elsif (@files) {
          # $htmldoc .= "(see below for action on selected files)\n";
        }
        $htmldoc .= qqq(qq(
          '<form name="files"'
          '  action="/$doxo/$file"'
          '  method="POST"'
          '  accept-charset="$charset"'
          '  enctype="multipart/form-data">'
        ));
      }

      # first the (sub)directories
      if (my $n = scalar(@dirs)) {
        $htmldoc .= "<h3>Directories ($n)</h3>\n";
        $htmldoc .= "<pre>\n";
        $htmldoc .= qq'<table border="0">\n';

        foreach my $d (asort(@dirs)) {
          $htmldoc .= "<tr><td>";
          if ($akey) {
            if ($dir eq $folder and ($d eq '.fexdox' or $d eq '.upload')) {
            } else {
              $htmldoc .= sprintf
                '<input type="checkbox" name="file" value="%s"> ',
                urlencode($d);
            }
            $htmldoc .= "<td>";
          }
          my $format = "&nbsp; <b><a href=\"%s/\">%s/</a></b>\n";
          if (excluded("$path/$d")) {
            $format = "# <b><a href=\"%s/\"><em>%s/</em></a></b>\n";
          }
          $htmldoc .= sprintf "<td $ar>%9s files<td>$format</tr>\n",
            d3(countfiles("$dir/$d")),
            urlencode($d),
            htmlencode($d);
        }
        $htmldoc .= "</table>\n";
        $htmldoc .= "</pre>\n";
      }

      # then the files
      if (my $n = scalar(@files)) {
        $htmldoc .= "<h3>Files ($n)</h3>\n";
      }
      $htmldoc .= "<pre>\n";
      foreach my $f (asort(@files)) {
        my ($format);
        if (excluded("$path/$f")) {
          $format = "# <a href=\"%s\"><em>%s</em></a>";
        } else {
          # $format = button('%s','*')." <a href=\"%s\">%s</a>\n";
          $format = "  <a href=\"%s\">%s</a>";
        }
        $format = "%s %20s bytes $format";
        my $action = '';
        if ($akey) {
          if ($path eq "$folder/.fexdox") {
            $action = "?ACTION=edit";
          } elsif ("$dir/$f" eq "$folder/.upload/log") {
            $action = "?ACTION=logview";
          }
        }
        my $uf = urlencode($f);
        my $hf = htmlencode($f);
        $htmldoc .= qq'<input type="checkbox" name="file" value="$uf"> ';
        $htmldoc .= sprintf $format,
          isodate(mtime("$dir/$f")),d3(-s "$dir/$f"||0),$uf.$action,$hf;
        if ($akey and $f =~ /\.zip$/i) {
          $htmldoc .=
#           qq' <a href="$uf?ACTION=ziplist"><button type="button">list</button></a>'.
            qq' <a class="button" href="$uf?ACTION=ziplist">list</a>'.
            qq' <a class="button" href="$uf?ACTION=extract">extract</a>';
        }
        $htmldoc .= "\n";
      }
      $htmldoc .= "</pre>\n";
      if (@files or @dirs and $akey) {
        if ($path ne "$folder/.upload") {
          my $x = $akey ? 'and directories' : '';
          $htmldoc .= qqq(qq(
            '<input type="checkbox" onClick="toggle_checkboxes(this)">'
            '(De)select all files $x<br>\n'
          ));
        }
        $htmldoc .= "&nbsp; &#8627; Action for selected files and directories:\n";
        if ($akey) {
          if ($path eq "$folder/.upload") {
            $htmldoc .= qq'<input type="submit" name="submit" value="delete">\n';
          } else {
            my (@folders,@dirs,$selection);
            @folders = grep { -d and -l and $_ ne $folder } glob '*';
            $selection = '<select name="destination" size="1">';
            $selection .= "<option>$_</option>" foreach asort(@folders);
            $selection .= "</select>";
            $htmldoc .=
              qq'<script>\n'.
              qq'function showcopy() {'.
              qq"  document.getElementById('actions').innerHTML = '".
              qq'  <input type="submit" name="submit" value="copy">'.
              qq"  to folder $selection'; ".
              qq"}\n".
              qq'</script>\n';
            foreach (find($folder)) {
              if (-d and not -l) {
                $_ .= '/';
                next if $_ eq "$file/";
                next if m:^\Q$folder/.\E(fexdox|upload)/|/\.versions/:;
                push @dirs,"/$_";
              }
            }
            $selection = '<select name="destination" size="1">'.
                         "<option>/$folder/</option>";
            foreach (asort(@dirs)) {
              local $_ = htmlquote($_);
              $selection .= "<option>$_</option>";
            }
            $selection .= "</select>";
            $htmldoc .=
              qq'<script>\n'.
              qq'function showmove() {'.
              qq"  document.getElementById('actions').innerHTML = '".
              qq'  <input type="submit" name="submit" value="move">'.
              qq"  to directory $selection'; ".
              qq"}\n".
              qq'</script>\n';
            $htmldoc .= qq'<a id="actions">\n';
            $htmldoc .= qq'<input type="submit" name="submit" value="zip it">\n';
            if ("/$dir" !~ /\/\./) {
              $htmldoc .= qq'<input type="submit" name="submit" value="fex it">\n';
            }
            if (@folders) {
              $htmldoc .= qq'<button onclick="showcopy()">copy</button>\n';
            }
            if ($folder !~ /_$vp$/) {
              if (@dirs) {
                $htmldoc .= qq'<button onclick="showmove()">move</button>\n';
              }
              if ("$path/" =~ m:^\Q$folder/.upload/:) {
                $htmldoc .= qq'<input type="submit" name="submit" value="publish">\n';
              }
              if ("$path/" !~ m:^\Q$folder/.fexdox/:) {
                $htmldoc .= qq'<input type="submit" name="submit" value="rename">\n';
              }
              $htmldoc .= qq'<input type="submit" name="submit" value="delete">\n';
           }
            $htmldoc .= "</a>\n";
          }
        } else {
          $htmldoc .= qq'<input type="submit" name="submit" value="zip it">\n';
          if ($user =~ /@/ and checkaddress($user)) {
            $htmldoc .= qq'<input type="submit" name="submit" value="fex it">\n';
          }
        }
      }
      $htmldoc .= "</form>\n" if @files or @dirs;
      if ($akey and $folder !~ /_$vp$/) {
        $htmldoc .= "<p><hr><p>\n";

        if ("$path/" !~ m:^\Q$folder/.fexdox/:) {
          $htmldoc .= qqq(qq(
            '<ul><li><form name="newdir"'
            '  action="/$DOX"'
            '  method="POST"'
            '  accept-charset="$charset"'
            '  enctype="multipart/form-data">'
            '  <input type="hidden" name="parentdir" value="$udir">'
            '  <input type="submit" value="Create"> directory'
            '  <input type="text" name="newdir" size="40" value="NEWDIRECTORY">'
            '</form></ul>'
            '<p>'
          ));
        }

        $htmldoc .= "<ul>\n";
        if ("$path/" !~ m:^\Q$folder/.upload/:) {
          $htmldoc .= qqq(qq(
            '<li><form name="upload"'
            '  action="/fup"'
            '  method="POST"'
            '  accept-charset="$charset"'
            '  enctype="multipart/form-data"'
            '  onsubmit="return showstatus()">'
            '  <input type="hidden" name="from"       value="$owner">'
            '  <input type="hidden" name="to"         value=".">'
            '  <input type="hidden" name="uid"        value="$uid">'
            '  <input type="hidden" name="comment"    value="DOX:SAVE=$udir">'
            '  <input type="hidden" name="keep"	      value="1">'
            '  <input type="hidden" name="autodelete" value="YES">'
            '  <input type="hidden" name="filesize"   value="">'
            '  <a id="uploadselect">'
            '    Select a'
            '    <button onclick="showfileupload()">local file for upload</button><br>'
          ));
          if ("$path/" !~ m:^\Q$folder/.fexdox/:) {
## bug with mupfile() in fup
#            $htmldoc .= qqq(qq(
#              '    or select a'
#              '    <button onclick="showdirectoryupload()">local directory for upload</button><br>'
#            ));
          }
          if ("$path/" =~ m:^public/gallery/:) {
            $htmldoc .= '(If you upload a zip file it will be extracted)'
          } else {
#            $htmldoc .= '(If you upload a file named <code>dox.zip</code> it will be extracted)'
          }
          $htmldoc .= qqq(qq(
            '  </a>'
            '  <a id="submit"></a>'
            '</form>'
          ));
          if ("$path/" !~ m:^\Q$folder/.fexdox/:) {
            $htmldoc .= qqq(qq(
              '<li><form name="mirror"'
              '  action="/$doxo/$dir"'
              '  method="POST"'
              '  accept-charset="$charset"'
              '  enctype="multipart/form-data">'
              '  <input type="submit" value="Mirror"> this URL:'
              '  <input type="text" name="mirror" size="80">'
              '  </form>'
            ));
          }
        }
        if ($path eq $folder or $path eq "$folder/.fexdox") {
          my @users = ();
          if (open my $users,"$folder/.fexdox/users") {
            while (<$users>) {
              /^#/ and next;
              s/\s//g;
              push @users,$1 if /^([^\/]+?@[\w.-]+):./;
            }
            close $users;
          }
          if (@users) {
            $htmldoc .=
              "<li>Manage your ".
              button("/$doxo/$folder/.upload",'user upload directories').
              "\n";
          }
        }
#        if (slurp("$folder/.fexdox/config") !~ /^\s*useraccess=anonymous\b/m) {
        if (@files and $path !~ /\/\./ and $folder ne 'public') {
          $htmldoc .=
            '<p><li>(De)select files for '.
            button("/$doxo/$dir?ACTION=paselect",'public access').
            "\n";
        }
        $htmldoc .= "</ul>\n";
        if ("/$path" !~ /\/\./) {
          $htmldoc .= qqq(qq(
            '<p><hr><p>'
            'URL of this page (for your users):<br>'
          ));
          foreach (@durl) {
            local $_ = $_;
            s:/fop.*:$ENV{REQUEST_URI}<br>\n:;
            if ($ENV{PROTO} eq 'https' and /^https/ or $ENV{PROTO} eq 'http') {
              $htmldoc .= $_;
            }
          }
        }
      }
    }
  }
  
  if ($folder and $dir eq "$folder/.fexdox") {
    my $url = $ENV{REQUEST_URL};
    $url =~ s:/\.fexdox.*::;
    $htmldoc .= qqq(qq(
      '<p><hr><p>'
      'URL for your users:<br>'
      '$url/'
    ));
  }

  $htmldoc .= "</body>\n</html>\n";

  $size = length($htmldoc);
#  $size = length(encode_utf8($htmldoc));
  $hdir = hexencode($dir).'/';
  doxlog($hdir.' '.$size);
  userdoxlog('ACCESS',$hdir);

  http_header(
    '200 OK',
    "Content-Length: $size",
  );
  if ($charset =~ /utf/i) {
    # binmode(STDOUT,':raw');
    print $htmldoc;
  } else {
    # binmode(STDOUT,':raw');
    print $htmldoc;
  }
}


sub countfiles {
  my $dir = shift;
  my $n = 0;
  local $_;

#  return 0;

  $dir = shellquote(untaint($dir));
  `find $dir -type f 2>/dev/null|wc -l` =~ /(\d+)/;
  return $1||0;

  # way too slow for MANY files!
  opendir $dir,$dir or return $n;
  while (defined($_ = readdir $dir)) {
    next if /^\.\.?$/;
    $_ = "$dir/$_";
    lstat;
    next if -l _;
    if (-d _) {
      $n += countfiles($_);
    } elsif (-f _) {
      $n++;
    }
  }
  closedir $dir;
  return $n;
}


sub edit {
  my $file = shift;
  my $ufile = urlencode($file);
  my $path = dirname($file);
  my $text = '';
  my ($htmldoc);
  local $/;

  if (open $file,$file) { # or http_die(htmlencode($file)." - $!\n");
    $text = <$file>;
    $text =~ s/\r//g;
    $text =~ s/&/&amp;/g;
    $text =~ s/</&lt;/g;
    $text =~ s/\n*$/\n/;
  } else {
    open $file,'>',$file or http_die(htmlencode($file)." - $!\n");
  }
  close $file;

  $htmldoc = html_header($head);
  $htmldoc .= qqq(qq(
    '<h2>DOX of $owner</h2>'
    '<h3>edit /$file :</h3>'
    '<form name="edit"'
    '  action="/$doxo/$ufile"'
    '  method="POST"'
    '  accept-charset="$charset"'
    '  enctype="multipart/form-data">'
    '  <textarea name="filedata" cols="80" rows="25">'
  ));
  $htmldoc .= $text;
  $htmldoc .= qqq(qq(
    '</textarea><br>'
    '<input type="submit" name="submit" value="save">'
    '</form>'
  ));
  $htmldoc .= button('javascript:history.back()','cancel');

  my $size = length(encode_utf8($htmldoc));
  http_header('200 OK',"Content-Length: $size");
  print $htmldoc;
  exit;
}


sub extract {
  my $file = shift;
  my $zip = shellquote(basename($file));
  my $path = dirname($file);
  my $qpath = htmlencode($path);
  my $qfile = htmlencode($file);
  local $_;

  chdir $path or http_die("$path - $!\n");
  $_ = `unzip -l $zip 2>&1`;
  if (m:/\.\./|\:\d\d\:\d\d\s+/:) { http_die("bad zip") } # hacked path
  open $zip,"unzip -o $zip 2>&1|" or http_die("cannot run unzip - $!");
  http_header('200 OK','Connection: close');
  print html_header($head);
  pq(qq(
    '<h3>extracting /$qfile:</h3>'
    '<pre>'
  ));
  while (<$zip>) {
    next if /^Archive:/;
    chomp;
    s/^\s*\w+://;
    print $scroll,htmlencode($_),"\n";
  }
  close $zip;
  pq(qq(
    '</pre>'
    '<p>'
    '<a href="/$doxo/$path">back to /$qpath</a>'
    '</body></html>'
  ));
#    '<script>window.location.href = "/$doxo/$path"</script>'
  exit;
}


sub ziplist {
  my $zip = shellquote(shift);
  local $_;

  open $zip,"unzip -l $zip 2>&1|" or http_die("cannot run unzip - $!");
  http_header('200 OK','Connection: close');
  print html_header($head);
  print "<pre>\n";
  while (<$zip>) {
    chomp;
#    s/^\s*\w+://;
    print htmlencode($_),"\n";
  }
  close $zip;
  pq(qq(
    '</pre>'
    '<p>'
    '$back'
    '</body></html>'
  ));
  exit;
}


sub logview {
  my $file = shift;
  my $path = dirname($file);
  my $text = '';
  my @log = ();
  my $htmldoc;
  local $/ = "\n\n";
  local $_;

  open $file,$file or http_die(htmlencode($file)." - $!\n");
  @log = <$file>;
  close $file;

  $htmldoc = html_header($head);
  $htmldoc .= "<h2>$file</h2>\n";
  $htmldoc .= "<pre>\n";

  while (defined($_ = pop @log)) {
    s/^\n*//;
    s/\n*$/\n\n/;
    $htmldoc .= htmlquote($_);
  }

  $htmldoc .= qqq(qq(
    '</pre>'
    '$back'
    '</body></html>'
  ));

  my $size = length($htmldoc);
  http_header('200 OK',"Content-Length: $size");
  # binmode(STDOUT,':raw');
  print $htmldoc;
  exit;
}


sub userdoxlog {
  my $access = shift;
  my $doc = shift;
  my $log = "$spooldir/$owner/.log/dox";
  if ($userlog and open $log,">>",$log) {
    printf {$log} "%s %s %s %s \"%s\"\n",
      isodate(time),$RA,$access,$doc,$http_client;
    close $log;
  }
}


sub button {
  my $href = shift;
  my $button = shift;
# return qq'<a href="$href" $stdn><button>$button</button></a>';
  return qq'<a href="$href"><button>$button</button></a>';
}


sub mkfexdox {
  my $folder = normalize_folder(shift);
  my $fexdox = "$folder/.fexdox";
  my ($config,$info);

  unlink($fexdox) unless -d $fexdox;
  mkdirp($fexdox);
  mkdir "$folder/.upload";

  $info = "$fexdox/#.html";
  if (not -f $info and open $info,'>',$info) {
    my $href = qq'<a href="/DOX/#Folders_and_configuration">help</a>';
    print {$info} "<h3>Folder configuration, see $href</h3>\r\n";
    close $info;
  }

  $config = "$fexdox/config";
  unless (-f $config) {
    open $config,'>',$config or http_die("cannot write $config - $!");
    print {$config}
      "# Lines beginning with # are comments.\r\n".
      "\r\n".
      "# access for other users\r\n".
      "#useraccess=no\r\n".
      ($folder eq 'public' ?
        "useraccess=anonymous\r\n" :
        "useraccess=yes\r\n#useraccess=anonymous\r\n").
      "\r\n".
      "# number of backups fexdox automatically creates and keeps\r\n".
      "backups=1\r\n".
      "\r\n".
      "# send HTML files with Content-Type text/html to web browser\r\n".
      "allowhtml=no\r\n".
      "\r\n".
      "# file name character set\r\n".
      "charset=utf-8\r\n".
      "\r\n".
      "# show delete button or not\r\n".
      "#showdelete=no\r\n".
      "#showdelete=backup\r\n".
      "showdelete=all\r\n".
      "";
    close $config;
  }

  $config = "$fexdox/users";
  unless (-f $config) {
    open $config,'>',$config or http_die("cannot write $config - $!");
    print {$config}
      "# Lines beginning with # are comments.\r\n",
      "#\r\n",
      "# User accounts are USER:PASSWORD strings.\r\n",
      "# If the user shall be enabled to upload files, it must be an email address.\r\n",
      "# Example:\r\n",
      "# framstag\@rus.uni-stuttgart.de:letthereberock\r\n",
      "";
    close $config;
  }

  $config = "$fexdox/access";
  unless (-f $config) {
    open $config,'>',$config or http_die("cannot write $config - $!");
    print {$config}
      "# Lines beginning with # are comments.\r\n",
      "#\r\n",
      "# Access is restricted to ips or ip ranges listed here.\r\n",
      "127.0.0.1\r\n",
      "0.0.0.0-255.255.255.255\r\n",
      "0:0:0:0:0:0:0:0-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\r\n",
      "";
    close $config;
  }

  $config = "$fexdox/private";
  unless (-f $config) {
    open $config,'>',$config or http_die("cannot write $config - $!");
    print {$config}
      "# Lines beginning with # are comments.\r\n",
      "#\r\n",
      "# List of private files and directories to be invisible for users.\r\n",
      "# Files and directories with . or # as first character are private by default.\r\n",
      "# You can use the shell patterns * ? [...]\r\n",
      "# Examples:\r\n",
      "#\r\n",
      "# internal.pdf\r\n",
      "# *.tmp\r\n",
      "# /software/test/alpha\r\n",
      "";
    close $config;
  }
}


sub list {
  my $dir = shift;
  my @files = ();
  my $htmldoc = html_header($head);
  local $_;

  foreach (find($dir)) {
    next if -l or not -f;
    next if m:/.pkeys/:;
    next if not $akey and excluded($_);
    push @files,$_;
  }

  $htmldoc .= qqq(qq(
    '<html>'
    '<body>'
    '<h1>/$dir/</h1>'
    '<pre>'
  ));

  foreach (asort(@files)) {
    if (m:\Q$dir\E/(.+)/(.+):) {
      my $hd = htmlencode($1);
      my $ud = urlencode("/$doxo/$dir/$1");
      my $hf = htmlencode($2);
      my $uf = urlencode("/$doxo/$dir/$1/$2");
      $htmldoc .= sprintf
        qq'%s %20s bytes <a href="%s">%s</a>/<a href="%s">%s</a>\n',
        isodate(mtime($_)),d3(-s||0),$ud,$hd,$uf,$hf;
    } elsif (m:\Q$dir\E/(.+):) {
      my $hf = htmlencode($1);
      my $uf = urlencode("/$doxo/$dir/$1");
      $htmldoc .= sprintf
        qq'%s %20s bytes <a href="%s">%s</a>\n',
        isodate(mtime($_)),d3(-s||0),$uf,$hf;
    }
  }

  $htmldoc .= qqq(qq(
    '<p>'
    '$back'
    '</body>'
    '</html>'
  ));

  my $size = length($htmldoc);
  doxlog(hexencode($dir).'/ '.$size);

  http_header(
    '200 OK',
    "Content-Length: $size",
  );
  # binmode(STDOUT,':raw');
  print $htmldoc;
}


# not in use any more
sub userlist {
  my $dir = shift;
  my %files = ();
  local $_;

  unless (-d "$dir/.upload/$user") {
    http_error(403);
  }

  foreach (find($dir)) {
    next if -l or not -f;
    next if m:/[.#]|~$:;
    next if excluded($_);
    $files{$1} = $_ if m:\Q$dir/\E(.+):;
  }

  foreach (find("$dir/.upload/$user")) {
    next if -l or not -f;
    $files{$1} = $_ if m:\Q$dir/.upload/$user/\E(.+):;
  }

  http_header(
    '200 OK',
    "Content-Type: text/plain",
  );

  # print "$dir/.upload/$user\n";
  foreach (asort(keys %files)) {
    printf "%d %s\n",mtime($files{$_}),hexencode($_);
  }
}


sub zipdir {
  my $dir = shift;
  my $zip = $dir;
  my @zip = qw'zip -r';
  my $uf = my $cf = 1;
  my @exclude = ();

  $zip =~ s:[^\w\@%~^,+-]:_:g;
  $zip .= sprintf "_%s.zip",time;

  foreach (find($dir)) {
    unless ($akey) {
      if (-l or excluded($_)) {
        $_ .= '/*' if -d and not -l;
        push @exclude,$_;
        next;
      }
    }
    next if -l or not -f;
    if (/\.($utypes)$/i) {
      $cf += -s;
    } else {
      $uf += -s;
    }
  }

  if ($uf+$cf > 2**30 or $uf/$cf < 0.2 and $uf+$cf > 2**24) {
    push @zip,'-0';
  }

  http_header('200 OK');

  pq(qq(
    '<html>'
    '<body>'
    '<pre>'
  ));
  push @zip,$zip,$dir;
  push @zip,'-x',@exclude if not $akey and @exclude;
  doxlog("[@zip]");
  if ($akey) {
    print htmlquote("\$ @zip\n");
  }
  unlink $zip;
  if (open my $zip,'-|',@zip) {
    while (<$zip>) {
      # print $scroll,htmlencode(decode_utf8($_));
      print $scroll,htmlencode($_);
    }
    close $zip;
  }
  print "</pre>\n";
  if (my $s = -s $zip) {
    $s = int($s/$MB);
    print qq'Download <a href="/$doxo/$zip">$zip</a> ($s MB)\n';
  }
  pq(qq(
    '<p>'
    '$back'
    '$scroll'
    '</body>'
    '</html>'
  ));

}


sub zipfiles {
  my @files = @_;
  my $dir = $file;
  my $zip = basename($dir);
  my @zip = qw'zip';
  my $uf = my $cf = 1;
  local $_;

  $zip =~ s:[^\w\@%~^,+-]:_:g;
  $zip .= sprintf "_%s.zip",time;

  map { $_="$dir/$_" } @files;

  unless ($akey) {
    foreach my $file (@files) {
      if (excluded($file)) { http_die("no access for ".htmlencode($file)) }
      if (-d $file)        { http_die("cannot fex ".htmlencode($file)."/") }
    }
  }

  foreach (@files) {
    if (my $size = -s) {
      if (/\.($utypes)$/i) {
        $cf += $size;
      } else {
        $uf += $size;
      }
    }
  }

  if ($uf+$cf > 2**30 or $uf/$cf < 0.2 and $uf+$cf > 2**24) {
    push @zip,'-0';
  }

  http_header('200 OK');

  pq(qq(
    '<html>'
    '<body>'
    '<pre>'
  ));
  if ($akey) { push @zip,'-r' }
  else       { push @zip,'-j' }
  push @zip,$zip,@files;
  doxlog("[@zip]");
  if ($akey) {
    print htmlquote("\$ @zip\n");
  }
  unlink $zip;
  if (open $zip,'-|',@zip) {
    while (<$zip>) {
      print $scroll,htmlencode($_);
    }
    close $zip;
  }
  print "</pre>\n";
  if (my $s = -s $zip) {
    $s = int($s/$MB);
    pq(qq(
      'Download <a href="/$doxo/$zip">$zip</a> ($s MB)'
      '$scroll\n'
    ));
  }
  pq(qq(
    '<p>'
    '$back'
    '</body>'
    '</html>'
  ));
}


sub fexdir {
  my $dir = shift;
  my $qdir = shellquote($dir);
  my $recipient = shift;
  my $fexsend = qq'fexsend -q -C "DOX $owner : $qdir"';
  local $ENV{FEXHOME} = '';
  local $ENV{FEXSERVER} = '';

  unless ($recipient =~ /@/ and checkaddress($recipient)) {
    http_die("$recipient is not a valid email address");
  }

  nvt_print(
    'HTTP/1.1 200 OK',
    'Server: fexsrv',
    "Content-Type: text/html; charset=$charset",
    '',
  );

  pq(qq(
    '<html>'
    '<body>'
    '<pre>'
  ));
  if ($akey) {
    # $fexsend .= " -A $dir.zip $dir/* $dir/.??*";
    $fexsend .= " -a $qdir.zip $qdir";
  } else {
    my $X = '.\*';
    foreach my $x (asort(keys %exclude)) {
      $x =~ s/([?*])/\\$1/g;
      $x =~ s/([^\w\/.-])/\\$1/g;
      $X .= "#$x";
    }
    $fexsend .= " -# $X -a $qdir.zip $qdir/*";
  }
  $fexsend .= ' '.shellquote($recipient);
  doxlog("[$fexsend]");
  print "\$ $fexsend\n";
  if (open $fexsend,"$fexsend 2>&1|") {
    while (<$fexsend>) {
      print $scroll,htmlencode($_);
    }
    close $fexsend;
  }
  pq(qq(
    '</pre>'
    '$back'
    '$scroll'
    '</body>'
    '</html>'
  ));
}


sub fexfiles {
  my $recipient = pop;
  my @files = @_;
  my $dir = $file;
  my $zip = shellquote(basename($dir)).'.zip';
  my $fexsend;
  local $ENV{FEXHOME} = '';
  local $ENV{FEXSERVER} = '';

  if ($recipient =~ /@/ and checkaddress($recipient)) {
    http_header('200 OK');
  } else {
    http_die("$recipient is not a valid email address");
  }

  chdir $dir or http_die("$dir - $!");

  unless ($akey) {
    foreach my $file (@files) {
      if (excluded("$dir/$file")) { http_die("no access for ".htmlencode($file)) }
      if (-d $file)               { http_die("cannot fex ".htmlencode($file)."/") }
    }
  }

  pq(qq(
    '<html>'
    '<body>'
    '<pre>'
  ));
  map { s/[\'\\]/_/g } @files;
  $fexsend = "fexsend -q -C 'DOX $owner : @files' ";
  $fexsend .= $akey ? '-A' : '-a';
  $fexsend .= " $zip @files ".shellquote($recipient);
  doxlog("[$fexsend]");
  print "\$ $fexsend\n";
  if (open $fexsend,"$fexsend 2>&1|") {
    while (<$fexsend>) {
      print $scroll,htmlencode($_);
    }
    close $fexsend;
  }
  pq(qq(
    '</pre>'
    '$back'
    '$scroll'
    '</body>'
    '</html>'
  ));
}


sub delfiles {
  my @files = @_;
  my $dir = $file;
  local $_;

  unless ($akey or "$file/" =~ m:^\Q$folder/.upload/$user/:) {
    http_die("no permission");
  }

  chdir $dir or http_die("$dir - $!");

  foreach my $file (@files) {
    if ($file =~ /\//) {
      http_die("illegal file name");
    }
    unless (-f $file or -d $file) {
      http_die("no such file or directory ".htmlencode("$dir/$file"));
    }
  }

  foreach my $file (@files) {
    if (-f $file) {
      unlink($file);
      unlink(".preview/browse/$file");
      unlink(".preview/gallery/$file");
    } elsif (-d $file) {
      unlink("$file!publish") if $dir =~ m:/\.upload$: and $file =~ /@/;
      rmrf($file);
    }
  }

  chdir "$spooldir/$owner/DOX" or die $!;
  update_folder($folder) if $file !~ m:^\Q$folder/.upload/:
}


sub movefiles {
  my @files = @_;
  my $dir = $file;

  unless ($akey) { http_die("no permission") }

  unless (-d $destination) {
    http_die("destination /$destination is not a directory")
  }

  map { $_="$dir/$_" } @files;

  my $errors = move(@files,$destination);
  update_folder($folder);
  if ($errors) {
    $errors = htmlquote($errors);
    http_header('200 OK');
    print html_header($head);
    pq(qq(
      '<h1>move error</h1>'
      '$errors'
      '</body>'
      '</html>'
    ));
    &reexec;
  }
}


sub copyfiles {
  my @files = @_;
  my $dir = $file;

  unless ($akey) { http_die("no permission") }

  foreach my $file (@files) {
    unless (-f "$dir/$file" or -d "$dir/$file") {
      http_die("no such file or directory ".htmlencode("$dir/$file"));
    }
  }

  if ($folder =~ /^\Q$destination\E_$vp$/) {
    # use same source directory if coming from same folder other version
    $destination = $dir;
    $destination =~ s/_$vp//;
    mkdirp($destination);
  } else {
    # add source folder name if coming from foreigner folder
    $destination .= "/$folder";
    $destination =~ s/!backup$//;
    unless (-d $destination) {
      mkdir $destination or http_die("cannot mkdir $destination - $!");
    }
  }

  foreach my $file (@files) {
    rmrf("$destination/$file");
    if (-f "$dir/$file") {
      link "$dir/$file","$destination/$file";
    } else {
      system qw'cp -al',"$dir/$file","$destination/$file";
    }
  }
  update_folder($1) if $destination =~ m:([^/]+):;
}


sub savefile {
  my $file = shift;

  unless ($akey) {
    http_die("no permission")
  }

  if ($file =~ m:^/: or "/$file/" =~ m:\Q/../:) {
    http_die("illegal file name ".htmlencode($file));
  }

  unless (-f $file) {
    http_die("/".htmlencode($file)." does not exist");
  }

  my $qfile = shellquote($file);
  system "$FEXHOME/bin/vv -s $qfile 2>/dev/null";
  open $file,'>',$file or http_die("cannot write ".htmlencode($file)." - $!");
  print {$file} $filedata;
  close $file;
}


sub queryrename {
  my @files = @_;
  my $dir = urlencode($file);
  unless ($akey) { http_die("no permission") }

  http_header('200 OK');
  print html_header($head);
  pq(qq(
    '<h1>/$dir/</h1>'
    '<form name="rename"'
    '  action="/$doxo/$dir"'
    '  method="POST"'
    '  accept-charset="$charset"'
    '  enctype="multipart/form-data">'
    '<table border="0">'
    '<tr><th align="left">old name<th>&rarr;<th align="left">new name</tr>'
  ));

  foreach my $file (@files) {
    print "<tr>";
    printf '<td>%s<input type="hidden" name="renamefrom" value="%s">',
           htmlencode($file),htmlquote($file);
    print "<td>&rarr;";
    printf '<td><input type="text" name="renameto" value="%s" size="60">',
           htmlquote($file);
    print "</tr>\n";
  }

  pq(qq(
    '</table>'
    '<input type="submit">'
    '</form>'
    '</body>'
    '</html>'
  ));
  exit;
}


sub renamefiles {
  my @files = @_;
  my $dir = decode_utf8($file);
  my $i = 0;

  unless ($akey) { http_die("no permission") }

  if (scalar(@renamefrom) != scalar(@renameto)) {
    http_die("rename: different parameter numbers")
  }

  chdir $dir or http_die("$dir - $1");

#  http_header('200 OK');
#  print html_header($head);
#  printf "<h1>/%s/</h1><pre>\n",htmlquote($dir);
#  foreach my $old (@renamefrom) {
#    printf "[%s] &rarr; [%s]\n",htmlquote($old),htmlquote($renameto[$i]);
#    $i++;
#  }
#  exit;

  foreach my $rf (@renamefrom) {
    my $rt = $renameto[$i];
    if ($rf ne $rt and not lstat $rt and length($rt)) {
      rename($rf,$rt);
    }
    $i++;
  }

}


sub update_folder {
  my $folder = normalize_folder(shift);
  my @d = localtime time;
  my $lv = readlink($folder) or return;
  my $nv = sprintf(
    '%s_%d%02d%02d_%02d%02d%02d',
    $folder,$d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]
  );

  rename untaint($lv),$nv or return;
  unlink $folder;
  symlink $nv,$folder;
  if (opendir my $dox,'.') {
    while (defined($_ = readdir $dox)) {
      if (-d and not -l and /$vp/) {
        if (/^((\Q$folder\E_$vp)!backup)$/ and -d $2) {
          rmrf($1);
        } elsif (/^((\Q$folder\E_$vp)!backup)$/) {
          rename $1,$2;
        }
      }
    }
    closedir $dox;
  }
}


sub sendfile {
  my $dir = shift;
  my $okey = randstring(8);
  my $okeyd = "$spooldir/$owner/\@OKEY";
  my $url = $ENV{REQUEST_URL};

  unless ($user =~ /@/ and checkaddress($user)) {
    http_die("$user is not a valid email address");
  }

  mkdir $okeyd;
  symlink $user,"$okeyd/$okey"
    or http_die("cannot create OKEY $okeyd/$okey - $!");

  $url =~ s:\?.*::;
  my $comment = urlencode($url);
  $url =~ s:/$DOX/.*:/fup?to=$owner&okey=$okey&comment=$comment:;

  redirect($url);
  exit;
}


sub okey {
  my $dir = shift;
  my $okey = randstring(8);
  my $okeyd = "$spooldir/$owner/\@OKEY";

  unless ($user =~ /@/ and checkaddress($user)) {
    http_die("$user is not a valid email address");
  }

  mkdir $okeyd;
  symlink $user,"$okeyd/$okey"
    or http_die("cannot create OKEY $okeyd/$okey - $!");

  nvt_print(
    'HTTP/1.0 200 OK',
    "Server: fexsrv",
    "X-okey: $okey",
    "Content-Type: text/plain",
    ''
  );

  print "okey=$okey\n";
  exit;
}


sub notify_owner {
  my $upload = "$folder/.upload/$user";
  my @files = ();
  my ($mfrom,$hfrom) = mhfrom($user);
  my $header = qqq(qq(
    'From: <$mfrom> ($hfrom via F*EX service $hostname)'
    'To: $owner'
    'Subject: DOX upload /$folder/'
    'MIME-Version: 1.0'
    'Content-Type: text/plain; charset=UTF-8'
    'Content-Transfer-Encoding: 8bit'
  ));
  local $_;

  chdir $upload or http_die("$owner : $upload - $!");

  foreach (asort(find("."))) {
    next if -l or not -f;
    push @files,"$1\n" if m:^\./(.+):;
  }

  # explicit sender set in fex.ph?
  if ($sender_from) {
    # obsoleted feature!
    map { s/^From: <\Q$user/From: <$sender_from/ } $header;
    open_sendmail($owner,$bcc);
  } else {
    # for special remote domains do not use same domain in From,
    # because remote MTA will probably reject this e-mail
    my $dfrom = $1 if $user  =~ /@(.+)/;
    my $dto   = $1 if $owner =~ /@(.+)/;
    if ($dfrom and $dto and @remote_domains and
        grep { $dfrom =~ /(^|\.)$_$/ and $dto =~ /(^|\.)$_$/ } @remote_domains)
    {
      $header =~ s/(From: <)\Q$user\E(.*?)\n/$1$admin$2\nReply-To: $user\n/;
      open_sendmail($owner,$bcc);
    } else {
      open_sendmail('-f',$mfrom,$owner,$bcc);
    }
  }

  my @body = (
    "$doxurl$folder/.upload/$user\n",
    "\n",
    @files
  );
  print {$sendmail} $header,"\n",@body;
  close $sendmail;
  &check_sendmail_error;
  http_header('200 OK');
  print html_header($head);
  pq(qq(
    '<h2>Notification email has been sent to $owner</h2>'
    '<a href="/$doxo/$folder/UPLOAD">back to DOX</a>'
  ));
}


sub mirror {
  my $bytes = 0;
  my ($quota,$du) = check_recipient_quota($owner);
  if ($quota and $du > $quota) {
    http_die("$owner is overquota");
  }
  chdir $file or http_die("$owner : ".htmlencode($file)." - $!");
  my $wget='wget -e robots=off -w 1 -nv -nH -np -m';
  $mirror .= '/' if $mirror =~ m:.*/[^./]+$:;
  $mirror = untaint(shellquote($mirror));
  open $wget,"$wget $mirror 2>&1|" or http_die("cannot run wget - $!");

  http_header('200 OK');
  print html_header($head);
  print "<h1>Mirroring to /$file/</h1>\n";
  print "<pre>\n";

  while (<$wget>) {
    if (/URL:(.+(\d+)\]) -> /) {
      $bytes += $2;
      printf "%s%s\n",$scroll,htmlquote($1) or exit;
      if ($quota and $du+$bytes/$MB > $quota) {
        pq(qq(
          '</pre>'
          '<h1>Overquota! ($quota MB)</h1>'
          '$scroll'
          '</body></html>'
        ));
        exit;
      }
    }
  }

  pq(qq(
    '</pre>'
    '<a href="/$doxo/$file/">back to DOX</a>'
    '</body>'
    '</html>'
  ));
  exit;
}


sub publish {
  my @files = @_;
  my $sdir = $file;
  my $ddir = $sdir;

  unless ($akey)    { http_die("no permission") }
  unless (-d $sdir) { http_die("unknown upload directory $sdir") }

  map { $_ = "$sdir/$_" } @files;
  $ddir =~ s:^\Q$folder/.upload/\E[^/]+(.*):$folder$1:;
  mkdirp($ddir);
  publishlog(@files);
  my $errors = move(@files,$ddir);
  update_folder($folder);
  if ($errors) {
    $errors = htmlquote($errors);
    http_header('200 OK');
    print html_header($head);
    pq(qq(
      '<h1>move error</h1>'
      '$errors'
      '</body>'
      '</html>'
    ));
    &reexec;
  }
}


sub publish_all {
  my $dir = shift;
  my @files = ();
  my $user = '';
  local $_;

  if (-d $dir and $dir =~ m:^\Q$folder/.upload/\E([^/]+)$:) {
    $user = $1;
  } else {
    http_die("unknown upload directory $dir");
  }

  foreach (glob "$dir/*") {
    next if -l;
    foreach (asort(find($_))) {
      push @files,$_ if -f and not -l;
    }
  }
  publishlog(@files) if @files;

  @files = glob "$dir/*" or return;
  map { /(.+)/; $_ = $1 } @files;

  my $errors = move(@files,$folder);
  update_folder($folder);

  if ($errors) {
    $errors = htmlquote($errors);
    http_header('200 OK');
    print html_header($head);
    pq(qq(
      '<h1>move error</h1>'
      '$errors'
      '</body>'
      '</html>'
    ));
    exit;
  }
}


sub syncdir {
  my $dir = shift;
  my @fexsync = ('fexsync');

  unless ($akey) {
    if ($dir ne $folder) {
      http_die('syncing not allowed for users');
    }
    my $exclude = '\.[^/]*';
    foreach (asort(values %exclude)) {
      s:^/+::;
      $exclude .= '|'.$_;
    }
    foreach (find($dir)) {
      if (-l) {
        s:^$folder/:./:;
        $exclude .= '|'.quotemeta($_);
      }
    }
    push @fexsync,'-X',$exclude;
  }

  nvt_print(
    'HTTP/1.1 200 OK',
    'Server: fexsrv',
    "Content-Type: text/html; charset=$charset",
    '',
  );

  pq(qq(
    '<html>'
    '<body>'
  ));
  push @fexsync,$dir;
  doxlog("[@fexsync]");
  print "\$ @fexsync\n" if $akey;
  local $ENV{FEXCOMMENT} = "$owner/DOX/$dir";
  local $ENV{FEXHOME} = '';
  local $ENV{FEXSERVER} = '';
  if (open my $fexsync,'-|',@fexsync) {
    while (<$fexsync>) {
      if (/to start sync receiving without FEXID/) {
        print "<h3>To start sync receiving run:</h3>\n";
        print "<pre>\n";
        $_ = <$fexsync>;
        s/:\d+/:$ENV{PORT}/;
        print;
        last;
      }
    }
    while (<$fexsync>) {
      s!^server/user:.*!!;
      last if /^Recipient: /;
      print $scroll,htmlencode($_);
    }
    while (<$fexsync>) { }
    close $fexsync;
  }
  pq(qq(
    '</pre>'
    '<script>history.back()</script>'
    '</body>'
    '</html>'
  ));
}


sub streamdir {
  my $dir = shift;
  my $stream = $dir;
  my @tar = qw'tar -c';
  my ($sex,$tar,$data,$sexsend);
  local $ENV{FEXHOME} = '';
  local $ENV{FEXSERVER} = '';

  $SIG{ALRM} = sub {
    $SIG{__DIE__} = 'DEFAULT';
    die "<h2>TIMEOUT<h2>\n";
  };
  alarm($timeout*10);

  if ($akey) {
    if (-l $dir) {
      push @tar,qw'-f -',"$dir/.";
    } else {
      push @tar,qw'-f -',$dir;
    }
  } else {
    push @tar,"--exclude=.*";
    foreach (asort(keys %exclude)) {
      s:^/+::;
      push @tar,"--exclude=$_";
    }
    foreach (find($dir)) {
      push @tar,"--exclude=$_" if -l;
    }
    if (-l $dir) {
      push @tar,qw'-f -',map {$_=untaint($_)} glob("$dir/*");
    } else {
      push @tar,qw'-f -',$dir;
    }
  }

  my $idf = "$ENV{HOME}/.fex/id";
  open $idf,$idf or http_die("no $idf");
  my $url = <$idf>;
  my $fexuser = <$idf>;
  close $idf;
  unless ($fexuser) {
    http_die("no fexuser in $idf");
  }
  chomp $url;
  chomp $fexuser;

  nvt_print(
    'HTTP/1.1 200 OK',
    'Server: fexsrv',
    "Content-Type: text/html; charset=$charset",
    '',
  );

  pq(qq(
    '<html>'
    '<body>'
  ));
  $stream =~ s/[^\w\@.+-]/_/g;
  $stream .= ':'.randstring(8);
  $sex = "@tar | sexsend public $stream";
  doxlog("[$sex]");
  my $sexurl = "$url/sex?user=$fexuser&ID=public&stream=$stream";
  print "\$ $sex\n" if $akey;
  pq(qq(
    "<h3>To start stream receiving run:</h3>"
    "<pre>"
    "sexget $url/$fexuser:public $stream | tar xvf -"
    ""
    "wget -O- '$sexurl' | tar xvf -"
    ""
    "curl '$sexurl' | tar xvf -"
    "</pre>"
  ));
  open $sexsend,"|sexsend public $stream >/dev/null" or exit;
  open $tar,'-|',@tar or exit;
  while (read($tar,$data,$bs)) {
    print {$sexsend} $data or exit;
    alarm($timeout*10);
  }
  close $sexsend;
  close $tar;
  pq(qq(
    '<script>history.back()</script>'
    '</body>'
    '</html>'
  ));
}


sub moveup {
  my $fdir = shift; # folder/subdir
  my $n = shift;
  my $hdir = htmlencode($fdir);
  my @images;
  my $ii;
  
  chdir $fdir or http_die("$hdir - $!");
  @images = collect_images($hdir,'prefix');
  
  if ($n == scalar(@images)) {
    my $img = pop @images;
    unshift @images,$img;
    $ii = 1;
  } else {
    ($images[$n-1],$images[$n]) = ($images[$n],$images[$n-1]);
    $ii = $n+1;
  }

  reorder(@images);

  my $uri = $ENV{REQUEST_URI};
  $uri =~ s/ACTION=.*/ACTION=preview:$ii/;
  redirect($uri);
  &reexec;
}


sub movedown {
  my $fdir = shift; # folder/subdir
  my $n = shift;
  my $hdir = htmlencode($fdir);
  my @images;
  my $ii;
  
  chdir $fdir or http_die("$hdir - $!");
  @images = collect_images($hdir,'prefix');
  
  if ($n == 1) {
    my $img = shift @images;
    push @images,$img;
    $ii = $#images+1;
  } else {
    ($images[$n-1],$images[$n-2]) = ($images[$n-2],$images[$n-1]);
    $ii = $n-1;
  }
  
  reorder(@images);
  
  my $uri = $ENV{REQUEST_URI};
  $uri =~ s/ACTION=.*/ACTION=preview:$ii/;
  redirect($uri);
  &reexec;
}


sub movefromto {
  my $fdir = shift; # folder/subdir
  my $hdir = htmlencode($fdir);
  my @images;
  my $i;
  
  chdir $fdir or http_die("$hdir - $!");
  
  @images = collect_images($hdir,'prefix');
  
  if ($move_from >= $#images) { http_die("image #$move_from does not exist") }
  if ($move_to   >= $#images) { http_die("image #$move_to does not exist") }

#  http_die("$hdir : $move_from -> $move_to");
  
  if ($move_from != $move_to) {
    $i = splice @images,$move_from-1,1;
    splice @images,$move_to-1,0,$i;
    reorder(@images);
  }
  
  my $uri = $ENV{REQUEST_URI};
  $uri =~ s/\?ACTION=.*//;
  redirect("$uri?ACTION=preview");
  &reexec;
}


sub reorder {
  my $i = 0;
  
  foreach my $img (@_) {
    $i++;
    my $nimg = $img;
    $nimg =~ s/^\[\d+\]/sprintf('[%03d]',$i)/e;
    img_rename($img,$nimg) if $img ne $nimg;
  }
}

sub img_rename {
  my ($img,$nimg) = @_;
  rename $img,$nimg;
  rename "$img.txt","$nimg.txt";
  rename ".preview/gallery/$img",".preview/gallery/$nimg";
  rename ".preview/browse/$img",".preview/browse/$nimg";
}

sub browsedir {
  my $fdir = shift; # folder/subdir
  my $hdir = htmlencode($fdir);
  my $udir = urlencode($fdir);
  my $i = shift || 1;
  my $rnd = $i;
  my $uri = $ENV{REQUEST_URI} or http_die("no REQUEST_URI");
  my ($previous,$next,$first,$last,$random,$index,$gallery,$previousa,$nexta);
  my ($dir,$fname,$ufile,$image,$counter,$file,$bfile,$src,$nav1,$nav2);
  my ($description,$edit,$delete,$rleft,$rright,$login,$sp,$view,$title);
  my ($fullsize,$istyle);
  my (@nav);
  my @images = ();
  my $date = '';

  $dir = $fdir;
  $dir =~ s:.+?/:: or $dir = '';

  chdir $fdir or http_die("$hdir - $!");
  @images = collect_images($hdir);
  
  $file = $images[$i-1] or redirect("$uri?ACTION=preview");
  $fname = htmlencode($file);
  $ufile = urlencode($file);
  $bfile = ".preview/browse/$file"; # image shown in browsing mode
  mkdirp('.preview/browse');
  if (-s $bfile and mtime($bfile) > mtime($file)) {
    $image = slurp($bfile);
  } elsif ($convert) {
    local $SYSTEMLOG = '>>.preview/error.log';
    logsystem($convert,'-resize',"$xpixel>",$file,$bfile);
    if (-s $bfile) {
      logsystem($jpgreduce,$bfile) if $jpgreduce;
      $image = slurp($bfile);
    }
  }
  unless ($image) {
    $image = slurp($file) or http_die("$hdir/$fname is empty");
  }

  if ($#images) { $rnd = int(rand($#images+1))+1 while $rnd == $i }

  $uri =~ s/\?.*//;

  if ($http_client =~ /Android|iPhone/) {
    $sp = ' &nbsp; ';
    $title = '';
  } else {
    $sp = ' &nbsp; 'x2;
    $title= 'title="click here for full size image"';
  }
  
  $first =    sprintf('<a href="%s?ACTION=browseit:%d"><button id="first">first</button></a>',$uri,1);
  $last =     sprintf('<a href="%s?ACTION=browseit:%d"><button id="last">last</button></a>',$uri,$#images+1);
  $random =   sprintf('<a href="%s?ACTION=browseit:%d"><button id="random">random</button></a>',$uri,$rnd);
  $edit =     sprintf('<a href="%s?ACTION=editit:%d"><button>edit description</button></a>',$uri,$i);
  $delete =   sprintf('<a href="%s?ACTION=del:%d"><button>delete</button></a>',$uri,$i);
  $rleft =    sprintf('<a href="%s?ACTION=rleft:%d"><button>rotate left</button></a>',$uri,$i);
  $rright =   sprintf('<a href="%s?ACTION=rright:%d"><button>rotate right</button></a>',$uri,$i);
  $gallery =  sprintf('<a href="%s?ACTION=preview:%d"><button id="gallery">gallery</button></a>',$uri,$i);
  $fullsize = sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="fullsize">fullsize</button></a>',$uri,$i);
  $index =    sprintf('<a href="%s"><button>index</button></a>',$uri);
  $counter =  sprintf('(%d/%d)',$i,$#images+1);
  $login =    qq'<a href="/fup?from=$owner?forward=/$doxo/$udir"><button>login</button></a>';
  if ($i>1) {
    $previous =  sprintf('<a href="%s?ACTION=browseit:%d"><button id="previous">previous</button></a>',$uri,$i-1);
    $previousa = sprintf('<a href="%s?ACTION=browseit:%d"><button class="big">&larr;</button></a>',$uri,$i-1);
  } else {
    $previous =  'previous';
    $first =     'first';
    $previousa = '<h1>&nbsp;</h1>';
  }
  if (defined($images[$i])) {
    $next =  sprintf('<a href="%s?ACTION=browseit:%d"><button id="next">next</button></a>',$uri,$i+1);
    $nexta = sprintf('<a href="%s?ACTION=browseit:%d"><button class="big">&rarr;</button></a>',$uri,$i+1);
  } else {
    $next =  'next';
    $last =  'last';
    $nexta = '<h1>&nbsp;</h1>';
  }
  if ($convert) {
    @nav = ($first,$previous,$next,$last,$random,$gallery);
  } else {
    @nav = ($first,$previous,$next,$last,$random);
  }
  if ($http_client !~ /Android|iPhone/) {
    push @nav,$fullsize;
  }
  if ($akey) {
    if ("/$dir" =~ m:/.preview:) {
      $nav1 = join($sp,$first,$previous,$next,$last,$index);
    } else {
      $nav1 = join($sp,@nav,$edit,$rleft,$rright,$delete);
    }
#  } elsif ($ENV{AKEY}) {
#    $nav1 = join($sp,@nav);
  } else {
    $nav1 = join($sp,@nav,$login);
  }
  if ($description = htmlencode(slurp("$file.txt")||'')) {
    $description =~ s|(https?://\S+)|<a href="$1">$1</a>|g;
    $description =~ s/\n\n+/<p>/g;
    $description =~ s/\n/<br>/g;
    $description = qq'<table border="0"><tr><td>$description</tr></table>\n';
  }
  $src = 'data:image/png;base64,'.encode_b64($image);
  if ($http_client =~ /Android|iPhone/) {
    $istyle = 'max-width:calc(100vw);max-height:calc(100vh)';
    $view = qqq(qq(
      '<table border="0">'
      '<tr><td><img style="$istyle" src="$src"></tr>'
      '<tr align="center"><td>$previousa $sp $counter $sp $nexta</tr>'
      '</table>'
   ));
    $nav2 = '';
  } else {
    $istyle = 'max-width:calc(100vw - 10em);max-height:calc(100vh - 10em)';
    $view = qqq(qq(
      '<table border="0"><tr>'
      '<td>$previousa'
#      '<td><a href="$uri/$ufile"><img style="$istyle" src="$src"></a>'
      '<td><a href="$uri?ACTION=browseitfull:$i" $title> <img style="$istyle" src="$src"></a>'
      '<td>$nexta'
      '</tr></table>'
    ));
    $nav2 = $nav1;
    $nav1 .= $sp.$counter;
  }
  if ($file =~ /(19|20)\d\d-\d\d-\d\d|(19|20)\d\d\d\d\d\d_\d\d\d\d\d\d/) {
    $date = '';
  } else {
    $date = isodate(mtime($file));
    $date =~ s/(.*):\d\d$/($1)/;
  }
  $hdir =~ s:^public/gallery/::;
  http_header('200 OK');
  # https://css-tricks.com/snippets/javascript/javascript-keycodes/
  # https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
  pq(qq(
    '<html>'
    '<HEAD>'
    '<meta name="viewport" content="width=device-width, initial-scale=1" />'
    '<TITLE>$fname</TITLE>'
    '<body>'
    '<style>'
    '  button.big { font-size: 3rem; }'
    '  img { border: 1px solid black; padding: 0.3em; }'
    '</style>'
    '<script>'
    'document.onkeydown = function(e) {'
#    '  // [F12]'
#    '  console.log("Tastatureingabe, Event:");'
#    '  console.log(e);'
    '  switch (e.keyCode) {'
    '    case 35: // End'
    '      document.getElementById("last").click();'
    '      break;'
    '    case 36: // Home'
    '      document.getElementById("first").click();'
    '      break;'
    '    case  8: // backspace'
    '    case 37: // cursor_left'
    '      document.getElementById("previous").click();'
    '      break;'
    '    case 32: // space'
    '    case 39: // cursor_right'
    '      document.getElementById("next").click();'
    '      break;'
    '    case 27: // Esc'
    '    case 38: // cursor_up'
    '    case 71: // G'
    '      document.getElementById("gallery").click();'
    '      break;'
    '    case 82: // R'
    '      document.getElementById("random").click();'
    '      break;'
    '    case 13: // enter'
#    '    case 40: // cursor_down'
    '      document.getElementById("fullsize").click();'
    '      break;'
    '  }'
    '};'
    '</script>'
    '<center>'
    $nav1
    '<p>'
    $description
    $view
    '<h3>$owner : <nobr>$hdir</nobr> <a href="$uri/$ufile" download>$fname</a> $date</h3>'
#    '<p>'
#    '$nav2'
  ));

  exit;
}


sub browsedirfull {
  my $fdir = shift; # folder/subdir
  my $i = shift || 1;
  my $hdir = htmlencode($fdir);
  my $udir = urlencode($fdir);
  my $rnd = $i;
  my ($previous,$next,$first,$last,$random,$viewsize,$gallery);
  my ($dir,$fname,$ufile,$image,$counter,$file,$src,$nav);
  my ($description,$sp,$istyle);
  my $uri = $ENV{REQUEST_URI} or http_die("no REQUEST_URI");
  my $title= 'title="click here to toogle image viewsize"';
  my (@nav);
  my @images = ();

  $dir = $fdir;
  $dir =~ s:.+?/:: or $dir = '';

  chdir $fdir or http_die("$hdir - $!");
  @images = collect_images($hdir);
  
  $file = $images[$i-1] or redirect("$uri?ACTION=preview");
  $fname = htmlencode($file);
  $ufile = urlencode($file);

  if ($#images) { $rnd = int(rand($#images+1))+1 while $rnd == $i }

  $uri =~ s/\?.*//;

  if ($http_client =~ /Android|iPhone/) {
    $sp = ' &nbsp; ';
  } else {
    $sp = ' &nbsp; 'x2;
  }
  
  $first =    sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="first">first</button></a>',$uri,1);
  $last =     sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="last">last</button></a>',$uri,$#images+1);
  $random =   sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="random">[r] random</button></a>',$uri,$rnd);
  $gallery =  sprintf('<a href="%s?ACTION=preview:%d"><button id="gallery">gallery</button></a>',$uri,$i);
  $viewsize = sprintf('<a href="javascript:toggle_view();"><button id="viewsize">[&#x21B5;] viewsize</button></a>');
  $counter =  sprintf('(%d/%d)',$i,$#images+1);
  if ($i>1) {
    $previous =  sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="previous">[&larr;] previous</button></a>',$uri,$i-1);
  } else {
    $previous =  sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="previous">previous</button></a>',$uri,1);
    $previous =  'previous';
    $first =     'first';
  }
  if (defined($images[$i])) {
    $next =  sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="next">[&rarr;] next</button></a>',$uri,$i+1);
  } else {
    $next =  sprintf('<a href="%s?ACTION=browseitfull:%d"><button id="next">next</button></a>',$uri,$i);
    $next =  'next';
    $last =  'last';
  }
  @nav = ($first,$previous,$next,$last,$random,$gallery,$viewsize);
  $nav = join($sp,@nav);
  if ($description = htmlencode(slurp("$file.txt")||'')) {
    $description =~ s|(https?://\S+)|<a href="$1">$1</a>|g;
    $description =~ s/\n\n+/<p>/g;
    $description =~ s/\n/<br>/g;
#    $description = qq'<table border="0"><tr><td>$description</tr></table>\n';
  }
  $istyle = 'max-width:calc(100vw - 2em); max-height:calc(100vh - 4em)';
  http_header('200 OK');
  # https://css-tricks.com/snippets/javascript/javascript-keycodes/
  pq(qq(
    '<html>'
    '<HEAD>'
    '<TITLE>$fname</TITLE>'
    '<body class="gallery single-img">'
    '<style>'
    '  body.gallery.single-img { margin: 0; }'
    '  img { border: 1px solid black; padding: 0.3em; }'
    '</style>'
    '<script>'
    'document.onkeydown = function(e) {'
#    '  // [F12]'
#    '  console.log("Tastatureingabe, Event:");'
#    '  console.log(e);'
    '  var imgstyle = document.getElementById("img").getAttribute("style");'
    '  switch (e.keyCode) {'
    '    case  8: // backspace'
    '      document.getElementById("previous").click();'
    '      break;'
    '    case 32: // space'
    '      document.getElementById("next").click();'
    '      break;'
    '    case 35: // End'
    '      document.getElementById("last").click();'
    '      break;'
    '    case 36: // Home'
    '      document.getElementById("first").click();'
    '      break;'
    '    case 37: // cursor_left'
    '      if (imgstyle) document.getElementById("previous").click();'
    '      break;'
    '    case 39: // cursor_right'
    '      if (imgstyle) document.getElementById("next").click();'
    '      break;'
    '    case 38: // cursor_up'
    '      if (imgstyle) document.getElementById("gallery").click();'
    '      break;'
    '    case 27: // Esc'
    '    case 71: // G'
    '      document.getElementById("gallery").click();'
    '      break;'
    '    case 82: // R'
    '      document.getElementById("random").click();'
    '      break;'
    '    case 13: // enter'
    '    case 86: // V'
    '      toggle_view();'
    '      break;'
    '  }'
    '};'
    ''
    'function toggle_view() {'
    '  var imgstyle = document.getElementById("img").getAttribute("style");'
    '  if (imgstyle)'
    '    document.getElementById("img").style = "";'
    '  else'
    '    document.getElementById("img").style = "$istyle";'
    '}'
    '</script>'
    '<center>'
    $nav
    '$sp $counter<br>'
#    '<a href="javascript:toggle_view()" $title>'
    $description<br>
    '<img id="img" style="$istyle" src="$uri/$ufile">'
#    '</a><br>'
  ));
  exit;
}


sub edit_description {
  my $fdir = shift; # folder/subdir
  my $hdir = htmlencode($fdir);
  my $i = shift || 1;
  my ($dir,$fname,$ufile,$image,$file,$style,$src,$description);
  my $uri = $ENV{REQUEST_URI} or http_die("no REQUEST_URI");
  my @images = ();

  return unless $akey;

  $dir = $fdir;
  $dir =~ s:.+?/:: or $dir = '';

  chdir $fdir or http_die("$hdir - $!");
  opendir $fdir,'.' or http_die("$hdir - $!");
  while (defined($_ = readdir $fdir)) {
    next if /\n/;
    next if -l;
    push @images,untaint($_) if -f and -s and /\.($imgtype)(#\d+)?$/i;
  }
  closedir $fdir;

  if (@images) {
    @images = asort(@images);
  } else {
    http_die("no images in $hdir");
  }

  $file = $images[$i-1] or http_die("no image #$i in $hdir");
  $fname = htmlencode($file);
  $ufile = urlencode($file);
  $image = slurp($file) or http_die("$hdir/$fname is empty");
  $uri =~ s/\?.*//;
  $description = htmlencode(slurp("$file.txt")||'');
  $style = 'max-width:calc(100vw - 8em);max-height:calc(100vh - 10em)';
  $src = 'data:image/png;base64,'.encode_b64($image);
  http_header('200 OK');
  pq(qq(
    '<html>'
    '<HEAD>'
    '<meta name="viewport" content="width=device-width, initial-scale=1" />'
    '<TITLE>$fname</TITLE>'
    '</HEAD>'
    '<body>'
    '<center>'
    '<form action="$uri/$ufile"'
    '      method="post"'
    '      accept-charset="UTF-8"'
    '      enctype="multipart/form-data">'
    '<table border="0"><tr>'
    '<td>description:'
    '<td><textarea name="description" cols="80" rows="2">$description</textarea>'
    '<td><input type="submit" value="save">'
    '</tr></table>'
    '</form>'
    '<p>'
    '<a href="$uri/$ufile"><img style="$style" src="$src"></a>'
    '<h3>/$hdir/<a href="$uri/$ufile">$fname</a></h3>'
    '<p>'
    '</center>'
    '</body>'
    '</html>'
  ));

  exit;
}


# delete, rotate left, rotate right
sub mod_img {
  my $mod = shift;
  my $dir = shift;
  my $hdir = htmlencode($dir);
  my $i = shift;
  my ($img,$image,$qimage);
  my @images = ();
  local $_;

  unless ($akey or $gallery_test) {
    http_die("operation $mod not authorized");
  }

  chdir $dir or http_die("$hdir - $!");
  @images = collect_images($hdir);

  $image = $images[$i-1] or http_die("no image #$i in $hdir [@images]");
  $qimage = untaint($image);
  if ($mod eq 'del') {
    unlink $image;
    if ($image =~ /^\[\d+\]./) {
      splice(@images,$i-1,1);
      reorder(@images);
    }
  } elsif ($mod eq 'rleft') {
    $img = `$convert -rotate 270 -orient top-left $qimage - 2>/dev/null`;
  } elsif ($mod eq 'rright') {
    $img = `$convert -rotate  90 -orient top-left $qimage - 2>/dev/null`;
  } else {
    http_die("unknown mod command $mod");
  }
  
  if ($img and length($img) > 99) {
    if (open $image,'>',$image) {
      print {$image} $img;
      close $image;
    }
  }
  # will be rebuild on next gallery call
  unlink ".preview/browse/$image";
  unlink ".preview/gallery/$image";

  return $image;
}


sub save_description {
  my $uri = shift;
  my $dir = dirname($uri);
  my $file = basename($uri);
  $dir =~ s:.+?/::;
  my $hdir = htmlencode($dir);
  my $i = 0;
  my @images;

  return unless $akey;

  chdir $dir or http_die("cannot chdir $hdir - $!");
  unless (-f $file) { http_error(404) }
  open $file,'>',"$file.txt" or http_die("cannot write $hfile.txt - $!");
  print {$file} $description;
  close $file;
  opendir $dir,'.' or http_die("$hdir - $!");
  while (defined($_ = readdir $dir)) {
    next if /\n/;
    next if -l;
    push @images,untaint($_) if -f and -s and /\.($imgtype)(#\d+)?$/i;
  }
  closedir $dir;

  if (@images) {
    @images = asort(@images);
  } else {
    http_die("no images in $hdir");
  }

  foreach my $img (@images) {
    $i++;
    if ($img eq $file) {
      redirect(dirname($ENV{REQUEST_URI})."?ACTION=browseit:$i");
      &reexec;
    }
  }
  http_die("cannot find $hfile");
}


# .preview/gallery/ : thumbnail images for gallery view
# .preview/browse/  : scaled images for browsing mode
sub gallery {
  my $fdir = shift; # folder/subdir
  my $hdir = htmlencode($fdir);
  my $dox = "/$doxo/$fdir";
  my $gallery = htmlencode(basename($fdir));
  my $h1 = "<h1>$owner : $gallery</h1>\n";
  my $ppw = 128;
  my $gap = 10;
  my $ppwl = '.preview/gallery/.ppw';
  my $i = 0;
  my $n = 0;
  my $ii = 0;
  # https://www.w3schools.com/tags/ref_colornames.asp
  my $bgcn = 'Beige';
  my $bgcs = 'LightGreen';
  my ($image,$src,$dir,$x,$bgcolor,$imax);
  my @images = ();
  my %images = ();
  local $_;

  $dir = $fdir;
  $dir =~ s:.+?/:: or $dir = '';

  $ii = 1;
  $ii = $1 if $referer =~ /ACTION=\w+:(\d+)/;
  $ii = $1 if $QS =~      /ACTION=preview:(\d+)/;

  chdir $fdir or http_die("$hdir - $!");
  @images = collect_images($hdir);
  $imax = $#images+1;

  foreach my $pd (qw(.preview .preview/browse .preview/gallery)) {
    unless (-d $pd) {
      mkdir $pd or http_die("$hdir/$pd - $!");
    }
  }

  if ($akey) {
    if ($newpreview) {
      unlink $ppwl;
      symlink $newpreview,$ppwl;
     }
  }
  if (my $w = readlink $ppwl) { $ppw = untaint($w) }
  
  http_header('200 OK');
  # https://css-tricks.com/snippets/javascript/javascript-keycodes/
  # https://codepen.io/fermion/pen/EaYbdoB
  # https://www.perplexity.ai/search/thema-js-li-id-l1-li-id-l2-cla-Vb8asP0GSfaIYIA_jOkTjg
  # https://fontawesome.com 
  # fontawesome-solid extracted by Andreas Borutta <borumat@gmx.de>
  pq(qq(
    '<HTML>'
    '<HEAD>'
    '<meta name="viewport" content="width=device-width, initial-scale=1" />'
    '<TITLE>$gallery</TITLE>'
    '<BODY>'
    '<style>'
    'table {'
    '  border-collapse: collapse;'
    '}'
    'ol {'
    '  display: flex;'
    '  flex-wrap: wrap;'
    '  gap: ${gap}px;'
    '  list-style: none;'
    '  padding: 0;'
    '}'
    'li {'
    '  height: ${ppw}px;'
    '  width: ${ppw}px;'
    '  position: relative;'
    '  background: $bgcn;'
    '}'
    'li.select { background: $bgcs; }'
    'img {'
    '  width: 100%;'
    '  height: 100%;'
    '  object-fit: contain;'
    '}'
    'div.number {'
    '  position: absolute;'
    '  top: 0;'
    '  background-color: $bgcn;'
#    '  background-color: transparent;'
    '  font-family: sans-serif;'
    '}'
    'div.buttons {'
    '  display: flex;'
    '  justify-content: space-between;'
    '  width: calc(100% - 6px);'
    '  position: absolute;'
    '  bottom: 0;'
    '  margin: 3px;'
    '}'
    'div a /* button mimik */ {'
    '  color: black;'
    '  background-color: #e6e6e6;'
#    '  width: 1.4em;'
#    '  height: 1.4em;'
    '  width:       calc((${ppw}px/8));'
    '  height:      calc((${ppw}px/8));'
    '  line-height: calc((${ppw}px/8));'
#    '  border-radius: 50%;'
    '  border-radius: 6px;'
    '  border: 1px solid gray;'
#    '  font-family: sans-serif;'
#    '  font-weight: bold;'
    '  font-family: fontawesome-solid;'
    '  font-size: calc((${ppw}px/10));'
    '  text-decoration: none;'
    '  text-align: center;'
    '  padding: 2px 2px;'
    '}'
    'div a:hover {'
    '  background-color: rgb(200,200,200);'
    '}'
#    'div a:nth-child(3) { '
#    '  color: red;'
#    '}'
    '\@font-face {'
    '  font-family: fontawesome-solid;'
    '  src: url(data:application/x-font-woff;charset=utf-8;base64,d09GMgABAAAAAANUAAoAAAAABxMAAAMKAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIIkATgCJAMYBCAFgwAGYAcgCoZghS8LHAAbZgYRVZTpID8OcjJXUymuJtqiLDiybA4v/lHE/wiitbJ6Zm4fD10IFJAFBAdECoWOsWGHOix8XBTr8SG7/BdoZmejRehKrega3At0qAKwFb9UqcuVH6pU8PJD1+QXe5CzL8HHN8xetxVl4qjEJ1oBPn4dyIRH8wnInnMRuTpQmQJC1dfB10FBxmwBrsgCb2SjxLBiG8YNS8qvSkf//OP/WukSURn/V4UkK1rcDZrYniSoFXlMCm3v4e6y/z2awI/Nz5HSW+q/+jqp4xUaSUQupENERm2svvhA+URPeuUJAk1PoaoSQgVUUzHuiQChjQBJS1uAbJqBAEXbYgFashUCNNpWy6KMCBPt0EAy6gzIVrgGiomegZbGx3Jjou/5eWzOHZekN2jTphdjyR/w5uIFixyGthNtdNIlJ11z1A0nnbDBZSTesNdlF5wd12t++hld4gBErzu7vs3pFltgUfxkdXdJOT/WMhzb4hQ2Sj/E/+w9JhnJAKIHgNUH925334xa41V9TXyyFQGxOp5iOjJ2YyMwjjFiDrEBUEASQmiJUubMWTq93263l7rXvXOpe6+DLJgEoIh5mKJqecZAJeWDoSKmCYcC8ISQW+MBkNW1ySgfB0RMUYZc7lTLBQWEkm0HA8zIM2IYbhKexT0Ju3Jfc1sNvYx9HP80fNpAJc9QtfiGqjMeGaii35KJ1DBMCZMCKVnwpdiyF0GhFqegCJOEw4REHxiFnMs4ZohZv10vDtsB+w5GeZMCMCXOyAaYlmivqaGE7jjud04LobiOfxr7OPTSbdV9Lewq7knCs4jvlF+PT02/N1DFvKPqtFBMilMiBcxRyBzZJR1mf9KZfxhnABtfWcEsY7PjjI03NSIE/NgYvzkhMLB2dp1xW+LxbkQo8MGCj8sSFVi+f38+hwuttld3cfH506fPs6xT6YPxdObGvEt8ZCSvHx/W8xGRbAwHZWW/240cKYEdCFTaUPkIS5ErKtF2qk3h+kgQa+tVYHWuI5EVEXpej4sHtbKMVlN492DOM3g1TwcA) format(woff2);'
    '}'
    '</style>'
    ''
    '<script>'
    'var ii = $ii;'
    'var imax = $imax;'
    ''
    'function GetElementsPerRow() {'
    '  let ol = document.querySelector("ol");'
    '  let li = ol.querySelector("li");'
    '  let liWidth = li.offsetWidth+$gap;'
    '  let olWidth = ol.offsetWidth;'
    '  let elementsPerRow = Math.floor(olWidth / liWidth);'
    '  // console.log(`olWidth = \${olWidth}`);'
    '  // console.log(`liWidth = \${liWidth}`);'
    '  // console.log(`There are \${elementsPerRow} elements in one row`);'
    '  return elementsPerRow;'
    '}'
    ''
    'document.onkeydown = function(e) {'
    '  let epr = GetElementsPerRow();'
    '  switch (e.keyCode) {'
    '    case 13: // enter'
    '      document.getElementById("i"+ii).click();'
    '      break;'
    '    case 35: // End'
    '      document.getElementById("l"+ii).classList.remove("select")'
    '      ii = imax;'
    '      document.getElementById("l"+ii).classList.add("select")'
    '      document.getElementById("l"+ii).scrollIntoView();'
    '      break;'
    '    case 36: // Home'
    '      document.getElementById("l"+ii).classList.remove("select")'
    '      ii = 1;'
    '      select_and_scroll();'
    '      break;'
    '    case 37: // cursor_left'
    '      document.getElementById("l"+ii).classList.remove("select")'
    '      ii--;'
    '      if (ii == 0) ii = imax;'
    '      select_and_scroll();'
    '      break;'
    '    case 39: // cursor_right'
    '      document.getElementById("l"+ii).classList.remove("select")'
    '      ii++;'
    '      if (ii > imax) ii = 1;'
    '      select_and_scroll();'
    '      break;'
    '    case 38: // cursor_up'
    '      document.getElementById("l"+ii).classList.remove("select")'
    '      if (ii-epr > 0) ii -= epr;'
    '      select_and_scroll();'
    '      break;'
    '    case 40: // cursor_down'
    '      document.getElementById("l"+ii).classList.remove("select")'
    '      if (ii+epr <= imax) ii += epr;'
    '      select_and_scroll();'
    '      break;'
    '  }'
    '};'
    ''
#    'function scroll() { window.scrollTo(0,document.body.scrollHeight) }'
    'function select_and_scroll() {'
    '  document.getElementById("l"+ii).classList.add("select");'
    '  document.getElementById("l"+ii).scrollIntoView({ block: "center" });'
    '}'
    '</script>'
  ));
  
  print "<center>\n";

  if ($fdir =~ m:^public/gallery:) {
    my $description = '#.html';
    if (not -f $description and open $description,'>',$description) {
      print {$description} $h1;
      close $description;
    }
  } else {
    print $h1;
  }

  foreach my $description ('.#.html','#.html') {
    $x = urlencode($description);
    if (open $description,$description) {
      print while <$description>;
      close $description;
      last;
    }
  }
  
  print "<p>\n";

  if ($akey) {
    print button("$dox/$x?ACTION=edit",'edit description'),"\n";
    print "$sp\n";
    print button("$dox",'directory view'),"\n";
    print "$sp\n";
    print button("$dox?ACTION=pview",'public preview'),"\n";
    print "<p>\n";
    pq(qq(
#      '<table border=0><tr>'
      '<td><form name="preview"'
      '  action="$dox"'
      '  method="POST"'
      '  enctype="multipart/form-data">'
      '  new preview pixel width: <input type="text" name="newpreview" size="3" value="128">'
      '  <input type="submit" value="create">'
      '</form>'
    ));
  }
  if ($akey or $gallery_test) {
    pq(qq(
      '<td><form name="move"'
      '  action="$dox"'
      '  method="POST"'
      '  enctype="multipart/form-data">'
      '  move image number <input type="text" name="move_from" size="3">'
      '  to <input type="text" name="move_to" size="3">'
      '  <input type="submit" value="move">'
      '</form>'
#      '</table>'
    ));
  }
  pq(qq(
    '<p>'
    '(click on a preview image for full view or use cursor keys + ENTER)'
    '<p>'
    '<ol>'
  ));

  local $SYSTEMLOG = '>>.preview/error.log';
  $i = 0;
  foreach my $img (@images) {
    $i++;
    my $pimg = ".preview/gallery/$img";
    my $mti = mtime($img) or next;
    my $mtp = mtime($pimg)||0;
    if ($mti > $mtp or $newpreview) {
      logsystem($convert,'-resize',"$ppw>",$img,$pimg);
    }
    $bgcolor = $i == $ii ? $bgcs : $bgcn;
    $image = slurp($pimg)||'';
    $src = "data:image/png;base64,".encode_b64($image);
    pq(qq(
      '<li id="l$i">'
      '  <a href="?ACTION=browseit:$i"><img id="i$i" src="$src"></a>'
      '  <div class="number">$i</div>'
    ));
    if ($akey or $gallery_test) {
      my %bi;
      if ($http_client =~ /Safari/) {
        %bi = (
          movedown => '&larr;',
          rleft    => '&#x21B6;',
          del      => '<font color="red">X</font>',
          rright   => '&#x21B7;',
          moveup   => '&rarr;',
        );
      } else {
        %bi = (
          movedown => '&#xf060;',
          rleft    => '&#xf2ea;',
          del      => '&#xf2ed;',
          rright   => '&#xf2f9;',
          moveup   => '&#xf061;',
        );
      }
      pq(qq(
        '  <div class="buttons">'
        '  <a href="?ACTION=movedown:$i" title="move left">$bi{movedown}</a>'
        '  <a href="?ACTION=rleft:$i"    title="rotate left">$bi{rleft}</a>'
        '  <a href="?ACTION=del:$i"      title="delete">$bi{del}</a>'
        '  <a href="?ACTION=rright:$i"   title="rotate right">$bi{rright}</a>'
        '  <a href="?ACTION=moveup:$i"   title="move right">$bi{moveup}</a>'
        '  </div>'
      ));
    }
  }
  
  pq(qq(
    '</ol>'
    '<script>select_and_scroll();</script>'
  ));
  if ($akey or $gallery_test) {
    my $url = $ENV{REQUEST_URL};
    if ($url !~ /\/\./) {
      $url =~ s:\?.*:/: if $url =~ m:/public/gallery/:;
      print "<p>\nPublic URL: $url\n";
    }
  } else {
    my $zip = htmlencode(basename($fdir)).'.zip';
    print qq'<p>Download <a href="$dox?ACTION=zipit">$zip</a>\n';
  }
  exit;
}


sub collect_images {
  my $hdir = shift;
  my $reorder = shift;
  my $n = 0;
  my @images = ();
  my %images = (); # with order number
  local $_;
  
  opendir my $dir,'.' or http_die("$hdir - $!");
  while (defined($_ = readdir $dir)) {
    next if /\n/;
    next if -l;
    next if not $akey and excluded("$dir/$_");
    if (-f and -s) {
      $_ = untaint($_);
      # image with number prefix?
      if (/^\[(\d+)\].*\.($imgtype)$/i) {
        $images{$1} = $_;
        $n = $1 if $1 > $n;
      } elsif (/\.($imgtype)$/i) {
        push @images,$_;
      }
    }
  }
  closedir $dir;

  # pdftoppm xx.pdf | convert -thumbnail x128 -background white -alpha remove - xx.png
  
  @images = asort(@images);

  # add missing number prefix 
  if (@images and %images or $reorder) {
    foreach my $img (@images) {
      $n++;
      my $np = sprintf('%03d',$n);
      my $nimg = "[$np]$img";
      img_rename($img,$nimg);
      $images{$np} = $nimg;
    }
  }
  
  if (%images) {
    @images = ();
    foreach my $i (sort {$a <=> $b} keys %images) {
      push @images,$images{$i};
    }
    reorder(@images) if $reorder;
  }
  
  foreach (glob ".preview/browse/* .preview/gallery/*") {
    unlink untaint($_) unless -f basename($_);
  }
  
  unless (@images) { http_die("No images in $hdir") }
  return @images;
}


sub paselect {
  my $dir = shift;
  my @files = ();
  my $pkd = $dir;
  $pkd =~ s:/:/.pkeys/: or $pkd .= '/.pkeys';

  if (opendir $dir,$dir) {
    while (defined($_ = readdir $dir)) {
      next if /^[.#]/;
      my $file = "$dir/$_";
      next if excluded($file);
      push @files,$_ if -f $file and not -l $file;
    }
    close $dir;
  }

  http_header('200 OK');
  print html_header($head);
  pq(qq(
    '<html>'
    '<HEAD><TITLE>$dir</TITLE></HEAD>'
    '<body>'
    '<h1>Public URLs for <a href="/$doxo/$dir/">/$dir/</a></h1>'
    '<table border="1">'
    '<tr><th>file<th>URL action<th>URL</tr>'
  ));
  foreach my $file (asort(@files)) {
    my $pkey = readline1("$pkd/$file")||'';
    my $fu = "/$doxo/".urlencode("$dir/$file");
    print "<tr><td><code>$file</code><td>";
    if ($pkey) {
      print button("$fu?ACTION=puremove",'remove');
      my $purl = "$hosturl/$doxo/pkey=$pkey/".urlencode("$dir/$file");
      print qq'<td><a href="$purl">$purl</a>';
    } else {
      print button("$fu?ACTION=pucreate",'create');
      print "<td>";
    }
    print "</tr>\n";
  }
  pq(qq(
    '</table>'
    '<p>'
    '<a href="/$doxo/$folder?ACTION=pulist">show all public URLs</a>'
    'for folder <code>$folder</code>'
    '</body>'
    '</html>'
  ));
  exit;
}


sub pulist {
  my %pkf;
  local $_;

  foreach (find("$folder/.pkeys")) {
    if (-f and not -l) {
      my $pkf = $_;
      my $pkey = readline1($pkf);
      next if $pkey !~ /^\w+$/;
      s:/.pkeys/:/:;
      if (-f) {
        $pkf{urlencode($_)} = $pkey;
      } else {
        unlink untaint($pkf);
      }
    }
  }

  http_header('200 OK');
  print html_header($head);
  pq(qq(
    '<html>'
    '<HEAD><TITLE>$folder</TITLE></HEAD>'
    '<body>'
    '<h1>Public URLs for folder <a href="/$doxo/$folder/">/$folder/</a></h1>'
    '<table border="0">'
  ));
  foreach (asort(keys %pkf)) {
    print "<tr><td>",button("/$doxo/$_?ACTION=puremove",'remove');
    my $url = "${doxurl}pkey=$pkf{$_}/$_";
    print qq'<td><a href="$url"><code>$url</code></a></tr>\n';
  }
  pq(qq(
    '</table>'
    '</body>'
    '</html>'
  ));
  exit;
}


sub pucreate {
  my $file = shift;
  my $dir = dirname($file);
  my $pkf = $file;

  $pkf =~ s:/:/.pkeys/: or $pkf = ".pkeys/$file";
  $file = basename($file);

  mkdirp(dirname($pkf));
  open $pkf,'>',$pkf or http_die("cannot mkdir ".htmlencode($pkf)." - $!");
  print {$pkf} randstring(8)."\n";
  close $pkf;

  nvt_print(
    "HTTP/1.1 302 Found",
    "Location: /$doxo/$dir?ACTION=paselect",
    'Content-Length: 0',
    ''
  );
  &reexec;
}


sub puremove {
  my $file = shift;
  my $dir = dirname($file);
  my $pkf = $file;

  $pkf =~ s:/:/.pkeys/:; # or $pkf = ".pkeys/$file";

  unlink $pkf;

  $referer =~ /ACTION=(\w+)/;

  nvt_print(
    "HTTP/1.1 302 Found",
    "Location: /$doxo/$dir?ACTION=$1",
    'Content-Length: 0',
    ''
  );
  &reexec;
}


sub backup_cleanup {
  my $folder = normalize_folder(shift);
  my $current = readlink($folder) or return;

  foreach my $v (grep /^\Q$folder\E_$vp$/,glob "*") {
    if ($v ne $current and -d $v and -d "$v!backup") {
      rmrf(untaint("$v!backup"));
    }
  }
}


sub d3 {
  local $_ = shift;
  while (s/(\d)(\d\d\d\b)/$1,$2/) {};
  return $_;
}


sub http_date {
  my $file = shift;
  my @stat;

  if (@stat = stat($file)) {
    return strftime("%a, %d %b %Y %T GMT",gmtime($stat[9]));
  } else {
    return 0;
  }
}


# test if file is excluded (private)
sub excluded {
  my $file = shift;
  $file =~ s://+:/:;
  $file =~ s:^/::;
  $file =~ s:/$::;
  $file =~ s:^\Q$folder/::;
  foreach my $p (keys %exclude) {
    my $pp = $exclude{$p};
    $pp = '.*/'.$pp if $pp !~ m:^/:;
    return 1 if "/$file" =~ m:^$pp(/.*)?$:;
  }
}


sub reldir {
  local $_ = '/'.shift.'/';
  while (s:/\.\./:/__/:) {}
  s://+:/:g;
  m:/(.+)/:;
  return $1;
}


sub redirect {
  my $uri = urlencode(shift);

  $uri =~ s/%3F/?/g;
  $uri =~ s/%26/&/g;

  nvt_print(
    "HTTP/1.1 302 Found",
    "Location: $uri",
    'Content-Length: 0',
    ''
  );
  # control back to fexsrv for further HTTP handling
  &reexec;
}


sub doxlog {
  my $msg = shift;
  my $ra = $RA||'-';

  $ra .= '/'.$ENV{HTTP_X_FORWARDED_FOR} if $ENV{HTTP_X_FORWARDED_FOR};
  $ra =~ s/\s//g;
  $msg = sprintf("%s %s %s %s %s\n",isodate(time),$ra,$owner,$user,$msg);
  writelog('dox.log',$msg);
}


sub publishlog {
  my @files = @_;
  my @d = localtime time;
  my $log;
  local $_;

  mkdir "$folder/.upload";
  $log = "$folder/.upload/log";
  open $log,'>>',$log or return;
  flock($log,LOCK_EX);

  printf {$log}
    "\nPUBLISH %d-%02d-%02d %02d:%02d:%02d %s %s %s\n",
    $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0],
    $user,$ENV{REMOTE_HOST}||'-',$ENV{REMOTE_ADDR}||'.';
  foreach (asort(@files)) {
    s:/+:/:g;
    s:^\Q$folder/::;
    s:^\Q.upload/::;
    print {$log} "$1\n" if /(.+)/;
  }
  close $log;
}


sub showenv {
  http_header('200 OK');
  foreach my $v (asort(keys %ENV)) {
    printf "%s = '%s'\n",$v,$ENV{$v};
  }
}


# parse GET and POST requests
sub parse_request {
  my ($boundary);
  my $QS = $ENV{QUERY_STRING};
  local $_;

  # parse HTTP QUERY_STRING (parameter=value pairs)
  if ($QS) {
    $QS =~ s/\?/&/g if $QS !~ /&/ and $QS =~ /\?\w+=/;
    foreach (split '&',$QS) {
      if (s/^(\w+)=(.*)//) {
        my $p = uc($1);
        my $v = $2;
        # decode URL-encoding
        $v =~ s/%([a-f0-9]{2})/chr(hex($1))/gie;
        setparam($p,$v);
      }
    }
  }

  if ($ENV{REQUEST_METHOD} eq 'POST') {
    $SIG{ALRM} = sub {
      $SIG{__DIE__} = 'DEFAULT';
      die "TIMEOUT\n";
    };
    alarm($timeout);
    # binmode(STDIN,':raw');

    if (($ENV{CONTENT_TYPE}||'') =~ /boundary=\"?([^\s\";,]+)/) {
      $boundary = $1;
    } else {
      http_die("malformed HTTP POST (no boundary found)");
    }

    while (&nvt_read) {
      alarm($timeout);
      if (/^Content-Disposition:\s*form-data;\s*name="([a-z]\w*)"/i) {
        my $name = $1;
        my $data = '';
        nvt_skip_to('^\s*$');
        while (&nvt_read) {
          alarm($timeout);
          last if /^--\Q$boundary/;
          $data .= $_."\n";
        }
        setparam($name,$data);
      }
      last if /^--\Q$boundary--/;
    }
  }

  alarm(0);
}


# set CGI parameter variables
sub setparam {
  my ($v,$vv) = @_;
  my ($idf,$to);
  local $_;

  $v = uc(despace($v));

  chomp($vv);
  $PARAM{$v} = $vv;
  if ($v eq 'LOGOUT' and $akey) {
    unlink "$akeydir/$akey";
    my $login = $FEXHOME.'/cgi-bin/login';
    if (-x $login) {
      $login = readlink($login) || 'login';
      nvt_print(
        "HTTP/1.1 302 Found",
        "Location: $hosturl/$login",
        'Content-Length: 0',
        ""
      );
    } else {
      nvt_print(
        "HTTP/1.1 302 Found",
        "Location: $hosturl/fup",
        'Content-Length: 0',
        ""
      );
    }
    &reexec;
  } elsif ($v eq 'SUBMIT') {
    $submit = lc($vv);
  } elsif ($v eq 'DIRECTORY') {
    # $directory = reldir(decode_utf8($vv));
    $directory = reldir($vv);
  } elsif ($v eq 'DESTINATION') {
    # $destination = reldir(decode_utf8(urldecode($vv)));
    $destination = reldir(urldecode($vv));
  } elsif ($v eq 'PARENTDIR') {
    # $parentdir = reldir(decode_utf8(urldecode($vv)));
    $parentdir = reldir(urldecode($vv));
  } elsif ($v eq 'UPLOADDIR' and $vv =~ /^($mrx)$/) {
    $uploaddir = $1;
  } elsif ($v eq 'NEWDIR' and $vv =~ /^\s*([^\/]+?)\s*$/) {
    # $newdir = decode_utf8(urldecode($1));
    $_ = urldecode($1);
    s:[\\/]:_:g;
    $newdir = $_;
  } elsif ($v eq 'NEWFOLDER' and $vv =~ /^\s*(.+?)\s*$/) {
    $newfolder = normalize_folder($1);
  } elsif ($v eq 'NEWPREVIEW' and $vv =~ /^\s*(\d+)\s*$/) {
    $newpreview = $1;
  } elsif ($v eq 'MOVE_FROM' and $vv =~ /^\s*(\d+)\s*$/) {
    $move_from = $1;
  } elsif ($v eq 'MOVE_TO' and $vv =~ /^\s*(\d+)\s*$/) {
    $move_to = $1;
  } elsif ($v eq 'ALLOWPUBLISH' and $vv =~ /^($mrx)$/) {
    $allowpublish = $1;
  } elsif ($v eq 'ACTION' and $vv =~ /^([\w:]+)$/) {
    $action = $1;
  } elsif ($v eq 'MIRROR' and $vv =~ /\.[a-z]/i) {
    $mirror = urldecode($vv);
    $mirror =~ s/\s//g;
    $mirror =~ s/[<>|]/_/g;
  } elsif ($v eq 'FILE' and $vv =~ /^([^\/]+)$/) {
    # push @files,decode_utf8(urldecode($1));
    $_ = urldecode($1);
    s:[\\/]:_:g;
    push @files,$_;
  } elsif ($v eq 'RENAMEFROM' and $vv =~ /^\s*(.*?)\s*$/) {
    local $_ = $1;
    s:/:_:g;
    # push @renamefrom,decode_utf8(urldecode($_));
    push @renamefrom,urldecode($_);
  } elsif ($v eq 'RENAMETO' and $vv =~ /^\s*(.*?)\s*$/) {
    $_ = urldecode($1);
    s:[\n\r]: :g;
    s:[\\/]:_:g;
    # push @renameto,decode_utf8($_);
    push @renameto,$_;
  } elsif ($v eq 'FILEDATA') {
    $filedata = $vv;
  } elsif ($v eq 'AKEY' and $vv =~ /^(\w+)/) {
    $akey = $1 if -f "$akeydir/$1/@";
  } elsif ($v eq 'DESCRIPTION' and length($vv)) {
    $description = $vv;
  } else {
    http_die("unknown or empty parameter $v");
  }
}
