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

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


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