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

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

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


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