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

version 1.326, 2009/01/28 11:51:22 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 '<div>'.   }
     '<input type="submit" name="dumpcourse" value="'.      }
     &mt('Dump '.$type.' DOCS to Construction Space').'" />'.      return ($home,$other,%outhash);
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs').  }
     '</div>';  
     } else {  
  return '<div>'.  sub clean {
      &mt('Dump '.$type.      my ($title)=@_;
  ' DOCS to Construction Space: available on other servers').      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
  '</div>';      return $title;
     }  }
 }  
   
 sub clean {  
     my ($title)=@_;  sub dumpcourse {
     $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;      my ($r) = @_;
     return $title;      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");
       $r->print(&startContentScreen('tools'));
       my ($home,$other,%outhash)=&authorhosts();
 sub dumpcourse {      unless ($home) {
     my ($r) = @_;          $r->print(&endContentScreen());
     my $type = &Apache::loncommon::course_type();          return '';
     $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').      }
       '<form name="dumpdoc" method="post">');      my $origcrsid=$env{'request.course.id'};
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
     my ($home,$other,%outhash)=&authorhosts();      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     unless ($home) { return ''; }  # Do the dumping
     my $origcrsid=$env{'request.course.id'};   unless ($outhash{'home_'.$env{'form.authorspace'}}) {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);              $r->print(&endContentScreen());
     if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {              return '';
 # Do the dumping          }
  unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }   my ($ca,$cd)=split(/\:/,$env{'form.authorspace'});
  my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  $r->print('<h3>'.&mt('Copying Files').'</h3>');   my $title=$env{'form.authorfolder'};
  my $title=$env{'form.authorfolder'};   $title=&clean($title);
  $title=&clean($title);   my %replacehash=();
  my %replacehash=();   foreach my $key (keys(%env)) {
  foreach my $key (keys(%env)) {      if ($key=~/^form\.namefor\_(.+)/) {
     if ($key=~/^form\.namefor\_(.+)/) {   $replacehash{$1}=$env{$key};
  $replacehash{$1}=$env{$key};      }
     }   }
  }   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
  my $crs='/uploaded/'.$env{'request.course.id'}.'/';   $crs=~s/\_/\//g;
  $crs=~s/\_/\//g;   foreach my $item (keys(%replacehash)) {
  foreach my $item (keys(%replacehash)) {      my $newfilename=$title.'/'.$replacehash{$item};
     my $newfilename=$title.'/'.$replacehash{$item};      $newfilename=~s/\.(\w+)$//;
     $newfilename=~s/\.(\w+)$//;      my $ext=$1;
     my $ext=$1;      $newfilename=&clean($newfilename);
     $newfilename=&clean($newfilename);      $newfilename.='.'.$ext;
     $newfilename.='.'.$ext;      my @dirs=split(/\//,$newfilename);
     my @dirs=split(/\//,$newfilename);      my $path=$r->dir_config('lonDocRoot')."/priv/$cd/$ca";
     my $path='/home/'.$ca.'/public_html';      my $makepath=$path;
     my $makepath=$path;      my $fail=0;
     my $fail=0;      for (my $i=0;$i<$#dirs;$i++) {
     for (my $i=0;$i<$#dirs;$i++) {   $makepath.='/'.$dirs[$i];
  $makepath.='/'.$dirs[$i];   unless (-e $makepath) {
  unless (-e $makepath) {      unless(mkdir($makepath,0777)) { $fail=1; }
     unless(mkdir($makepath,0777)) { $fail=1; }   }
  }      }
     }      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
  if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      print $fh &Apache::lonclonecourse::rewritefile(
     print $fh &Apache::lonclonecourse::rewritefile(           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),       (%replacehash,$crs => '')
      (%replacehash,$crs => '')      );
     );   } else {
  } else {      print $fh
     print $fh           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
          &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);         }
        }   $fh->close();
  $fh->close();      } else {
     } else {   $fail=1;
  $fail=1;      }
     }      if ($fail) {
     if ($fail) {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
  $r->print('<span class="LC_error">'.&mt('fail').'</span>');      } else {
     } else {   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
  $r->print('<span class="LC_success">'.&mt('ok').'</span>');      }
     }   }
  }      } else {
     } else {          $r->print(&mt('Searching ...').'<br />');
 # Input form          $r->rflush();
  unless ($home==1) {  # Input form
     $r->print(          $r->print('<form name="dumpdoc" action="" method="post">'."\n");
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');   unless ($home==1) {
  }      $r->print('<div class="LC_left_float">'.
  foreach my $key (sort(keys(%outhash))) {        '<fieldset><legend>'.
     if ($key=~/^home_(.+)$/) {                        &mt('Select the Authoring Space').
  if ($home==1) {                        '</legend><select name="authorspace">');
     $r->print(   }
   '<input type="hidden" name="authorspace" value="'.$1.'" />');   foreach my $key (sort(keys(%outhash))) {
  } else {      if ($key=~/^home_(.+)$/) {
     $r->print('<option value="'.$1.'">'.$1.' - '.   if ($home==1) {
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');      $r->print(
  }    '<input type="hidden" name="authorspace" value="'.$1.'" />');
     }   } else {
  }      $r->print('<option value="'.$1.'">'.$1.' - '.
  unless ($home==1) {        &Apache::loncommon::plainname(split(/\:/,$1)).'</option>');
     $r->print('</select>');   }
  }      }
  my $title=$origcrsdata{'description'};   }
  $title=~s/[\/\s]+/\_/gs;   unless ($home==1) {
  $title=&clean($title);      $r->print('</select></fieldset></div>'."\n");
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'   }
                  .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');   my $title=$origcrsdata{'description'};
  &tiehash();   $title=~s/[\/\s]+/\_/gs;
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'   $title=&clean($title);
                  .&Apache::loncommon::start_data_table()   $r->print('<div class="LC_left_float">'.
                  .&Apache::loncommon::start_data_table_header_row()                    '<fieldset><legend>'.&mt('Folder in Authoring Space').'</legend>'.
                  .'<th>'.&mt('Internal Filename').'</th>'                    '<input type="text" size="50" name="authorfolder" value="'.
                  .'<th>'.&mt('Title').'</th>'                    $title.'" />'.
                  .'<th>'.&mt('Save as ...').'</th>'                    '</fieldset></div><br clear="all" />'."\n");
                  .&Apache::loncommon::end_data_table_header_row());   &tiehash();
  foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {   $r->print('<h4>'.&mt('Filenames in Authoring Space').'</h4>'
     $r->print(&Apache::loncommon::start_data_table_row()                   .&Apache::loncommon::start_data_table()
                      .'<td>'.$file.'</td>');                   .&Apache::loncommon::start_data_table_header_row()
     my ($ext)=($file=~/\.(\w+)$/);                   .'<th>'.&mt('Internal Filename').'</th>'
     my $title=$hash{'title_'.$hash{                   .'<th>'.&mt('Title').'</th>'
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};                   .'<th>'.&mt('Save as ...').'</th>'
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');                   .&Apache::loncommon::end_data_table_header_row());
     if (!$title) {   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
  $title=$file;      $r->print(&Apache::loncommon::start_data_table_row()
     } else {                       .'<td>'.$file.'</td>');
  $title=~s|/|_|g;      my ($ext)=($file=~/\.(\w+)$/);
     }      my $title=$hash{'title_'.$hash{
     $title=~s/\.(\w+)$//;   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     $title=&clean($title);      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
     $title.='.'.$ext;      if (!$title) {
     $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"   $title=$file;
                      .&Apache::loncommon::end_data_table_row());      } else {
  }   $title=~s|/|_|g;
  $r->print(&Apache::loncommon::end_data_table());      }
  &untiehash();      $title=~s/\.(\w+)$//;
  $r->print(      $title=&clean($title);
   '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');      $title.='.'.$ext;
     }      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
 }                       .&Apache::loncommon::end_data_table_row());
    }
    $r->print(&Apache::loncommon::end_data_table());
    &untiehash();
 sub exportbutton {   $r->print(
     my $type = &Apache::loncommon::course_type();    '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $crstype Content").'" /></p></form>');
     return '<div>'.      }
             '<input type="submit" name="exportcourse" value="'.      $r->print(&endContentScreen());
             &mt('Export '.$type.' to IMS').'" />'.  }
     &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'</div>';  
 }  sub group_import {
       my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
       my ($donechk,$allmaps,%hierarchy,%titles,%addedmaps,%removefrommap,
           %removeparam,$importuploaded,$fixuperrors);
 sub exportcourse {      $allmaps = {};
     my $r=shift;      while (@files) {
     my $type = &Apache::loncommon::course_type();   my ($name, $url, $residx) = @{ shift(@files) };
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                                                $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});       && ($caller eq 'londocs')
     my $numdisc = keys(%discussiontime);       && (!&Apache::lonnet::stat_file($url))) {
     my $navmap = Apache::lonnavmaps::navmap->new();  
     if (!defined($navmap)) {              my $errtext = '';
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').              my $fatal = 0;
                   '<h2>IMS Export Failed</h2>'.              my $newmapstr = '<map>'."\n".
                   '<div class="LC_error">'.                              '<resource id="1" src="" type="start"></resource>'."\n".
                   &mt('Unable to retrieve information about course contents').                              '<link from="1" to="2" index="1"></link>'."\n".
                   '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');                              '<resource id="2" src="" type="finish"></resource>'."\n".
         &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                              '</map>';
         return;              $env{'form.output'}=$newmapstr;
     }              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);                                                  'output',$1.$2);
     my $curRes;              if ($result !~ m{^/uploaded/}) {
     my $outcome;                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
                   $fatal = 2;
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['finishexport']);              if ($fatal) {
     if ($env{'form.finishexport'}) {                  return ($errtext,$fatal);
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},              }
                                             ['archive','discussion']);          }
    if ($url) {
         my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');              if (($caller eq 'londocs') &&
         my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');                  ($folder =~ /^default/)) {
         if (@exportitems == 0 && @discussions == 0) {                  if (($url =~ /\.(page|sequence)$/) && (!$donechk)) {
             $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';                      my $chome = &Apache::lonnet::homeserver($coursenum,$coursedom);
         } else {                      my $cid = $coursedom.'_'.$coursenum;
             my $now = time;                      $allmaps =
             my %symbs;                          &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
             my $manifestok = 0;                                                               $chome,$cid);
             my $imsresources;                      $donechk = 1;
             my $tempexport;                  }
             my $copyresult;                  if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) {
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);                      &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
             if ($manifestok) {                                           \%addedmaps,\%hierarchy,\%titles,$allmaps);
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);                      $importuploaded = 1;
                 close($ims_manifest);                  } elsif ($url =~ m{^/res/.+\.(page|sequence)$}) {
                       next if ($allmaps->{$url});
 #Create zip file in prtspool                  }
                 my $imszipfile = '/prtspool/'.              }
                 $env{'user.name'}.'_'.$env{'user.domain'}.'_'.      if (!$residx
                    time.'_'.rand(1000000000).'.zip';   || defined($LONCAPA::map::zombies[$residx])) {
                 my $cwd = &Cwd::getcwd();   $residx = &LONCAPA::map::getresidx($url,$residx);
                 my $imszip = '/home/httpd/'.$imszipfile;   push(@LONCAPA::map::order, $residx);
                 chdir $tempexport;      }
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");      my $ext = 'false';
                 close(OUTPUT);      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
                 chdir $cwd;      $url  = &LONCAPA::map::qtunescape($url);
                 $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);      $name = &LONCAPA::map::qtunescape($name);
                 if ($copyresult) {              if ($name eq '') {
                     $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);                  $name = &mt('Web Page');
                 }              }
             } else {              if ($url =~ m{^/uploaded/$coursedom/$coursenum/((?:docs|supplemental)/(?:default|\d+))/new\.html$}) {
                 $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 />';                  my $filepath = $1;
             }                  my $fname = $name;
         }                  if ($fname =~ /^\W+$/) {
         $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));                      $fname = 'web';
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));                  } else {
         $r->print($outcome);                      $fname =~ s/\W/_/g;
         $r->print(&Apache::loncommon::end_page());                  }
     } else {                  if (length($fname > 15)) {
         my $display;                      $fname = substr($fname,0,14);
         $display = '<form name="exportdoc" method="post">'."\n";                  }
         $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');                  my $initialtext = &mt('Replace with your own content.');
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  my $newhtml = <<END;
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                     '<input type="button" value="check all" '.  <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.  <head>
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.  <title>$name</title>
                     '<td>&nbsp;</td><td>&nbsp;</td>'.  </head>
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.  <body bgcolor="#ffffff">
                     '</b></legend><input type="button" value="check all"'.  $initialtext
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.  </body>
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.  </html>
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.  END
                     '</tr></table>';                  $env{'form.output'}=$newhtml;
         my $curRes;                  my $result = 
         my $depth = 0;                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
         my $count = 0;                                                            'output',
         my $boards = 0;                                                            "$filepath/$residx/$fname.html");
         my $startcount = 5;                  if ($result =~ m{^/uploaded/}) {
         my %parent = ();                      $url = $result;
         my %children = ();                      if ($filepath =~ /^supplemental/) {
         my $lastcontainer = $startcount;                          $name = time.'___&&&___'.$env{'user.name'}.'___&&&___'.
         my @bgcolors = ('#F6F6F6','#FFFFFF');                                  $env{'user.domain'}.'___&&&___'.$name;
         $display .= '<table cellspacing="0"><tr>'.                      }
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                  } else {
         if ($numdisc > 0) {                      return (&mt('Failed to save new web page.'),1);
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                  }
         }              }
         $display.='&nbsp;</td></tr>';      $LONCAPA::map::resources[$residx] =
         while ($curRes = $it->next()) {   join(':', ($name, $url, $ext, 'normal', 'res'));
             if (ref($curRes)) {   }
                 $count ++;      }
             }      if ($importuploaded) {
             if ($curRes == $it->BEGIN_MAP()) {          my %import_errors;
                 $depth++;          my %updated = (
                 $parent{$depth} = $lastcontainer;                            removefrommap => \%removefrommap,
             }                            removeparam   => \%removeparam,
             if ($curRes == $it->END_MAP()) {                        );
                 $depth--;          my ($result,$msgsarray,$lockerror) = 
                 $lastcontainer = $parent{$depth};              &apply_fixups($folder,1,$coursedom,$coursenum,\%import_errors,\%updated);
             }          if (keys(%import_errors) > 0) {
             if (ref($curRes)) {              $fixuperrors =
                 my $symb = $curRes->symb();                  '<p span class="LC_warning">'."\n".
                 my $ressymb = $symb;                  &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".
                 if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {                  '<ul>'."\n";
                     unless ($ressymb =~ m|adm/wrapper/adm|) {              foreach my $key (sort(keys(%import_errors))) {
                         $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';                  $fixuperrors .= '<li>'.$key.'</li>'."\n";
                     }              }
                 }              $fixuperrors .= '</ul></p>'."\n";
                 my $color = $count%2;          }
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".          if (ref($msgsarray) eq 'ARRAY') {
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              if (@{$msgsarray} > 0) {
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {                  $fixuperrors .= '<p class="LC_info">'.
                     my $checkitem = $count + $boards + $startcount;                                  join('<br />',@{$msgsarray}).
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';                                  '</p>';
                 }              }
                 $display .= ' />'."\n";          }
                 for (my $i=0; $i<$depth; $i++) {          if ($lockerror) {
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" /><img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" />'."\n";              $fixuperrors .= '<p class="LC_error">'.
                 }                              $lockerror.
                 if ($curRes->is_sequence()) {                              '</p>';
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";          }
                     $lastcontainer = $count + $startcount + $boards;      }
                 } elsif ($curRes->is_page()) {      my ($errtext,$fatal) =
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";          &storemap($coursenum, $coursedom, $folder.'.'.$container,1);
                     $lastcontainer = $count + $startcount + $boards;      return ($errtext,$fatal,$fixuperrors);
                 }  }
                 my $currelem = $count+$boards+$startcount;  
                 $children{$parent{$depth}} .= $currelem.':';  sub log_docs {
                 $display .= '&nbsp;'.$curRes->title().'</td>';      return &Apache::lonnet::write_log('course','docslog',@_);
                 if ($discussiontime{$ressymb} > 0) {  }
                     $boards ++;  
                     $currelem = $count+$boards+$startcount;  {
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";      my @oldresources=();
                 } else {      my @oldorder=();
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";      my $parmidx;
                 }      my %parmaction=();
             }      my %parmvalue=();
         }      my $changedflag;
         my $scripttag = qq|  
 <script>      sub snapshotbefore {
           @oldresources=@LONCAPA::map::resources;
 function checkAll(field) {          @oldorder=@LONCAPA::map::order;
     if (field.length > 0) {          $parmidx=undef;
         for (i = 0; i < field.length; i++) {          %parmaction=();
             field[i].checked = true ;          %parmvalue=();
         }          $changedflag=0;
     } else {      }
         field.checked = true  
     }      sub remember_parms {
 }          my ($idx,$parameter,$action,$value)=@_;
                                                                                          $parmidx=$idx;
 function uncheckAll(field) {          $parmaction{$parameter}=$action;
     if (field.length > 0) {          $parmvalue{$parameter}=$value;
         for (i = 0; i < field.length; i++) {          $changedflag=1;
             field[i].checked = false ;      }
         }  
     } else {      sub log_differences {
         field.checked = false ;          my ($plain)=@_;
     }          my %storehash=('folder' => $plain,
 }                         'currentfolder' => $env{'form.folder'});
           if ($parmidx) {
 function propagateCheck(item) {             $storehash{'parameter_res'}=$oldresources[$parmidx];
     if (document.exportdoc.elements[item].checked == true) {             foreach my $parm (keys(%parmaction)) {
         containerCheck(item)                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
     }                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
 }             }
           }
 function containerCheck(item) {          my $maxidx=$#oldresources;
     document.exportdoc.elements[item].checked = true          if ($#LONCAPA::map::resources>$#oldresources) {
     var numitems = $count + $boards + $startcount             $maxidx=$#LONCAPA::map::resources;
     var parents = new Array(numitems)          }
     for (var i=$startcount; i<numitems; i++) {          for (my $idx=0; $idx<=$maxidx; $idx++) {
         parents[i] = new Array             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
     }                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
         |;                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
                 $changedflag=1;
         foreach my $container (sort { $a <=> $b } (keys(%children))) {             }
             my @contents = split(/:/,$children{$container});             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
             for (my $i=0; $i<@contents; $i ++) {                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
             }                $changedflag=1;
         }             }
           }
         $scripttag .= qq|   $storehash{'maxidx'}=$maxidx;
     if (parents[item].length > 0) {          if ($changedflag) { &log_docs(\%storehash); }
         for (var j=0; j<parents[item].length; j++) {      }
             containerCheck(parents[item][j])  }
         }  
      }    sub docs_change_log {
 }      my ($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath)=@_;
       my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 </script>      my $js = '<script type="text/javascript">'."\n".
         |;               '// <![CDATA['."\n".
  $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',               &Apache::loncommon::display_filter_js('docslog')."\n".
  $scripttag));               &editing_js($env{'user.domain'},$env{'user.name'},$supplementalflag)."\n".
  $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));               &history_tab_js()."\n".
  $r->print($display.'</table>'.               &Apache::lonratedt::editscript('simple')."\n".
                   '<p><input type="hidden" name="finishexport" value="1">'.               '// ]]>'."\n".
                   '<input type="submit" name="exportcourse" value="'.               '</script>'."\n";
                   &mt('Export '.$type.' DOCS').'" /></p></form>');      $r->print(&Apache::loncommon::start_page('Content Change Log',$js));
     }      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Change Log'));
 }      $r->print(&startContentScreen(($supplementalflag?'suppdocs':'docs')));
       my %orderhash;
 sub create_ims_store {      my $container='sequence';
     my ($now,$manifestok,$outcome,$tempexport) = @_;      my $pathitem;
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';      if ($env{'form.folderpath'} =~ /\:1$/) {
     my $ims_manifest;          $container='page';
     if (!-e $$tempexport) {      }
         mkdir($$tempexport,0700);      my $folderpath=$env{'form.folderpath'};
     }      if ($folderpath eq '') {
     $$tempexport .= '/'.$now;          $folderpath = 'default&'.&escape(&mt('Main '.$crstype.' Documents').':::::');
     if (!-e $$tempexport) {      }
         mkdir($$tempexport,0700);      $pathitem = '<input type="hidden" name="folderpath" value="'.
     }                  &HTML::Entities::encode($folderpath,'<>&"').'" />';
     $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};      my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
     if (!-e $$tempexport) {      my $jumpto = $readfile;
         mkdir($$tempexport,0700);      $jumpto =~ s{^/}{};
     }      my $tid = 1;
     if (!-e "$$tempexport/resources") {      if ($supplementalflag) {
         mkdir("$$tempexport/resources",0700);          $tid = 2;
     }      }
 # open manifest file      my ($breadcrumbtrail) = 
     my $manifest = '/imsmanifest.xml';          &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
     my $manifestfilename = $$tempexport.$manifest;      $r->print($breadcrumbtrail.
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {                &generate_edit_table($tid,\%orderhash,undef,$iconpath,$jumpto,
         $$manifestok=1;                $readfile));
         print $ims_manifest      my %docslog=&Apache::lonnet::dump('nohist_docslog',
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.                                        $env{'course.'.$env{'request.course.id'}.'.num'});
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.  
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.  
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.      my %saveable_parameters = ('show' => 'scalar',);
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".      &Apache::loncommon::store_course_settings('docs_log',
 '  <metadata>                                                \%saveable_parameters);
     <schema></schema>      &Apache::loncommon::restore_course_settings('docs_log',
     <imsmd:lom>                                                  \%saveable_parameters);
       <imsmd:general>      if (!$env{'form.show'}) { $env{'form.show'}=10; }
         <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>  # FIXME: internationalization seems wrong here
         <imsmd:title>      my %lt=('hiddenresource' => 'Resources hidden',
           <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>      'encrypturl'     => 'URL hidden',
         </imsmd:title>      'randompick'     => 'Randomly pick',
       </imsmd:general>      'randomorder'    => 'Randomly ordered',
     </imsmd:lom>      'set'            => 'set to',
   </metadata>'."\n".      'del'            => 'deleted');
 '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".      my $filter = &Apache::loncommon::display_filter('docslog')."\n".
 '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.                   $pathitem."\n".
 ' structure="hierarchical">'."\n".                   '<input type="hidden" name="folder" value="'.$env{'form.folder'}.'" />'.
 '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'                   ('&nbsp;'x2).'<input type="submit" value="'.&mt('Display').'" />';
     } else {      $r->print('<div class="LC_left_float">'.
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'                '<fieldset><legend>'.&mt('Display of Content Changes').'</legend>'."\n".
 ;                &makedocslogform($filter,1).
     }                '</fieldset></div><br clear="all" />');
     return $ims_manifest;      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
 }                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
                 &mt('After').'</th>'.
 sub build_package {                &Apache::loncommon::end_data_table_header_row());
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;      my $shown=0;
 # first iterator to look for dependencies      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);   if ($env{'form.displayfilter'} eq 'currentfolder') {
     my $curRes;      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
     my $count = 0;   }
     my $depth = 0;          my @changes=keys(%{$docslog{$id}{'logentry'}});
     my $lastcontainer = 0;          if ($env{'form.displayfilter'} eq 'containing') {
     my %parent = ();      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
     my @dependencies = ();   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};      foreach my $key (@changes) {
     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
     while ($curRes = $it->next()) {      }
         if (ref($curRes)) {      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
             $count ++;   }
         }          my $count = 0;
         if ($curRes == $it->BEGIN_MAP()) {          my $time =
             $depth++;              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
             $parent{$depth} = $lastcontainer;          my $plainname =
         }              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
         if ($curRes == $it->END_MAP()) {                                            $docslog{$id}{'exe_udom'});
             $depth--;          my $about_me_link =
             $lastcontainer = $parent{$depth};              &Apache::loncommon::aboutmewrapper($plainname,
         }                                                 $docslog{$id}{'exe_uname'},
         if (ref($curRes)) {                                                 $docslog{$id}{'exe_udom'});
             if ($curRes->is_sequence() || $curRes->is_page()) {          my $send_msg_link='';
                 $lastcontainer = $count;          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
             }               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
             if (grep(/^$count$/,@$exportitems)) {              $send_msg_link ='<br />'.
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);                  &Apache::loncommon::messagewrapper(&mt('Send message'),
             }                                                     $docslog{$id}{'exe_uname'},
         }                                                     $docslog{$id}{'exe_udom'});
     }          }
 # second iterator to build manifest and store resources          $r->print(&Apache::loncommon::start_data_table_row());
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);          $r->print('<td>'.$time.'</td>
     $depth = 0;                         <td>'.$about_me_link.
     my $prevdepth;                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
     $count = 0;                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
     my $imsresources;                    $send_msg_link.'</td><td>'.
     my $pkgdepth;                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     while ($curRes = $it->next()) {          my $is_supp = 0; 
         if ($curRes == $it->BEGIN_MAP()) {          if ($docslog{$id}{'logentry'}{'currentfolder'} =~ /^supplemental/) {
             $prevdepth = $depth;              $is_supp = 1;
             $depth++;          }
         }  # Before
         if ($curRes == $it->END_MAP()) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
             $prevdepth = $depth;      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
             $depth--;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
         }      if ($oldname ne $newname) {
                   my $shown = &LONCAPA::map::qtescape($oldname);
         if (ref($curRes)) {                  if ($is_supp) {
             $count ++;                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
             if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {                  }
                 my $symb = $curRes->symb();                  $r->print($shown);
                 my $isvisible = 'true';      }
                 my $resourceref;   }
                 if ($curRes->randomout()) {   $r->print('<ul>');
                     $isvisible = 'false';   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 }              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
                 unless ($curRes->is_sequence()) {                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]);
                     $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';                  if ($is_supp) {
                 }                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                 my $step = $prevdepth - $depth;                  }
                 if (($step >= 0) && ($count > 1)) {   $r->print('<li>'.$shown.'</li>');
                     while ($step >= 0) {      }
                         print $ims_manifest "\n".'  </item>'."\n";   }
                         $step --;   $r->print('</ul>');
                     }  # After
                 }          $r->print('</td><td>');
                 $prevdepth = $depth;  
    for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                 my $itementry =      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
               '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.      if ($oldname ne '' && $oldname ne $newname) {
               '<title>'.$curRes->title().'</title>';                  my $shown = &LONCAPA::map::qtescape($newname);
                 print $ims_manifest "\n".$itementry;                  if ($is_supp) {
                       $shown = &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($newname));
                 unless ($curRes->is_sequence()) {                  }
                     my $content_file;                  $r->print($shown);
                     my @hrefs = ();      }
                     &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);   }
                     if ($content_file) {   $r->print('<ul>');
                         $imsresources .= "\n".   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
                      '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
                      '" type="webcontent" href="'.$content_file.'">'."\n".                  my $shown = &LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]);
                      '       <file href="'.$content_file.'" />'."\n";                  if ($is_supp) {
                         foreach my $item (@hrefs) {                      $shown = &Apache::loncommon::parse_supplemental_title($shown);
                             $imsresources .=                  }
                      '        <file href="'.$item.'" />'."\n";                  $r->print('<li>'.$shown.'</li>');
                         }      }
                         if (grep(/^$count$/,@$discussions)) {   }
                             my $ressymb = $symb;   $r->print('</ul>');
                             my $mode;   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
                             if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
                                 unless ($ressymb =~ m|adm/wrapper/adm|) {      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
                                     $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
                                 }  # FIXME: internationalization seems wrong here
                                 $mode = 'board';      $r->print('<li>'.
                             }        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
                             my %extras = (    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
                                           caller => 'imsexport',        .'</li>');
                                           tempexport => $tempexport.'/resources',   }
                                           count => $count      }
                                          );      $r->print('</ul>');
                             my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);   }
                         }  # End
                         $imsresources .= '    </resource>'."\n";          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
                     }          $shown++;
                 }          if (!($env{'form.show'} eq &mt('all')
                 $pkgdepth = $depth;                || $shown<=$env{'form.show'})) { last; }
             }      }
         }      $r->print(&Apache::loncommon::end_data_table()."\n".
     }                &makesimpleeditform($pathitem)."\n".
     while ($pkgdepth > 0) {                '</div></div>');
         print $ims_manifest "    </item>\n";      $r->print(&endContentScreen());
         $pkgdepth --;  }
     }  
     my $resource_text = qq|  sub update_paste_buffer {
     </organization>      my ($coursenum,$coursedom,$folder) = @_;
   </organizations>  
   <resources>      return if (!defined($env{'form.markcopy'}));
     $imsresources      return if (!defined($env{'form.copyfolder'}));
   </resources>      return if ($env{'form.markcopy'} < 0);
 </manifest>  
     |;      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
     print $ims_manifest $resource_text;      $env{'form.copyfolder'});
 }  
       return if ($fatal);
 sub get_dependencies {  
     my ($exportitems,$parent,$depth,$dependencies) = @_;  # Mark for copying
     if ($depth > 1) {      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
         if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {      if (&is_supplemental_title($title)) {
             push(@{$dependencies},$$parent{$depth});          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
             if ($depth > 2) {   ($title) = &Apache::loncommon::parse_supplemental_title($title);
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);      } elsif ($env{'docs.markedcopy_supplemental'}) {
             }          &Apache::lonnet::delenv('docs.markedcopy_supplemental');
         }      }
     }      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
 }  
       (my $cmd,undef)=split('_',$env{'form.cmd'});
 sub process_content {  
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;      my %addtoenv = (
     my $content_type;                      'docs.markedcopy_title' => $title,
     my $message;                      'docs.markedcopy_url'   => $url,
     my @uploads = ();                      'docs.markedcopy_cmd'   => $cmd,
     if ($curRes->is_sequence()) {                     );
         $content_type = 'sequence';      &Apache::lonnet::delenv('docs.markedcopy_nested');
     } elsif ($curRes->is_page()) {      &Apache::lonnet::delenv('docs.markedcopy_nestednames');
         $content_type = 'page'; # need to handle individual items in pages.      if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(default|supplemental)_?(\d*)\.(page|sequence)$}) {
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {          my $prefix = $1;
         $content_type = 'syllabus';          my $subdir =$2;
         my $contents = &Apache::imsexport::templatedpage($content_type);          if ($subdir eq '') {
         if ($contents) {              $subdir = $prefix;
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          }
         }          my (%addedmaps,%removefrommap,%removeparam,%hierarchy,%titles,%allmaps);
     } elsif ($symb =~ m-\.sequence___\d+___ext-) {          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,\%addedmaps,
         $content_type = 'external';                               \%hierarchy,\%titles,\%allmaps);
         my $title = $curRes->title;          if (ref($hierarchy{$url}) eq 'HASH') {
         my $contents =  &Apache::imsexport::external($symb,$title);              my ($nested,$nestednames);
         if ($contents) {              &recurse_uploaded_maps($url,$subdir,\%hierarchy,\%titles,\$nested,\$nestednames);
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              $nested =~ s/\&$//;
         }              $nestednames =~ s/\Q___&&&___\E$//;
     } elsif ($symb =~ m-adm/navmaps$-) {              if ($nested ne '') {
         $content_type =  'navmap';                  $addtoenv{'docs.markedcopy_nested'} = $nested;
     } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {              }
         $content_type = 'simplepage';              if ($nestednames ne '') {
         my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);                  $addtoenv{'docs.markedcopy_nestednames'} = $nestednames;
         if ($contents) {              }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          }
         }      }
     } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {      &Apache::lonnet::appenv(\%addtoenv);
         $content_type = 'simpleproblem';      delete($env{'form.markcopy'});
         my $contents =  &Apache::imsexport::simpleproblem($symb);  }
         if ($contents) {  
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);  sub recurse_uploaded_maps {
         }      my ($url,$dir,$hierarchy,$titlesref,$nestref,$namesref) = @_;
     } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {      if (ref($hierarchy->{$url}) eq 'HASH') {
         $content_type = 'examupload';          my @maps = map { $hierarchy->{$url}{$_}; } sort { $a <=> $b } (keys(%{$hierarchy->{$url}}));
     } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {          my @titles = map { $titlesref->{$url}{$_}; } sort { $a <=> $b } (keys(%{$titlesref->{$url}}));
         $content_type = 'bulletinboard';          my (@uploaded,@names,%shorter);
         my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);          for (my $i=0; $i<@maps; $i++) {
         if ($contents) {              my ($inner) = ($maps[$i] =~ m{^/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_(\d+)\.(?:page|sequence)$});
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);              if ($inner ne '') {
         }                  push(@uploaded,$inner);
     } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {                  push(@names,&escape($titles[$i]));
         $content_type = 'aboutme';                  $shorter{$maps[$i]} = $inner;
         my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);              }
         if ($contents) {          }
             $$content_file = &store_template($contents,$tempexport,$count,$content_type);          $$nestref .= "$dir:".join(',',@uploaded).'&';
         }          $$namesref .= "$dir:".(join(',',@names)).'___&&&___';
     } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {          foreach my $map (@maps) {
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');              if ($shorter{$map} ne '') {
     } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {                  &recurse_uploaded_maps($map,$shorter{$map},$hierarchy,$titlesref,$nestref,$namesref);
         my $canedit = 0;              }
         if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {          }
             $canedit= 1;      }
         }      return;
 # only include problem code where current user is author  }
         if ($canedit) {  
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');  sub print_paste_buffer {
         } else {      my ($r,$container,$folder,$coursedom,$coursenum) = @_;
             $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');      return if (!defined($env{'docs.markedcopy_url'}));
         }  
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {      my ($is_external,$othercourse,$fromsupp,$is_uploaded_map,$parent);
         $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');      my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
     }      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
     if (@uploads > 0) {          $is_external = 1;
         foreach my $item (@uploads) {      }
             my $uploadmsg = '';  
             &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');      my ($canpaste,$nopaste,$othercrs,$areachange);
             if ($uploadmsg) {      if ($folder =~ /^supplemental/) {
                 $$copyresult .= $uploadmsg."\n";          $canpaste = &supp_pasteable($env{'docs.markedcopy_url'});
             }          unless ($canpaste) {
         }              $nopaste = &mt('Paste into Supplemental Content unavailable for this type of content.');
     }          } 
     if ($message) {      } else {
         $$copyresult .= $message."\n";          $canpaste = 1;
     }      }
 }  
       if ($canpaste) {
 sub replicate_content {          if ($env{'docs.markedcopy_url'} =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;              my $srcdom = $1;
     my ($map,$ind,$url);              my $srcnum = $2;
     if ($caller eq 'templateupload') {              my $rem = $3;
         $url = $symb;              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum)) {
         $url =~ s#//#/#g;                  $othercourse = 1;
     } else {                  if ($env{"user.priv.cm./$srcdom/$srcnum"} =~ /\Q:mdc&F\E/) {
         ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);                      if ($canpaste) {
     }                          $othercrs = '<br />'.&mt('(from another course).');  
     my $content;                      }
     my $filename;                  } else {
     my $repstatus;                      $canpaste = 0;
     my $content_name;                      $nopaste = &mt('Paste from another course unavailable.') 
     if ($url =~ m-/([^/]+)$-) {                  }
         $filename = $1;              }
         if (!-e $tempexport.'/resources') {              if ($rem =~ m{^(default|supplemental)_?(\d*)\.(?:page|sequence)$}) {
             mkdir($tempexport.'/resources',0700);                  my $prefix = $1;
         }                  $parent = $2;
         if (!-e $tempexport.'/resources/'.$count) {                  if ($folder !~ /^\Q$prefix\E/) {
             mkdir($tempexport.'/resources/'.$count,0700);                      $areachange = 1;
         }                  }
         my $destination = $tempexport.'/resources/'.$count.'/'.$filename;                  $is_uploaded_map = 1;
         my $copiedfile;              }
         if ($copiedfile = Apache::File->new('>'.$destination)) {          }
             my $content;      }
             if ($caller eq 'resource') {  
                 my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';      $r->print('<fieldset>'
                 my $filepath = &Apache::lonnet::filelocation($respath,$url);               .'<legend>'.&mt('Clipboard').'</legend>');
                 $content = &Apache::lonnet::getfile($filepath);      my ($type,$buffer);
                 if ($content eq -1) {      if ($is_external) {
                     $$message = 'Could not copy file '.$filename;          $type = &mt('External Resource');
                 } else {          $buffer = $type.': '.
                     &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');                    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
                     $repstatus = 'ok';                    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')';
                 }      } else {
             } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {          my $icon = &Apache::loncommon::icon($extension);
                 my $rtncode;          if ($extension eq 'sequence' &&
                 $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);              $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
                 if ($repstatus eq 'ok') {              $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                     if ($url =~ /\.html?$/i) {              $icon .= '/navmap.folder.closed.gif';
                         &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');          }
                     }          $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
                 } else {          $buffer = $icon.$type.': '.  &Apache::loncommon::parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'}));
                     $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";      }
                 }      if ($canpaste) {
             } elsif ($caller eq 'noedit') {          $r->print('<form name="pasteform" action="/adm/coursedocs" method="post">'.$buffer);
 # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.          if ((!$areachange) && (!$othercourse) &&
                 $repstatus = 'ok';              ($env{'docs.markedcopy_cmd'} eq 'cut')) {
                 $content = 'Not the owner of this resource';              if (($is_uploaded_map) || 
             }                  ($env{'docs.markedcopy_url'} =~ /(bulletinboard|smppg)$/) ||
             if ($repstatus eq 'ok') {                  ($env{'docs.markedcopy_url'} =~ m{^/uploaded/$coursedom/$coursenum/(?:docs|supplemental)/(.+)$})) {
                 print $copiedfile $content;                  my ($copytext,$movetext);
             }                  if ($is_uploaded_map) {
             close($copiedfile);                      $copytext = &mt('Copy to new folder');
         } else {                      $movetext = &mt('Move old folder');
             $$message = 'Could not open destination file for '.$filename."<br />\n";                  } elsif ($env{'docs.markedcopy_url'} =~ /bulletinboard$/) {
         }                      $copytext = &mt('Copy to new bulletin board (not posts)');
     } else {                      $movetext = &mt('Move old bulletin board (not posts)');
         $$message = 'Could not determine name of file for '.$symb."<br />\n";                  } elsif ($env{'docs.markedcopy_url'} =~ /smppg$/) {
     }                      $copytext = &mt('Copy to new simple page');
     if ($repstatus eq 'ok') {                      $movetext = &mt('Move old simple page');
         $content_name = 'resources/'.$count.'/'.$filename;                  } else {
     }                      $copytext = &mt('Copy to new uploaded document');
     return $content_name;                      $movetext = &mt('Move old uploaded document');
 }                  }
                   $r->print(('&nbsp;'x 4).'<span id="pasteoptionstext">'.
 sub extract_media {                            '<a href="javascript:showPasteOptions();" class="LC_menubuttons_link">'.
     my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;                            &mt('Show Paste Options').'</a></span><br />'.
     my ($dirpath,$container);                            '<div id="pasteoptions" class="LC_dccid">'.('&nbsp;'x 4).
     my %allfiles = ();                            '<label>'.
     my %codebase = ();                            '<input type="radio" name="docs.markedcopy_options" value="new" checked="checked" />'.
     if ($url =~ m-(.*/)([^/]+)$-) {                            $copytext.'</label>'.('&nbsp;' x2).
         $dirpath = $1;                            '<label>'.   
         $container = $2;                            '<input type="radio" name="docs.markedcopy_options" value="move" />'.
     } else {                            $movetext.'</label><br />');
         $dirpath = $url;                  if (($is_uploaded_map) && ($env{'docs.markedcopy_nested'})) {
         $container = '';                      $r->print('<br />'.&mt('Folder to paste contains sub-folders').
     }                                '<br /><table border="0">');
     &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);                      my @pastemaps = split(/\&/,$env{'docs.markedcopy_nested'});
     foreach my $embed_file (keys(%allfiles)) {                      my @titles = split(/\Q___&&&___\E/,$env{'docs.markedcopy_nestednames'});
         my $filename;                      my $lastdir = $parent;
         if ($embed_file =~ m#([^/]+)$#) {                      my %depths = (
             $filename = $1;                                     $lastdir => 0,
         } else {                                   );
             $filename = $embed_file;                      my (%display,%deps); 
         }                      for (my $i=0; $i<@pastemaps; $i++) {
         my $newname = 'res/'.$filename;                          ($lastdir,my $subfolderstr) = split(/\:/,$pastemaps[$i]);
         my ($rtncode,$embed_content,$repstatus);                          my ($namedir,$esctitlestr) = split(/\:/,$titles[$i]);
         my $embed_url;                          my @subfolders = split(/,/,$subfolderstr);
         if ($embed_file =~ m-^/-) {                          $deps{$lastdir} = \@subfolders;
             $embed_url = $embed_file;           # points to absolute path                          my @subfoldertitles = map { &unescape($_); } split(/,/,$esctitlestr);
         } else {                          my $depth = $depths{$lastdir} + 1;
             if ($embed_file =~ m-https?://-) {                          my $offset = int($depth * 4);
                 next;                           # points to url                          my $indent = ('&nbsp;' x $offset);
             } else {                          for (my $j=0; $j<@subfolders; $j++) {
                 $embed_url = $dirpath.$embed_file;  # points to relative path                              $depths{$subfolders[$j]} = $depth;
             }                              $display{$subfolders[$j]} = 
         }                                    '<tr><td>'.$indent.$subfoldertitles[$j].'&nbsp;</td>'.
         if ($caller eq 'resource') {                                    '<td><label>'.
             my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';                                      '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="new" checked="checked" />'.&mt('Copy to new').'</label>'.('&nbsp;' x2).
             my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);                                    '<label>'.
             $embed_content = &Apache::lonnet::getfile($embed_path);                                    '<input type="radio" name="docs.markedcopy_'.$subfolders[$j].'" value="move" />'.
             unless ($embed_content eq -1) {                                    &mt('Move old').'</label>'.
                 $repstatus = 'ok';                                    '</td></tr>';
             }                          }
         } elsif ($caller eq 'uploaded') {                      }
                                  &recurse_print($r,$parent,\%deps,\%display);
             $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);                      $r->print('</table>');
         }                  }
         if ($repstatus eq 'ok') {                  $r->print('</div>');
             my $destination = $tempexport.'/resources/'.$count.'/res';              }
             if (!-e "$destination") {          }
                 mkdir($destination,0755);          $r->print('<br /><input type="submit" name="pastemarked" value="'.&mt('Paste').'" />'.$othercrs);
             }          $r->print('
             $destination .= '/'.$filename;          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
             my $copiedfile;  ');
             if ($copiedfile = Apache::File->new('>'.$destination)) {          $r->print('</form>');
                 print $copiedfile $embed_content;      } else {
                 push(@{$href},'resources/'.$count.'/res/'.$filename);          $r->print(&mt('Paste buffer contains:').' '.$buffer.
                 my $attrib_regexp = '';                    '<br /><p class="LC_info">'.$nopaste.'</p>');
                 if (@{$allfiles{$embed_file}} > 1) {      }
                     $attrib_regexp = join('|',@{$allfiles{$embed_file}});      $r->print('</fieldset>');
                 } else {  }
                     $attrib_regexp = $allfiles{$embed_file}[0];  
                 }  sub recurse_print {
                 $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;      my ($r,$dir,$deps,$display) = @_;
                 if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {      $r->print($display->{$dir}."\n");
                     $$content =~ s#\Q$embed_file\E#$newname#gi;      if (ref($deps->{$dir}) eq 'ARRAY') {
                 }          foreach my $subdir (@{$deps->{$dir}}) {
             }              &recurse_print($r,$subdir,$deps,$display);
         } else {          }
             $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";      }
         }  }
     }  
     return;  sub supp_pasteable {
 }      my ($url) = @_;
       if (($url =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//}) ||
 sub store_template {          (($url =~ /\.sequence$/) && ($url =~ m{^/uploaded/})) ||
     my ($contents,$tempexport,$count,$content_type) = @_;          ($url =~ m{^/uploaded/$match_domain/$match_courseid/(docs|supplemental)/(default|\d+)/\d+/}) ||
     if ($contents) {          ($url =~ m{^/adm/$match_domain/$match_username/aboutme}) ||
         if ($tempexport) {          ($url =~ m{^/public/$match_domain/$match_courseid/syllabus})) {
             if (!-e $tempexport.'/resources') {          return 1;
                 mkdir($tempexport.'/resources',0700);      }
             }      return;
             if (!-e $tempexport.'/resources/'.$count) {  }
                 mkdir($tempexport.'/resources/'.$count,0700);  
             }  sub paste_popup_js {
             my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';      my %lt = &Apache::lonlocal::texthash(
             my $storetemplate;                                            show => 'Show Paste Options',
             if ($storetemplate = Apache::File->new('>'.$destination)) {                                            hide => 'Hide Paste Options',
                 print $storetemplate $contents;                                          );
                 close($storetemplate);      return <<"END";
             }  
             if ($content_type eq 'external') {  function showPasteOptions() {
                 return 'resources/'.$count.'/'.$content_type.'.html';      document.getElementById('pasteoptions').style.display='block';
             } else {      document.getElementById('pasteoptions').style.textAlign='left';
                 return 'resources/'.$count.'/'.$content_type.'.xml';      document.getElementById('pasteoptions').style.textFace='normal';
             }      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:hidePasteOptions();" class="LC_menubuttons_link">$lt{'hide'}</a><br />';
         }      return;
     }  }
 }  
   function hidePasteOptions() {
       document.getElementById('pasteoptions').style.display='none';
 sub group_import {      document.getElementById('pasteoptionstext').innerHTML ='<a href="javascript:showPasteOptions()" class="LC_menubuttons_link">$lt{'show'}</a>';
     my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;      return;
   }
     while (@files) {  
  my ($name, $url, $residx) = @{ shift(@files) };  END
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})  
      && ($caller eq 'londocs')  }
      && (!&Apache::lonnet::stat_file($url))) {  
       
             my $errtext = '';  sub do_paste_from_buffer {
             my $fatal = 0;      my ($coursenum,$coursedom,$folder,$container,$errors) = @_;
             my $newmapstr = '<map>'."\n".  
                             '<resource id="1" src="" type="start"></resource>'."\n".  # Early out if paste buffer is empty
                             '<link from="1" to="2" index="1"></link>'."\n".      if (!$env{'form.pastemarked'}) {
                             '<resource id="2" src="" type="finish"></resource>'."\n".          return ();
                             '</map>';      }
             $env{'form.output'}=$newmapstr;  
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,  # Supplemental content may only include certain types of content
                                                 'output',$1.$2);  # Early out if pasted content is not supported in Supplemental area
             if ($result != m|^/uploaded/|) {      if ($folder =~ /^supplemental/) {
                 $errtext.='Map not saved: A network error occurred when trying to save the new map. ';          unless (&supp_pasteable($env{'docs.markedcopy_url'})) {
                 $fatal = 2;              return (&mt('Paste failed: content type is not supported within Supplemental Content'));
             }          }
             if ($fatal) {      }
                 return ($errtext,$fatal);  
             }  # Prepare to paste resource at end of list
         }      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
  if ($url) {      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
     if (!$residx  
  || defined($LONCAPA::map::zombies[$residx])) {      my ($is_map,$srcdom,$srcnum,$prefixchg,%before,%after,%mapchanges,%tomove);
  $residx = &LONCAPA::map::getresidx($url,$residx);      if ($url=~/\.(page|sequence)$/) {
  push(@LONCAPA::map::order, $residx);          $is_map = 1; 
     }      }
     my $ext = 'false';      if ($url =~ m{^/uploaded/($match_domain)/($match_courseid)/([^/]+)}) {
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }          $srcdom = $1;
     $url  = &LONCAPA::map::qtunescape($url);          $srcnum = $2;
     $name = &LONCAPA::map::qtunescape($name);          my $oldprefix = $3;
     $LONCAPA::map::resources[$residx] =  # When paste buffer was populated using an active role in a different course
  join(':', ($name, $url, $ext, 'normal', 'res'));  # 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/) {
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);                  return (&mt('Paste failed: Item is from a different course which you do not have rights to edit.'));
 }              }
           }
 sub breadcrumbs {  # When pasting content from Main Content to Supplemental Content and vice versa 
     my ($where,$allowed,$type)=@_;  # URLs will contain different paths (which depend on whether pasted item is
     &Apache::lonhtmlcommon::clear_breadcrumbs();  # a folder/page or a document.   
     my (@folders);          if (($folder =~ /^supplemental/) && (($oldprefix =~ /^default/) || ($oldprefix eq 'docs'))) {
     if ($env{'form.pagepath'}) {              $prefixchg = 1;
         @folders = split('&',$env{'form.pagepath'});              %before = ( map => 'default',
     } else {                          doc => 'docs');
         @folders=split('&',$env{'form.folderpath'});              %after =  ( map => 'supplemental',
     }                          doc => 'supplemental' );
     my $folderpath;          } elsif (($folder =~ /^default/) && ($oldprefix =~ /^supplemental/)) {
     my $cpinfo='';              $prefixchg = 1;
     my $plain='';              %before = ( map => 'supplemental',
     my $randompick=-1;                          doc => 'supplemental');
     my $isencrypted=0;              %after  = ( map => 'default',
     my $ishidden=0;                          doc => 'docs');
     my $is_random_order=0;          }
     while (@folders) {  
  my $folder=shift(@folders);  # If pasting an uploaded map, get list of contained uploaded maps.
     my $foldername=shift(@folders);          my @nested;
  if ($folderpath) {$folderpath.='&';}          if ($env{'docs.markedcopy_nested'}) {
  $folderpath.=$folder.'&'.$foldername;              my ($type) = ($oldprefix =~ /^(default|supplemental)/);
  my $url='/adm/coursedocs?folderpath='.              my @items = split(/\&/,$env{'docs.markedcopy_nested'});
     &escape($folderpath);              my @deps = map { /\d+:([\d,]+$)/ } @items;
     my $name=&unescape($foldername);              foreach my $dep (@deps) {
 # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername                  if ($dep =~ /,/) {
      $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;                      push(@nested,split(/,/,$dep));
     if ($1 ne '') {                  } else {
                $randompick=$1;                      push(@nested,$dep);
             } else {                  }
                $randompick=-1;              }
             }              foreach my $item (@nested) {
             if ($2) { $ishidden=1; }                  if ($env{'form.docs.markedcopy_'.$item} eq 'move') {
             if ($3) { $isencrypted=1; }                      $tomove{$type.'_'.$item} = 1;
     if ($4 ne '') { $is_random_order = 1; }                  }
             if ($folder eq 'supplemental') {              }
                 if ($allowed) {          }
                     $name = &mt('Supplemental '.$type.' Documents');      }
                 } else {  
                     $name = &mt($type.' Documents');  # Maps need to be copied first
                 }      my ($oldurl,%removefrommap,%removeparam,%addedmaps,%rewrites,%retitles,%copies,
             }          %dbcopies,%zombies,%params,%docmoves,%mapmoves,%newsubdir,%newurls);
     &Apache::lonhtmlcommon::add_breadcrumb(      $oldurl = $url;
       {'href'=>$url.$cpinfo,      if ($is_map) {
        'title'=>$name,  # If pasting a map, check if map contains other maps
        'text'=>'<font size="+1">'.          my ($allmaps,%hierarchy,%titles);
    $name.'</font>',          $allmaps = {};
        'no_mt'=>1,          if ($folder =~ /^default/) {
        });              $allmaps =
  $plain.=$name.' &gt; ';                  &Apache::loncommon::allmaps_incourse($coursedom,$coursenum,
     }                                                       $env{"course.$env{'request.course.id'}.home"},
     $plain=~s/\&gt\;\s*$//;                                                       $env{'request.course.id'});
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',          }
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);          &contained_map_check($url,$folder,\%removefrommap,\%removeparam,
 }                               \%addedmaps,\%hierarchy,\%titles,$allmaps);
           if ($url=~ m{^/uploaded/}) {
 sub log_docs {              my $newurl;
     return &Apache::lonnet::instructor_log('docslog',@_);              unless ($env{'form.docs.markedcopy_options'} eq 'move') {
 }                  ($newurl,my $error) = 
                       &get_newmap_url($url,$folder,$prefixchg,$coursedom,$coursenum,
 {                                      $srcdom,$srcnum,\$title,$allmaps,\%newurls);
     my @oldresources=();                  if ($error) {
     my @oldorder=();                      return ($error);
     my $parmidx;                  }
     my %parmaction=();                  if ($newurl ne '') {
     my %parmvalue=();                      if ($newurl ne $url) {
     my $changedflag;                          if ($newurl =~ /(?:default|supplemental)_(\d+).(?:sequence|page)$/) {
                               $newsubdir{$url} = $1;
     sub snapshotbefore {                          }
         @oldresources=@LONCAPA::map::resources;                          $mapchanges{$url} = 1;
         @oldorder=@LONCAPA::map::order;                      }
         $parmidx=undef;                  }
         %parmaction=();              }
         %parmvalue=();              if (($srcdom ne $coursedom) || ($srcnum ne $coursenum) || ($prefixchg) ||
         $changedflag=0;                  (($newurl ne '') && ($newurl ne $url))) {
     }                  unless (&url_paste_fixups($url,$folder,$prefixchg,$coursedom,
                                             $coursenum,$srcdom,$srcnum,$allmaps,
     sub remember_parms {                                            \%rewrites,\%retitles,\%copies,\%dbcopies,
         my ($idx,$parameter,$action,$value)=@_;                                            \%zombies,\%params,\%mapmoves,\%mapchanges,\%tomove,
         $parmidx=$idx;                                            \%newsubdir,\%newurls)) {
         $parmaction{$parameter}=$action;                      $mapmoves{$url} = 1;
         $parmvalue{$parameter}=$value;                  }
         $changedflag=1;                  $url = $newurl;
     }              } elsif ($env{'docs.markedcopy_nested'}) {
                   &url_paste_fixups($url,$folder,$prefixchg,$coursedom,$coursenum,
     sub log_differences {                                    $srcdom,$srcnum,$allmaps,\%rewrites,
         my ($plain)=@_;                                    \%retitles,\%copies,\%dbcopies,\%zombies,\%params,\%mapmoves,
         my %storehash=('folder' => $plain,                                    \%mapchanges,\%tomove,\%newsubdir,\%newurls); 
                        'currentfolder' => $env{'form.folder'});              }
         if ($parmidx) {          } elsif ($url=~m {^/res/}) {
            $storehash{'parameter_res'}=$oldresources[$parmidx];  # published maps can only exists once, so remove it from paste buffer when done
            foreach my $parm (keys(%parmaction)) {              &Apache::lonnet::delenv('docs.markedcopy');
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};  # if pasting published map (main content are only) check map is not already in course
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};              if ($folder =~ /^default/) {
            }                  if ((ref($allmaps) eq 'HASH') && ($allmaps->{$url})) {
         }                      return (&mt('Paste failed: only one instance of a particular published sequence or page is allowed within each course.'));
         my $maxidx=$#oldresources;                  }
         if ($#LONCAPA::map::resources>$#oldresources) {              }
            $maxidx=$#LONCAPA::map::resources;          }
         }      }
         for (my $idx=0; $idx<=$maxidx; $idx++) {      my $lockerrors;
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {      if ($url=~ m{/(bulletinboard|smppg)$}) {
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];          my $prefix = $1;
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];          #need to copy the db contents to a new one, unless this is a move.
               $changedflag=1;          my %info = (
            }                       src  => $url,
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {                       cdom => $coursedom,
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];                       cnum => $coursenum,
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          );
               $changedflag=1;          my (%lockerr,$msg);
            }          unless ($env{'form.docs.markedcopy_options'} eq 'move') {
         }              my ($newurl,$result,$errtext) =
  $storehash{'maxidx'}=$maxidx;                  &dbcopy(\%info,$coursedom,$coursenum,\%lockerr);
         if ($changedflag) { &log_docs(\%storehash); }              if ($result eq 'ok') {
     }                  $url = $newurl;
 }                  $title=&mt('Copy of').' '.$title;
               } else {
                   if ($prefix eq 'smppg') {
                       $msg = &mt('Paste failed: An error occurred when copying the simple page.').' '.$errtext;
                   } elsif ($prefix eq 'bulletinboard') {
                       $msg = &mt('Paste failed: An error occurred when copying the bulletin board.').' '.$errtext;
 sub docs_change_log {                  }
     my ($r)=@_;                  return ($result,undef,[$msg],$lockerr{$prefix});
     my $folder=$env{'form.folder'};      }
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));              if ($lockerr{$prefix}) {
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));                  $lockerrors = $lockerr{$prefix};  
     my %docslog=&Apache::lonnet::dump('nohist_docslog',              }
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},          }
                                       $env{'course.'.$env{'request.course.id'}.'.num'});      }
       $title = &LONCAPA::map::qtunescape($title);
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }      my $ext='false';
       if ($url=~m{^http(|s)://}) { $ext='true'; }
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.      $url       = &LONCAPA::map::qtunescape($url);
               '<input type="hidden" name="docslog" value="1" />');  
   # For uploaded files (excluding pages/sequences) path in copied file is changed
     my %saveable_parameters = ('show' => 'scalar',);  # if paste is from Main to Supplemental (or vice versa), or if pasting between
     &Apache::loncommon::store_course_settings('docs_log',  # courses.
                                               \%saveable_parameters);  
     &Apache::loncommon::restore_course_settings('docs_log',      my $newidx;
                                                 \%saveable_parameters);      unless ($is_map) {
     if (!$env{'form.show'}) { $env{'form.show'}=10; }  # Now insert the URL at the bottom
     my %lt=('hiddenresource' => 'Resources hidden',          $newidx = &LONCAPA::map::getresidx($url);
     'encrypturl'     => 'URL hidden',          if ($url =~ m{^/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(.+)$}) {
     'randompick'     => 'Randomly pick',              my $relpath = $1;
     'randomorder'    => 'Randomly ordered',              if ($relpath ne '') {
     'set'            => 'set to',                  my ($prefix,$subdir,$rem) = ($relpath =~ m{^(default|\d+)/(\d+)/(.+)$});
     'del'            => 'deleted');                  my ($newloc,$newdocsdir) = ($folder =~ /^(default|supplemental)_?(\d*)/);
     $r->print(&Apache::loncommon::display_filter().                  my $newprefix = $newloc;
               '<input type="hidden" name="folder" value="'.$folder.'" />'.                  if ($newloc eq 'default') {
               '<input type="submit" value="'.&mt('Display').'" /></form>');                      $newprefix = 'docs';
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().                  }
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.                  if ($newdocsdir eq '') {
               &mt('After').'</th>'.                      $newdocsdir = 'default';
               &Apache::loncommon::end_data_table_header_row());                  }
     my $shown=0;                  if (($prefixchg) || 
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {                      ($srcdom ne $coursedom) || ($srcnum ne $coursenum) ||
  if ($env{'form.displayfilter'} eq 'currentfolder') {                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }                      my $newpath = "$newprefix/$newdocsdir/$newidx/$rem";
  }                      $url =
         my @changes=keys(%{$docslog{$id}{'logentry'}});                          &Apache::lonclonecourse::writefile($env{'request.course.id'},$newpath,
         if ($env{'form.displayfilter'} eq 'containing') {                                                             &Apache::lonnet::getfile($oldurl));
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.                      if ($url eq '/adm/notfound.html') {
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});                          return (&mt('Paste failed: an error occurred saving the file.'));
     foreach my $key (@changes) {                      } else {
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};                          my ($newsubpath) = ($newpath =~ m{^(.*/)[^/]*$});
     }                          $newsubpath =~ s{/+$}{/};
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }                                  $docmoves{$oldurl} = $newsubpath;
  }                      }
         my $count = 0;                  }
         my $time =              }
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});          }
         my $plainname =      }
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},  # Apply any changes to maps, or copy dependencies for uploaded HTML pages 
                                           $docslog{$id}{'exe_udom'});      my ($result,$save_err);
         my $about_me_link =      my %updated = (
             &Apache::loncommon::aboutmewrapper($plainname,                      rewrites      => \%rewrites,
                                                $docslog{$id}{'exe_uname'},                      zombies       => \%zombies,
                                                $docslog{$id}{'exe_udom'});                      removefrommap => \%removefrommap,
         my $send_msg_link='';                      removeparam   => \%removeparam,
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})                      dbcopies      => \%dbcopies,
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {                      retitles      => \%retitles,
             $send_msg_link ='<br />'.                    );
                 &Apache::loncommon::messagewrapper(&mt('Send message'),      my %info = (
                                                    $docslog{$id}{'exe_uname'},                     newsubdir => \%newsubdir,
                                                    $docslog{$id}{'exe_udom'});                     params    => \%params,
         }                     before    => \%before,
         $r->print(&Apache::loncommon::start_data_table_row());                     after     => \%after,
         $r->print('<td>'.$time.'</td>                 );
                        <td>'.$about_me_link.      my %moves = (
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.                     copies   => \%copies,
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.                     docmoves => \%docmoves,
                   $send_msg_link.'</td><td>'.                     mapmoves => \%mapmoves,
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');                  );
 # Before      ($result,my $msgsarray,my $lockerror) =
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          &apply_fixups($folder,$is_map,$coursedom,$coursenum,$errors,
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                        \%updated,\%info,\%moves,$prefixchg,$oldurl,$url,'paste');
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];      $lockerrors .= $lockerror;
     if ($oldname ne $newname) {      if ($result eq 'ok') {
  $r->print(&LONCAPA::map::qtescape($oldname));          if ($is_map) { 
     }              my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  }                                              $folder.'.'.$container);
  $r->print('<ul>');              return ($errtext,$save_err,$msgsarray,$lockerrors) if ($fatal);
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {  
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {              if ($#LONCAPA::map::order<1) {
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');                  my $idx=&LONCAPA::map::getresidx();
     }                  if ($idx<=0) { $idx=1; }
  }                  $LONCAPA::map::order[0]=$idx;
  $r->print('</ul>');                  $LONCAPA::map::resources[$idx]='';
 # After              }
         $r->print('</td><td>');              $newidx = &LONCAPA::map::getresidx($url);
           }
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {          if ($env{'docs.markedcopy_supplemental'}) {
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];              if ($folder !~ /^supplemental/) {
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];                  (undef,undef,$title) =
     if ($oldname ne '' && $oldname ne $newname) {                      &Apache::loncommon::parse_supplemental_title($env{'docs.markedcopy_supplemental'});
  $r->print(&LONCAPA::map::qtescape($newname));              }
     }          } else {
  }                      if ($folder=~/^supplemental/) {
  $r->print('<ul>');                  $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                         $env{'user.domain'}.'___&&&___'.$title;
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {              }
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');          }
     }          $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
  }          push(@LONCAPA::map::order, $newidx);
  $r->print('</ul>');  
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {  # Store the result
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');          my ($errtext,$fatal) = 
     foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {              &storemap($coursenum,$coursedom,$folder.'.'.$container,1);
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {          if ($fatal) {
     $r->print('<li>'.              $save_err = $errtext;
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',          }
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})      }
       .'</li>');  
  }      if ($env{'form.docs.markedcopy_options'} eq 'move') {
     }          &Apache::lonnet::delenv('docs.markedcopy');
     $r->print('</ul>');          &Apache::lonnet::delenv('docs.markedcopy_nested');
  }          &Apache::lonnet::delenv('docs.markedcopy_nestednames');
 # End      }
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());      return ($result,$save_err,$msgsarray,$lockerrors);
         $shown++;  }
         if (!($env{'form.show'} eq &mt('all')  
               || $shown<=$env{'form.show'})) { last; }  sub get_newmap_url {
     }      my ($url,$folder,$prefixchg,$coursedom,$coursenum,$srcdom,$srcnum,
     $r->print(&Apache::loncommon::end_data_table());          $titleref,$allmaps,$newurls) = @_;
 }      my $newurl;
       if ($url=~ m{^/uploaded/}) {
 sub update_paste_buffer {          $$titleref=&mt('Copy of').' '.$$titleref;
     my ($coursenum,$coursedom) = @_;      }
       my $now = time;
     return if (!defined($env{'form.markcopy'}));      my $suffix=$$.int(rand(100)).$now;
     return if (!defined($env{'form.copyfolder'}));      my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
     return if ($env{'form.markcopy'} < 0);      if ($oldid =~ m{^(/uploaded/$match_domain/$match_courseid/)(\D+)(\d+)$}) {
           my $path = $1;
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,          my $prefix = $2;
     $env{'form.copyfolder'});          my $ancestor = $3;
              if (length($ancestor) > 10) {
     return if ($fatal);              $ancestor = substr($ancestor,-10,10);
           }
 # Mark for copying          my $newid;
     my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);          if ($prefixchg) {
     if (&is_supplemental_title($title)) {              if ($folder =~ /^supplemental/) {
         &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});                  $prefix =~ s/^default/supplemental/;
  ($title) = &parse_supplemental_title($title);              } else {
     } elsif ($env{'docs.markedcopy_supplemental'}) {                  $prefix =~ s/^supplemental/default/;
         &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');              }
     }          }
     $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};          if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
               $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,          } else {
     'docs.markedcopy_url'   => $url});              $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$now.'.'.$ext;
     delete($env{'form.markcopy'});          }
 }          my $counter = 0;
           my $is_unique = &uniqueness_check($newurl);
 sub print_paste_buffer {          if ($folder =~ /^default/) {
     my ($r,$container) = @_;              if ($allmaps->{$newurl}) {
     return if (!defined($env{'docs.markedcopy_url'}));                  $is_unique = 0;
               }
     $r->print(<<ENDPASTE);          }
 <form name="pasteform" action="/adm/coursedocs" method="post"><p>          while ((!$is_unique || $allmaps->{$newurl} || $newurls->{$newurl}) && ($counter < 100)) {
 ENDPASTE              $counter ++;
     $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');              $suffix ++;
               if (($srcdom eq $coursedom) && ($srcnum eq $coursenum)) {
     my $type;                  $newurl = $path.$prefix.$ancestor.$suffix.'.'.$ext;
     if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {              } else {
  $type = &mt('External Resource');                  $newurl = "/uploaded/$coursedom/$coursenum/$prefix".$ancestor.$suffix.'.'.$ext;
  $r->print($type.': '.              }
   &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.              $is_unique = &uniqueness_check($newurl);
   &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');          }
     }  else {          if ($is_unique) {
  my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];              $newurls->{$newurl} = 1;
  my $icon = &Apache::loncommon::icon($extension);          } else {
  if ($extension eq 'sequence' &&              if ($url=~/\.page$/) {
     $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the composite page'));
     $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));              } else {
     $icon .= '/folder_closed.gif';                  return (undef,&mt('Paste failed: an error occurred creating a unique URL for the folder'));
  }              }
  $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';          }
  $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));      }
     }      return ($newurl);
     if ($container eq 'page') {  }
  $r->print('  
  <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />  sub dbcopy {
  <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />      my ($dbref,$coursedom,$coursenum,$lockerrorsref) = @_;
 ');      my ($url,$result,$errtext);
     } else {      my $url = $dbref->{'src'};
  $r->print('      if (ref($dbref) eq 'HASH') {
         <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />          if ($url =~ m{/(smppg|bulletinboard)$}) {
 ');              my $prefix = $1;
     }              if (($dbref->{'cdom'} =~ /^$match_domain$/) && 
     $r->print('</p></form>');                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
 }                  my $db_name;
                   my $marker = (split(m{/},$url))[4];
 sub do_paste_from_buffer {                  $marker=~s/\D//g;
     my ($coursenum,$coursedom,$folder) = @_;                  if ($dbref->{'src'} =~ m{/smppg$}) {
                       $db_name =
     if (!$env{'form.pastemarked'}) {                          &Apache::lonsimplepage::get_db_name($url,$marker,
         return;                                                              $dbref->{'cdom'},
     }                                                              $dbref->{'cnum'});
                   } else {
 # paste resource to end of list                      $db_name = 'bulletinpage_'.$marker;
     my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});                  }
     my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});                  my ($suffix,$freedlock,$error) =
 # Maps need to be copied first                      &Apache::lonnet::get_timebased_id($prefix,'num','templated',
     if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {                                                        $coursedom,$coursenum,
  $title=&mt('Copy of').' '.$title;                                                        'concat');
  my $newid=$$.int(rand(100)).time;                  if (!$suffix) {
  my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);                      if ($prefix eq 'smppg') {
         if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a simple page [_1].',$url);
             my $path = $1;                      } else {
             my $prefix = $2;                          $errtext = &mt('Failed to acquire a unique timestamp-based suffix when copying a bulletin board [_1].',$url);
             my $ancestor = $3;                      }
             if (length($ancestor) > 10) {                      if ($error) {
                 $ancestor = substr($ancestor,-10,10);                          $errtext .= '<br />'.$error;
             }                      }
             $oldid = $path.$prefix.$ancestor;                  } else {
         }                      #need to copy the db contents to a new one.
         my $counter = 0;                      my %contents=&Apache::lonnet::dump($db_name,
         my $newurl=$oldid.$newid.'.'.$ext;                                                         $dbref->{'cdom'},
         my $is_unique = &uniqueness_check($newurl);                                                         $dbref->{'cnum'});
         while (!$is_unique && $counter < 100) {                      if (exists($contents{'uploaded.photourl'})) {
             $counter ++;                          my $photo = $contents{'uploaded.photourl'};
             $newid ++;                          my ($subdir,$fname) =
             $newurl = $oldid.$newid;                              ($photo =~ m{^/uploaded/$match_domain/$match_courseid/+(bulletin|simplepage)/(?:|\d+/)([^/]+)$});
             $is_unique = &uniqueness_check($newurl);                          my $newphoto; 
         }                          if ($fname ne '') {
         if (!$is_unique) {                              my $content = &Apache::lonnet::getfile($photo);
             if ($url=~/\.page$/) {                              unless ($content eq '-1') {
                 return &mt('Paste failed: an error occurred creating a unique URL for the composite page');                                  $env{'form.'.$suffix.'.photourl'} = $content;
             } else {                                  $newphoto = 
                 return &mt('Paste failed: an error occurred creating a unique URL for the folder');                                      &Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$suffix.'.photourl',"$subdir/$suffix/$fname");
             }                                  delete($env{'form.'.$suffix.'.photourl'});
         }                              }
  my $storefn=$newurl;                          }
  $storefn=~s{^/\w+/$match_domain/$match_username/}{};                          if ($newphoto =~ m{^/uploaded/}) {
  my $paste_map_result =                              $contents{'uploaded.photourl'} = $newphoto;
             &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,                          }
        &Apache::lonnet::getfile($url));                      }
         if ($paste_map_result eq '/adm/notfound.html') {                      $db_name =~ s{_\d*$ }{_$suffix}x;
             if ($url=~/\.page$/) {                      $result=&Apache::lonnet::put($db_name,\%contents,
                 return &mt('Paste failed: an error occurred saving the composite page');                                                   $coursedom,$coursenum);
             } else {                      if ($result eq 'ok') {
                 return &mt('Paste failed: an error occurred saving the folder');                          $url =~ s{/(\d*)/(smppg|bulletinboard)$}{/$suffix/$2}x;
             }                      }
         }                  }
  $url = $newurl;                  if (($freedlock ne 'ok') && (ref($lockerrorsref) eq 'HASH')) {
     }                      $lockerrorsref->{$prefix} = 
 # published maps can only exists once, so remove it from paste buffer when done                          '<div class="LC_error">'.
     if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {                          &mt('There was a problem removing a lockfile.');
  &Apache::lonnet::delenv('docs\\.markedcopy');                      if ($prefix eq 'smppg') {
     }                          $lockerrorsref->{$prefix} .= 
     if ($url=~ m{/smppg$}) {                              &mt('This will prevent creation of additional simple pages in this course.');
  my $db_name = &Apache::lonsimplepage::get_db_name($url);                      } else {
  if ($db_name =~ /^smppage_/) {                          $lockerrorsref->{$prefix} .= &mt('This will prevent creation of additional bulletin boards in this course.');
     #simple pages, need to copy the db contents to a new one.                      }
     my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);                      $lockerrorsref->{$prefix} .= &mt('Please contact the domain coordinator for your LON-CAPA domain.').'</div>';
     my $now = time();                  }
     $db_name =~ s{_\d*$ }{_$now}x;              }
     my $result=&Apache::lonnet::put($db_name,\%contents,          } elsif ($url =~ m{/syllabus$}) {
     $coursedom,$coursenum);              if (($dbref->{'cdom'} =~ /^$match_domain$/) &&
     $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;                  ($dbref->{'cnum'} =~ /^$match_courseid$/)) {
     $title=&mt('Copy of').' '.$title;                  if (($dbref->{'cdom'} ne $coursedom) ||
  }                      ($dbref->{'cnum'} ne $coursenum)) {
     }                      my %contents=&Apache::lonnet::dump('syllabus',
     $title = &LONCAPA::map::qtunescape($title);                                                         $dbref->{'cdom'},
     my $ext='false';                                                         $dbref->{'cnum'});
     if ($url=~m{^http(|s)://}) { $ext='true'; }                      $result=&Apache::lonnet::put('syllabus',\%contents,
     $url       = &LONCAPA::map::qtunescape($url);                                                   $coursedom,$coursenum);
 # Now insert the URL at the bottom                  }
     my $newidx = &LONCAPA::map::getresidx($url);              }
     if ($env{'docs.markedcopy_supplemental'}) {          }
         if ($folder =~ /^supplemental/) {      }
             $title = $env{'docs.markedcopy_supplemental'};      return ($url,$result,$errtext);
         } else {  }
             (undef,undef,$title) =  
                 &parse_supplemental_title($env{'docs.markedcopy_supplemental'});  sub uniqueness_check {
         }      my ($newurl) = @_;
     } else {      my $unique = 1;
         if ($folder=~/^supplemental/) {      foreach my $res (@LONCAPA::map::order) {
            $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
                   $env{'user.domain'}.'___&&&___'.$title;          $url=&LONCAPA::map::qtescape($url);
         }          if ($newurl eq $url) {
     }              $unique = 0;
               last;
     $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';          }
     push(@LONCAPA::map::order, $newidx);      }
     return 'ok';      return $unique;
 # Store the result  }
 }  
   sub contained_map_check {
 sub uniqueness_check {      my ($url,$folder,$removefrommap,$removeparam,$addedmaps,$hierarchy,$titles,
     my ($newurl) = @_;          $allmaps) = @_;
     my $unique = 1;      my $content = &Apache::lonnet::getfile($url);
     foreach my $res (@LONCAPA::map::order) {      unless ($content eq '-1') {
         my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);          my $parser = HTML::TokeParser->new(\$content);
         $url=&LONCAPA::map::qtescape($url);          $parser->attr_encoded(1);
         if ($newurl eq $url) {          while (my $token = $parser->get_token) {
             $unique = 0;              next if ($token->[0] ne 'S');
             last;                  if ($token->[1] eq 'resource') {
         }                  next if ($token->[2]->{'type'} eq 'zombie');
     }                  my $ressrc = $token->[2]->{'src'};
     return $unique;                  if ($folder =~ /^supplemental/) {
 }                      unless (&supp_pasteable($ressrc)) {
                           $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
 my %parameter_type = ( 'randompick'     => 'int_pos',                          next;
        'hiddenresource' => 'string_yesno',                      }
        'encrypturl'     => 'string_yesno',                  }
        'randomorder'    => 'string_yesno',);                  if ($ressrc =~ m{^/(res|uploaded)/.+\.(sequence|page)$}) {
 my $valid_parameters_re = join('|',keys(%parameter_type));                      if ($1 eq 'uploaded') {
 # set parameters                          $hierarchy->{$url}{$token->[2]->{'id'}} = $ressrc;
 sub update_parameter {                          $titles->{$url}{$token->[2]->{'id'}} = $token->[2]->{'title'};
                       } else {
     return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);                          if ($allmaps->{$ressrc}) {
                               $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     my $which = $env{'form.changeparms'};                          } elsif (ref($addedmaps->{$ressrc}) eq 'ARRAY') {
     my $idx = $env{'form.setparms'};                              $removefrommap->{$url}{$token->[2]->{'id'}} = $ressrc;
     if ($env{'form.'.$which.'_'.$idx}) {                          } else {
  my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}                              $addedmaps->{$ressrc} = [$url];
                                      : 'yes';                          }
  &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,                      }
       $parameter_type{$which});                      &contained_map_check($ressrc,$folder,$removefrommap,$removeparam,
  &remember_parms($idx,$which,'set',$value);                                           $addedmaps,$hierarchy,$titles,$allmaps);
     } else {                  }
  &LONCAPA::map::delparameter($idx,'parameter_'.$which);              } elsif ($token->[1] eq 'param') {
                   if ($folder =~ /^supplemental/) {
  &remember_parms($idx,$which,'del');                      if (ref($removeparam->{$url}{$token->[2]->{'to'}}) eq 'ARRAY') {
     }                          push(@{$removeparam->{$url}{$token->[2]->{'to'}}},$token->[2]->{'name'});
     return 1;                      } else {
 }                          $removeparam->{$url}{$token->[2]->{'to'}} = [$token->[2]->{'name'}]; 
                       }
                   }
 sub handle_edit_cmd {              }
     my ($coursenum,$coursedom) =@_;          }
       }
     my ($cmd,$idx)=split('_',$env{'form.cmd'});      return;
   }
     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];  
     my ($title, $url, @rrest) = split(':', $ratstr);  sub url_paste_fixups {
       my ($oldurl,$folder,$prefixchg,$cdom,$cnum,$fromcdom,$fromcnum,$allmaps,
     if ($cmd eq 'del') {          $rewrites,$retitles,$copies,$dbcopies,$zombies,$params,$mapmoves,
  if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&          $mapchanges,$tomove,$newsubdir,$newurls) = @_;
     ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {      my $checktitle;
     &Apache::lonnet::removeuploadedurl($url);      if (($prefixchg) &&
  } else {          ($oldurl =~ m{^/uploaded/$match_domain/$match_courseid/supplemental})) {
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);          $checktitle = 1;
  }      }
  splice(@LONCAPA::map::order, $idx, 1);      my $skip;
       if ($oldurl =~ m{^\Q/uploaded/$cdom/$cnum/\E(default|supplemental)(_?\d*)\.(?:page|sequence)$}) {
     } elsif ($cmd eq 'cut') {          my $mapid = $1.$2;
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);          if ($tomove->{$mapid}) {
  splice(@LONCAPA::map::order, $idx, 1);              $skip = 1;
           }
     } elsif ($cmd eq 'up'      }
      && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {      my $file = &Apache::lonnet::getfile($oldurl);
  @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];      return if ($file eq '-1');
       my $parser = HTML::TokeParser->new(\$file);
     } elsif ($cmd eq 'down'      $parser->attr_encoded(1);
      && defined($LONCAPA::map::order[$idx+1])) {      my $changed = 0;
  @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];      while (my $token = $parser->get_token) {
           next if ($token->[0] ne 'S');
     } elsif ($cmd eq 'rename') {          if ($token->[1] eq 'resource') {
               my $ressrc = $token->[2]->{'src'};
  my $comment = &LONCAPA::map::qtunescape($env{'form.title'});              next if ($ressrc eq '');
  if ($comment=~/\S/) {              my $id = $token->[2]->{'id'};
     $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=              my $title = $token->[2]->{'title'};
  $comment.':'.join(':', $url, @rrest);              if ($checktitle) {
  }                  if ($title =~ m{\d+\Q___&amp;&amp;&amp;___\E$match_username\Q___&amp;&amp;&amp;___\E$match_domain\Q___&amp;&amp;&amp;___\E(.+)$}) {
 # Devalidate title cache                      $retitles->{$oldurl}{$id} = $ressrc;
  my $renamed_url=&LONCAPA::map::qtescape($url);                  }
  &Apache::lonnet::devalidate_title_cache($renamed_url);              }
     } else {              next if ($token->[2]->{'type'} eq 'external');
  return 0;              if ($token->[2]->{'type'} eq 'zombie') {
     }                  next if ($skip);  
     return 1;                  $zombies->{$oldurl}{$id} = $ressrc;
 }                  $changed = 1;
               } elsif ($ressrc =~ m{^/uploaded/($match_domain)/($match_courseid)/(.+)$}) {
 sub editor {                  my $srcdom = $1;
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;                  my $srcnum = $2;
                   my $rem = $3;
     my $container= ($env{'form.pagepath'}) ? 'page'                  my $newurl;
                            : 'sequence';                  my $mapname;
                   if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
     my ($errtext,$fatal) = &mapread($coursenum,$coursedom,                      my $prefix = $1;
     $folder.'.'.$container);                      $mapname = $prefix.$2;
     return $errtext if ($fatal);                      if ($tomove->{$mapname}) {
                           &url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,$cnum,
     if ($#LONCAPA::map::order<1) {                                            $srcdom,$srcnum,$allmaps,$rewrites,
  my $idx=&LONCAPA::map::getresidx();                                            $retitles,$copies,$dbcopies,$zombies,
  if ($idx<=0) { $idx=1; }                                            $params,$mapmoves,$mapchanges,$tomove,
         $LONCAPA::map::order[0]=$idx;                                            $newsubdir,$newurls);
         $LONCAPA::map::resources[$idx]='';                          next;
     }                      } else {
                              ($newurl,my $error) =
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=                              &get_newmap_url($ressrc,$folder,$prefixchg,$cdom,$cnum,
  &breadcrumbs($folder,$allowed,$type);                                              $srcdom,$srcnum,\$title,$allmaps,$newurls);
     $r->print($breadcrumbtrail);                          if ($newurl =~ /(?:default|supplemental)_(\d+)\.(?:sequence|page)$/) {
                                  $newsubdir->{$ressrc} = $1;
 # ------------------------------------------------------------ Process commands                          }
                           if ($error) {
 # ---------------- if they are for this folder and user allowed to make changes                              next;
     if (($allowed) && ($env{'form.folder'} eq $folder)) {                          }
 # set parameters and change order                      }
  &snapshotbefore();                  }
                   if (($srcdom ne $cdom) || ($srcnum ne $cnum) || ($prefixchg) ||
  if (&update_parameter()) {                      ($mapchanges->{$oldurl}) || (($newurl ne '') && ($newurl ne $oldurl))) {
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                     
     return $errtext if ($fatal);                      if ($rem =~ /^(default|supplemental)(_?\d*).(sequence|page)$/) {
  }                          $rewrites->{$oldurl}{$id} = $ressrc;
                           $mapchanges->{$ressrc} = 1;
  if ($env{'form.newpos'} && $env{'form.currentpos'}) {                          unless (&url_paste_fixups($ressrc,$folder,$prefixchg,$cdom,
 # change order                                                    $cnum,$srcdom,$srcnum,$allmaps,
     my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);                                                    $rewrites,$retitles,$copies,$dbcopies,
     splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);                                                    $zombies,$params,$mapmoves,$mapchanges,
                                                     $tomove,$newsubdir,$newurls)) {
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                              $mapmoves->{$ressrc} = 1;
     return $errtext if ($fatal);                          }
  }                          $changed = 1;
                           } else {
  if ($env{'form.pastemarked'}) {                          $rewrites->{$oldurl}{$id} = $ressrc;
             my $paste_res =                          $copies->{$oldurl}{$ressrc} = $id;
                 &do_paste_from_buffer($coursenum,$coursedom,$folder);                          $changed = 1;
             if ($paste_res eq 'ok') {                      }
                 ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);                  }
                 return $errtext if ($fatal);              } elsif ($ressrc =~ m{^/adm/($match_domain)/($match_courseid)/.+$}) {
             } elsif ($paste_res ne '') {                  next if ($skip);
                 $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');                  my $srcdom = $1;
             }                  my $srcnum = $2;
  }                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
                       $rewrites->{$oldurl}{$id} = $ressrc;
  $r->print($upload_output);                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
                       $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
  if (&handle_edit_cmd()) {                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
     ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                      $changed = 1;
     return $errtext if ($fatal);                  }
  }              } elsif ($ressrc =~ m{^/adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$}) {
 # Group import/search                  if (($fromcdom ne $cdom) || ($fromcnum ne $cnum) ||
  if ($env{'form.importdetail'}) {                      ($env{'form.docs.markedcopy_options'} ne 'move')) {
     my @imports;                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
     foreach my $item (split(/\&/,$env{'form.importdetail'})) {                      $dbcopies->{$oldurl}{$id}{'cdom'} = $fromcdom;
  if (defined($item)) {                      $dbcopies->{$oldurl}{$id}{'cnum'} = $fromcnum;
     my ($name,$url,$residx)=                      $changed = 1;
  map {&unescape($_)} split(/\=/,$item);                  }
     push(@imports, [$name, $url, $residx]);              } elsif ($ressrc =~ m{^/public/($match_domain)/($match_courseid)/(.+)$}) {
  }                  next if ($skip);
     }                  my $srcdom = $1;
     ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,                  my $srcnum = $2;
     $container,'londocs',@imports);                  if (($srcdom ne $cdom) || ($srcnum ne $cnum)) {
     return $errtext if ($fatal);                      $dbcopies->{$oldurl}{$id}{'src'} = $ressrc;
  }                      $dbcopies->{$oldurl}{$id}{'cdom'} = $srcdom;
 # Loading a complete map                      $dbcopies->{$oldurl}{$id}{'cnum'} = $srcnum;
  if ($env{'form.loadmap'}) {                      $changed = 1;
     if ($env{'form.importmap'}=~/\w/) {                  }
  foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {              }
     my ($title,$url,$ext,$type)=split(/\:/,$res);          } elsif ($token->[1] eq 'param') {
     my $idx=&LONCAPA::map::getresidx($url);              next if ($skip);
     $LONCAPA::map::resources[$idx]=$res;              my $to = $token->[2]->{'to'}; 
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;              if ($to ne '') {
  }                  if (ref($params->{$oldurl}{$to}) eq 'ARRAY') {
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,                      push(@{$params->{$oldurl}{$to}},$token->[2]->{'name'});
     $folder.'.'.$container);                  } else {
  return $errtext if ($fatal);                      @{$params->{$oldurl}{$to}} = ($token->[2]->{'name'});
     } else {                  }
  $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');              }
           }
     }      }
  }      return $changed;
  &log_differences($plain);  }
     }  
 # ---------------------------------------------------------------- End commands  sub apply_fixups {
 # ---------------------------------------------------------------- Print screen      my ($folder,$is_map,$cdom,$cnum,$errors,$updated,$info,$moves,$prefixchg,
     my $idx=0;          $oldurl,$url,$caller) = @_;
     my $shown=0;      my (%rewrites,%zombies,%removefrommap,%removeparam,%dbcopies,%retitles,
     if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {          %params,%newsubdir,%before,%after,%copies,%docmoves,%mapmoves,@msgs,
  $r->print('<p>'.&mt('Parameters').':<ul>'.          %lockerrors,$lockmsg);
   ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').      if (ref($updated) eq 'HASH') {
   ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').          if (ref($updated->{'rewrites'}) eq 'HASH') {
   ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').              %rewrites = %{$updated->{'rewrites'}};
   '</ul></p>');          }
     }                                                                                                              if (ref($updated->{'zombies'}) eq 'HASH') {
     if ($randompick>=0) {              %zombies = %{$updated->{'zombies'}};
  $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->{'removefrommap'}) eq 'HASH') {
     if ($is_random_order) {              %removefrommap = %{$updated->{'removefrommap'}};
  $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->{'removeparam'}) eq 'HASH') {
     $r->print('<table class="LC_docs_editor">');              %removeparam = %{$updated->{'removeparam'}};
     foreach my $res (@LONCAPA::map::order) {          }
  my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);          if (ref($updated->{'dbcopies'}) eq 'HASH') {
  $name=&LONCAPA::map::qtescape($name);              %dbcopies = %{$updated->{'dbcopies'}};
  $url=&LONCAPA::map::qtescape($url);          }
  unless ($name) {  $name=(split(/\//,$url))[-1]; }          if (ref($updated->{'retitles'}) eq 'HASH') {
  unless ($name) { $idx++; next; }              %retitles = %{$updated->{'retitles'}};
  $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,          }
      $coursenum));      }
  $idx++;      if (ref($info) eq 'HASH') {
  $shown++;          if (ref($info->{'newsubdir'}) eq 'HASH') {
     }              %newsubdir = %{$info->{'newsubdir'}};
     unless ($shown) {          }
  $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');          if (ref($info->{'params'}) eq 'HASH') {
     }              %params = %{$info->{'params'}};
     $r->print("\n</table>\n");          }
     if ($allowed) {          if (ref($info->{'before'}) eq 'HASH') {
         &print_paste_buffer($r,$container);              %before = %{$info->{'before'}};
     }          }
     return;          if (ref($info->{'after'}) eq 'HASH') {
 }              %after = %{$info->{'after'}};
           }
 sub process_file_upload {      }
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;      if (ref($moves) eq 'HASH') {
 # upload a file, if present          if (ref($moves->{'copies'}) eq 'HASH') {
     my $parseaction;              %copies = %{$moves->{'copies'}};
    if ($env{'form.parserflag'}) {          }
         $parseaction = 'parse';          if (ref($moves->{'docmoves'}) eq 'HASH') {
     }              %docmoves = %{$moves->{'docmoves'}};
     my $phase_status;          }
     my $folder=$env{'form.folder'};          if (ref($moves->{'mapmoves'}) eq 'HASH') {
     if ($folder eq '') {              %mapmoves = %{$moves->{'mapmoves'}};
         $folder='default';          }
     }      }
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {      foreach my $key (keys(%copies),keys(%docmoves)) {
         my $errtext='';          my @allcopies;
         my $fatal=0;          if (exists($copies{$key})) {
         my $container='sequence';              if (ref($copies{$key}) eq 'HASH') {
         if ($env{'form.pagepath'}) {                  my %added;
             $container='page';                  foreach my $innerkey (keys(%{$copies{$key}})) {
         }                      if (($innerkey ne '') && (!$added{$innerkey})) {
         ($errtext,$fatal)=                          push(@allcopies,$innerkey);
               &mapread($coursenum,$coursedom,$folder.'.'.$container);                          $added{$innerkey} = 1;
         if ($#LONCAPA::map::order<1) {                      }
             $LONCAPA::map::order[0]=1;                  }
             $LONCAPA::map::resources[1]='';                  undef(%added);
         }              }
         if ($fatal) {          }
             return 'failed';          if ($key eq $oldurl) {
         }              if ((exists($docmoves{$key}))) {
         my $destination = 'docs/';                  unless (grep(/^\Q$oldurl\E$/,@allcopies)) {
         if ($folder =~ /^supplemental/) {                      push(@allcopies,$oldurl);
             $destination = 'supplemental/';                  }
         }              }
         if (($folder eq 'default') || ($folder eq 'supplemental')) {          }
             $destination .= 'default/';          if (@allcopies > 0) {
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {              foreach my $item (@allcopies) {
             $destination .=  $2.'/';                  my ($relpath,$oldsubdir,$fname) = 
         }                      ($item =~ m{^(/uploaded/$match_domain/$match_courseid/(?:docs|supplemental)/(default|\d+)/.*/)([^/]+)$});
 # this is for a course, not a user, so set coursedoc flag                  if ($fname ne '') {
 # probably the only place in the system where this should be "1"                      my $content = &Apache::lonnet::getfile($item);
         my $newidx=&LONCAPA::map::getresidx();                      unless ($content eq '-1') {
         $destination .= $newidx;                          my $storefn;
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,                          if (($key eq $oldurl) && (exists($docmoves{$key}))) {
  $parseaction,$allfiles,                              $storefn = $docmoves{$key};
  $codebase);                          } else {
         my $ext='false';                              $storefn = $relpath;
         if ($url=~m{^http://}) { $ext='true'; }                              $storefn =~s{^/uploaded/$match_domain/$match_courseid/}{};
  $url     = &LONCAPA::map::qtunescape($url);                              if ($prefixchg && $before{'doc'} && $after{'doc'}) {
         my $comment=$env{'form.comment'};                                  $storefn =~ s/^\Q$before{'doc'}\E/$after{'doc'}/;
  $comment = &LONCAPA::map::qtunescape($comment);                              }
         if ($folder=~/^supplemental/) {                              if ($newsubdir{$key}) {
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.                                  $storefn =~ s#^(docs|supplemental)/\Q$oldsubdir\E/#$1/$newsubdir{$key}/#;
                   $env{'user.domain'}.'___&&&___'.$comment;                              }
         }                          }
                           &copy_dependencies($item,$storefn,$relpath,$errors,\$content);
         $LONCAPA::map::resources[$newidx]=                          my $copyurl = 
     $comment.':'.$url.':'.$ext.':normal:res';                              &Apache::lonclonecourse::writefile($env{'request.course.id'},
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;                                                                 $storefn.$fname,$content);
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,                          if ($copyurl eq '/adm/notfound.html') {
     $folder.'.'.$container);                              if (exists($docmoves{$oldurl})) {
         if ($fatal) {                                  return &mt('Paste failed: an error occurred copying the file.');
             $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';                              } elsif (ref($errors) eq 'HASH') {
             return 'failed';                                  $errors->{$item} = 1;
         } else {                              }
             if ($parseaction eq 'parse') {                          }
                 my $total_embedded = keys(%{$allfiles});                      }
                 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" />      foreach my $key (keys(%mapmoves)) {
    <input type="hidden" name="newidx" value="'.$newidx.'" />          my $storefn=$key;
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />          $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';          if ($prefixchg && $before{'map'} && $after{'map'}) {
     $phase_status = 'phasetwo';              $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
           }
                     $$upload_output .=          if ($newsubdir{$key}) {
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.              $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
  &Apache::loncommon::ask_for_embedded_content(          }
                             '/adm/coursedocs',$state,$allfiles,$codebase);          my $mapcontent = &Apache::lonnet::getfile($key);
                 } else {          if ($mapcontent eq '-1') {
                     $$upload_output .= 'No embedded items identified<br />';              if (ref($errors) eq 'HASH') {
                 }                  $errors->{$key} = 1;
             }              }
         }          } else {
     }              my $newmap =
     return $phase_status;                  &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
 }                                                     $mapcontent);
               if ($newmap eq '/adm/notfound.html') {
 sub process_secondary_uploads {                  if (ref($errors) eq 'HASH') {
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;                      $errors->{$key} = 1;
     my $folder=$env{'form.folder'};                  }
     my $destination = 'docs/';              }
     if ($folder =~ /^supplemental/) {          }
         $destination = 'supplemental/';      }
     }      my %updates;
     if (($folder eq 'default') || ($folder eq 'supplemental')) {      if ($is_map) {
         $destination .= 'default/';          if (ref($updated) eq 'HASH') {
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {              foreach my $type (keys(%{$updated})) {
         $destination .=  $2.'/';                  if (ref($updated->{$type}) eq 'HASH') {
     }                      foreach my $key (keys(%{$updated->{$type}})) {
     $destination .= $newidx;                          $updates{$key} = 1;
     my ($url,$filename);                      }
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);                  }
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});              }
     return $filename;          }
 }          foreach my $key (keys(%updates)) {
               my (%torewrite,%toretitle,%toremove,%remparam,%currparam,%zombie,%newdb);
 sub is_supplemental_title {              if (ref($rewrites{$key}) eq 'HASH') {
     my ($title) = @_;                  %torewrite = %{$rewrites{$key}};
     return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);              }
 }              if (ref($retitles{$key}) eq 'HASH') {
                   %toretitle = %{$retitles{$key}};
 sub parse_supplemental_title {              }
     my ($title) = @_;              if (ref($removefrommap{$key}) eq 'HASH') {
                   %toremove = %{$removefrommap{$key}};
     my ($foldertitle,$renametitle);              }
     if ($title =~ /&amp;&amp;&amp;/) {              if (ref($removeparam{$key}) eq 'HASH') {
  $title = &HTML::Entites::decode($title);                  %remparam = %{$removeparam{$key}};
     }              }
  if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {              if (ref($zombies{$key}) eq 'HASH') {
  $renametitle=$4;                  %zombie = %{$zombies{$key}};
  my ($time,$uname,$udom) = ($1,$2,$3);              }
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);              if (ref($dbcopies{$key}) eq 'HASH') {
  my $name =  &Apache::loncommon::plainname($uname,$udom);                  foreach my $idx (keys(%{$dbcopies{$key}})) {
  $name = &HTML::Entities::encode($name,'"<>&\'');                      if (ref($dbcopies{$key}{$idx}) eq 'HASH') {
  $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.                          my ($newurl,$result,$errtext) =
     $name.': <br />'.$foldertitle;                              &dbcopy($dbcopies{$key}{$idx},$cdom,$cnum,\%lockerrors);
     }                          if ($result eq 'ok') {
     if (wantarray) {                              $newdb{$idx} = $newurl;
  return ($title,$foldertitle,$renametitle);                          } elsif (ref($errors) eq 'HASH') {
     }                              $errors->{$key} = 1;
     return $title;                          }
 }                          push(@msgs,$errtext);
                       }
 # --------------------------------------------------------------- An entry line                  }
               }
 sub entryline {              if (ref($params{$key}) eq 'HASH') {
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;                  %currparam = %{$params{$key}};
               }
     my ($foldertitle,$pagetitle,$renametitle);              my ($errtext,$fatal) = &LONCAPA::map::mapread($key);
     if (&is_supplemental_title($title)) {              if ($fatal) {
  ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);                  return ($errtext);
  $pagetitle = $foldertitle;              }
     } else {              for (my $i=0; $i<@LONCAPA::map::zombies; $i++) {
  $title=&HTML::Entities::encode($title,'"<>&\'');                  if (defined($LONCAPA::map::zombies[$i])) {
  $renametitle=$title;                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::zombies[$i]);
  $foldertitle=$title;                      if ($zombie{$i} eq $src) {
  $pagetitle=$title;                          undef($LONCAPA::map::zombies[$i]);
     }                      }
                   }
     my $orderidx=$LONCAPA::map::order[$index];              }
                  for (my $i=0; $i<@LONCAPA::map::order; $i++) {
                   my $idx = $LONCAPA::map::order[$i];
     $renametitle=~s/\\/\\\\/g;                  if (defined($LONCAPA::map::resources[$idx])) {
     $renametitle=~s/\&quot\;/\\\"/g;                      my $changed;
     $renametitle=~s/ /%20/g;                      my ($title,$src,$ext,$type)=split(/\:/,$LONCAPA::map::resources[$idx]);
     my $line='<tr>';                      if ((exists($toremove{$idx})) && ($toremove{$idx} eq $src)) {
     my ($form_start,$form_end);                          splice(@LONCAPA::map::order,$i,1);
 # Edit commands                          if (ref($currparam{$idx}) eq 'ARRAY') {
     my ($container, $type, $esc_path, $path, $symb);                              foreach my $name (@{$currparam{$idx}}) {
     if ($env{'form.folderpath'}) {                                  &LONCAPA::map::delparameter($idx,'parameter_'.$name);
  $type = 'folder';                              }
         $container = 'sequence';                          }
  $esc_path=&escape($env{'form.folderpath'});                          next;
  $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');                      }
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                      my $origsrc = $src;
     }                      if ((exists($toretitle{$idx})) && ($toretitle{$idx} eq $src)) {
     if ($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(.+)$}) {
         $type = $container = 'page';                              $changed = 1;
         $esc_path=&escape($path = $env{'form.pagepath'});                          }
  $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');                      }
         $symb=&escape($env{'form.pagesymb'});                      if ((exists($torewrite{$idx})) && ($torewrite{$idx} eq $src)) {
     }                          $src =~ s{^/(uploaded|adm|public)/$match_domain/$match_courseid/}{/$1/$cdom/$cnum/};
     my $cpinfo='';                          if ($origsrc =~ m{^/uploaded/}) {
     if ($allowed) {                              if ($prefixchg && $before{'map'} && $after{'map'}) {
  my $incindex=$index+1;                                  if ($src =~ /\.(page|sequence)$/) {
  my $selectbox='';                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'map'}\E#$1$after{'map'}#;
  if (($folder!~/^supplemental/) &&                                  } else {
     ($#LONCAPA::map::order>0) &&                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/)\Q$before{'doc'}\E#$1$after{'doc'}#;
     ((split(/\:/,                                  }
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]                              }
      ne '') &&                              if ($origsrc =~ /\.(page|sequence)$/) {
     ((split(/\:/,                                  if ($newsubdir{$origsrc}) {
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]                                      $src =~ s#^(/uploaded/$match_domain/$match_courseid/(?:default|supplemental)_)(\d+)#$1$newsubdir{$origsrc}#;
      ne '')) {                                  }
     $selectbox=                              } elsif ($newsubdir{$key}) {
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.                                  $src =~ s#^(/uploaded/$match_domain/$match_courseid/\w+/)(\d+)#$1$newsubdir{$key}#;
  '<select name="newpos" onChange="this.form.submit()">';                              }
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {                          }
  if ($i==$incindex) {                          $changed = 1;
     $selectbox.='<option value="" selected="1">('.$i.')</option>';                      } elsif ($newdb{$idx} ne '') {
  } else {                          $src = $newdb{$idx};
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';                          $changed = 1;
  }                      }
     }                      if ($changed) {
     $selectbox.='</select>';                          $LONCAPA::map::resources[$idx] = join(':',($title,$src,$ext,$type));
  }                      }
  my %lt=&Apache::lonlocal::texthash(                  }
                 'up' => 'Move Up',              }
  'dw' => 'Move Down',              foreach my $idx (keys(%remparam)) {
  'rm' => 'Remove',                  if (ref($remparam{$idx}) eq 'ARRAY') {
                 'ct' => 'Cut',                      foreach my $name (@{$remparam{$idx}}) {   
  'rn' => 'Rename',                          &LONCAPA::map::delparameter($idx,'parameter_'.$name);
  'cp' => 'Copy');                      }
  my $nocopy=0;                  }
         my $nocut=0;              }
         if ($url=~/\.(page|sequence)$/) {              if (values(%lockerrors) > 0) {
     if ($url =~ m{/res/}) {                  $lockmsg = join('<br />',values(%lockerrors));
  # no copy for published maps              }
  $nocopy = 1;              my $storefn;
     } else {              if ($key eq $oldurl) {
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {                  $storefn = $url;
     my ($title,$url,$ext,$type)=split(/\:/,$item);                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {              } else {
  $nocopy=1;                  $storefn = $key;
  last;                  $storefn=~s{^/uploaded/$match_domain/$match_courseid/}{};
     }                  if ($prefixchg && $before{'map'} && $after{'map'}) {
  }                      $storefn =~ s/^\Q$before{'map'}\E/$after{'map'}/;
     }                  }
  }                  if ($newsubdir{$key}) {
         if ($url=~/^\/res\/lib\/templates\//) {                      $storefn =~ s/^((?:default|supplemental)_)(\d+)/$1$newsubdir{$key}/;
            $nocopy=1;                  }
            $nocut=1;              }
         }              my $report;
         my $copylink='&nbsp;';              if ($folder !~ /^supplemental/) {
         my $cutlink='&nbsp;';                  $report = 1;
               }
  my $skip_confirm = 0;              (my $outtext,$errtext) =
  if ( $folder =~ /^supplemental/                  &LONCAPA::map::storemap("/uploaded/$cdom/$cnum/$storefn",1,$report);
      || ($url =~ m{( /smppg$              if ($errtext) {
     |/syllabus$                  if ($caller eq 'paste') {
     |/aboutme$                      return (&mt('Paste failed: an error occurred saving the folder or page.'));
     |/navmaps$                  }
     |/bulletinboard$              }
     |\.html$          }
     |^/adm/wrapper/ext)}x)) {      }
     $skip_confirm = 1;      return ('ok',\@msgs,$lockmsg);
  }  }
   
  if (!$nocopy) {  sub copy_dependencies {
     $copylink=(<<ENDCOPY);      my ($item,$storefn,$relpath,$errors,$contentref) = @_;
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>      my $content;
 ENDCOPY      if (ref($contentref)) {
         }          $content = $$contentref;
  if (!$nocut) {      } else {
     $cutlink=(<<ENDCUT);          $content = &Apache::lonnet::getfile($item);
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>      }
 ENDCUT      unless ($content eq '-1') {
         }          my $mm = new File::MMagic;
  $form_start = (<<END);          my $mimetype = $mm->checktype_contents($content);
    <form  action="/adm/coursedocs" method="post">          if ($mimetype eq 'text/html') {
    <input type="hidden" name="${type}path" value="$path" />              my (%allfiles,%codebase,$state);
    <input type="hidden" name="${type}symb" value="$symb" />              my $res = &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,\$content);
    <input type="hidden" name="setparms" value="$orderidx" />              if ($res eq 'ok') {
    <input type="hidden" name="changeparms" value="0" />                  my ($numexisting,$numpathchanges,$existing);
 END                  (undef,$numexisting,$numpathchanges,$existing) =
         $form_end = '</form>';                      &Apache::loncommon::ask_for_embedded_content(
  $line.=(<<END);                          '/adm/coursedocs',$state,\%allfiles,\%codebase,
 <td>                          {'error_on_invalid_names'   => 1,
    <table class="LC_docs_entry_move">                           'ignore_remote_references' => 1,
       <tr>                           'docs_url'                 => $item,
          <td>                           'context'                  => 'paste'});
             <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>                  if ($numexisting > 0) {
          </td>                      if (ref($existing) eq 'HASH') {
       </tr>                          foreach my $dep (keys(%{$existing})) {
       <tr>                              my $depfile = $dep;
         <td>                              unless ($depfile =~ m{^\Q$relpath\E}) {
            <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>                                  $depfile = $relpath.$dep;
         </td>                              }
       </tr>                              my $depcontent = &Apache::lonnet::getfile($depfile);
     </table>                              unless ($depcontent eq '-1') {
 </td>                                  my $storedep = $dep;
 <td>                                  $storedep =~ s{^\Q$relpath\E}{};
    $form_start                                  my $dep_url =
    $selectbox                                      &Apache::lonclonecourse::writefile(
    $form_end                                          $env{'request.course.id'},
 </td>                                          $storefn.$storedep,$depcontent);
 <td class="LC_docs_entry_commands">                                  if ($dep_url eq '/adm/notfound.html') {
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>                                      if (ref($errors) eq 'HASH') {
 $cutlink                                          $errors->{$depfile} = 1;
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>                                      }
 $copylink                                  } else {
 </td>                                      &copy_dependencies($depfile,$storefn,$relpath,$errors,\$depcontent);
 END                                  }
                               }
     }                          }
 # 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;      return;
     my $folderarg;  }
     my $pagearg;  
     my $pagefile;  my %parameter_type = ( 'randompick'     => 'int_pos',
     if ($uploaded) {         'hiddenresource' => 'string_yesno',
  if ($extension eq 'sequence') {         'encrypturl'     => 'string_yesno',
     $icon=$iconpath.'/folder_closed.gif';         'randomorder'    => 'string_yesno',);
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;  my $valid_parameters_re = join('|',keys(%parameter_type));
     $url='/adm/coursedocs?';  # set parameters
     $folderarg=$1;  sub update_parameter {
     $isfolder=1;      if ($env{'form.changeparms'} eq 'all') {
         } elsif ($extension eq 'page') {          my (@allidx,@allmapidx,%allchecked,%currchecked);
             $icon=$iconpath.'/page.gif';          %allchecked = (
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;                           'hiddenresource' => {},
             $pagearg=$1;                           'encrypturl'     => {},
             $url='/adm/coursedocs?';                           'randompick'     => {},
             $ispage=1;                           'randomorder'    => {},
  } else {                        );
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);          foreach my $which (keys(%allchecked)) {
  }              $env{'form.all'.$which} =~ s/,$//;   
     }              if ($which eq 'randompick') {
                      foreach my $item (split(/,/,$env{'form.all'.$which})) {
     my $orig_url = $url;                      my ($res,$value) = split(/:/,$item);
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});                      if ($value =~ /^\d+$/) {
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {                          $allchecked{$which}{$res} = $value;
  my $symb=&Apache::lonnet::symbclean(                      }
           &Apache::lonnet::declutter('uploaded/'.                  }
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.              } else {
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.                  map { $allchecked{$which}{$_} = 1; } split(/,/,$env{'form.all'.$which});
            '.sequence').              }
            '___'.$residx.'___'.          }
    &Apache::lonnet::declutter($url));          my $haschanges = 0;
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);          foreach my $res (@LONCAPA::map::order) {
  $url=&Apache::lonnet::clutter($url);              my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  if ($url=~/^\/*uploaded\//) {              $name=&LONCAPA::map::qtescape($name);
     $url=~/\.(\w+)$/;              $url=&LONCAPA::map::qtescape($url);
     my $embstyle=&Apache::loncommon::fileembstyle($1);              next unless ($name && $url);
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {              my $is_map;
  $url='/adm/wrapper'.$url;              if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
     } elsif ($embstyle eq 'ssi') {                  $is_map = 1;
  #do nothing with these              }
     } elsif ($url!~/\.(sequence|page)$/) {              foreach my $which (keys(%allchecked)) {
  $url='/adm/coursedocs/showdoc'.$url;                  if (($which eq 'randompick' || $which eq 'randomorder')) {
     }                      next if (!$is_map);
  } elsif ($url=~m|^/ext/|) {                  } 
     $url='/adm/wrapper'.$url;                  my $oldvalue = 0;
     $external = 1;                  my $newvalue = 0;
  }                  if ($allchecked{$which}{$res}) {
         if (&Apache::lonnet::symbverify($symb,$url)) {                      $newvalue = $allchecked{$which}{$res};
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                  }
         } else {                  my $current = (&LONCAPA::map::getparameter($res,'parameter_'.$which))[0];
             $url='';                  if ($which eq 'randompick') {
         }                      if ($current =~ /^(\d+)$/) {
  if ($container eq 'page') {                          $oldvalue = $1;
     my $symb=$env{'form.pagesymb'};                      }
                           } else {
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);                      if ($current =~ /^yes$/i) {
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);                          $oldvalue = 1;
  }                      }
     }                  }
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');                  if ($oldvalue ne $newvalue) {
     if ($isfolder || $extension eq 'sequence') {                      $haschanges = 1;
  my $foldername=&escape($foldertitle);                      if ($newvalue) {
  my $folderpath=$env{'form.folderpath'};                          my $storeval = 'yes';
  if ($folderpath) { $folderpath.='&' };                          if ($which eq 'randompick') {
 # Append randompick number, hidden, and encrypted with ":" to foldername,                              $storeval = $newvalue;
 # so it gets transferred between levels                          }
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,                          &LONCAPA::map::storeparameter($res,'parameter_'.$which,
                                               'parameter_randompick'))[0]                                                        $storeval,
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                                                        $parameter_type{$which});
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)                          &remember_parms($res,$which,'set',$storeval);
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                      } elsif ($oldvalue) {
                                               'parameter_encrypturl'))[0]=~/^yes$/i)                          &LONCAPA::map::delparameter($res,'parameter_'.$which);
                                                .':'.((&LONCAPA::map::getparameter($orderidx,                          &remember_parms($res,$which,'del');
                                               'parameter_randomorder'))[0]=~/^yes$/i);                      }
  $url.='folderpath='.&escape($folderpath).$cpinfo;                  }
  $parameterset='<label>'.&mt('Randomly Pick: ').              }
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.          }
     (&LONCAPA::map::getparameter($orderidx,          return $haschanges;
                                               'parameter_randompick'))[0].      } else {
                                               '" />'.          return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';  
     my $ro_set=          my $which = $env{'form.changeparms'};
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');          my $idx = $env{'form.setparms'};
  $rand_order_text ='          if ($env{'form.'.$which.'_'.$idx}) {
 <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 $value = ($which eq 'randompick') ? $env{'form.rpicknum_'.$idx}
     }                                           : 'yes';
     if ($ispage) {      &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
         my $pagename=&escape($pagetitle);            $parameter_type{$which});
         my $pagepath;      &remember_parms($idx,$which,'set',$value);
         my $folderpath=$env{'form.folderpath'};          } else {
         if ($folderpath) { $pagepath = $folderpath.'&' };      &LONCAPA::map::delparameter($idx,'parameter_'.$which);
         $pagepath.=$pagearg.'&'.$pagename;  
  my $symb=$env{'form.pagesymb'};      &remember_parms($idx,$which,'del');
  if (!$symb) {          }
     my $path='uploaded/'.          return 1;
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.      }
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';  }
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',  
        $residx,  
        $path.$pagearg.'.page');  sub handle_edit_cmd {
  }      my ($coursenum,$coursedom) =@_;
  $url.='pagepath='.&escape($pagepath).      my ($cmd,$idx)=split('_',$env{'form.cmd'});
     '&amp;pagesymb='.&escape($symb).$cpinfo;  
     }      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     if ($external) {      my ($title, $url, @rrest) = split(':', $ratstr);
  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>';      if ($cmd eq 'del') {
     } else {   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  undef($external);      ($url!~/$LONCAPA::assess_page_seq_re/)) {
     }      &Apache::lonnet::removeuploadedurl($url);
     $line.='   } else {
   <td class="LC_docs_entry_icon">      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'   }
   </td>   splice(@LONCAPA::map::order, $idx, 1);
   <td class="LC_docs_entry_title">  
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."      } elsif ($cmd eq 'cut') {
   </td>";   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     if (($allowed) && ($folder!~/^supplemental/)) {   splice(@LONCAPA::map::order, $idx, 1);
   my %lt=&Apache::lonlocal::texthash(  
        'hd' => 'Hidden',      } elsif ($cmd eq 'up'
        'ec' => 'URL hidden');       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
  my $enctext=   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');  
  my $hidtext=      } elsif ($cmd eq 'down'
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');       && defined($LONCAPA::map::order[$idx+1])) {
  $line.=(<<ENDPARMS);   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
   <td class="LC_docs_entry_parameter">  
     $form_start      } elsif ($cmd eq 'rename') {
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>  
     $form_end   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
   </td>   if ($comment=~/\S/) {
   <td class="LC_docs_entry_parameter">      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
     $form_start   $comment.':'.join(':', $url, @rrest);
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>   }
     $form_end  # Devalidate title cache
   </td>   my $renamed_url=&LONCAPA::map::qtescape($url);
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>   &Apache::lonnet::devalidate_title_cache($renamed_url);
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>      } else {
 ENDPARMS   return 0;
     }      }
     $line.="</tr>";      return 1;
     return $line;  }
 }  
   sub editor {
 =pod      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$crstype,
           $supplementalflag,$orderhash,$iconpath,$pathitem)=@_;
 =item tiehash()      my ($randompick,$ishidden,$isencrypted,$plain,$is_random_order,$container);
       if ($allowed) {
 tie the hash          (my $breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,
            $is_random_order,$container) =
 =cut              &Apache::lonhtmlcommon::docs_breadcrumbs($allowed,$crstype,1);
           $r->print($breadcrumbtrail);
 sub tiehash {      } elsif ($env{'form.folderpath'} =~ /\:1$/) {
     my ($mode)=@_;          $container = 'page'; 
     $hashtied=0;      } else {
     if ($env{'request.course.fn'}) {          $container = 'sequence';
  if ($mode eq 'write') {      }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",  
     &GDBM_WRCREAT(),0640)) {      my $jumpto;
                 $hashtied=2;  
     }      unless ($supplementalflag) {
  } else {          $jumpto = "'uploaded/$coursedom/$coursenum/$folder.$container'";
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      }
     &GDBM_READER(),0640)) {  
                 $hashtied=1;      unless ($allowed) {
     }          $randompick = -1;
  }      }
     }      
 }      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
       $folder.'.'.$container);
 sub untiehash {      return $errtext if ($fatal);
     if ($hashtied) { untie %hash; }  
     $hashtied=0;      if ($#LONCAPA::map::order<1) {
     return OK;   my $idx=&LONCAPA::map::getresidx();
 }   if ($idx<=0) { $idx=1; }
           $LONCAPA::map::order[0]=$idx;
           $LONCAPA::map::resources[$idx]='';
       }
   
 sub checkonthis {  # ------------------------------------------------------------ Process commands
     my ($r,$url,$level,$title)=@_;  
     $url=&unescape($url);  # ---------------- if they are for this folder and user allowed to make changes
     $alreadyseen{$url}=1;      if (($allowed) && ($env{'form.folder'} eq $folder)) {
     $r->rflush();  # set parameters and change order
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {   &snapshotbefore();
        $r->print("\n<br />");  
        if ($level==0) {   if (&update_parameter()) {
            $r->print("<br />");      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
        }      return $errtext if ($fatal);
        for (my $i=0;$i<=$level*5;$i++) {   }
            $r->print('&nbsp;');  
        }   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
        $r->print('<a href="'.$url.'" target="cat">'.  # change order
  ($title?$title:$url).'</a> ');      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
        if ($url=~/^\/res\//) {      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
   my $result=&Apache::lonnet::repcopy(  
                               &Apache::lonnet::filelocation('',$url));      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
           if ($result eq 'ok') {      return $errtext if ($fatal);
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');   }
              $r->rflush();  
              &Apache::lonnet::countacc($url);   if ($env{'form.pastemarked'}) {
              $url=~/\.(\w+)$/;              my %paste_errors;
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {              my ($paste_res,$save_error,$pastemsgarray,$lockerror) =
  $r->print('<br />');                  &do_paste_from_buffer($coursenum,$coursedom,$folder,$container,
                  $r->rflush();                                        \%paste_errors);
                  for (my $i=0;$i<=$level*5;$i++) {                  if (ref($pastemsgarray) eq 'ARRAY') {
                      $r->print('&nbsp;');                      if (@{$pastemsgarray} > 0) {
                  }                            
                  $r->print('- '.&mt('Rendering:').' ');                          $r->print('<p class="LC_info">'.
  my ($errorcount,$warningcount)=split(/:/,                                    join('<br />',@{$pastemsgarray}).
        &Apache::lonnet::ssi_body($url,                                    '</p>');
        ('grade_target'=>'web',                      }
  'return_only_error_and_warning_counts' => 1)));                  }
                  if (($errorcount) ||                  if ($lockerror) {
                      ($warningcount)) {                      $r->print('<p class="LC_error">'.
      if ($errorcount) {                                $lockerror.
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.                                '</p>');
                           &mt('[quant,_1,error]',$errorcount).'</span>');                  }
                      }                  if ($save_error ne '') {
      if ($warningcount) {                      return $save_error; 
                         $r->print('<span class="LC_warning">'.                  }
                           &mt('[quant,_1,warning]',$warningcount).'</span>');              if ($paste_res ne 'ok') {
                      }                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
                  } else {              }
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');              if (keys(%paste_errors) > 0) {
                  }                  $r->print('<p span class="LC_warning">'."\n".
                  $r->rflush();                            &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".
              }                            '<ul>'."\n");
      my $dependencies=                  foreach my $key (sort(keys(%paste_errors))) {
                 &Apache::lonnet::metadata($url,'dependencies');                      $r->print('<li>'.$key.'</li>'."\n");
              foreach my $dep (split(/\,/,$dependencies)) {                  }
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {                  $r->print('</ul></p>'."\n");
                     &checkonthis($r,$dep,$level+1);              }
                  }   }
              }  
           } elsif ($result eq 'unavailable') {   $r->print($upload_output);
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');  
           } elsif ($result eq 'not_found') {   if (&handle_edit_cmd()) {
       unless ($url=~/\$/) {              my $contentchg;
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');              if ($env{'form.cmd'} =~ /^(del|cut)_/) {
       } else {                  $contentchg = 1;
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');              }
       }      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container,$contentchg);
           } else {      return $errtext if ($fatal);
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');   }
           }  # Group import/search
        }   if ($env{'form.importdetail'}) {
     }      my @imports;
 }      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
    if (defined($item)) {
       my ($name,$url,$residx)=
    map { &unescape($_); } split(/\=/,$item);
 =pod                      if ($url =~ m{^\Q/uploaded/$coursedom/$coursenum/\E(default|supplemental)_new\.(sequence|page)$}) {
                           my ($suffix,$errortxt,$locknotfreed) =
 =item list_symbs()                              &new_timebased_suffix($coursedom,$coursenum,'map',$1,$2);
                           if ($locknotfreed) {
 List Symbs                              $r->print($locknotfreed);
                           }
 =cut                          if ($suffix) {
                               $url =~ s/_new\./_$suffix./; 
 sub list_symbs {                          } else {
     my ($r) = @_;                              return $errortxt;
                           }
     my $type = &Apache::loncommon::course_type();                      } elsif ($url =~ m{^/adm/$match_domain/$match_username/new/(smppg|bulletinboard)$}) {
     $r->print(&Apache::loncommon::start_page('Symb List'));                          my $type = $1;
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));                          my ($suffix,$errortxt,$locknotfreed) =
     my $navmap = Apache::lonnavmaps::navmap->new();                              &new_timebased_suffix($coursedom,$coursenum,$type);
     if (!defined($navmap)) {                          if ($locknotfreed) {
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.                              $r->print($locknotfreed);
                   '<div class="LC_error">'.                          }
                   &mt('Unable to retrieve information about course contents').                          if ($suffix) {
                   '</div>');                              $url =~ s{^(/adm/$match_domain/$match_username)/new}{$1/$suffix};
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});                          } else {
     } else {                              return $errortxt;
         $r->print("<pre>\n");                          }
         foreach my $res ($navmap->retrieveResources()) {                      } elsif ($url =~ m{^/uploaded/$coursedom/$coursenum/(docs|supplemental)/(default|\d+)/new.html$}) {
     $r->print($res->compTitle()."\t".$res->symb()."\n");                          if ($supplementalflag) {
         }                              next unless ($1 eq 'supplemental');
         $r->print("\n</pre>\n");                              if ($folder eq 'supplemental') {
     }                                  next unless ($2 eq 'default');
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');                              } else {
 }                                  next unless ($folder eq 'supplemental_'.$2);
                               }
                           } else {
 sub verifycontent {                              next unless ($1 eq 'docs');
     my ($r) = @_;                              if ($folder eq 'default') {
     my $type = &Apache::loncommon::course_type();                                  next unless ($2 eq 'default');
    my $loaderror=&Apache::lonnet::overloaderror($r);                              } else {
    if ($loaderror) { return $loaderror; }                                  next unless ($folder eq 'default_'.$2);
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));                              }
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));                          }
    $hashtied=0;                      }
    undef %alreadyseen;      push(@imports, [$name, $url, $residx]);
    %alreadyseen=();   }
    &tiehash();      }
    foreach my $key (keys(%hash)) {              ($errtext,$fatal,my $fixuperrors) =
        if ($hash{$key}=~/\.(page|sequence)$/) {                  &group_import($coursenum, $coursedom, $folder,$container,
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {                                'londocs',@imports);
        $r->print('<hr /><span class="LC_error">'.      return $errtext if ($fatal);
  &mt('The following sequence or page is included more than once in your '.$type.': ').              if ($fixuperrors) {
  &unescape($hash{$key}).'</span><br />'.                  $r->print($fixuperrors);
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));              }
    }   }
        }  # Loading a complete map
        if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {   if ($env{'form.loadmap'}) {
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});      if ($env{'form.importmap'}=~/\w/) {
        }   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
    }      my ($title,$url,$ext,$type)=split(/\:/,$res);
    &untiehash();      my $idx=&LONCAPA::map::getresidx($url);
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.      $LONCAPA::map::resources[$idx]=$res;
      &mt('Return to DOCS').'</a>');      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
 }   }
    ($errtext,$fatal)=&storemap($coursenum,$coursedom,
       $folder.'.'.$container,1);
 sub devalidateversioncache {   return $errtext if ($fatal);
     my $src=shift;      } else {
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
   &Apache::lonnet::clutter($src));  
 }      }
    }
 sub checkversions {   &log_differences($plain);
     my ($r) = @_;      }
     my $type = &Apache::loncommon::course_type();  # ---------------------------------------------------------------- End commands
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));  # ---------------------------------------------------------------- Print screen
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));      my $idx=0;
     my $header='';      my $shown=0;
     my $startsel='';      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
     my $monthsel='';   $r->print('<div class="LC_Box">'.
     my $weeksel='';            '<ol class="LC_docs_parameters"><li class="LC_docs_parameters_title">'.&mt('Parameters:').'</li>'.
     my $daysel='';    ($randompick>=0?'<li>'.&mt('randomly pick [quant,_1,resource]',$randompick).'</li>':'').
     my $allsel='';    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     my %changes=();    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
     my $starttime=0;    ($is_random_order?'<li>'.&mt('random order').'</li>':'').
     my $haschanged=0;    '</ol>');
     my %setversions=&Apache::lonnet::dump('resourceversions',          if ($randompick>=0) {
   $env{'course.'.$env{'request.course.id'}.'.domain'},              $r->print('<p class="LC_warning">'
   $env{'course.'.$env{'request.course.id'}.'.num'});                   .&mt('Caution: this folder is set to randomly pick a subset'
                        .' of resources. Adding or removing resources from this'
     $hashtied=0;                       .' folder will change the set of resources that the'
     &tiehash();                       .' students see, resulting in spurious or missing credit'
     my %newsetversions=();                       .' for completed problems, not limited to ones you'
     if ($env{'form.setmostrecent'}) {                       .' modify. Do not modify the contents of this folder if'
  $haschanged=1;                       .' it is in active student use.')
  foreach my $key (keys(%hash)) {                   .'</p>'
     if ($key=~/^ids\_(\/res\/.+)$/) {              );
  $newsetversions{$1}='mostrecent';          }
                 &devalidateversioncache($1);          if ($is_random_order) {
     }              $r->print('<p class="LC_warning">'
  }                   .&mt('Caution: this folder is set to randomly order its'
     } elsif ($env{'form.setcurrent'}) {                       .' contents. Adding or removing resources from this folder'
  $haschanged=1;                       .' will change the order of resources shown.')
  foreach my $key (keys(%hash)) {                   .'</p>'
     if ($key=~/^ids\_(\/res\/.+)$/) {              );
  my $getvers=&Apache::lonnet::getversion($1);          }
  if ($getvers>0) {          $r->print('</div>');
     $newsetversions{$1}=$getvers;      }
     &devalidateversioncache($1);  
  }      my ($to_show,$output,@allidx,@allmapidx);
     }  
  }      &Apache::loncommon::start_data_table_count(); #setup a row counter 
     } elsif ($env{'form.setversions'}) {      foreach my $res (@LONCAPA::map::order) {
  $haschanged=1;          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  foreach my $key (keys(%env)) {          $name=&LONCAPA::map::qtescape($name);
     if ($key=~/^form\.set_version_(.+)$/) {          $url=&LONCAPA::map::qtescape($url);
  my $src=$1;          unless ($name) {  $name=(split(/\//,$url))[-1]; }
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {          unless ($name) { $idx++; next; }
     $newsetversions{$src}=$env{$key};          push(@allidx,$res);
     &devalidateversioncache($src);          if ($url =~ m{/uploaded/.+\.(page|sequence)$}) {
  }              push(@allmapidx,$res);
     }          }
  }          $output .= &entryline($idx,$name,$url,$folder,$allowed,$res,
     }                                $coursenum,$coursedom,$crstype,
     if ($haschanged) {                                $pathitem,$supplementalflag,$container);
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,          $idx++;
   $env{'course.'.$env{'request.course.id'}.'.domain'},          $shown++;
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {      }
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');      &Apache::loncommon::end_data_table_count();
  } else {  
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');      if (($allowed) || ($supplementalflag && $folder eq 'supplemental')) {
  }          my $toolslink = '<table><tr><td>'
  &mark_hash_old();                         .&Apache::loncommon::help_open_menu('Navigation Screen',
     }                                                             'Navigation_Screen',undef,'RAT')
     &changewarning($r,'');                         .'</td><td class="LC_middle">'.&mt('Tools:').'</td>'
     if ($env{'form.timerange'} eq 'all') {                         .'<td align="left"><ul id="LC_toolbar">'
 # show all documents                         .'<li><a href="/adm/coursedocs?forcesupplement=1&amp;command=editsupp" '
  $header=&mt('All Documents in '.$type);                         .'id="LC_content_toolbar_edittoplevel" '
  $allsel=1;                         .'class="LC_toolbarItem" '
  foreach my $key (keys(%hash)) {                         .'title="'.&mt('Supplemental Content Editor').'">'
     if ($key=~/^ids\_(\/res\/.+)$/) {                         .'</a></li></ul></td></tr></table><br />';
  my $src=$1;          if ($shown) {
  $changes{$src}=1;              if ($allowed) {
     }                  $to_show = &Apache::loncommon::start_scrollbox('900px','880px','400px','contentscroll')
  }                            .&Apache::loncommon::start_data_table(undef,'contentlist')
     } else {                            .&Apache::loncommon::start_data_table_header_row()
 # show documents which changed                            .'<th colspan="2">'.&mt('Move').'</th>'
  %changes=&Apache::lonnet::dump                            .'<th>'.&mt('Actions').'</th>'
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},                            .'<th colspan="2">'.&mt('Document').'</th>';
                      $env{'course.'.$env{'request.course.id'}.'.num'});                  if ($folder !~ /^supplemental/) {
  my $firstkey=(keys(%changes))[0];                      $to_show .= '<th colspan="4">'.&mt('Settings').'</th>';
  unless ($firstkey=~/^error\:/) {                  }
     unless ($env{'form.timerange'}) {                  $to_show .= &Apache::loncommon::end_data_table_header_row();
  $env{'form.timerange'}=604800;                  if ($folder !~ /^supplemental/) {
     }                      my $idxlist = join(',',@allidx);
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '                      my $mapidxlist = join(',',@allmapidx);
  .&mt('seconds');                      if (@allidx > 0) {
     if ($env{'form.timerange'}==-1) {                          my $path;
  $seltext='since start of course';                          if ($env{'form.folderpath'}) {
  $startsel='selected';                              $path = 
  $env{'form.timerange'}=time;                                  &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
     }                          }
     $starttime=time-$env{'form.timerange'};                          $to_show .= 
     if ($env{'form.timerange'}==2592000) {                              &Apache::loncommon::continue_data_table_row().
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                              '<td colspan="5">&nbsp;</td>'.
  $monthsel='selected';                              '<td colspan="4">'.
     } elsif ($env{'form.timerange'}==604800) {                              '<form action="/adm/coursedocs" method="post" name="togglemultchecks">'.
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                              '<span class="LC_nobreak" style="font-size:x-small;font-weight:bold;">'.&mt('Select:').'&nbsp;'.
  $weeksel='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>'.
     } elsif ($env{'form.timerange'}==86400) {                              '<div id="multiclick" style="display: none">'.
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';                              '<form action="/adm/coursedocs" method="post" name="cumulativechecks" onsubmit="return submitSettings(this);">'."\n".
  $daysel='selected';                              '<fieldset><legend style="font-size:x-small;">'.&mt('check/uncheck all').'</legend>'."\n".
     }                              '<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>'.
     $header=&mt('Content changed').' '.$seltext;                              '</tr>'."\n".
  } else {                              '<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".
     $header=&mt('No content modifications yet.');                              '</fieldset>'.
  }                              '<input type="hidden" name="folderpath" value="'.$path.'" />'.
     }                              '<input type="hidden" name="symb" value="'.$env{'form.symb'}.'" />'.
     %setversions=&Apache::lonnet::dump('resourceversions',                              '<input type="hidden" name="allhiddenresource" value="" />'.
   $env{'course.'.$env{'request.course.id'}.'.domain'},                              '<input type="hidden" name="allencrypturl" value="" />'.
   $env{'course.'.$env{'request.course.id'}.'.num'});                              '<input type="hidden" name="allrandompick" value="" />'.
     my %lt=&Apache::lonlocal::texthash                              '<input type="hidden" name="allrandomorder" value="" />'.
       ('st' => 'Version changes since start of '.$type,                              '<input type="hidden" name="allidx" value="'.$idxlist.'" />'.
        'lm' => 'Version changes since last Month',                              '<input type="hidden" name="allmapidx" value="'.$mapidxlist.'" />'.
        'lw' => 'Version changes since last Week',                              '<input type="hidden" name="changeparms" value="all" />'.
        'sy' => 'Version changes since Yesterday',                              '<input type="submit" name="multiplesettings" value="'.&mt('Save settings below').'" />'.
                'al' => 'All Resources (possibly large output)',                              '</form>'.
        'sd' => 'Display',                              '</div>'.
        'fi' => 'File',  
        'md' => 'Modification Date',                              '</td>'.
                'mr' => 'Most recently published Version',                              &Apache::loncommon::end_data_table_row();
        've' => 'Version used in '.$type,                      }
                'vu' => 'Set Version to be used in '.$type,                  }
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',                  $to_show .= $output.' '
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',                             .&Apache::loncommon::end_data_table()
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',                             .'<br style="line-height:2px;" />'
        'di' => 'Differences');                             .&Apache::loncommon::end_scrollbox();
     $r->print(<<ENDHEADERS);              } else {
 <form action="/adm/coursedocs" method="post">                  $to_show .= $toolslink
 <input type="hidden" name="versions" value="1" />                             .&Apache::loncommon::start_data_table('LC_tableOfContent')
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />                             .$output.' '
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />                             .&Apache::loncommon::end_data_table();
 <select name="timerange">              }
 <option value='all' $allsel>$lt{'al'}</option>          } else {
 <option value="-1" $startsel>$lt{'st'}</option>              if (!$allowed) {
 <option value="2592000" $monthsel>$lt{'lm'}</option>                  $to_show .= $toolslink;
 <option value="604800" $weeksel>$lt{'lw'}</option>              }
 <option value="86400" $daysel>$lt{'sy'}</option>              $to_show .= &Apache::loncommon::start_scrollbox('400px','380px','200px','contentscroll')
 </select>                         .'<div class="LC_info" id="contentlist">'
 <input type="submit" name="display" value="$lt{'sd'}" />                         .&mt('Currently no documents.')
 <h3>$header</h3>                         .'</div>'
 <input type="submit" name="setversions" value="$lt{'sv'}" />                         .&Apache::loncommon::end_scrollbox();
 <table border="0">          }
 ENDHEADERS      } else {
     foreach my $key (sort(keys(%changes))) {          if ($shown) {
  if ($changes{$key}>$starttime) {              $to_show = '<div>'
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);                        .&Apache::loncommon::start_data_table('LC_tableOfContent')
     my $currentversion=&Apache::lonnet::getversion($key);                        .$output
     if ($currentversion<0) {                        .&Apache::loncommon::end_data_table()
  $currentversion=&mt('Could not be determined.');                        .'</div>';
     }          } else {
     my $linkurl=&Apache::lonnet::clutter($key);              $to_show = '<div class="LC_info" id="contentlist">'
     $r->print(                        .&mt('Currently no documents.')
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.                        .'</div>'
       &Apache::lonnet::gettitle($linkurl).          }
                       '</b></font></td></tr>'.      }
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      my $tid = 1;
                       '<td colspan="4">'.      if ($supplementalflag) {
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.          $tid = 2;
       '</a></td></tr>'.      }
                       '<tr><td></td>'.      if ($allowed) {
                       '<td title="'.$lt{'md'}.'">'.          my $readfile="/uploaded/$coursedom/$coursenum/$folder.$container";
       &Apache::lonlocal::locallocaltime(          $r->print(&generate_edit_table($tid,$orderhash,$to_show,$iconpath,$jumpto,
                            &Apache::lonnet::metadata($root.'.'.$extension,                                         $readfile));
                                                      'lastrevisiondate')          &print_paste_buffer($r,$container,$folder,$coursedom,$coursenum);
                                                         ).      } else {
                       '</td>'.          $r->print($to_show);
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.      }
                       '<font size="+1">'.$currentversion.'</font>'.      return;
                       '</span></td>'.  }
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.  
                       '<font size="+1">');  sub process_file_upload {
 # Used in course      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     my $usedversion=$hash{'version_'.$linkurl};  # upload a file, if present
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      my ($parseaction,$showupload,$nextphase,$mimetype);
  $r->print($usedversion);      if ($env{'form.parserflag'}) {
     } else {          $parseaction = 'parse';
  $r->print($currentversion);      }
     }      my $folder=$env{'form.folder'};
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.      if ($folder eq '') {
                       '<span class="LC_nobreak">Use: ');          $folder='default';
 # Set version      }
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
       'set_version_'.$linkurl,          my $errtext='';
       ('select_form_order' =>          my $fatal=0;
        ['',1..$currentversion,'mostrecent'],          my $container='sequence';
        '' => '',          if ($env{'form.folderpath'} =~ /:1$/) {
        'mostrecent' => 'most recent',              $container='page';
        map {$_,$_} (1..$currentversion))));          }
     $r->print('</span></td></tr><tr><td></td>');          ($errtext,$fatal)=
     my $lastold=1;              &mapread($coursenum,$coursedom,$folder.'.'.$container);
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {          if ($#LONCAPA::map::order<1) {
  my $url=$root.'.'.$prevvers.'.'.$extension;              $LONCAPA::map::order[0]=1;
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<              $LONCAPA::map::resources[1]='';
     $starttime) {          }
     $lastold=$prevvers;          my $destination = 'docs/';
  }          if ($folder =~ /^supplemental/) {
     }              $destination = 'supplemental/';
             #          }
             # Code to figure out how many version entries should go in          if (($folder eq 'default') || ($folder eq 'supplemental')) {
             # each of the four columns              $destination .= 'default/';
             my $entries_per_col = 0;          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
             my $num_entries = ($currentversion-$lastold);              $destination .=  $2.'/';
             if ($num_entries % 4 == 0) {          }
                 $entries_per_col = $num_entries/4;          if ($fatal) {
             } else {              $$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>';
                 $entries_per_col = $num_entries/4 + 1;              return;
             }          }
             my $entries_count = 0;  # this is for a course, not a user, so set context to coursedoc.
             $r->print('<td valign="top"><font size="-2">');          my $newidx=&LONCAPA::map::getresidx();
             my $cols_output = 1;          $destination .= $newidx;
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {          my $url=&Apache::lonnet::userfileupload('uploaddoc','coursedoc',$destination,
  my $url=$root.'.'.$prevvers.'.'.$extension;   $parseaction,$allfiles,
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).   $codebase,undef,undef,undef,undef,
   '">'.&mt('Version').' '.$prevvers.'</a> ('.                                                  undef,undef,\$mimetype);
   &Apache::lonlocal::locallocaltime(          if ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E.*/([^/]+)$}) {
                                 &Apache::lonnet::metadata($url,              my $stored = $1;
                                                           'lastrevisiondate')              $showupload = '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
                                                             ).                            $stored.'</span>').'</p>';
   ')');          } else {
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {              my ($filename) = ($env{'form.uploaddoc.filename'} =~ m{([^/]+)$});
                     $r->print(' <a href="/adm/diff?filename='.              
       &Apache::lonnet::clutter($root.'.'.$extension).              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.&mt('Unable to save file [_1].','<span class="LC_filename">'.$filename.'</span>').'</div>';
       '&versionone='.$prevvers.              return;
       '">'.&mt('Diffs').'</a>');          }
  }          my $ext='false';
  $r->print('</span><br />');          if ($url=~m{^http://}) { $ext='true'; }
                 if (++$entries_count % $entries_per_col == 0) {   $url     = &LONCAPA::map::qtunescape($url);
                     $r->print('</font></td>');          my $comment=$env{'form.comment'};
                     if ($cols_output != 4) {   $comment = &LONCAPA::map::qtunescape($comment);
                         $r->print('<td valign="top"><font size="-2">');          if ($folder=~/^supplemental/) {
                         $cols_output++;                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
                     }                    $env{'user.domain'}.'___&&&___'.$comment;
                 }          }
     }  
             while($cols_output++ < 4) {          $LONCAPA::map::resources[$newidx]=
                 $r->print('</font></td><td><font>')      $comment.':'.$url.':'.$ext.':normal:res';
             }          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     $r->print('</font></td></tr>'."\n");          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
  }      $folder.'.'.$container,1);
     }          if ($fatal) {
     $r->print('</table></form>');              $$upload_output = '<div class="LC_error" id="uploadfileresult">'.$errtext.'</div>';
     $r->print('<h1>'.&mt('Done').'.</h1>');              return;
           } else {
     &untiehash();              if ($parseaction eq 'parse' && $mimetype eq 'text/html') {
 }                  $$upload_output = $showupload;
                   my $total_embedded = scalar(keys(%{$allfiles}));
 sub mark_hash_old {                  if ($total_embedded > 0) {
     my $retie_hash=0;                      my $uploadphase = 'upload_embedded';
     if ($hashtied) {                      my $primaryurl = &HTML::Entities::encode($url,'<>&"');
  $retie_hash=1;      my $state = &embedded_form_elems($uploadphase,$primaryurl,$newidx); 
  &untiehash();                      my ($embedded,$num) = 
     }                          &Apache::loncommon::ask_for_embedded_content(
     &tiehash('write');                              '/adm/coursedocs',$state,$allfiles,$codebase,{'docs_url' => $url});
     $hash{'old'}=1;                      if ($embedded) {
     &untiehash();                          if ($num) {
     if ($retie_hash) { &tiehash(); }                              $$upload_output .=
 }           '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
                               $nextphase = $uploadphase;
 sub is_hash_old {                          } else {
     my $untie_hash=0;                              $$upload_output .= $embedded;
     if (!$hashtied) {                          }
  $untie_hash=1;                      } else {
  &tiehash();                          $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
     }                      }
     my $return=$hash{'old'};                  } else {
     if ($untie_hash) { &untiehash(); }                      $$upload_output .= &mt('No embedded items identified').'<br />';
     return $return;                  }
 }                  $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
               } elsif (&Apache::loncommon::is_archive_file($mimetype)) {
 sub changewarning {                  $nextphase = 'decompress_uploaded';
     my ($r,$postexec,$message,$url)=@_;                  my $position = scalar(@LONCAPA::map::order)-1;
     if (!&is_hash_old()) { return; }                  my $noextract = &return_to_editor();
     my $pathvar='folderpath';                  my $archiveurl = &HTML::Entities::encode($url,'<>&"');
     my $path=&escape($env{'form.folderpath'});                  my %archiveitems = (
     if (!defined($url)) {                      folderpath => $env{'form.folderpath'},
  if (defined($env{'form.pagepath'})) {                      cmd        => $nextphase,
     $pathvar='pagepath';                      newidx     => $newidx,
     $path=&escape($env{'form.pagepath'});                      position   => $position,
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                      phase      => $nextphase,
  }                      comment    => $comment,
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                  );
     }                  my ($destination,$dir_root) = &embedded_destination($coursenum,$coursedom);
     my $course_type = &Apache::loncommon::course_type();                  my @current = &get_dir_list($url,$coursenum,$coursedom,$newidx); 
     if (!defined($message)) {                  $$upload_output = $showupload.
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                                    &Apache::loncommon::decompress_form($mimetype,
     }                                        $archiveurl,'/adm/coursedocs',$noextract,
     $r->print("\n\n".                                        \%archiveitems,\@current);
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".              }
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.          }
 '<input type="hidden" name="orgurl" value="'.$url.      }
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.      return $nextphase;
 &mt($message,' <input type="hidden" name="'.  }
     $env{'request.role'}.'" value="1" /><input type="button" value="'.  
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').  sub get_dir_list {
 $help{'Caching'}.'</span></h3></form>'."\n\n");      my ($url,$coursenum,$coursedom,$newidx) = @_;
 }      my ($destination,$dir_root) = &embedded_destination();
       my ($dirlistref,$listerror) =  
           &Apache::lonnet::dirlist("$dir_root/$destination/$newidx",$coursedom,$coursenum,1);
 sub init_breadcrumbs {      my @dir_lines;
     my ($form,$text)=@_;      my $dirptr=16384;
     &Apache::lonhtmlcommon::clear_breadcrumbs();      if (ref($dirlistref) eq 'ARRAY') {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",          foreach my $dir_line (sort
     text=>"Edit ".&Apache::loncommon::course_type(),                            {
     faq=>273,                                my ($afile)=split('&',$a,2);
     bug=>'Instructor Interface',                                my ($bfile)=split('&',$b,2);
                                             help => 'Docs_Adding_Course_Doc'});                                return (lc($afile) cmp lc($bfile));
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',                            } (@{$dirlistref})) {
     text=>$text,              my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16);
     faq=>273,              $filename =~ s/\s+$//;
     bug=>'Instructor Interface'});              next if ($filename =~ /^\.\.?$/); 
 }              my $isdir = 0;
               if ($dirptr&$testdir) {
                   $isdir = 1;
               }
               push(@dir_lines, [$filename,$dom,$isdir,$size,$mtime,$obs]);
 sub handler {          }
     my $r = shift;      }
     &Apache::loncommon::content_type($r,'text/html');      return @dir_lines;
     $r->send_http_header;  }
     return OK if $r->header_only;  
     my $type = &Apache::loncommon::course_type();  sub is_supplemental_title {
       my ($title) = @_;
       return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
 # --------------------------------------------- Initialize help topics for this  }
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',  
                'Adding_External_Resource','Navigate_Content',  # --------------------------------------------------------------- An entry line
                'Adding_Folders','Docs_Overview', 'Load_Map',  
                'Supplemental','Score_Upload_Form','Adding_Pages',  sub entryline {
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$coursedom,
                'Check_Resource_Versions','Verify_Content') {          $crstype,$pathitem,$supplementalflag,$container)=@_;
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);      my ($foldertitle,$renametitle);
     }      if (&is_supplemental_title($title)) {
     # Composite help files   ($title,$foldertitle,$renametitle) = &Apache::loncommon::parse_supplemental_title($title);
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      } else {
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');   $title=&HTML::Entities::encode($title,'"<>&\'');
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(   $renametitle=$title;
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');   $foldertitle=$title;
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(      }
     'Option_Response_Simple');  
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(      my $orderidx=$LONCAPA::map::order[$index];
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');  
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(      $renametitle=~s/\\/\\\\/g;
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');      $renametitle=~s/\&quot\;/\\\"/g;
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');      $renametitle=~s/ /%20/g;
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');      my $line=&Apache::loncommon::start_data_table_row();
       my ($form_start,$form_end,$form_common);
 # does this user have privileges to modify docs  # Edit commands
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});      my ($esc_path, $path, $symb);
   if ($allowed && $env{'form.verify'}) {      if ($env{'form.folderpath'}) {
       &init_breadcrumbs('verify','Verify Content');   $esc_path=&escape($env{'form.folderpath'});
       &verifycontent($r);   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   } elsif ($allowed && $env{'form.listsymbs'}) {   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
       &init_breadcrumbs('listsymbs','List Symbs');      }
       &list_symbs($r);      my $isexternal;
   } elsif ($allowed && $env{'form.docslog'}) {      if ($residx) {
       &init_breadcrumbs('docslog','Show Log');          my $currurl = $url;
       &docs_change_log($r);          $currurl =~ s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
   } elsif ($allowed && $env{'form.versions'}) {          if ($currurl =~ m{^/adm/wrapper/ext/}) {
       &init_breadcrumbs('versions','Check/Set Resource Versions');              $isexternal = 1;
       &checkversions($r);          }
   } elsif ($allowed && $env{'form.dumpcourse'}) {          if (!$supplementalflag) {
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');              my $path = 'uploaded/'.
       &dumpcourse($r);                         $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
   } elsif ($allowed && $env{'form.exportcourse'}) {                         $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');              $symb = &Apache::lonnet::encode_symb($path.$folder.".$container",
       &exportcourse($r);                                                   $residx,
   } else {                                                   &Apache::lonnet::declutter($currurl));
 # is this a standard course?          }
       }
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      my ($renamelink,%lt);
     my $forcestandard = 0;      if ($allowed) {
     my $forcesupplement;   my $incindex=$index+1;
     my $script='';   my $selectbox='';
     my $showdoc=0;   if (($#LONCAPA::map::order>0) &&
     my $containertag;      ((split(/\:/,
     my $uploadtag;       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
        ne '') &&
       ((split(/\:/,
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
     ['folderpath','pagepath',       ne '')) {
      'pagesymb']);      $selectbox=
 # No folderpath, no pagepath, see if we have something stored   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {   '<select name="newpos" onchange="this.form.submit()">';
         &Apache::loncommon::restore_course_settings('docs_folderpath',      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
                                               {'folderpath' => 'scalar'});   if ($i==$incindex) {
     }      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
     if (!$env{'form.folderpath'}) {   } else {
         &Apache::loncommon::restore_course_settings('docs_folderpath',      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
                                               {'pagepath' => 'scalar'});   }
     }      }
     if ($env{'form.pagepath'}) {      $selectbox.='</select>';
        $env{'form.folderpath'}='';   }
     }   %lt=&Apache::lonlocal::texthash(
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {                  'up' => 'Move Up',
         $env{'form.folderpath'} = 'supplemental&'.   'dw' => 'Move Down',
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.   'rm' => 'Remove',
                                   $env{'form.folderpath'};                  'ct' => 'Cut',
     }   'rn' => 'Rename',
     &Apache::loncommon::store_course_settings('docs_folderpath',   'cp' => 'Copy',
                                                 {'pagepath' => 'scalar',                  'ex' => 'External Resource',
                                                  'folderpath' => 'scalar'});                  'ed' => 'Edit',
     if ($env{'form.folderpath'}) {                  'pr' => 'Preview',
  my (@folderpath)=split('&',$env{'form.folderpath'});                  'sv' => 'Save',
  $env{'form.foldername'}=&unescape(pop(@folderpath));                  'ul' => 'URL',
  $env{'form.folder'}=pop(@folderpath);                  'ti' => 'Title', 
     }                  );
     if ($env{'form.pagepath'}) {   my $nocopy=0;
         my (@pagepath)=split('&',$env{'form.pagepath'});          my $nocut=0;
         $env{'form.pagename'}=&unescape(pop(@pagepath));          my $noremove=0;
         $env{'form.folder'}=pop(@pagepath);          if ($url=~ m{^/res/.+\.(page|sequence)$}) {
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      # no copy for published maps
     '<input type="hidden" name="pagesymb" value="" />';      $nocopy=1;
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.   }
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';          if ($url=~/^\/res\/lib\/templates\//) {
     }             $nocopy=1;
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {             $nocut=1;
        $showdoc='/'.$1;          }
     }          my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
     unless ($showdoc) { # got called from remote          my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||          if ($url eq "/uploaded/$cdom/$cnum/group_allfolders.sequence") {
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {              if ($env{'form.folderpath'} =~ /^default&[^\&]+$/) {
            $forcestandard = 1;                  my %curr_groups = &Apache::longroup::coursegroups();
        }                  if (keys(%curr_groups) > 0) {
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);                      $noremove=1;
                   }
        if ($allowed) {                  $nocut=1;
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);                  $nocopy=1;
          $script=&Apache::lonratedt::editscript('simple');              }
        }          } elsif ($url =~ m{^\Q/uploaded/$cdom/$cnum/group_folder_\E(\w+)\.sequence$}) {
     } else { # got called in sequence from course              my $group = $1;
        $allowed=0;              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+$/) {
     }                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
                   if (keys(%curr_group) > 0) {
 # get course data                      $noremove=1;
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};                  }
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};              }
               $nocut=1;
 # get personal data              $nocopy=1;
     my $uname=$env{'user.name'};          } elsif ($url =~ m{^\Q/adm/$cdom/$cnum/\E(\w+)/smppg$}) {
     my $udom=$env{'user.domain'};              my $group = $1;
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));              if ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&\Qgroup_folder_$group\E\&[^\&]+$/) {
                   my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
 # graphics settings                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
                   if (keys(%groupsettings) > 0) {
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");                      $noremove=1;
                   }
     if ($allowed) {                  $nocut=1;
  $script .= &editing_js($udom,$uname);                  $nocopy=1;
     }              }
 # -------------------------------------------------------------------- Body tag          } elsif ($env{'form.folderpath'} =~ /^default&[^\&]+\&group_allfolders\&[^\&]+\&group_folder_(\w+)\&/) {
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';              my $group = $1;
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];              my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,              if ($url =~ /group_boards_\Q$group\E/) {
     {'force_register' => $showdoc,                  my %curr_group = &Apache::longroup::coursegroups($cdom,$cnum,$group);
                                      'bread_crumbs' => $brcrum}).                  my %groupsettings = &Apache::longroup::get_group_settings($curr_group{$group});
       &Apache::loncommon::help_open_menu('','',273,'RAT'));                  if (keys(%groupsettings) > 0) {
                        if (ref($groupsettings{'functions'}) eq 'HASH') {
   my %allfiles = ();                          if ($groupsettings{'functions'}{'discussion'} eq 'on') {
   my %codebase = ();                              $noremove=1;
   my ($upload_result,$upload_output);                          }
   if ($allowed) {                      }
       if (($env{'form.uploaddoc.filename'}) &&                  }
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                  $nocut=1;
 # Process file upload - phase one - upload and parse primary file.                    $nocopy=1;
   undef($hadchanges);              }
           $upload_result = &process_file_upload(\$upload_output,$coursenum,          }
  $coursedom,\%allfiles,          my ($copylink,$cutlink,$removelink);
  \%codebase,$1);   my $skip_confirm = 0;
   if ($hadchanges) {   if ( $folder =~ /^supplemental/
       &mark_hash_old();       || ($url =~ m{( /smppg$
   }      |/syllabus$
           if ($upload_result eq 'phasetwo') {      |/aboutme$
               $r->print($upload_output);      |/navmaps$
           }      |/bulletinboard$
       } elsif ($env{'form.phasetwo'}) {      |\.html$)}x)
           my %newname = ();               || $isexternal) {
           my %origname = ();      $skip_confirm = 1;
           my %attribs = ();   }
           my $updateflag = 0;  
           my $residx = $env{'form.newidx'};   if ($nocopy) {
           my $primary_url = &unescape($env{'form.primaryurl'});              $copylink=(<<ENDCOPY);
 # Process file upload - phase two - gather secondary files.  <span style="visibility: hidden;">$lt{'cp'}</span>
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {  ENDCOPY
               if ($env{'form.embedded_item_'.$i.'.filename'}) {          } else {
                   my $javacodebase;      $copylink=(<<ENDCOPY);
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);  <a href="javascript:markcopy('$esc_path','$index','$renametitle','$container','$folder');" class="LC_docs_copy">$lt{'cp'}</a>
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});  ENDCOPY
                   if (exists($env{'form.embedded_codebase_'.$i})) {          }
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});     if ($nocut) {
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;              $cutlink=(<<ENDCUT);
                   }  <span style="visibility: hidden;">$lt{'ct'}</span>
                   my @attributes = ();  ENDCUT
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {          } else {
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});      $cutlink=(<<ENDCUT);
                   } else {  <a href="javascript:cutres('$esc_path','$index','$renametitle','$container','$folder',$skip_confirm);" class="LC_docs_cut">$lt{'ct'}</a>
                       @attributes = ($env{'form.embedded_attrib_'.$i});  ENDCUT
                   }          }
                   foreach my $attr (@attributes) {          if ($noremove) {
                       push(@{$attribs{$i}},&unescape($attr));              $removelink=(<<ENDREM);
                   }  <span style="visibility: hidden;">$lt{'rm'}</a>
                   if ($javacodebase) {  ENDREM
                       $codebase{$i} = $javacodebase;          } else {
                       $codebase{$i} =~ s#/$##;              $removelink=(<<ENDREM);
                       $updateflag = 1;  <a href='javascript:removeres("$esc_path","$index","$renametitle",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
                   }  ENDREM
               }          }
               unless ($newname{$i} eq $origname{$i}) {          unless ($isexternal) {
                   $updateflag = 1;              $renamelink=(<<ENDREN);
               }  <a href='javascript:changename("$esc_path","$index","$renametitle");' class="LC_docs_rename">$lt{'rn'}</a>
           }  ENDREN
 # Process file upload - phase three - modify primary file          }
           if ($updateflag) {   $form_start = '
               my ($content,$rtncode);     <form action="/adm/coursedocs" method="post">
               my $updateflag = 0;  ';
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);          $form_common=(<<END);
               if ($getstatus eq 'ok') {     <input type="hidden" name="folderpath" value="$path" />
                   foreach my $item (keys(%newname)) {     <input type="hidden" name="symb" value="$symb" />
                       if ($newname{$item} ne $origname{$item}) {     <input type="hidden" name="setparms" value="$orderidx" />
                           my $attrib_regexp = '';     <input type="hidden" name="changeparms" value="0" />
                           if (@{$attribs{$item}} > 1) {  END
                               $attrib_regexp = join('|',@{$attribs{$item}});          $form_end = '</form>';
                           } else {   $line.=(<<END);
                               $attrib_regexp = $attribs{$item}[0];  <td>
                           }  <div class="LC_docs_entry_move">
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {    <a href='/adm/coursedocs?cmd=up_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
                           }      <img src="${iconpath}move_up.gif" alt="$lt{'up'}" class="LC_icon" />
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;    </a>
                       }  </div>
                       if (exists($codebase{$item})) {  <div class="LC_docs_entry_move">
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs    <a href='/adm/coursedocs?cmd=down_$index&amp;folderpath=$esc_path&amp;symb=$symb'>
                       }      <img src="${iconpath}move_down.gif" alt="$lt{'dw'}" class="LC_icon" />
                   }    </a>
 # Save edited file.  </div>
                   my $saveresult;  </td>
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};  <td>
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};     $form_start
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);     $form_common
               } else {     $selectbox
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);     $form_end
               }  </td>
           }  <td class="LC_docs_entry_commands"><span class="LC_nobreak">
       }  $removelink
   }  $cutlink
   $copylink
   unless ($showdoc ||  $upload_result eq 'phasetwo') {  </span>
 # -----------------------------------------------------------------------------  </td>
        my %lt=&Apache::lonlocal::texthash(  END
                 'uplm' => 'Upload a new main '.lc($type).' document',  
                 'upls' => 'Upload a new supplemental '.lc($type).' document',      }
                 'impp' => 'Import a document',  # Figure out what kind of a resource this is
                 'pubd' => 'Published Documents',      my ($extension)=($url=~/\.(\w+)$/);
  'copm' => 'All documents out of a published map into this folder',      my $uploaded=($url=~/^\/*uploaded\//);
                 'upld' => 'Upload Document',      my $icon=&Apache::loncommon::icon($url);
                 'srch' => 'Search',      my $isfolder;
                 'impo' => 'Import',      my $ispage;
  'book' => 'Import Bookmarks',      my $containerarg;
                 'selm' => 'Select Map',      if ($uploaded) {
                 'load' => 'Load Map',          if (($extension eq 'sequence') || ($extension eq 'page')) {
                 'reco' => 'Recover Deleted Resources',              $url=~/\Q$coursenum\E\/([\/\w]+)\.\Q$extension\E$/;
                 'newf' => 'New Folder',              $containerarg = $1;
                 'newp' => 'New Composite Page',      if ($extension eq 'sequence') {
                 'extr' => 'External Resource',          $icon=$iconpath.'navmap.folder.closed.gif';
                 'syll' => 'Syllabus',                  $isfolder=1;
                 'navc' => 'Navigate Contents',              } else {
                 'sipa' => 'Simple Page',                  $icon=$iconpath.'page.gif';
                 'sipr' => 'Simple Problem',                  $ispage=1;
                 'drbx' => 'Drop Box',              }
                 'scuf' => 'Score Upload Form',              if ($allowed) {
                 'bull' => 'Bulletin Board',                  $url='/adm/coursedocs?';
                 'mypi' => 'My Personal Info',              } else {
                 'grpo' => 'Group Files',                  $url='/adm/supplemental?';
                 'rost' => 'Course Roster',              }
  'abou' => 'About User',   } else {
                 'imsf' => 'Import IMS package',      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
                 'file' =>  'File',   }
                 'title' => 'Title',      }
                 'comment' => 'Comment',  
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',      my ($editlink,$extresform);
  'nd' => 'New Document',      my $orig_url = $url;
  'pm' => 'Published Map',      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  'sd' => 'Special Document',      $url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/};
  'mo' => 'More Options',      if (!$supplementalflag && $residx && $symb) {
  'hao' => 'Hide all Options'          if ((!$isfolder) && (!$ispage)) {
   );      (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 # -----------------------------------------------------------------------------      $url=&Apache::lonnet::clutter($url);
  my $fileupload=(<<FIUP);      if ($url=~/^\/*uploaded\//) {
  $lt{'file'}:<br />          $url=~/\.(\w+)$/;
  <input type="file" name="uploaddoc" size="40" />          my $embstyle=&Apache::loncommon::fileembstyle($1);
 FIUP          if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
       $url='/adm/wrapper'.$url;
  my $checkbox=(<<CHBO);          } elsif ($embstyle eq 'ssi') {
  <!-- <label>$lt{'parse'}?      #do nothing with these
  <input type="checkbox" name="parserflag" />          } elsif ($url!~/\.(sequence|page)$/) {
  </label> -->      $url='/adm/coursedocs/showdoc'.$url;
  <label>          }
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}      } elsif ($url=~m|^/ext/|) {
  </label>          $url='/adm/wrapper'.$url;
 CHBO      }
               if (&Apache::lonnet::symbverify($symb,$url)) {
  my $fileuploadform=(<<FUFORM);          $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">              } else {
  $fileupload                  $url='';
  <br />              }
  $lt{'title'}:<br />   }
  <input type="text" size="50" name="comment" />      }
  $uploadtag      my ($rand_pick_text,$rand_order_text);
  <input type="hidden" name="cmd" value="upload_default" />      if ($isfolder || $ispage || $extension eq 'sequence' || $extension eq 'page') {
  <br />   my $foldername=&escape($foldertitle);
  <span class="LC_nobreak">   my $folderpath=$env{'form.folderpath'};
  $checkbox   if ($folderpath) { $folderpath.='&' };
  </span>          if (!$allowed && $supplementalflag) {
  <br />              $folderpath.=$containerarg.'&'.$foldername;
  <br />              $url.='folderpath='.&escape($folderpath);
  <span class="LC_nobreak">          } else {
  <input type="submit" value="$lt{'upld'}" />  # Append randompick number, hidden, and encrypted with ":" to foldername,
  $help{'Uploading_From_Harddrive'}  # so it gets transferred between levels
  </span>      $folderpath.=$containerarg.'&'.$foldername.
  </form>                                                ':'.(&LONCAPA::map::getparameter($orderidx,
 FUFORM                                                'parameter_randompick'))[0]
                                                  .':'.((&LONCAPA::map::getparameter($orderidx,
  my $simpleeditdefaultform=(<<SEDFFORM);                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  $lt{'pubd'}<br />                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  $uploadtag                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />                                                'parameter_randomorder'))[0]=~/^yes$/i)
  <br />                                                 .':'.$ispage;
  <span class="LC_nobreak">      $url.='folderpath='.&escape($folderpath);
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />              my $rpicknum = (&LONCAPA::map::getparameter($orderidx,
  $help{'Importing_LON-CAPA_Resource'}                                                          'parameter_randompick'))[0];
  </span>              my $rpckchk;
  <br />              if ($rpicknum) {
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />                  $rpckchk = ' checked="checked"';
  <hr />              }
  <p>              my $formname = 'edit_randompick_'.$orderidx;
  $lt{'copm'}<br />      $rand_pick_text = 
  <input type="text" size="40" name="importmap" /><br />  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
  <span class="LC_nobreak"><input type="button"  $form_common."\n".
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"  '<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.'">';
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />              if ($rpicknum ne '') {
  $help{'Load_Map'}</span>                  $rand_pick_text .= ':&nbsp;<a href="javascript:updatePick('."document.$formname,'$orderidx','link'".')">'.$rpicknum.'</a>';
  </p>              }
  </form>              $rand_pick_text .= '</span></span>'.
 SEDFFORM                                 $form_end;
          my $ro_set=
  my $extresourcesform=(<<ERFORM);          ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
  <form action="/adm/coursedocs" method="post" name="newext">              my $formname = 'edit_rorder_'.$orderidx;
  $uploadtag      $rand_order_text = 
  <input type="hidden" name="importdetail" value="" />  '<form action="/adm/coursedocs" method="post" name="'.$formname.'">'."\n".
  <span class="LC_nobreak">  $form_common."\n".
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"  '<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>'.
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  $form_end; 
  </span>          }
  </form>      } elsif ($supplementalflag && !$allowed) {
 ERFORM          $url .= ($url =~ /\?/) ? '&amp;':'?';
           $url .= 'folderpath='.&HTML::Entities::encode($esc_path,'<>&"');
     if ($allowed) {          if ($title) {
  &update_paste_buffer($coursenum,$coursedom);              $url .= '&amp;title='.&HTML::Entities::encode($renametitle,'<>&"');
        my $dumpbut=&dumpbutton();          }
        my $exportbut=&exportbutton();          if ($isexternal && $orderidx) {
        my %lt=&Apache::lonlocal::texthash(              $url .= '&amp;idx='.$orderidx;
  'vc' => 'Verify Content',          }
  'cv' => 'Check/Set Resource Versions',      }
  'ls' => 'List Symbs',      my ($tdalign,$tdwidth);
                                          'sl' => 'Show Log'      if ($allowed) {
   );          my $fileloc = 
               &Apache::lonnet::declutter(&Apache::lonnet::filelocation('',$orig_url));
        my $folderpath=$env{'form.folderpath'};          if ($isexternal) {
        if (!$folderpath) {              ($editlink,$extresform) = 
    if ($env{'form.folder'} eq '' ||                  &Apache::lonextresedit::extedit_form(0,$residx,$orig_url,$title,$pathitem);
        $env{'form.folder'} eq 'supplemental') {          } elsif (!$isfolder && !$ispage) {
        $folderpath='default&'.              my ($cfile,$home,$switchserver,$forceedit,$forceview) = 
    &escape(&mt('Main '.$type.' Documents'));                  &Apache::lonnet::can_edit_resource($fileloc,$coursenum,$coursedom,$orig_url);
    }              if (($cfile ne '') && ($symb ne '' || $supplementalflag)) {
        }                  my $jscall = 
        unless ($env{'form.pagepath'}) {                      &Apache::lonhtmlcommon::jump_to_editres($cfile,$home,
            $containertag = '<input type="hidden" name="folderpath" value="" />';                                                              $switchserver,
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';                                                              $forceedit,
        }                                                              undef,$symb,
                                                               &escape($env{'form.folderpath'}),
        $r->print(<<ENDCOURSEVERIFY);                                                              $renametitle,'','',1);
 <form name="renameform" method="post" action="/adm/coursedocs">                  if ($jscall) {
   <input type="hidden" name="title" />                      $editlink = '<a class="LC_docs_ext_edit" href="javascript:'.
   <input type="hidden" name="cmd" />                                  $jscall.'" >'.&mt('Edit').'</a>&nbsp;'."\n";
   <input type="hidden" name="markcopy" />                  }
   <input type="hidden" name="copyfolder" />              }
   $containertag          }
 </form>          $tdalign = ' align="right" valign="top"';
 <form name="simpleedit" method="post" action="/adm/coursedocs">          $tdwidth = ' width="80%"';
   <input type="hidden" name="importdetail" value="" />      }
   $uploadtag      my $reinit;
 </form>      if ($crstype eq 'Community') {
 <form action="/adm/coursedocs" method="post" name="courseverify">          $reinit = &mt('(re-initialize community to access)');
   <div class="LC_docs_course_commands">      } else {
           $reinit = &mt('(re-initialize course to access)');
       <div>      }
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}      $line.='<td class="LC_docs_entry_commands"'.$tdalign.'><span class="LC_nobreak">'.$editlink.$renamelink;
       </div>      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
       <div>         $line.='<a href="'.$url.'"><img src="'.$icon.'" alt="" class="LC_icon" /></a>';
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}      } elsif ($url) {
       </div>         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
         $dumpbut                                               '<img src="'.$icon.'" alt="" class="LC_icon" />',600,500);
         $exportbut      } else {
       <div>         $line.='<img src="'.$icon.'" alt="" class="LC_icon" />';
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />      }
       </div>      $line.='</span></td><td'.$tdwidth.'>';
       <div>      if (($url=~m{/adm/(coursedocs|supplemental)}) || (!$allowed && $url)) {
         <input type="hidden" name="folder" value="$env{'form.folder'}" />         $line.='<a href="'.$url.'">'.$title.'</a>';
         <input type="submit" name="docslog" value="$lt{'sl'}" />      } elsif ($url) {
       </div>         $line.=&Apache::loncommon::modal_link($url.(($url=~/\?/)?'&amp;':'?').'inhibitmenu=yes',
   </div>                                               $title,600,500);
 </form>      } else {
 <div style="clear: both; height: 0px;">&nbsp;</div>         $line.=$title.' <span class="LC_docs_reinit_warn">'.$reinit.'</span>';
 ENDCOURSEVERIFY      }
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',      $line.="$extresform</td>";
      &mt('Editing the Table of Contents for your '.$type)));      $rand_pick_text = '&nbsp;' if ($rand_pick_text eq '');
     }      $rand_order_text = '&nbsp;' if ($rand_order_text eq '');
 # --------------------------------------------------------- Standard documents      if (($allowed) && ($folder!~/^supplemental/)) {
     $r->print('<table class="LC_docs_documents">');    my %lt=&Apache::lonlocal::texthash(
          'hd' => 'Hidden',
     if (($standard) && ($allowed) && (!$forcesupplement)) {         'ec' => 'URL hidden');
  $r->print('<tr><td class="LC_docs_document">');   my $enctext=
 #  '<h2>'.&mt('Main Course Documents').      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');   my $hidtext=
        my $folder=$env{'form.folder'};      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
        if ($folder eq '' || $folder eq 'supplemental') {          my $formhidden = 'edit_hiddenresource_'.$orderidx;
            $folder='default';          my $formurlhidden = 'edit_encrypturl_'.$orderidx;
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));   $line.=(<<ENDPARMS);
            $uploadtag = '<input type="hidden" name="folderpath" value="'.    <td class="LC_docs_entry_parameter">
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';      <form action="/adm/coursedocs" method="post" name="$formhidden">
        }      $form_common
        my $postexec='';      <label><input type="checkbox" name="hiddenresource_$orderidx" id="hiddenresource_$orderidx" onclick="checkForSubmit(this.form,'."'hiddenresource'".');" $hidtext /> $lt{'hd'}</label>
        if ($folder eq 'default') {      $form_end
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');      <br />
        } else {      <form action="/adm/coursedocs" method="post" name="$formurlhidden">
            #$postexec='self.close();';      $form_common
        }      <label><input type="checkbox" name="encrypturl_$orderidx" id="encrypturl_$orderidx" onclick="checkForSubmit(this.form,'."'encrypturl'".');" $enctext /> $lt{'ec'}</label>
        $hadchanges=0;      $form_end
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,    </td>
    $upload_output,$type);    <td class="LC_docs_entry_parameter">$rand_pick_text<br />
        if ($error) {                                        $rand_order_text</td>
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');  ENDPARMS
        }      }
        if ($hadchanges) {      $line.=&Apache::loncommon::end_data_table_row();
    &mark_hash_old();      return $line;
        }  }
        &changewarning($r,$postexec);  
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  sub new_timebased_suffix {
                      '.sequence';      my ($coursedom,$coursenum,$type,$area,$container) = @_;
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      my ($prefix,$namespace,$idtype,$errtext,$locknotfreed);
                      '.page';      if ($type eq 'map') {
  my $container='sequence';          $prefix = 'docs';
  if ($env{'form.pagepath'}) {          if ($area eq 'supplemental') {
     $container='page';              $prefix = 'supp';
  }          }
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;          $prefix .= $container;
           $namespace = 'uploadedmaps';
       } else {
           $prefix = $type;
  my $recoverform=(<<RFORM);          $namespace = 'templated';
  <form action="/adm/groupsort" method="post" name="recover">      }
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />      $idtype = 'concat';
  </form>      my ($suffix,$freedlock,$error) =
 RFORM          &Apache::lonnet::get_timebased_id($prefix,'num',$namespace,
                                             $coursedom,$coursenum);
  my $imspform=(<<IMSPFORM);      if (!$suffix) {
  <form action="/adm/imsimportdocs" method="post" name="ims">          if ($type eq 'map') {
  <input type="hidden" name="folder" value="$folder" />              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new folder/page.');
  <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />          } elsif ($type eq 'smppg') {
  </form>              $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new simple page.');
 IMSPFORM          } else {
               $errtext = &mt('Failed to acquire a unique timestamp-based suffix for the new bulletin board.');
  my $newnavform=(<<NNFORM);          }
  <form action="/adm/coursedocs" method="post" name="newnav">          if ($error) {
  $uploadtag              $errtext .= '<br />'.$error;
  <input type="hidden" name="importdetail"          }
  value="$lt{'navc'}=/adm/navmaps" />      }
  <span class="LC_nobreak">      if ($freedlock ne 'ok') {
  <input name="newnav" type="submit" value="$lt{'navc'}" />          $locknotfreed = 
  $help{'Navigate_Content'}              '<div class="LC_error">'.
  </span>              &mt('There was a problem removing a lockfile.').' ';
  </form>          if ($type eq 'map') {
 NNFORM              &mt('This will prevent creation of additional folders or composite pages in this course.');
  my $newsmppageform=(<<NSPFORM);          } elsif ($type eq 'smppg') {
  <form action="/adm/coursedocs" method="post" name="newsmppg">              $locknotfreed .=
  $uploadtag                  &mt('This will prevent creation of additional simple pages in this course.');
  <input type="hidden" name="importdetail" value="" />          } else {
  <span class="LC_nobreak">              $locknotfreed .=
  <input name="newsmppg" type="button" value="$lt{'sipa'}"                  &mt('This will prevent creation of additional bulletin boards in this course.');
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}          }
  </span>          $locknotfreed .=
  </form>              ' '.&mt('Please contact the domain coordinator for your LON-CAPA domain.').
 NSPFORM              '</div>';
       }
  my $newsmpproblemform=(<<NSPROBFORM);      return ($suffix,$errtext,$locknotfreed);
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">  }
  $uploadtag  
  <input type="hidden" name="importdetail" value="" />  =pod
  <span class="LC_nobreak">  
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"  =item tiehash()
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}  
  </span>  tie the hash
  </form>  
   =cut
 NSPROBFORM  
   sub tiehash {
  my $newdropboxform=(<<NDBFORM);      my ($mode)=@_;
  <form action="/adm/coursedocs" method="post" name="newdropbox">      $hashtied=0;
  $uploadtag            if ($env{'request.course.fn'}) {
  <input type="hidden" name="importdetail" value="" />   if ($mode eq 'write') {
  <span class="LC_nobreak">                if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
  <input name="newdropbox" type="button" value="$lt{'drbx'}"      &GDBM_WRCREAT(),0640)) {
  onClick="javascript:makedropbox();" />                  $hashtied=2;
  </span>              }
  </form>   } else {
 NDBFORM      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
       &GDBM_READER(),0640)) {
  my $newexuploadform=(<<NEXUFORM);                  $hashtied=1;
  <form action="/adm/coursedocs" method="post" name="newexamupload">      }
  $uploadtag   }
  <input type="hidden" name="importdetail" value="" />      }
  <span class="LC_nobreak">  }
  <input name="newexamupload" type="button" value="$lt{'scuf'}"  
  onClick="javascript:makeexamupload();" />  sub untiehash {
  $help{'Score_Upload_Form'}      if ($hashtied) { untie %hash; }
  </span>      $hashtied=0;
  </form>      return OK;
 NEXUFORM  }
   
  my $newbulform=(<<NBFORM);  
  <form action="/adm/coursedocs" method="post" name="newbul">  
  $uploadtag  
  <input type="hidden" name="importdetail" value="" />  sub checkonthis {
  <span class="LC_nobreak">      my ($r,$url,$level,$title)=@_;
  <input name="newbulletin" type="button" value="$lt{'bull'}"      $url=&unescape($url);
  onClick="javascript:makebulboard();" />      $alreadyseen{$url}=1;
  $help{'Bulletin Board'}      $r->rflush();
  </span>      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
  </form>         $r->print("\n<br />");
 NBFORM         if ($level==0) {
              $r->print("<br />");
  my $newaboutmeform=(<<NAMFORM);         }
  <form action="/adm/coursedocs" method="post" name="newaboutme">         for (my $i=0;$i<=$level*5;$i++) {
  $uploadtag             $r->print('&nbsp;');
  <input type="hidden" name="importdetail"         }
  value="$plainname=/adm/$udom/$uname/aboutme" />         $r->print('<a href="'.$url.'" target="cat">'.
  <span class="LC_nobreak">   ($title?$title:$url).'</a> ');
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />         if ($url=~/^\/res\//) {
  $help{'My Personal Info'}    my $result=&Apache::lonnet::repcopy(
  </span>                                &Apache::lonnet::filelocation('',$url));
  </form>            if ($result eq 'ok') {
 NAMFORM               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                $r->rflush();
  my $newaboutsomeoneform=(<<NASOFORM);               &Apache::lonnet::countacc($url);
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">               $url=~/\.(\w+)$/;
  $uploadtag               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
  <input type="hidden" name="importdetail" value="" />   $r->print('<br />');
  <span class="LC_nobreak">                   $r->rflush();
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"                   for (my $i=0;$i<=$level*5;$i++) {
  onClick="javascript:makeabout();" />                       $r->print('&nbsp;');
  </span>                   }
  </form>                   $r->print('- '.&mt('Rendering:').' ');
 NASOFORM   my ($errorcount,$warningcount)=split(/:/,
          &Apache::lonnet::ssi_body($url,
          ('grade_target'=>'web',
  my $newrosterform=(<<NROSTFORM);   'return_only_error_and_warning_counts' => 1)));
  <form action="/adm/coursedocs" method="post" name="newroster">                   if (($errorcount) ||
  $uploadtag                       ($warningcount)) {
  <input type="hidden" name="importdetail"       if ($errorcount) {
  value="$lt{'rost'}=/adm/viewclasslist" />                          $r->print('<img src="/adm/lonMisc/bomb.gif" alt="'.&mt('bomb').'" /><span class="LC_error">'.
  <span class="LC_nobreak">                            &mt('[quant,_1,error]',$errorcount).'</span>');
  <input name="newroster" type="submit" value="$lt{'rost'}" />                       }
  $help{'Course Roster'}       if ($warningcount) {
  </span>                          $r->print('<span class="LC_warning">'.
  </form>                            &mt('[quant,_1,warning]',$warningcount).'</span>');
 NROSTFORM                       }
                    } else {
        $r->print(<<ENDFORM);                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                    }
 <ul class="LC_TabContent">                   $r->rflush();
 <li>$lt{'nd'}</li>               }
 <li>$lt{'pm'}</li>       my $dependencies=
 <li>$lt{'pubd'}</li>                  &Apache::lonnet::metadata($url,'dependencies');
 <li>$lt{'sd'}</li>               foreach my $dep (split(/\,/,$dependencies)) {
 <li>$lt{'mo'}</li>   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 <li>$lt{'hao'}</li>                      &checkonthis($r,$dep,$level+1);
 </ul>                   }
                }
 <table class="LC_docs_adddocs">            } elsif ($result eq 'unavailable') {
 <!-- <tr>               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 <th>$lt{'uplm'}</th>            } elsif ($result eq 'not_found') {
 <th>$lt{'impp'}</th>        unless ($url=~/\$/) {
 <th>$lt{'spec'}</th>    $r->print('<span class="LC_error">'.&mt('not found').'</span>');
 </tr> -->        } else {
 <tr>    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
 <td>        }
 $fileuploadform            } else {
 </td>               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
 <td>            }
 $simpleeditdefaultform         }
 <hr />      }
 $recoverform  }
 ENDFORM  
        unless ($env{'form.pagepath'}) {  
    $r->print(<<ENDFORM);  
 <hr />  =pod
 $extresourcesform  
  <br />  =item list_symbs()
 $imspform  
 ENDFORM  List Content Identifiers
        }  
        $r->print('</td><td>');  =cut
        unless ($env{'form.pagepath'}) {  
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');  sub list_symbs {
       my ($r) = @_;
   
       my $crstype = &Apache::loncommon::course_type();
  my $newpageform=(<<NPFORM);      $r->print(&Apache::loncommon::start_page('List of Content Identifiers'));
  <form action="/adm/coursedocs" method="post" name="newpage">      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content Identifiers'));
  <input type="hidden" name="folderpath" value="$path" />      $r->print(&startContentScreen('tools'));
  <input type="hidden" name="importdetail" value="" />      my $navmap = Apache::lonnavmaps::navmap->new();
  <span class="LC_nobreak">      if (!defined($navmap)) {
  <input name="newpage" type="button"          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
  onClick="javascript:makenewpage(this.form,'$pageseq');"                    '<div class="LC_error">'.
  value="$lt{'newp'}" />$help{'Adding_Pages'}                    &mt('Unable to retrieve information about course contents').
  </span>                    '</div>');
  </form>          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 NPFORM      } else {
           $r->print('<h4 class="LC_info">'.&mt("$crstype Content Identifiers").'</h4>'.
  my $newfolderform=(<<NFFORM);                    &Apache::loncommon::start_data_table().
  <form action="/adm/coursedocs" method="post" name="newfolder">                    &Apache::loncommon::start_data_table_header_row().
  <input type="hidden" name="folderpath" value="$path" />                    '<th>'.&mt('Title').'</th><th>'.&mt('Identifier').'</th>'.
  <input type="hidden" name="importdetail" value="" />                    &Apache::loncommon::end_data_table_header_row()."\n");
  <span class="LC_nobreak">          my $count;
  <input name="newfolder" type="button"          foreach my $res ($navmap->retrieveResources()) {
  onClick="javascript:makenewfolder(this.form,'$folderseq');"              $r->print(&Apache::loncommon::start_data_table_row().
  value="$lt{'newf'}" />$help{'Adding_Folders'}                        '<td>'.$res->compTitle().'</td>'.
  </span>                        '<td>'.$res->symb().'</td>'.
  </form>                        &Apache::loncommon::end_data_table_row());
 NFFORM              $count ++;
           }
  my $newsylform=(<<NSYLFORM);          if (!$count) {
  <form action="/adm/coursedocs" method="post" name="newsyl">              $r->print(&Apache::loncommon::start_data_table_row().
  $uploadtag                        '<td colspan="2">'.&mt("$crstype is empty").'</td>'.
  <input type="hidden" name="importdetail"                        &Apache::loncommon::end_data_table_row()); 
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />          }
  <span class="LC_nobreak">          $r->print(&Apache::loncommon::end_data_table());
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      }
  $help{'Syllabus'}      $r->print(&endContentScreen());
  </span>  }
  </form>  
 NSYLFORM  
   sub verifycontent {
  my $newgroupfileform=(<<NGFFORM);      my ($r) = @_;
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">      my $crstype = &Apache::loncommon::course_type();
  $uploadtag      $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
  <input type="hidden" name="importdetail"      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />      $r->print(&startContentScreen('tools'));
  <span class="LC_nobreak">      $r->print('<h4 class="LC_info">'.&mt($crstype.' content verification').'</h4>'); 
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />     $hashtied=0;
  $help{'Group Files'}     undef %alreadyseen;
  </span>     %alreadyseen=();
  </form>     &tiehash();
 NGFFORM     
      foreach my $key (keys(%hash)) {
          if ($hash{$key}=~/\.(page|sequence)$/) {
            $r->print(<<ENDFORM);     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 <br />         $r->print('<hr /><span class="LC_error">'.
 $newfolderform   &mt('The following sequence or page is included more than once in your '.$crstype.':').' '.
 <br />   &unescape($hash{$key}).'</span><br />'.
 $newpageform   &mt('Note that grading records for problems included in this sequence or folder will overlap.').'<hr />');
 <br />     }
 $newsylform         }
 <br />         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 $newnavform             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
 <br />         }
 $newsmppageform     }
 <br />     &untiehash();
 $newsmpproblemform     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
 <br />      $r->print(&endContentScreen());
 $newdropboxform  }
 <br />  
 $newexuploadform  
 <br />  sub devalidateversioncache {
 $newbulform      my $src=shift;
 <br />      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
 $newaboutmeform    &Apache::lonnet::clutter($src));
 <br />  }
 $newaboutsomeoneform  
 <br />  sub checkversions {
 $newgroupfileform      my ($r) = @_;
 <br />      my $crstype = &Apache::loncommon::course_type();
 $newrosterform      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
 ENDFORM      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
        }      $r->print(&startContentScreen('tools'));
        if ($env{'form.pagepath'}) {  
            $r->print(<<ENDBLOCK);      my $header='';
 $newsmpproblemform      my $startsel='';
 <br />      my $monthsel='';
 $newexuploadform      my $weeksel='';
 ENDBLOCK      my $daysel='';
        }      my $allsel='';
        $r->print('</td></tr>'."\n".      my %changes=();
 '</table>');      my $starttime=0;
        $r->print('</td></tr>');      my $haschanged=0;
     }      my %setversions=&Apache::lonnet::dump('resourceversions',
 # ----------------------------------------------------- Supplemental documents    $env{'course.'.$env{'request.course.id'}.'.domain'},
     if (!$forcestandard) {    $env{'course.'.$env{'request.course.id'}.'.num'});
        $r->print('<tr><td class="LC_docs_document">');  
 # '<h2>'.&mt('Supplemental Course Documents').      $hashtied=0;
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');      &tiehash();
        my $folder=$env{'form.folder'};      my %newsetversions=();
        unless ($folder=~/^supplemental/) {      if ($env{'form.setmostrecent'}) {
    $folder='supplemental';   $haschanged=1;
        }   foreach my $key (keys(%hash)) {
        if ($folder =~ /^supplemental$/ &&      if ($key=~/^ids\_(\/res\/.+)$/) {
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {   $newsetversions{$1}='mostrecent';
           $env{'form.folderpath'} = 'supplemental&'.                  &devalidateversioncache($1);
                                     &escape(&mt('Supplemental '.$type.' Documents'));      }
        }   }
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);      } elsif ($env{'form.setcurrent'}) {
        if ($error) {   $haschanged=1;
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');   foreach my $key (keys(%hash)) {
        }      if ($key=~/^ids\_(\/res\/.+)$/) {
        if ($allowed) {   my $getvers=&Apache::lonnet::getversion($1);
    my $folderseq=   if ($getvers>0) {
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.      $newsetversions{$1}=$getvers;
        '.sequence';      &devalidateversioncache($1);
    }
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');      }
    }
  my $supupdocform=(<<SUPDOCFORM);      } elsif ($env{'form.setversions'}) {
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">   $haschanged=1;
  $fileupload   foreach my $key (keys(%env)) {
  <br />      if ($key=~/^form\.set_version_(.+)$/) {
  <br />   my $src=$1;
  <span class="LC_nobreak">   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
  $checkbox      $newsetversions{$src}=$env{$key};
  </span>      &devalidateversioncache($src);
  <br /><br />   }
  $lt{'comment'}:<br />      }
  <textarea cols=50 rows=4 name='comment'>   }
  </textarea>      }
  <br />      if ($haschanged) {
  <input type="hidden" name="folderpath" value="$path" />          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
  <input type="hidden" name="cmd" value="upload_supplemental" />    $env{'course.'.$env{'request.course.id'}.'.domain'},
  <span class="LC_nobreak">    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
  <input type="submit" value="$lt{'upld'}" />      $r->print(&Apache::loncommon::confirmwrapper(
  $help{'Uploading_From_Harddrive'}                  &Apache::lonhtmlcommon::confirm_success(&mt('Your Version Settings have been Saved'))));
  </span>   } else {
  </form>      $r->print(&Apache::loncommon::confirmwrapper(
 SUPDOCFORM                  &Apache::lonhtmlcommon::confirm_success(&mt('An Error Occured while Attempting to Save your Version Settings'),1)));
    }
  my $supnewfolderform=(<<SNFFORM);   &mark_hash_old();
  <form action="/adm/coursedocs" method="post" name="supnewfolder">      }
  <input type="hidden" name="folderpath" value="$path" />      &changewarning($r,'');
  <input type="hidden" name="importdetail" value="" />      if ($env{'form.timerange'} eq 'all') {
  <span class="LC_nobreak">  # show all documents
  <input name="newfolder" type="button"   $header=&mt('All Documents in '.$crstype);
  onClick="javascript:makenewfolder(this.form,'$folderseq');"   $allsel=' selected="selected"';
  value="$lt{'newf'}" /> $help{'Adding_Folders'}   foreach my $key (keys(%hash)) {
  </span>      if ($key=~/^ids\_(\/res\/.+)$/) {
  </form>   my $src=$1;
 SNFFORM   $changes{$src}=1;
       }
    }
  my $supnewextform=(<<SNEFORM);      } else {
  <form action="/adm/coursedocs" method="post" name="supnewext">  # show documents which changed
  <input type="hidden" name="folderpath" value="$path" />   %changes=&Apache::lonnet::dump
  <input type="hidden" name="importdetail" value="" />   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
  <span class="LC_nobreak">                       $env{'course.'.$env{'request.course.id'}.'.num'});
  <input name="newext" type="button"   my $firstkey=(keys(%changes))[0];
  onClick="javascript:makenewext('supnewext');"   unless ($firstkey=~/^error\:/) {
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      unless ($env{'form.timerange'}) {
  </span>   $env{'form.timerange'}=604800;
  </form>      }
 SNEFORM      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
    .&mt('seconds');
  my $supnewsylform=(<<SNSFORM);      if ($env{'form.timerange'}==-1) {
  <form action="/adm/coursedocs" method="post" name="supnewsyl">   $seltext='since start of course';
  <input type="hidden" name="folderpath" value="$path" />   $startsel=' selected="selected"';
  <input type="hidden" name="importdetail"   $env{'form.timerange'}=time;
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />      }
  <span class="LC_nobreak">      $starttime=time-$env{'form.timerange'};
  <input name="newsyl" type="submit" value="$lt{'syll'}" />      if ($env{'form.timerange'}==2592000) {
  $help{'Syllabus'}   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  </span>   $monthsel=' selected="selected"';
  </form>      } elsif ($env{'form.timerange'}==604800) {
 SNSFORM   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $weeksel=' selected="selected"';
  my $supnewaboutmeform=(<<SNAMFORM);      } elsif ($env{'form.timerange'}==86400) {
  <form action="/adm/coursedocs" method="post" name="subnewaboutme">   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  <input type="hidden" name="folderpath" value="$path" />   $daysel=' selected="selected"';
  <input type="hidden" name="importdetail"      }
  value="$plainname=/adm/$udom/$uname/aboutme" />      $header=&mt('Content changed').' '.$seltext;
  <span class="LC_nobreak">   } else {
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      $header=&mt('No content modifications yet.');
  $help{'My Personal Info'}   }
  </span>      }
  </form>      %setversions=&Apache::lonnet::dump('resourceversions',
 SNAMFORM    $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
    $r->print(<<ENDSUPFORM);      my %lt=&Apache::lonlocal::texthash
 <ul class="LC_TabContent">        ('st' => 'Version changes since start of '.$crstype,
 <li>$lt{'nd'}</li>         'lm' => 'Version changes since last Month',
 <li>$lt{'sd'}</li>         'lw' => 'Version changes since last Week',
 <li>$lt{'hao'}</li>         'sy' => 'Version changes since Yesterday',
 </ul>                 'al' => 'All Resources (possibly large output)',
 <table class="LC_docs_adddocs">                 'cd' => 'Change display', 
 <tr><td>         'sd' => 'Display',
 $supupdocform         'fi' => 'File',
 </td>         'md' => 'Modification Date',
 <td>                 'mr' => 'Most recently published Version',
 $supnewfolderform         've' => 'Version used in '.$crstype,
 <br />                 'vu' => 'Set Version to be used in '.$crstype,
 $supnewextform  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
 <br />  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 $supnewsylform  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
 <br />         'di' => 'Differences',
 $supnewaboutmeform         'save' => 'Save changes',
 </td></tr>                 'vers' => 'Version choice(s) for specific resources', 
 </table></td></tr>         'act' => 'Actions');
 ENDSUPFORM      $r->print(<<ENDHEADERS);
        }  <h4 class="LC_info">$header</h4>
     }  <form action="/adm/coursedocs" method="post">
     $r->print('</table>');  <input type="hidden" name="versions" value="1" />
     if ($allowed) {  <div class="LC_left_float">
  $r->print('  <fieldset>
 <form method="post" name="extimport" action="/adm/coursedocs">  <legend>$lt{'cd'}</legend>
   <input type="hidden" name="title" />  <select name="timerange">
   <input type="hidden" name="url" />  <option value='all'$allsel>$lt{'al'}</option>
   <input type="hidden" name="useform" />  <option value="-1"$startsel>$lt{'st'}</option>
   <input type="hidden" name="residx" />  <option value="2592000"$monthsel>$lt{'lm'}</option>
 </form>');  <option value="604800"$weeksel>$lt{'lw'}</option>
     }  <option value="86400"$daysel>$lt{'sy'}</option>
   } else {  </select>
       unless ($upload_result eq 'phasetwo') {  <input type="submit" name="display" value="$lt{'sd'}" />
 # -------------------------------------------------------- This is showdoc mode  </fieldset>
           $r->print("<h1>".&mt('Uploaded Document').' - '.  </div>
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.  <div class="LC_left_float">
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".  <fieldset>
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');  <legend>$lt{'act'}</legend>
       }  $lt{'sm'}: <input type="submit" name="setmostrecent" value="Go" /><br />
   }  $lt{'sc'}: <input type="submit" name="setcurrent" value="Go" />
  }  </fieldset>
  $r->print(&Apache::loncommon::end_page());  </div>
  return OK;  <br clear="all" />
 }  <hr />
   <h4>$lt{'vers'}</h4>
   <input type="submit" name="setversions" value="$lt{'save'}" />
 sub editing_js {  ENDHEADERS
     my ($udom,$uname) = @_;      #number of columns for version history
     my $now = time();      $r->print(
     my %lt = &Apache::lonlocal::texthash(          &Apache::loncommon::start_data_table().
                                           p_mnf => 'Name of New Folder',          &Apache::loncommon::start_data_table_header_row().
                                           t_mnf => 'New Folder',          '<th>'.&mt('Resources').'</th>'.
                                           p_mnp => 'Name of New Page',          "<th>$lt{'mr'}</th>".
                                           t_mnp => 'New Page',          "<th>$lt{'ve'}</th>".
                                           p_mxu => 'Title for the Uploaded Score',          "<th>$lt{'vu'}</th>".
                                           p_msp => 'Title for the Page',          '<th>'.&mt('History').'</th>'.
                                           p_msb => 'Title for the Problem',          &Apache::loncommon::end_data_table_header_row()
                                           p_mdb => 'Title for the Drop Box',      );
                                           p_mbb => 'Title for the Bulletin Board',      foreach my $key (sort(keys(%changes))) {
                                           p_mab => "Enter user:domain for User's 'About Me' Page",          #excludes not versionable problems from resource version history:
                                           p_mab2 => "About [_99]",          next unless ($changes{$key}>$starttime && $key !~ /^\/res\/lib\/templates/);
                                           p_mab_alrt1 => 'Not a valid user:domain',          my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',          my $currentversion=&Apache::lonnet::getversion($key);
                                           p_chn => 'New Title',          if ($currentversion<0) {
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',              $currentversion='<span class="LC_error">'.&mt('Could not be determined.').'</span>';
                                           p_rmr2a => 'Remove[_99]',          }
                                           p_rmr2b => '?[_99]',          my $linkurl=&Apache::lonnet::clutter($key);
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',          $r->print(
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',              &Apache::loncommon::start_data_table_row().
                                           p_ctr2a => 'Cut[_98]',              '<td><b>'.&Apache::lonnet::gettitle($linkurl).'</b><br />'.
                                           p_ctr2b => '?[_98]'              '<a href="'.$linkurl.'" target="cat">'.$linkurl.'</a></td>'.
                                         );              '<td align="right">'.$currentversion.'<span class="LC_fontsize_medium"><br />('.
               &Apache::lonlocal::locallocaltime(&Apache::lonnet::metadata($root.'.'.$extension,'lastrevisiondate')).')</span></td>'.
     return <<ENDNEWSCRIPT;              '<td align="right">'
 function makenewfolder(targetform,folderseq) {          );
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');          # Used in course
     if (foldername) {          my $usedversion=$hash{'version_'.$linkurl};
        targetform.importdetail.value=escape(foldername)+"="+folderseq;          if (($usedversion) && ($usedversion ne 'mostrecent')) {
         targetform.submit();                  if ($usedversion != $currentversion) {
     }                      $r->print('<span class="LC_warning">'.$usedversion.'</span>');
 }                  } else {
                       $r->print($usedversion);
 function makenewpage(targetform,folderseq) {                  }
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');              } else {
     if (pagename) {                  $r->print($currentversion);
         targetform.importdetail.value=escape(pagename)+"="+folderseq;              }
         targetform.submit();          $r->print('</td><td title="'.$lt{'vu'}.'">');
     }          # Set version
 }          $r->print(&Apache::loncommon::select_form(
               $setversions{$linkurl},
 function makenewext(targetname) {              'set_version_'.$linkurl,
     this.document.forms.extimport.useform.value=targetname;              {'select_form_order' => ['',1..$currentversion,'mostrecent'],
     this.document.forms.extimport.title.value='';               '' => '',
     this.document.forms.extimport.url.value='';               'mostrecent' => &mt('most recent'),
     this.document.forms.extimport.residx.value='';               map {$_,$_} (1..$currentversion)}));
     window.open('/adm/rat/extpickframe.html');          my $lastold=1;
 }          for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
               my $url=$root.'.'.$prevvers.'.'.$extension;
 function edittext(targetname,residx,title,url) {              if (&Apache::lonnet::metadata($url,'lastrevisiondate')<$starttime) {
     this.document.forms.extimport.useform.value=targetname;                  $lastold=$prevvers;
     this.document.forms.extimport.residx.value=residx;              }
     this.document.forms.extimport.url.value=url;          }
     this.document.forms.extimport.title.value=title;          $r->print('</td>');
     window.open('/adm/rat/extpickframe.html');          # List all available versions
 }          $r->print('<td valign="top"><span class="LC_fontsize_medium">');
           for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
 function makeexamupload() {              my $url=$root.'.'.$prevvers.'.'.$extension;
    var title=prompt('$lt{"p_mxu"}');              $r->print(
    if (title) {                  '<span class="LC_nobreak">'
     this.document.forms.newexamupload.importdetail.value=                 .'<a href="'.&Apache::lonnet::clutter($url).'">'
  escape(title)+'=/res/lib/templates/examupload.problem';                 .&mt('Version [_1]',$prevvers).'</a>'
     this.document.forms.newexamupload.submit();                 .' ('.&Apache::lonlocal::locallocaltime(
    }                           &Apache::lonnet::metadata($url,'lastrevisiondate'))
 }                 .')');
               if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
 function makesmppage() {                  $r->print(
    var title=prompt('$lt{"p_msp"}');                      ' <a href="/adm/diff?filename='.
    if (title) {                      &Apache::lonnet::clutter($root.'.'.$extension).
     this.document.forms.newsmppg.importdetail.value=                      &HTML::Entities::encode('&versionone='.$prevvers,'"<>&').
  escape(title)+'=/adm/$udom/$uname/$now/smppg';                      '" target="diffs">'.&mt('Diffs').'</a>');
     this.document.forms.newsmppg.submit();              }
    }              $r->print('</span><br />');
 }          }
           $r->print('</span></td>'.&Apache::loncommon::end_data_table_row());
 function makesmpproblem() {      }
    var title=prompt('$lt{"p_msb"}');      $r->print(
    if (title) {          &Apache::loncommon::end_data_table().
     this.document.forms.newsmpproblem.importdetail.value=          '<input type="submit" name="setversions" value="'.$lt{'save'}.'" />'.
  escape(title)+'=/res/lib/templates/simpleproblem.problem';          '</form>'
     this.document.forms.newsmpproblem.submit();      );
    }  
 }      &untiehash();
       $r->print(&endContentScreen());
 function makedropbox() {  }
    var title=prompt('$lt{"p_mdb"}');  
    if (title) {  sub mark_hash_old {
     this.document.forms.newdropbox.importdetail.value=      my $retie_hash=0;
         escape(title)+'=/res/lib/templates/DropBox.problem';      if ($hashtied) {
     this.document.forms.newdropbox.submit();   $retie_hash=1;
    }   &untiehash();
 }      }
       &tiehash('write');
 function makebulboard() {      $hash{'old'}=1;
    var title=prompt('$lt{"p_mbb"}');      &untiehash();
    if (title) {      if ($retie_hash) { &tiehash(); }
     this.document.forms.newbul.importdetail.value=  }
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';  
     this.document.forms.newbul.submit();  sub is_hash_old {
    }      my $untie_hash=0;
 }      if (!$hashtied) {
    $untie_hash=1;
 function makeabout() {   &tiehash();
    var user=prompt("$lt{'p_mab'}");      }
    if (user) {      my $return=$hash{'old'};
        var comp=new Array();      if ($untie_hash) { &untiehash(); }
        comp=user.split(':');      return $return;
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {  }
    if ((comp[0]) && (comp[1])) {  
        this.document.forms.newaboutsomeone.importdetail.value=  sub changewarning {
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';      my ($r,$postexec,$message,$url)=@_;
        this.document.forms.newaboutsomeone.submit();      if (!&is_hash_old()) { return; }
    } else {      my $pathvar='folderpath';
                alert("$lt{'p_mab_alrt1'}");      my $path=&escape($env{'form.folderpath'});
            }      if (!defined($url)) {
        } else {   $url='/adm/coursedocs?'.$pathvar.'='.$path;
            alert("$lt{'p_mab_alrt2'}");      }
        }      my $course_type = &Apache::loncommon::course_type();
    }      if (!defined($message)) {
 }   $message='Changes will become active for your current session after [_1], or the next time you log in.';
       }
 function makeims() {      $r->print("\n\n".
     var caller = document.forms.ims.folder.value;  '<script type="text/javascript">'."\n".
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";  '// <![CDATA['."\n".
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
     newWindow.location.href = newlocation;  '// ]]>'."\n".
 }  '</script>'."\n".
   '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
   '<input type="hidden" name="orgurl" value="'.$url.
 function finishpick() {  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
     var title=this.document.forms.extimport.title.value;  &mt($message,' <input type="hidden" name="'.
     var url=this.document.forms.extimport.url.value;      $env{'request.role'}.'" value="1" /><input type="button" value="'.
     var form=this.document.forms.extimport.useform.value;      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
     var residx=this.document.forms.extimport.residx.value;  $help{'Caching'}.'</p></form>'."\n\n");
     eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');  }
 }  
   
 function changename(folderpath,index,oldtitle,container,pagesymb) {  sub init_breadcrumbs {
     var title=prompt('$lt{"p_chn"}',oldtitle);      my ($form,$text)=@_;
     if (title) {      &Apache::lonhtmlcommon::clear_breadcrumbs();
  this.document.forms.renameform.markcopy.value=-1;      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?tools=1",
  this.document.forms.renameform.title.value=title;      text=>&Apache::loncommon::course_type().' Editor',
  this.document.forms.renameform.cmd.value='rename_'+index;      faq=>273,
         if (container == 'sequence') {      bug=>'Instructor Interface',
     this.document.forms.renameform.folderpath.value=folderpath;                                              help => 'Docs_Adding_Course_Doc'});
         }      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
         if (container == 'page') {      text=>$text,
             this.document.forms.renameform.pagepath.value=folderpath;      faq=>273,
             this.document.forms.renameform.pagesymb.value=pagesymb;      bug=>'Instructor Interface'});
         }  }
         this.document.forms.renameform.submit();  
     }  # subroutine to list form elements
 }  sub create_list_elements {
      my @formarr = @_;
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {     my $list = '';
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {     foreach my $button (@formarr){
  this.document.forms.renameform.markcopy.value=-1;          foreach my $picture (keys(%{$button})) {
  this.document.forms.renameform.cmd.value='del_'+index;              $list .= &Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text', id => ''});
         if (container == 'sequence') {          }
             this.document.forms.renameform.folderpath.value=folderpath;     }
         }     return $list;
         if (container == 'page') {  }
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  # subroutine to create ul from list elements
         }  sub create_form_ul {
         this.document.forms.renameform.submit();     my $list = shift;
     }     my $ul = &Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
 }     return $ul;
   }
 function cutres(folderpath,index,oldtitle,container,pagesymb,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;  # Start tabs
  this.document.forms.renameform.markcopy.value=index;  #
  this.document.forms.renameform.copyfolder.value=folder+'.'+container;  
         if (container == 'sequence') {  sub startContentScreen {
             this.document.forms.renameform.folderpath.value=folderpath;      my ($mode) = @_;
         }      my $output = '<ul class="LC_TabContentBigger" id="mainnav">';
         if (container == 'page') {      if (($mode eq 'navmaps') || ($mode eq 'supplemental')) {
             this.document.forms.renameform.pagepath.value=folderpath;          $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";
             this.document.forms.renameform.pagesymb.value=pagesymb;          $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";
         }          $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";
         this.document.forms.renameform.submit();          $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";
           $output .= '<li '.(($mode eq 'suppdocs')?' class="active"':'').'><a href="/adm/coursedocs?forcesupplement=1"><b>'.&mt('Supplemental Content Editor').'</b></a></li>'."\n";
 function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {          $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=index;                     '><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.copyfolder.value=folder+'.'+container;      }
     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
   #
   
 ENDNEWSCRIPT  sub endContentScreen {
 }      return '</div></div></div>';
 1;  }
 __END__  
   sub supplemental_base {
       return 'supplemental&'.&escape(&mt('Supplemental '.&Apache::loncommon::course_type().' Content'));
 =head1 NAME  }
   
 Apache::londocs.pm  sub handler {
       my $r = shift;
 =head1 SYNOPSIS      &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
 This is part of the LearningOnline Network with CAPA project      return OK if $r->header_only;
 described at http://www.lon-capa.org.  
   # get course data
 =head1 SUBROUTINES      my $crstype = &Apache::loncommon::course_type();
       my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 =over      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
   
 =item %help=()  # graphics settings
       $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL').'/');
 Available help topics  
   #
 =item mapread()  # --------------------------------------------- Initialize help topics for this
       foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
 Mapread read maps into LONCAPA::map:: global arrays                 'Adding_External_Resource','Navigate_Content',
 @order and @resources, determines status                 'Adding_Folders','Docs_Overview', 'Load_Map',
 sets @order - pointer to resources in right order                 'Supplemental','Score_Upload_Form','Adding_Pages',
 sets @resources - array with the resources with correct idx                 'Importing_LON-CAPA_Resource','Importing_IMS_Course',
                          'Uploading_From_Harddrive',
 =item authorhosts()                 'Check_Resource_Versions','Verify_Content') {
    $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 Return hash with valid author names      }
       # Composite help files
 =item dumpbutton()      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 Generate "dump" button      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 =item clean()      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
 =item dumpcourse()      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
     Actually dump course      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
     'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
       $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 =item exportbutton()      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
       $help{'Course Roster'} = &Apache::loncommon::help_open_topic('Docs_Course_Roster');
     Generate "export" button      $help{'Web Page'} =  &Apache::loncommon::help_open_topic('Docs_Web_Page');
    
 =item exportcourse()      my $allowed;
   # URI is /adm/supplemental when viewing supplemental docs in non-edit mode.
 =item create_ims_store()      unless ($r->uri eq '/adm/supplemental') {
           # does this user have privileges to modify content.  
 =item build_package()          $allowed = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
       }
 =item get_dependencies()  
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['chooseserver',
 =item process_content()                                              'inhibitmenu']);
     if ($allowed && $env{'form.chooseserver'}) {
 =item replicate_content()        &choose_dump_server($r);
         return OK;
 =item extract_media()    } elsif ($allowed && $env{'form.verify'}) {
         &init_breadcrumbs('verify','Verify Content');
 =item store_template()        &verifycontent($r);
     } elsif ($allowed && $env{'form.listsymbs'}) {
 =item group_import()        &init_breadcrumbs('listsymbs','List Content IDs');
         &list_symbs($r);
     Imports the given (name, url) resources into the course    } elsif ($allowed && $env{'form.docslog'}) {
     coursenum, coursedom, and folder must precede the list        &init_breadcrumbs('docslog','Show Log');
         my $folder = $env{'form.folder'};
 =item breadcrumbs()        if ($folder eq '') {
             $folder='default';
 =item log_docs()        }
         &docs_change_log($r,$coursenum,$coursedom,$folder,$allowed,$crstype,$iconpath);
 =item docs_change_log()    } elsif ($allowed && $env{'form.versions'}) {
         &init_breadcrumbs('versions','Check/Set Resource Versions');
 =item update_paste_buffer()        &checkversions($r);
     } elsif ($allowed && $env{'form.dumpcourse'}) {
 =item print_paste_buffer()        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' Content to Authoring Space');
         &dumpcourse($r);
 =item do_paste_from_buffer()    } elsif ($allowed && $env{'form.exportcourse'}) {
         &init_breadcrumbs('exportcourse','IMS Export');
 =item update_parameter()        &Apache::imsexport::exportcourse($r);
     } else {
 =item handle_edit_cmd()  #
   # Done catching special calls
 =item editor()  # The whole rest is for course and supplemental documents and utilities menu
   # Get the parameters that may be needed
 =item process_file_upload()  #
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 =item process_secondary_uploads()                                              ['folderpath',
                                                'forcesupplement','forcestandard',
 =item is_supplemental_title()                                               'tools','symb','command','supppath']);
   
 =item parse_supplemental_title()  # standard=1: this is a "new-style" course with an uploaded map as top level
   # standard=2: this is a "old-style" course, and there is nothing we can do
 =item entryline()  
       my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 =item tiehash()  
   # Decide whether this should display supplemental or main content or utilities
 =item untiehash()  # supplementalflag=1: show supplemental documents
   # supplementalflag=0: show standard documents
 =item checkonthis()  # toolsflag=1: show utilities
   
 check on this  
       my $supplementalflag=($env{'form.folderpath'}=~/^supplemental/);
 =item verifycontent()      if (($env{'form.folderpath'}=~/^default/) || ($env{'form.folderpath'} eq "")) {
          $supplementalflag=0;
 Verify Content      }
       if ($env{'form.forcesupplement'}) { $supplementalflag=1; }
 =item devalidateversioncache() & checkversions()      if ($env{'form.forcestandard'})   { $supplementalflag=0; }
       unless ($allowed) { $supplementalflag=1; }
 Check Versions      unless ($standard) { $supplementalflag=1; }
       my $toolsflag=0;
 =item mark_hash_old()      if ($env{'form.tools'}) { $toolsflag=1; }
   
 =item is_hash_old()      my $script='';
       my $showdoc=0;
 =item changewarning()      my $addentries = {};
       my $container;
 =item init_breadcrumbs()      my $containertag;
       my $pathitem;
 Breadcrumbs for special functions  
   # Do we directly jump somewhere?
 =back  
      if (($env{'form.command'} eq 'direct') || ($env{'form.command'} eq 'directnav')) {
 =cut         if ($env{'form.symb'} ne '') {
              $env{'form.folderpath'}=
                  &Apache::loncommon::symb_to_docspath($env{'form.symb'});
              &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
                  $env{'form.command'}.'_'.$env{'form.symb'}});
          } elsif ($env{'form.supppath'} ne '') {
              $env{'form.folderpath'}=$env{'form.supppath'};
              &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} =>
                  $env{'form.command'}.'_'.$env{'form.supppath'}});
          }
      } elsif ($env{'form.command'} eq 'editdocs') {
          $env{'form.folderpath'} = 'default&'.
                                    &Apache::lonhtmlcommon::entity_encode('Main Course Content').
                                    ':::::';
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => $env{'form.command'}});
      } elsif ($env{'form.command'} eq 'editsupp') {
          $env{'form.folderpath'} = 'supplemental&'.
                                     &Apache::lonhtmlcommon::entity_encode('Supplemental Content');
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/supplemental'});
      } elsif ($env{'form.command'} eq 'contents') {
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/navmaps'});
      } elsif ($env{'form.command'} eq 'home') {
          &Apache::lonnet::appenv({'docs.exit.'.$env{'request.course.id'} => '/adm/menu'});
      }
   
   
   # Where do we store these for when we come back?
       my $stored_folderpath='docs_folderpath';
       if ($supplementalflag) {
          $stored_folderpath='docs_sup_folderpath';
       }
   
   # 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.326  
changed lines
  Added in v.1.537


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