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

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

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


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