/* File system manager addon for srehttp/2
 
   MANAGER uses the (possibly host-specific) MANAGER.CFG files
   in the SREHTTP2\CFG directory (or subdirectories).  
   MANAGER.CFG contains a number of variables, including what
   directories one may access.

   Manager is a "system" utility, and is subject to several kinds of
   access controls
    1) If the SECURITY_LEVEL=0, MANAGER will not run
       (SECURITY_LEVEL is a SRE2003.CFG configuration variable).
    2) The user must have either SUPERUSER or MANAGER privileges
    3) The user ALSO must have a ?MANAGER:xxx "dynamic privilege" --
       he'll be asked to supply the "xxx" in a secondary logon

*/

/***************** User Configurable Parameters ***********/

/* duration of "dynamic passwords", in days (or fraction of days) */
pwd_duration=0.02

/* Name of "response file" to use for dynamic passwords. If blank, use
   the generic response file. */
respfile=''


/***************** End User Configurable Parameters ***********/


parse arg list,servername,verb,tempfile,,
          prog_file,reqnum,verbose,client_ip,privset,,
          uri,host_nickname,id_info,aiter,attribs

signal on error name badguys; signal on syntax name badguys
signal on novalue name badguys

if verb=" " then do
   say "This SREhttp/2 procedure is not meant to be run in standalone mode "
   exit
end  

/* is this guy allowed ? */
res=is_allowed()
if res<>'' then return res

/* read configuration file */
call read_cfg           /* allowed_dirs. is set */

res1=result
if res1<>'' then return res1    /* possible error */

if allowed_dirs.0=0 then do
   return 'String MANAGER.CFG does not list any allowed-directories.<br>Please edit MANAGER.CFG (in your SREHTTP2\CFG directory), and then re-run MANAGER '
end 
parse var uri manname '?' .
manname='/'||strip(manname,'l','/')

/* first call? */
if list='' then do
   call show_alldirs
   signal alldone
end 


/* is this an upload? */
call is_upload
if result<>0 then signal alldone

/* not an upload ... */

/* fill in varlist. */
alist=read_vars(list)

/* if varlist.!DIR not specified, then display list
   of all allowed_dirs */
ddir=''
if varlist.!DIR<>'' then do
  ddir=varlist.!dir
  if ddir='\' | ddir='/' then ddir=allowed_dirs.1
  ddir=translate(ddir,'\','/')
  ddir1=ddir||'\*.*'
end


if ddir<>'' then do
  varlist.!dir=ddir
  foo=sysfiletree(ddir1,'ddirfiles','FT')
  foo=sysfiletree(ddir1,'ddirdirs','DO')
end

/* write top of response file */

/* no arguments-- make the frameset */
varlist.!mode=translate(varlist.!mode)
select
  when list='' | varlist.!mode='FRAMESET' then do
      call make_frames
  end
   when varlist.!mode="DOWNLOADS" then do
      call do_downloads
  end 
  when varlist.!mode='SAVEFILE' then do
    call save_file
  end
  when varlist.!MIMEFILE<>'' & strip(varlist.!VIEW_TYPE)='ZIP' then do
     call show_zipfile
  end 
  when varlist.!INZIP<>'' then do 
    call send_zipfile
  end 
  when varlist.!UNZIPALL<>'' then do
     call unzip_zipfile
  end
  when varlist.!file<>'' | varlist.!mimefile<>'' then do
      call show_file  
      return rcode
  end  
  when translate(varlist.!mode)='TOC' then do
     call make_a_control
  end
  when varlist.!mode='DIRDO' then do
     call dirdo
  end
  when varlist.!mode='LIST' then do
      call make_list 0
  end 
  when varlist.!mode='EXT_LIST' then do
      call make_list 1
  end 
  when varlist.!mode='DATE_LIST' then do
      call make_list 2
  end 
  when varlist.!mode='NAME_LIST' then do
      call make_list 3
  end 

  when varlist.!mode="LOGON" then do
      call relogon
  end 
  when varlist.!mode='SHORTLIST' then do
      call make_short_list 0
  end 
  when varlist.!mode='EXT_SHORTLIST' then do
      call make_short_list 1
  end 
  when varlist.!mode='EXT_NAME_LIST' then do
      call make_short_list 3
  end 
  when varlist.!mode='EXT_DATE_LIST' then do
      call make_short_list 2
  end 

  when varlist.!mode='TREE' then do
       call make_tree
  end
  when varlist.!mode='TREECOMPACT' then do
       call make_tree_compact
  end
  when varlist.!mode='DOIT' & varlist.!EDIT=1 then do
    call editit
  end
  when varlist.!mode='DOIT' then do
     call make_doit1
     if result=1 then  call do_actions
  end
  when varlist.!mode='DOIT2' then do
      call cvt_actions
      call lineout tempfile,'<html><head><title>SREH2-FileManager </title></head>'
      call do_actions
  end
  otherwise do
    if ddir<>'' then
       call make_list
    else
       call show_alldirs
    signal alldone
  end 
end

/* all done creating output -- ship it */
alldone:
if rcode<>''  then return rcode
return 'FILE ERASE type text/html name 'tempfile



/***********************/
/* show list of all "accessible directories */
show_alldirs:

call lineout tempfile,'<html><head><title>SREH2-FileManager </title>'
call lineout tempfile,'</head>'

call lineout tempfile,'<body>'

/* jump row of jumps */
call lineout tempfile,'<a name="top"> </a> '
call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="'||manname||'?mode=frameset">Use frames version of MANAGER</a>  '
call lineout tempfile,'</font> <br>'

call lineout tempfile,'<table align="center"><tr><td bgcolor="tan"><font size=+1>SREH2-FileManager: choose a base directory </font></td></table>'

call lineout tempfile,'Choose one of the following base directories '
call lineout tempfile,'<em>These are set in MANAGER.CFG</em>'

call lineout tempfile,'<Ul>'
do mm=1 to allowed_dirs.0
   ba=make_dir_entry(allowed_dirs.mm)
   call lineout tempfile,ba
end 
call lineout tempfile,'</ul>'
call lineout tempfile,'</body></html>'
call lineout tempfile
return ' '


/***********************/
/* save an "edited" file */
save_file:

call lineout tempfile,'<html><head><title>SREH2-FileManager: save edited file </title>'
call lineout tempfile,'</head><body>'

call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="javascript:history.go(-1)">back</a><br>'
call lineout tempfile,'</font>'
call lineout tempfile,'<table align="middle"><tr ><td bgcolor="tan">'
call lineout tempfile,'<font size=+1>SREH2-FileManager: saving an edited file </font></td></table> '


/* do first file with COPY checked */
okay=1
this_dir=sre_packur(varlist.!DOIT_DIR)
this_dir=strip(translate(this_dir,'\','/'))

DO MGOG =1 TO 1

fuse=sre_Packur(varlist.!file)
if is_allowed_dir(fuse)=0 then leave

fname=get_filename(fuse)

/* save CONTENTS */
dastuff=varlist.!contents
okay=4

if dastuff='' then leave

okay=5
isold=stream(fuse,'c','query exists')
if varlist.!backup<>1 & isold<>'' then do
       foo=sysfiledelete(isold)
       if foo<>0 then leave
       call lineout tempfile,'Old file deleted: 'isold'<p>'
end 
if varlist.!backup=1 & isold<>'' then do
        arf=lastpos('.',isold); if arf=0 then arf=length(isold)
        bkname=left(isold,arf)||'???'
        bkname=dostempname(bkname)
        foo=dosrename(isold,bkname)
        okay=6
        if foo=0 then leave
        call lineout tempfile,'Old file renamed to: 'bkname'<p>'
end
   
foo=stream(fuse,'c','open write')
okay=7
if abbrev(translate(foo),'READY')<>1 then leave
okay=8
foo=charout(fuse,dastuff,1) 
foo2=stream(fuse,'c','close')
if foo>0 then leave
okay=0

errms.1='No file specifiled'
errms.2='No such directory '
errms.3='Not allowed to access this directory'
errms.4='No contents'
errms.5='Problem deleting old file' 
errms.6='Problem renaming old file' 
errms.7='Problem opening file for write '
errms.8='Problem writing contents to file '
if okay>0 then do
   call lineout tempfile,'<b>Error:</b>'errms.okay
end
else do
   call lineout tempfile,length(dastuff)' bytes saved to 'fuse
end 

leave

end             /* mm=1 to 1 */

call lineout tempfile,'<p><a href="'manname'?" target="_top">ReLoad Manager</a>'
ff=sre_packur(varlist.!THIS_URI)
call lineout tempfile,'<br><a href="'||ff||'">Go back to </a> '||sre_packur(varlist.!DOIT_DIR,1)

call lineout tempfile,'</body></html>'
call lineout tempfile
return 0


/***********************/
/* edit a file */
editit:


a_max_size_edit=max_size_edit
a_col_size_edit=col_size_edit
a_row_size_edit=row_size_edit
stuff=''
infuse=''

/* write file list */
call lineout tempfile,'<html><head><title>SREH2-FileManager: edit file </title>'
call lineout tempfile,'<script language="javascript">'
vvar=varlist.!dir
if vvar='' then vvar='/'
vvar=sre_packur_make(vvar,1)
call lineout tempfile,'var viewing="'vvar'"'
call lineout tempfile,'</script>'
call lineout tempfile,'</head><body>'

call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="javascript:history.go(-1)">back</a><br>'
call lineout tempfile,'</font>'
call lineout tempfile,'<table align="middle"><tr ><td bgcolor="tan">'
call lineout tempfile,'<font size=+1>SREH2-FileManager: edit a file </font></td></table> '

/* do first file with COPY checked */
okay=1
this_dir=sre_packur(varlist.!DOIT_DIR)
this_dir=strip(translate(this_dir,'\','/'))

do mmm=1 to varlist.!file.0
   extrax=strip(varlist.!DEST.mmM)
   if extrax=0 then iterate
   if varlist.!do.mmm<>'COPY' then iterate

   fuse=varlist.!file.mmm
   fname=get_filename(fuse)
   fuse=strip(this_dir,'t','\')||'\'fuse

   if is_allowed_dir(fuse)=0 then leave

   stuff=sre_read_file(fuse,3,5,1)
   infuse=length(stuff)
   okay=4
   if infuse=0 | infuse='' then leave
   okay=5
   if extrax<>'' then do
     parse var extrax mx1 mx2 mx3 .
     lb=sre_extract('LIMITBODY')
     if mx1='*' then mx1=(lb-1)
     if datatype(mx1)="NUM" then do
        a_max_size_edit=mx1*1000
     end 
     if datatype(mx2)='NUM' then do
        a_col_size_edit=mx2
     end 
     if datatype(mx3)='NUM' then do
        a_row_size_edit=mx3
     end 
   end 
   okay=7
   if infuse>a_max_size_edit then leave
   okay=0     /* okay=0 means "no error" */
   leave
end
if okay>0 then do       /* some kind of error */
   errms.1='No file specified'
   errms.3='Not allowed to access this directory'
   errms.2='No such directory'
   errms.4='No such file'
   errms.5='File inaccessible' 
   errms.6='Problem reading file '||LENGTH(STUFF)',' INFUSE
   errms.7='File too large:'||infuse' (max is 'a_max_Size_edit' bytes)'
   call lineout tempfile,'<b>Error:</b>'errms.okay
   call lineout tempfile,'</body></html>'
   call lineout tempfile
   return 0
end
thefile=sre_packur_make(fuse,1)
call lineout tempfile,'<form action="'manname'" method="POST">'
call lineout tempfile,'<input type="hidden" name="MODE" value="SAVEFILE">'
call lineout tempfile,'<input type="hidden" name="FILE" value="'||thefile||'">'
call lineout tempfile,'Edit 'fuse', and then '
call lineout tempfile,' <a href="#saveit">save it </a><p>'

call lineout tempfile,'<textarea ROWS='a_row_size_edit' COLS='a_col_size_edit' name="CONTENTS">'

/* adesc=sre_html_encode(stuff)  -- within textarea, no special html characters*/
adesc=stuff

call lineout tempfile,ADESC
call lineout tempfile,'</textarea>'
call lineout tempfile,'<a name="saveit"><br></a><input type="submit" value="Save it">'
call lineout tempfile,'<input type="checkbox" name="BACKUP" checked value=1>Rename old version'

call lineout tempfile,'<input type="hidden" name="THIS_URI" value="'||varlist.!THIS_URI||'">'
call lineout tempfile,'<input type="hidden" name="DOIT_DIR" value="'||varlist.!DOIT_DIR||'">'
call lineout tempfile,'</form>'

call lineout tempfile,'<p><a href="'manname'?" target="_top">ReLoad Manager</a>'
ff=sre_packur(varlist.!THIS_URI)
call lineout tempfile,'<br><a href="'||ff||'">Go back to </a> '||sre_packur(varlist.!DOIT_DIR,1)


call lineout tempfile,'</body></html>'
call lineout tempfile

return 0

  
/***********************/
/* logon again */
relogon:
authh=sre_reqfield('Authorization',,id_info)
aname=strip(translate(sre_extract_username(authh)))

if aname=strip(translate(varlist.!user)) then do
  realm_name=''
  if attribs<>'' then
     realm_name=sreh2_get_attributes(host_nickname,,,id_info,attribs)
  if realm_name='' then
     realm_name=sreh2_value('REALM_DEFAULT',,host_nickname)
  dodigest=sre_value('DIGEST_AUTH',,'SRE')-1    


  aa='<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
  aa=aa||"<html><head><title>Logon to MANAGER  </title>"
  aa=aa||'</head><body>'
  aa=aa||' <strong>To use MANAGER, please enter a (possibly new) username and password</strong> <pre>'
  aa=aa||'<br><a href="javascript:self.back()">back</a><br>'
  aa=aa||' </body> </html> '
  rcode=sre_auth_response(realm_name,servername,dodigest,aa,id_info)

end
call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 3.0//EN">'
call lineout tempfile, "<html><head><title>New user </title>"
call lineout tempfile, '</head><body>'
call lineout tempfile,' <strong>You are now logged on as: 'aname'</strong> <pre>'
call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
call lineout tempfile,'<a href="'manname'?mode=FRAMESET&time='time('s')'" target="_top">ReLoad MANAGER</a>'
call lineout tempfile,' </body> </html> '
call lineout tempfile


return 1

/****************/
/* figure out parent of this directory (or file)
   See if it's allowed */
up_dir:procedure expose allowed_dirs. rcode id_info
parse arg adir
ii=lastpos('\',adir)
if ii<2 then return ''
gdir=left(adir,ii-1)
if right(gdir,1)=':' then return ''
oo=is_allowed_dir(gdir)
if oo=0 then return ' '
return gdir


/***********************/
/* is this an allowed directory (or subdirectory of allowed directory)? */
is_allowed_dir:procedure expose allowed_dirs. rcode id_info tempfile
parse upper arg adir,noclose

if allowed_dirs.!0=1 then return 1  /* allowed_dirs * means "all directories allowed */
adir=translate(adir,'\','/')
adir=strip(strip(translate(adir)),'t','\')
do mm=1 to allowed_dirs.0
   if abbrev(adir,allowed_dirs.mm)=1 then return 1  /* under an allowed directory */
end
return 0


/***********************/
/* remove or search a directory */
dirdo:
call lineout tempfile,'<html><head><title>SREH2-FileManager:Dir Action</title></head>'
call lineout tempfile,'<BODY><h3>Directory Action </h3>'

thedir=translate(sre_packur(varlist.!dir),'\','/')
if is_allowed_dir(thedir)=0 then do 
     rcode=not_allowed_dir(thedir)
     return 1
end 
dirname=thedir

if wordpos(varlist.!diraction,'SEARCH REMOVE')=0 then do
   call lineout tempfile,' <b>Invalid action:</b> 'varlist.!diraction
   call lineout tempfile,'<br><a href="javascript:self.back()">Back</a><br>'
   call lineout tempfile,'</body></html>'
   call lineout tempfile
   return 1
end

if varlist.!diraction="REMOVE" & varlist.!CONFIRM<>1 then do
   foo=sysfiletree(dirname'\*.*','fls','FSO')
   foo=sysfiletree(dirname'\*.*','drs','DSO')

   call lineout tempfile,'<form action="'manname'" method="GET">'
   call lineout tempfile,'<INPUT type="hidden" name="DIRACTION" value="REMOVE">'
   call lineout tempfile,'<INPUT type="hidden" name="DIR" value="'varlist.!dir'">'
   call lineout tempfile,'<input type="hidden" name="MODE" value="DIRDO">'
   call lineout tempfile,'There are 'fls.0 ' files and 'drs.0' subdirectories under <tt>'dirname'</tt><p>'

   call lineout tempfile,'<input type="checkbox" value=1 name="CONFIRM">'
 
   call lineout tempfile,'Are you sure you want to remove: 'dirname
   call lineout tempfile,'<Input type="SUBMIT" value="Yes. Remove this directory">'
   call lineout tempfile,'<br><a href="javascript:self.back()">No. Go Back</a><br>'
   call lineout tempfile,'</form>'
   call lineout tempfile,'</body></html>'
   call lineout tempfile
   return 1
end /* do */

if varlist.!diraction='REMOVE' then do  /* remove this dir (confirm must be 1) */
   foo=sysfiletree(dirname'\*.*','fls','FSO')
   foo=sysfiletree(dirname'\*.*','drs','DSO')
   call lineout tempfile,'Deleting 'fls.0 ' files and 'drs.0' subdirectories under <tt>'dirname'</tt>'
   foo=del_dir(dirname)
   parse var foo a1 a2
   call lineout tempfile,'<p>'a1 ' files and subdirectories deleted ('a2 'failure)'
   call lineout tempfile,'<br><a href="javascript:history.go(-2)">Back to directory tree</a><br>'
   call lineout tempfile,'</body></html>'
   call lineout tempfile
   return 1
end /* do */

/* if here, must be SEARCH */ 
ss=strip(varlist.!string)
dirname2=strip(dirname,'t','\')'\'||strip(ss,'l','\')
oo=sysfiletree(dirname2,'dds','FOS')
call lineout tempfile,' # of matches to 'dirname2' :<b> 'dds.0'</b>'
call lineout tempfile,'<table>'
do mm=1 to dds.0
   yfile=filespec('n',dds.mm)
   oof0=sre_packur_make(dds.mm)
   call lineout tempfile,'<tr><td><a href="'manname'?file='oof0'" target="VIEWER"  >'yfile'</a> </td>'
   yogo=strip(filespec('d',dds.mm)||filespec('p',dds.mm),,'\')
   oof=sre_packur_make(yogo)
   call lineout tempfile,' <td>  <a href="'manname'?dir='oof'&Mode=LIST">'yogo'</a>'
   call lineout tempfile,' (<a href="'manname'?dir='oof'&Mode=SHORTLIST">s</a>)</td>'
end /* do */
call lineout tempfile,'</table>'

call lineout tempfile,'<br><a href="javascript:self.back()">BACK</a><br>'

call lineout tempfile,'</body></html>'
call lineout tempfile
return 1

/**************************/
/* delete a directory tree */
del_dir:procedure expose  allowed_dirs. manname  rcode id_info  tempfile
parse arg user_dir

rc=SysFileTree(user_dir,'dir_list', 'D')
IF dir_list.0 = 0  THEN return '0 0'

rc=SysFileTree(user_dir,'dir_list', 'BO', '****','----')

askdel=1
ndid=0 ; nbad=0
rc=SysFileTree(user_dir || '\*.*', 'dir_list', 'FSO')
DO x = 1 TO dir_list.0
 rc = SysFileDelete(dir_list.x)
 if rc=5 & askdel=1 then do      /* set to non readonly */
          if gotch=1 then do
              fop=doschmod(dir_list.x,,'R')
          end /* do */
          rc = SysFileDelete(dir_list.x)
  end
  if rc=0 then
     ndid=ndid+1
  else
    nbad=nbad+1

END

rc=SysFileTree(user_dir || '\*.*', 'dir_list', 'DSO')
DO x = dir_list.0 TO 1 BY -1
 rc=SysRmDir(dir_list.x)
 if rc=0 then
     ndid=ndid+1
 else
     nbad=nbad+1
END

DROP dir_list.
rc=SysRmDir(user_dir)
return ndid' 'nbad


/***********************/
/* deal with uploads */
is_upload:

conttype=sre_reqfield('Content-type',,id_info) 
/* IS IT A file upload ? */
if abbrev(upper(conttype),'MULTIPART/FORM-DATA')=0 THEN RETURN 0  /* nope */

DELRCtext.0='Error deleting.'
DELRCText.0 = 'File deleted successfully. '
DELRCText.2 = 'Error.  File not found. '
DELRCText.3 = 'Error.  Path not found. '
DELRCText.5 = 'Error.  Access denied. '
DELRCText.26 = 'Error.  Not DOS disk. '
DELRCText.32 = 'Error.  Sharing violation. '
DELRCText.36 = 'Error.  Sharing buffer exceeded. '
DELRCText.87 = 'Error.  Invalid parameter. '
DELRCText.206 = 'Error.  Filename exceeds range error. '


nparts=read_multipart_data(list,conttype)  /* parse into form_data. */

varlist.=''
varlist.0=''
do mm=1 to nparts
   aname=translate(form_data.!name.mm) ;aa='!'||aname
   if aname='' then iterate                     /* this should never happen */
   varlist.aa=form_data.mm
   varlist.0=varlist.0' 'aname
   if wordpos('FILENAME',form_data.!list.mm)>0 then do
        aname2=aname'.!ORIGNAME' ; aa='!'aname2
        varlist.aa=form_data.!filename.mm
        varlist.0=varlist.0' 'aname2
   end
end

destdir2=translate(varlist.!destdir,'\','/')
if is_allowed_dir(destdir2)=0 then do
  rcode=not_allowed_dir(destdir2)
  return 1
end

chkdir=destdir2
if pos('.',chkdir)>0 then chkdir=filespec('d',chkdir)||filespec('p',chkdir)
chkdir=strip(chkdir,'t','\')
if right(chkdir,1)=':' then chkdir=chkdir||'\'
aa=dosisdir(chkdir)
if aa=0 then do
  rcode=not_allowed_dir(destdir2,'<em>No such directory.</em>')
  return 1
end

call lineout tempfile,'<html><head><title>SREH2-FileManager: file upload</title></head>'
call lineout tempfile,'<BODY>'

/* jump row of jumps */
call lineout tempfile,'<a name="top"> </a> '
call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="javascript:history.go(-1)">back</a> || '
call lineout tempfile,'<a href="'||manname||'?" target="_top">Base DIRs</a>  '
call lineout tempfile,'</font> <br>'

call lineout tempfile,'<table align="center"><tr><td bgcolor="tan"><font size=+1>SREH2-FileManager: Uploading a file </font></td></table>'

call lineout tempfile,' Uploading to: <tt>'destdir2'</tt><p>'

if aa=0 then do
   call lineout tempfile,'<b> Sorry, no such directory! </b>'
   call lineout tempfile,'</body></html>'
   call lineout tempfile
   signal updone
end

do nn=1 to nparts
   if varlist.!contents.nn='' then iterate
   if varlist.!usename.nn=''  then varlist.!usename.nn=varlist.!contents.nn.!origname
   if varlist.!usename.nn='' then iterate
   toname=filespec('n',varlist.!usename.nn)
   if toname='' then iterate
   call lineout tempfile,' Creating file: <b>'toname '</b>,'
   call lineout tempfile,' w/length of 'length(varlist.!contents.nn)' bytes <p>'
 
   tryname=strip(destdir2,'t','\')'\'toname
   if validname(tryname)<>1 then do
        call lineout tempfile,' <br><b>Error: invalid name: 'tryname'<br>'
        call lineout tempfile,'</body></html>'
        call lineout tempfile
        signal updone
   end

  oof=stream(tryname,'c','query exists')
  if oof<>'' then do
      if varlist.!OVERWRITE.nn<>1 then do
         call lineout tempfile,'ERROR: file exists, and overwrite not enabled: 'tryname
         call lineout tempfile,'</body></html>'
         call lineout tempfile
         signal updone
      end 
      else do
         foo=sysfiledelete(tryname)
         if foo<>0 then do
           call lineout tempfile,'ERROR: unable to delete pre-existing file: 'tryname
           call lineout tempfile,'<br><tt>'||delrctext.foo||'</tt>'
           call lineout tempfile,'</body></html>'
           call lineout tempfile
           signal updone
         end
      end 
  end 

/*now, write it out */
   foo=stream(tryname,'c','open write')
   if abbrev(translate(foo),'READY')<>1 then do
        call lineout tempfile,' <br><b>Error: unable to open for write:'tryname'<br>'
        call lineout tempfile,'</body></html>'
        call lineout tempfile
        signal updone
    end
    oobly=charout(tryname,varlist.!contents.nn,1)
    foo=stream(tryname,'c','close')
    if abbrev(translate(foo),'READY')<>1 then do
        call lineout tempfile,' <br><b>Error: unable to complete write:'tryname'<br>'
        call lineout tempfile,'</body></html>'
        call lineout tempfile
        signal updone
    end
    call lineout tempfile,' <b> File successfully uploaded </b>'
end

updone:
call lineout tempfile,'<p><a href="'manname'?" target="_top">ReLoad Manager</a>'
ff=sre_packur(varlist.!THIS_URI)
call lineout tempfile,'<br><a href="'||ff||'">Go back to </a> '||sre_packur(varlist.!DOIT_DIR,1)

call lineout tempfile,'</body></html>'
call lineout tempfile
return 1



/****************/
/* show a file */
show_file:

ismime='OCTET'

if varlist.!MIMEFILE<>'' then do
  thedir=sre_packur(varlist.!DOIT_DIR)
  thedir=translate(thedir,'\','/')
  if is_allowed_dir(thedir)=0 then do 
     rcode=not_allowed_dir(thedir)
     return 1
  end 
  thefile0=translate(varlist.!mimefile,'\','/')
  ismime=varlist.!VIEW_TYPE
  thefile=strip(strip(thedir,'t','\')||'\'||thefile0)
end
else do
  thefile=translate(varlist.!file,'\','/')
  if is_allowed_dir(thefile)=0 then do 
     rcode=not_allowed_dir(thefile)
     return 1
  end 
end


foo=stream(thefile,'c','query exists')
if foo='' then do
  call lineout tempfile,'<html><head><title>SREH2-FileManager: no such file </title></head>'
  call lineout tempfile,'<BODY><h3>File not found </h3>'
  call lineout tempfile,'Sorry, could not find: 'varlist.!file
  call lineout tempfile,'</body></html>'
  call lineout tempfile
  iff=stream(tempfile,'c','query size')
  rcode=sre_command('FILE ERASE type text/html name 'tempfile,,id_info)
  return 1
end

ahdr=''
select
   when ismime='MIME' then  do
     atype=sreh2_get_mimetype(thefile,host_nickname,1)
   end
   when ismime='TEXT' then do
       atype='text/plain'
   end 
   when ismime='HTML' then do
        atype='text/html'
   end 
   otherwise do
     atype='application/octet-stream'
     fname=get_filename(thefile)
     ahdr='Content-disposition: attachment; filename="'fname'"'
   end
end
thefile='"'||thefile||'"'
rcode=sre_command('FILE nocache type 'atype 'name 'thefile,,id_info,,ahdr)
return 1

/****************/
/* do the actual DEL, MOVE, COPY */
do_actions:

DELRCtext.0='Error deleting.'
DELRCText.0 = 'File deleted successfully. '
DELRCText.2 = 'Error.  File not found. '
DELRCText.3 = 'Error.  Path not found. '
DELRCText.5 = 'Error.  Access denied. '
DELRCText.26 = 'Error.  Not DOS disk. '
DELRCText.32 = 'Error.  Sharing violation. '
DELRCText.36 = 'Error.  Sharing buffer exceeded. '
DELRCText.87 = 'Error.  Invalid parameter. '
DELRCText.206 = 'Error.  Filename exceeds range error. '

copyrctext.='Error copying.'
COPYRCtext.0 ='File copied successfully'
COPYRCtext.2 ='Error: source file not found '
COPYRCtext.3 ='Error: source or target path not found '
COPYRCtext.5 ='Error: target file exists but OVERWRITE was not specified '
COPYRCtext.32 ='Error: sharing violation for source or target file '
COPYRCtext.108 ='Error: source or target drive locked '
COPYRCtext.112 ='Error: disk full '
COPYRCtext.206 ='Error: invalid source or target file name '
COPYRCtext.267 ='Error: source name is a directory '
COPYRCtext.282='Error: extended attributes not supported for target '
 

moverctext.1='File moved successfully'
moverctext.0='Error moving file.'
moverctext.2='Error: can not move file to a different drive '
moverctext.3='Error: target directory does not exist'
moverctext.4='Error: file already exists'

doover='N'
if varlist.!overwrite=1 then doover='R'

downloadlist.0=0

call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="javascript:history.go(-1)">back</a><br>'
call lineout tempfile,'</font>'
call lineout tempfile,'<table align="middle"><tr ><td bgcolor="tan">'
call lineout tempfile,'<font size=+1>SREH2-FileManager: processing selected actions </font></td></table> '
call lineout tempfile,'<pre>'
do mm=1 to actions.0
    todo=actions.mm.!do
    thefile=translate(actions.mm.!file,'\','/')
    if is_allowed_dir(thefile)=0 then do
       call lineout tempfile,'No acces allowed to: 'thefile
       iterate
    end

    dest=actions.mm.!dest
    if todo='COPY' | todo='MOVE' then do
       if is_allowed_dir(dest)=0 then do
         rcode=not_allowed_dir(thefile,'Choose a different destination directory')
         call lineout tempfile,'COPY or MOVE 'thefile' to 'dest' failed: No access.'
         iterate
       end
    end
    if todo='DEL' then do
       foo=sysfiledelete(thefile)
       call lineout tempfile,'DEL 'thefile': 'delrctext.foo
    end 
    if todo='COPY' then do
       if is_allowed_dir(dest)=0 then return 1
       foo=doscopy(thefile,dest,doover)
       call lineout tempfile,'COPY 'thefile' to 'dest': 'copyrctext.foo
    end
    if todo='DOWNLOAD'  then do
      ndowns=downloadlist.0+1
      downloadlist.ndowns=actions.mm.!file
      downloadlist.0=ndowns
      call lineout tempfile,'DOWNLOAD... 'thefile ||' (pending)'
    end
    if todo='MOVE' then do
       ug=is_allowed_dir(dest)
       if ug=0 then return 1
       adr1=translate(filespec('d',thefile))
       adr2=translate(filespec('d',dest))
       foo=1
       if adr1<>adr2 then do
           foo=2
       end
       if foo=1 then do
          chkdir=dest
          if pos('.',chkdir)>0 then chkdir=filespec('d',chkdir)||filespec('p',chkdir)
          chkdir=strip(chkdir,'t','\')
          if right(chkdir,1)=':' then chkdir=chkdir||'\'
          aa=dosisdir(chkdir)
          if aa=0 then foo=3
       end 
       if foo=1 & pos('.',dest)=0 then do
           nm=filespec('n',thefile)
           dest=strip(dest,'t','\')'\'nm
       end 
       if stream(dest,'c','query exists')<>'' then  foo=4
       if foo=1 then  foo=dosrename(thefile,dest)
       if foo=1 then
         call lineout tempfile,'MOVE 'thefile' to 'dest ': 'moverctext.foo
      else
         call lineout tempfile,'MOVE 'thefile 'to ' dest ': 'moverctext.foo ' ('dest')'
    end 
end 
call lineout tempfile,'</pre>'
call lineout tempfile,'<a href="'manname'?" target="_top">ReLoad Manager</a>'
ff=sre_packur(varlist.!THIS_URI)
call lineout tempfile,'<br><a href="'||ff||'">Go back to </a> '||sre_packur(varlist.!DOIT_DIR,1)



if downloadlist.0>0 then do 
   call lineout tempfile,'<hr width="30%"><h3 align="center">'downloadlist.0 " files will be downloaded</h3> "
   call lineout tempfile,'<form action="'manname'" method="POST" target="VIEWER">'
   call lineout tempfile,'<input type="hidden" name="MODE" value="DOWNLOADS">'
   hh=''
   do iu=1 to downloadlist.0
      hh=hh','||sre_packur_make(downloadlist.iu,1)
   end /* do */
   call lineout tempfile,' <input type="hidden" name="FILELIST" value="'||hh||'">'
   call lineout tempfile,'<table><tr><td>'
   call lineout tempfile,'<select name="DOWNLOAD_TYPE" size=3>'
   call lineout tempfile,'<option value=1 selected>Download as SRE-multipart'
   call lineout tempfile,'<Option value=2>Download as multipart/mixed -- mimetype'
   call lineout tempfile,'<Option value=3>Download as multipart/mixed -- binary'

   call lineout tempfile,'</select> </td><td>'
   call lineout tempfile,'Note that SRE-multipart requires the <a href="DOMULTI.CMD">DoMulti.CMD</a> browser callable application'
   call lineout tempfile,'</td><tr><td>Delay=<input type="text" name="DELAY" value=5 size=5> '
   call lineout tempfile,'<br><font size="-1">(only used with multipart/mixed -- mimetype)</font></td>'
   call lineout tempfile,'<td><input type="SUBMIT" value="Start the Download">'
   call lineout tempfile,'</td></tr></table>'
   call lineout tempfile,'</FORM>'
end
call lineout tempfile,'</body></html>'
call lineout tempfile

return 1


/****************/
/* process input -- this is called upon first submission of del/move/copy choices */
make_doit1:

ACTIONS.=0
actions.0=0
ndownloads=0
this_dir=sre_packur(varlist.!DOIT_DIR)
this_dir=strip(translate(this_dir,'\','/'))

/* on any one call, only files in one directory are acted on -- the DOIT_DIR directory */
if is_allowed_dir(this_dir)=0 then do   /* even one transgression is fatal */
   rcode=not_allowed_dir(this_dir)
   return 1
end

/* write file list */
call lineout tempfile,'<html><head><title>SREH2-FileManager </title></head>'
call lineout tempfile,'<body>'
call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="javascript:history.go(-1)">back</a><br>'
call lineout tempfile,'</font>'
call lineout tempfile,'<table align="middle"><tr ><td bgcolor="tan">'
call lineout tempfile,'<font size=+1>SREH2-FileManager: selected actions </font></td></table> '

call lineout tempfile,'<ul>'
defdest=strip(translate(varlist.!defdest))

destds.=0
do mmm=1 to varlist.!file.0             /* check all destination directories */
   if varlist.!DO.mmm='' then iterate    /* no actions for this file */
   destd=strip(varlist.!DEST.mmM)
   select
      when destd=0 then iterate      /* 0 means " do nothing "*/
      when destd='' then do             /* use defdest */
         destd=defdest
      end
      when defdest='' then do
         if pos(':',destd)+pos('\',destd)=0 then do 
            destd=strip(this_dir,'t','\')||'\'||destd
         end
      end
      otherwise  do                       /* perhaps append defdest to destd? */
         if pos(':',destd)+pos('\',destd)=0 then do 
            destd=strip(defdest,'t','\')||'\'||destd
         end
      end
    end
/* check if destination directory needed, and if it is legit */
    doit=strip(translate(varlist.!do.mmm))
    if doit='COPY' | doit="MOVE" then do
      if destd<>'' then do                     
        if is_allowed_dir(destd)=0 then do         /* even one transgression is fatal */
          rcode=not_allowed_dir(destd,'<em>Choose a different  destination directory</em>')
          return 1
        end 
        chkdir=destd
        if pos('.',chkdir)>0 then chkdir=filespec('d',chkdir)||filespec('p',chkdir)
        chkdir=strip(chkdir,'t','\')
        if right(chkdir,1)=':' then chkdir=chkdir||'\'
        if dosisdir(chkdir)=0 then do
          rcode=not_allowed_dir(destd,'<em>The destination directory does not exist</em>')
          return 1
        end
      end                       /* destd specified */
      else do                   /* destd needed, but not specified */
        
          rcode=not_allowed_dir(destd,'<em>You did not specify a destination directory</em>')
          return 1
      end 
    end                 /* copy or move */

    destds.mmm=destd            /* we are alright */    
    destds.mmm.!action=doit

end

this_dir=translate(this_dir,'\','/')
do mmm=1 to varlist.!file.0             /* check all destination directories */
   fuse=varlist.!file.mmm
   fname=get_filename(fuse)
   fuse=strip(this_dir,'t','\')||'\'fuse

   destd=destds.mmm
   if destd=0 then  iterate        /* 0 means "skip this" */
   doit=destds.mmm.!action

   fname=get_filename(fuse)
   
   call lineout tempfile,'<li> 'doit' <tt>'fuse'</tt>'
   if doit='COPY' | doit="MOVE" then call lineout tempfile,' to <tt> ' destd '</tt>'
    if doit='DOWNLOAD' then ndownloads=ndownloads+1

    IF STREAM(fuse,'C','QUERY EXISTS')='' then DO
       call lineout tempfile,'<b>'||doit||' not attempted</b>. No such file: '||fuse
       iterate
    end 
    IAA=ACTIONS.0+1
    ACTIONS.IAA.!DO=DOIT
    ACTIONS.IAA.!FILE=translate(fuse,'/','\')
    ACTIONS.IAA.!DEST=DESTD
    ACTIONS.0=IAA
end

call lineout tempfile,'</ul>'
IF VARLIST.!VERIFY=1 then DO
 call lineout tempfile,'<form method="POST" action="'manname'">'
 call lineout tempfile,'<input type="hidden" name="MODE" value="DOIT2">'
 call lineout tempfile,'<input type="hidden" name="THIS_URI" value="'||varlist.!THIS_URI||'">'
 call lineout tempfile,'<input type="hidden" name="DOIT_DIR" value="'||varlist.!DOIT_DIR||'">'

 if varlist.!overwrite=1 then
   call lineout tempfile,'<input type="hidden" name="OVERWRITE" value=1>'
 call lineout tempfile,'<input type="hidden" name="ACTIONS.0" value='actions.0'>'
 do mm=1 to actions.0
   call lineout tempfile,'<input type="hidden" name="ACTIONS.'mm'.!DO" value="'actions.mm.!do'">'
   call lineout tempfile,'<input type="hidden" name="ACTIONS.'mm'.!FILE" value="'actions.mm.!file'">'
   call lineout tempfile,'<input type="hidden" name="ACTIONS.'mm'.!DEST" value="'actions.mm.!dest'">'
 end 
 call lineout tempfile,'<input type="hidden" name="ndownloads" value='ndownloads'>'
 call lineout tempfile,'<input type="submit" value="This is correct "><p>'
 call lineout tempfile,'If this is <b>not</b> correct, you can:'
 call lineout tempfile,'<ul>'
 call lineout tempfile,'<li> <a href="'manname'?" target="_top">ReLoad Manager </a>'
 ff=sre_packur(varlist.!THIS_URI)
 call lineout tempfile,'<li><a href="'||ff||'">Select files</a> from '||sre_packur(varlist.!DOIT_DIR,1)
 call lineout tempfile,'</ul>'
 call lineout tempfile,'</form>'
 call lineout tempfile,'</body></html>'
 call lineout tempfile
 return 0
end

return 1

/********************/
/* convert varlist.!actions... to actions. 
  This is called after a "verification submisstion" */
cvt_actions:
actions.0=varlist.!actions.0
actions.!destdir=varlist.!destdir
do mm=1 to varlist.!actions.0
   actions.mm.!DO=varlist.!actions.mm.!DO
   actions.mm.!FILE=varlist.!actions.mm.!FILE
   actions.mm.!DEST=varlist.!actions.mm.!DEST
end
return 


/****************/
/* show directory tree; allow choice */
make_Tree:

call lineout tempfile,'<html><head><title>SREH2-FileManager:Dir Tree </title></head>'
call lineout tempfile,'<body><h3 align="Center">Directory Tree</h3><p>'

call lineout tempfile,"<br>"

call lineout tempfile,'<FORM name="DIR_DO" action="'manname'" method="POST">'
call lineout tempfile,'<input type="HIDDEN" name="MODE" value="DIRDO">'
call lineout tempfile,'<table><tr><td>Choose an action: <br>'
call lineout tempfile,'<select size=3 name="DIRACTION">'
call lineout tempfile,'<option value="none" selected> ---- '
call lineout tempfile,'<option value="REMOVE">Remove Directory'
call lineout tempfile,'<option value="SEARCH">Search for a file'
call lineout tempfile,'</select>'
call lineout tempfile,'</td><td>Search for: <input type="text" name="STRING" size=40> </td>'
call lineout tempfile,'</table>'
call lineout tempfile,'<center><Input type="submit" value="...process"></center><p>'
CALL lineout tempfile,'<em>or choose a directory to list ...</em>'
  
do jj=1 to allowed_dirs.0 
   dlist2.=''
   tdir=allowed_dirs.jj
   aa=sysfiletree(tdir'\*.*','dlist','DoS')
   ltdir=length(tdir)+2
   do mm=1 to dlist.0
      adir=strip(dlist.mm)
      adir=translate(substr(adir,ltdir))
      dlist2.mm=sre_packur_make(strip(adir,,'\'),1)
  end
  dlist2.0=dlist.0

  if dlist2.0>0 then foo=arraysort('dlist2') 

  call lineout tempfile,'<hr width="66%">' 

  call lineout tempfile,'<font size="+1">There are 'dlist.0' subdirectories under 'tdir'</font>,'
  foo=make_tree2(tdir)
end
call lineout tempfile,'<INPUT type="SUBMIT" value="Process ..."></form>'
call lineout tempfile,'</body></html>'
call lineout tempfile

return 1


/*******************/
/* table of dir entries */
make_Tree2:procedure expose dlist2. tempfile allowed_dirs. tdir manname  rcode id_info 
parse arg tdir

tdir0=strip(tdir,,'\')
tdirp0=sre_packur_make(tdir0,1)
tdirp=tdirp0||'%5c'

call lineout tempfile,'<table>'

chk=tdir0||'\*.*'
oink=sysfiletree(chk,'gg','OF')

aba='<input type="radio" name="DIR" value="'||tdirp0||'">'
call lineout tempfile,'<tr><td>'aba' </td><td><a href="'manname'?dir='||tdirp0||'" '
call lineout tempfile,' target="main_frame"> <font size="+1">'||tdir0||'</font></a>'
call lineout tempfile,' <em>('||gg.0||' files) </em></td>'

do mm=1 to dlist2.0
   adir=dlist2.mm
   if adir='' then iterate

   a1=sre_packur(adir)

   a1t=strip(translate(a1,' ','\'))
   a1use=word(a1t,words(a1t))
   apre=copies('&nbsp',2*words(a1t)-1)

   realdir=tdirp||adir

   aba='<input type="radio" name="DIR" value="'||realdir||'">'

   call lineout tempfile,'<tr><td>'aba' </td>'

   lref=' <a href="'manname'?dir='||realdir||'" target="main_frame">'||a1use||'</a>'
   lrefs=' <a href="'manname'?mode=SHORTLIST&dir='||realdir||'" target="main_frame">[c]</a> '

   chk=sre_packur(realdir)||'\*.*'
   oink=sysfiletree(chk,'gg','OF')

   alin=apre||lref||lrefs||' <em>('||gg.0||')</em>'
   call lineout tempfile,'<td>'||alin||'</td>'

end
call lineout tempfile,'</table>'
return 0


/****************/
/* show directory tree; allow choice */
make_Tree_compact:

call lineout tempfile,'<html><head><title>SREH2-FileManager: Show Compact Dir </title></head>'
call lineout tempfile,'<body><b>Directory Tree:</b>'
call lineout tempfile,'<font size="-1">'servername'<p>'

do jj=1 to allowed_dirs.0 
   dlist2.=''
   tdir=allowed_dirs.jj
   aa=sysfiletree(tdir'\*.*','dlist','DoS')
   ltdir=length(tdir)+2
   do mm=1 to dlist.0
      adir=strip(dlist.mm)
      adir=translate(substr(adir,ltdir))
      dlist2.mm=sre_packur_make(strip(adir,,'\'),1)
  end
  dlist2.0=dlist.0

  if dlist2.0>0 then foo=arraysort('dlist2') 

  foo=make_tree_compact2(tdir)

  call lineout tempfile,'<hr width="50%">'
end
call lineout tempfile,'</font></body></html>'
call lineout tempfile

return 1


/***************/
/* display a "compact" directory list, of the dlist2. stem */
make_tree_compact2:procedure expose dlist2. tempfile  allowed_dirs. tdir manname  rcode id_info
parse arg tdir

tdir0=strip(tdir,,'\')
tdirp=sre_packur_make(tdir0,1)
call lineout tempfile,'<a href="'||manname||'?dir='||tdirp||'" target="main_frame">'||tdir0||' </a> '
tdirp=tdirp||'%5c'
call lineout tempfile,'<pre>'


do mm=1 to dlist2.0
   adir=dlist2.mm
   a1=sre_packur(adir)
   a1t=strip(translate(a1,' ','\'))
   a1use=word(a1t,words(a1t))
   apre=copies('&nbsp',2*words(a1t)-1)
   realdir=tdirp||adir
   if adir='' then iterate
   lrefs=' <a href="'manname'?mode=SHORTLIST&dir='||realdir||'" target="main_frame">[c]</a> '
   lref=' <a href="'manname'?dir='||realdir||'" target="main_frame">'||a1use||'</a>'
   alin=apre||lref||lrefs
   call lineout tempfile,alin       
end 
   
call lineout tempfile,'</pre>'
return 1


/****************/
/* make a control panel frame */
make_a_control:
crlf='0d0a'x

authh=sre_reqfield('Authorization',,id_info)
aname=strip(translate(sre_extract_username(authh)))

aout=' onMouseOut="window.status=''The SREH2-FileManager Control Panel'' ; return true " '

call lineout tempfile,'<html><head><title>SREH2-FileManager: control panel </title>'
call lineout tempfile,'<script language="javascript">'
call lineout tempfile,'function Open_viewtree(isblur)'
call lineout tempfile,'{daVIEWTREE=window.open("'manname'?mode=TREECOMPACT","VIEWTREE",',
                     '"location=NO,MENUBAR=NO,RESIZABLE,DEPENDENT,SCROLLBARS,STATUS=NO,TITLEBAR,TOOLBAR=NO,SCREENX=12,SCREENY=30,height=440,width=200")'
call lineout tempfile,' var openVIEWTREE=1  '
call lineout tempfile, 'if (isblur==1) ; {daVIEWTREE.blur() }'
call lineout tempfile,' }'                    
call lineout tempfile,' '
call lineout tempfile,'function dolist(ltype,ii) {'
call lineout tempfile,'adir=parent.main_frame.viewing;'
call lineout tempfile,'if (ii==1)'
call lineout tempfile,'{gto="'manname'?mode=TREECOMPACT"'
call lineout tempfile,'  daVIEWTREE.location=gto}'
call lineout tempfile,' else {'
call lineout tempfile,'gto="'manname'?&mode="+ltype+"&dir="+adir'
call lineout tempfile,'gto2="http://"+window.location.hostname+gto'
call lineout tempfile,'top.main_frame.location.href=gto2 }'
call lineout tempfile,'}'
call lineout tempfile,'Open_viewtree(1) '
call lineout tempfile,'</script>'

call lineout tempfile,'</head>'
call lineout tempfile,'<body><nobr><b>Control Panel</b></nobr><br>'
call lineout tempfile,'<font size="-1"> Key: </font><br>'
call lineout tempfile,'<table><tr><td bgcolor="'delcolor'"><font size="-1">Del</font></td>' 
call lineout tempfile,'<td bgcolor="'movecolor'"><font size="-1">Move</font></td>'
call lineout tempfile,'<td bgcolor="'copycolor'"><font size="-1">Copy</font></td>'
call lineout tempfile,'<td bgcolor="'downloadcolor'"><font size="-1">Down</font></td></table></font><br>'


astatus=aout||' onMouseOver="window.status='||"'"||' ... make the changes '||"'"||';return true "'
call lineout tempfile,'<a href="javascript:parent.main_frame.location.hash=''DOSUBMIT2''; void(0)"'||astatus||' >Submit!</a><br>'

astatus=' onMouseOver="window.status='||"'"||'[current user: 'aname'] :: Logon as a different user (you may need to first reload this frame)'||"'"||';return true "'
call lineout tempfile,'<a href="'manname'?mode=logon&user='aname'" target="main_frame" 'astatus' >Logon</a><p>'

onc=' onCLick="Open_viewtree(); daVIEWTREE.focus() ; return true "'
astatus=onc||aout||' onMouseOver="window.status='||"'"||'Display compact directory in separate window'||"'"||' ;return true"'
call lineout tempfile,'<nobr><a href="javascript:dolist('||"'"||'TREECOMPACT'||"'"||',1) ; void(0)"'
call lineout tempfile,astatus||'>[c]</a>'

astatus=aout||' onMouseOver="window.status='||"'"||'Display directory in main frame'||"'"||' ;return true "'
call lineout tempfile,'<a href="'manname'?mode=TREE" target="main_frame"||'astatus||'>DirTree</a></nobr><p>'

astatus=aout||' onMouseOver="window.status='||"'"||'Jump to file section of main frame'||"'"||' ;return true "'
call lineout tempfile,'<a href="javascript:parent.main_frame.location.hash=''FILELIST''; void(0)"'||astatus||'>Files</a><br>'

astatus=aout||' onMouseOver="window.status='||"'"||'Jump to subdirectories section of main frame'||"'"||' ;return true "'
call lineout tempfile,'<a href="javascript:parent.main_frame.location.hash=''DIRLIST''; void(0)"'||astatus||' >SubDirectories</a><br>'

astatus=aout||' onMouseOver="window.status='||"'"||'Jump to file upload section of main frame'||"'"||' ;return true "'
call lineout tempfile,'<a href="javascript:parent.main_frame.location.hash=''UPLOADS''; void(0)"'||astatus||' >Upload</a><br>'

astatus=aout||' onMouseOver="window.status='||"'"||'Jump to help section of main frame'||"'"||' ;return true "'
call lineout tempfile,'<a href="javascript:parent.main_frame.location.hash=''dohelp''; void(0)"'||astatus||' >Tips &amp; tricks</a><p>'


goose="var tmp1='List of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,'<a href="javascript:dolist('||"'"||'LIST'||"'"||') ; void(0)"'||astatus||'>List</a> &nbsp;'

goose="var tmp1='Extension sorted list of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,' (<a href="javascript:dolist('||"'"||'EXT_LIST'||"'"||') ; void(0)"'||astatus||'>e</a>'

goose="var tmp1='Date sorted list of files in  ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,' <a href="javascript:dolist('||"'"||'DATE_LIST'||"'"||') ; void(0)"'||astatus||'>d</a>'

goose="var tmp1='Name sorted list of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,' <a href="javascript:dolist('||"'"||'NAME_LIST'||"'"||') ; void(0)"'||astatus||'>n</a>)<br>'

goose="var tmp1='Compact list of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,'<nobr><a href="javascript:dolist('||"'"||'SHORTLIST'||"'"||') ; void(0)"'||astatus||'>QuickList</a>&nbsp;'

goose="var tmp1='Extension sorted, compact list of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,' (<a href="javascript:dolist('||"'"||'EXT_SHORTLIST'||"'"||') ; void(0)"'||astatus||'>e</a>'

goose="var tmp1='Date sorted, compact list of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,' <a href="javascript:dolist('||"'"||'EXT_DATE_LIST'||"'"||') ; void(0)"'||astatus||'>d</a>'

goose="var tmp1='Name sorted, compact list of files in ' + unescape(parent.main_frame.viewing) ; window.status=tmp1 ;return true  "
astatus=aout||' onMouseOver="'||goose||'"'
call lineout tempfile,' <a href="javascript:dolist('||"'"||'EXT_NAME_LIST'||"'"||') ; void(0)"'||astatus||'>n</a>)<br>'


call lineout tempfile,'<p><a href="/sre2k/srehttp2/manager.txt" target="VIEWER">Documentation</a>'

call lineout tempfile,'</body></html>'
call lineout tempfile

return 0


/****************/
/* make the frameset */
make_frames:

call lineout tempfile,'<html><head><title>The SREH2-FileManager </title></head>'
call lineout tempfile,'<frameset name="THEMANAGER" cols="15%,*" >'
    call lineout tempfile,'  <frame src="'manname'?mode=toc" name="toc_frame">'
    call lineout tempfile,'  <frame src="'manname'?mode=list&dir=/" name="main_frame">'
call lineout tempfile,'<noframes>'
call lineout tempfile,'This is the <b>frame</b> version of the SREhttp/2 file manager.'
call lineout tempfile,'If you are seeing this message, your browser does not'
call lineout tempfile,'support frames -- try the <a href="'manname'?mode=list" target="_top"> non-frames version </a>'
call lineout tempfile,'</noframes>'
call lineout tempfile,'</frameset>'
call lineout tempfile,'</body></html>'
call lineout tempfile
return 0


/***********************/
/* write a del/move/copy enabled list of files and directories */
make_list:
parse arg sortext


if is_allowed_dir(ddir)=0 then do
   rcode=not_allowed_dir(ddir)
   return 1
end
                             
/* write file list */
call lineout tempfile,'<html><head><title>SREH2-FileManager </title>'
call lineout tempfile,'<script language="javascript">'
vvar=varlist.!dir
if vvar='' then vvar='/'
vvar=sre_packur_make(vvar,1)
call lineout tempfile,'var viewing="'vvar'"'
call lineout tempfile,"var  openargs='scrollbars=yes,resizable=yes,screenX=50,screenY=50,innerWidth=500,toolbar=no,directories=no,dependent=yes' ;" 

call lineout tempfile,''
call lineout tempfile,'function gob(jj) '
call lineout tempfile,'{fooo="" ;'
call lineout tempfile,'for (var i=0 ; i<document.DO_MANAGER.elements.length ; i++  ) '
call lineout tempfile,'{'
call lineout tempfile,'   notchecked=document.DO_MANAGER.elements[i].checked ;'
call lineout tempfile,'  if (!notchecked) {continue} ;'
call lineout tempfile,'   elname=document.DO_MANAGER.elements[i].name ;'
call lineout tempfile,'   elname2=elname.substr(0,3);'
call lineout tempfile,'   if ( elname2 != "do." ) { continue } ;'
call lineout tempfile,'   eact=document.DO_MANAGER.elements[i].value ;'
call lineout tempfile,'   if ( eact != "COPY" ) { continue } ;'
call lineout tempfile,'   i2=elname.substr(3); '
call lineout tempfile,'   fooo=eval(''document.DO_MANAGER.elements["FILE.''+i2+''"].value'');'
call lineout tempfile,'   document.DO_MANAGER.dasubmit.value="Edit "+fooo;'
call lineout tempfile,'   document.DO_MANAGER.DEFDEST.value="def dest-dir not used in edit mode" ;'
call lineout tempfile,'   document.DO_MANAGER.destbutton.value=''Max_size  #Cols  #Rows'' ;'
call lineout tempfile,'  break;'
call lineout tempfile,'}   // for'
call lineout tempfile,' if (fooo=="") {alert("You need to chose which file to edit (by clicking its COPY button)")'
call lineout tempfile,'   document.DO_MANAGER.EDIT.checked=0 ;}'
call lineout tempfile,'}  // function'

/* and the viewer function */
call lineout tempfile,'function dovu(vname,istype) {'
call lineout tempfile," t1='"||manname||'?mimefile='' + vname ;'
call lineout tempfile," t1=t1 + '&DOIT_DIR=' + document.DO_MANAGER.DOIT_DIR.value ;"
call lineout tempfile,' if (istype!=undefined) {jv=istype} else '
call lineout tempfile,' {jis=document.DO_MANAGER.VIEW_TYPE.selectedIndex ;'
call lineout tempfile,' if (jis<0) {jis=0};'
call lineout tempfile,' jv=document.DO_MANAGER.VIEW_TYPE.options[jis].value}  ;'
call lineout tempfile," t1=t1 + '&VIEW_TYPE=' + jv ;"
call lineout tempfile,"gpw=window.open(t1,'VIEWER',openargs); gpw.focus();  "
call lineout tempfile,''
call lineout tempfile,''

call lineout tempfile,'}  // end of dovu'


call lineout tempfile,'</script>'
call lineout tempfile,'</head>'

aaupdir=up_dir(ddir)

call lineout tempfile,'<body>'

/* jump row of jumps */
call lineout tempfile,'<a name="top"> </a> '
call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="'||manname||'?" target="_top">Base DIRs</a>  '
if ddirdirs.0>0 then
   call lineout tempfile,' || <a href="#DIRLIST" >SubDIRs</a> '
if aaupdir<>'' then do
  baa=make_dir_entry(aaupdir,'..',1)
  call lineout tempfile,' || '||baa
end
call lineout tempfile,' || <a href="#doupload">UpLoad</a> '
if varlist.!NOHELP<>1 then call lineout tempfile,' || <a href="#dohelp">Help</a> '
call lineout tempfile,'</font> <br>'

call lineout tempfile,'<table align="center"><tr><td bgcolor="tan"><font size=+1>SREH2-FileManager: Display a directory </font></td></table>'

call lineout tempfile,'<form name="DO_MANAGER" method="POST" action="'manname'">'
call lineout tempfile,'<input type="hidden" value="DOIT" name="mode">'

call lineout tempfile,'<input type="hidden" value="'||sre_packur_make(ddir,1)||'" name="DOIT_DIR">'
call lineout tempfile,'<input type="hidden" value="'||sre_packur_make(uri,1)||'" name="THIS_URI">'

call lineout tempfile,'<input type="hidden" name="FILE.0" value="'ddirfiles.0'">'

call lineout tempfile,' <tt><a name="FILELIST">'ddirfiles.0' </tt> files in <b>'||ddir'</b></a></b></font>,'
call lineout tempfile,' and 'ddirdirs.0' <a href="#DIRLIST"> subdirectories</a> <p>'

call lineout tempfile,' '

call lineout tempfile,'<table border=2> <tr><td><input type="checkbox" name="VERIFY" value=1 checked>Verify?</td>'
call lineout tempfile,'<td><input type="checkbox" name="OVERWRITE" value=1 checked>Overwrite?</td>'
call lineout tempfile,'<td><nobr>Default destination-directory:</nobr></a><input type="text" name="DEFDEST" size=36></td>'
call lineout tempfile,'<tr><td >'

call lineout tempfile,'<input type="checkbox" name="EDIT" value=1 '
call lineout tempfile,'onClick=" ;'
call lineout tempfile,'  if (this.checked) { '
call lineout tempfile,'      gob(1) ;'
call lineout tempfile,'   } '
call lineout tempfile,'   else {'
call lineout tempfile,'      document.DO_MANAGER.dasubmit.value=''   Make the changes     ''; '
call lineout tempfile,'      document.DO_MANAGER.destbutton.value=''       Destination  '' ;'
call lineout tempfile,'      document.DO_MANAGER.DEFDEST.value='' '' '
call lineout tempfile,'   } '
call lineout tempfile,' ; return true">Edit?</td>'
call lineout tempfile,'<td >View&nbsp;<select name="VIEW_TYPE" >'
call lineout tempfile,'<option value="MIME" selected>using mimetype'
call lineout tempfile,'<option value="TEXT" >As plain-text'
call lineout tempfile,'<option value="HTML" >As html'
call lineout tempfile,'<option value="ZIP" >As ZIP file'

call lineout tempfile,'</select>'
call lineout tempfile,'<td><input type="reset" value="reset"> '
call lineout tempfile,'<a name="DOSUBMIT2"><input name="dasubmit" type="submit" value="make the changes    "></a><br></td></table>'

call lineout tempfile,' '
call lineout tempfile,'<table padding=0><tr><td>'
call lineout tempfile,'<table width="100%"><tr><td bgcolor="'delcolor'">Del</td>' 
call lineout tempfile,'<td bgcolor="'movecolor'">Move</td>'
call lineout tempfile,'<td bgcolor="'copycolor'">Copy</td>'
call lineout tempfile,'<td bgcolor="'downloadcolor'">Down</td></table></td>'

call lineout tempfile,'<td><a name="headerline">Name</a></td> <td width="10%">Date &amp; Size</td> '
call lineout tempfile,'<td bgcolor="#5aedf9" align="left">'

call lineout tempfile,'<input type="button" name="destbutton" value="     Destination     ">'
call lineout tempfile,'<tr> <td colspan=4><hr></td>'

if sortext=1 then do
   do mm=1 to ddirfiles.0
      ff=lastpos('.',ddirfiles.mm)
      if ff=0 then 
         aext=''
      else
         aext=translate(substr(ddirfiles.mm,ff+1))
      ext=translate(left(aext,20))
      ddirfiles.mm=ext||ddirfiles.mm
   end
   if ddirfiles.0>0 then foo=arraysort('ddirfiles')
   do mm=1 to ddirfiles.0
       ddirfiles.mm=substr(ddirfiles.mm,21)
   end
end 

if sortext=2 then do
   do mm=1 to ddirfiles.0
      ff=strip(word(ddirfiles.mm,1))
      if left(ff,2)<70 then
        ff='20'||ff
      else
        ff='19'||ff
      ff=translate(left(ff,20))
      ddirfiles.mm=ff||ddirfiles.mm
   end
   if ddirfiles.0>0 then foo=arraysort('ddirfiles')
   do mm=1 to ddirfiles.0
       ddirfiles.mm=substr(ddirfiles.mm,21)
   end
end 

if sortext=3 then do
   do mm=1 to ddirfiles.0
      ff=strip(word(ddirfiles.mm,words(ddirfiles.mm)))
      ff=filespec('n',ff)
      parse var ff ff '.' .  
      ff=translate(left(ff,20))
      ddirfiles.mm=ff||ddirfiles.mm
   end 
   if ddirfiles.0>0 then foo=arraysort('ddirfiles')
   do mm=1 to ddirfiles.0
       ddirfiles.mm=substr(ddirfiles.mm,21)
   end
end 

do mm=1 to ddirfiles.0
    aa=make_file_entry(ddirfiles.mm,mm)
    call lineout tempfile,aa
end
call lineout tempfile,'</table>'

call lineout tempfile,'<a name="DIRLIST"><hr width="20%"></a>'

/*
call lineout tempfile,'<br><input type="reset" value="reset"> &nbsp;<input type="submit" value="make the changes    ">'
*/

call lineout tempfile,'<h3> <a name="DIRLIST2">' ddirdirs.0 ' SubDirectories under 'ddir'</a></h3>'
call lineout tempfile,'<ul>'

/* check to see if you can show a .. directory link */
aaupdir=up_dir(ddir)
if aaupdir<>'' then do
  baa=make_dir_entry(aaupdir,'..')
  call lineout tempfile,baa
end

do mm=1 to ddirdirs.0
   aa=make_dir_entry(ddirdirs.mm)
   call lineout tempfile,aa
end
call lineout tempfile,'</ul>'
call lineout tempfile,'</form>'

foof=ddir

call lineout tempfile,'<FORM name="BFORM" enctype="multipart/form-data" ACTION="'manname'" METHOD="post" >'
call lineout tempfile,'<input type="hidden" name="destdir" value="'foof'">'
call lineout tempfile,'<a name="UPLOADS"><hr width="73%"></a>'
call lineout tempfile,'<a name="doupload"><h3> Upload a file to: 'ddir'</h3></a>'
call lineout tempfile,'<input type="hidden" value="'||sre_packur_make(ddir,1)||'" name="DOIT_DIR">'
call lineout tempfile,'<input type="hidden" value="'||sre_packur_make(uri,1)||'" name="THIS_URI">'
call lineout tempfile,'File to upload:<INPUT TYPE="file" size=35  name="CONTENTS.1"><br>'
call lineout tempfile,'<br>Use name: <input type="text" name="usename.1"><em>leave empty to use "own name"</em>'
call lineout tempfile,'<br><input type="checkbox" name="overwrite.1" value=1><em>Overwrite?</em>'

call lineout tempfile,''
call lineout tempfile,'<br><input type="reset" value="reset"> &nbsp;<input type="submit" value="Upload the file">'
call lineout tempfile,'</form>'

if varlist.!NOHELP=1 then do
  call lineout tempfile,'<p><font size=-1><a href="#top">top</a></font>'
  call lineout tempfile,'</body></html>'
  call lineout tempfile,''
  call lineout tempfile
  return 0
end

call lineout tempfile,'<a name="dohelp"> <hr width="50%"></a>'
call lineout tempfile,'<h4>Tips and Tricks</h4>'
call lineout tempfile,'<dl>'
call lineout tempfile,'<dt>Overwrite'
call lineout tempfile,'<dd>If  checked, COPY operations will overwrite'
call lineout tempfile,'pre-existing files. <br>If not checked, COPY operations will fail'
call lineout tempfile,'<dt>Verify'
call lineout tempfile,'<dd>If checked, you will be presented with a list of operations,'
call lineout tempfile,'and asked to verify them. <br>This is a useful double check, to make sure'
call lineout tempfile,'you made no egregious mistakes.'

call lineout tempfile,'<dt>Edit file'
call lineout tempfile,'<dd>If checked, then the <b>first</b> file with a <tt>COPY</tt> box'
call lineout tempfile,'checked will be returned to you for editing.<br> Editing is done within a  '
call lineout tempfile,'&lt;TEXTAREA&gt; box in an HTML form -- so you can''t make '
call lineout tempfile,'fancy changes, nor can you edit a large file.'

call lineout tempfile,'<dt> Default Destination directory'
call lineout tempfile,'<dd>The target directory for move and copy operations '
call lineout tempfile,'<br>This is used in MOVE and COPY operations.'
call lineout tempfile,'<br>You can override it on a file specific basis.'
call lineout tempfile,'<br><Em>Special Feature:</em><menu> <li type="disc"> if you are <b>Editing</b>'
call lineout tempfile,'a file, you can use the <tt>destination</tt> field to specify the'
call lineout tempfile,'<br>&nbsp;&nbsp;&nbsp; <tt>max_size #_columns #_rows</tt>'
call lineout tempfile,'<br>where a <tt>max_size</tt> of <tt>*</tt> means <em>use server''s LIMITBODY value</em>,'
call lineout tempfile,'<br> and <tt>#_columns</tt> and <tt>#_rows</tt> describe the size of the TEXTAREA box used for editing'
call lineout tempfile,'<br>Note: the default values are: '
call lineout tempfile,'<tt>'max_size_edit||' '||col_size_edit||' '||row_size_edit||'</tt>'
call lineout tempfile,'</menu>'

call lineout tempfile,'<dt>Del / Move / Copy / Down '
call lineout tempfile,'<dd>You can select one of these actions for one, or more, files:'
call lineout tempfile,'<table>'
call lineout tempfile,'<tr><td  bgcolor="'delcolor'">Del </td><td> delete the file</td>'
call lineout tempfile,'<tr><td  bgcolor="'movecolor'"> Move </td><td>  move the file to a destination directory '
call lineout tempfile,'<br><em>you must specify either a default, or file specific, destination directory</em></td>'
call lineout tempfile,'<tr><td  bgcolor="'copycolor'"> Copy </td><td>  copy the file to a destination directory '
call lineout tempfile,'<br><em>you must specify either a default, or file specific, destination directory</em></td>'
call lineout tempfile,'<tr><td  bgcolor="'downloadcolor'"> Down </td><td>  download the file to your machine '
call lineout tempfile,'<br>If you are using a modern (post 4.0) browser,'
call lineout tempfile,' you can download <b>more then one</b> file at '
call lineout tempfile,'a time. For older browsers, you may need to set up the DOMIXED.CMD  helper application.</td>'
call lineout tempfile,'</table>'

call lineout tempfile,'<dt><a href="#headerline">Destination</a>'
call lineout tempfile,'<dd><a name="destdirdef"> '
call lineout tempfile,'A file specific destination directory, or a fully qualified file name, </a>'
call lineout tempfile,'used with MOVE &amp; COPY.<br>'
call lineout tempfile,'<table ><tr valign="top"><td><em>Special <br> values: &nbsp; </em>&nbsp;&nbsp;</td>'
call lineout tempfile,'<td>&nbsp;&nbsp;&nbsp;&nbsp;<tt>0</tt> &nbsp;&nbsp;:  Do <b>not</b> move/copy/del/download'
call lineout tempfile,'<br><tt>blank</tt> : use default destination directory </td></table>'
call lineout tempfile,'</dl>'
call lineout tempfile,'<p><font size=-1><a href="#top">top</a></font>'

call lineout tempfile,'</body></html>'
call lineout tempfile,''


call lineout tempfile

return 0



/***********************/
/* write a short del/move/copy enabled list of files and directorie */
make_short_list:
parse arg sortext

if is_allowed_dir(ddir)=0 then do
   rcode=not_allowed_dir(ddir)
   return 1
end

/* write file list */
call lineout tempfile,'<html><head><title>SREH2 FileManager: display directory</title>'
call lineout tempfile,'<script language="javascript">'
vvar=varlist.!dir
if vvar='' then vvar='/'
vvar=sre_packur_make(vvar,1)
call lineout tempfile,'var viewing="'vvar'"'

call lineout tempfile,'</script>'
call lineout tempfile,'</head>'

call lineout tempfile,'<body>'

/* jump row of jumps */
call lineout tempfile,'<a name="top"> </a> '
call lineout tempfile,'<font size=-1>'
call lineout tempfile,'<a href="'||manname||'?" target="_top">Base DIRs</a>  '
call lineout tempfile,' || <a href="#DIRLIST" >SubDIRs</a> '
call lineout tempfile,'</font> <br>'

call lineout tempfile,'<table align="center"><tr><td bgcolor="tan"><font size=+1>SREH2-FileManager: Display a directory (condensed)</font></td></table>'

call lineout tempfile,'<form name="DO_MANAGER" method="POST" action="'manname'">'
call lineout tempfile,'<input type="hidden" value="DOIT" name="mode">'
call lineout tempfile,'<input type="hidden" value="'||sre_packur_make(ddir,1)||'" name="DOIT_DIR">'
call lineout tempfile,'<input type="hidden" value="'||sre_packur_make(uri,1)||'" name="THIS_URI">'

call lineout tempfile,'<input type="hidden" name="FILE.0" value="'ddirfiles.0'">'

call lineout tempfile,' <tt><a name="FILELIST">'ddirfiles.0' </tt> files in <b>'||ddir'</b></a></b></font>,'
call lineout tempfile,' and 'ddirdirs.0' <a href="#DIRLIST"> subdirectories</a> <p>'

/*call lineout tempfile,'<font size="+2"><b><a name="FILELIST">'ddirfiles.0' files in 'ddir'</a></b></font>,'
call lineout tempfile,' and 'ddirdirs.0' <a href="#DIRLIST"> subdirectories</a> <p>' */


call lineout tempfile,'<table><tr><td><input type="checkbox" name="VERIFY" value=1 checked>Verify?&nbsp;&nbsp;</td>'
call lineout tempfile,'<td><input type="checkbox" name="OVERWRITE" value=1 checked>Overwrite?&nbsp;&nbsp;</td>'
call lineout tempfile,'<td><nobr>Default destination-directory:</nobr></a><input type="text" name="DEFDEST" size=20></td></table>'
call lineout tempfile,' '
call lineout tempfile,'<table align="center"><tr> '
call lineout tempfile,'<td><input type="reset" value="reset"></td>'

call lineout tempfile,'<td><table border=1 align="center"><tr align="center"><Td>Key:</td><td> <table><tr>'
call lineout tempfile,'<td bgcolor="'delcolor'">Del</td>' 
call lineout tempfile,'<td bgcolor="'movecolor'">Move</td>'
call lineout tempfile,'<td bgcolor="'copycolor'">Copy</td>'

call lineout tempfile,'<td> <u>FileName</u> </td></tr></table></td>'
call lineout tempfile,'</td></tr></table>'
call lineout tempfile,'<td><a name="DOSUBMIT2"><input type="submit" value="make the changes    "></a></td></tr></table>'

if sortext=1 then do
   do mm=1 to ddirfiles.0
      ff=lastpos('.',ddirfiles.mm)
      if ff=0 then 
         aext=''
      else
         aext=translate(substr(ddirfiles.mm,ff+1))
      ext=translate(left(aext,20))
      ddirfiles.mm=ext||ddirfiles.mm
   end
   if ddirfiles.0>0 then foo=arraysort('ddirfiles')
   do mm=1 to ddirfiles.0
       ddirfiles.mm=substr(ddirfiles.mm,21)
   end
end 

if sortext=2 then do
   do mm=1 to ddirfiles.0
      ff=strip(word(ddirfiles.mm,1))
      if left(ff,2)<70 then
        ff='20'||ff
      else
        ff='19'||ff
      ff=translate(left(ff,20))
      ddirfiles.mm=ff||ddirfiles.mm
   end
   if ddirfiles.0>0 then foo=arraysort('ddirfiles')
   do mm=1 to ddirfiles.0
       ddirfiles.mm=substr(ddirfiles.mm,21)
   end
end 

if sortext=3 then do
   do mm=1 to ddirfiles.0
      ff=strip(word(ddirfiles.mm,words(ddirfiles.mm)))
      ff=filespec('n',ff)
      parse var ff ff '.' .  
      ff=translate(left(ff,20))
      ddirfiles.mm=ff||ddirfiles.mm
   end
   if ddirfiles.0>0 then foo=arraysort('ddirfiles')
   do mm=1 to ddirfiles.0
       ddirfiles.mm=substr(ddirfiles.mm,21)
   end
end 


mxflen=0
do mm=1 to ddirfiles.0
   ill=length(strip(filespec('n',ddirfiles.mm)))
   mxflen=max(mxflen,ill)
end 

kols=3
if mxflen>12 then kols=2

call lineout tempfile,'<table><tr> <td colspan=8><hr></td>'
do mm=1 to ddirfiles.0
    aa=make_SHORT_file_entry(ddirfiles.mm,mm,kols)
    call lineout tempfile,aa
end
call lineout tempfile,'</table>'

call lineout tempfile,'<a name="DIRLIST"><hr width="20%"></a>'

call lineout tempfile,'<h3> <a name="DIRLIST2">' ddirdirs.0 ' subDirectories under 'ddir'</a></h3>'
call lineout tempfile,'<table>'


/* check to see if you can show a .. directory link */
aaupdir=up_dir(ddir)
if aaupdir<>'' then do
  baa=make_dir_entry_short(aaupdir,1,1,'..')
  call lineout tempfile,baa
end

do mm=1 to ddirdirs.0
   aa=make_dir_entry_short(ddirdirs.mm,mm,5)
   call lineout tempfile,aa
end
call lineout tempfile,'</table>'
call lineout tempfile,'</form>'

call lineout tempfile,'<p><font size=-1><a href="#top">top</a></font>'

call lineout tempfile,'</body></html>'

call lineout tempfile

return 0


/***********************/
/* parse a sysfileetree dir entry ... */
make_dir_entry:procedure  expose downloadcolor copycolor delcolor movecolor  allowed_dirs. manname  rcode id_info  tempfile

parse arg adir,isup,noli


ali='<li>'
if noli=1 then ali=''

if isup<>''  then do
  entry=ali||'<a href="'manname'?dir='||sre_packur_make(adir,1)||'">'||isup||'</a>'
  if noli<>1 then entry=entry||'&nbsp;&nbsp; <font size=-1>('||adir||')</font>'
end
else do
  entry=ali||'<a href="'manname'?dir='||sre_packur_make(adir)||'">'||adir||'</a>'
end
return entry

/***********************/
/* parse a sysfileetree dir entry ... */
make_dir_entry_short:procedure  expose downloadcolor copycolor delcolor movecolor  allowed_dirs. manname  rcode id_info  tempfile

parse arg adir,mm,kols,isup

selname2=adir
igoo=lastpos('\',selname2)
if igoo>0 then do
   selname2=translate(substr(selname2,igoo+1))
end

if datatype(kols)<>'NUM' then kols=6
kols=min(max(1,kols),12)
nn=mm//kols

if isup<>''  then do
   entry='<a href="'manname'?mode=SHORTLIST&dir='||sre_packur_make(adir)||'">'||isup||'</a>'
   entry=entry||'&nbsp;&nbsp; <font size=-1>('||selname2||')</font>'
end
else do
  entry='<a href="'manname'?mode=SHORTLIST&dir='||sre_packur_make(adir)||'">'||selname2||'</a> '
end

select
 when nn=0 then 
   entry='<td> '||entry||'</td></tr>'
 when nn=1 then 
   entry='<tr><td>'||entry||'</td>'
 otherwise
   entry='<td> '||entry||'</td>'
end 


return entry



/***********************/
/* parse a sysfiletree file entry, and make it into a table row with link */
make_file_entry:procedure  expose downloadcolor copycolor delcolor movecolor  ,
                           text_exts allowed_dirs. manname  rcode id_info img_exts  tempfile

parse arg eafile,nf,basedir,diralias
crlf='0d0a'x
parse var eafile adate  asize . aname

aname=strip(aname)
fname=get_filename(aname)
iext=lastpos('.',aname)
if iext=0 then
   aext=''
else
   aext=strip(translate(substr(aname,iext+1)))

adate=strip(adate)
foo=left(adate,2)
if foo<78 then
  adate='20'||adate
else
  adate='19'||adate
adate=overlay(' ',adate,11,1)
adate=overlay(':',adate,14,1)

selname=sre_packur_make(aname,2,' "')

/* selnamex=manname||'?file='||fname */

selname0=filespec('n',eafile)

asize=insertcommas(asize)

iji=length(asize)
do ii2=iji+1 to 12
  asize='&nbsp;'asize
end 
amime='(vu)'
select 
  when aext='ZIP' then do
    selnamey="javascript:dovu('"||fname||"','ZIP'); "
    amime='(ZIP)'
    selnamey='<a href="'selnamey'" >'||amime||'</a>'
  end 
  otherwise do
    selnamey="javascript:dovu('"||fname||"'); "
    selnamey='<a href="'selnamey'" >'||amime||'</a>'

/*    if wordpos(aext,text_exts)>0 then amime='(vu)'
    if wordpos(aext,img_exts)>0 then amime='(vu)'    NOT CURRENTLY USED */

  end
end

selnamex="javascript:dovu('"||fname||"','OCTET'); "

entry='<td><a href="'selnamex'">'selname0'</a> 'selnamey' </td><td width="10%">'adate' 'asize' </td>'

/* now put in buttons */
fname=strip(fname)

but0='<input type="hidden" name="FILE.'||nf'" value="'||fname||'">'
but1='<td><table width="100%"><tr ><td bgcolor="'delcolor'">'||but0||'<input type="radio" value="DEL" name="do.'nf'"></td>'
but2='<td bgcolor="'movecolor'"><input type="radio" value="MOVE" name="do.'nf'"></td>'
but3='<td bgcolor="'copycolor'"> <input type="radio" value="COPY" name="do.'nf'"></td>'
but4='<td bgcolor="'downloadcolor'"> <input type="radio" value="DOWNLOAD" name="do.'nf'"></td></table></td>'

in1='<td bgcolor="#5aedf9"><input type="text" name="DEST.'nf'" size=20></td>'
entry='<tr>'but1||but2||but3||but4||entry||in1
return entry


/***********************/
/* parse a sysfiletree file entry, and make it into a table row with link */
make_SHORT_file_entry:procedure expose downloadcolor copycolor delcolor movecolor   allowed_dirs. manname rcode id_info  tempfile
parse arg eafile,nf,kols
crlf='0d0a'x
parse var eafile adate  asize . aname
aname=strip(aname)
adate=strip(adate)
foo=left(adate,2)
if foo<78 then
  adate='20'||adate
else
  adate='19'||adate
adate=overlay(' ',adate,11,1)
adate=overlay(':',adate,14,1)

selname=sre_packur_make(aname,2,' "')

selnamex=manname'?file='||translate(selname,'/','\')

selname0=get_filename(aname)

asize=insertcommas(asize)
iji=length(asize)
do ii2=iji+1 to 12
  asize=' 'asize
end /* do */

/* the buttons */
aname=strip(aname)
a1a='<input type="hidden" name="FILE.'||nf'" value="'||selname0||'">'
a1='<input type="radio" value="DEL"  name="do.'nf'">'
a2='<input type="radio" value="MOVE" name="do.'nf'">'
a3='<input type="radio" value="COPY" name="do.'nf'">'
a4='<input type="radio" value="DOWNLOAD" name="do.'nf'">'

/* the file link */
winstat=' onMouseOver="window.status='||"'"||selname0' 'adate' 'asize||"';return true "||'"'
a4='<a href="'||selnamex||'"'||winstat||'" target="VIEWER">'||selname0||'</a>'

aline='<td><table><tr>'
aline=aline||'<td bgcolor="'delcolor'">'||a1a||a1'</td>'crlf 
aline=aline||'<td bgcolor="'movecolor'">'a2'</td>'crlf
aline=aline||'<td bgcolor="'copycolor'">'a3'</td>'crlf

aline=aline||'<td>'a4'</td>'crlf
aline=aline||'</tr></table></td>'
if (nf//kols)==1 then aline='<tr>'aline
if (nf//kols)==0 then aline=aline'</tr>'crlf

return aline




/************/
/*  parse varlist, return in varlisrt.!name.
   With varlist.0 containing list of names */
read_vars:procedure expose varlist.  allowed_dirs. manname  rcode id_info  tempfile

parse arg alist
varlist.=''
alist=translate(alist, ' ', '+'||'090a0d'x)  /* Whitespace, etc. */

do forever
    if alist='' then leave
    parse var alist a1 '&' alist
    parse var a1 aname '=' avalue
    if avalue='' then iterate             /* ignore empty entries */
    aname=sre_packur(translate(space(translate(aname,' ','+'||'00090a0d'x),0)))
    aval=strip(sre_packur(translate(avalue,' ','+'||'00090a0d'x)))
    aa='!'||aname
    varlist.aa=aval
    varlist.0=varlist.0' 'aname
end
return varlist.0


/***************/
/* convert to xxx,yyy,zzz */
insertcommas:procedure 
parse arg asize
 il=length(asize)
 if il>3 then do
         oop=""
         do mm=il to 3 by -3
               tt=substr(asize,mm-2,3)
               if mm=il then
                  oop=tt
               else
                oop=tt||','||oop
         end /* do */
         if mm<>0 then oop=substr(asize,1,mm)||','||oop
         asize=oop
 end
 return asize

/*************************************************/
/* Check for the existence of a directory. Correctly identifies
   empty directories.
Usage:
   flag=dir_exists(a_directory)
where
   flag=1 if a_directory exists (it might be an empty directory )
   flag=0 if it doesn't exist
*/
dir_exists:procedure 
parse arg adir
ip=pos('.',adir)
if ip>0 then do /* strip out filename */
   ip2=lastpos('\',adir)
   adir=left(adir,ip2)
end /* do */
adir=strip(adir)
adir=strip(adir,'t','\')
nowdir=directory()
nowdrive=filespec('d',nowdir'\')
nowpath=filespec('p',nowdir'\')
adr=filespec('d',adir)
if adr='' then do
   if abbrev(adir,'\')=0 then 
       adir=nowdrive||nowpath||adir
   else
       adir=nowdrive||adir
end /* do */

foo=sysfiletree(adir,goo,'D')
if  goo.0>0  then return 1
return 0


/**************************************/
/* read data sent back by an html FORM declared with:
   enctype="multipart/form-data" method="POST"

Calling syntax:
   nentries=read_multipart(stuff,content_type)
  where
     stuff == the body of a POST request (i.e.; the 4th argument sent to
              sre-http addons)
     nentries == the number of entries found. If error, nentries=0
    
  and also the expose variable FORM_DATA is constructed.

The structure of FORM_DATA is:
  FORM_DATA.0 = # of entries (in this multipart submission)
  FORM_DATA.!list.j = space delimited list of "variable names" in part
                       j (j=1.. FORM_DATA.0)
     For each word in FORM_DATA.!list.j, there is FORM_DATA. tail.
     In particular, FORM_DATA.!aword.j, where !aword is an ! prepended
     to a word form the FORM_DATA.!list.j list.
     For example, in almost all cases, one of these words will be "NAME".
       Thus, FORM_DATA.!NAME.j = the "name" of this variable
  FORM_DATA.j  - the actual value of this part.

  Basically, a typical entry  will contain:
    FORM_DATA.!NAME.j and FORM_DATA.j
  which can be interpreted as the "name" of the variable and it's "value".
  However, sometimes other variables will be mentioned in the
  FORM_DATA.!LIST. In particular, file uploads will often have a
  FORM_DATA.!FILENAME.j, which is often the local name of 
  the file the client is uploading.


  Notes:
    * if an error occurs, a 0 is returmed, and FORM_DATA.!ERROR
      will contain an error message
    * a content-disposition entry, if found, is NOT included in FORM_DATA

*/
read_multipart_data:procedure expose form_data. manname  rcode id_info  tempfile
parse arg abody,atype

drop form_data.
form_data.=''

crlf='0d0a'x

/* is there a content-type request header ? */
if atype="" then do
   form_data.!error=" No  content-type  request header"
   return 0
end

parse var atype thetype ";" boog 'boundary=' abound    /* get the type */

if translate(thetype)<>"MULTIPART/FORM-DATA" then do
  form_data.!error="No  multipart/form-data in Content-type "
  return 0
end

if translate(thetype)<>"MULTIPART/FORM-DATA" then do
  form_data.!error=" upload error: No boundary in multipart/form-data header "
  return 0
end

abound="--"||abound   /* since boundaries always start with -- */

abd2=abound||crlf
/* loop through message, pulling out blocks and storing in stem var bigstuff. */

/* Now parse the various parts.*/

parse var abody foo1 (abd2) abody    /* move beyond first boundary and it's crlf */
/* check for netscape 2.0 incorrect format */
if pos(abound,abody)=0 then do   /* no ending boundary, so add one */
   abody=abody||crlf||abound||" -- "
end

mm=0
do until abody=""
  parse var abody thestuff (abound) abody        /* get a  boundary defined block */
  if strip(left(thestuff,4))="--" then leave        /* -- signals no more */
  if abody="" then leave
  mm=mm+1
  form_data.!list.mm='' ; form_data.mm=''
  do forever            /* get block headers.  Stop when hit a blank line */
     parse var thestuff anarg (crlf) thestuff
     if anarg="" then do
           leave
     end
     else do                    /* extract the arguments on this line */
         do until anarg=""
              parse var anarg anarg1 ";" anarg
              boob1=pos(':',anarg1) ; boob2=pos('=',anarg1)
              if boob1=0 then nixon=boob2
              if boob2=0 then nixon=boob1
              if boob1>0 & boob2>0 then nixon=min(boob1,boob2)
              t1=translate(strip(strip(substr(anarg1,1,nixon-1)),,'"'))
              t2=strip(strip(substr(anarg1,nixon+1)),,'"')
              if t1="CONTENT-DISPOSITION" then iterate /* don't bother retaining this */
              form_data.!list.mm=form_data.!list.mm' 't1
              nm1='!'||t1
              form_data.nm1.mm=t2
          end     /* exract arguments */
     end        /* extract args on this line */
  end                    /* get a line */
  if thestuff<>"" then do
    form_data.mm=left(thestuff,length(thestuff)-2)  /* strip off ending crlf */
    parse var abody foo (crlf) abody   /* jump past extra crlf */
  end
  else do
     form_data.body.mm=""
  end
end

return mm


/*********************************/
/* expand a .zip file 
zipfile: The zipfile to examine
lookin: real directory of the zipfile 
 */

show_zipfile:
thedir=sre_packur(varlist.!DOIT_DIR)
thedir=translate(thedir,'\','/')
if is_allowed_dir(thedir)=0 then do 
   rcode=not_allowed_dir(thedir)
   return 1
end 

thefile0=translate(varlist.!mimefile,'\','/')

thefile=strip(strip(thedir,'t','\')||'\'||thefile0)

zipfile=stream(thefile,'c','query exists')
if zipfile='' then do
  call lineout tempfile,'<html><head><title>SREH2-FileManager: no such file </title></head>'
  call lineout tempfile,'<BODY><h3>File not found </h3>'
  call lineout tempfile,'Sorry, could not find: 'thefile
  call lineout tempfile,'</body></html>'
  call lineout tempfile
  iff=stream(tempfile,'c','query size')
  rcode=sre_command('FILE ERASE type text/html name 'tempfile,,id_info)
  return 1
end


rc=uzfiletree(zipfile,'getem',,,'Z')
call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 2.0//EN">'
call lineout tempfile, "<HTML>"
call lineout tempfile, "<HEAD>"
call lineout tempfile, "<TITLE>Contents of "zipfile"</TITLE>"
call lineout tempfile, "</HEAD> <body> <h2> Contents of " zipfile '</h2>'


call lineout tempfile, '<pre> <b>'left("Name",19)||left("Last Modified",17)||right("Size",8)'</b>'
call lineout tempfile,'<hr>    <b>Key:</b> <u><Em>+</em></u> = extract | <u><Em>++</em></u> : extract &amp; overwrite<br>'

call lineout tempfile,'<a href="javascript:history.go(-1)">back</a><br>'
thezip=sre_packur_make(zipfile,1)
do mm=1 to getem.0
    aline=getem.mm
    Fname=word(aline,8)
    Ftime=word(aline,6)
    Fdate=word(aline,5)
    fdate=dateconv(translate(fdate,'/','-'),'U','N')
    Fsize=word(aline,1)
    feeb=' '
    feeb1=manname||'?INZIP='||fname||'&THEZIP='||thezip
    feeb2=manname'?INZIP='fname'&THEZIP='thezip'&UNZIP=1'

    feeb3=feeb||'<A href="'||feeb1||'" target="VIEWER">'||fname||'</a> '
    feeb3=feeb3||' <em>(<A href="'||feeb2||'">+</a>)</em>'
    feeb3=feeb3||' <em>(<A href="'||feeb2||'&over=1">++</a>)</em>'

    call lineout tempfile, feeb3''copies(' ',max(0,20-length(Fname)))''right(Fdate,10)''right(Ftime,6)' 'right(Fsize,10)
end

call lineout tempfile,' '

call lineout tempfile,'</pre><form action="'manname'" method="GET">'
call lineout tempfile,'<input type="HIDDEN" name="UNZIPALL" value="'THEZIP'">'
call lineout tempfile,'<select size=5 name="OPT">'
call lineout tempfile,'<option value="-o">Overwrite everything'
call lineout tempfile,'<option value="-n">Never Overwrite '
call lineout tempfile,'<option value="-f">Freshen pre-existing'
call lineout tempfile,'<option value="-u">Update (freshen, and create)'
call lineout tempfile,'</select>'
call lineout tempfile,'<input type="checkbox" name="OPT2" value="-j">Do NOT make directories<br>'
call lineout tempfile,'<input type="submit" value="UnZip '||filespec('n',zipfile)||'">'
call lineout tempfile,'</form>'

call lineout tempfile, "</BODY>"
call lineout tempfile, "</HTML>"
call lineout tempfile


return 

/*********************************/
/* unzip the file */

unzip_zipfile:

zipfile=strip(translate(varlist.!UNZIPALL,'\','/'))

if is_allowed_dir(zipfile)=0 then do 
  rcode=not_allowed_dir(zipfile)
  return 1
end

/* make sure it exists */
if stream(zipfile,'c','query exists')=' ' then  do
  call lineout tempfile, "<body><h2>Sorry...</h2>"
  call lineout tempfile,' Could not find .ZIP file: ' zipfile
  call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
  call lineout tempfile, "</body></html>"
  call lineout tempfile  /* close */
end


call lineout tempfile, '<!doctype html public "-//IETF//DTD HTML 2.0//EN">'
call lineout tempfile, "<HTML>"
call lineout tempfile, "<HEAD>"
call lineout tempfile, "<TITLE>UnZipping</TITLE>"
call lineout tempfile, '</HEAD> <body> <h2> Files unzipped from :'zipfile '</h2>'



aopt=varlist.!opt
zipfile=translate(zipfile,'\','/')
if aopt='' then aopt=' -n'
tod=strip(filespec('d',zipfile)||filespec('p',zipfile),,'\')
tod='-d 'tod
fro=uzunzip(aopt||' -o '||tod||' '||varlist.!opt2||' '||zipfile,'outit.')
call lineout tempfile,'<pre> '
do mm=1 to outit.0
   call lineout tempfile,outit.mm
end /* do */
call lineout tempfile,'</pre>'

call lineout tempfile,'<a href="javascript:self.back()">back</a><br>'

call lineout tempfile, "</pre></BODY>"
call lineout tempfile, "</HTML>"
call lineout tempfile


return 0


/**************/
/* Extract and send a zip file. */
send_zipfile:

zipfile=strip(translate(varlist.!thezip,'\','/'))

if is_allowed_dir(zipfile)=0 then do 
  rcode=not_allowed_dir(zipfile)
  return 1
end


/* make sure it exists */
if stream(zipfile,'c','query exists')=' ' then  do
  call lineout tempfile, "<body><h2>Sorry...</h2>"
  call lineout tempfile,' Could not find .ZIP file: ' zipfile
  call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
  call lineout tempfile, "</body></html>"
  call lineout tempfile  /* close */
end

getfile=varlist.!inzip
rc=uzunziptostem(zipfile,'sook.',getfile)

if sook.1=0 then do
  call lineout tempfile, "<body><h3>Sorry...</h3>"
  call lineout tempfile,' Could not find Zipped file: ' getfile
  call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
  call lineout tempfile, "</body></html>"
  call lineout tempfile 
  return 1
end

arf=strip(sook.1)
thesize=length(sook.arf)
if thesize=0 then do  /* hack to get around unzip.dll ?bug? */
     sook.arf=uzunziptovar(zipfile,getfile)
     thesize=length(sook.arf)
end

if varlist.!unzip=1 then do                   /* sae the zipped file to disk */
    ggo=translate(getfile,' ','/\')
    getfile2=strip(word(ggo,words(ggo)))
    saveto=strip(filespec('d',zipfile)||filespec('p',zipfile),'t','\')'\'getfile2
    if varlist.!over<>1 then do
        ook=stream(saveto,'c','query exists')
        if ook<>'' then do
           call lineout tempfile,'<html><head><title>SREH2-FileManager: zip extract</title></head>'
           call lineout tempfile,' <b>Ovewrite not permitted, can not extract:</b> 'saveto
           call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
           call lineout tempfile,'</body></html>'
           call lineout tempfile
           return 1
        end /* do */
    end /* do */
    foo=stream(saveto,'c','open write')
    if abbrev(translate(foo),'READY')<>1 then do
           call lineout tempfile,'<html><head><title>SREH2-FileManager: zip extract</title></head>'
           call lineout tempfile,' <b>Can not write zip file to:</b> 'saveto
           call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
           call lineout tempfile,'</body></html>'
           call lineout tempfile
           return 1
    end
    fii=charout(saveto,sook.arf,1)
    if fii<>0 then do
           call lineout tempfile,'<html><head><title>SREH2-FileManager: zip extract</title></head>'
           call lineout tempfile,' <b>Unable to fully write zip file to:</b> 'saveto
           call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
           call lineout tempfile,'</body></html>'
           call lineout tempfile
           return 1
     end 
     foo=stream(saveto,'c','close')
     call lineout tempfile,'<html><head><title>SREH2-FileManager: zip extract</title></head>'
     call lineout tempfile,'<b>'length(sook.arf)' bytes  extracted to:</b> 'saveto
     call lineout tempfile,'<br><a href="javascript:self.back()">back</a><br>'
     call lineout tempfile,'</body></html>'
     call lineout tempfile
     return 1
end
else do              /* dsplay */
     atype=sreh2_get_mimetype(getfile,host_nickname,1)
     foog=sook.arf      /* sometime problems passing stem vars */
     ahdr='Content-disposition: attachment; filename="'||get_filename(getfile)||'"'
     rcode=sre_command('VAR TYPE 'atype' ',foog,id_info,,ahdr)
     return 1
end

/* here on error */
badguys:
call pmprintf(' MANAGER error at 'sigl','rc)
foo=stream(tempfile,'c','close')
rcode=sre_command('string Manager Error at ' sigl  ' ' rc,,id_info)
return 0





/* ================================== */
/* do a multipart/mixed or application/sre-mixed download */
do_downloads:

/* 3=multipart/mixed binary 2= multipart/mixed mime, 1=application/sre-mixed */
dtype=varlist.!download_type  

ifil=0
alist=varlist.!filelist
cprot=sre_extract('clientprotocol',id_info)

do forever
  if alist='' then leave
  parse var alist thefile ','  alist ; thefile=strip(thefile)
  if thefile='' then iterate
  ifil=ifil+1
  fils.ifil=translate(sre_packur(thefile),'\','/')
  fils.0=ifil
end


stuff='X-FileCount: 'fils.0||crlf  /* used as base in dtype=1 */
atype='application/octet-stream'

fname=get_filename(fils.1)
if dtype<>3 then atype=sreh2_get_mimetype(fname,host_nickname,1)
if dtype=1 then do                      /* note that stuff is exposed */
  sst=multi_send2(fils.1,atype,'S',1,'Content-disposition: attachment; filename="'fname'"')
end
else do
   opthdr='Content-disposition: attachment; filename="'fname'"'
   stuff=SREH2_multi_send(fils.1,'NOWAIT '||atype,'S',1,0,opthdr,id_info,cprot)
end
if dtype=2 & datatype(varlist.!DELAY)="NUM" then call delay(varlist.!DELAY)


do mm=2 to fils.0-1
  fname=get_filename(fils.mm)
  if dtype<>3 then atype=sreh2_get_mimetype(fname,host_nickname,1)
  if dtype=1 then do
     sst=multi_send2(fils.mm,atype,'M',1,'Content-disposition: attachment; filename="'fname'"')
  end
  else do
     opthdr='Content-disposition: attachment; filename="'fname'"'
     stuff=SREH2_multi_send(fils.mm,atype,'M',1,0,opthdr,id_info,cprot)
  end
  if dtype=2 & datatype(varlist.!DELAY)="NUM" then call delay(varlist.!DELAY)
end

mm=fils.0
fname=get_filename(fils.mm)
if dtype<>3 then atype=sreh2_get_mimetype(fname,host_nickname,1)
if dtype=1 then do
  sst=multi_send2(fils.mm,atype,'E',1,'Content-disposition: attachment; filename="'fname'"')
end
else do
  opthdr='Content-disposition: attachment; filename="'fname'"'
  stuff=SREH2_multi_send(fils.mm,atype,'E',1,0,opthdr,id_info,cprot)
end

if dtype=2 & datatype(varlist.!DELAY)="NUM" then call delay(varlist.!DELAY)


if dtype=1 then do
  rcode=sre_command('var type application/x-sre-mixed ',stuff,id_info)
end

return 0


/******************************************/
/* send a multipart document as one big document  -- cause  
4.0x netscape's got a bug ! 
Note that this builds "STUFF", which is exposed */
*/

multi_send2:procedure expose stuff manname  rcode id_info  tempfile
parse arg thevalue,thetype,astatus,isfile,optheaders

parse var astatus status doclose

eclose=''

crlf='0d0a'x                /* useful */
bound='asfa235sdfF#234asg#%^6q32472341as'
bound2='asfA235sdfF#234asg#%^6q32472341p'

/* if isfile, then thevalue is a fully qualified file name. Read it */
if isfile=1 then thevalue=sre_read_file(thevalue,2,2,5)

/* if by odd chance a bound string is found in thevalue, it will
  be replaced by bound2 */
foo=pos(bound,thevalue)
if foo>0 then do
      thevalue=sre_replacestrg(thevalue,bound,bound2,'ALL') 
      call sre_pmprintf('Multi_Send. Warning: boundary value found in message (and modified) ')
end

/* mime types */
if thetype=0 | thetype="" then thetype="text/html"

/* status */
status=strip(upper(status)); 

  mimestart='--'bound''crlf   /* starts a MIME multipart section */
  mimeend  ='--'bound'--'crlf /* ends a MIME multipart section */
  out=""

/* for now, assume multipart sends are not to be cached */
  if status='S'  then do
    stuff=stuff||'Content-Type: multipart/mixed;boundary='bound||crlf
    stuff=stuff||crlf||mimestart         
  end

  if wordpos(status,'S M E ')>0 then do   
     stuff=stuff||'Content-type: '||thetype||crlf
     if optheaders<>'' then stuff=stuff||optheaders||crlf
     stuff=stuff||crlf
  end

  out=out||thevalue||crlf

  if status="E"  then do
    out=out||mimeend           /* Mime 'last data' indicator */
  end
  if wordpos(status,'M S')>0 then do
       out=out||mimestart         /* Mime 'start data' indicator */
 end
 stuff=stuff||out

return 1


/***************/
/* pull out file name (strip path) */
get_filename:procedure
parse arg aname
aname=translate(aname,'\','/')
ii=lastpos('\',aname)
if ii=0  then do
   ii=pos(':',aname)
end 
fname=substr(aname,ii+1)
return fname

/***************/
/* no access to this directory allowed */
not_allowed_dir:procedure expose tempfile id_info rcode 
parse arg afile,amessage
  call lineout tempfile,'<html><head><title>SREH2-FileManager:access not permitted </title></head>'
  call lineout tempfile,'<h3>Access not permitted </h3>'
  call lineout tempfile,'Sorry, access not allowed to: 'afile
  if amessage<>'' then call lineout tempfile,'<p>'||amessage
  call lineout tempfile,'</body></html>'
  call lineout tempfile
  rcode0=sre_command('FILE ERASE type text/html name 'tempfile,,id_info)
  return rcode0

/***************/
/* check for SUPERUSER permissions, dynamic privileges, and security level */
is_allowed:

ss=sre_value('SECURITY_LEVEL',,'SRESYS')
if ss=0 then do
  foo=sre_command('String Sorry. Remote access to system utilities not permitted.',,idinfo)
  return foo
end

if (wordpos('SUPERUSER',privset)+wordpos('MANAGER',privset))=0 then do
  if aiter='' then return 'PRIVS MANAGER requires superuser or manager privileges '
  return 'AUTH MANAGER requires that you have superuser or manager privileges '
end 

/* now check for the secret privilege */
parse var privset . ',' privset2
authh=sre_reqfield('Authorization',,id_info)
uname=sre_extract_username(authh)
foo=sre_reqfield('cookie')
this_flag='RELOGON:'||uname
resp=sreh2_dynamic_pwd('MANAGER',,privset2,pwd_duration,respfile,,,id_info,this_flag) 
if resp=this_flag then do
  return 'AUTH Please logon as a user other then <tt> 'uname '</tt>'
end 

if resp<>''  then do
    return resp
end 



return ''               /* if here, it's okay */

************************/
/* read configuration file */
read_cfg:
crlf = '0d0a'x

rcode=''

allowed_dirs.=''
allowed_dirs.0=0

/* some defaults */
delcolor="#f5ddf9"      /* colors used to display del,copy,move radio buttons */
copycolor="#00fdf9"
movecolor="#9addf9"
downloadcolor="#778877"
max_size_edit=25000   /* maximum size (in byte) of files that can be edited */
col_size_edit=70     /* columns and rows to use (in TEXTAREA box) when editing a file */
row_size_edit=20
text_exts='TXT HTML SHTML SHT HTM FAQ '   
img_exts='GIF JPEG JPG PNG '

arf=sreh2_value('CFG_DIR',,host_nickname)
cfile=arf||'\MANAGER.CFG'
stuff=sre_read_file(cfile,2,5,1)
if stuff='' then do               /* couldn't find */
  supc=sreh2_value('SUPERCEDING',,host_nickname)
  if supc<>2 then do
     arf=sreh2_value('CFG_DIR',,'DEFAULT')
     cfile=arf||'\MANAGER.CFG'
     stuff=sre_read_file(cfile,2,5,1)
  end
end
if stuff='' then do               /* couldn't find */
   rcode=sre_error_response(500,,,arf' Unable to find MANAGER configuration file ',id_info)
   return rcode
end

PLIST1='DELCOLOR COPYCOLOR MOVECOLOR DOWNLOADCOLOR MAX_SIZE_EDIT '||,
       'COL_SIZE_EDIT ROW_SIZE_EDIT TEXT_EXTS IMG_EXTS '

do until stuff=''
   parse var stuff aline '0d0a'x stuff
   aline=strip(aline)
   if aline='' | abbrev(aline,';')=1 then iterate
   parse var aline avar aval
   avar=strip(translate(avar))
   if wordpos(avar,PLIST1)>0 THEN DO  /* one of the simple parameters */
        foo=value(avar,strip(aval))
        iterate
   end
   if avar<>'ALLOWED_DIR' then do
      call sre_pmprintf('MANAGER: ignoring unknown parameter = 'avar)
      iterate   /* ignore unknown */
   end 

/* if here, it's one of the ALLOWED_DIR directories
Some special entries:
;    ALLOWED_DIR         -- Ignored.
;    ALLOWED_DIR   *     -- all directories are accessible
;    ALLOWED_DIR   1     -- the data directory, and virtual directories
;    ALLOWED_DIR   2     -- same as 1, plus the SREHTTP2 directory 
;    ALLOWED_DIR   3     -- same as 2, plus the SRE2003 directory 
*/

   aval=strip(translate(aval))
   if aval='' then iterate
   if aval='*' then do
      allowed_dirs.!0=1  /* signal "all directories accessible */
   end

   if aval=1 | aval=2 | aval=3 then do
      mm=allowed_dirs.0+1
      allowed_dirs.mm=sre_datadir()
      allowed_dirs.0=mm
      vlist=sreh2_get_attributes(host_nickname,'*DIR',,id_info)
      do until vlist=''         /* parse off the virtual directories */
          parse var vlist avdir vlist
          avdir=translate(strip(sre_packur(avdir)))
          if avdir=',' then iterate
          parse var avdir rname ':' avdir
          mm=allowed_dirs.0+1
          allowed_dirs.mm=avdir
          allowed_dirs.mm.!RNAME=rname
          allowed_dirs.0=mm
      end 
   end
   
   if aval=2 | aval=3 then do
      mm=allowed_dirs.0+1
      allowed_dirs.mm=sre_value('FILTER_DIR',,'SRESYS')
      allowed_dirs.0=mm
   end 

   if aval=3 then do 
      mm=allowed_dirs.0+1
      allowed_dirs.mm=sre_value('SRV_DIR',,'SRESYS')
      allowed_dirs.0=mm
   end 

   if wordpos(aval,'1 2 3')=0 then do   /* an explicit directory */
      mm=allowed_dirs.0+1
      allowed_dirs.mm=aval
      allowed_dirs.0=mm
   end

end 

text_exts=translate(text_exts)
img_exts=translate(img_exts)

jj0=0
do jj=1 to allowed_dirs.0        /* make sure these directories exist */
  adir=allowed_dirs.jj
  if adir=''  then iterate
  adir=translate(adir,'\','/')
  adir=translate(strip(adir,'t','\'))
  if right(adir,1)=':' then adir=adir||'\'
  if dosisdir(adir)=0 then do
     foo=sre_write_error('MANAGER: warning -- Directory does not exist: 'adir ,,1)
     iterate
  end
  jj0=jj0+1
  allowed_dirs.jj0=strip(adir,,'\')  
end
allowed_dirs.0=jj0
return  ''

