Diff for /loncom/interface/londocs.pm between versions 1.327 and 1.537

version 1.327, 2009/01/28 12:56:08 version 1.537, 2013/03/17 14:27:34
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Documents  # Documents
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
   package Apache::londocs;
   
 package Apache::londocs;  use strict;
   use Apache::Constants qw(:common :http);
 use strict;  use Apache::imsexport;
 use Apache::Constants qw(:common :http);  use Apache::lonnet;
 use Apache::imsexport;  use Apache::loncommon;
 use Apache::lonnet;  use Apache::lonhtmlcommon;
 use Apache::loncommon;  use LONCAPA::map();
 use LONCAPA::map();  use Apache::lonratedt();
 use Apache::lonratedt();  use Apache::lonxml;
 use Apache::lonxml;  use Apache::lonclonecourse;
 use Apache::lonclonecourse;  use Apache::lonnavmaps;
 use Apache::lonnavmaps;  use Apache::lonnavdisplay();
 use HTML::Entities;  use Apache::lonextresedit();
 use GDBM_File;  use HTML::Entities;
 use Apache::lonlocal;  use HTML::TokeParser;
 use Cwd;  use GDBM_File;
 use LONCAPA qw(:DEFAULT :match);  use Apache::lonlocal;
   use Cwd;
 my $iconpath;  use LONCAPA qw(:DEFAULT :match);
   
 my %hash;  my $iconpath;
   
 my $hashtied;  my %hash;
 my %alreadyseen=();  
   my $hashtied;
 my $hadchanges;  my %alreadyseen=();
   
   my $hadchanges;
 my %help=();  
   
   my %help=();
 sub mapread {  
     my ($coursenum,$coursedom,$map)=@_;  
     return  sub mapread {
       &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map)=@_;
      $map);      return
 }        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
        $map);
 sub storemap {  }
     my ($coursenum,$coursedom,$map)=@_;  
     my ($outtext,$errtext)=  sub storemap {
       &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      my ($coursenum,$coursedom,$map,$contentchg)=@_;
       $map,1);      my $report;
     if ($errtext) { return ($errtext,2); }      if (($contentchg) && ($map =~ /^default/)) {
             $report = 1;
     $hadchanges=1;      }
     return ($errtext,0);      my ($outtext,$errtext)=
 }        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
         $map,1,$report);
       if ($errtext) { return ($errtext,2); }
   
 sub authorhosts {      $hadchanges=1;
     my %outhash=();      return ($errtext,0);
     my $home=0;  }
     my $other=0;  
     foreach my $key (keys(%env)) {  
  if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {  
     my $role=$1;  sub authorhosts {
     my $realm=$2;      my %outhash=();
     my ($start,$end)=split(/\./,$env{$key});      my $home=0;
     if (($start) && ($start>time)) { next; }      my $other=0;
     if (($end) && (time>$end)) { next; }      foreach my $key (keys(%env)) {
     my ($ca,$cd);   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     if ($1 eq 'au') {      my $role=$1;
  $ca=$env{'user.name'};      my $realm=$2;
  $cd=$env{'user.domain'};      my ($start,$end)=split(/\./,$env{$key});
     } else {      if (($start) && ($start>time)) { next; }
  ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);      if (($end) && (time>$end)) { next; }
     }      my ($ca,$cd);
     my $allowed=0;      if ($1 eq 'au') {
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);   $ca=$env{'user.name'};
     my @ids=&Apache::lonnet::current_machine_ids();   $cd=$env{'user.domain'};
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }      } else {
     if ($allowed) {   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
  $home++;      }
  $outhash{'home_'.$ca.'@'.$cd}=1;      my $allowed=0;
     } else {      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      my @ids=&Apache::lonnet::current_machine_ids();
  $other++;      foreach my $id (@ids) {
     }                  if ($id eq $myhome) {
  }                      $allowed=1;
     }                      last;
     return ($home,$other,%outhash);                  }
 }              }
       if ($allowed) {
    $home++;
 sub dumpbutton {   $outhash{'home_'.$ca.':'.$cd}=1;
     my ($home,$other,%outhash)=&authorhosts();      } else {
     my $type = &Apache::loncommon::course_type();   $outhash{'otherhome_'.$ca.':'.$cd}=$myhome;
     if ($home+$other==0) { return ''; }   $other++;
     if ($home) {      }
  return '<input type="submit" name="dumpcourse" value="'.   }
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      }
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');      return ($home,$other,%outhash);
     } else {  }
  return '<div>'.  
      &mt('Dump '.$type.  
  ' DOCS to Construction Space: available on other servers').  sub clean {
  '</div>';      my ($title)=@_;
     }      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
 }      return $title;
   }
 sub clean {  
     my ($title)=@_;  
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;  
     return $title;  sub dumpcourse {
 }      my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page('Dump '.$crstype.' Content to Authoring Space')."\n".
                 &Apache::lonhtmlcommon::breadcrumbs('Dump '.$crstype.' Content to Authoring Space')."\n");
 sub dumpcourse {      $r->print(&startContentScreen('tools'));
     my ($r) = @_;      my ($home,$other,%outhash)=&authorhosts();
     my $type = &Apache::loncommon::course_type();      unless ($home) {
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').          $r->print(&endContentScreen());
       '<form name="dumpdoc" method="post">');          return '';
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      }
     my ($home,$other,%outhash)=&authorhosts();      my $origcrsid=$env{'request.course.id'};
     unless ($home) { return ''; }      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my $origcrsid=$env{'request.course.id'};      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);  # Do the dumping
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
 # Do the dumping              $r->print(&endContentScreen());
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }              return '';
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});          }
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  my $title=$env{'form.authorfolder'};   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $title=&clean($title);   my $title=$env{'form.authorfolder'};
  my %replacehash=();   $title=&clean($title);
  foreach my $key (keys(%env)) {   my %replacehash=();
     if ($key=~/^form\.namefor\_(.+)/) {   foreach my $key (keys(%env)) {
  $replacehash{$1}=$env{$key};      if ($key=~/^form\.namefor\_(.+)/) {
     }   $replacehash{$1}=$env{$key};
  }      }
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   }
  $crs=~s/\_/\//g;   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  foreach my $item (keys(%replacehash)) {   $crs=~s/\_/\//g;
     my $newfilename=$title.'/'.$replacehash{$item};   foreach my $item (keys(%replacehash)) {
     $newfilename=~s/\.(\w+)$//;      my $newfilename=$title.'/'.$replacehash{$item};
     my $ext=$1;      $newfilename=~s/\.(\w+)$//;
     $newfilename=&clean($newfilename);      my $ext=$1;
     $newfilename.='.'.$ext;      $newfilename=&clean($newfilename);
     my @dirs=split(/\//,$newfilename);      $newfilename.='.'.$ext;
     my $path='/home/'.$ca.'/public_html';      my @dirs=split(/\//,$newfilename);
     my $makepath=$path;      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $fail=0;      my $makepath=$path;
     for (my $i=0;$i<$#dirs;$i++) {      my $fail=0;
  $makepath.='/'.$dirs[$i];      for (my $i=0;$i<$#dirs;$i++) {
  unless (-e $makepath) {   $makepath.='/'.$dirs[$i];
     unless(mkdir($makepath,0777)) { $fail=1; }   unless (-e $makepath) {
  }      unless(mkdir($makepath,0777)) { $fail=1; }
     }   }
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      }
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     print $fh &Apache::lonclonecourse::rewritefile(   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),      print $fh &Apache::lonclonecourse::rewritefile(
      (%replacehash,$crs => '')           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
     );       (%replacehash,$crs => '')
  } else {      );
     print $fh   } else {
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);      print $fh
        }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
  $fh->close();         }
     } else {   $fh->close();
  $fail=1;      } else {
     }   $fail=1;
     if ($fail) {      }
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');      if ($fail) {
     } else {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      } else {
     }   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  }      }
     } else {   }
 # Input form      } else {
  unless ($home==1) {          $r->print(&mt('Searching ...').'<br />');
     $r->print(          $r->rflush();
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');  # Input form
  }          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
  foreach my $key (sort(keys(%outhash))) {   unless ($home==1) {
     if ($key=~/^home_(.+)$/) {      $r->print('<div class="LC_left_float">'.
  if ($home==1) {        '<fieldset><legend>'.
     $r->print(                        &mt('Select the Authoring Space').
   '<input type="hidden" name="authorspace" value="'.$1.'" />');                        '</legend><select name="authorspace">');
  } else {   }
     $r->print('<option value="'.$1.'">'.$1.' - '.   foreach my $key (sort(keys(%outhash))) {
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      if ($key=~/^home_(.+)$/) {
  }   if ($home==1) {
     }      $r->print(
  }    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  unless ($home==1) {   } else {
     $r->print('</select>');      $r->print('<option value="'.$1.'">'.$1.' - '.
  }        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
  my $title=$origcrsdata{'description'};   }
  $title=~s/[\/\s]+/\_/gs;      }
  $title=&clean($title);   }
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'   unless ($home==1) {
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');      $r->print('</select></fieldset></div>'."\n");
  &tiehash();   }
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   my $title=$origcrsdata{'description'};
                  .&Apache::loncommon::start_data_table()   $title=~s/[\/\s]+/\_/gs;
                  .&Apache::loncommon::start_data_table_header_row()   $title=&clean($title);
                  .'<th>'.&mt('Internal Filename').'</th>'   $r->print('<div class="LC_left_float">'.
                  .'<th>'.&mt('Title').'</th>'                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                  .'<th>'.&mt('Save as ...').'</th>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .&Apache::loncommon::end_data_table_header_row());                    $title.'" />'.
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {                    '</fieldset></div><br clear="all" />'."\n");
     $r->print(&Apache::loncommon::start_data_table_row()   &tiehash();
                      .'<td>'.$file.'</td>');   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
     my ($ext)=($file=~/\.(\w+)$/);                   .&Apache::loncommon::start_data_table()
     my $title=$hash{'title_'.$hash{                   .&Apache::loncommon::start_data_table_header_row()
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                   .'<th>'.&mt('Internal Filename').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .'<th>'.&mt('Title').'</th>'
     if (!$title) {                   .'<th>'.&mt('Save as ...').'</th>'
  $title=$file;                   .&Apache::loncommon::end_data_table_header_row());
     } else {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=~s|/|_|g;      $r->print(&Apache::loncommon::start_data_table_row()
     }                       .'<td>'.$file.'</td>');
     $title=~s/\.(\w+)$//;      my ($ext)=($file=~/\.(\w+)$/);
     $title=&clean($title);      my $title=$hash{'title_'.$hash{
     $title.='.'.$ext;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
                      .&Apache::loncommon::end_data_table_row());      if (!$title) {
  }   $title=$file;
  $r->print(&Apache::loncommon::end_data_table());      } else {
  &untiehash();   $title=~s|/|_|g;
  $r->print(      }
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      $title=~s/\.(\w+)$//;
     }      $title=&clean($title);
 }      $title.='.'.$ext;
       $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
                        .&Apache::loncommon::end_data_table_row());
    }
 sub exportbutton {   $r->print(&Apache::loncommon::end_data_table());
     my $type = &Apache::loncommon::course_type();   &untiehash();
     return '<input type="submit" name="exportcourse" value="'.   $r->print(
             &mt('Export '.$type.' to IMS').'" />'.    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');      }
 }      $r->print(&endContentScreen());
   }
   
   sub group_import {
 sub exportcourse {      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
     my $r=shift;      my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
     my $type = &Apache::loncommon::course_type();          %removeparam,$importuploaded,$fixuperrors);
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',      $allmaps = {};
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});      while (@files) {
     my $numdisc = keys(%discussiontime);   my ($name, $url, $residx) = @{ shift(@files) };
     my $navmap = Apache::lonnavmaps::navmap->new();          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
     if (!defined($navmap)) {       && ($caller eq 'londocs')
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').       && (!&Apache::lonnet::stat_file($url))) {
                   '<h2>IMS Export Failed</h2>'.  
                   '<div class="LC_error">'.              my $errtext = '';
                   &mt('Unable to retrieve information about course contents').              my $fatal = 0;
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');              my $newmapstr = '<map>'."\n".
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              '<resource id="1" src="" type="start"></resource>'."\n".
         return;                              '<link from="1" to="2" index="1"></link>'."\n".
     }                              '<resource id="2" src="" type="finish"></resource>'."\n".
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);                              '</map>';
     my $curRes;              $env{'form.output'}=$newmapstr;
     my $outcome;              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
                                                   'output',$1.$2);
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              if ($result !~ m{^/uploaded/}) {
                                             ['finishexport']);                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
     if ($env{'form.finishexport'}) {                  $fatal = 2;
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['archive','discussion']);              if ($fatal) {
                   return ($errtext,$fatal);
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');              }
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');          }
         if (@exportitems == 0 && @discussions == 0) {   if ($url) {
             $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';              if (($caller eq 'londocs') &&
         } else {                  ($folder =~ /^default/)) {
             my $now = time;                  if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
             my %symbs;                      my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
             my $manifestok = 0;                      my $cid = $coursedom.'_'.$coursenum;
             my $imsresources;                      $allmaps =
             my $tempexport;                          &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
             my $copyresult;                                                               $chome,$cid);
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);                      $donechk = 1;
             if ($manifestok) {                  }
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);                  if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
                 close($ims_manifest);                      &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
                                            \%addedmaps,\%hierarchy,\%titles,$allmaps);
 #Create zip file in prtspool                      $importuploaded = 1;
                 my $imszipfile = '/prtspool/'.                  } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.                      next if ($allmaps->{$url});
                    time.'_'.rand(1000000000).'.zip';                  }
                 my $cwd = &Cwd::getcwd();              }
                 my $imszip = '/home/httpd/'.$imszipfile;      if (!$residx
                 chdir $tempexport;   || defined($LONCAPA::map::zombies[$residx])) {
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");   $residx = &LONCAPA::map::getresidx($url,$residx);
                 close(OUTPUT);   push(@LONCAPA::map::order, $residx);
                 chdir $cwd;      }
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      my $ext = 'false';
                 if ($copyresult) {      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);      $url  = &LONCAPA::map::qtunescape($url);
                 }      $name = &LONCAPA::map::qtunescape($name);
             } else {              if ($name eq '') {
                 $outcome = '<br />'.&mt('Unfortunately you will not be able to retrieve an IMS archive of this posts at this time, because there was a problem creating a manifest file.').'<br />';                  $name = &mt('Web Page');
             }              }
         }              if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));                  my $filepath = $1;
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));                  my $fname = $name;
         $r->print($outcome);                  if ($fname =~ /^\W+$/) {
         $r->print(&Apache::loncommon::end_page());                      $fname = 'web';
     } else {                  } else {
         my $display;                      $fname =~ s/\W/_/g;
         $display = '<form name="exportdoc" method="post">'."\n";                  }
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                  if (length($fname > 15)) {
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                      $fname = substr($fname,0,14);
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.                  }
                     '<input type="button" value="check all" '.                  my $initialtext = &mt('Replace with your own content.');
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.                  my $newhtml = <<END;
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.  <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
                     '<td>&nbsp;</td><td>&nbsp;</td>'.  <head>
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                     '</b></legend><input type="button" value="check all"'.  <title>$name</title>
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.  </head>
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  <body bgcolor="#ffffff">
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.  $initialtext
                     '</tr></table>';  </body>
         my $curRes;  </html>
         my $depth = 0;  END
         my $count = 0;                  $env{'form.output'}=$newhtml;
         my $boards = 0;                  my $result = 
         my $startcount = 5;                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
         my %parent = ();                                                            'output',
         my %children = ();                                                            "$filepath/$residx/$fname.html");
         my $lastcontainer = $startcount;                  if ($result =~ m{^/uploaded/}) {
         my @bgcolors = ('#F6F6F6','#FFFFFF');                      $url = $result;
         $display .= '<table cellspacing="0"><tr>'.                      if ($filepath =~ /^supplemental/) {
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                          $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
         if ($numdisc > 0) {                                  $env{'user.domain'}.'___&&&___'.$name;
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                      }
         }                  } else {
         $display.='&nbsp;</td></tr>';                      return (&mt('Failed to save new web page.'),1);
         while ($curRes = $it->next()) {                  }
             if (ref($curRes)) {              }
                 $count ++;      $LONCAPA::map::resources[$residx] =
             }   join(':', ($name, $url, $ext, 'normal', 'res'));
             if ($curRes == $it->BEGIN_MAP()) {   }
                 $depth++;      }
                 $parent{$depth} = $lastcontainer;      if ($importuploaded) {
             }          my %import_errors;
             if ($curRes == $it->END_MAP()) {          my %updated = (
                 $depth--;                            removefrommap => \%removefrommap,
                 $lastcontainer = $parent{$depth};                            removeparam   => \%removeparam,
             }                        );
             if (ref($curRes)) {          my ($result,$msgsarray,$lockerror) = 
                 my $symb = $curRes->symb();              &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
                 my $ressymb = $symb;          if (keys(%import_errors) > 0) {
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {              $fixuperrors =
                     unless ($ressymb =~ m|adm/wrapper/adm|) {                  '<p span class="LC_warning">'."\n".
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';                  &mt('The following files are either dependencies of a web page or references within a folder and/or composite page for which errors occurred during import:')."\n".
                     }                  '<ul>'."\n";
                 }              foreach my $key (sort(keys(%import_errors))) {
                 my $color = $count%2;                  $fixuperrors .= '<li>'.$key.'</li>'."\n";
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".              }
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              $fixuperrors .= '</ul></p>'."\n";
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {          }
                     my $checkitem = $count + $boards + $startcount;          if (ref($msgsarray) eq 'ARRAY') {
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';              if (@{$msgsarray} > 0) {
                 }                  $fixuperrors .= '<p class="LC_info">'.
                 $display .= ' />'."\n";                                  join('<br />',@{$msgsarray}).
                 for (my $i=0; $i<$depth; $i++) {                                  '</p>';
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";              }
                 }          }
                 if ($curRes->is_sequence()) {          if ($lockerror) {
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";              $fixuperrors .= '<p class="LC_error">'.
                     $lastcontainer = $count + $startcount + $boards;                              $lockerror.
                 } elsif ($curRes->is_page()) {                              '</p>';
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";          }
                     $lastcontainer = $count + $startcount + $boards;      }
                 }      my ($errtext,$fatal) =
                 my $currelem = $count+$boards+$startcount;          &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
                 $children{$parent{$depth}} .= $currelem.':';      return ($errtext,$fatal,$fixuperrors);
                 $display .= '&nbsp;'.$curRes->title().'</td>';  }
                 if ($discussiontime{$ressymb} > 0) {  
                     $boards ++;  sub log_docs {
                     $currelem = $count+$boards+$startcount;      return &Apache::lonnet::write_log('course','docslog',@_);
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";  }
                 } else {  
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";  {
                 }      my @oldresources=();
             }      my @oldorder=();
         }      my $parmidx;
         my $scripttag = qq|      my %parmaction=();
 <script>      my %parmvalue=();
       my $changedflag;
 function checkAll(field) {  
     if (field.length > 0) {      sub snapshotbefore {
         for (i = 0; i < field.length; i++) {          @oldresources=@LONCAPA::map::resources;
             field[i].checked = true ;          @oldorder=@LONCAPA::map::order;
         }          $parmidx=undef;
     } else {          %parmaction=();
         field.checked = true          %parmvalue=();
     }          $changedflag=0;
 }      }
                                                                                  
 function uncheckAll(field) {      sub remember_parms {
     if (field.length > 0) {          my ($idx,$parameter,$action,$value)=@_;
         for (i = 0; i < field.length; i++) {          $parmidx=$idx;
             field[i].checked = false ;          $parmaction{$parameter}=$action;
         }          $parmvalue{$parameter}=$value;
     } else {          $changedflag=1;
         field.checked = false ;      }
     }  
 }      sub log_differences {
           my ($plain)=@_;
 function propagateCheck(item) {          my %storehash=('folder' => $plain,
     if (document.exportdoc.elements[item].checked == true) {                         'currentfolder' => $env{'form.folder'});
         containerCheck(item)          if ($parmidx) {
     }             $storehash{'parameter_res'}=$oldresources[$parmidx];
 }             foreach my $parm (keys(%parmaction)) {
                 $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
 function containerCheck(item) {                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
     document.exportdoc.elements[item].checked = true             }
     var numitems = $count + $boards + $startcount          }
     var parents = new Array(numitems)          my $maxidx=$#oldresources;
     for (var i=$startcount; i<numitems; i++) {          if ($#LONCAPA::map::resources>$#oldresources) {
         parents[i] = new Array             $maxidx=$#LONCAPA::map::resources;
     }          }
         |;          for (my $idx=0; $idx<=$maxidx; $idx++) {
              if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
         foreach my $container (sort { $a <=> $b } (keys(%children))) {                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
             my @contents = split(/:/,$children{$container});                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
             for (my $i=0; $i<@contents; $i ++) {                $changedflag=1;
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";             }
             }             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
         }                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
                 $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
         $scripttag .= qq|                $changedflag=1;
     if (parents[item].length > 0) {             }
         for (var j=0; j<parents[item].length; j++) {          }
             containerCheck(parents[item][j])   $storehash{'maxidx'}=$maxidx;
         }          if ($changedflag) { &log_docs(\%storehash); }
      }        }
 }  }
   
 </script>  sub docs_change_log {
         |;      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',      my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
  $scripttag));      my $js = '<script type="text/javascript">'."\n".
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));               '// <![CDATA['."\n".
  $r->print($display.'</table>'.               &Apache::loncommon::display_filter_js('docslog')."\n".
                   '<p><input type="hidden" name="finishexport" value="1">'.               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
                   '<input type="submit" name="exportcourse" value="'.               &history_tab_js()."\n".
                   &mt('Export '.$type.' DOCS').'" /></p></form>');               &Apache::lonratedt::editscript('simple')."\n".
     }               '// ]]>'."\n".
 }               '</script>'."\n";
       $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
 sub create_ims_store {      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
     my ($now,$manifestok,$outcome,$tempexport) = @_;      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';      my %orderhash;
     my $ims_manifest;      my $container='sequence';
     if (!-e $$tempexport) {      my $pathitem;
         mkdir($$tempexport,0700);      if ($env{'form.folderpath'} =~ /\:1$/) {
     }          $container='page';
     $$tempexport .= '/'.$now;      }
     if (!-e $$tempexport) {      my $folderpath=$env{'form.folderpath'};
         mkdir($$tempexport,0700);      if ($folderpath eq '') {
     }          $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Documents').':::::');
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};      }
     if (!-e $$tempexport) {      $pathitem = '<input type="hidden" name="folderpath" value="'.
         mkdir($$tempexport,0700);                  &HTML::Entities::encode($folderpath,'<>&"').'" />';
     }      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
     if (!-e "$$tempexport/resources") {      my $jumpto = $readfile;
         mkdir("$$tempexport/resources",0700);      $jumpto =~ s{^/}{};
     }      my $tid = 1;
 # open manifest file      if ($supplementalflag) {
     my $manifest = '/imsmanifest.xml';          $tid = 2;
     my $manifestfilename = $$tempexport.$manifest;      }
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {      my ($breadcrumbtrail) = 
         $$manifestok=1;          &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
         print $ims_manifest      $r->print($breadcrumbtrail.
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".                &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.                $readfile));
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.      my %docslog=&Apache::lonnet::dump('nohist_docslog',
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.                                        $env{'course.'.$env{'request.course.id'}.'.num'});
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.  
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 '  <metadata>  
     <schema></schema>      my %saveable_parameters = ('show' => 'scalar',);
     <imsmd:lom>      &Apache::loncommon::store_course_settings('docs_log',
       <imsmd:general>                                                \%saveable_parameters);
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>      &Apache::loncommon::restore_course_settings('docs_log',
         <imsmd:title>                                                  \%saveable_parameters);
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>      if (!$env{'form.show'}) { $env{'form.show'}=10; }
         </imsmd:title>  # FIXME: internationalization seems wrong here
       </imsmd:general>      my %lt=('hiddenresource' => 'Resources hidden',
     </imsmd:lom>      'encrypturl'     => 'URL hidden',
   </metadata>'."\n".      'randompick'     => 'Randomly pick',
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".      'randomorder'    => 'Randomly ordered',
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.      'set'            => 'set to',
 ' structure="hierarchical">'."\n".      'del'            => 'deleted');
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
     } else {                   $pathitem."\n".
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
 ;                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     }      $r->print('<div class="LC_left_float">'.
     return $ims_manifest;                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
 }                &makedocslogform($filter,1).
                 '</fieldset></div><br clear="all" />');
 sub build_package {      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
 # first iterator to look for dependencies                &mt('After').'</th>'.
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                &Apache::loncommon::end_data_table_header_row());
     my $curRes;      my $shown=0;
     my $count = 0;      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     my $depth = 0;   if ($env{'form.displayfilter'} eq 'currentfolder') {
     my $lastcontainer = 0;      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
     my %parent = ();   }
     my @dependencies = ();          my @changes=keys(%{$docslog{$id}{'logentry'}});
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};          if ($env{'form.displayfilter'} eq 'containing') {
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     while ($curRes = $it->next()) {   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
         if (ref($curRes)) {      foreach my $key (@changes) {
             $count ++;   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
         }      }
         if ($curRes == $it->BEGIN_MAP()) {      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
             $depth++;   }
             $parent{$depth} = $lastcontainer;          my $count = 0;
         }          my $time =
         if ($curRes == $it->END_MAP()) {              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
             $depth--;          my $plainname =
             $lastcontainer = $parent{$depth};              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
         }                                            $docslog{$id}{'exe_udom'});
         if (ref($curRes)) {          my $about_me_link =
             if ($curRes->is_sequence() || $curRes->is_page()) {              &Apache::loncommon::aboutmewrapper($plainname,
                 $lastcontainer = $count;                                                 $docslog{$id}{'exe_uname'},
             }                                                 $docslog{$id}{'exe_udom'});
             if (grep(/^$count$/,@$exportitems)) {          my $send_msg_link='';
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
             }               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
         }              $send_msg_link ='<br />'.
     }                  &Apache::loncommon::messagewrapper(&mt('Send message'),
 # second iterator to build manifest and store resources                                                     $docslog{$id}{'exe_uname'},
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);                                                     $docslog{$id}{'exe_udom'});
     $depth = 0;          }
     my $prevdepth;          $r->print(&Apache::loncommon::start_data_table_row());
     $count = 0;          $r->print('<td>'.$time.'</td>
     my $imsresources;                         <td>'.$about_me_link.
     my $pkgdepth;                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
     while ($curRes = $it->next()) {                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
         if ($curRes == $it->BEGIN_MAP()) {                    $send_msg_link.'</td><td>'.
             $prevdepth = $depth;                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
             $depth++;          my $is_supp = 0; 
         }          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
         if ($curRes == $it->END_MAP()) {              $is_supp = 1;
             $prevdepth = $depth;          }
             $depth--;  # Before
         }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
       my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
         if (ref($curRes)) {      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
             $count ++;      if ($oldname ne $newname) {
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {                  my $shown = &LONCAPA::map::qtescape($oldname);
                 my $symb = $curRes->symb();                  if ($is_supp) {
                 my $isvisible = 'true';                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                 my $resourceref;                  }
                 if ($curRes->randomout()) {                  $r->print($shown);
                     $isvisible = 'false';      }
                 }   }
                 unless ($curRes->is_sequence()) {   $r->print('<ul>');
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 }              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
                 my $step = $prevdepth - $depth;                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
                 if (($step >= 0) && ($count > 1)) {                  if ($is_supp) {
                     while ($step >= 0) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                         print $ims_manifest "\n".'  </item>'."\n";                  }
                         $step --;   $r->print('<li>'.$shown.'</li>');
                     }      }
                 }   }
                 $prevdepth = $depth;   $r->print('</ul>');
   # After
                 my $itementry =          $r->print('</td><td>');
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.  
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
               '<title>'.$curRes->title().'</title>';      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
                 print $ims_manifest "\n".$itementry;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
       if ($oldname ne '' && $oldname ne $newname) {
                 unless ($curRes->is_sequence()) {                  my $shown = &LONCAPA::map::qtescape($newname);
                     my $content_file;                  if ($is_supp) {
                     my @hrefs = ();                      $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);                  }
                     if ($content_file) {                  $r->print($shown);
                         $imsresources .= "\n".      }
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.   }
                      '" type="webcontent" href="'.$content_file.'">'."\n".   $r->print('<ul>');
                      '       <file href="'.$content_file.'" />'."\n";   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                         foreach my $item (@hrefs) {              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
                             $imsresources .=                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                      '        <file href="'.$item.'" />'."\n";                  if ($is_supp) {
                         }                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                         if (grep(/^$count$/,@$discussions)) {                  }
                             my $ressymb = $symb;                  $r->print('<li>'.$shown.'</li>');
                             my $mode;      }
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {   }
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {   $r->print('</ul>');
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                                 }      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
                                 $mode = 'board';      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                             }   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                             my %extras = (  # FIXME: internationalization seems wrong here
                                           caller => 'imsexport',      $r->print('<li>'.
                                           tempexport => $tempexport.'/resources',        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
                                           count => $count    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
                                          );        .'</li>');
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);   }
                         }      }
                         $imsresources .= '    </resource>'."\n";      $r->print('</ul>');
                     }   }
                 }  # End
                 $pkgdepth = $depth;          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
             }          $shown++;
         }          if (!($env{'form.show'} eq &mt('all')
     }                || $shown<=$env{'form.show'})) { last; }
     while ($pkgdepth > 0) {      }
         print $ims_manifest "    </item>\n";      $r->print(&Apache::loncommon::end_data_table()."\n".
         $pkgdepth --;                &makesimpleeditform($pathitem)."\n".
     }                '</div></div>');
     my $resource_text = qq|      $r->print(&endContentScreen());
     </organization>  }
   </organizations>  
   <resources>  sub update_paste_buffer {
     $imsresources      my ($coursenum,$coursedom,$folder) = @_;
   </resources>  
 </manifest>      return if (!defined($env{'form.markcopy'}));
     |;      return if (!defined($env{'form.copyfolder'}));
     print $ims_manifest $resource_text;      return if ($env{'form.markcopy'} < 0);
 }  
       my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 sub get_dependencies {      $env{'form.copyfolder'});
     my ($exportitems,$parent,$depth,$dependencies) = @_;  
     if ($depth > 1) {      return if ($fatal);
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {  
             push(@{$dependencies},$$parent{$depth});  # Mark for copying
             if ($depth > 2) {      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      if (&is_supplemental_title($title)) {
             }          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
         }   ($title) = &Apache::loncommon::parse_supplemental_title($title);
     }      } elsif ($env{'docs.markedcopy_supplemental'}) {
 }          &Apache::lonnet::delenv('docs.markedcopy_supplemental');
       }
 sub process_content {      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;  
     my $content_type;      (my $cmd,undef)=split('_',$env{'form.cmd'});
     my $message;  
     my @uploads = ();      my %addtoenv = (
     if ($curRes->is_sequence()) {                      'docs.markedcopy_title' => $title,
         $content_type = 'sequence';                      'docs.markedcopy_url'   => $url,
     } elsif ($curRes->is_page()) {                      'docs.markedcopy_cmd'   => $cmd,
         $content_type = 'page'; # need to handle individual items in pages.                     );
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {      &Apache::lonnet::delenv('docs.markedcopy_nested');
         $content_type = 'syllabus';      &Apache::lonnet::delenv('docs.markedcopy_nestednames');
         my $contents = &Apache::imsexport::templatedpage($content_type);      if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
         if ($contents) {          my $prefix = $1;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          my $subdir =$2;
         }          if ($subdir eq '') {
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {              $subdir = $prefix;
         $content_type = 'external';          }
         my $title = $curRes->title;          my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
         my $contents =  &Apache::imsexport::external($symb,$title);          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
         if ($contents) {                               \%hierarchy,\%titles,\%allmaps);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          if (ref($hierarchy{$url}) eq 'HASH') {
         }              my ($nested,$nestednames);
     } elsif ($symb =~ m-adm/navmaps$-) {              &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
         $content_type =  'navmap';              $nested =~ s/\&$//;
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {              $nestednames =~ s/\Q___&&&___\E$//;
         $content_type = 'simplepage';              if ($nested ne '') {
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);                  $addtoenv{'docs.markedcopy_nested'} = $nested;
         if ($contents) {              }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              if ($nestednames ne '') {
         }                  $addtoenv{'docs.markedcopy_nestednames'} = $nestednames;
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {              }
         $content_type = 'simpleproblem';          }
         my $contents =  &Apache::imsexport::simpleproblem($symb);      }
         if ($contents) {      &Apache::lonnet::appenv(\%addtoenv);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);      delete($env{'form.markcopy'});
         }  }
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {  
         $content_type = 'examupload';  sub recurse_uploaded_maps {
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {      my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
         $content_type = 'bulletinboard';      if (ref($hierarchy->{$url}) eq 'HASH') {
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
         if ($contents) {          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          my (@uploaded,@names,%shorter);
         }          for (my $i=0; $i<@maps; $i++) {
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
         $content_type = 'aboutme';              if ($inner ne '') {
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);                  push(@uploaded,$inner);
         if ($contents) {                  push(@names,&escape($titles[$i]));
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);                  $shorter{$maps[$i]} = $inner;
         }              }
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          }
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');          $$nestref .= "$dir:".join(',',@uploaded).'&';
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
         my $canedit = 0;          foreach my $map (@maps) {
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {              if ($shorter{$map} ne '') {
             $canedit= 1;                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
         }              }
 # only include problem code where current user is author          }
         if ($canedit) {      }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');      return;
         } else {  }
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');  
         }  sub print_paste_buffer {
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');      return if (!defined($env{'docs.markedcopy_url'}));
     }  
     if (@uploads > 0) {      my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent);
         foreach my $item (@uploads) {      my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
             my $uploadmsg = '';      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');          $is_external = 1;
             if ($uploadmsg) {      }
                 $$copyresult .= $uploadmsg."\n";  
             }      my ($canpaste,$nopaste,$othercrs,$areachange);
         }      if ($folder =~ /^supplemental/) {
     }          $canpaste = &supp_pasteable($env{'docs.markedcopy_url'});
     if ($message) {          unless ($canpaste) {
         $$copyresult .= $message."\n";              $nopaste = &mt('Paste into Supplemental Content unavailable for this type of content.');
     }          } 
 }      } else {
           $canpaste = 1;
 sub replicate_content {      }
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;  
     my ($map,$ind,$url);      if ($canpaste) {
     if ($caller eq 'templateupload') {          if ($env{'docs.markedcopy_url'} =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
         $url = $symb;              my $srcdom = $1;
         $url =~ s#//#/#g;              my $srcnum = $2;
     } else {              my $rem = $3;
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
     }                  $othercourse = 1;
     my $content;                  if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
     my $filename;                      if ($canpaste) {
     my $repstatus;                          $othercrs = '<br />'.&mt('(from another course).');  
     my $content_name;                      }
     if ($url =~ m-/([^/]+)$-) {                  } else {
         $filename = $1;                      $canpaste = 0;
         if (!-e $tempexport.'/resources') {                      $nopaste = &mt('Paste from another course unavailable.') 
             mkdir($tempexport.'/resources',0700);                  }
         }              }
         if (!-e $tempexport.'/resources/'.$count) {              if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
             mkdir($tempexport.'/resources/'.$count,0700);                  my $prefix = $1;
         }                  $parent = $2;
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;                  if ($folder !~ /^\Q$prefix\E/) {
         my $copiedfile;                      $areachange = 1;
         if ($copiedfile = Apache::File->new('>'.$destination)) {                  }
             my $content;                  $is_uploaded_map = 1;
             if ($caller eq 'resource') {              }
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';          }
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);      }
                 $content = &Apache::lonnet::getfile($filepath);  
                 if ($content eq -1) {      $r->print('<fieldset>'
                     $$message = 'Could not copy file '.$filename;               .'<legend>'.&mt('Clipboard').'</legend>');
                 } else {      my ($type,$buffer);
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');      if ($is_external) {
                     $repstatus = 'ok';          $type = &mt('External Resource');
                 }          $buffer = $type.': '.
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
                 my $rtncode;                    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')';
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);      } else {
                 if ($repstatus eq 'ok') {          my $icon = &Apache::loncommon::icon($extension);
                     if ($url =~ /\.html?$/i) {          if ($extension eq 'sequence' &&
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');              $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
                     }              $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                 } else {              $icon .= '/navmap.folder.closed.gif';
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";          }
                 }          $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
             } elsif ($caller eq 'noedit') {          $buffer = $icon.$type.': '.  &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'}));
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.      }
                 $repstatus = 'ok';      if ($canpaste) {
                 $content = 'Not the owner of this resource';          $r->print('<form name="pasteform" action="/adm/coursedocs" method="post">'.$buffer);
             }          if ((!$areachange) && (!$othercourse) &&
             if ($repstatus eq 'ok') {              ($env{'docs.markedcopy_cmd'} eq 'cut')) {
                 print $copiedfile $content;              if (($is_uploaded_map) || 
             }                  ($env{'docs.markedcopy_url'} =~ /(bulletinboard|smppg)$/) ||
             close($copiedfile);                  ($env{'docs.markedcopy_url'} =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
         } else {                  my ($copytext,$movetext);
             $$message = 'Could not open destination file for '.$filename."<br />\n";                  if ($is_uploaded_map) {
         }                      $copytext = &mt('Copy to new folder');
     } else {                      $movetext = &mt('Move old folder');
         $$message = 'Could not determine name of file for '.$symb."<br />\n";                  } elsif ($env{'docs.markedcopy_url'} =~ /bulletinboard$/) {
     }                      $copytext = &mt('Copy to new bulletin board (not posts)');
     if ($repstatus eq 'ok') {                      $movetext = &mt('Move old bulletin board (not posts)');
         $content_name = 'resources/'.$count.'/'.$filename;                  } elsif ($env{'docs.markedcopy_url'} =~ /smppg$/) {
     }                      $copytext = &mt('Copy to new simple page');
     return $content_name;                      $movetext = &mt('Move old simple page');
 }                  } else {
                       $copytext = &mt('Copy to new uploaded document');
 sub extract_media {                      $movetext = &mt('Move old uploaded document');
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;                  }
     my ($dirpath,$container);                  $r->print(('&nbsp;'x 4).'<span id="pasteoptionstext">'.
     my %allfiles = ();                            '<a href="javascript:showPasteOptions();" class="LC_menubuttons_link">'.
     my %codebase = ();                            &mt('Show Paste Options').'</a></span><br />'.
     if ($url =~ m-(.*/)([^/]+)$-) {                            '<div id="pasteoptions" class="LC_dccid">'.('&nbsp;'x 4).
         $dirpath = $1;                            '<label>'.
         $container = $2;                            '<input type="radio" name="docs.markedcopy_options" value="new" checked="checked" />'.
     } else {                            $copytext.'</label>'.('&nbsp;' x2).
         $dirpath = $url;                            '<label>'.   
         $container = '';                            '<input type="radio" name="docs.markedcopy_options" value="move" />'.
     }                            $movetext.'</label><br />');
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);                  if (($is_uploaded_map) && ($env{'docs.markedcopy_nested'})) {
     foreach my $embed_file (keys(%allfiles)) {                      $r->print('<br />'.&mt('Folder to paste contains sub-folders').
         my $filename;                                '<br /><table border="0">');
         if ($embed_file =~ m#([^/]+)$#) {                      my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested'});
             $filename = $1;                      my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames'});
         } else {                      my $lastdir = $parent;
             $filename = $embed_file;                      my %depths = (
         }                                     $lastdir => 0,
         my $newname = 'res/'.$filename;                                   );
         my ($rtncode,$embed_content,$repstatus);                      my (%display,%deps); 
         my $embed_url;                      for (my $i=0; $i<@pastemaps; $i++) {
         if ($embed_file =~ m-^/-) {                          ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
             $embed_url = $embed_file;           # points to absolute path                          my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
         } else {                          my @subfolders = split(/,/,$subfolderstr);
             if ($embed_file =~ m-https?://-) {                          $deps{$lastdir} = \@subfolders;
                 next;                           # points to url                          my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
             } else {                          my $depth = $depths{$lastdir} + 1;
                 $embed_url = $dirpath.$embed_file;  # points to relative path                          my $offset = int($depth * 4);
             }                          my $indent = ('&nbsp;' x $offset);
         }                          for (my $j=0; $j<@subfolders; $j++) {
         if ($caller eq 'resource') {                              $depths{$subfolders[$j]} = $depth;
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                                $display{$subfolders[$j]} = 
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);                                    '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
             $embed_content = &Apache::lonnet::getfile($embed_path);                                    '<td><label>'.
             unless ($embed_content eq -1) {                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
                 $repstatus = 'ok';                                    '<label>'.
             }                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="move" />'.
         } elsif ($caller eq 'uploaded') {                                    &mt('Move old').'</label>'.
                                                '</td></tr>';
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);                          }
         }                      }
         if ($repstatus eq 'ok') {                      &recurse_print($r,$parent,\%deps,\%display);
             my $destination = $tempexport.'/resources/'.$count.'/res';                      $r->print('</table>');
             if (!-e "$destination") {                  }
                 mkdir($destination,0755);                  $r->print('</div>');
             }              }
             $destination .= '/'.$filename;          }
             my $copiedfile;          $r->print('<br /><input type="submit" name="pastemarked" value="'.&mt('Paste').'" />'.$othercrs);
             if ($copiedfile = Apache::File->new('>'.$destination)) {          $r->print('
                 print $copiedfile $embed_content;          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
                 push(@{$href},'resources/'.$count.'/res/'.$filename);  ');
                 my $attrib_regexp = '';          $r->print('</form>');
                 if (@{$allfiles{$embed_file}} > 1) {      } else {
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});          $r->print(&mt('Paste buffer contains:').' '.$buffer.
                 } else {                    '<br /><p class="LC_info">'.$nopaste.'</p>');
                     $attrib_regexp = $allfiles{$embed_file}[0];      }
                 }      $r->print('</fieldset>');
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;  }
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {  
                     $$content =~ s#\Q$embed_file\E#$newname#gi;  sub recurse_print {
                 }      my ($r,$dir,$deps,$display) = @_;
             }      $r->print($display->{$dir}."\n");
         } else {      if (ref($deps->{$dir}) eq 'ARRAY') {
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";          foreach my $subdir (@{$deps->{$dir}}) {
         }              &recurse_print($r,$subdir,$deps,$display);
     }          }
     return;      }
 }  }
   
 sub store_template {  sub supp_pasteable {
     my ($contents,$tempexport,$count,$content_type) = @_;      my ($url) = @_;
     if ($contents) {      if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
         if ($tempexport) {          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
             if (!-e $tempexport.'/resources') {          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
                 mkdir($tempexport.'/resources',0700);          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
             }          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
             if (!-e $tempexport.'/resources/'.$count) {          return 1;
                 mkdir($tempexport.'/resources/'.$count,0700);      }
             }      return;
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';  }
             my $storetemplate;  
             if ($storetemplate = Apache::File->new('>'.$destination)) {  sub paste_popup_js {
                 print $storetemplate $contents;      my %lt = &Apache::lonlocal::texthash(
                 close($storetemplate);                                            show => 'Show Paste Options',
             }                                            hide => 'Hide Paste Options',
             if ($content_type eq 'external') {                                          );
                 return 'resources/'.$count.'/'.$content_type.'.html';      return <<"END";
             } else {  
                 return 'resources/'.$count.'/'.$content_type.'.xml';  function showPasteOptions() {
             }      document.getElementById('pasteoptions').style.display='block';
         }      document.getElementById('pasteoptions').style.textAlign='left';
     }      document.getElementById('pasteoptions').style.textFace='normal';
 }      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:hidePasteOptions();" class="LC_menubuttons_link">$lt{'hide'}</a><br />';
       return;
   }
 sub group_import {  
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;  function hidePasteOptions() {
       document.getElementById('pasteoptions').style.display='none';
     while (@files) {      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:showPasteOptions()" class="LC_menubuttons_link">$lt{'show'}</a>';
  my ($name, $url, $residx) = @{ shift(@files) };      return;
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})  }
      && ($caller eq 'londocs')  
      && (!&Apache::lonnet::stat_file($url))) {  END
       
             my $errtext = '';  }
             my $fatal = 0;  
             my $newmapstr = '<map>'."\n".  
                             '<resource id="1" src="" type="start"></resource>'."\n".  sub do_paste_from_buffer {
                             '<link from="1" to="2" index="1"></link>'."\n".      my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
                             '<resource id="2" src="" type="finish"></resource>'."\n".  
                             '</map>';  # Early out if paste buffer is empty
             $env{'form.output'}=$newmapstr;      if (!$env{'form.pastemarked'}) {
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,          return ();
                                                 'output',$1.$2);      }
             if ($result != m|^/uploaded/|) {  
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';  # Supplemental content may only include certain types of content
                 $fatal = 2;  # Early out if pasted content is not supported in Supplemental area
             }      if ($folder =~ /^supplemental/) {
             if ($fatal) {          unless (&supp_pasteable($env{'docs.markedcopy_url'})) {
                 return ($errtext,$fatal);              return (&mt('Paste failed: content type is not supported within Supplemental Content'));
             }          }
         }      }
  if ($url) {  
     if (!$residx  # Prepare to paste resource at end of list
  || defined($LONCAPA::map::zombies[$residx])) {      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
  $residx = &LONCAPA::map::getresidx($url,$residx);      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
  push(@LONCAPA::map::order, $residx);  
     }      my ($is_map,$srcdom,$srcnum,$prefixchg,%before,%after,%mapchanges,%tomove);
     my $ext = 'false';      if ($url=~/\.(page|sequence)$/) {
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }          $is_map = 1; 
     $url  = &LONCAPA::map::qtunescape($url);      }
     $name = &LONCAPA::map::qtunescape($name);      if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/([^/]+)}) {
     $LONCAPA::map::resources[$residx] =          $srcdom = $1;
  join(':', ($name, $url, $ext, 'normal', 'res'));          $srcnum = $2;
  }          my $oldprefix = $3;
     }  # When paste buffer was populated using an active role in a different course
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);  # check for mdc privilege in the course from which the resource was pasted 
 }          if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
               unless ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
 sub breadcrumbs {                  return (&mt('Paste failed: Item is from a different course which you do not have rights to edit.'));
     my ($where,$allowed,$type)=@_;              }
     &Apache::lonhtmlcommon::clear_breadcrumbs();          }
     my (@folders);  # When pasting content from Main Content to Supplemental Content and vice versa 
     if ($env{'form.pagepath'}) {  # URLs will contain different paths (which depend on whether pasted item is
         @folders = split('&',$env{'form.pagepath'});  # a folder/page or a document.   
     } else {          if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
         @folders=split('&',$env{'form.folderpath'});              $prefixchg = 1;
     }              %before = ( map => 'default',
     my $folderpath;                          doc => 'docs');
     my $cpinfo='';              %after =  ( map => 'supplemental',
     my $plain='';                          doc => 'supplemental' );
     my $randompick=-1;          } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
     my $isencrypted=0;              $prefixchg = 1;
     my $ishidden=0;              %before = ( map => 'supplemental',
     my $is_random_order=0;                          doc => 'supplemental');
     while (@folders) {              %after  = ( map => 'default',
  my $folder=shift(@folders);                          doc => 'docs');
     my $foldername=shift(@folders);          }
  if ($folderpath) {$folderpath.='&';}  
  $folderpath.=$folder.'&'.$foldername;  # If pasting an uploaded map, get list of contained uploaded maps.
  my $url='/adm/coursedocs?folderpath='.          my @nested;
     &escape($folderpath);          if ($env{'docs.markedcopy_nested'}) {
     my $name=&unescape($foldername);              my ($type) = ($oldprefix =~ /^(default|supplemental)/);
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername              my @items = split(/\&/,$env{'docs.markedcopy_nested'});
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;              my @deps = map { /\d+:([\d,]+$)/ } @items;
     if ($1 ne '') {              foreach my $dep (@deps) {
                $randompick=$1;                  if ($dep =~ /,/) {
             } else {                      push(@nested,split(/,/,$dep));
                $randompick=-1;                  } else {
             }                      push(@nested,$dep);
             if ($2) { $ishidden=1; }                  }
             if ($3) { $isencrypted=1; }              }
     if ($4 ne '') { $is_random_order = 1; }              foreach my $item (@nested) {
             if ($folder eq 'supplemental') {                  if ($env{'form.docs.markedcopy_'.$item} eq 'move') {
                 if ($allowed) {                      $tomove{$type.'_'.$item} = 1;
                     $name = &mt('Supplemental '.$type.' Documents');                  }
                 } else {              }
                     $name = &mt($type.' Documents');          }
                 }      }
             }  
     &Apache::lonhtmlcommon::add_breadcrumb(  # Maps need to be copied first
       {'href'=>$url.$cpinfo,      my ($oldurl,%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
        'title'=>$name,          %dbcopies,%zombies,%params,%docmoves,%mapmoves,%newsubdir,%newurls);
        'text'=>'<font size="+1">'.      $oldurl = $url;
    $name.'</font>',      if ($is_map) {
        'no_mt'=>1,  # If pasting a map, check if map contains other maps
        });          my ($allmaps,%hierarchy,%titles);
  $plain.=$name.' &gt; ';          $allmaps = {};
     }          if ($folder =~ /^default/) {
     $plain=~s/\&gt\;\s*$//;              $allmaps =
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',                  &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);                                                       $env{"course.$env{'request.course.id'}.home"},
 }                                                       $env{'request.course.id'});
           }
 sub log_docs {          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
     return &Apache::lonnet::instructor_log('docslog',@_);                               \%addedmaps,\%hierarchy,\%titles,$allmaps);
 }          if ($url=~ m{^/uploaded/}) {
               my $newurl;
 {              unless ($env{'form.docs.markedcopy_options'} eq 'move') {
     my @oldresources=();                  ($newurl,my $error) = 
     my @oldorder=();                      &get_newmap_url($url,$folder,$prefixchg,$coursedom,$coursenum,
     my $parmidx;                                      $srcdom,$srcnum,\$title,$allmaps,\%newurls);
     my %parmaction=();                  if ($error) {
     my %parmvalue=();                      return ($error);
     my $changedflag;                  }
                   if ($newurl ne '') {
     sub snapshotbefore {                      if ($newurl ne $url) {
         @oldresources=@LONCAPA::map::resources;                          if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
         @oldorder=@LONCAPA::map::order;                              $newsubdir{$url} = $1;
         $parmidx=undef;                          }
         %parmaction=();                          $mapchanges{$url} = 1;
         %parmvalue=();                      }
         $changedflag=0;                  }
     }              }
               if (($srcdom ne $coursedom) || ($srcnum ne $coursenum) || ($prefixchg) ||
     sub remember_parms {                  (($newurl ne '') && ($newurl ne $url))) {
         my ($idx,$parameter,$action,$value)=@_;                  unless (&url_paste_fixups($url,$folder,$prefixchg,$coursedom,
         $parmidx=$idx;                                            $coursenum,$srcdom,$srcnum,$allmaps,
         $parmaction{$parameter}=$action;                                            \%rewrites,\%retitles,\%copies,\%dbcopies,
         $parmvalue{$parameter}=$value;                                            \%zombies,\%params,\%mapmoves,\%mapchanges,\%tomove,
         $changedflag=1;                                            \%newsubdir,\%newurls)) {
     }                      $mapmoves{$url} = 1;
                   }
     sub log_differences {                  $url = $newurl;
         my ($plain)=@_;              } elsif ($env{'docs.markedcopy_nested'}) {
         my %storehash=('folder' => $plain,                  &url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,
                        'currentfolder' => $env{'form.folder'});                                    $srcdom,$srcnum,$allmaps,\%rewrites,
         if ($parmidx) {                                    \%retitles,\%copies,\%dbcopies,\%zombies,\%params,\%mapmoves,
            $storehash{'parameter_res'}=$oldresources[$parmidx];                                    \%mapchanges,\%tomove,\%newsubdir,\%newurls); 
            foreach my $parm (keys(%parmaction)) {              }
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};          } elsif ($url=~m {^/res/}) {
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};  # published maps can only exists once, so remove it from paste buffer when done
            }              &Apache::lonnet::delenv('docs.markedcopy');
         }  # if pasting published map (main content are only) check map is not already in course
         my $maxidx=$#oldresources;              if ($folder =~ /^default/) {
         if ($#LONCAPA::map::resources>$#oldresources) {                  if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
            $maxidx=$#LONCAPA::map::resources;                      return (&mt('Paste failed: only one instance of a particular published sequence or page is allowed within each course.'));
         }                  }
         for (my $idx=0; $idx<=$maxidx; $idx++) {              }
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {          }
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];      }
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];      my $lockerrors;
               $changedflag=1;      if ($url=~ m{/(bulletinboard|smppg)$}) {
            }          my $prefix = $1;
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {          #need to copy the db contents to a new one, unless this is a move.
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];          my %info = (
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];                       src  => $url,
               $changedflag=1;                       cdom => $coursedom,
            }                       cnum => $coursenum,
         }          );
  $storehash{'maxidx'}=$maxidx;          my (%lockerr,$msg);
         if ($changedflag) { &log_docs(\%storehash); }          unless ($env{'form.docs.markedcopy_options'} eq 'move') {
     }              my ($newurl,$result,$errtext) =
 }                  &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
               if ($result eq 'ok') {
                   $url = $newurl;
                   $title=&mt('Copy of').' '.$title;
               } else {
                   if ($prefix eq 'smppg') {
 sub docs_change_log {                      $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
     my ($r)=@_;                  } elsif ($prefix eq 'bulletinboard') {
     my $folder=$env{'form.folder'};                      $msg = &mt('Paste failed: An error occurred when copying the bulletin board.').' '.$errtext;
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));                  }
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));                  return ($result,undef,[$msg],$lockerr{$prefix});
     my %docslog=&Apache::lonnet::dump('nohist_docslog',      }
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},              if ($lockerr{$prefix}) {
                                       $env{'course.'.$env{'request.course.id'}.'.num'});                  $lockerrors = $lockerr{$prefix};  
               }
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }          }
       }
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.      $title = &LONCAPA::map::qtunescape($title);
               '<input type="hidden" name="docslog" value="1" />');      my $ext='false';
       if ($url=~m{^http(|s)://}) { $ext='true'; }
     my %saveable_parameters = ('show' => 'scalar',);      $url       = &LONCAPA::map::qtunescape($url);
     &Apache::loncommon::store_course_settings('docs_log',  
                                               \%saveable_parameters);  # For uploaded files (excluding pages/sequences) path in copied file is changed
     &Apache::loncommon::restore_course_settings('docs_log',  # if paste is from Main to Supplemental (or vice versa), or if pasting between
                                                 \%saveable_parameters);  # courses.
     if (!$env{'form.show'}) { $env{'form.show'}=10; }  
     my %lt=('hiddenresource' => 'Resources hidden',      my $newidx;
     'encrypturl'     => 'URL hidden',      unless ($is_map) {
     'randompick'     => 'Randomly pick',  # Now insert the URL at the bottom
     'randomorder'    => 'Randomly ordered',          $newidx = &LONCAPA::map::getresidx($url);
     'set'            => 'set to',          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
     'del'            => 'deleted');              my $relpath = $1;
     $r->print(&Apache::loncommon::display_filter().              if ($relpath ne '') {
               '<input type="hidden" name="folder" value="'.$folder.'" />'.                  my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
               '<input type="submit" value="'.&mt('Display').'" /></form>');                  my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().                  my $newprefix = $newloc;
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.                  if ($newloc eq 'default') {
               &mt('After').'</th>'.                      $newprefix = 'docs';
               &Apache::loncommon::end_data_table_header_row());                  }
     my $shown=0;                  if ($newdocsdir eq '') {
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {                      $newdocsdir = 'default';
  if ($env{'form.displayfilter'} eq 'currentfolder') {                  }
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }                  if (($prefixchg) || 
  }                      ($srcdom ne $coursedom) || ($srcnum ne $coursenum) ||
         my @changes=keys(%{$docslog{$id}{'logentry'}});                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
         if ($env{'form.displayfilter'} eq 'containing') {                      my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.                      $url =
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});                          &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
     foreach my $key (@changes) {                                                             &Apache::lonnet::getfile($oldurl));
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};                      if ($url eq '/adm/notfound.html') {
     }                          return (&mt('Paste failed: an error occurred saving the file.'));
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }                              } else {
  }                          my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
         my $count = 0;                          $newsubpath =~ s{/+$}{/};
         my $time =                          $docmoves{$oldurl} = $newsubpath;
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});                      }
         my $plainname =                  }
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},              }
                                           $docslog{$id}{'exe_udom'});          }
         my $about_me_link =      }
             &Apache::loncommon::aboutmewrapper($plainname,  # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
                                                $docslog{$id}{'exe_uname'},      my ($result,$save_err);
                                                $docslog{$id}{'exe_udom'});      my %updated = (
         my $send_msg_link='';                      rewrites      => \%rewrites,
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})                      zombies       => \%zombies,
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {                      removefrommap => \%removefrommap,
             $send_msg_link ='<br />'.                      removeparam   => \%removeparam,
                 &Apache::loncommon::messagewrapper(&mt('Send message'),                      dbcopies      => \%dbcopies,
                                                    $docslog{$id}{'exe_uname'},                      retitles      => \%retitles,
                                                    $docslog{$id}{'exe_udom'});                    );
         }      my %info = (
         $r->print(&Apache::loncommon::start_data_table_row());                     newsubdir => \%newsubdir,
         $r->print('<td>'.$time.'</td>                     params    => \%params,
                        <td>'.$about_me_link.                     before    => \%before,
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.                     after     => \%after,
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                 );
                   $send_msg_link.'</td><td>'.      my %moves = (
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');                     copies   => \%copies,
 # Before                     docmoves => \%docmoves,
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                     mapmoves => \%mapmoves,
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                  );
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];      ($result,my $msgsarray,my $lockerror) =
     if ($oldname ne $newname) {          &apply_fixups($folder,$is_map,$coursedom,$coursenum,$errors,
  $r->print(&LONCAPA::map::qtescape($oldname));                        \%updated,\%info,\%moves,$prefixchg,$oldurl,$url,'paste');
     }      $lockerrors .= $lockerror;
  }      if ($result eq 'ok') {
  $r->print('<ul>');          if ($is_map) { 
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {                                              $folder.'.'.$container);
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');              return ($errtext,$save_err,$msgsarray,$lockerrors) if ($fatal);
     }  
  }              if ($#LONCAPA::map::order<1) {
  $r->print('</ul>');                  my $idx=&LONCAPA::map::getresidx();
 # After                  if ($idx<=0) { $idx=1; }
         $r->print('</td><td>');                  $LONCAPA::map::order[0]=$idx;
                   $LONCAPA::map::resources[$idx]='';
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              }
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];              $newidx = &LONCAPA::map::getresidx($url);
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];          }
     if ($oldname ne '' && $oldname ne $newname) {          if ($env{'docs.markedcopy_supplemental'}) {
  $r->print(&LONCAPA::map::qtescape($newname));              if ($folder !~ /^supplemental/) {
     }                  (undef,undef,$title) =
  }                              &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental'});
  $r->print('<ul>');              }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          } else {
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {              if ($folder=~/^supplemental/) {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     }                         $env{'user.domain'}.'___&&&___'.$title;
  }              }
  $r->print('</ul>');          }
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {          $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');          push(@LONCAPA::map::order, $newidx);
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {  
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {  # Store the result
     $r->print('<li>'.          my ($errtext,$fatal) = 
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})          if ($fatal) {
       .'</li>');              $save_err = $errtext;
  }          }
     }      }
     $r->print('</ul>');  
  }      if ($env{'form.docs.markedcopy_options'} eq 'move') {
 # End          &Apache::lonnet::delenv('docs.markedcopy');
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());          &Apache::lonnet::delenv('docs.markedcopy_nested');
         $shown++;          &Apache::lonnet::delenv('docs.markedcopy_nestednames');
         if (!($env{'form.show'} eq &mt('all')      }
               || $shown<=$env{'form.show'})) { last; }      return ($result,$save_err,$msgsarray,$lockerrors);
     }  }
     $r->print(&Apache::loncommon::end_data_table());  
 }  sub get_newmap_url {
       my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
 sub update_paste_buffer {          $titleref,$allmaps,$newurls) = @_;
     my ($coursenum,$coursedom) = @_;      my $newurl;
       if ($url=~ m{^/uploaded/}) {
     return if (!defined($env{'form.markcopy'}));          $$titleref=&mt('Copy of').' '.$$titleref;
     return if (!defined($env{'form.copyfolder'}));      }
     return if ($env{'form.markcopy'} < 0);      my $now = time;
       my $suffix=$$.int(rand(100)).$now;
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
     $env{'form.copyfolder'});      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
              my $path = $1;
     return if ($fatal);          my $prefix = $2;
           my $ancestor = $3;
 # Mark for copying          if (length($ancestor) > 10) {
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);              $ancestor = substr($ancestor,-10,10);
     if (&is_supplemental_title($title)) {          }
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});          my $newid;
  ($title) = &parse_supplemental_title($title);          if ($prefixchg) {
     } elsif ($env{'docs.markedcopy_supplemental'}) {              if ($folder =~ /^supplemental/) {
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');                  $prefix =~ s/^default/supplemental/;
     }              } else {
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};                  $prefix =~ s/^supplemental/default/;
               }
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,          }
     'docs.markedcopy_url'   => $url});          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
     delete($env{'form.markcopy'});              $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
 }          } else {
               $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
 sub print_paste_buffer {          }
     my ($r,$container) = @_;          my $counter = 0;
     return if (!defined($env{'docs.markedcopy_url'}));          my $is_unique = &uniqueness_check($newurl);
           if ($folder =~ /^default/) {
     $r->print(<<ENDPASTE);              if ($allmaps->{$newurl}) {
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>                  $is_unique = 0;
 ENDPASTE              }
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');          }
           while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
     my $type;              $counter ++;
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {              $suffix ++;
  $type = &mt('External Resource');              if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
  $r->print($type.': '.                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.              } else {
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
     }  else {              }
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];              $is_unique = &uniqueness_check($newurl);
  my $icon = &Apache::loncommon::icon($extension);          }
  if ($extension eq 'sequence' &&          if ($is_unique) {
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {              $newurls->{$newurl} = 1;
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));          } else {
     $icon .= '/folder_closed.gif';              if ($url=~/\.page$/) {
  }                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';              } else {
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
     }              }
     if ($container eq 'page') {          }
  $r->print('      }
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />      return ($newurl);
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />  }
 ');  
     } else {  sub dbcopy {
  $r->print('      my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />      my ($url,$result,$errtext);
 ');      my $url = $dbref->{'src'};
     }      if (ref($dbref) eq 'HASH') {
     $r->print('</p></form>');          if ($url =~ m{/(smppg|bulletinboard)$}) {
 }              my $prefix = $1;
               if (($dbref->{'cdom'} =~ /^$match_domain$/) && 
 sub do_paste_from_buffer {                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
     my ($coursenum,$coursedom,$folder) = @_;                  my $db_name;
                   my $marker = (split(m{/},$url))[4];
     if (!$env{'form.pastemarked'}) {                  $marker=~s/\D//g;
         return;                  if ($dbref->{'src'} =~ m{/smppg$}) {
     }                      $db_name =
                           &Apache::lonsimplepage::get_db_name($url,$marker,
 # paste resource to end of list                                                              $dbref->{'cdom'},
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});                                                              $dbref->{'cnum'});
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});                  } else {
 # Maps need to be copied first                      $db_name = 'bulletinpage_'.$marker;
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {                  }
  $title=&mt('Copy of').' '.$title;                  my ($suffix,$freedlock,$error) =
  my $newid=$$.int(rand(100)).time;                      &Apache::lonnet::get_timebased_id($prefix,'num','templated',
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);                                                        $coursedom,$coursenum,
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {                                                        'concat');
             my $path = $1;                  if (!$suffix) {
             my $prefix = $2;                      if ($prefix eq 'smppg') {
             my $ancestor = $3;                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
             if (length($ancestor) > 10) {                      } else {
                 $ancestor = substr($ancestor,-10,10);                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a bulletin board [_1].',$url);
             }                      }
             $oldid = $path.$prefix.$ancestor;                      if ($error) {
         }                          $errtext .= '<br />'.$error;
         my $counter = 0;                      }
         my $newurl=$oldid.$newid.'.'.$ext;                  } else {
         my $is_unique = &uniqueness_check($newurl);                      #need to copy the db contents to a new one.
         while (!$is_unique && $counter < 100) {                      my %contents=&Apache::lonnet::dump($db_name,
             $counter ++;                                                         $dbref->{'cdom'},
             $newid ++;                                                         $dbref->{'cnum'});
             $newurl = $oldid.$newid;                      if (exists($contents{'uploaded.photourl'})) {
             $is_unique = &uniqueness_check($newurl);                          my $photo = $contents{'uploaded.photourl'};
         }                          my ($subdir,$fname) =
         if (!$is_unique) {                              ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
             if ($url=~/\.page$/) {                          my $newphoto; 
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');                          if ($fname ne '') {
             } else {                              my $content = &Apache::lonnet::getfile($photo);
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');                              unless ($content eq '-1') {
             }                                  $env{'form.'.$suffix.'.photourl'} = $content;
         }                                  $newphoto = 
  my $storefn=$newurl;                                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};                                  delete($env{'form.'.$suffix.'.photourl'});
  my $paste_map_result =                              }
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                          }
        &Apache::lonnet::getfile($url));                          if ($newphoto =~ m{^/uploaded/}) {
         if ($paste_map_result eq '/adm/notfound.html') {                              $contents{'uploaded.photourl'} = $newphoto;
             if ($url=~/\.page$/) {                          }
                 return &mt('Paste failed: an error occurred saving the composite page');                      }
             } else {                      $db_name =~ s{_\d*$ }{_$suffix}x;
                 return &mt('Paste failed: an error occurred saving the folder');                      $result=&Apache::lonnet::put($db_name,\%contents,
             }                                                   $coursedom,$coursenum);
         }                      if ($result eq 'ok') {
  $url = $newurl;                          $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
     }                      }
 # published maps can only exists once, so remove it from paste buffer when done                  }
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {                  if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
  &Apache::lonnet::delenv('docs\\.markedcopy');                      $lockerrorsref->{$prefix} = 
     }                          '<div class="LC_error">'.
     if ($url=~ m{/smppg$}) {                          &mt('There was a problem removing a lockfile.');
  my $db_name = &Apache::lonsimplepage::get_db_name($url);                      if ($prefix eq 'smppg') {
  if ($db_name =~ /^smppage_/) {                          $lockerrorsref->{$prefix} .= 
     #simple pages, need to copy the db contents to a new one.                              &mt('This will prevent creation of additional simple pages in this course.');
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);                      } else {
     my $now = time();                          $lockerrorsref->{$prefix} .= &mt('This will prevent creation of additional bulletin boards in this course.');
     $db_name =~ s{_\d*$ }{_$now}x;                      }
     my $result=&Apache::lonnet::put($db_name,\%contents,                      $lockerrorsref->{$prefix} .= &mt('Please contact the domain coordinator for your LON-CAPA domain.').'</div>';
     $coursedom,$coursenum);                  }
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;              }
     $title=&mt('Copy of').' '.$title;          } elsif ($url =~ m{/syllabus$}) {
  }              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
     }                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
     $title = &LONCAPA::map::qtunescape($title);                  if (($dbref->{'cdom'} ne $coursedom) ||
     my $ext='false';                      ($dbref->{'cnum'} ne $coursenum)) {
     if ($url=~m{^http(|s)://}) { $ext='true'; }                      my %contents=&Apache::lonnet::dump('syllabus',
     $url       = &LONCAPA::map::qtunescape($url);                                                         $dbref->{'cdom'},
 # Now insert the URL at the bottom                                                         $dbref->{'cnum'});
     my $newidx = &LONCAPA::map::getresidx($url);                      $result=&Apache::lonnet::put('syllabus',\%contents,
     if ($env{'docs.markedcopy_supplemental'}) {                                                   $coursedom,$coursenum);
         if ($folder =~ /^supplemental/) {                  }
             $title = $env{'docs.markedcopy_supplemental'};              }
         } else {          }
             (undef,undef,$title) =      }
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});      return ($url,$result,$errtext);
         }  }
     } else {  
         if ($folder=~/^supplemental/) {  sub uniqueness_check {
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.      my ($newurl) = @_;
                   $env{'user.domain'}.'___&&&___'.$title;      my $unique = 1;
         }      foreach my $res (@LONCAPA::map::order) {
     }          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
           $url=&LONCAPA::map::qtescape($url);
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';          if ($newurl eq $url) {
     push(@LONCAPA::map::order, $newidx);              $unique = 0;
     return 'ok';              last;
 # Store the result          }
 }      }
       return $unique;
 sub uniqueness_check {  }
     my ($newurl) = @_;  
     my $unique = 1;  sub contained_map_check {
     foreach my $res (@LONCAPA::map::order) {      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);          $allmaps) = @_;
         $url=&LONCAPA::map::qtescape($url);      my $content = &Apache::lonnet::getfile($url);
         if ($newurl eq $url) {      unless ($content eq '-1') {
             $unique = 0;          my $parser = HTML::TokeParser->new(\$content);
             last;              $parser->attr_encoded(1);
         }          while (my $token = $parser->get_token) {
     }              next if ($token->[0] ne 'S');
     return $unique;              if ($token->[1] eq 'resource') {
 }                  next if ($token->[2]->{'type'} eq 'zombie');
                   my $ressrc = $token->[2]->{'src'};
 my %parameter_type = ( 'randompick'     => 'int_pos',                  if ($folder =~ /^supplemental/) {
        'hiddenresource' => 'string_yesno',                      unless (&supp_pasteable($ressrc)) {
        'encrypturl'     => 'string_yesno',                          $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
        'randomorder'    => 'string_yesno',);                          next;
 my $valid_parameters_re = join('|',keys(%parameter_type));                      }
 # set parameters                  }
 sub update_parameter {                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
                       if ($1 eq 'uploaded') {
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
                           $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
     my $which = $env{'form.changeparms'};                      } else {
     my $idx = $env{'form.setparms'};                          if ($allmaps->{$ressrc}) {
     if ($env{'form.'.$which.'_'.$idx}) {                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
                                      : 'yes';                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,                          } else {
       $parameter_type{$which});                              $addedmaps->{$ressrc} = [$url];
  &remember_parms($idx,$which,'set',$value);                          }
     } else {                      }
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
                                            $addedmaps,$hierarchy,$titles,$allmaps);
  &remember_parms($idx,$which,'del');                  }
     }              } elsif ($token->[1] eq 'param') {
     return 1;                  if ($folder =~ /^supplemental/) {
 }                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
                           push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
                       } else {
 sub handle_edit_cmd {                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
     my ($coursenum,$coursedom) =@_;                      }
                   }
     my ($cmd,$idx)=split('_',$env{'form.cmd'});              }
           }
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];      }
     my ($title, $url, @rrest) = split(':', $ratstr);      return;
   }
     if ($cmd eq 'del') {  
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&  sub url_paste_fixups {
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {      my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
     &Apache::lonnet::removeuploadedurl($url);          $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
  } else {          $mapchanges,$tomove,$newsubdir,$newurls) = @_;
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);      my $checktitle;
  }      if (($prefixchg) &&
  splice(@LONCAPA::map::order, $idx, 1);          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
           $checktitle = 1;
     } elsif ($cmd eq 'cut') {      }
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);      my $skip;
  splice(@LONCAPA::map::order, $idx, 1);      if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
           my $mapid = $1.$2;
     } elsif ($cmd eq 'up'          if ($tomove->{$mapid}) {
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {              $skip = 1;
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];          }
       }
     } elsif ($cmd eq 'down'      my $file = &Apache::lonnet::getfile($oldurl);
      && defined($LONCAPA::map::order[$idx+1])) {      return if ($file eq '-1');
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];      my $parser = HTML::TokeParser->new(\$file);
       $parser->attr_encoded(1);
     } elsif ($cmd eq 'rename') {      my $changed = 0;
       while (my $token = $parser->get_token) {
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});          next if ($token->[0] ne 'S');
  if ($comment=~/\S/) {          if ($token->[1] eq 'resource') {
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=              my $ressrc = $token->[2]->{'src'};
  $comment.':'.join(':', $url, @rrest);              next if ($ressrc eq '');
  }              my $id = $token->[2]->{'id'};
 # Devalidate title cache              my $title = $token->[2]->{'title'};
  my $renamed_url=&LONCAPA::map::qtescape($url);              if ($checktitle) {
  &Apache::lonnet::devalidate_title_cache($renamed_url);                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
     } else {                      $retitles->{$oldurl}{$id} = $ressrc;
  return 0;                  }
     }              }
     return 1;              next if ($token->[2]->{'type'} eq 'external');
 }              if ($token->[2]->{'type'} eq 'zombie') {
                   next if ($skip);  
 sub editor {                  $zombies->{$oldurl}{$id} = $ressrc;
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;                  $changed = 1;
               } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
     my $container= ($env{'form.pagepath'}) ? 'page'                  my $srcdom = $1;
                            : 'sequence';                  my $srcnum = $2;
                   my $rem = $3;
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,                  my $newurl;
     $folder.'.'.$container);                  my $mapname;
     return $errtext if ($fatal);                  if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
                       my $prefix = $1;
     if ($#LONCAPA::map::order<1) {                      $mapname = $prefix.$2;
  my $idx=&LONCAPA::map::getresidx();                      if ($tomove->{$mapname}) {
  if ($idx<=0) { $idx=1; }                          &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
         $LONCAPA::map::order[0]=$idx;                                            $srcdom,$srcnum,$allmaps,$rewrites,
         $LONCAPA::map::resources[$idx]='';                                            $retitles,$copies,$dbcopies,$zombies,
     }                                            $params,$mapmoves,$mapchanges,$tomove,
                                                $newsubdir,$newurls);
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=                          next;
  &breadcrumbs($folder,$allowed,$type);                      } else {
     $r->print($breadcrumbtrail);                          ($newurl,my $error) =
                                  &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
 # ------------------------------------------------------------ Process commands                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
                           if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
 # ---------------- if they are for this folder and user allowed to make changes                              $newsubdir->{$ressrc} = $1;
     if (($allowed) && ($env{'form.folder'} eq $folder)) {                          }
 # set parameters and change order                          if ($error) {
  &snapshotbefore();                              next;
                           }
  if (&update_parameter()) {                      }
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                  }
     return $errtext if ($fatal);                  if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
  }                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
                      
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
 # change order                          $rewrites->{$oldurl}{$id} = $ressrc;
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);                          $mapchanges->{$ressrc} = 1;
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
                                                     $cnum,$srcdom,$srcnum,$allmaps,
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                                                    $rewrites,$retitles,$copies,$dbcopies,
     return $errtext if ($fatal);                                                    $zombies,$params,$mapmoves,$mapchanges,
  }                                                    $tomove,$newsubdir,$newurls)) {
                                   $mapmoves->{$ressrc} = 1;
  if ($env{'form.pastemarked'}) {                          }
             my $paste_res =                          $changed = 1;
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);                      } else {
             if ($paste_res eq 'ok') {                          $rewrites->{$oldurl}{$id} = $ressrc;
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);                          $copies->{$oldurl}{$ressrc} = $id;
                 return $errtext if ($fatal);                          $changed = 1;
             } elsif ($paste_res ne '') {                      }
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');                  }
             }              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
  }                  next if ($skip);
                   my $srcdom = $1;
  $r->print($upload_output);                  my $srcnum = $2;
                   if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
  if (&handle_edit_cmd()) {                      $rewrites->{$oldurl}{$id} = $ressrc;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
     return $errtext if ($fatal);                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
  }                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
 # Group import/search                      $changed = 1;
  if ($env{'form.importdetail'}) {                  }
     my @imports;              } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {                  if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
  if (defined($item)) {                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
     my ($name,$url,$residx)=                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
  map {&unescape($_)} split(/\=/,$item);                      $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
     push(@imports, [$name, $url, $residx]);                      $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
  }                      $changed = 1;
     }                  }
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,              } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
     $container,'londocs',@imports);                  next if ($skip);
     return $errtext if ($fatal);                  my $srcdom = $1;
  }                  my $srcnum = $2;
 # Loading a complete map                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
  if ($env{'form.loadmap'}) {                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
     if ($env{'form.importmap'}=~/\w/) {                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
     my ($title,$url,$ext,$type)=split(/\:/,$res);                      $changed = 1;
     my $idx=&LONCAPA::map::getresidx($url);                  }
     $LONCAPA::map::resources[$idx]=$res;              }
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;          } elsif ($token->[1] eq 'param') {
  }              next if ($skip);
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,              my $to = $token->[2]->{'to'}; 
     $folder.'.'.$container);              if ($to ne '') {
  return $errtext if ($fatal);                  if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
     } else {                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');                  } else {
                       @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
     }                  }
  }              }
  &log_differences($plain);          }
     }      }
 # ---------------------------------------------------------------- End commands      return $changed;
 # ---------------------------------------------------------------- Print screen  }
     my $idx=0;  
     my $shown=0;  sub apply_fixups {
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {      my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
  $r->print('<p>'.&mt('Parameters').':<ul>'.          $oldurl,$url,$caller) = @_;
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').      my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').          %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').          %lockerrors,$lockmsg);
   '</ul></p>');      if (ref($updated) eq 'HASH') {
     }                                                                                                              if (ref($updated->{'rewrites'}) eq 'HASH') {
     if ($randompick>=0) {              %rewrites = %{$updated->{'rewrites'}};
  $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');          }
     }          if (ref($updated->{'zombies'}) eq 'HASH') {
     if ($is_random_order) {              %zombies = %{$updated->{'zombies'}};
  $r->print('<p>'.&mt('Caution: this folder is set to randomly order its contents. Adding or removing resources from this folder will change the order of resources shown.').'</p>');          }
     }          if (ref($updated->{'removefrommap'}) eq 'HASH') {
     $r->print('<table class="LC_docs_editor">');              %removefrommap = %{$updated->{'removefrommap'}};
     foreach my $res (@LONCAPA::map::order) {          }
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);          if (ref($updated->{'removeparam'}) eq 'HASH') {
  $name=&LONCAPA::map::qtescape($name);              %removeparam = %{$updated->{'removeparam'}};
  $url=&LONCAPA::map::qtescape($url);          }
  unless ($name) {  $name=(split(/\//,$url))[-1]; }          if (ref($updated->{'dbcopies'}) eq 'HASH') {
  unless ($name) { $idx++; next; }              %dbcopies = %{$updated->{'dbcopies'}};
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,          }
      $coursenum));          if (ref($updated->{'retitles'}) eq 'HASH') {
  $idx++;              %retitles = %{$updated->{'retitles'}};
  $shown++;          }
     }      }
     unless ($shown) {      if (ref($info) eq 'HASH') {
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');          if (ref($info->{'newsubdir'}) eq 'HASH') {
     }              %newsubdir = %{$info->{'newsubdir'}};
     $r->print("\n</table>\n");          }
     if ($allowed) {          if (ref($info->{'params'}) eq 'HASH') {
         &print_paste_buffer($r,$container);              %params = %{$info->{'params'}};
     }          }
     return;          if (ref($info->{'before'}) eq 'HASH') {
 }              %before = %{$info->{'before'}};
           }
 sub process_file_upload {          if (ref($info->{'after'}) eq 'HASH') {
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;              %after = %{$info->{'after'}};
 # upload a file, if present          }
     my $parseaction;      }
    if ($env{'form.parserflag'}) {      if (ref($moves) eq 'HASH') {
         $parseaction = 'parse';          if (ref($moves->{'copies'}) eq 'HASH') {
     }              %copies = %{$moves->{'copies'}};
     my $phase_status;          }
     my $folder=$env{'form.folder'};          if (ref($moves->{'docmoves'}) eq 'HASH') {
     if ($folder eq '') {              %docmoves = %{$moves->{'docmoves'}};
         $folder='default';          }
     }          if (ref($moves->{'mapmoves'}) eq 'HASH') {
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {              %mapmoves = %{$moves->{'mapmoves'}};
         my $errtext='';          }
         my $fatal=0;      }
         my $container='sequence';      foreach my $key (keys(%copies),keys(%docmoves)) {
         if ($env{'form.pagepath'}) {          my @allcopies;
             $container='page';          if (exists($copies{$key})) {
         }              if (ref($copies{$key}) eq 'HASH') {
         ($errtext,$fatal)=                  my %added;
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                  foreach my $innerkey (keys(%{$copies{$key}})) {
         if ($#LONCAPA::map::order<1) {                      if (($innerkey ne '') && (!$added{$innerkey})) {
             $LONCAPA::map::order[0]=1;                          push(@allcopies,$innerkey);
             $LONCAPA::map::resources[1]='';                          $added{$innerkey} = 1;
         }                      }
         if ($fatal) {                  }
             return 'failed';                  undef(%added);
         }              }
         my $destination = 'docs/';          }
         if ($folder =~ /^supplemental/) {          if ($key eq $oldurl) {
             $destination = 'supplemental/';              if ((exists($docmoves{$key}))) {
         }                  unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
         if (($folder eq 'default') || ($folder eq 'supplemental')) {                      push(@allcopies,$oldurl);
             $destination .= 'default/';                  }
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {              }
             $destination .=  $2.'/';          }
         }          if (@allcopies > 0) {
 # this is for a course, not a user, so set coursedoc flag              foreach my $item (@allcopies) {
 # probably the only place in the system where this should be "1"                  my ($relpath,$oldsubdir,$fname) = 
         my $newidx=&LONCAPA::map::getresidx();                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
         $destination .= $newidx;                  if ($fname ne '') {
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,                      my $content = &Apache::lonnet::getfile($item);
  $parseaction,$allfiles,                      unless ($content eq '-1') {
  $codebase);                          my $storefn;
         my $ext='false';                          if (($key eq $oldurl) && (exists($docmoves{$key}))) {
         if ($url=~m{^http://}) { $ext='true'; }                              $storefn = $docmoves{$key};
  $url     = &LONCAPA::map::qtunescape($url);                          } else {
         my $comment=$env{'form.comment'};                              $storefn = $relpath;
  $comment = &LONCAPA::map::qtunescape($comment);                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
         if ($folder=~/^supplemental/) {                              if ($prefixchg && $before{'doc'} && $after{'doc'}) {
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                                  $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
                   $env{'user.domain'}.'___&&&___'.$comment;                              }
         }                              if ($newsubdir{$key}) {
                                   $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
         $LONCAPA::map::resources[$newidx]=                              }
     $comment.':'.$url.':'.$ext.':normal:res';                          }
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                          &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                          my $copyurl = 
     $folder.'.'.$container);                              &Apache::lonclonecourse::writefile($env{'request.course.id'},
         if ($fatal) {                                                                 $storefn.$fname,$content);
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';                          if ($copyurl eq '/adm/notfound.html') {
             return 'failed';                              if (exists($docmoves{$oldurl})) {
         } else {                                  return &mt('Paste failed: an error occurred copying the file.');
             if ($parseaction eq 'parse') {                              } elsif (ref($errors) eq 'HASH') {
                 my $total_embedded = keys(%{$allfiles});                                  $errors->{$item} = 1;
                 if ($total_embedded > 0) {                              }
                     my $num = 0;                          }
     my $state = '                      }
    <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />                  }
    <input type="hidden" name="cmd" value="upload_embedded" />              }
    <input type="hidden" name="newidx" value="'.$newidx.'" />          }
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />      }
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';      foreach my $key (keys(%mapmoves)) {
     $phase_status = 'phasetwo';          my $storefn=$key;
           $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
                     $$upload_output .=          if ($prefixchg && $before{'map'} && $after{'map'}) {
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.              $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
  &Apache::loncommon::ask_for_embedded_content(          }
                             '/adm/coursedocs',$state,$allfiles,$codebase);          if ($newsubdir{$key}) {
                 } else {              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
                     $$upload_output .= 'No embedded items identified<br />';          }
                 }          my $mapcontent = &Apache::lonnet::getfile($key);
             }          if ($mapcontent eq '-1') {
         }              if (ref($errors) eq 'HASH') {
     }                  $errors->{$key} = 1;
     return $phase_status;              }
 }          } else {
               my $newmap =
 sub process_secondary_uploads {                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;                                                     $mapcontent);
     my $folder=$env{'form.folder'};              if ($newmap eq '/adm/notfound.html') {
     my $destination = 'docs/';                  if (ref($errors) eq 'HASH') {
     if ($folder =~ /^supplemental/) {                      $errors->{$key} = 1;
         $destination = 'supplemental/';                  }
     }              }
     if (($folder eq 'default') || ($folder eq 'supplemental')) {          }
         $destination .= 'default/';      }
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      my %updates;
         $destination .=  $2.'/';      if ($is_map) {
     }          if (ref($updated) eq 'HASH') {
     $destination .= $newidx;              foreach my $type (keys(%{$updated})) {
     my ($url,$filename);                  if (ref($updated->{$type}) eq 'HASH') {
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);                      foreach my $key (keys(%{$updated->{$type}})) {
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});                          $updates{$key} = 1;
     return $filename;                      }
 }                  }
               }
 sub is_supplemental_title {          }
     my ($title) = @_;          foreach my $key (keys(%updates)) {
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);              my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
 }              if (ref($rewrites{$key}) eq 'HASH') {
                   %torewrite = %{$rewrites{$key}};
 sub parse_supplemental_title {              }
     my ($title) = @_;              if (ref($retitles{$key}) eq 'HASH') {
                   %toretitle = %{$retitles{$key}};
     my ($foldertitle,$renametitle);              }
     if ($title =~ /&amp;&amp;&amp;/) {              if (ref($removefrommap{$key}) eq 'HASH') {
  $title = &HTML::Entites::decode($title);                  %toremove = %{$removefrommap{$key}};
     }              }
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {              if (ref($removeparam{$key}) eq 'HASH') {
  $renametitle=$4;                  %remparam = %{$removeparam{$key}};
  my ($time,$uname,$udom) = ($1,$2,$3);              }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);              if (ref($zombies{$key}) eq 'HASH') {
  my $name =  &Apache::loncommon::plainname($uname,$udom);                  %zombie = %{$zombies{$key}};
  $name = &HTML::Entities::encode($name,'"<>&\'');              }
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.              if (ref($dbcopies{$key}) eq 'HASH') {
     $name.': <br />'.$foldertitle;                  foreach my $idx (keys(%{$dbcopies{$key}})) {
     }                      if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
     if (wantarray) {                          my ($newurl,$result,$errtext) =
  return ($title,$foldertitle,$renametitle);                              &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
     }                          if ($result eq 'ok') {
     return $title;                              $newdb{$idx} = $newurl;
 }                          } elsif (ref($errors) eq 'HASH') {
                               $errors->{$key} = 1;
 # --------------------------------------------------------------- An entry line                          }
                           push(@msgs,$errtext);
 sub entryline {                      }
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;                  }
               }
     my ($foldertitle,$pagetitle,$renametitle);              if (ref($params{$key}) eq 'HASH') {
     if (&is_supplemental_title($title)) {                  %currparam = %{$params{$key}};
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);              }
  $pagetitle = $foldertitle;              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
     } else {              if ($fatal) {
  $title=&HTML::Entities::encode($title,'"<>&\'');                  return ($errtext);
  $renametitle=$title;              }
  $foldertitle=$title;              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
  $pagetitle=$title;                  if (defined($LONCAPA::map::zombies[$i])) {
     }                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
                       if ($zombie{$i} eq $src) {
     my $orderidx=$LONCAPA::map::order[$index];                          undef($LONCAPA::map::zombies[$i]);
                          }
                   }
     $renametitle=~s/\\/\\\\/g;              }
     $renametitle=~s/\&quot\;/\\\"/g;              for (my $i=0; $i<@LONCAPA::map::order; $i++) {
     $renametitle=~s/ /%20/g;                  my $idx = $LONCAPA::map::order[$i];
     my $line='<tr>';                  if (defined($LONCAPA::map::resources[$idx])) {
     my ($form_start,$form_end);                      my $changed;
 # Edit commands                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
     my ($container, $type, $esc_path, $path, $symb);                      if ((exists($toremove{$idx})) && ($toremove{$idx} eq $src)) {
     if ($env{'form.folderpath'}) {                          splice(@LONCAPA::map::order,$i,1);
  $type = 'folder';                          if (ref($currparam{$idx}) eq 'ARRAY') {
         $container = 'sequence';                              foreach my $name (@{$currparam{$idx}}) {
  $esc_path=&escape($env{'form.folderpath'});                                  &LONCAPA::map::delparameter($idx,'parameter_'.$name);
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                              }
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                          }
     }                          next;
     if ($env{'form.pagepath'}) {                      }
         $type = $container = 'page';                      my $origsrc = $src;
         $esc_path=&escape($path = $env{'form.pagepath'});                      if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');                          if ($title =~ m{^\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
         $symb=&escape($env{'form.pagesymb'});                              $changed = 1;
     }                          }
     my $cpinfo='';                      }
     if ($allowed) {                      if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
  my $incindex=$index+1;                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
  my $selectbox='';                          if ($origsrc =~ m{^/uploaded/}) {
  if (($folder!~/^supplemental/) &&                              if ($prefixchg && $before{'map'} && $after{'map'}) {
     ($#LONCAPA::map::order>0) &&                                  if ($src =~ /\.(page|sequence)$/) {
     ((split(/\:/,                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]                                  } else {
      ne '') &&                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
     ((split(/\:/,                                  }
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]                              }
      ne '')) {                              if ($origsrc =~ /\.(page|sequence)$/) {
     $selectbox=                                  if ($newsubdir{$origsrc}) {
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
  '<select name="newpos" onChange="this.form.submit()">';                                  }
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {                              } elsif ($newsubdir{$key}) {
  if ($i==$incindex) {                                  $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
     $selectbox.='<option value="" selected="1">('.$i.')</option>';                              }
  } else {                          }
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';                          $changed = 1;
  }                      } elsif ($newdb{$idx} ne '') {
     }                          $src = $newdb{$idx};
     $selectbox.='</select>';                          $changed = 1;
  }                      }
  my %lt=&Apache::lonlocal::texthash(                      if ($changed) {
                 'up' => 'Move Up',                          $LONCAPA::map::resources[$idx] = join(':',($title,$src,$ext,$type));
  'dw' => 'Move Down',                      }
  'rm' => 'Remove',                  }
                 'ct' => 'Cut',              }
  'rn' => 'Rename',              foreach my $idx (keys(%remparam)) {
  'cp' => 'Copy');                  if (ref($remparam{$idx}) eq 'ARRAY') {
  my $nocopy=0;                      foreach my $name (@{$remparam{$idx}}) {   
         my $nocut=0;                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
         if ($url=~/\.(page|sequence)$/) {                      }
     if ($url =~ m{/res/}) {                  }
  # no copy for published maps              }
  $nocopy = 1;              if (values(%lockerrors) > 0) {
     } else {                  $lockmsg = join('<br />',values(%lockerrors));
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {              }
     my ($title,$url,$ext,$type)=split(/\:/,$item);              my $storefn;
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {              if ($key eq $oldurl) {
  $nocopy=1;                  $storefn = $url;
  last;                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     }              } else {
  }                  $storefn = $key;
     }                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
  }                  if ($prefixchg && $before{'map'} && $after{'map'}) {
         if ($url=~/^\/res\/lib\/templates\//) {                      $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
            $nocopy=1;                  }
            $nocut=1;                  if ($newsubdir{$key}) {
         }                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
         my $copylink='&nbsp;';                  }
         my $cutlink='&nbsp;';              }
               my $report;
  my $skip_confirm = 0;              if ($folder !~ /^supplemental/) {
  if ( $folder =~ /^supplemental/                  $report = 1;
      || ($url =~ m{( /smppg$              }
     |/syllabus$              (my $outtext,$errtext) =
     |/aboutme$                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
     |/navmaps$              if ($errtext) {
     |/bulletinboard$                  if ($caller eq 'paste') {
     |\.html$                      return (&mt('Paste failed: an error occurred saving the folder or page.'));
     |^/adm/wrapper/ext)}x)) {                  }
     $skip_confirm = 1;              }
  }          }
       }
  if (!$nocopy) {      return ('ok',\@msgs,$lockmsg);
     $copylink=(<<ENDCOPY);  }
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>  
 ENDCOPY  sub copy_dependencies {
         }      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
  if (!$nocut) {      my $content;
     $cutlink=(<<ENDCUT);      if (ref($contentref)) {
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>          $content = $$contentref;
 ENDCUT      } else {
         }          $content = &Apache::lonnet::getfile($item);
  $form_start = (<<END);      }
    <form  action="/adm/coursedocs" method="post">      unless ($content eq '-1') {
    <input type="hidden" name="${type}path" value="$path" />          my $mm = new File::MMagic;
    <input type="hidden" name="${type}symb" value="$symb" />          my $mimetype = $mm->checktype_contents($content);
    <input type="hidden" name="setparms" value="$orderidx" />          if ($mimetype eq 'text/html') {
    <input type="hidden" name="changeparms" value="0" />              my (%allfiles,%codebase,$state);
 END              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
         $form_end = '</form>';              if ($res eq 'ok') {
  $line.=(<<END);                  my ($numexisting,$numpathchanges,$existing);
 <td>                  (undef,$numexisting,$numpathchanges,$existing) =
    <table class="LC_docs_entry_move">                      &Apache::loncommon::ask_for_embedded_content(
       <tr>                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
          <td>                          {'error_on_invalid_names'   => 1,
             <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" /></a>                           'ignore_remote_references' => 1,
          </td>                           'docs_url'                 => $item,
       </tr>                           'context'                  => 'paste'});
       <tr>                  if ($numexisting > 0) {
         <td>                      if (ref($existing) eq 'HASH') {
            <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>                          foreach my $dep (keys(%{$existing})) {
         </td>                              my $depfile = $dep;
       </tr>                              unless ($depfile =~ m{^\Q$relpath\E}) {
     </table>                                  $depfile = $relpath.$dep;
 </td>                              }
 <td>                              my $depcontent = &Apache::lonnet::getfile($depfile);
    $form_start                              unless ($depcontent eq '-1') {
    $selectbox                                  my $storedep = $dep;
    $form_end                                  $storedep =~ s{^\Q$relpath\E}{};
 </td>                                  my $dep_url =
 <td class="LC_docs_entry_commands">                                      &Apache::lonclonecourse::writefile(
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>                                          $env{'request.course.id'},
 $cutlink                                          $storefn.$storedep,$depcontent);
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>                                  if ($dep_url eq '/adm/notfound.html') {
 $copylink                                      if (ref($errors) eq 'HASH') {
 </td>                                          $errors->{$depfile} = 1;
 END                                      }
                                   } else {
     }                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
 # Figure out what kind of a resource this is                                  }
     my ($extension)=($url=~/\.(\w+)$/);                              }
     my $uploaded=($url=~/^\/*uploaded\//);                          }
     my $icon=&Apache::loncommon::icon($url);                      }
     my $isfolder=0;                  }
     my $ispage=0;              }
     my $folderarg;          }
     my $pagearg;      }
     my $pagefile;      return;
     if ($uploaded) {  }
  if ($extension eq 'sequence') {  
     $icon=$iconpath.'/folder_closed.gif';  my %parameter_type = ( 'randompick'     => 'int_pos',
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;         'hiddenresource' => 'string_yesno',
     $url='/adm/coursedocs?';         'encrypturl'     => 'string_yesno',
     $folderarg=$1;         'randomorder'    => 'string_yesno',);
     $isfolder=1;  my $valid_parameters_re = join('|',keys(%parameter_type));
         } elsif ($extension eq 'page') {  # set parameters
             $icon=$iconpath.'/page.gif';  sub update_parameter {
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;      if ($env{'form.changeparms'} eq 'all') {
             $pagearg=$1;          my (@allidx,@allmapidx,%allchecked,%currchecked);
             $url='/adm/coursedocs?';          %allchecked = (
             $ispage=1;                           'hiddenresource' => {},
  } else {                           'encrypturl'     => {},
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);                           'randompick'     => {},
  }                           'randomorder'    => {},
     }                        );
              foreach my $which (keys(%allchecked)) {
     my $orig_url = $url;              $env{'form.all'.$which} =~ s/,$//;   
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});              if ($which eq 'randompick') {
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {                  foreach my $item (split(/,/,$env{'form.all'.$which})) {
  my $symb=&Apache::lonnet::symbclean(                      my ($res,$value) = split(/:/,$item);
           &Apache::lonnet::declutter('uploaded/'.                      if ($value =~ /^\d+$/) {
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.                          $allchecked{$which}{$res} = $value;
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                      }
            '.sequence').                  }
            '___'.$residx.'___'.              } else {
    &Apache::lonnet::declutter($url));                  map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);              }
  $url=&Apache::lonnet::clutter($url);          }
  if ($url=~/^\/*uploaded\//) {          my $haschanges = 0;
     $url=~/\.(\w+)$/;          foreach my $res (@LONCAPA::map::order) {
     my $embstyle=&Apache::loncommon::fileembstyle($1);              my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {              $name=&LONCAPA::map::qtescape($name);
  $url='/adm/wrapper'.$url;              $url=&LONCAPA::map::qtescape($url);
     } elsif ($embstyle eq 'ssi') {              next unless ($name && $url);
  #do nothing with these              my $is_map;
     } elsif ($url!~/\.(sequence|page)$/) {              if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
  $url='/adm/coursedocs/showdoc'.$url;                  $is_map = 1;
     }              }
  } elsif ($url=~m|^/ext/|) {              foreach my $which (keys(%allchecked)) {
     $url='/adm/wrapper'.$url;                  if (($which eq 'randompick' || $which eq 'randomorder')) {
     $external = 1;                      next if (!$is_map);
  }                  } 
         if (&Apache::lonnet::symbverify($symb,$url)) {                  my $oldvalue = 0;
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                  my $newvalue = 0;
         } else {                  if ($allchecked{$which}{$res}) {
             $url='';                      $newvalue = $allchecked{$which}{$res};
         }                  }
  if ($container eq 'page') {                  my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
     my $symb=$env{'form.pagesymb'};                  if ($which eq 'randompick') {
                               if ($current =~ /^(\d+)$/) {
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);                          $oldvalue = $1;
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                      }
  }                  } else {
     }                      if ($current =~ /^yes$/i) {
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');                          $oldvalue = 1;
     if ($isfolder || $extension eq 'sequence') {                      }
  my $foldername=&escape($foldertitle);                  }
  my $folderpath=$env{'form.folderpath'};                  if ($oldvalue ne $newvalue) {
  if ($folderpath) { $folderpath.='&' };                      $haschanges = 1;
 # Append randompick number, hidden, and encrypted with ":" to foldername,                      if ($newvalue) {
 # so it gets transferred between levels                          my $storeval = 'yes';
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,                          if ($which eq 'randompick') {
                                               'parameter_randompick'))[0]                              $storeval = $newvalue;
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                          }
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)                          &LONCAPA::map::storeparameter($res,'parameter_'.$which,
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                                                        $storeval,
                                               'parameter_encrypturl'))[0]=~/^yes$/i)                                                        $parameter_type{$which});
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                          &remember_parms($res,$which,'set',$storeval);
                                               'parameter_randomorder'))[0]=~/^yes$/i);                      } elsif ($oldvalue) {
  $url.='folderpath='.&escape($folderpath).$cpinfo;                          &LONCAPA::map::delparameter($res,'parameter_'.$which);
  $parameterset='<label>'.&mt('Randomly Pick: ').                          &remember_parms($res,$which,'del');
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.                      }
     (&LONCAPA::map::getparameter($orderidx,                  }
                                               'parameter_randompick'))[0].              }
                                               '" />'.          }
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';          return $haschanges;
     my $ro_set=      } else {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');          return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
  $rand_order_text ='  
 <span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" onClick="this.form.changeparms.value=\'randomorder\';this.form.submit()" '.$ro_set.' /> '.&mt('Random Order').' </label></span>';            my $which = $env{'form.changeparms'};
     }          my $idx = $env{'form.setparms'};
     if ($ispage) {          if ($env{'form.'.$which.'_'.$idx}) {
         my $pagename=&escape($pagetitle);      my $value = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
         my $pagepath;                                           : 'yes';
         my $folderpath=$env{'form.folderpath'};      &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
         if ($folderpath) { $pagepath = $folderpath.'&' };            $parameter_type{$which});
         $pagepath.=$pagearg.'&'.$pagename;      &remember_parms($idx,$which,'set',$value);
  my $symb=$env{'form.pagesymb'};          } else {
  if (!$symb) {      &LONCAPA::map::delparameter($idx,'parameter_'.$which);
     my $path='uploaded/'.  
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.      &remember_parms($idx,$which,'del');
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';          }
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',          return 1;
        $residx,      }
        $path.$pagearg.'.page');  }
  }  
  $url.='pagepath='.&escape($pagepath).  
     '&amp;pagesymb='.&escape($symb).$cpinfo;  sub handle_edit_cmd {
     }      my ($coursenum,$coursedom) =@_;
     if ($external) {      my ($cmd,$idx)=split('_',$env{'form.cmd'});
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';  
  $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     } else {      my ($title, $url, @rrest) = split(':', $ratstr);
  undef($external);  
     }      if ($cmd eq 'del') {
     $line.='   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
   <td class="LC_docs_entry_icon">      ($url!~/$LONCAPA::assess_page_seq_re/)) {
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'      &Apache::lonnet::removeuploadedurl($url);
   </td>   } else {
   <td class="LC_docs_entry_title">      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."   }
   </td>";   splice(@LONCAPA::map::order, $idx, 1);
     if (($allowed) && ($folder!~/^supplemental/)) {  
   my %lt=&Apache::lonlocal::texthash(      } elsif ($cmd eq 'cut') {
        'hd' => 'Hidden',   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
        'ec' => 'URL hidden');   splice(@LONCAPA::map::order, $idx, 1);
  my $enctext=  
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');      } elsif ($cmd eq 'up'
  my $hidtext=       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
  $line.=(<<ENDPARMS);  
   <td class="LC_docs_entry_parameter">      } elsif ($cmd eq 'down'
     $form_start       && defined($LONCAPA::map::order[$idx+1])) {
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
     $form_end  
   </td>      } elsif ($cmd eq 'rename') {
   <td class="LC_docs_entry_parameter">  
     $form_start   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>   if ($comment=~/\S/) {
     $form_end      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
   </td>   $comment.':'.join(':', $url, @rrest);
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>   }
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>  # Devalidate title cache
 ENDPARMS   my $renamed_url=&LONCAPA::map::qtescape($url);
     }   &Apache::lonnet::devalidate_title_cache($renamed_url);
     $line.="</tr>";      } else {
     return $line;   return 0;
 }      }
       return 1;
 =pod  }
   
 =item tiehash()  sub editor {
       my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
 tie the hash          $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
       my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
 =cut      if ($allowed) {
           (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
 sub tiehash {           $is_random_order,$container) =
     my ($mode)=@_;              &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
     $hashtied=0;          $r->print($breadcrumbtrail);
     if ($env{'request.course.fn'}) {      } elsif ($env{'form.folderpath'} =~ /\:1$/) {
  if ($mode eq 'write') {          $container = 'page'; 
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      } else {
     &GDBM_WRCREAT(),0640)) {          $container = 'sequence';
                 $hashtied=2;      }
     }  
  } else {      my $jumpto;
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",  
     &GDBM_READER(),0640)) {      unless ($supplementalflag) {
                 $hashtied=1;          $jumpto = "'uploaded/$coursedom/$coursenum/$folder.$container'";
     }      }
  }  
     }          unless ($allowed) {
 }          $randompick = -1;
       }
 sub untiehash {  
     if ($hashtied) { untie %hash; }      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     $hashtied=0;      $folder.'.'.$container);
     return OK;      return $errtext if ($fatal);
 }  
       if ($#LONCAPA::map::order<1) {
    my $idx=&LONCAPA::map::getresidx();
    if ($idx<=0) { $idx=1; }
           $LONCAPA::map::order[0]=$idx;
 sub checkonthis {          $LONCAPA::map::resources[$idx]='';
     my ($r,$url,$level,$title)=@_;      }
     $url=&unescape($url);  
     $alreadyseen{$url}=1;  # ------------------------------------------------------------ Process commands
     $r->rflush();  
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {  # ---------------- if they are for this folder and user allowed to make changes
        $r->print("\n<br />");      if (($allowed) && ($env{'form.folder'} eq $folder)) {
        if ($level==0) {  # set parameters and change order
            $r->print("<br />");   &snapshotbefore();
        }  
        for (my $i=0;$i<=$level*5;$i++) {   if (&update_parameter()) {
            $r->print('&nbsp;');      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
        }      return $errtext if ($fatal);
        $r->print('<a href="'.$url.'" target="cat">'.   }
  ($title?$title:$url).'</a> ');  
        if ($url=~/^\/res\//) {   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
   my $result=&Apache::lonnet::repcopy(  # change order
                               &Apache::lonnet::filelocation('',$url));      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
           if ($result eq 'ok') {      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');  
              $r->rflush();      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
              &Apache::lonnet::countacc($url);      return $errtext if ($fatal);
              $url=~/\.(\w+)$/;   }
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {  
  $r->print('<br />');   if ($env{'form.pastemarked'}) {
                  $r->rflush();              my %paste_errors;
                  for (my $i=0;$i<=$level*5;$i++) {              my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
                      $r->print('&nbsp;');                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
                  }                                        \%paste_errors);
                  $r->print('- '.&mt('Rendering:').' ');                  if (ref($pastemsgarray) eq 'ARRAY') {
  my ($errorcount,$warningcount)=split(/:/,                      if (@{$pastemsgarray} > 0) {
        &Apache::lonnet::ssi_body($url,                            
        ('grade_target'=>'web',                          $r->print('<p class="LC_info">'.
  'return_only_error_and_warning_counts' => 1)));                                    join('<br />',@{$pastemsgarray}).
                  if (($errorcount) ||                                    '</p>');
                      ($warningcount)) {                      }
      if ($errorcount) {                  }
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.                  if ($lockerror) {
                           &mt('[quant,_1,error]',$errorcount).'</span>');                      $r->print('<p class="LC_error">'.
                      }                                $lockerror.
      if ($warningcount) {                                '</p>');
                         $r->print('<span class="LC_warning">'.                  }
                           &mt('[quant,_1,warning]',$warningcount).'</span>');                  if ($save_error ne '') {
                      }                      return $save_error; 
                  } else {                  }
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');              if ($paste_res ne 'ok') {
                  }                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
                  $r->rflush();              }
              }              if (keys(%paste_errors) > 0) {
      my $dependencies=                  $r->print('<p span class="LC_warning">'."\n".
                 &Apache::lonnet::metadata($url,'dependencies');                            &mt('The following files are either dependencies of a web page or references within a folder and/or composite page which could not be copied during the paste operation:')."\n".
              foreach my $dep (split(/\,/,$dependencies)) {                            '<ul>'."\n");
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {                  foreach my $key (sort(keys(%paste_errors))) {
                     &checkonthis($r,$dep,$level+1);                      $r->print('<li>'.$key.'</li>'."\n");
                  }                  }
              }                  $r->print('</ul></p>'."\n");
           } elsif ($result eq 'unavailable') {              }
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');   }
           } elsif ($result eq 'not_found') {  
       unless ($url=~/\$/) {   $r->print($upload_output);
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');  
       } else {   if (&handle_edit_cmd()) {
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');              my $contentchg;
       }              if ($env{'form.cmd'} =~ /^(del|cut)_/) {
           } else {                  $contentchg = 1;
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');              }
           }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
        }      return $errtext if ($fatal);
     }   }
 }  # Group import/search
    if ($env{'form.importdetail'}) {
       my @imports;
       foreach my $item (split(/\&/,$env{'form.importdetail'})) {
 =pod   if (defined($item)) {
       my ($name,$url,$residx)=
 =item list_symbs()   map { &unescape($_); } split(/\=/,$item);
                       if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
 List Symbs                          my ($suffix,$errortxt,$locknotfreed) =
                               &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
 =cut                          if ($locknotfreed) {
                               $r->print($locknotfreed);
 sub list_symbs {                          }
     my ($r) = @_;                          if ($suffix) {
                               $url =~ s/_new\./_$suffix./; 
     my $type = &Apache::loncommon::course_type();                          } else {
     $r->print(&Apache::loncommon::start_page('Symb List'));                              return $errortxt;
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));                          }
     my $navmap = Apache::lonnavmaps::navmap->new();                      } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
     if (!defined($navmap)) {                          my $type = $1;
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.                          my ($suffix,$errortxt,$locknotfreed) =
                   '<div class="LC_error">'.                              &new_timebased_suffix($coursedom,$coursenum,$type);
                   &mt('Unable to retrieve information about course contents').                          if ($locknotfreed) {
                   '</div>');                              $r->print($locknotfreed);
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                          }
     } else {                          if ($suffix) {
         $r->print("<pre>\n");                              $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
         foreach my $res ($navmap->retrieveResources()) {                          } else {
     $r->print($res->compTitle()."\t".$res->symb()."\n");                              return $errortxt;
         }                          }
         $r->print("\n</pre>\n");                      } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
     }                          if ($supplementalflag) {
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');                              next unless ($1 eq 'supplemental');
 }                              if ($folder eq 'supplemental') {
                                   next unless ($2 eq 'default');
                               } else {
 sub verifycontent {                                  next unless ($folder eq 'supplemental_'.$2);
     my ($r) = @_;                              }
     my $type = &Apache::loncommon::course_type();                          } else {
    my $loaderror=&Apache::lonnet::overloaderror($r);                              next unless ($1 eq 'docs');
    if ($loaderror) { return $loaderror; }                              if ($folder eq 'default') {
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));                                  next unless ($2 eq 'default');
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));                              } else {
    $hashtied=0;                                  next unless ($folder eq 'default_'.$2);
    undef %alreadyseen;                              }
    %alreadyseen=();                          }
    &tiehash();                      }
    foreach my $key (keys(%hash)) {      push(@imports, [$name, $url, $residx]);
        if ($hash{$key}=~/\.(page|sequence)$/) {   }
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {      }
        $r->print('<hr /><span class="LC_error">'.              ($errtext,$fatal,my $fixuperrors) =
  &mt('The following sequence or page is included more than once in your '.$type.': ').                  &group_import($coursenum, $coursedom, $folder,$container,
  &unescape($hash{$key}).'</span><br />'.                                'londocs',@imports);
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      return $errtext if ($fatal);
    }              if ($fixuperrors) {
        }                  $r->print($fixuperrors);
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {              }
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});   }
        }  # Loading a complete map
    }   if ($env{'form.loadmap'}) {
    &untiehash();      if ($env{'form.importmap'}=~/\w/) {
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
      &mt('Return to DOCS').'</a>');      my ($title,$url,$ext,$type)=split(/\:/,$res);
 }      my $idx=&LONCAPA::map::getresidx($url);
       $LONCAPA::map::resources[$idx]=$res;
       $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 sub devalidateversioncache {   }
     my $src=shift;   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.      $folder.'.'.$container,1);
   &Apache::lonnet::clutter($src));   return $errtext if ($fatal);
 }      } else {
    $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
 sub checkversions {  
     my ($r) = @_;      }
     my $type = &Apache::loncommon::course_type();   }
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));   &log_differences($plain);
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));      }
     my $header='';  # ---------------------------------------------------------------- End commands
     my $startsel='';  # ---------------------------------------------------------------- Print screen
     my $monthsel='';      my $idx=0;
     my $weeksel='';      my $shown=0;
     my $daysel='';      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
     my $allsel='';   $r->print('<div class="LC_Box">'.
     my %changes=();            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
     my $starttime=0;    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
     my $haschanged=0;    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     my %setversions=&Apache::lonnet::dump('resourceversions',    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
   $env{'course.'.$env{'request.course.id'}.'.domain'},    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
   $env{'course.'.$env{'request.course.id'}.'.num'});    '</ol>');
           if ($randompick>=0) {
     $hashtied=0;              $r->print('<p class="LC_warning">'
     &tiehash();                   .&mt('Caution: this folder is set to randomly pick a subset'
     my %newsetversions=();                       .' of resources. Adding or removing resources from this'
     if ($env{'form.setmostrecent'}) {                       .' folder will change the set of resources that the'
  $haschanged=1;                       .' students see, resulting in spurious or missing credit'
  foreach my $key (keys(%hash)) {                       .' for completed problems, not limited to ones you'
     if ($key=~/^ids\_(\/res\/.+)$/) {                       .' modify. Do not modify the contents of this folder if'
  $newsetversions{$1}='mostrecent';                       .' it is in active student use.')
                 &devalidateversioncache($1);                   .'</p>'
     }              );
  }          }
     } elsif ($env{'form.setcurrent'}) {          if ($is_random_order) {
  $haschanged=1;              $r->print('<p class="LC_warning">'
  foreach my $key (keys(%hash)) {                   .&mt('Caution: this folder is set to randomly order its'
     if ($key=~/^ids\_(\/res\/.+)$/) {                       .' contents. Adding or removing resources from this folder'
  my $getvers=&Apache::lonnet::getversion($1);                       .' will change the order of resources shown.')
  if ($getvers>0) {                   .'</p>'
     $newsetversions{$1}=$getvers;              );
     &devalidateversioncache($1);          }
  }          $r->print('</div>');
     }      }
  }  
     } elsif ($env{'form.setversions'}) {      my ($to_show,$output,@allidx,@allmapidx);
  $haschanged=1;  
  foreach my $key (keys(%env)) {      &Apache::loncommon::start_data_table_count(); #setup a row counter 
     if ($key=~/^form\.set_version_(.+)$/) {      foreach my $res (@LONCAPA::map::order) {
  my $src=$1;          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {          $name=&LONCAPA::map::qtescape($name);
     $newsetversions{$src}=$env{$key};          $url=&LONCAPA::map::qtescape($url);
     &devalidateversioncache($src);          unless ($name) {  $name=(split(/\//,$url))[-1]; }
  }          unless ($name) { $idx++; next; }
     }          push(@allidx,$res);
  }          if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
     }              push(@allmapidx,$res);
     if ($haschanged) {          }
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
   $env{'course.'.$env{'request.course.id'}.'.domain'},                                $coursenum,$coursedom,$crstype,
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {                                $pathitem,$supplementalflag,$container);
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');          $idx++;
  } else {          $shown++;
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');      }
  }      &Apache::loncommon::end_data_table_count();
  &mark_hash_old();  
     }      if (($allowed) || ($supplementalflag && $folder eq 'supplemental')) {
     &changewarning($r,'');          my $toolslink = '<table><tr><td>'
     if ($env{'form.timerange'} eq 'all') {                         .&Apache::loncommon::help_open_menu('Navigation Screen',
 # show all documents                                                             'Navigation_Screen',undef,'RAT')
  $header=&mt('All Documents in '.$type);                         .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
  $allsel=1;                         .'<td align="left"><ul id="LC_toolbar">'
  foreach my $key (keys(%hash)) {                         .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
     if ($key=~/^ids\_(\/res\/.+)$/) {                         .'id="LC_content_toolbar_edittoplevel" '
  my $src=$1;                         .'class="LC_toolbarItem" '
  $changes{$src}=1;                         .'title="'.&mt('Supplemental Content Editor').'">'
     }                         .'</a></li></ul></td></tr></table><br />';
  }          if ($shown) {
     } else {              if ($allowed) {
 # show documents which changed                  $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
  %changes=&Apache::lonnet::dump                            .&Apache::loncommon::start_data_table(undef,'contentlist')
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},                            .&Apache::loncommon::start_data_table_header_row()
                      $env{'course.'.$env{'request.course.id'}.'.num'});                            .'<th colspan="2">'.&mt('Move').'</th>'
  my $firstkey=(keys(%changes))[0];                            .'<th>'.&mt('Actions').'</th>'
  unless ($firstkey=~/^error\:/) {                            .'<th colspan="2">'.&mt('Document').'</th>';
     unless ($env{'form.timerange'}) {                  if ($folder !~ /^supplemental/) {
  $env{'form.timerange'}=604800;                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
     }                  }
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '                  $to_show .= &Apache::loncommon::end_data_table_header_row();
  .&mt('seconds');                  if ($folder !~ /^supplemental/) {
     if ($env{'form.timerange'}==-1) {                      my $idxlist = join(',',@allidx);
  $seltext='since start of course';                      my $mapidxlist = join(',',@allmapidx);
  $startsel='selected';                      if (@allidx > 0) {
  $env{'form.timerange'}=time;                          my $path;
     }                          if ($env{'form.folderpath'}) {
     $starttime=time-$env{'form.timerange'};                              $path = 
     if ($env{'form.timerange'}==2592000) {                                  &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                          }
  $monthsel='selected';                          $to_show .= 
     } elsif ($env{'form.timerange'}==604800) {                              &Apache::loncommon::continue_data_table_row().
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                              '<td colspan="5">&nbsp;</td>'.
  $weeksel='selected';                              '<td colspan="4">'.
     } elsif ($env{'form.timerange'}==86400) {                              '<form action="/adm/coursedocs" method="post" name="togglemultchecks">'.
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                              '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.&mt('Select:').'&nbsp;'.
  $daysel='selected';                              '<label><input type="radio" name="showmultpick" value="0" onclick="javascript:togglePick();" checked="checked" />'.&mt('single').'</label>'.('&nbsp;'x2).'<label><input type="radio" name="showmultpick" value="1" onclick="javascript:togglePick();" />'.&mt('multiple').'</label></span></form>'.
     }                              '<div id="multiclick" style="display: none">'.
     $header=&mt('Content changed').' '.$seltext;                              '<form action="/adm/coursedocs" method="post" name="cumulativechecks" onsubmit="return submitSettings(this);">'."\n".
  } else {                              '<fieldset><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n".
     $header=&mt('No content modifications yet.');                              '<table><tr><td class="LC_docs_entry_parameter"><span class="LC_nobreak"><input type="checkbox" name="hiddenresourceall" id="hiddenresourceall" onclick="propagateState(this.form,'."'hiddenresource'".')" />'.&mt('Hidden').'</span></td><td class="LC_docs_entry_parameter"><span class="LC_nobreak"><input type="checkbox" name="randompickall" id="randompickall" onclick="updatePick(this.form,'."'all','check'".');propagateState(this.form,'."'randompick'".');propagateState(this.form,'."'rpicknum'".');" />'.&mt('Randomly Pick').'<span id="rpicktextall"></span><input type="hidden" name="rpicknumall" id="rpicknumall" value="" /></span></td>'.
  }                              '</tr>'."\n".
     }                              '<tr><td class="LC_docs_entry_parameter"><span class="LC_nobreak"><input type="checkbox" name="encrypturlall" id="encrypturlall" onclick="propagateState(this.form,'."'encrypturl'".')" />'.&mt('URL hidden').'</span></td><td class="LC_docs_entry_parameter"><span class="LC_nobreak"><input type="checkbox" name="randomorderall" id="randomorderall" onclick="propagateState(this.form,'."'randomorder'".')" />'.&mt('Random Order').'</span></td></tr></table>'."\n".
     %setversions=&Apache::lonnet::dump('resourceversions',                              '</fieldset>'.
   $env{'course.'.$env{'request.course.id'}.'.domain'},                              '<input type="hidden" name="folderpath" value="'.$path.'" />'.
   $env{'course.'.$env{'request.course.id'}.'.num'});                              '<input type="hidden" name="symb" value="'.$env{'form.symb'}.'" />'.
     my %lt=&Apache::lonlocal::texthash                              '<input type="hidden" name="allhiddenresource" value="" />'.
       ('st' => 'Version changes since start of '.$type,                              '<input type="hidden" name="allencrypturl" value="" />'.
        'lm' => 'Version changes since last Month',                              '<input type="hidden" name="allrandompick" value="" />'.
        'lw' => 'Version changes since last Week',                              '<input type="hidden" name="allrandomorder" value="" />'.
        'sy' => 'Version changes since Yesterday',                              '<input type="hidden" name="allidx" value="'.$idxlist.'" />'.
                'al' => 'All Resources (possibly large output)',                              '<input type="hidden" name="allmapidx" value="'.$mapidxlist.'" />'.
        'sd' => 'Display',                              '<input type="hidden" name="changeparms" value="all" />'.
        'fi' => 'File',                              '<input type="submit" name="multiplesettings" value="'.&mt('Save settings below').'" />'.
        'md' => 'Modification Date',                              '</form>'.
                'mr' => 'Most recently published Version',                              '</div>'.
        've' => 'Version used in '.$type,  
                'vu' => 'Set Version to be used in '.$type,                              '</td>'.
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',                              &Apache::loncommon::end_data_table_row();
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',                      }
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',                  }
        'di' => 'Differences');                  $to_show .= $output.' '
     $r->print(<<ENDHEADERS);                             .&Apache::loncommon::end_data_table()
 <form action="/adm/coursedocs" method="post">                             .'<br style="line-height:2px;" />'
 <input type="hidden" name="versions" value="1" />                             .&Apache::loncommon::end_scrollbox();
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />              } else {
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />                  $to_show .= $toolslink
 <select name="timerange">                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
 <option value='all' $allsel>$lt{'al'}</option>                             .$output.' '
 <option value="-1" $startsel>$lt{'st'}</option>                             .&Apache::loncommon::end_data_table();
 <option value="2592000" $monthsel>$lt{'lm'}</option>              }
 <option value="604800" $weeksel>$lt{'lw'}</option>          } else {
 <option value="86400" $daysel>$lt{'sy'}</option>              if (!$allowed) {
 </select>                  $to_show .= $toolslink;
 <input type="submit" name="display" value="$lt{'sd'}" />              }
 <h3>$header</h3>              $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
 <input type="submit" name="setversions" value="$lt{'sv'}" />                         .'<div class="LC_info" id="contentlist">'
 <table border="0">                         .&mt('Currently no documents.')
 ENDHEADERS                         .'</div>'
     foreach my $key (sort(keys(%changes))) {                         .&Apache::loncommon::end_scrollbox();
  if ($changes{$key}>$starttime) {          }
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      } else {
     my $currentversion=&Apache::lonnet::getversion($key);          if ($shown) {
     if ($currentversion<0) {              $to_show = '<div>'
  $currentversion=&mt('Could not be determined.');                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
     }                        .$output
     my $linkurl=&Apache::lonnet::clutter($key);                        .&Apache::loncommon::end_data_table()
     $r->print(                        .'</div>';
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.          } else {
       &Apache::lonnet::gettitle($linkurl).              $to_show = '<div class="LC_info" id="contentlist">'
                       '</b></font></td></tr>'.                        .&mt('Currently no documents.')
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.                        .'</div>'
                       '<td colspan="4">'.          }
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.      }
       '</a></td></tr>'.      my $tid = 1;
                       '<tr><td></td>'.      if ($supplementalflag) {
                       '<td title="'.$lt{'md'}.'">'.          $tid = 2;
       &Apache::lonlocal::locallocaltime(      }
                            &Apache::lonnet::metadata($root.'.'.$extension,      if ($allowed) {
                                                      'lastrevisiondate')          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
                                                         ).          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
                       '</td>'.                                         $readfile));
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
                       '<font size="+1">'.$currentversion.'</font>'.      } else {
                       '</span></td>'.          $r->print($to_show);
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.      }
                       '<font size="+1">');      return;
 # Used in course  }
     my $usedversion=$hash{'version_'.$linkurl};  
     if (($usedversion) && ($usedversion ne 'mostrecent')) {  sub process_file_upload {
  $r->print($usedversion);      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     } else {  # upload a file, if present
  $r->print($currentversion);      my ($parseaction,$showupload,$nextphase,$mimetype);
     }      if ($env{'form.parserflag'}) {
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.          $parseaction = 'parse';
                       '<span class="LC_nobreak">Use: ');      }
 # Set version      my $folder=$env{'form.folder'};
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      if ($folder eq '') {
       'set_version_'.$linkurl,          $folder='default';
       ('select_form_order' =>      }
        ['',1..$currentversion,'mostrecent'],      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
        '' => '',          my $errtext='';
        'mostrecent' => 'most recent',          my $fatal=0;
        map {$_,$_} (1..$currentversion))));          my $container='sequence';
     $r->print('</span></td></tr><tr><td></td>');          if ($env{'form.folderpath'} =~ /:1$/) {
     my $lastold=1;              $container='page';
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {          }
  my $url=$root.'.'.$prevvers.'.'.$extension;          ($errtext,$fatal)=
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<              &mapread($coursenum,$coursedom,$folder.'.'.$container);
     $starttime) {          if ($#LONCAPA::map::order<1) {
     $lastold=$prevvers;              $LONCAPA::map::order[0]=1;
  }              $LONCAPA::map::resources[1]='';
     }          }
             #          my $destination = 'docs/';
             # Code to figure out how many version entries should go in          if ($folder =~ /^supplemental/) {
             # each of the four columns              $destination = 'supplemental/';
             my $entries_per_col = 0;          }
             my $num_entries = ($currentversion-$lastold);          if (($folder eq 'default') || ($folder eq 'supplemental')) {
             if ($num_entries % 4 == 0) {              $destination .= 'default/';
                 $entries_per_col = $num_entries/4;          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
             } else {              $destination .=  $2.'/';
                 $entries_per_col = $num_entries/4 + 1;          }
             }          if ($fatal) {
             my $entries_count = 0;              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('The uploaded file has not been stored as an error occurred reading the contents of the current folder.').'</div>';
             $r->print('<td valign="top"><font size="-2">');              return;
             my $cols_output = 1;          }
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {  # this is for a course, not a user, so set context to coursedoc.
  my $url=$root.'.'.$prevvers.'.'.$extension;          my $newidx=&LONCAPA::map::getresidx();
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).          $destination .= $newidx;
   '">'.&mt('Version').' '.$prevvers.'</a> ('.          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
   &Apache::lonlocal::locallocaltime(   $parseaction,$allfiles,
                                 &Apache::lonnet::metadata($url,   $codebase,undef,undef,undef,undef,
                                                           'lastrevisiondate')                                                  undef,undef,\$mimetype);
                                                             ).          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
   ')');              my $stored = $1;
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
                     $r->print(' <a href="/adm/diff?filename='.                            $stored.'</span>').'</p>';
       &Apache::lonnet::clutter($root.'.'.$extension).          } else {
       '&versionone='.$prevvers.              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
       '">'.&mt('Diffs').'</a>');              
  }              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
  $r->print('</span><br />');              return;
                 if (++$entries_count % $entries_per_col == 0) {          }
                     $r->print('</font></td>');          my $ext='false';
                     if ($cols_output != 4) {          if ($url=~m{^http://}) { $ext='true'; }
                         $r->print('<td valign="top"><font size="-2">');   $url     = &LONCAPA::map::qtunescape($url);
                         $cols_output++;          my $comment=$env{'form.comment'};
                     }   $comment = &LONCAPA::map::qtunescape($comment);
                 }          if ($folder=~/^supplemental/) {
     }                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
             while($cols_output++ < 4) {                    $env{'user.domain'}.'___&&&___'.$comment;
                 $r->print('</font></td><td><font>')          }
             }  
     $r->print('</font></td></tr>'."\n");          $LONCAPA::map::resources[$newidx]=
  }      $comment.':'.$url.':'.$ext.':normal:res';
     }          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     $r->print('</table></form>');          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     $r->print('<h1>'.&mt('Done').'.</h1>');      $folder.'.'.$container,1);
           if ($fatal) {
     &untiehash();              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
 }              return;
           } else {
 sub mark_hash_old {              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
     my $retie_hash=0;                  $$upload_output = $showupload;
     if ($hashtied) {                  my $total_embedded = scalar(keys(%{$allfiles}));
  $retie_hash=1;                  if ($total_embedded > 0) {
  &untiehash();                      my $uploadphase = 'upload_embedded';
     }                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
     &tiehash('write');      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
     $hash{'old'}=1;                      my ($embedded,$num) = 
     &untiehash();                          &Apache::loncommon::ask_for_embedded_content(
     if ($retie_hash) { &tiehash(); }                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
 }                      if ($embedded) {
                           if ($num) {
 sub is_hash_old {                              $$upload_output .=
     my $untie_hash=0;           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
     if (!$hashtied) {                              $nextphase = $uploadphase;
  $untie_hash=1;                          } else {
  &tiehash();                              $$upload_output .= $embedded;
     }                          }
     my $return=$hash{'old'};                      } else {
     if ($untie_hash) { &untiehash(); }                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
     return $return;                      }
 }                  } else {
                       $$upload_output .= &mt('No embedded items identified').'<br />';
 sub changewarning {                  }
     my ($r,$postexec,$message,$url)=@_;                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
     if (!&is_hash_old()) { return; }              } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
     my $pathvar='folderpath';                  $nextphase = 'decompress_uploaded';
     my $path=&escape($env{'form.folderpath'});                  my $position = scalar(@LONCAPA::map::order)-1;
     if (!defined($url)) {                  my $noextract = &return_to_editor();
  if (defined($env{'form.pagepath'})) {                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
     $pathvar='pagepath';                  my %archiveitems = (
     $path=&escape($env{'form.pagepath'});                      folderpath => $env{'form.folderpath'},
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                      cmd        => $nextphase,
  }                      newidx     => $newidx,
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                      position   => $position,
     }                      phase      => $nextphase,
     my $course_type = &Apache::loncommon::course_type();                      comment    => $comment,
     if (!defined($message)) {                  );
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
     }                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
     $r->print("\n\n".                  $$upload_output = $showupload.
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".                                    &Apache::loncommon::decompress_form($mimetype,
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.                                        $archiveurl,'/adm/coursedocs',$noextract,
 '<input type="hidden" name="orgurl" value="'.$url.                                        \%archiveitems,\@current);
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.              }
 &mt($message,' <input type="hidden" name="'.          }
     $env{'request.role'}.'" value="1" /><input type="button" value="'.      }
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').      return $nextphase;
 $help{'Caching'}.'</span></h3></form>'."\n\n");  }
 }  
   sub get_dir_list {
       my ($url,$coursenum,$coursedom,$newidx) = @_;
 sub init_breadcrumbs {      my ($destination,$dir_root) = &embedded_destination();
     my ($form,$text)=@_;      my ($dirlistref,$listerror) =  
     &Apache::lonhtmlcommon::clear_breadcrumbs();          &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",      my @dir_lines;
     text=>"Edit ".&Apache::loncommon::course_type(),      my $dirptr=16384;
     faq=>273,      if (ref($dirlistref) eq 'ARRAY') {
     bug=>'Instructor Interface',          foreach my $dir_line (sort
                                             help => 'Docs_Adding_Course_Doc'});                            {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',                                my ($afile)=split('&',$a,2);
     text=>$text,                                my ($bfile)=split('&',$b,2);
     faq=>273,                                return (lc($afile) cmp lc($bfile));
     bug=>'Instructor Interface'});                            } (@{$dirlistref})) {
 }              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
               $filename =~ s/\s+$//;
               next if ($filename =~ /^\.\.?$/); 
               my $isdir = 0;
               if ($dirptr&$testdir) {
 sub handler {                  $isdir = 1;
     my $r = shift;              }
     &Apache::loncommon::content_type($r,'text/html');              push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
     $r->send_http_header;          }
     return OK if $r->header_only;      }
     my $type = &Apache::loncommon::course_type();      return @dir_lines;
   }
   
 # --------------------------------------------- Initialize help topics for this  sub is_supplemental_title {
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',      my ($title) = @_;
                'Adding_External_Resource','Navigate_Content',      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
                'Adding_Folders','Docs_Overview', 'Load_Map',  }
                'Supplemental','Score_Upload_Form','Adding_Pages',  
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',  # --------------------------------------------------------------- An entry line
                'Check_Resource_Versions','Verify_Content') {  
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);  sub entryline {
     }      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
     # Composite help files          $crstype,$pathitem,$supplementalflag,$container)=@_;
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      my ($foldertitle,$renametitle);
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');      if (&is_supplemental_title($title)) {
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');      } else {
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(   $title=&HTML::Entities::encode($title,'"<>&\'');
     'Option_Response_Simple');   $renametitle=$title;
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(   $foldertitle=$title;
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');      }
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(  
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');      my $orderidx=$LONCAPA::map::order[$index];
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');  
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');      $renametitle=~s/\\/\\\\/g;
       $renametitle=~s/\&quot\;/\\\"/g;
 # does this user have privileges to modify docs      $renametitle=~s/ /%20/g;
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});      my $line=&Apache::loncommon::start_data_table_row();
   if ($allowed && $env{'form.verify'}) {      my ($form_start,$form_end,$form_common);
       &init_breadcrumbs('verify','Verify Content');  # Edit commands
       &verifycontent($r);      my ($esc_path, $path, $symb);
   } elsif ($allowed && $env{'form.listsymbs'}) {      if ($env{'form.folderpath'}) {
       &init_breadcrumbs('listsymbs','List Symbs');   $esc_path=&escape($env{'form.folderpath'});
       &list_symbs($r);   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   } elsif ($allowed && $env{'form.docslog'}) {   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
       &init_breadcrumbs('docslog','Show Log');      }
       &docs_change_log($r);      my $isexternal;
   } elsif ($allowed && $env{'form.versions'}) {      if ($residx) {
       &init_breadcrumbs('versions','Check/Set Resource Versions');          my $currurl = $url;
       &checkversions($r);          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
   } elsif ($allowed && $env{'form.dumpcourse'}) {          if ($currurl =~ m{^/adm/wrapper/ext/}) {
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');              $isexternal = 1;
       &dumpcourse($r);          }
   } elsif ($allowed && $env{'form.exportcourse'}) {          if (!$supplementalflag) {
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');              my $path = 'uploaded/'.
       &exportcourse($r);                         $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
   } else {                         $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 # is this a standard course?              $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
                                                    $residx,
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);                                                   &Apache::lonnet::declutter($currurl));
     my $forcestandard = 0;          }
     my $forcesupplement;      }
     my $script='';      my ($renamelink,%lt);
     my $showdoc=0;      if ($allowed) {
     my $containertag;   my $incindex=$index+1;
     my $uploadtag;   my $selectbox='';
    if (($#LONCAPA::map::order>0) &&
       ((split(/\:/,
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
     ['folderpath','pagepath',       ne '') &&
      'pagesymb']);      ((split(/\:/,
 # No folderpath, no pagepath, see if we have something stored       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {       ne '')) {
         &Apache::loncommon::restore_course_settings('docs_folderpath',      $selectbox=
                                               {'folderpath' => 'scalar'});   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
     }   '<select name="newpos" onchange="this.form.submit()">';
     if (!$env{'form.folderpath'}) {      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
         &Apache::loncommon::restore_course_settings('docs_folderpath',   if ($i==$incindex) {
                                               {'pagepath' => 'scalar'});      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
     }   } else {
     if ($env{'form.pagepath'}) {      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
        $env{'form.folderpath'}='';   }
     }      }
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {      $selectbox.='</select>';
         $env{'form.folderpath'} = 'supplemental&'.   }
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.   %lt=&Apache::lonlocal::texthash(
                                   $env{'form.folderpath'};                  'up' => 'Move Up',
     }   'dw' => 'Move Down',
     &Apache::loncommon::store_course_settings('docs_folderpath',   'rm' => 'Remove',
                                                 {'pagepath' => 'scalar',                  'ct' => 'Cut',
                                                  'folderpath' => 'scalar'});   'rn' => 'Rename',
     if ($env{'form.folderpath'}) {   'cp' => 'Copy',
  my (@folderpath)=split('&',$env{'form.folderpath'});                  'ex' => 'External Resource',
  $env{'form.foldername'}=&unescape(pop(@folderpath));                  'ed' => 'Edit',
  $env{'form.folder'}=pop(@folderpath);                  'pr' => 'Preview',
     }                  'sv' => 'Save',
     if ($env{'form.pagepath'}) {                  'ul' => 'URL',
         my (@pagepath)=split('&',$env{'form.pagepath'});                  'ti' => 'Title', 
         $env{'form.pagename'}=&unescape(pop(@pagepath));                  );
         $env{'form.folder'}=pop(@pagepath);   my $nocopy=0;
         $containertag = '<input type="hidden" name="pagepath" value="" />'.          my $nocut=0;
     '<input type="hidden" name="pagesymb" value="" />';          my $noremove=0;
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.          if ($url=~ m{^/res/.+\.(page|sequence)$}) {
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';      # no copy for published maps
     }      $nocopy=1;
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {   }
        $showdoc='/'.$1;          if ($url=~/^\/res\/lib\/templates\//) {
     }             $nocopy=1;
     unless ($showdoc) { # got called from remote             $nocut=1;
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||          }
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {          my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
            $forcestandard = 1;          my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        }          if ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);              if ($env{'form.folderpath'} =~ /^default&[^\&]+$/) {
                   my %curr_groups = &Apache::longroup::coursegroups();
        if ($allowed) {                  if (keys(%curr_groups) > 0) {
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);                      $noremove=1;
          $script=&Apache::lonratedt::editscript('simple');                  }
        }                  $nocut=1;
     } else { # got called in sequence from course                  $nocopy=1;
        $allowed=0;              }
     }          } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
               my $group = $1;
 # get course data              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};                  if (keys(%curr_group) > 0) {
                       $noremove=1;
 # get personal data                  }
     my $uname=$env{'user.name'};              }
     my $udom=$env{'user.domain'};              $nocut=1;
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));              $nocopy=1;
           } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
 # graphics settings              my $group = $1;
               if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
                   my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
     if ($allowed) {                  if (keys(%groupsettings) > 0) {
  $script .= &editing_js($udom,$uname);                      $noremove=1;
     }                  }
 # -------------------------------------------------------------------- Body tag                  $nocut=1;
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';                  $nocopy=1;
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];              }
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,          } elsif ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
     {'force_register' => $showdoc,              my $group = $1;
                                      'bread_crumbs' => $brcrum}).              my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
       &Apache::loncommon::help_open_menu('','',273,'RAT'));              if ($url =~ /group_boards_\Q$group\E/) {
                    my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
   my %allfiles = ();                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
   my %codebase = ();                  if (keys(%groupsettings) > 0) {
   my ($upload_result,$upload_output);                      if (ref($groupsettings{'functions'}) eq 'HASH') {
   if ($allowed) {                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
       if (($env{'form.uploaddoc.filename'}) &&                              $noremove=1;
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                          }
 # Process file upload - phase one - upload and parse primary file.                        }
   undef($hadchanges);                  }
           $upload_result = &process_file_upload(\$upload_output,$coursenum,                  $nocut=1;
  $coursedom,\%allfiles,                  $nocopy=1;
  \%codebase,$1);              }
   if ($hadchanges) {          }
       &mark_hash_old();          my ($copylink,$cutlink,$removelink);
   }   my $skip_confirm = 0;
           if ($upload_result eq 'phasetwo') {   if ( $folder =~ /^supplemental/
               $r->print($upload_output);       || ($url =~ m{( /smppg$
           }      |/syllabus$
       } elsif ($env{'form.phasetwo'}) {      |/aboutme$
           my %newname = ();      |/navmaps$
           my %origname = ();      |/bulletinboard$
           my %attribs = ();      |\.html$)}x)
           my $updateflag = 0;               || $isexternal) {
           my $residx = $env{'form.newidx'};      $skip_confirm = 1;
           my $primary_url = &unescape($env{'form.primaryurl'});   }
 # Process file upload - phase two - gather secondary files.  
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {   if ($nocopy) {
               if ($env{'form.embedded_item_'.$i.'.filename'}) {              $copylink=(<<ENDCOPY);
                   my $javacodebase;  <span style="visibility: hidden;">$lt{'cp'}</span>
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);  ENDCOPY
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});          } else {
                   if (exists($env{'form.embedded_codebase_'.$i})) {      $copylink=(<<ENDCOPY);
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});    <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;  ENDCOPY
                   }          }
                   my @attributes = ();   if ($nocut) {
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {              $cutlink=(<<ENDCUT);
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});  <span style="visibility: hidden;">$lt{'ct'}</span>
                   } else {  ENDCUT
                       @attributes = ($env{'form.embedded_attrib_'.$i});          } else {
                   }      $cutlink=(<<ENDCUT);
                   foreach my $attr (@attributes) {  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
                       push(@{$attribs{$i}},&unescape($attr));  ENDCUT
                   }          }
                   if ($javacodebase) {          if ($noremove) {
                       $codebase{$i} = $javacodebase;              $removelink=(<<ENDREM);
                       $codebase{$i} =~ s#/$##;  <span style="visibility: hidden;">$lt{'rm'}</a>
                       $updateflag = 1;  ENDREM
                   }          } else {
               }              $removelink=(<<ENDREM);
               unless ($newname{$i} eq $origname{$i}) {  <a href='javascript:removeres("$esc_path","$index","$renametitle",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
                   $updateflag = 1;  ENDREM
               }          }
           }          unless ($isexternal) {
 # Process file upload - phase three - modify primary file              $renamelink=(<<ENDREN);
           if ($updateflag) {  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
               my ($content,$rtncode);  ENDREN
               my $updateflag = 0;          }
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);   $form_start = '
               if ($getstatus eq 'ok') {     <form action="/adm/coursedocs" method="post">
                   foreach my $item (keys(%newname)) {  ';
                       if ($newname{$item} ne $origname{$item}) {          $form_common=(<<END);
                           my $attrib_regexp = '';     <input type="hidden" name="folderpath" value="$path" />
                           if (@{$attribs{$item}} > 1) {     <input type="hidden" name="symb" value="$symb" />
                               $attrib_regexp = join('|',@{$attribs{$item}});     <input type="hidden" name="setparms" value="$orderidx" />
                           } else {     <input type="hidden" name="changeparms" value="0" />
                               $attrib_regexp = $attribs{$item}[0];  END
                           }          $form_end = '</form>';
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {   $line.=(<<END);
                           }  <td>
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;  <div class="LC_docs_entry_move">
                       }    <a href='/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
                       if (exists($codebase{$item})) {      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs    </a>
                       }  </div>
                   }  <div class="LC_docs_entry_move">
 # Save edited file.    <a href='/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
                   my $saveresult;      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};    </a>
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};  </div>
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);  </td>
               } else {  <td>
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);     $form_start
               }     $form_common
           }     $selectbox
       }     $form_end
   }  </td>
   <td class="LC_docs_entry_commands"><span class="LC_nobreak">
   unless ($showdoc ||  $upload_result eq 'phasetwo') {  $removelink
 # -----------------------------------------------------------------------------  $cutlink
        my %lt=&Apache::lonlocal::texthash(  $copylink
                 'uplm' => 'Upload a new main '.lc($type).' document',  </span>
                 'upls' => 'Upload a new supplemental '.lc($type).' document',  </td>
                 'impp' => 'Import a document',  END
                 'pubd' => 'Published Documents',  
  'copm' => 'All documents out of a published map into this folder',      }
                 'upld' => 'Upload Document',  # Figure out what kind of a resource this is
                 'srch' => 'Search',      my ($extension)=($url=~/\.(\w+)$/);
                 'impo' => 'Import',      my $uploaded=($url=~/^\/*uploaded\//);
  'book' => 'Import Bookmarks',      my $icon=&Apache::loncommon::icon($url);
                 'selm' => 'Select Map',      my $isfolder;
                 'load' => 'Load Map',      my $ispage;
                 'reco' => 'Recover Deleted Resources',      my $containerarg;
                 'newf' => 'New Folder',      if ($uploaded) {
                 'newp' => 'New Composite Page',          if (($extension eq 'sequence') || ($extension eq 'page')) {
                 'extr' => 'External Resource',              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
                 'syll' => 'Syllabus',              $containerarg = $1;
                 'navc' => 'Navigate Contents',      if ($extension eq 'sequence') {
                 'sipa' => 'Simple Page',          $icon=$iconpath.'navmap.folder.closed.gif';
                 'sipr' => 'Simple Problem',                  $isfolder=1;
                 'drbx' => 'Drop Box',              } else {
                 'scuf' => 'Score Upload Form',                  $icon=$iconpath.'page.gif';
                 'bull' => 'Bulletin Board',                  $ispage=1;
                 'mypi' => 'My Personal Info',              }
                 'grpo' => 'Group Files',              if ($allowed) {
                 'rost' => 'Course Roster',                  $url='/adm/coursedocs?';
  'abou' => 'About User',              } else {
                 'imsf' => 'Import IMS package',                  $url='/adm/supplemental?';
                 'file' =>  'File',              }
                 'title' => 'Title',   } else {
                 'comment' => 'Comment',      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',   }
  'nd' => 'New Document',      }
  'pm' => 'Published Map',  
  'sd' => 'Special Document',      my ($editlink,$extresform);
  'mo' => 'More Options',      my $orig_url = $url;
  'hao' => 'Hide all Options'      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
   );      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
 # -----------------------------------------------------------------------------      if (!$supplementalflag && $residx && $symb) {
  my $fileupload=(<<FIUP);          if ((!$isfolder) && (!$ispage)) {
  $lt{'file'}:<br />      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  <input type="file" name="uploaddoc" size="40" />      $url=&Apache::lonnet::clutter($url);
 FIUP      if ($url=~/^\/*uploaded\//) {
           $url=~/\.(\w+)$/;
  my $checkbox=(<<CHBO);          my $embstyle=&Apache::loncommon::fileembstyle($1);
  <!-- <label>$lt{'parse'}?          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
  <input type="checkbox" name="parserflag" />      $url='/adm/wrapper'.$url;
  </label> -->          } elsif ($embstyle eq 'ssi') {
  <label>      #do nothing with these
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}          } elsif ($url!~/\.(sequence|page)$/) {
  </label>      $url='/adm/coursedocs/showdoc'.$url;
 CHBO          }
       } elsif ($url=~m|^/ext/|) {
  my $fileuploadform=(<<FUFORM);          $url='/adm/wrapper'.$url;
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">      }
  $fileupload              if (&Apache::lonnet::symbverify($symb,$url)) {
  <br />          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  $lt{'title'}:<br />              } else {
  <input type="text" size="50" name="comment" />                  $url='';
  $uploadtag              }
  <input type="hidden" name="cmd" value="upload_default" />   }
  <br />      }
  <span class="LC_nobreak">      my ($rand_pick_text,$rand_order_text);
  $checkbox      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
  </span>   my $foldername=&escape($foldertitle);
  <br />   my $folderpath=$env{'form.folderpath'};
  <br />   if ($folderpath) { $folderpath.='&' };
  <span class="LC_nobreak">          if (!$allowed && $supplementalflag) {
  <input type="submit" value="$lt{'upld'}" />              $folderpath.=$containerarg.'&'.$foldername;
  $help{'Uploading_From_Harddrive'}              $url.='folderpath='.&escape($folderpath);
  </span>          } else {
  </form>  # Append randompick number, hidden, and encrypted with ":" to foldername,
 FUFORM  # so it gets transferred between levels
       $folderpath.=$containerarg.'&'.$foldername.
  my $simpleeditdefaultform=(<<SEDFFORM);                                                ':'.(&LONCAPA::map::getparameter($orderidx,
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">                                                'parameter_randompick'))[0]
  $lt{'pubd'}<br />                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  $uploadtag                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  <br />                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  <span class="LC_nobreak">                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />                                                'parameter_randomorder'))[0]=~/^yes$/i)
  $help{'Importing_LON-CAPA_Resource'}                                                 .':'.$ispage;
  </span>      $url.='folderpath='.&escape($folderpath);
  <br />              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />                                                          'parameter_randompick'))[0];
  <hr />              my $rpckchk;
  <p>              if ($rpicknum) {
  $lt{'copm'}<br />                  $rpckchk = ' checked="checked"';
  <input type="text" size="40" name="importmap" /><br />              }
  <span class="LC_nobreak"><input type="button"              my $formname = 'edit_randompick_'.$orderidx;
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      $rand_pick_text = 
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
  $help{'Load_Map'}</span>  $form_common."\n".
  </p>  '<span class="LC_nobreak"><label><input type="checkbox" name="randompick_'.$orderidx.'" id="randompick_'.$orderidx.'" onclick="'."updatePick(this.form,'$orderidx','check');".'"'.$rpckchk.' /> '.&mt('Randomly Pick').'</label><input type="hidden" name="rpicknum_'.$orderidx.'" id="rpicknum_'.$orderidx.'" value="'.$rpicknum.'" /><span id="randompicknum_'.$orderidx.'">';
  </form>              if ($rpicknum ne '') {
 SEDFFORM                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
               }
  my $extresourcesform=(<<ERFORM);              $rand_pick_text .= '</span></span>'.
  <form action="/adm/coursedocs" method="post" name="newext">                                 $form_end;
  $uploadtag         my $ro_set=
  <input type="hidden" name="importdetail" value="" />          ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
  <span class="LC_nobreak">              my $formname = 'edit_rorder_'.$orderidx;
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"      $rand_order_text = 
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
  </span>  $form_common."\n".
  </form>  '<span class="LC_nobreak"><label><input type="checkbox" name="randomorder_'.$orderidx.'" id="randomorder_'.$orderidx.'" onclick="checkForSubmit(this.form,'."'randomorder'".')"; '.$ro_set.' /> '.&mt('Random Order').' </label></span>'.
 ERFORM  $form_end; 
           }
     if ($allowed) {      } elsif ($supplementalflag && !$allowed) {
  &update_paste_buffer($coursenum,$coursedom);          $url .= ($url =~ /\?/) ? '&amp;':'?';
        my $dumpbut=&dumpbutton();          $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
        my $exportbut=&exportbutton();          if ($title) {
        my %lt=&Apache::lonlocal::texthash(              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
  'vc' => 'Verify Content',          }
  'cv' => 'Check/Set Resource Versions',          if ($isexternal && $orderidx) {
  'ls' => 'List Symbs',              $url .= '&amp;idx='.$orderidx;
                                          'sl' => 'Show Log'          }
   );      }
       my ($tdalign,$tdwidth);
        my $folderpath=$env{'form.folderpath'};      if ($allowed) {
        if (!$folderpath) {          my $fileloc = 
    if ($env{'form.folder'} eq '' ||              &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
        $env{'form.folder'} eq 'supplemental') {          if ($isexternal) {
        $folderpath='default&'.              ($editlink,$extresform) = 
    &escape(&mt('Main '.$type.' Documents'));                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
    }          } elsif (!$isfolder && !$ispage) {
        }              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
        unless ($env{'form.pagepath'}) {                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
            $containertag = '<input type="hidden" name="folderpath" value="" />';              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';                  my $jscall = 
        }                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
        $r->print(&generate_admin_options($containertag,$uploadtag,\%lt,\%help,\%env));                                                              $switchserver,
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',                                                              $forceedit,
      &mt('Editing the Table of Contents for your '.$type)));                                                              undef,$symb,
     }                                                              &escape($env{'form.folderpath'}),
 # --------------------------------------------------------- Standard documents                                                              $renametitle,'','',1);
     $r->print('<table class="LC_docs_documents">');                  if ($jscall) {
                       $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
     if (($standard) && ($allowed) && (!$forcesupplement)) {                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
  $r->print('<tr><td class="LC_docs_document">');                  }
 #  '<h2>'.&mt('Main Course Documents').              }
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');          }
        my $folder=$env{'form.folder'};          $tdalign = ' align="right" valign="top"';
        if ($folder eq '' || $folder eq 'supplemental') {          $tdwidth = ' width="80%"';
            $folder='default';      }
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));      my $reinit;
            $uploadtag = '<input type="hidden" name="folderpath" value="'.      if ($crstype eq 'Community') {
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';          $reinit = &mt('(re-initialize community to access)');
        }      } else {
        my $postexec='';          $reinit = &mt('(re-initialize course to access)');
        if ($folder eq 'default') {      }
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
        } else {      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
            #$postexec='self.close();';         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
        }      } elsif ($url) {
        $hadchanges=0;         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
    $upload_output,$type);      } else {
        if ($error) {         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');      }
        }      $line.='</span></td><td'.$tdwidth.'>';
        if ($hadchanges) {      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
    &mark_hash_old();         $line.='<a href="'.$url.'">'.$title.'</a>';
        }      } elsif ($url) {
        &changewarning($r,$postexec);         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.                                               $title,600,500);
                      '.sequence';      } else {
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
                      '.page';      }
  my $container='sequence';      $line.="$extresform</td>";
  if ($env{'form.pagepath'}) {      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
     $container='page';      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
  }      if (($allowed) && ($folder!~/^supplemental/)) {
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;    my %lt=&Apache::lonlocal::texthash(
          'hd' => 'Hidden',
          'ec' => 'URL hidden');
    my $enctext=
  my $recoverform=(<<RFORM);      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
  <form action="/adm/groupsort" method="post" name="recover">   my $hidtext=
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
  </form>          my $formhidden = 'edit_hiddenresource_'.$orderidx;
 RFORM          my $formurlhidden = 'edit_encrypturl_'.$orderidx;
    $line.=(<<ENDPARMS);
  my $imspform=(<<IMSPFORM);    <td class="LC_docs_entry_parameter">
  <form action="/adm/imsimportdocs" method="post" name="ims">      <form action="/adm/coursedocs" method="post" name="$formhidden">
  <input type="hidden" name="folder" value="$folder" />      $form_common
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />      <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'."'hiddenresource'".');" $hidtext /> $lt{'hd'}</label>
  </form>      $form_end
 IMSPFORM      <br />
       <form action="/adm/coursedocs" method="post" name="$formurlhidden">
  my $newnavform=(<<NNFORM);      $form_common
  <form action="/adm/coursedocs" method="post" name="newnav">      <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'."'encrypturl'".');" $enctext /> $lt{'ec'}</label>
  $uploadtag      $form_end
  <input type="hidden" name="importdetail"    </td>
  value="$lt{'navc'}=/adm/navmaps" />    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
  <span class="LC_nobreak">                                        $rand_order_text</td>
  <input name="newnav" type="submit" value="$lt{'navc'}" />  ENDPARMS
  $help{'Navigate_Content'}      }
  </span>      $line.=&Apache::loncommon::end_data_table_row();
  </form>      return $line;
 NNFORM  }
  my $newsmppageform=(<<NSPFORM);  
  <form action="/adm/coursedocs" method="post" name="newsmppg">  sub new_timebased_suffix {
  $uploadtag      my ($coursedom,$coursenum,$type,$area,$container) = @_;
  <input type="hidden" name="importdetail" value="" />      my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
  <span class="LC_nobreak">      if ($type eq 'map') {
  <input name="newsmppg" type="button" value="$lt{'sipa'}"          $prefix = 'docs';
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}          if ($area eq 'supplemental') {
  </span>              $prefix = 'supp';
  </form>          }
 NSPFORM          $prefix .= $container;
           $namespace = 'uploadedmaps';
  my $newsmpproblemform=(<<NSPROBFORM);      } else {
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">          $prefix = $type;
  $uploadtag          $namespace = 'templated';
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">      $idtype = 'concat';
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"      my ($suffix,$freedlock,$error) =
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}          &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,
  </span>                                            $coursedom,$coursenum);
  </form>      if (!$suffix) {
           if ($type eq 'map') {
 NSPROBFORM              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
           } elsif ($type eq 'smppg') {
  my $newdropboxform=(<<NDBFORM);              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
  <form action="/adm/coursedocs" method="post" name="newdropbox">          } else {
  $uploadtag                    $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new bulletin board.');
  <input type="hidden" name="importdetail" value="" />          }
  <span class="LC_nobreak">                    if ($error) {
  <input name="newdropbox" type="button" value="$lt{'drbx'}"              $errtext .= '<br />'.$error;
  onClick="javascript:makedropbox();" />          }
  </span>              }
  </form>      if ($freedlock ne 'ok') {
 NDBFORM          $locknotfreed = 
               '<div class="LC_error">'.
  my $newexuploadform=(<<NEXUFORM);              &mt('There was a problem removing a lockfile.').' ';
  <form action="/adm/coursedocs" method="post" name="newexamupload">          if ($type eq 'map') {
  $uploadtag              &mt('This will prevent creation of additional folders or composite pages in this course.');
  <input type="hidden" name="importdetail" value="" />          } elsif ($type eq 'smppg') {
  <span class="LC_nobreak">              $locknotfreed .=
  <input name="newexamupload" type="button" value="$lt{'scuf'}"                  &mt('This will prevent creation of additional simple pages in this course.');
  onClick="javascript:makeexamupload();" />          } else {
  $help{'Score_Upload_Form'}              $locknotfreed .=
  </span>                  &mt('This will prevent creation of additional bulletin boards in this course.');
  </form>          }
 NEXUFORM          $locknotfreed .=
               ' '.&mt('Please contact the domain coordinator for your LON-CAPA domain.').
  my $newbulform=(<<NBFORM);              '</div>';
  <form action="/adm/coursedocs" method="post" name="newbul">      }
  $uploadtag      return ($suffix,$errtext,$locknotfreed);
  <input type="hidden" name="importdetail" value="" />  }
  <span class="LC_nobreak">  
  <input name="newbulletin" type="button" value="$lt{'bull'}"  =pod
  onClick="javascript:makebulboard();" />  
  $help{'Bulletin Board'}  =item tiehash()
  </span>  
  </form>  tie the hash
 NBFORM  
   =cut
  my $newaboutmeform=(<<NAMFORM);  
  <form action="/adm/coursedocs" method="post" name="newaboutme">  sub tiehash {
  $uploadtag      my ($mode)=@_;
  <input type="hidden" name="importdetail"      $hashtied=0;
  value="$plainname=/adm/$udom/$uname/aboutme" />      if ($env{'request.course.fn'}) {
  <span class="LC_nobreak">   if ($mode eq 'write') {
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  $help{'My Personal Info'}      &GDBM_WRCREAT(),0640)) {
  </span>                  $hashtied=2;
  </form>      }
 NAMFORM   } else {
       if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  my $newaboutsomeoneform=(<<NASOFORM);      &GDBM_READER(),0640)) {
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">                  $hashtied=1;
  $uploadtag      }
  <input type="hidden" name="importdetail" value="" />   }
  <span class="LC_nobreak">      }
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"  }
  onClick="javascript:makeabout();" />  
  </span>  sub untiehash {
  </form>      if ($hashtied) { untie %hash; }
 NASOFORM      $hashtied=0;
       return OK;
   }
  my $newrosterform=(<<NROSTFORM);  
  <form action="/adm/coursedocs" method="post" name="newroster">  
  $uploadtag  
  <input type="hidden" name="importdetail"  
  value="$lt{'rost'}=/adm/viewclasslist" />  sub checkonthis {
  <span class="LC_nobreak">      my ($r,$url,$level,$title)=@_;
  <input name="newroster" type="submit" value="$lt{'rost'}" />      $url=&unescape($url);
  $help{'Course Roster'}      $alreadyseen{$url}=1;
  </span>      $r->rflush();
  </form>      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 NROSTFORM         $r->print("\n<br />");
          if ($level==0) {
        $r->print(<<ENDFORM);             $r->print("<br />");
          }
 <ul class="LC_TabContent">         for (my $i=0;$i<=$level*5;$i++) {
 <li>$lt{'nd'}</li>             $r->print('&nbsp;');
 <li>$lt{'pm'}</li>         }
 <li>$lt{'pubd'}</li>         $r->print('<a href="'.$url.'" target="cat">'.
 <li>$lt{'sd'}</li>   ($title?$title:$url).'</a> ');
 <li>$lt{'mo'}</li>         if ($url=~/^\/res\//) {
 <li>$lt{'hao'}</li>    my $result=&Apache::lonnet::repcopy(
 </ul>                                &Apache::lonnet::filelocation('',$url));
             if ($result eq 'ok') {
 <table class="LC_docs_adddocs">               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 <!-- <tr>               $r->rflush();
 <th>$lt{'uplm'}</th>               &Apache::lonnet::countacc($url);
 <th>$lt{'impp'}</th>               $url=~/\.(\w+)$/;
 <th>$lt{'spec'}</th>               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 </tr> -->   $r->print('<br />');
 <tr>                   $r->rflush();
 <td>                   for (my $i=0;$i<=$level*5;$i++) {
 $fileuploadform                       $r->print('&nbsp;');
 </td>                   }
 <td>                   $r->print('- '.&mt('Rendering:').' ');
 $simpleeditdefaultform   my ($errorcount,$warningcount)=split(/:/,
 <hr />         &Apache::lonnet::ssi_body($url,
 $recoverform         ('grade_target'=>'web',
 ENDFORM   'return_only_error_and_warning_counts' => 1)));
        unless ($env{'form.pagepath'}) {                   if (($errorcount) ||
    $r->print(<<ENDFORM);                       ($warningcount)) {
 <hr />       if ($errorcount) {
 $extresourcesform                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
  <br />                            &mt('[quant,_1,error]',$errorcount).'</span>');
 $imspform                       }
 ENDFORM       if ($warningcount) {
        }                          $r->print('<span class="LC_warning">'.
        $r->print('</td><td>');                            &mt('[quant,_1,warning]',$warningcount).'</span>');
        unless ($env{'form.pagepath'}) {                       }
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                   } else {
                        $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                    }
                    $r->rflush();
  my $newpageform=(<<NPFORM);               }
  <form action="/adm/coursedocs" method="post" name="newpage">       my $dependencies=
  <input type="hidden" name="folderpath" value="$path" />                  &Apache::lonnet::metadata($url,'dependencies');
  <input type="hidden" name="importdetail" value="" />               foreach my $dep (split(/\,/,$dependencies)) {
  <span class="LC_nobreak">   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
  <input name="newpage" type="button"                      &checkonthis($r,$dep,$level+1);
  onClick="javascript:makenewpage(this.form,'$pageseq');"                   }
  value="$lt{'newp'}" />$help{'Adding_Pages'}               }
  </span>            } elsif ($result eq 'unavailable') {
  </form>               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 NPFORM            } elsif ($result eq 'not_found') {
         unless ($url=~/\$/) {
  my $newfolderform=(<<NFFORM);    $r->print('<span class="LC_error">'.&mt('not found').'</span>');
  <form action="/adm/coursedocs" method="post" name="newfolder">        } else {
  <input type="hidden" name="folderpath" value="$path" />    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
  <input type="hidden" name="importdetail" value="" />        }
  <span class="LC_nobreak">            } else {
  <input name="newfolder" type="button"               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
  onClick="javascript:makenewfolder(this.form,'$folderseq');"            }
  value="$lt{'newf'}" />$help{'Adding_Folders'}         }
  </span>      }
  </form>  }
 NFFORM  
   
  my $newsylform=(<<NSYLFORM);  
  <form action="/adm/coursedocs" method="post" name="newsyl">  =pod
  $uploadtag  
  <input type="hidden" name="importdetail"  =item list_symbs()
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />  
  <span class="LC_nobreak">  List Content Identifiers
  <input name="newsyl" type="submit" value="$lt{'syll'}" />  
  $help{'Syllabus'}  =cut
  </span>  
  </form>  sub list_symbs {
 NSYLFORM      my ($r) = @_;
   
  my $newgroupfileform=(<<NGFFORM);      my $crstype = &Apache::loncommon::course_type();
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
  $uploadtag      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
  <input type="hidden" name="importdetail"      $r->print(&startContentScreen('tools'));
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />      my $navmap = Apache::lonnavmaps::navmap->new();
  <span class="LC_nobreak">      if (!defined($navmap)) {
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
  $help{'Group Files'}                    '<div class="LC_error">'.
  </span>                    &mt('Unable to retrieve information about course contents').
  </form>                    '</div>');
 NGFFORM          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
       } else {
           $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
            $r->print(<<ENDFORM);                    &Apache::loncommon::start_data_table().
 <br />                    &Apache::loncommon::start_data_table_header_row().
 $newfolderform                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
 <br />                    &Apache::loncommon::end_data_table_header_row()."\n");
 $newpageform          my $count;
 <br />          foreach my $res ($navmap->retrieveResources()) {
 $newsylform              $r->print(&Apache::loncommon::start_data_table_row().
 <br />                        '<td>'.$res->compTitle().'</td>'.
 $newnavform                        '<td>'.$res->symb().'</td>'.
 <br />                        &Apache::loncommon::end_data_table_row());
 $newsmppageform              $count ++;
 <br />          }
 $newsmpproblemform          if (!$count) {
 <br />              $r->print(&Apache::loncommon::start_data_table_row().
 $newdropboxform                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
 <br />                        &Apache::loncommon::end_data_table_row()); 
 $newexuploadform          }
 <br />          $r->print(&Apache::loncommon::end_data_table());
 $newbulform      }
 <br />      $r->print(&endContentScreen());
 $newaboutmeform  }
 <br />  
 $newaboutsomeoneform  
 <br />  sub verifycontent {
 $newgroupfileform      my ($r) = @_;
 <br />      my $crstype = &Apache::loncommon::course_type();
 $newrosterform      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
 ENDFORM      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
        }      $r->print(&startContentScreen('tools'));
        if ($env{'form.pagepath'}) {      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
            $r->print(<<ENDBLOCK);     $hashtied=0;
 $newsmpproblemform     undef %alreadyseen;
 <br />     %alreadyseen=();
 $newexuploadform     &tiehash();
 ENDBLOCK     
        }     foreach my $key (keys(%hash)) {
        $r->print('</td></tr>'."\n".         if ($hash{$key}=~/\.(page|sequence)$/) {
 '</table>');     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
        $r->print('</td></tr>');         $r->print('<hr /><span class="LC_error">'.
     }   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
 # ----------------------------------------------------- Supplemental documents   &unescape($hash{$key}).'</span><br />'.
     if (!$forcestandard) {   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
        $r->print('<tr><td class="LC_docs_document">');     }
 # '<h2>'.&mt('Supplemental Course Documents').         }
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
        my $folder=$env{'form.folder'};             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
        unless ($folder=~/^supplemental/) {         }
    $folder='supplemental';     }
        }     &untiehash();
        if ($folder =~ /^supplemental$/ &&     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {      $r->print(&endContentScreen());
           $env{'form.folderpath'} = 'supplemental&'.  }
                                     &escape(&mt('Supplemental '.$type.' Documents'));  
        }  
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);  sub devalidateversioncache {
        if ($error) {      my $src=shift;
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
        }    &Apache::lonnet::clutter($src));
        if ($allowed) {  }
    my $folderseq=  
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.  sub checkversions {
        '.sequence';      my ($r) = @_;
       my $crstype = &Apache::loncommon::course_type();
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
  my $supupdocform=(<<SUPDOCFORM);      $r->print(&startContentScreen('tools'));
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">  
  $fileupload      my $header='';
  <br />      my $startsel='';
  <br />      my $monthsel='';
  <span class="LC_nobreak">      my $weeksel='';
  $checkbox      my $daysel='';
  </span>      my $allsel='';
  <br /><br />      my %changes=();
  $lt{'comment'}:<br />      my $starttime=0;
  <textarea cols=50 rows=4 name='comment'>      my $haschanged=0;
  </textarea>      my %setversions=&Apache::lonnet::dump('resourceversions',
  <br />    $env{'course.'.$env{'request.course.id'}.'.domain'},
  <input type="hidden" name="folderpath" value="$path" />    $env{'course.'.$env{'request.course.id'}.'.num'});
  <input type="hidden" name="cmd" value="upload_supplemental" />  
  <span class="LC_nobreak">      $hashtied=0;
  <input type="submit" value="$lt{'upld'}" />      &tiehash();
  $help{'Uploading_From_Harddrive'}      my %newsetversions=();
  </span>      if ($env{'form.setmostrecent'}) {
  </form>   $haschanged=1;
 SUPDOCFORM   foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
  my $supnewfolderform=(<<SNFFORM);   $newsetversions{$1}='mostrecent';
  <form action="/adm/coursedocs" method="post" name="supnewfolder">                  &devalidateversioncache($1);
  <input type="hidden" name="folderpath" value="$path" />      }
  <input type="hidden" name="importdetail" value="" />   }
  <span class="LC_nobreak">      } elsif ($env{'form.setcurrent'}) {
  <input name="newfolder" type="button"   $haschanged=1;
  onClick="javascript:makenewfolder(this.form,'$folderseq');"   foreach my $key (keys(%hash)) {
  value="$lt{'newf'}" /> $help{'Adding_Folders'}      if ($key=~/^ids\_(\/res\/.+)$/) {
  </span>   my $getvers=&Apache::lonnet::getversion($1);
  </form>   if ($getvers>0) {
 SNFFORM      $newsetversions{$1}=$getvers;
       &devalidateversioncache($1);
    }
  my $supnewextform=(<<SNEFORM);      }
  <form action="/adm/coursedocs" method="post" name="supnewext">   }
  <input type="hidden" name="folderpath" value="$path" />      } elsif ($env{'form.setversions'}) {
  <input type="hidden" name="importdetail" value="" />   $haschanged=1;
  <span class="LC_nobreak">   foreach my $key (keys(%env)) {
  <input name="newext" type="button"      if ($key=~/^form\.set_version_(.+)$/) {
  onClick="javascript:makenewext('supnewext');"   my $src=$1;
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
  </span>      $newsetversions{$src}=$env{$key};
  </form>      &devalidateversioncache($src);
 SNEFORM   }
       }
  my $supnewsylform=(<<SNSFORM);   }
  <form action="/adm/coursedocs" method="post" name="supnewsyl">      }
  <input type="hidden" name="folderpath" value="$path" />      if ($haschanged) {
  <input type="hidden" name="importdetail"          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />    $env{'course.'.$env{'request.course.id'}.'.domain'},
  <span class="LC_nobreak">    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      $r->print(&Apache::loncommon::confirmwrapper(
  $help{'Syllabus'}                  &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
  </span>   } else {
  </form>      $r->print(&Apache::loncommon::confirmwrapper(
 SNSFORM                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
    }
  my $supnewaboutmeform=(<<SNAMFORM);   &mark_hash_old();
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">      }
  <input type="hidden" name="folderpath" value="$path" />      &changewarning($r,'');
  <input type="hidden" name="importdetail"      if ($env{'form.timerange'} eq 'all') {
  value="$plainname=/adm/$udom/$uname/aboutme" />  # show all documents
  <span class="LC_nobreak">   $header=&mt('All Documents in '.$crstype);
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   $allsel=' selected="selected"';
  $help{'My Personal Info'}   foreach my $key (keys(%hash)) {
  </span>      if ($key=~/^ids\_(\/res\/.+)$/) {
  </form>   my $src=$1;
 SNAMFORM   $changes{$src}=1;
       }
    $r->print(<<ENDSUPFORM);   }
 <ul class="LC_TabContent">      } else {
 <li>$lt{'nd'}</li>  # show documents which changed
 <li>$lt{'sd'}</li>   %changes=&Apache::lonnet::dump
 <li>$lt{'hao'}</li>   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
 </ul>                       $env{'course.'.$env{'request.course.id'}.'.num'});
 <table class="LC_docs_adddocs">   my $firstkey=(keys(%changes))[0];
 <tr><td>   unless ($firstkey=~/^error\:/) {
 $supupdocform      unless ($env{'form.timerange'}) {
 </td>   $env{'form.timerange'}=604800;
 <td>      }
 $supnewfolderform      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 <br />   .&mt('seconds');
 $supnewextform      if ($env{'form.timerange'}==-1) {
 <br />   $seltext='since start of course';
 $supnewsylform   $startsel=' selected="selected"';
 <br />   $env{'form.timerange'}=time;
 $supnewaboutmeform      }
 </td></tr>      $starttime=time-$env{'form.timerange'};
 </table></td></tr>      if ($env{'form.timerange'}==2592000) {
 ENDSUPFORM   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
        }   $monthsel=' selected="selected"';
     }      } elsif ($env{'form.timerange'}==604800) {
     $r->print('</table>');   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
     if ($allowed) {   $weeksel=' selected="selected"';
  $r->print('      } elsif ($env{'form.timerange'}==86400) {
 <form method="post" name="extimport" action="/adm/coursedocs">   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
   <input type="hidden" name="title" />   $daysel=' selected="selected"';
   <input type="hidden" name="url" />      }
   <input type="hidden" name="useform" />      $header=&mt('Content changed').' '.$seltext;
   <input type="hidden" name="residx" />   } else {
 </form>');      $header=&mt('No content modifications yet.');
     }   }
   } else {      }
       unless ($upload_result eq 'phasetwo') {      %setversions=&Apache::lonnet::dump('resourceversions',
 # -------------------------------------------------------- This is showdoc mode    $env{'course.'.$env{'request.course.id'}.'.domain'},
           $r->print("<h1>".&mt('Uploaded Document').' - '.    $env{'course.'.$env{'request.course.id'}.'.num'});
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.      my %lt=&Apache::lonlocal::texthash
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".        ('st' => 'Version changes since start of '.$crstype,
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');         'lm' => 'Version changes since last Month',
       }         'lw' => 'Version changes since last Week',
   }         'sy' => 'Version changes since Yesterday',
  }                 'al' => 'All Resources (possibly large output)',
  $r->print(&Apache::loncommon::end_page());                 'cd' => 'Change display', 
  return OK;         'sd' => 'Display',
 }         'fi' => 'File',
          'md' => 'Modification Date',
 sub generate_admin_options {                 'mr' => 'Most recently published Version',
   my ($containertag,$uploadtag,$lt_ref,$help_ref,$env_ref) = @_;         've' => 'Version used in '.$crstype,
   my %lt = %{$lt_ref};                 'vu' => 'Set Version to be used in '.$crstype,
   my %help = %{$help_ref};  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
   my %env = %{$env_ref};  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
   my $dumpbut=&dumpbutton();  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
   my $exportbut=&exportbutton();         'di' => 'Differences',
   return (<<ENDOPTIONFORM);         'save' => 'Save changes',
  <form name="renameform" method="post" action="/adm/coursedocs">                 'vers' => 'Version choice(s) for specific resources', 
    <input type="hidden" name="title" />         'act' => 'Actions');
    <input type="hidden" name="cmd" />      $r->print(<<ENDHEADERS);
    <input type="hidden" name="markcopy" />  <h4 class="LC_info">$header</h4>
    <input type="hidden" name="copyfolder" />  <form action="/adm/coursedocs" method="post">
    $containertag  <input type="hidden" name="versions" value="1" />
  </form>  <div class="LC_left_float">
  <form name="simpleedit" method="post" action="/adm/coursedocs">  <fieldset>
    <input type="hidden" name="importdetail" value="" />  <legend>$lt{'cd'}</legend>
    $uploadtag  <select name="timerange">
  </form>  <option value='all'$allsel>$lt{'al'}</option>
  <form action="/adm/coursedocs" method="post" name="courseverify">  <option value="-1"$startsel>$lt{'st'}</option>
    <ul style="list-style-type:none">  <option value="2592000"$monthsel>$lt{'lm'}</option>
        <li>  <option value="604800"$weeksel>$lt{'lw'}</option>
            <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}  <option value="86400"$daysel>$lt{'sy'}</option>
        </li>  </select>
        <li>  <input type="submit" name="display" value="$lt{'sd'}" />
            <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}  </fieldset>
        </li>  </div>
        <li>  <div class="LC_left_float">
            $dumpbut  <fieldset>
        </li>  <legend>$lt{'act'}</legend>
        <li>  $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
            $exportbut  $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
        </li>  </fieldset>
        <li>  </div>
           <input type="submit" name="listsymbs" value="$lt{'ls'}" />  <br clear="all" />
         </li>  <hr />
         <li>  <h4>$lt{'vers'}</h4>
           <input type="hidden" name="folder" value="$env{'form.folder'}" />  <input type="submit" name="setversions" value="$lt{'save'}" />
           <input type="submit" name="docslog" value="$lt{'sl'}" />  ENDHEADERS
         </li>      #number of columns for version history
    </ul>      $r->print(
  </form>          &Apache::loncommon::start_data_table().
  <div style="clear: both; height: 0px;">&nbsp;</div>          &Apache::loncommon::start_data_table_header_row().
 ENDOPTIONFORM          '<th>'.&mt('Resources').'</th>'.
 }          "<th>$lt{'mr'}</th>".
           "<th>$lt{'ve'}</th>".
 sub generate_edit_table {          "<th>$lt{'vu'}</th>".
     my ($optionhash_ref,$namehash_ref,$orderhash_ref) = @_;          '<th>'.&mt('History').'</th>'.
     my %optionhash = %{$optionhash_ref};         #id verlinkt mit inhalt          &Apache::loncommon::end_data_table_header_row()
     my %namehash = %{$namehash_ref};             #name verlinkt mit id      );
     my %orderhash = %{$orderhash_ref};           #name mit kürzel verlinkt mit name      foreach my $key (sort(keys(%changes))) {
     my $form;          #excludes not versionable problems from resource version history:
     $form = '<div class="LC_ContentBoxSpecial"><h4 class="LC_hcell">'.&mt('Upload Course Documents').'<h4>';          next unless ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/);
     $form .= '<ul class="LC_TabContent">';          my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
     foreach my $name (sort(keys(%orderhash))){          my $currentversion=&Apache::lonnet::getversion($key);
         if($name eq 'zz_hide'){          if ($currentversion<0) {
             $form .= '<li><a onclick="hideAllSection();" href="#">'.&mt($orderhash{$name}).'</a></li>';              $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
         }else{          }
             $form .= '<li><a onclick="popUpSection(\''.$namehash{$orderhash{$name}}.'\');" href="#">'.&mt($orderhash{$name}).'</a></li>';          my $linkurl=&Apache::lonnet::clutter($key);
         }          $r->print(
     }              &Apache::loncommon::start_data_table_row().
     foreach my $field (keys(%optionhash)){              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
         $form .= '<div id="'.$field.'" class="LC_ContentBox LC_hideThis">'.$optionhash{$field}.'</div>';              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
     }              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
     $form .= '</div>';              &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
     return $form;              '<td align="right">'
 }          );
           # Used in course
 sub editing_js {          my $usedversion=$hash{'version_'.$linkurl};
     my ($udom,$uname) = @_;          if (($usedversion) && ($usedversion ne 'mostrecent')) {
     my $now = time();                  if ($usedversion != $currentversion) {
     my %lt = &Apache::lonlocal::texthash(                      $r->print('<span class="LC_warning">'.$usedversion.'</span>');
                                           p_mnf => 'Name of New Folder',                  } else {
                                           t_mnf => 'New Folder',                      $r->print($usedversion);
                                           p_mnp => 'Name of New Page',                  }
                                           t_mnp => 'New Page',              } else {
                                           p_mxu => 'Title for the Uploaded Score',                  $r->print($currentversion);
                                           p_msp => 'Title for the Page',              }
                                           p_msb => 'Title for the Problem',          $r->print('</td><td title="'.$lt{'vu'}.'">');
                                           p_mdb => 'Title for the Drop Box',          # Set version
                                           p_mbb => 'Title for the Bulletin Board',          $r->print(&Apache::loncommon::select_form(
                                           p_mab => "Enter user:domain for User's 'About Me' Page",              $setversions{$linkurl},
                                           p_mab2 => "About [_99]",              'set_version_'.$linkurl,
                                           p_mab_alrt1 => 'Not a valid user:domain',              {'select_form_order' => ['',1..$currentversion,'mostrecent'],
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',               '' => '',
                                           p_chn => 'New Title',               'mostrecent' => &mt('most recent'),
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',               map {$_,$_} (1..$currentversion)}));
                                           p_rmr2a => 'Remove[_99]',          my $lastold=1;
                                           p_rmr2b => '?[_99]',          for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',              my $url=$root.'.'.$prevvers.'.'.$extension;
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',              if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
                                           p_ctr2a => 'Cut[_98]',                  $lastold=$prevvers;
                                           p_ctr2b => '?[_98]'              }
                                         );          }
           $r->print('</td>');
     return <<ENDNEWSCRIPT;          # List all available versions
 function makenewfolder(targetform,folderseq) {          $r->print('<td valign="top"><span class="LC_fontsize_medium">');
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');          for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
     if (foldername) {              my $url=$root.'.'.$prevvers.'.'.$extension;
        targetform.importdetail.value=escape(foldername)+"="+folderseq;              $r->print(
         targetform.submit();                  '<span class="LC_nobreak">'
     }                 .'<a href="'.&Apache::lonnet::clutter($url).'">'
 }                 .&mt('Version [_1]',$prevvers).'</a>'
                  .' ('.&Apache::lonlocal::locallocaltime(
 function makenewpage(targetform,folderseq) {                           &Apache::lonnet::metadata($url,'lastrevisiondate'))
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');                 .')');
     if (pagename) {              if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
         targetform.importdetail.value=escape(pagename)+"="+folderseq;                  $r->print(
         targetform.submit();                      ' <a href="/adm/diff?filename='.
     }                      &Apache::lonnet::clutter($root.'.'.$extension).
 }                      &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
                       '" target="diffs">'.&mt('Diffs').'</a>');
 function makenewext(targetname) {              }
     this.document.forms.extimport.useform.value=targetname;              $r->print('</span><br />');
     this.document.forms.extimport.title.value='';          }
     this.document.forms.extimport.url.value='';          $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
     this.document.forms.extimport.residx.value='';      }
     window.open('/adm/rat/extpickframe.html');      $r->print(
 }          &Apache::loncommon::end_data_table().
           '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
 function edittext(targetname,residx,title,url) {          '</form>'
     this.document.forms.extimport.useform.value=targetname;      );
     this.document.forms.extimport.residx.value=residx;  
     this.document.forms.extimport.url.value=url;      &untiehash();
     this.document.forms.extimport.title.value=title;      $r->print(&endContentScreen());
     window.open('/adm/rat/extpickframe.html');  }
 }  
   sub mark_hash_old {
 function makeexamupload() {      my $retie_hash=0;
    var title=prompt('$lt{"p_mxu"}');      if ($hashtied) {
    if (title) {   $retie_hash=1;
     this.document.forms.newexamupload.importdetail.value=   &untiehash();
  escape(title)+'=/res/lib/templates/examupload.problem';      }
     this.document.forms.newexamupload.submit();      &tiehash('write');
    }      $hash{'old'}=1;
 }      &untiehash();
       if ($retie_hash) { &tiehash(); }
 function makesmppage() {  }
    var title=prompt('$lt{"p_msp"}');  
    if (title) {  sub is_hash_old {
     this.document.forms.newsmppg.importdetail.value=      my $untie_hash=0;
  escape(title)+'=/adm/$udom/$uname/$now/smppg';      if (!$hashtied) {
     this.document.forms.newsmppg.submit();   $untie_hash=1;
    }   &tiehash();
 }      }
       my $return=$hash{'old'};
 function makesmpproblem() {      if ($untie_hash) { &untiehash(); }
    var title=prompt('$lt{"p_msb"}');      return $return;
    if (title) {  }
     this.document.forms.newsmpproblem.importdetail.value=  
  escape(title)+'=/res/lib/templates/simpleproblem.problem';  sub changewarning {
     this.document.forms.newsmpproblem.submit();      my ($r,$postexec,$message,$url)=@_;
    }      if (!&is_hash_old()) { return; }
 }      my $pathvar='folderpath';
       my $path=&escape($env{'form.folderpath'});
 function makedropbox() {      if (!defined($url)) {
    var title=prompt('$lt{"p_mdb"}');   $url='/adm/coursedocs?'.$pathvar.'='.$path;
    if (title) {      }
     this.document.forms.newdropbox.importdetail.value=      my $course_type = &Apache::loncommon::course_type();
         escape(title)+'=/res/lib/templates/DropBox.problem';      if (!defined($message)) {
     this.document.forms.newdropbox.submit();   $message='Changes will become active for your current session after [_1], or the next time you log in.';
    }      }
 }      $r->print("\n\n".
   '<script type="text/javascript">'."\n".
 function makebulboard() {  '// <![CDATA['."\n".
    var title=prompt('$lt{"p_mbb"}');  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
    if (title) {  '// ]]>'."\n".
     this.document.forms.newbul.importdetail.value=  '</script>'."\n".
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
     this.document.forms.newbul.submit();  '<input type="hidden" name="orgurl" value="'.$url.
    }  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 }  &mt($message,' <input type="hidden" name="'.
       $env{'request.role'}.'" value="1" /><input type="button" value="'.
 function makeabout() {      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
    var user=prompt("$lt{'p_mab'}");  $help{'Caching'}.'</p></form>'."\n\n");
    if (user) {  }
        var comp=new Array();  
        comp=user.split(':');  
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {  sub init_breadcrumbs {
    if ((comp[0]) && (comp[1])) {      my ($form,$text)=@_;
        this.document.forms.newaboutsomeone.importdetail.value=      &Apache::lonhtmlcommon::clear_breadcrumbs();
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
        this.document.forms.newaboutsomeone.submit();      text=>&Apache::loncommon::course_type().' Editor',
    } else {      faq=>273,
                alert("$lt{'p_mab_alrt1'}");      bug=>'Instructor Interface',
            }                                              help => 'Docs_Adding_Course_Doc'});
        } else {      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
            alert("$lt{'p_mab_alrt2'}");      text=>$text,
        }      faq=>273,
    }      bug=>'Instructor Interface'});
 }  }
   
 function makeims() {  # subroutine to list form elements
     var caller = document.forms.ims.folder.value;  sub create_list_elements {
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";     my @formarr = @_;
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");     my $list = '';
     newWindow.location.href = newlocation;     foreach my $button (@formarr){
 }          foreach my $picture (keys(%{$button})) {
               $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
           }
 function finishpick() {     }
     var title=this.document.forms.extimport.title.value;     return $list;
     var url=this.document.forms.extimport.url.value;  }
     var form=this.document.forms.extimport.useform.value;  
     var residx=this.document.forms.extimport.residx.value;  # subroutine to create ul from list elements
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');  sub create_form_ul {
 }     my $list = shift;
      my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
 function changename(folderpath,index,oldtitle,container,pagesymb) {     return $ul;
     var title=prompt('$lt{"p_chn"}',oldtitle);  }
     if (title) {  
  this.document.forms.renameform.markcopy.value=-1;  #
  this.document.forms.renameform.title.value=title;  # Start tabs
  this.document.forms.renameform.cmd.value='rename_'+index;  #
         if (container == 'sequence') {  
     this.document.forms.renameform.folderpath.value=folderpath;  sub startContentScreen {
         }      my ($mode) = @_;
         if (container == 'page') {      my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
             this.document.forms.renameform.pagepath.value=folderpath;      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
             this.document.forms.renameform.pagesymb.value=pagesymb;          $output .= '<li'.(($mode eq 'navmaps')?' class="active"':'').'><a href="/adm/navmaps"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Overview').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
         }          $output .= '<li'.(($mode eq 'coursesearch')?' class="active"':'').'><a href="/adm/searchcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Search').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
         this.document.forms.renameform.submit();          $output .= '<li'.(($mode eq 'courseindex')?' class="active"':'').'><a href="/adm/indexcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Index').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
     }          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/supplemental"><b>'.&mt('Supplemental Content').'</b></a></li>';
 }      } else {
           $output .= '<li '.(($mode eq 'docs')?' class="active"':'').' id="tabbededitor"><a href="/adm/coursedocs?forcestandard=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Editor').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {          $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {          $output .= '<li '.(($mode eq 'tools')?' class="active"':'').'><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n";
  this.document.forms.renameform.markcopy.value=-1;                     '><a href="/adm/coursedocs?tools=1"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Content Utilities').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>';
  this.document.forms.renameform.cmd.value='del_'+index;      }
         if (container == 'sequence') {      $output .= "\n".'</ul>'."\n";
             this.document.forms.renameform.folderpath.value=folderpath;      $output .= '<div class="LC_DocsBox" style="clear:both;margin:0;" id="contenteditor">'.
         }                 '<div id="maincoursedoc" style="margin:0 0;padding:0 0;">'.
         if (container == 'page') {                 '<div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">';
             this.document.forms.renameform.pagepath.value=folderpath;      return $output;
             this.document.forms.renameform.pagesymb.value=pagesymb;  }
         }  
         this.document.forms.renameform.submit();  #
     }  # End tabs
 }  #
   
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {  sub endContentScreen {
     if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {      return '</div></div></div>';
  this.document.forms.renameform.cmd.value='cut_'+index;  }
  this.document.forms.renameform.markcopy.value=index;  
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;  sub supplemental_base {
         if (container == 'sequence') {      return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
             this.document.forms.renameform.folderpath.value=folderpath;  }
         }  
         if (container == 'page') {  sub handler {
             this.document.forms.renameform.pagepath.value=folderpath;      my $r = shift;
             this.document.forms.renameform.pagesymb.value=pagesymb;      &Apache::loncommon::content_type($r,'text/html');
         }      $r->send_http_header;
         this.document.forms.renameform.submit();      return OK if $r->header_only;
     }  
 }  # get course data
       my $crstype = &Apache::loncommon::course_type();
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
     this.document.forms.renameform.markcopy.value=index;      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;  
     if (container == 'sequence') {  # graphics settings
  this.document.forms.renameform.folderpath.value=folderpath;      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
     }  
     if (container == 'page') {  #
  this.document.forms.renameform.pagepath.value=folderpath;  # --------------------------------------------- Initialize help topics for this
  this.document.forms.renameform.pagesymb.value=pagesymb;      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
     }                 'Adding_External_Resource','Navigate_Content',
     this.document.forms.renameform.submit();                 'Adding_Folders','Docs_Overview', 'Load_Map',
 }                 'Supplemental','Score_Upload_Form','Adding_Pages',
                  'Importing_LON-CAPA_Resource','Importing_IMS_Course',
                          'Uploading_From_Harddrive',
 ENDNEWSCRIPT                 'Check_Resource_Versions','Verify_Content') {
 }   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 1;      }
 __END__      # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 =head1 NAME      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 Apache::londocs.pm      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
 =head1 SYNOPSIS      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 This is part of the LearningOnline Network with CAPA project      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
 described at http://www.lon-capa.org.    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
       $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 =head1 SUBROUTINES      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
       $help{'Course Roster'} = &Apache::loncommon::help_open_topic('Docs_Course_Roster');
 =over      $help{'Web Page'} =  &Apache::loncommon::help_open_topic('Docs_Web_Page');
    
 =item %help=()      my $allowed;
   # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
 Available help topics      unless ($r->uri eq '/adm/supplemental') {
           # does this user have privileges to modify content.  
 =item mapread()          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
       }
 Mapread read maps into LONCAPA::map:: global arrays  
 @order and @resources, determines status      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
 sets @order - pointer to resources in right order                                              'inhibitmenu']);
 sets @resources - array with the resources with correct idx    if ($allowed && $env{'form.chooseserver'}) {
         &choose_dump_server($r);
 =item authorhosts()        return OK;
     } elsif ($allowed && $env{'form.verify'}) {
 Return hash with valid author names        &init_breadcrumbs('verify','Verify Content');
         &verifycontent($r);
 =item dumpbutton()    } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Content IDs');
 Generate "dump" button        &list_symbs($r);
     } elsif ($allowed && $env{'form.docslog'}) {
 =item clean()        &init_breadcrumbs('docslog','Show Log');
         my $folder = $env{'form.folder'};
 =item dumpcourse()        if ($folder eq '') {
             $folder='default';
     Actually dump course        }
         &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
     } elsif ($allowed && $env{'form.versions'}) {
 =item exportbutton()        &init_breadcrumbs('versions','Check/Set Resource Versions');
         &checkversions($r);
     Generate "export" button    } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
 =item exportcourse()        &dumpcourse($r);
     } elsif ($allowed && $env{'form.exportcourse'}) {
 =item create_ims_store()        &init_breadcrumbs('exportcourse','IMS Export');
         &Apache::imsexport::exportcourse($r);
 =item build_package()    } else {
   #
 =item get_dependencies()  # Done catching special calls
   # The whole rest is for course and supplemental documents and utilities menu
 =item process_content()  # Get the parameters that may be needed
   #
 =item replicate_content()      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                               ['folderpath',
 =item extract_media()                                               'forcesupplement','forcestandard',
                                                'tools','symb','command','supppath']);
 =item store_template()  
   # standard=1: this is a "new-style" course with an uploaded map as top level
 =item group_import()  # standard=2: this is a "old-style" course, and there is nothing we can do
   
     Imports the given (name, url) resources into the course      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
     coursenum, coursedom, and folder must precede the list  
   # Decide whether this should display supplemental or main content or utilities
 =item breadcrumbs()  # supplementalflag=1: show supplemental documents
   # supplementalflag=0: show standard documents
 =item log_docs()  # toolsflag=1: show utilities
   
 =item docs_change_log()  
       my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 =item update_paste_buffer()      if (($env{'form.folderpath'}=~/^default/) || ($env{'form.folderpath'} eq "")) {
          $supplementalflag=0;
 =item print_paste_buffer()      }
       if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 =item do_paste_from_buffer()      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
       unless ($allowed) { $supplementalflag=1; }
 =item update_parameter()      unless ($standard) { $supplementalflag=1; }
       my $toolsflag=0;
 =item handle_edit_cmd()      if ($env{'form.tools'}) { $toolsflag=1; }
   
 =item editor()      my $script='';
       my $showdoc=0;
 =item process_file_upload()      my $addentries = {};
       my $container;
 =item process_secondary_uploads()      my $containertag;
       my $pathitem;
 =item is_supplemental_title()  
   # Do we directly jump somewhere?
 =item parse_supplemental_title()  
      if (($env{'form.command'} eq 'direct') || ($env{'form.command'} eq 'directnav')) {
 =item entryline()         if ($env{'form.symb'} ne '') {
              $env{'form.folderpath'}=
 =item tiehash()                 &Apache::loncommon::symb_to_docspath($env{'form.symb'});
              &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
 =item untiehash()                 $env{'form.command'}.'_'.$env{'form.symb'}});
          } elsif ($env{'form.supppath'} ne '') {
 =item checkonthis()             $env{'form.folderpath'}=$env{'form.supppath'};
              &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
 check on this                 $env{'form.command'}.'_'.$env{'form.supppath'}});
          }
 =item verifycontent()     } elsif ($env{'form.command'} eq 'editdocs') {
          $env{'form.folderpath'} = 'default&'.
 Verify Content                                   &Apache::lonhtmlcommon::entity_encode('Main Course Content').
                                    ':::::';
 =item devalidateversioncache() & checkversions()         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
      } elsif ($env{'form.command'} eq 'editsupp') {
 Check Versions         $env{'form.folderpath'} = 'supplemental&'.
                                     &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
 =item mark_hash_old()         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
      } elsif ($env{'form.command'} eq 'contents') {
 =item is_hash_old()         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
      } elsif ($env{'form.command'} eq 'home') {
 =item changewarning()         &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
      }
 =item init_breadcrumbs()  
   
 Breadcrumbs for special functions  # Where do we store these for when we come back?
       my $stored_folderpath='docs_folderpath';
 =back      if ($supplementalflag) {
          $stored_folderpath='docs_sup_folderpath';
 =cut      }
   
   # No folderpath, and in edit mode, see if we have something stored
       if ((!$env{'form.folderpath'}) && $allowed) {
           &Apache::loncommon::restore_course_settings($stored_folderpath,
                                             {'folderpath' => 'scalar'});
           unless (&unescape($env{'form.folderpath'}) =~ m{^(default|supplemental)&}) {
               undef($env{'form.folderpath'});
           }
       }
      
   # If we are not allowed to make changes, all we can see are supplemental docs
       if (!$allowed) {
           unless ($env{'form.folderpath'} =~ /^supplemental/) {
               $env{'form.folderpath'} = &supplemental_base();
           }
       }
   # Make the zeroth entry in supplemental docs page paths, so we can get to top level
       if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = &supplemental_base()
                                     .'&'.
                                     $env{'form.folderpath'};
       }
   # If after all of this, we still don't have any paths, make them
       unless ($env{'form.folderpath'}) {
          if ($supplementalflag) {
             $env{'form.folderpath'}=&supplemental_base();
          } else {
             $env{'form.folderpath'}='default'.&escape(&mt('Main '.$crstype.' Documents')).
                                     ':::::';
          }
       }
   
   # Store this
       unless ($toolsflag) {
           if ($allowed) {
               &Apache::loncommon::store_course_settings($stored_folderpath,
                                                         {'folderpath' => 'scalar'});
           }
           my $folderpath;
           if ($env{'form.folderpath'}) {
               $folderpath = $env{'form.folderpath'};
       my (@folders)=split('&',$env{'form.folderpath'});
       $env{'form.foldername'}=&unescape(pop(@folders));
               if ($env{'form.foldername'} =~ /\:1$/) {
                   $container = 'page';
               } else {
                   $container = 'sequence';
               }
       $env{'form.folder'}=pop(@folders);
           } else {
               if ($env{'form.folder'} eq '' ||
                   $env{'form.folder'} eq 'supplemental') {
                   $folderpath='default&'.
                               &escape(&mt('Main '.$crstype.' Documents')).
                               ':::::';
               }
           }
           $containertag = '<input type="hidden" name="folderpath" value="" />';
           $pathitem = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
           if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
              $showdoc='/'.$1;
           }
           if ($showdoc) { # got called in sequence from course
       $allowed=0; 
           } else {
               if ($allowed) {
                   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                   $script=&Apache::lonratedt::editscript('simple');
               }
           }
       }
   
   # get personal data
       my $uname=$env{'user.name'};
       my $udom=$env{'user.domain'};
       my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
   
       if ($allowed) {
           if ($toolsflag) {
               $script .= &inject_data_js();
               my ($home,$other,%outhash)=&authorhosts();
               if (!$home && $other) {
                   my @hosts;
                   foreach my $aurole (keys(%outhash)) {
                       unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                           push(@hosts,$outhash{$aurole});
                       }
                   }
                   $script .= &dump_switchserver_js(@hosts); 
               }
           } else {
               my @tabids;
               if ($supplementalflag) {
                   @tabids = ('002','ee2','ff2');
               } else {
                   @tabids = ('aa1','bb1','cc1','ff1');
                   unless ($env{'form.folderpath'} =~ /\:1$/) {
                       unshift(@tabids,'001');
                       push(@tabids,('dd1','ee1'));
                   }
               }
               my $tabidstr = join("','",@tabids);
       $script .= &editing_js($udom,$uname,$supplementalflag).
                          &history_tab_js().
                          &inject_data_js().
                          &Apache::lonhtmlcommon::resize_scrollbox_js('docs',$tabidstr).
                          &Apache::lonextresedit::extedit_javascript();
               $addentries = {
                               onload   => "javascript:resize_scrollbox('contentscroll','1','1');",
                             };
           }
           if ($env{'docs.markedcopy_url'}) {
               $script .= &paste_popup_js(); 
           }
           my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
                                &mt('Switch server?');
           
   
       }
   # -------------------------------------------------------------------- Body tag
       $script = '<script type="text/javascript">'."\n"
                 .'// <![CDATA['."\n"
                 .$script."\n"
                 .'// ]]>'."\n"
                 .'</script>'."\n";
   
       # Breadcrumbs
       &Apache::lonhtmlcommon::clear_breadcrumbs();
   
       if ($showdoc) {
           $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
                                                   {'force_register' => $showdoc,}));
       } elsif ($r->uri eq '/adm/supplemental') {
           my $brcrum = &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype);
           $r->print(&Apache::loncommon::start_page("Supplemental $crstype Content",undef,
                                                   {'bread_crumbs' => $brcrum,}));
       } else {
           &Apache::lonhtmlcommon::add_breadcrumb({
               href=>"/adm/coursedocs",text=>"$crstype Contents"});
   
           $r->print(&Apache::loncommon::start_page("$crstype Contents", $script,
                                                    {'add_entries'    => $addentries}
                                                   )
                    .&Apache::loncommon::help_open_menu('','',273,'RAT')
                    .&Apache::lonhtmlcommon::breadcrumbs(
                        'Editing '.$crstype.' Contents',
                        'Docs_Adding_Course_Doc')
           );
       }
   
     my %allfiles = ();
     my %codebase = ();
     my ($upload_result,$upload_output,$uploadphase);
     if ($allowed) {
         if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
             my $context = $1; 
             # Process file upload - phase one - upload and parse primary file.
     undef($hadchanges);
             $uploadphase = &process_file_upload(\$upload_output,$coursenum,$coursedom,
                                                 \%allfiles,\%codebase,$context);
     if ($hadchanges) {
         &mark_hash_old();
     }
             $r->print($upload_output);
         } elsif ($env{'form.phase'} eq 'upload_embedded') {
             # Process file upload - phase two - upload embedded objects 
             $uploadphase = 'check_embedded';
             my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');   
             my $state = &embedded_form_elems($uploadphase,$primaryurl,
                                              $env{'form.newidx'});
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $url_root = '/uploaded/'.$docudom.'/'.$docuname;
             my $actionurl = '/adm/coursedocs';
             my ($result,$flag) = 
                 &Apache::loncommon::upload_embedded('coursedoc',$destination,
                     $docuname,$docudom,$dir_root,$url_root,undef,undef,undef,$state,
                     $actionurl);
             $r->print($result.&return_to_editor());
         } elsif ($env{'form.phase'} eq 'check_embedded') {
             # Process file upload - phase three - modify references in HTML file
             $uploadphase = 'modified_orightml';
             my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
             my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
             my ($destination,$dir_root) = &embedded_destination();
             my $result = 
                 &Apache::loncommon::modify_html_refs('coursedoc',$destination,
                                                      $docuname,$docudom,undef,
                                                      $dir_root);
             $r->print($result.&return_to_editor());   
         } elsif ($env{'form.phase'} eq 'decompress_uploaded') {
             $uploadphase = 'decompress_phase_one';
             $r->print(&decompression_phase_one().
                       &return_to_editor());
         } elsif ($env{'form.phase'} eq 'decompress_cleanup') {
             $uploadphase = 'decompress_phase_two';
             $r->print(&decompression_phase_two().
                       &return_to_editor());
         }
     }
   
     if ($allowed && $toolsflag) {
         $r->print(&startContentScreen('tools'));
         $r->print(&generate_admin_menu($crstype));
         $r->print(&endContentScreen());
     } elsif ((!$showdoc) && (!$uploadphase)) {
   # -----------------------------------------------------------------------------
          my %lt=&Apache::lonlocal::texthash(
    'copm' => 'All documents out of a published map into this folder',
                   'upfi' => 'Upload File',
                   'upld' => 'Import Content',
                   'srch' => 'Search',
                   'impo' => 'Import',
    'lnks' => 'Import from Stored Links',
                   'impm' => 'Import from Assembled Map',
                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'syll' => 'Syllabus',
                   'navc' => 'Table of Contents',
                   'sipa' => 'Simple Course Page',
                   'sipr' => 'Simple Problem',
                   'webp' => 'Blank Web Page (editable)', 
                   'drbx' => 'Drop Box',
                   'scuf' => 'External Scores (handgrade, upload, clicker)',
                   'bull' => 'Discussion Board',
                   'mypi' => 'My Personal Information Page',
                   'grpo' => 'Group Portfolio',
                   'rost' => 'Course Roster',
                   'abou' => 'Personal Information Page for a User',
                   'imsf' => 'IMS Import',
                   'imsl' => 'Import IMS package',
                   'cms'  => 'Origin of IMS package',
                   'se'   => 'Select',
                   'file' =>  'File',
                   'title' => 'Title',
                   'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file',
     );
   # -----------------------------------------------------------------------------
    my $fileupload=(<<FIUP);
    $lt{'file'}:<br />
    <input type="file" name="uploaddoc" size="40" />
   FIUP
   
    my $checkbox=(<<CHBO);
    <!-- <label>$lt{'parse'}?
    <input type="checkbox" name="parserflag" />
    </label> -->
    <label>
    <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
    </label>
   CHBO
           my $imsfolder = $env{'form.folder'};
           if ($imsfolder eq '') {
               $imsfolder = 'default';  
           }
           my $imspform=(<<IMSFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('ims');">
           $lt{'imsf'}</a> $help{'Importing_IMS_Course'}
           <form name="uploadims" action="/adm/imsimportdocs" method="post" enctype="multipart/form-data" target="IMSimport">
           <fieldset id="uploadimsform" style="display: none;">
           <legend>$lt{'imsf'}</legend>
           $fileupload
           <br />
           <p>
           $lt{'cms'}:&nbsp; 
           <select name="source">
           <option value="-1" selected="selected">$lt{'se'}</option>
           <option value="bb5">Blackboard 5</option>
           <option value="bb6">Blackboard 6</option>
           <option value="angel5">ANGEL 5.5</option>
           <option value="webctce4">WebCT 4 Campus Edition</option>
           </select>
           <input type="hidden" name="folder" value="$imsfolder" />
           </p>
           <input type="hidden" name="phase" value="one" />
           <input type="button" value="$lt{'imsl'}" onclick="makeims(this.form);" />
           </fieldset>
           </form>
   IMSFORM
   
    my $fileuploadform=(<<FUFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('doc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
           <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
           <fieldset id="uploaddocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="aa" />
    $fileupload
    <br />
    $lt{'title'}:<br />
    <input type="text" size="60" name="comment" />
    $pathitem
    <input type="hidden" name="cmd" value="upload_default" />
    <br />
    <span class="LC_nobreak" style="float:left">
    $checkbox
    </span>
           <br clear="all" />
           <input type="submit" value="$lt{'upld'}" />
           </fieldset>
           </form>
   FUFORM
   
    my $importpubform=(<<SEDFFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleMap('map');">
           $lt{'impm'}</a>$help{'Load_Map'}
    <form action="/adm/coursedocs" method="post" name="mapimportform">
           <fieldset id="importmapform" style="display: none;">
           <legend>$lt{'impm'}</legend>
    <input type="hidden" name="active" value="bb" />
           $lt{'copm'}<br />
           <span class="LC_nobreak">
           <input type="text" name="importmap" size="40" value="" 
           onfocus="this.blur();openbrowser('mapimportform','importmap','sequence,page','');" />
           &nbsp;<a href="javascript:openbrowser('mapimportform','importmap','sequence,page','');">$lt{'selm'}</a></span><br />
           <input type="submit" name="loadmap" value="$lt{'load'}" />
           </fieldset>
           </form>
   
   SEDFFORM
    my @importpubforma = (
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/src.png" alt="'.$lt{srch}.'"  onclick="javascript:groupsearch()" />' => $pathitem."<a class='LC_menubuttons_link' href='javascript:groupsearch()'>$lt{'srch'}</a>" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/res.png" alt="'.$lt{impo}.'"  onclick="javascript:groupimport();"/>' => "<a class='LC_menubuttons_link' href='javascript:groupimport();'>$lt{'impo'}</a>$help{'Importing_LON-CAPA_Resource'}" },
    { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/wishlist.png" alt="'.$lt{lnks}.'" onclick="javascript:open_StoredLinks_Import();" />' => "<a class='LC_menubuttons_link' href='javascript:open_StoredLinks_Import();'>$lt{'lnks'}</a>" },
           { '<img class="LC_noBorder LC_middle" src="/res/adm/pages/sequence.png" alt="'.$lt{impm}.'" onclick="javascript:toggleMap(\'map\');" />' => $importpubform }
    );
    $importpubform = &create_form_ul(&create_list_elements(@importpubforma));
           my $extresourcesform =
               &Apache::lonextresedit::extedit_form(0,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
       if ($allowed) {
           my $folder = $env{'form.folder'};
           if ($folder eq '') {
               $folder='default';
           }
    &update_paste_buffer($coursenum,$coursedom,$folder);
    $r->print(<<HIDDENFORM);
    <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
      <input type="hidden" name="cmd" />
      <input type="hidden" name="markcopy" />
      <input type="hidden" name="copyfolder" />
      $containertag
    </form>
   
   HIDDENFORM
           $r->print(&makesimpleeditform($pathitem)."\n".
                     &makedocslogform($pathitem."\n".
                                      '<input type="hidden" name="folder" value="'.
                                      $env{'form.folder'}.'" />'."\n"));
       }
   
   # Generate the tabs
       my ($mode,$needs_end);
       if (($supplementalflag) && (!$allowed)) {
           my @folders = split('&',$env{'form.folderpath'});
           unless (@folders > 2) {
               &Apache::lonnavdisplay::startContentScreen($r,'supplemental');
               $needs_end = 1;
           }
       } else {
           $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
           $needs_end = 1;
       }
   
   #
   
       my $savefolderpath;
   
       if ($allowed) {
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $supplementalflag) {
              $folder='default';
      $savefolderpath = $env{'form.folderpath'};
      $env{'form.folderpath'}='default&'.&escape(&mt('Content'));
              $pathitem = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
              $r->print('<script type="text/javascript">'."\n"
                       .'// <![CDATA['."\n"
                       .'this.window.name="loncapaclient";'."\n"
                       .'// ]]>'."\n"
                       .'</script>'."\n"
          );
          } else {
              #$postexec='self.close();';
          }
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_new.page';
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'navc'}=/adm/navmaps" />
    <a class="LC_menubuttons_link" href="javascript:document.newnav.submit()">$lt{'navc'}</a>
    $help{'Navigate_Content'}
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmppage();"> $lt{'sipa'}</a>
    $help{'Simple Page'}
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makesmpproblem();">$lt{'sipr'}</a>
    $help{'Simple Problem'}
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makedropbox();">$lt{'drbx'}</a>
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeexamupload();">$lt{'scuf'}</a>
    $help{'Score_Upload_Form'}
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makebulboard();" >$lt{'bull'}</a>
    $help{'Bulletin Board'}
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makeabout();">$lt{'abou'}</a>
    </form>
   NASOFORM
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'rost'}=/adm/viewclasslist" />
    <a class="LC_menubuttons_link" href="javascript:document.newroster.submit()">$lt{'rost'}</a>
    $help{'Course Roster'}
    </form>
   NROSTFORM
   
           my $newwebpage;
           if ($folder =~ /^default_?(\d*)$/) {
               $newwebpage = "/uploaded/$coursedom/$coursenum/docs/";
               if ($1) {
                   $newwebpage .= $1;
               } else {
                   $newwebpage .= 'default';
               }
               $newwebpage .= '/new.html';
           }
           my $newwebpageform =(<<NWEBFORM);
           <form action="/adm/coursedocs" method="post" name="newwebpage">
           <input type="hidden" name="active" value="cc" />
           $pathitem
           <input type="hidden" name="importdetail" value="$newwebpage" />
           <a class="LC_menubuttons_link" href="javascript:makewebpage();">$lt{'webp'}</a>
           $help{'Web Page'}
           </form>
   NWEBFORM
    
   
   my $specialdocumentsform;
   my @specialdocumentsforma;
   my $gradingform;
   my @gradingforma;
   my $communityform;
   my @communityforma;
   my $newfolderform;
   my $newfolderb;
   
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $newpageform=(<<NPFORM);
    <form action="/adm/coursedocs" method="post" name="newpage">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="cc" />
    <a class="LC_menubuttons_link" href="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
    $help{'Adding_Pages'}
    </form>
   NPFORM
   
   
    $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    $pathitem
    <input type="hidden" name="importdetail" value="" />
    <input type="hidden" name="active" value="aa" />
    <a href="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail" 
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.newsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
   
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    <input type="hidden" name="active" value="cc" />
    $pathitem
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.newgroupfiles.submit()">$lt{'grpo'}</a>
    $help{'Group Portfolio'}
    </form>
   NGFFORM
    @specialdocumentsforma=(
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,\''.$pageseq.'\');" />'=>$newpageform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage();" />'=>$newwebpageform},
           );
           $specialdocumentsform = &create_form_ul(&create_list_elements(@specialdocumentsforma));
   
   
           my @importdoc = (
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="toggleUpload(\'ext\');" />'=>$extresourcesform}
           );
           unless ($container eq 'page') {
               push(@importdoc,
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:toggleUpload(\'ims\');" />'=>$imspform}
               );
           }
           push(@importdoc,
               {'<img class="LC_noBorder_LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'doc\');" />'=>$fileuploadform}
           );
           $fileuploadform =  &create_form_ul(&create_list_elements(@importdoc));
   
           @gradingforma=(
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
   
           );
           $gradingform = &create_form_ul(&create_list_elements(@gradingforma));
   
           @communityforma=(
          {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/clst.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},
           {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
           );
           $communityform = &create_form_ul(&create_list_elements(@communityforma));
   
   my %orderhash = (
                   'aa' => ['Import Content',$fileuploadform],
                   'bb' => ['Published Content',$importpubform],
                   'cc' => ['Grading Resources',$gradingform],
                   );
   unless ($container eq 'page') {
       $orderhash{'00'} = ['Newfolder',$newfolderform];
       $orderhash{'dd'} = ['Collaboration',$communityform];
       $orderhash{'ee'} = ['Special Pages',$specialdocumentsform];
   }
   
    $hadchanges=0;
          unless (($supplementalflag || $toolsflag)) {
             my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                 $supplementalflag,\%orderhash,$iconpath,$pathitem);
             if ($error) {
                $r->print('<p><span class="LC_error">'.$error.'</span></p>');
             }
             if ($hadchanges) {
                &mark_hash_old();
             }
   
             &changewarning($r,'');
           }
       }
   
   # Supplemental documents start here
   
          my $folder=$env{'form.folder'};
          unless ($supplementalflag) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = &supplemental_base();
          } elsif ($allowed) {
     $env{'form.folderpath'} = $savefolderpath;
          }
          $pathitem = '<input type="hidden" name="folderpath" value="'.
                       &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_new.sequence';
   
    my $supupdocform=(<<SUPDOCFORM);
           <a class="LC_menubuttons_link" href="javascript:toggleUpload('suppdoc');">
           $lt{'upfi'}</a> $help{'Uploading_From_Harddrive'}
    <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
           <fieldset id="uploadsuppdocform" style="display: none;">
           <legend>$lt{'upfi'}</legend>
    <input type="hidden" name="active" value="ee" />
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols="50" rows="4" name="comment"></textarea>
    <br />
    $pathitem
    <input type="hidden" name="cmd" value="upload_supplemental" />
           <input type='submit' value="$lt{'upld'}" />
           </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="active" value="ee" />
           $pathitem
    <input type="hidden" name="importdetail" value="" />
    <a class="LC_menubuttons_link" href="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
    $help{'Adding_Folders'}
    </form>
   SNFFORM
   
           my $supextform =
               &Apache::lonextresedit::extedit_form(1,0,undef,undef,$pathitem,
                                                    $help{'Adding_External_Resource'});
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <input type="hidden" name="importdetail" 
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewsyl.submit()">$lt{'syll'}</a>
    $help{'Syllabus'}
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="supnewaboutme">
    <input type="hidden" name="active" value="ff" />
           $pathitem
    <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <a class="LC_menubuttons_link" href="javascript:document.supnewaboutme.submit()">$lt{'mypi'}</a>
    $help{'My Personal Information Page'}
    </form>
   SNAMFORM
   
           my $supwebpage;
           if ($folder =~ /^supplemental_?(\d*)$/) {
               $supwebpage = "/uploaded/$coursedom/$coursenum/supplemental/";
               if ($1) {
                   $supwebpage .= $1;
               } else {
                   $supwebpage .= 'default';
               }
               $supwebpage .= '/new.html';
           }
           my $supwebpageform =(<<SWEBFORM);
           <form action="/adm/coursedocs" method="post" name="supwebpage">
           <input type="hidden" name="active" value="cc" />
           $pathitem
           <input type="hidden" name="importdetail" value="$supwebpage" />
           <a class="LC_menubuttons_link" href="javascript:makewebpage('supp');">$lt{'webp'}</a>
           $help{'Web Page'}
           </form>
   SWEBFORM
   
   
   my @specialdocs = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.supnewsyl.submit()" />'
               =>$supnewsylform},
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
               =>$supnewaboutmeform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/webpage.png" alt="'.$lt{webp}.'" onclick="javascript:makewebpage('."'supp'".');" />'=>$supwebpageform},
   
    );
   my @supimportdoc = (
    {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:toggleUpload(\'suppext\')" />'
               =>$supextform},
                   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/pdfupload.png" alt="'.$lt{upl}.'" onclick="javascript:toggleUpload(\'suppdoc\');" />'
               =>$supupdocform},
                      );
   
   $supupdocform =  &create_form_ul(&create_list_elements(@supimportdoc));
   my %suporderhash = (
    '00' => ['Supnewfolder', $supnewfolderform],
                   'ee' => ['Import Content',$supupdocform],
                   'ff' => ['Special Pages',&create_form_ul(&create_list_elements(@specialdocs))]
                   );
           if ($supplementalflag) {
              my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                                  $supplementalflag,\%suporderhash,$iconpath,$pathitem);
              if ($error) {
                 $r->print('<p><span class="LC_error">'.$error.'</span></p>');
              }
           }
       } elsif ($supplementalflag) {
           my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype,
                               $supplementalflag,'',$iconpath,$pathitem);
           if ($error) {
               $r->print('<p><span class="LC_error">'.$error.'</span></p>');
           }
       }
   
       if ($needs_end) {
           $r->print(&endContentScreen());
       }
   
       if ($allowed) {
    $r->print('
   <form method="post" name="extimport" action="/adm/coursedocs">
     <input type="hidden" name="title" />
     <input type="hidden" name="url" />
     <input type="hidden" name="useform" />
     <input type="hidden" name="residx" />
   </form>');
       }
     } elsif ($showdoc) {
   # -------------------------------------------------------- This is showdoc mode
         $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p class="LC_warning">'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
                   &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
     }
    }
    $r->print(&Apache::loncommon::end_page());
    return OK;
   }
   
   sub embedded_form_elems {
       my ($phase,$primaryurl,$newidx) = @_;
       my $folderpath = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
       return <<STATE;
       <input type="hidden" name="folderpath" value="$folderpath" />
       <input type="hidden" name="cmd" value="upload_embedded" />
       <input type="hidden" name="newidx" value="$newidx" />
       <input type="hidden" name="phase" value="$phase" />
       <input type="hidden" name="primaryurl" value="$primaryurl" />
   STATE
   }
   
   sub embedded_destination {
       my $folder=$env{'form.folder'};
       my $destination = 'docs/';
       if ($folder =~ /^supplemental/) {
           $destination = 'supplemental/';
       }
       if (($folder eq 'default') || ($folder eq 'supplemental')) {
           $destination .= 'default/';
       } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
           $destination .=  $2.'/';
       }
       $destination .= $env{'form.newidx'};
       my $dir_root = '/userfiles';
       return ($destination,$dir_root);
   }
   
   sub return_to_editor {
       my $actionurl = '/adm/coursedocs';
       return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'."\n". 
              '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" /></form>'."\n".
              '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
              '</a></p>';
   }
   
   sub decompression_info {
       my ($destination,$dir_root) = &embedded_destination();
       my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
       my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
       my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $container='sequence';
       my ($pathitem,$hiddenelem);
       my @hiddens = ('newidx','comment','position','folderpath');
       if ($env{'form.folderpath'} =~ /\:1$/) {
           $container='page';
       }
       unshift(@hiddens,$pathitem);
       foreach my $item (@hiddens) {
           if ($env{'form.'.$item}) {
               $hiddenelem .= '<input type="hidden" name="'.$item.'" value="'.
                              $env{'form.'.$item}.'" />'."\n";
           }
       }
       return ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,
               $hiddenelem);
   }
   
   sub decompression_phase_one {
       my ($dir,$file,$warning,$error,$output);
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       if ($env{'form.archiveurl'} !~ m{^/uploaded/\Q$docudom/$docuname/\E(?:docs|supplemental)/(?:default|\d+).*/([^/]+)$}) {
           $error = &mt('Archive file "[_1]" not in the expected location.',$env{'form.archiveurl'});
       } else {
           my $file = $1;
           $output = 
               &Apache::loncommon::process_decompression($docudom,$docuname,$file,
                                                         $destination,$dir_root,
                                                         $hiddenelem);
           if ($env{'form.autoextract_camtasia'}) {
               $output .= &remove_archive($docudom,$docuname,$container);
           }
       }
       if ($error) {
           $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                      $error.'</p>'."\n";
       }
       if ($warning) {
           $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
       }
       return $output;
   }
   
   sub decompression_phase_two {
       my ($destination,$dir_root,$londocroot,$docudom,$docuname,$container,$hiddenelem)=
           &decompression_info();
       my $output;
       if ($env{'form.archivedelete'}) {
           $output = &remove_archive($docudom,$docuname,$container);
       }
       $output .= 
           &Apache::loncommon::process_extracted_files('coursedocs',$docudom,$docuname,
                                                       $destination,$dir_root,$hiddenelem);
       return $output;
   }
   
   sub remove_archive {
       my ($docudom,$docuname,$container) = @_;
       my $map = $env{'form.folder'}.'.'.$container;
       my ($output,$delwarning,$delresult,$url);
       my ($errtext,$fatal) = &mapread($docuname,$docudom,$map);
       if ($fatal) {
           if ($container eq 'page') {
               $delwarning = &mt('An error occurred retrieving the contents of the current page.');
           } else {
               $delwarning = &mt('An error occurred retrieving the contents of the current folder.');
           }
           $delwarning .= &mt('As a result the archive file has not been removed.');
       } else {
           my $currcmd = $env{'form.cmd'};
           my $position = $env{'form.position'};
           if ($position > 0) { 
               $env{'form.cmd'} = 'del_'.$position;
               my ($title,$url,@rrest) = 
                   split(/:/,$LONCAPA::map::resources[$LONCAPA::map::order[$position]]);
               if (&handle_edit_cmd($docuname,$docudom)) {
                   ($errtext,$fatal) = &storemap($docuname,$docudom,$map,1);
                   if ($fatal) {
                       if ($container eq 'page') {
                           $delwarning = &mt('An error occurred updating the contents of the current page.');
                       } else {
                           $delwarning = &mt('An error occurred updating the contents of the current folder.');
                       }
                   } else {
                       $delresult = &mt('Archive file removed.');
                   }
               }
           }
           $env{'form.cmd'} = $currcmd;
       }
       if ($delwarning) {
           $output = '<p class="LC_warning">'.
                      $delwarning.
                      '</p>';
       }
       if ($delresult) {
           $output .= '<p class="LC_info">'.
                      $delresult.
                      '</p>';
       }
       return $output;
   }
   
   sub generate_admin_menu {
       my ($crstype) = @_;
       my $lc_crstype = lc($crstype);
       my ($home,$other,%outhash)=&authorhosts();
       my %lt=&Apache::lonlocal::texthash (
                                            'vc'   => 'Verify Content',
                                            'cv'   => 'Check/Set Resource Versions',
                                            'ls'   => 'List Resource Identifiers',
                                            'imse' => 'Export contents to IMS Archive',
                                            'dcd'  => "Dump $crstype Content to Authoring Space",
                                          );
       my ($candump,$dumpurl);
       if ($home + $other > 0) {
           $candump = 'F';
           if ($home) {
               $dumpurl = "javascript:injectData(document.courseverify,'dummy','dumpcourse','$lt{'dcd'}')";
           } else {
               my @hosts;
               foreach my $aurole (keys(%outhash)) {
                   unless(grep(/^\Q$outhash{$aurole}\E/,@hosts)) {
                       push(@hosts,$outhash{$aurole});
                   }  
               }
               if (@hosts == 1) {
                   my $switchto = '/adm/switchserver?otherserver='.$hosts[0].
                                  '&amp;role='.
                                  &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;origurl='.
                                  &HTML::Entities::encode('/adm/coursedocs?dumpcourse=1','"<>&');
                   $dumpurl = "javascript:dump_needs_switchserver('$switchto')";
               } else {
                   $dumpurl = "javascript:choose_switchserver_window()";
               }
           }
       }
       my @menu=
           ({  categorytitle=>'Administration',
               items =>[
                   {   linktext   => $lt{'vc'},
                       url        => "javascript:injectData(document.courseverify,'dummy','verify','$lt{'vc'}')",
                       permission => 'F',
                       help       => 'Verify_Content',
                       icon       => 'verify.png',
                       linktitle  => 'Verify contents can be retrieved/rendered',
                   },
                   {   linktext => $lt{'cv'},
                       url => "javascript:injectData(document.courseverify,'dummy','versions','$lt{'cv'}')",
                       permission => 'F',
                       help       => 'Check_Resource_Versions',
                       icon       => 'resversion.png',
                       linktitle  => "View version information for resources in your $lc_crstype, and fix/unfix use of specific versions",
                   },
                   {   linktext   => $lt{'ls'},
                       url        => "javascript:injectData(document.courseverify,'dummy','listsymbs','$lt{'ls'}')",
                       permission => 'F',
                       #help => '',
                       icon       => 'symbs.png',
                       linktitle  => "List the unique identifier used for each resource instance in your $lc_crstype"
                   },
                   ]
           },
           {   categorytitle=>'Export',
               items =>[
                   {   linktext   => $lt{'imse'},
                       url => "javascript:injectData(document.courseverify,'dummy','exportcourse','$lt{'imse'}')",
                       permission => 'F',
                       help       => 'Docs_Export_Course_Docs',
                       icon       => 'imsexport.png',
                       linktitle  => $lt{'imse'},
                   },
                   {   linktext   => $lt{'dcd'},
                       url        => $dumpurl,
                       permission => $candump,
                       #help => '',
                       icon       => 'dump.png',
                       linktitle  => $lt{'dcd'},
                   },
                   ]
           });
       return '<form action="/adm/coursedocs" method="post" name="courseverify">'."\n".
              '<input type="hidden" id="dummy" />'."\n".
              &Apache::lonhtmlcommon::generate_menu(@menu)."\n".
              '</form>';
   }
   
   sub generate_edit_table {
       my ($tid,$orderhash_ref,$to_show,$iconpath,$jumpto,$readfile) = @_;
       return unless(ref($orderhash_ref) eq 'HASH');
       my %orderhash = %{$orderhash_ref};
       my $form;
       my $activetab;
       my $active;
       if (($env{'form.active'} ne '') && ($env{'form.active'} ne 'aa')) {
           $activetab = $env{'form.active'};
       }
       my $backicon = $iconpath.'clickhere.gif';
       my $backtext = &mt('Exit Editor');
       $form = '<div class="LC_Box" style="margin:0;">'.
               '<ul id="navigation'.$tid.'" class="LC_TabContent">'."\n".
               '<li class="goback">'.
               '<a href="javascript:toContents('.$jumpto.');">'.
               '<img src="'.$backicon.'" class="LC_icon" style="border: none; vertical-align: top;"'.
               '  alt="'.$backtext.'" />'.$backtext.'</a></li>'."\n".
               '<li>'.
               '<a href="javascript:groupopen('."'$readfile'".',1);">'.
               &mt('Undo Delete').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li class="active">';
       } else {
           $form .= '<li>';
       }
       $form .= '<a href="javascript:toggleHistoryDisp(1);">'.
                &mt('History').'</a></li>'."\n";
       if ($env{'form.docslog'}) {
           $form .= '<li><a href="javascript:toggleHistoryDisp(0);">'.
                    &mt('Edit').'</a></li>'."\n";
       }
       foreach my $name (reverse(sort(keys(%orderhash)))) {
           if($name ne '00'){
               if($activetab eq '' || $activetab ne $name){
                  $active = '';
               }elsif($activetab eq $name){
                  $active = 'class="active"';
               }
               $form .= '<li style="float:right" '.$active
                   .' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');"><a href="javascript:;"><b>'.&mt(${$orderhash{$name}}[0]).'</b></a></li>'."\n";
           } else {
       $form .= '<li '.$active.' style="float:right">'.${$orderhash{$name}}[1].'</li>'."\n";
   
    }
       }
       $form .= '</ul>'."\n";
       $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; overflow: hidden; clear:right">'."\n";
   
       if ($to_show ne '') {
           $form .= '<div style="padding:0;margin:0;float:left">'.$to_show.'</div>'."\n";
       }
       foreach my $field (keys(%orderhash)){
    if($field ne '00'){
               if($activetab eq '' || $activetab ne $field){
                   $active = 'style="display: none;float:left"';
               }elsif($activetab eq $field){
                   $active = 'style="display:block;float:left"';
               }
               $form .= '<div id="'.$field.$tid.'"'
                       .' class="LC_ContentBox" '.$active.'>'.${$orderhash{$field}}[1]
                       .'</div>'."\n";
           }
       }
       unless ($env{'form.docslog'}) {
           $form .= '</div></div>'."\n";
       }
       return $form;
   }
   
   sub editing_js {
       my ($udom,$uname,$supplementalflag) = @_;
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
                                             p_mxu => 'Title for the External Score',
                                             p_msp => 'Name of Simple Course Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Discussion Board',
                                             p_mwp => 'Title for Web Page', 
                                             p_mab => "Enter user:domain for User's Personal Information Page",
                                             p_mab2 => 'Personal Information Page of ',
                                             p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                             p_chn => 'New Title',
                                             p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
                                             p_rmr2a => 'Remove[_99]',
                                             p_rmr2b => '?[_99]',
                                             p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
                                             p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                             p_ctr2a => 'Cut[_98]',
                                             p_ctr2b => '?[_98]',
                                             rpck    => 'Enter number to pick (e.g., 3)',
                                             imsfile => 'You must choose an IMS package for import',
                                             imscms  => 'You must select which Course Management System was the source of the IMS package',
                                             invurl  => 'Invalid URL',
                                             titbl   => 'Title is blank',
                                           );
   
       my $crstype = &Apache::loncommon::course_type();
       my $docs_folderpath = &HTML::Entities::encode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'},'<>&"');
       my $main_container_page;
       if (&HTML::Entities::decode($env{'environment.internal.'.$env{'request.course.id'}.'.docs_folderpath.folderpath'}) =~ /\:1$/) {
           $main_container_page = 1;
       }
       my $toplevelmain = 'default&Main%20'.$crstype.'%20Documents%3A%3A%3A%3A%3A';
       my $toplevelsupp = &supplemental_base();
   
       my $backtourl;
       if ($env{'docs.exit.'.$env{'request.course.id'}} =~ /^direct_(.+)$/) {
           my $caller = $1;
           if ($caller =~ /^supplemental/) {
               $backtourl = '/adm/supplemental?folderpath='.&escape($caller);
           } else {
               my ($map,$id,$res)=&Apache::lonnet::decode_symb($caller);
               $res = &Apache::lonnet::clutter($res);
               if (&Apache::lonnet::is_on_map($res)) {
                   $backtourl = &HTML::Entities::encode(&Apache::lonnet::clutter($res),'<>&"').'?symb='.
                                &HTML::Entities::encode($caller,'<>&"');
               }
           }
       } elsif ($env{'docs.exit.'.$env{'request.course.id'}} eq '/adm/menu') {
           $backtourl = '/adm/menu';
       } elsif ($supplementalflag) {
           $backtourl = '/adm/supplemental';
       } else {
           $backtourl = '/adm/navmaps';
       }
   
       my $fieldsets = "'ext','doc'";
       unless ($main_container_page) {
           $fieldsets .=",'ims'";
       }
       if ($supplementalflag) {
           $fieldsets = "'suppext','suppdoc'";
       }
   
       return <<ENDNEWSCRIPT;
   function makenewfolder(targetform,folderseq) {
       var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
       if (foldername) {
          targetform.importdetail.value=escape(foldername)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makenewpage(targetform,folderseq) {
       var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
           targetform.importdetail.value=escape(pagename)+"="+folderseq;
           targetform.submit();
       }
   }
   
   function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
      if (title) {
       this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
      }
   }
   
   function makesmppage() {
      var title=prompt('$lt{"p_msp"}');
      if (title) {
       this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/new/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makewebpage(type) {
      var title=prompt('$lt{"p_mwp"}');
      var formname;
      if (type == 'supp') {
          formname = this.document.forms.supwebpage;
      } else {
          formname = this.document.forms.newwebpage;
      }
      if (title) {
          var webpage = formname.importdetail.value; 
          formname.importdetail.value = escape(title)+'='+webpage;
          formname.submit();
      }
   }
   
   function makesmpproblem() {
      var title=prompt('$lt{"p_msb"}');
      if (title) {
       this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
       this.document.forms.newsmpproblem.submit();
      }
   }
   
   function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
      if (title) {
       this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
      }
   }
   
   function makebulboard() {
      var title=prompt('$lt{"p_mbb"}');
      if (title) {
       this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/new/bulletinboard';
       this.document.forms.newbul.submit();
      }
   }
   
   function makeabout() {
      var user=prompt("$lt{'p_mab'}");
      if (user) {
          var comp=new Array();
          comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
      if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
      } else {
          alert("$lt{'p_mab_alrt1'}");
      }
   } else {
      alert("$lt{'p_mab_alrt2'}");
   }
   }
   }
   
   function toggleUpload(caller) {
       var blocks = Array($fieldsets);
       for (var i=0; i<blocks.length; i++) {
           var disp = 'none';
           if (caller == blocks[i]) {
               var curr = document.getElementById('upload'+caller+'form').style.display;
               if (curr == 'none') {
                   disp='block';
               }
           }
           document.getElementById('upload'+blocks[i]+'form').style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   function toggleMap(caller) {
       var disp = 'none';
       if (document.getElementById('importmapform')) {
           if (caller == 'map') {
               var curr = document.getElementById('importmapform').style.display;
               if (curr == 'none') {
                   disp='block';
               }
           }
           document.getElementById('importmapform').style.display=disp;
           resize_scrollbox('contentscroll','1','1');
       }
       return;
   }
   
   function makeims(imsform) {
       if ((imsform.uploaddoc.value == '')  || (!imsform.uploaddoc.value)) {
           alert("$lt{'imsfile'}");
           return;
       }
       if (imsform.source.selectedIndex == 0) {
           alert("$lt{'imscms'}");
           return;
       }
       newWindow = window.open('', 'IMSimport',"HEIGHT=700,WIDTH=750,scrollbars=yes");
       imsform.submit();
   }
   
   function changename(folderpath,index,oldtitle) {
   var title=prompt('$lt{"p_chn"}',oldtitle);
   if (title) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.title.value=title;
   this.document.forms.renameform.cmd.value='rename_'+index;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function removeres(folderpath,index,oldtitle,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.cmd.value='del_'+index;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function cutres(folderpath,index,oldtitle,container,folder,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
   this.document.forms.renameform.cmd.value='cut_'+index;
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   }
   
   function markcopy(folderpath,index,oldtitle,container,folder) {
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   this.document.forms.renameform.folderpath.value=folderpath;
   this.document.forms.renameform.submit();
   }
   
   function updatePick(targetform,index,caller) {
       var pickitem;
       var picknumitem;
       var picknumtext;
       if (index == 'all') {
           pickitem = document.getElementById('randompickall');
           picknumitem = document.getElementById('rpicknumall');
           picknumtext = document.getElementById('rpicktextall');
       } else {
           pickitem = document.getElementById('randompick_'+index);
           picknumitem = document.getElementById('rpicknum_'+index);
           picknumtext = document.getElementById('randompicknum_'+index);
       }
       if (pickitem.checked) {
           var picknum=prompt('$lt{"rpck"}',picknumitem.value);
           if (picknum == '' || picknum == null) {
               if (caller == 'check') {
                   pickitem.checked=false;
                   if (index == 'all') {
                       picknumtext.innerHTML = '';
                       if (caller == 'link') {
                           propagateState(targetform,'rpicknum');
                       }
                   } else {
                       checkForSubmit(targetform,'randompick');
                   }
               }
           } else {
               picknum.toString();
               var regexdigit=/^\\d+\$/;
               if (regexdigit.test(picknum)) {
                   picknumitem.value = picknum;
                   if (index == 'all') {
                       picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.cumulativechecks,\\'all\\',\\'link\\');">'+picknum+'</a>';
                       if (caller == 'link') {
                           propagateState(targetform,'rpicknum');
                       }
                   } else {
                       picknumtext.innerHTML = '&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+index+',\\''+index+'\\',\\'link\\');">'+picknum+'</a>';
                       checkForSubmit(targetform,'randompick');
                   }
               } else {
                   if (caller == 'check') {
                       if (index == 'all') {
                           picknumtext.innerHTML = '';
                           if (caller == 'link') {
                               propagateState(targetform,'rpicknum');
                           }
                       } else {
                           pickitem.checked=false;
                           checkForSubmit(targetform,'randompick');
                       }
                   }
                   return;
               }
           }
       } else {
           picknumitem.value = '';
           picknumtext.innerHTML = '';
           if (index == 'all') {
               if (caller == 'link') {
                   propagateState(targetform,'rpicknum');
               }
           } else {
               checkForSubmit(targetform,'randompick');
           }
       }
   }
   
   function propagateState(form,param) {
       if (document.getElementById(param+'all')) {
           var setcheck = 0;
           var rpick = 0;
           if (param == 'rpicknum') {
               if (document.getElementById('randompickall')) {
                   if (document.getElementById('randompickall').checked) {
                       if (document.getElementById('rpicknumall')) {
                           rpick = document.getElementById('rpicknumall').value;
                       }
                   }
               }
           } else {
               if (document.getElementById(param+'all').checked) {
                   setcheck = 1;
               }
           }
           if ((param == 'encrypturl') || (param == 'hiddenresource')) {
               var allidxlist = form.allidx.value;
               if (allidxlist != '') {
                   var allidxs = allidxlist.split(',');
                   if (allidxs.length > 1) {
                       for (var i=0; i<allidxs.length; i++) {
                           if (document.getElementById(param+'_'+allidxs[i])) {
                               if (setcheck == 1) {
                                   document.getElementById(param+'_'+allidxs[i]).checked = true;
                               } else {
                                   document.getElementById(param+'_'+allidxs[i]).checked = false;
                               }
                           }
                       }
                   }
               }
           } else {
               var allmapidxlist = form.allmapidx.value;
               if (allmapidxlist != '') {
                   var allmapidxs = allmapidxlist.split(',');
                   if (allmapidxs.length > 1) {
                       for (var i=0; i<allmapidxs.length; i++) {
                           var item = param+'_'+allmapidxs[i];
                           if (document.getElementById(item)) {
                               if (param == 'rpicknum') {
                                   if (document.getElementById('randompick_'+allmapidxs[i])) {
                                       if (document.getElementById('randompick_'+allmapidxs[i]).checked) {
                                           document.getElementById(param+'_'+allmapidxs[i]).value = rpick;
                                           if (rpick > 0) {
                                               document.getElementById('randompicknum_'+allmapidxs[i]).innerHTML = ':&nbsp;<a href="javascript:updatePick(document.edit_randompick_'+allmapidxs[i]+',\\''+allmapidxs[i]+'\\',\\'link\\')">'+rpick+'</a>';
                                           } else {
                                               document.getElementById('randompicknum_'+allmapidxs[i]).innerHTML =  '';
                                           }
                                       }
                                   }
                               } else {
                                   if (setcheck == 1) {
                                       document.getElementById(param+'_'+allmapidxs[i]).checked = true;
                                   } else {
                                       document.getElementById(param+'_'+allmapidxs[i]).checked = false;
                                   }
                               }
                           }
                       }
                   }
               }
           }
       }
       return;
   }
   
   function checkForSubmit(targetform,param) {
       if (document.togglemultchecks.showmultpick.length) {
           for (var i=0; i<document.togglemultchecks.showmultpick.length; i++) {
               if (document.togglemultchecks.showmultpick[i].checked) {
                   if (document.togglemultchecks.showmultpick[i].value == 0) {
                       targetform.changeparms.value=param;
                       targetform.submit();
                   }
               }
           }
       }
       return;
   }
   
   function unselectInactive(nav) {
   currentNav = document.getElementById(nav);
   currentLis = currentNav.getElementsByTagName('LI');
   for (i = 0; i < currentLis.length; i++) {
           if (currentLis[i].className == 'goback') {
               currentLis[i].className = 'goback';
           } else {
       if (currentLis[i].className == 'right active' || currentLis[i].className == 'right') {
    currentLis[i].className = 'right';
       } else {
    currentLis[i].className = 'i';
       }
           }
   }
   }
   
   function hideAll(current, nav, data) {
   unselectInactive(nav);
   if(current.className == 'right'){
    current.className = 'right active'
    }else{
    current.className = 'active';
   }
   currentData = document.getElementById(data);
   currentDivs = currentData.getElementsByTagName('DIV');
   for (i = 0; i < currentDivs.length; i++) {
    if(currentDivs[i].className == 'LC_ContentBox'){
    currentDivs[i].style.display = 'none';
    }
   }
   }
   
   function openTabs(pageId) {
    tabnav = document.getElementById(pageId).getElementsByTagName('UL');
    if(tabnav.length > 2 ){
    currentNav = document.getElementById(tabnav[1].id);
    currentLis = currentNav.getElementsByTagName('LI');
    for(i = 0; i< currentLis.length; i++){
    if(currentLis[i].className == 'active') {
    funcString = currentLis[i].onclick.toString();
    tab = funcString.split('"');
                                   if(tab.length < 2) {
                                      tab = funcString.split("'");
                                   }
    currentData = document.getElementById(tab[1]);
           currentData.style.display = 'block';
    }
    }
    }
   }
   
   function showPage(current, pageId, nav, data) {
    hideAll(current, nav, data);
    openTabs(pageId);
    unselectInactive(nav);
    current.className = 'active';
    currentData = document.getElementById(pageId);
    currentData.style.display = 'block';
           activeTab = pageId;
           toggleUpload();
           toggleMap();
           if (nav == 'mainnav') {
               var storedpath = "$docs_folderpath";
               var storedpage = "$main_container_page";
               var reg = new RegExp("^supplemental");
               if (pageId == 'mainCourseDocuments') {
                   if (storedpage == 1) {
                       document.simpleedit.folderpath.value = '';
                       document.uploaddocument.folderpath.value = '';
                   } else {
                       if (reg.test(storedpath)) {
                           document.simpleedit.folderpath.value = '$toplevelmain';
                           document.uploaddocument.folderpath.value = '$toplevelmain';
                           document.newext.folderpath.value = '$toplevelmain';
                       } else {
                           document.simpleedit.folderpath.value = storedpath;
                           document.uploaddocument.folderpath.value = storedpath;
                           document.newext.folderpath.value = storedpath;
                       }
                   }
               } else {
                   if (reg.test(storedpath)) {
                       document.simpleedit.folderpath.value = storedpath;
                       document.supuploaddocument.folderpath.value = storedpath;
                       document.supnewext.folderpath.value = storedpath;
                   } else {
                       document.simpleedit.folderpath.value = '$toplevelsupp';
                       document.supuploaddocument.folderpath.value = '$toplevelsupp';
                       document.supnewext.folderpath.value = '$toplevelsupp';
                   }
               }
           }
           resize_scrollbox('contentscroll','1','0');
    return false;
   }
   
   function toContents(jumpto) {
       var newurl = '$backtourl';
       if ((newurl == '/adm/navmaps') && (jumpto != '')) {
           newurl = newurl+'?postdata='+jumpto;
       }
       location.href=newurl;
   }
   
   function submitSettings(form) {
       var allidxlist = form.allidx.value;
       form.allencrypturl.value = '';
       form.allhiddenresource.value = '';
       if (allidxlist != '') {
           var allidxs = allidxlist.split(',');
           if (allidxs.length > 1) {
               for (var i=0; i<allidxs.length; i++) {
                   if (document.getElementById('hiddenresource_'+allidxs[i])) {
                       if (document.getElementById('hiddenresource_'+allidxs[i]).checked) {
                           form.allhiddenresource.value += allidxs[i]+',';
                       }
                   }
                   if (document.getElementById('encrypturl_'+allidxs[i])) {
                       if (document.getElementById('encrypturl_'+allidxs[i]).checked) {
                           form.allencrypturl.value += allidxs[i]+',';
                       }
                   }
               }
           }
       }
       var allmapidxlist = form.allmapidx.value;
       form.allrandompick.value = '';
       form.allrandomorder.value = '';
       if (allmapidxlist != '') {
           var allmapidxs = allmapidxlist.split(',');
           for (var i=0; i<allmapidxs.length; i++) {
               var randompick = document.getElementById('randompick_'+allmapidxs[i]);
               var rpicknum = document.getElementById('rpicknum_'+allmapidxs[i]);
               var randorder = document.getElementById('randomorder_'+allmapidxs[i]);
               if ((randompick.checked) && (rpicknum.value != '')) {
                   form.allrandompick.value += allmapidxs[i]+':'+rpicknum.value+',';
               }
               if (randorder.checked) {
                   form.allrandomorder.value += allmapidxs[i]+',';
               }
           }
       }
       form.submit();
       return true;
   }
   
   function togglePick() {
       var disp = 'none';
       if (document.getElementById('multiclick')) {
           var curr = document.getElementById('multiclick').style.display;
           if (curr == 'none') {
               disp='block';
           }
           document.getElementById('multiclick').style.display=disp;
       }
       if (document.getElementById('savemulti')) {
           var curr = document.getElementById('save.multi').style.display;
           if (curr == 'none') {
               disp='inline';
           }
           document.getElementById('savemulti').style.display=disp;
       }
       resize_scrollbox('contentscroll','1','1');
       return;
   }
   
   ENDNEWSCRIPT
   }
   
   sub history_tab_js {
       return <<"ENDHIST";
   function toggleHistoryDisp(choice) {
       document.docslogform.docslog.value = choice;
       document.docslogform.submit();
       return;
   }
   
   ENDHIST
   }
   
   sub inject_data_js {
       return <<ENDINJECT;
   
   function injectData(current, hiddenField, name, value) {
           currentElement = document.getElementById(hiddenField);
           currentElement.name = name;
           currentElement.value = value;
           current.submit();
   }
   
   ENDINJECT
   }
   
   sub dump_switchserver_js {
       my @hosts = @_;
       my %lt = &Apache::lonlocal::texthash(
           dump => 'Dumping to Authoring Space requires switching server.',
           swit => 'Switch server?',
           duco => 'Dump content to Authoring Space',
           yone => 'You need to switch to a server housing an Authoring Space for which you are author or co-author.',
           chos => 'Choose server',
       );
       my $role = $env{'request.role'};
       my $js = <<"ENDSWJS";
   <script type="text/javascript">
   function write_switchserver() {
       var server;
       if (document.setserver.posshosts.length > 0) {
           for (var i=0; i<document.setserver.posshosts.length; i++) {
               if (document.setserver.posshosts[i].checked) {
                   server = document.setserver.posshosts[i].value;
               }
          }
          opener.document.location.href="/adm/switchserver?otherserver="+server+"&role=$role&origurl=/adm/coursedocs";
       }
       window.close();
   }
   </script>
   
   ENDSWJS
   
       my $startpage = &Apache::loncommon::start_page('Choose server',$js,
                                                      {'only_body' => 1,
                                                       'js_ready'  => 1,});
       my $endpage = &Apache::loncommon::end_page({'js_ready'  => 1});
   
       my $hostpicker;
       my $count = 0;
       foreach my $host (sort(@hosts)) {
           my $checked;
           if ($count == 0) {
               $checked = ' checked="checked"';
           }
           $hostpicker .= '<label><input type="radio" name="posshosts" value="'.
                          $host.'"'.$checked.' />'.$host.'</label>&nbsp;&nbsp;';
           $count++;
       }
       
       return <<"ENDSWITCHJS";
   
   function dump_needs_switchserver(url) {
       if (url!='' && url!= null) {
           if (confirm("$lt{'dump'}\\n$lt{'swit'}")) {
               go(url);
           }
       }
       return;
   }
   
   function choose_switchserver_window() {
       newWindow = window.open('','ChooseServer','height=400,width=500,scrollbars=yes')
       newWindow.document.open();
       newWindow.document.writeln('$startpage');
       newWindow.document.write('<h3>$lt{'duco'}<\\/h3>\\n'+
          '<p>$lt{'yone'}<\\/p>\\n'+
          '<div class="LC_left_float"><fieldset><legend>$lt{'chos'}<\\/legend>\\n'+
          '<form name="setserver" method="post" action="" \\/>\\n'+
          '$hostpicker\\n'+
          '<br \\/><br \\/>\\n'+
          '<input type="button" name="makeswitch" value="$lt{'swit'}" '+
          'onclick="write_switchserver();" \\/>\\n'+
          '<\\/form><\\/fieldset><\\/div><br clear="all" \\/>\\n');
       newWindow.document.writeln('$endpage');
       newWindow.document.close();
       newWindow.focus();
   }
   
   ENDSWITCHJS
   }
   
   sub makedocslogform {
       my ($formelems,$docslog) = @_;
       return <<"LOGSFORM";
    <form action="/adm/coursedocs" method="post" name="docslogform">
      <input type="hidden" name="docslog" value="$docslog" />
      $formelems
    </form>
   LOGSFORM
   }
   
   sub makesimpleeditform {
       my ($formelems) = @_;
       return <<"SIMPFORM";
    <form name="simpleedit" method="post" action="/adm/coursedocs">
      <input type="hidden" name="importdetail" value="" />
      $formelems
    </form>
   SIMPFORM
   }
   
   1;
   __END__
   
   
   =head1 NAME
   
   Apache::londocs.pm
   
   =head1 SYNOPSIS
   
   This is part of the LearningOnline Network with CAPA project
   described at http://www.lon-capa.org.
   
   =head1 SUBROUTINES
   
   =over
   
   =item %help=()
   
   Available help topics
   
   =item mapread()
   
   Mapread read maps into LONCAPA::map:: global arrays
   @order and @resources, determines status
   sets @order - pointer to resources in right order
   sets @resources - array with the resources with correct idx
   
   =item authorhosts()
   
   Return hash with valid author names
   
   =item clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   =item group_import()
   
       Imports the given (name, url) resources into the course
       coursenum, coursedom, and folder must precede the list
   
   =item breadcrumbs()
   
   =item log_docs()
   
   =item docs_change_log()
   
   =item update_paste_buffer()
   
   =item print_paste_buffer()
   
   =item do_paste_from_buffer()
   
   =item get_newmap_url()
   
   =item dbcopy()
   
   =item uniqueness_check()
   
   =item contained_map_check()
   
   =item url_paste_fixups()
   
   =item apply_fixups()
   
   =item copy_dependencies()
   
   =item update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_supplemental_title()
   
   =item entryline()
   
   =item tiehash()
   
   =item untiehash()
   
   =item checkonthis()
   
   check on this
   
   =item verifycontent()
   
   Verify Content
   
   =item devalidateversioncache() & checkversions()
   
   Check Versions
   
   =item mark_hash_old()
   
   =item is_hash_old()
   
   =item changewarning()
   
   =item init_breadcrumbs()
   
   Breadcrumbs for special functions
   
   =item create_list_elements()
   
   =item create_form_ul()
   
   =item startContentScreen() 
   
   =item endContentScreen()
   
   =item supplemental_base()
   
   =item embedded_form_elems()
   
   =item embedded_destination()
   
   =item return_to_editor()
   
   =item decompression_info()
   
   =item decompression_phase_one()
   
   =item decompression_phase_two()
   
   =item remove_archive()
   
   =item generate_admin_menu()
   
   =item generate_edit_table()
   
   =item editing_js()
   
   =item history_tab_js()
   
   =item inject_data_js()
   
   =item dump_switchserver_js()
   
   =item resize_scrollbox_js()
   
   =item makedocslogform()
   
   =item makesimpleeditform()
   
   =back
   
   =cut

Removed from v.1.327  
changed lines
  Added in v.1.537


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>