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

version 1.151, 2004/12/10 19:22:29 version 1.326, 2009/01/28 11:51:22
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;  
   
 use strict;  package Apache::londocs;
 use Apache::Constants qw(:common :http);  
 use Apache::lonnet;  use strict;
 use Apache::loncommon;  use Apache::Constants qw(:common :http);
 use Apache::lonratedt;  use Apache::imsexport;
 use Apache::lonratsrv;  use Apache::lonnet;
 use Apache::lonxml;  use Apache::loncommon;
 use Apache::loncreatecourse;  use LONCAPA::map();
 use Apache::lonnavmaps;  use Apache::lonratedt();
 use HTML::Entities;  use Apache::lonxml;
 use GDBM_File;  use Apache::lonclonecourse;
 use Apache::lonlocal;  use Apache::lonnavmaps;
 use Cwd;  use HTML::Entities;
   use GDBM_File;
 my $iconpath;  use Apache::lonlocal;
   use Cwd;
 my %hash;  use LONCAPA qw(:DEFAULT :match);
   
 my $hashtied;  my $iconpath;
 my %alreadyseen=();  
   my %hash;
 my $hadchanges;  
   my $hashtied;
 # Available help topics  my %alreadyseen=();
   
 my %help=();  my $hadchanges;
   
 # Mapread read maps into lonratedt::global arrays   
 # @order and @resources, determines status  my %help=();
 # sets @order - pointer to resources in right order  
 # sets @resources - array with the resources with correct idx  
 #  sub mapread {
       my ($coursenum,$coursedom,$map)=@_;
 sub mapread {      return
     my ($coursenum,$coursedom,$map)=@_;        &LONCAPA::map::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
     return       $map);
       &Apache::lonratedt::mapread('/uploaded/'.$coursedom.'/'.$coursenum.'/'.  }
                                 $map);  
 }  sub storemap {
       my ($coursenum,$coursedom,$map)=@_;
 sub storemap {      my ($outtext,$errtext)=
     my ($coursenum,$coursedom,$map)=@_;        &LONCAPA::map::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.
     my ($outtext,$errtext)=        $map,1);
       &Apache::lonratedt::storemap('/uploaded/'.$coursedom.'/'.$coursenum.'/'.      if ($errtext) { return ($errtext,2); }
                                 $map,1);     
     if ($errtext) { return ($errtext,2); }      $hadchanges=1;
           return ($errtext,0);
     $hadchanges=1;  }
     return ($errtext,0);  
 }  
   
 # ----------------------------------------- Return hash with valid author names  sub authorhosts {
       my %outhash=();
 sub authorhosts {      my $home=0;
     my %outhash=();      my $other=0;
     my $home=0;      foreach my $key (keys(%env)) {
     my $other=0;   if ($key=~/^user\.role\.(au|ca)\.(.+)$/) {
     foreach (keys %ENV) {      my $role=$1;
  if ($_=~/^user\.role\.(au|ca)\.(.+)$/) {      my $realm=$2;
     my $role=$1;      my ($start,$end)=split(/\./,$env{$key});
     my $realm=$2;      if (($start) && ($start>time)) { next; }
     my ($start,$end)=split(/\./,$ENV{$_});      if (($end) && (time>$end)) { next; }
     if (($start) && ($start>time)) { next; }      my ($ca,$cd);
     if (($end) && (time>$end)) { next; }      if ($1 eq 'au') {
     my $ca; my $cd;   $ca=$env{'user.name'};
     if ($1 eq 'au') {   $cd=$env{'user.domain'};
  $ca=$ENV{'user.name'};      } else {
  $cd=$ENV{'user.domain'};   ($cd,$ca)=($realm=~/^\/($match_domain)\/($match_username)$/);
     } else {      }
  ($cd,$ca)=($realm=~/^\/(\w+)\/(\w+)$/);      my $allowed=0;
     }      my $myhome=&Apache::lonnet::homeserver($ca,$cd);
     my $allowed=0;      my @ids=&Apache::lonnet::current_machine_ids();
     my $myhome=&Apache::lonnet::homeserver($ca,$cd);      foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }
     my @ids=&Apache::lonnet::current_machine_ids();      if ($allowed) {
     foreach my $id (@ids) { if ($id eq $myhome) { $allowed=1; } }   $home++;
     if ($allowed) {   $outhash{'home_'.$ca.'@'.$cd}=1;
  $home++;      } else {
  $outhash{'home_'.$ca.'@'.$cd}=1;   $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;
     } else {   $other++;
  $outhash{'otherhome_'.$ca.'@'.$cd}=$myhome;      }
  $other++;   }
     }      }
  }      return ($home,$other,%outhash);
     }  }
     return ($home,$other,%outhash);  
 }  
 # ------------------------------------------------------ Generate "dump" button  sub dumpbutton {
       my ($home,$other,%outhash)=&authorhosts();
 sub dumpbutton {      my $type = &Apache::loncommon::course_type();
     my ($home,$other,%outhash)=&authorhosts();      if ($home+$other==0) { return ''; }
     if ($home+$other==0) { return ''; }      if ($home) {
     my $output='</td><td bgcolor="#DDDDCC">';   return '<div>'.
     if ($home) {      '<input type="submit" name="dumpcourse" value="'.
  return '</td><td bgcolor="#DDDDCC">'.      &mt('Dump '.$type.' DOCS to Construction Space').'" />'.
     '<input type="submit" name="dumpcourse" value="'.      &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs').
     &mt('Dump Course DOCS to Construction Space').'" />'.      '</div>';
     &Apache::loncommon::help_open_topic('Docs_Dump_Course_Docs');      } else {
     } else {   return '<div>'.
  return'</td><td bgcolor="#DDDDCC">'.       &mt('Dump '.$type.
      &mt('Dump Course DOCS to Construction Space: available on other servers');   ' DOCS to Construction Space: available on other servers').
     }   '</div>';
 }      }
   }
 # -------------------------------------------------------- Actually dump course  
   sub clean {
 sub dumpcourse {      my ($title)=@_;
     my $r=shift;      $title=~s/[^\w\/\!\$\%\^\*\-\_\=\+\;\:\,\\\|\`\~]+/\_/gs;
     $r->print('<html><head><title>Dump DOCS</title></head>'.      return $title;
         &Apache::loncommon::bodytag('Dump Course DOCS to Construction Space').  }
       '<form name="dumpdoc" method="post">');  
     my ($home,$other,%outhash)=&authorhosts();  
     unless ($home) { return ''; }  
     my $origcrsid=$ENV{'request.course.id'};  sub dumpcourse {
     my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);      my ($r) = @_;
     if (($ENV{'form.authorspace'}) && ($ENV{'form.authorfolder'}=~/\w/)) {      my $type = &Apache::loncommon::course_type();
 # Do the dumping      $r->print(&Apache::loncommon::start_page('Dump '.$type.' DOCS to Construction Space').
  unless ($outhash{'home_'.$ENV{'form.authorspace'}}) { return ''; }        '<form name="dumpdoc" method="post">');
  my ($ca,$cd)=split(/\@/,$ENV{'form.authorspace'});      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Dump '.$type.' DOCS to Construction Space'));
  $r->print('<h3>'.&mt('Copying Files').'</h3>');      my ($home,$other,%outhash)=&authorhosts();
  my $title=$ENV{'form.authorfolder'};      unless ($home) { return ''; }
  $title=~s/[^\w\/]+/\_/g;      my $origcrsid=$env{'request.course.id'};
  my %replacehash=();      my %origcrsdata=&Apache::lonnet::coursedescription($origcrsid);
  foreach (keys %ENV) {      if (($env{'form.authorspace'}) && ($env{'form.authorfolder'}=~/\w/)) {
     if ($_=~/^form\.namefor\_(.+)/) {  # Do the dumping
  $replacehash{$1}=$ENV{$_};   unless ($outhash{'home_'.$env{'form.authorspace'}}) { return ''; }
     }   my ($ca,$cd)=split(/\@/,$env{'form.authorspace'});
  }   $r->print('<h3>'.&mt('Copying Files').'</h3>');
  my $crs='/uploaded/'.$ENV{'request.course.id'}.'/';   my $title=$env{'form.authorfolder'};
  $crs=~s/\_/\//g;   $title=&clean($title);
  foreach (keys %replacehash) {   my %replacehash=();
     my $newfilename=$title.'/'.$replacehash{$_};   foreach my $key (keys(%env)) {
     $newfilename=~s/[^\w\/\.\/]+/\_/g;      if ($key=~/^form\.namefor\_(.+)/) {
     my @dirs=split(/\//,$newfilename);   $replacehash{$1}=$env{$key};
     my $path='/home/'.$ca.'/public_html';      }
     my $makepath=$path;   }
     my $fail=0;   my $crs='/uploaded/'.$env{'request.course.id'}.'/';
     for (my $i=0;$i<$#dirs;$i++) {   $crs=~s/\_/\//g;
  $makepath.='/'.$dirs[$i];   foreach my $item (keys(%replacehash)) {
  unless (-e $makepath) {       my $newfilename=$title.'/'.$replacehash{$item};
     unless(mkdir($makepath,0777)) { $fail=1; }       $newfilename=~s/\.(\w+)$//;
  }      my $ext=$1;
     }      $newfilename=&clean($newfilename);
     $r->print('<br /><tt>'.$_.'</tt> => <tt>'.$newfilename.'</tt>: ');      $newfilename.='.'.$ext;
     if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {      my @dirs=split(/\//,$newfilename);
  if ($_=~/\.(sequence|page|html|htm|xml|xhtml)$/) {      my $path='/home/'.$ca.'/public_html';
     print $fh &Apache::loncreatecourse::rewritefile(      my $makepath=$path;
          &Apache::loncreatecourse::readfile($ENV{'request.course.id'},$_),      my $fail=0;
      (%replacehash,$crs => '')      for (my $i=0;$i<$#dirs;$i++) {
     );   $makepath.='/'.$dirs[$i];
  } else {   unless (-e $makepath) {
     print $fh      unless(mkdir($makepath,0777)) { $fail=1; }
          &Apache::loncreatecourse::readfile($ENV{'request.course.id'},$_);   }
        }      }
  $fh->close();      $r->print('<br /><tt>'.$item.'</tt> => <tt>'.$newfilename.'</tt>: ');
     } else {      if (my $fh=Apache::File->new('>'.$path.'/'.$newfilename)) {
  $fail=1;   if ($item=~/\.(sequence|page|html|htm|xml|xhtml)$/) {
     }      print $fh &Apache::lonclonecourse::rewritefile(
     if ($fail) {           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item),
  $r->print('<font color="red">fail</font>');       (%replacehash,$crs => '')
     } else {      );
  $r->print('<font color="green">ok</font>');   } else {
     }      print $fh
  }           &Apache::lonclonecourse::readfile($env{'request.course.id'},$item);
     } else {         }
 # Input form   $fh->close();
  unless ($home==1) {      } else {
     $r->print(   $fail=1;
       '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');      }
  }      if ($fail) {
  foreach (sort keys %outhash) {   $r->print('<span class="LC_error">'.&mt('fail').'</span>');
     if ($_=~/^home_(.+)$/) {      } else {
  if ($home==1) {   $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     $r->print(      }
   '<input type="hidden" name="authorspace" value="'.$1.'" />');   }
  } else {      } else {
     $r->print('<option value="'.$1.'">'.$1.' - '.  # Input form
       &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');   unless ($home==1) {
  }      $r->print(
     }        '<h3>'.&mt('Select the Construction Space').'</h3><select name="authorspace">');
  }   }
  unless ($home==1) {   foreach my $key (sort(keys(%outhash))) {
     $r->print('</select>');      if ($key=~/^home_(.+)$/) {
  }   if ($home==1) {
  my $title=$origcrsdata{'description'};      $r->print(
  $title=~s/\s+/\_/gs;    '<input type="hidden" name="authorspace" value="'.$1.'" />');
  $title=~s/\W//gs;   } else {
  $r->print('<h3>'.&mt('Folder in Construction Space').'</h3><input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');      $r->print('<option value="'.$1.'">'.$1.' - '.
  &tiehash();        &Apache::loncommon::plainname(split(/\@/,$1)).'</option>');
  $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3><table border="2"><tr><th>'.&mt('Internal Filename').'</th><th>'.&mt('Title').'</th><th>'.&mt('Save as ...').'</th></tr>');   }
  foreach (&Apache::loncreatecourse::crsdirlist($origcrsid,'userfiles')) {      }
     $r->print('<tr><td>'.$_.'</td>');   }
     my ($ext)=($_=~/\.(\w+)$/);   unless ($home==1) {
     my $title=$hash{'title_'.$hash{      $r->print('</select>');
  'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$_}};   }
     $r->print('<td>'.($title?$title:'&nbsp;').'</td>');   my $title=$origcrsdata{'description'};
     unless ($title) {   $title=~s/[\/\s]+/\_/gs;
  $title=$_;   $title=&clean($title);
     }   $r->print('<h3>'.&mt('Folder in Construction Space').'</h3>'
     $title=~s/\.(\w+)$//;                   .'<input type="text" size="50" name="authorfolder" value="'.$title.'" /><br />');
     $title=~s/[^\w\/]+/\_/gs;   &tiehash();
     $title.='.'.$ext;   $r->print('<h3>'.&mt('Filenames in Construction Space').'</h3>'
     $r->print("\n<td><input type='text' size='60' name='namefor_".$_."' value='".$title."' /></td></tr>\n");                   .&Apache::loncommon::start_data_table()
  }                   .&Apache::loncommon::start_data_table_header_row()
  $r->print("</table>\n");                   .'<th>'.&mt('Internal Filename').'</th>'
  &untiehash();                   .'<th>'.&mt('Title').'</th>'
  $r->print(                   .'<th>'.&mt('Save as ...').'</th>'
   '<p><input type="submit" name="dumpcourse" value="'.&mt('Dump Course DOCS').'" /></p></form>');                   .&Apache::loncommon::end_data_table_header_row());
     }   foreach my $file (&Apache::lonclonecourse::crsdirlist($origcrsid,'userfiles')) {
 }      $r->print(&Apache::loncommon::start_data_table_row()
                        .'<td>'.$file.'</td>');
 # ------------------------------------------------------ Generate "export" button      my ($ext)=($file=~/\.(\w+)$/);
       my $title=$hash{'title_'.$hash{
 sub exportbutton {   'ids_/uploaded/'.$origcrsdata{'domain'}.'/'.$origcrsdata{'num'}.'/'.$file}};
     return '</td><td bgcolor="#DDDDCC">'.      $r->print('<td>'.($title?$title:'&nbsp;').'</td>');
             '<input type="submit" name="exportcourse" value="'.      if (!$title) {
             &mt('Export Course to IMS').'" />'.   $title=$file;
             &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs');      } else {
 }   $title=~s|/|_|g;
       }
 sub exportcourse {      $title=~s/\.(\w+)$//;
     my $r=shift;      $title=&clean($title);
     my %discussiontime = &Apache::lonnet::dump('discussiontimes',      $title.='.'.$ext;
                                                $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}, $ENV{'course.'.$ENV{'request.course.id'}.'.num'});      $r->print("\n<td><input type='text' size='60' name='namefor_".$file."' value='".$title."' /></td>"
     my $numdisc = keys %discussiontime;                       .&Apache::loncommon::end_data_table_row());
     my $navmap = Apache::lonnavmaps::navmap->new();   }
     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);   $r->print(&Apache::loncommon::end_data_table());
     my $curRes;   &untiehash();
     my $outcome;   $r->print(
     '<p><input type="submit" name="dumpcourse" value="'.&mt("Dump $type DOCS").'" /></p></form>');
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      }
                                             ['finishexport']);  }
     if ($ENV{'form.finishexport'}) {  
         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  
                                             ['archive','discussion']);  
   sub exportbutton {
         my @exportitems = ();      my $type = &Apache::loncommon::course_type();
         if (defined($ENV{'form.archive'})) {      return '<div>'.
             if (ref($ENV{'form.archive'}) eq 'ARRAY') {              '<input type="submit" name="exportcourse" value="'.
                 @exportitems = @{$ENV{'form.archive'}};              &mt('Export '.$type.' to IMS').'" />'.
             } else {      &Apache::loncommon::help_open_topic('Docs_Export_Course_Docs').'</div>';
                 $exportitems[0] = $ENV{'form.archive'};  }
             }  
         }  
         my @discussions = ();  
         if (defined($ENV{'form.discussion'})) {  sub exportcourse {
             if (ref($ENV{'form.discussion'}) eq 'ARRAY') {      my $r=shift;
                 @discussions = $ENV{'form.discussion'};      my $type = &Apache::loncommon::course_type();
             } else {      my %discussiontime = &Apache::lonnet::dump('discussiontimes',
                 $discussions[0] = $ENV{'form.discussion'};                                                 $env{'course.'.$env{'request.course.id'}.'.domain'}, $env{'course.'.$env{'request.course.id'}.'.num'});
             }      my $numdisc = keys(%discussiontime);
         }      my $navmap = Apache::lonnavmaps::navmap->new();
         if (@exportitems == 0 && @discussions == 0) {      if (!defined($navmap)) {
             $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';          $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package').
         } else {                    '<h2>IMS Export Failed</h2>'.
             my $now = time;                    '<div class="LC_error">'.
             my $count = 0;                    &mt('Unable to retrieve information about course contents').
             my %symbs;                    '</div><a href="/adm/coursedocs">'.&mt('Return to Course Editor').'</a>');
             my $manifestok = 0;          &Apache::lonnet::logthis('IMS export failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
             my $imsresources;          return;
             my $tempexport;      }
             my $copyresult;      my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);
             my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);      my $curRes;
             if ($manifestok) {      my $outcome;
                 &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,\$tempexport,\$copyresult,$ims_manifest);  
                 close($ims_manifest);      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                               ['finishexport']);
 #Create zip file in prtspool      if ($env{'form.finishexport'}) {
                 my $imszipfile = '/prtspool/'.          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                 $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.                                              ['archive','discussion']);
                    time.'_'.rand(1000000000).'.zip';  
 # zip can cause an sh launch which can pass along all of %ENV          my @exportitems = &Apache::loncommon::get_env_multiple('form.archive');
 # which can be too large for /bin/sh to handle          my @discussions = &Apache::loncommon::get_env_multiple('form.discussion');
                 my %oldENV=%ENV;          if (@exportitems == 0 && @discussions == 0) {
                 undef(%ENV);              $outcome = '<br />As you did not select any content items or discussions for export, an IMS package has not been created.  Please <a href="javascript:history.go(-1)">go back</a> to select either content items or discussions for export';
                 my $cwd = &Cwd::getcwd();          } else {
                 my $imszip = '/home/httpd/'.$imszipfile;              my $now = time;
                 chdir $tempexport;              my %symbs;
                 open(OUTPUT, "zip -r $imszip *  2> /dev/null |");              my $manifestok = 0;
                 close(OUTPUT);              my $imsresources;
                 chdir $cwd;              my $tempexport;
                 %ENV=%oldENV;              my $copyresult;
                 undef(%oldENV);              my $ims_manifest = &create_ims_store($now,\$manifestok,\$outcome,\$tempexport);
                 $outcome .= 'Download the zip file from <a href="'.$imszipfile.'">IMS course archive</a><br />';              if ($manifestok) {
                 if ($copyresult) {                  &build_package($now,$navmap,\@exportitems,\@discussions,\$outcome,$tempexport,\$copyresult,$ims_manifest);
                     $outcome .= 'The following errors occurred during export - '.$copyresult;                  close($ims_manifest);
                 }  
             } else {  #Create zip file in prtspool
                 $outcome = '<br />Unfortunately you will not be able to retrieve an IMS archive of this posts at this time, because there was a problem creating a manifest file.<br />';                  my $imszipfile = '/prtspool/'.
             }                  $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
         }                     time.'_'.rand(1000000000).'.zip';
                   my $cwd = &Cwd::getcwd();
         $r->print('<html><head><title>Export Course</title></head>'.                  my $imszip = '/home/httpd/'.$imszipfile;
             &Apache::loncommon::bodytag('Export course to IMS or SCORM content package'));                  chdir $tempexport;
         $r->print($outcome);                  open(OUTPUT, "zip -r $imszip *  2> /dev/null |");
         $r->print('</body></html>');                  close(OUTPUT);
     } else {                  chdir $cwd;
         my $display;                  $outcome .= &mt('Download the zip file from <a href="[_1]">IMS '.lc($type).' archive</a><br />',$imszipfile,);
         $display = '<form name="exportdoc" method="post">'."\n";                  if ($copyresult) {
         $display .= 'Choose which items you wish to export from your course.<br /><br />';                      $outcome .= &mt('The following errors occurred during export - [_1]',$copyresult);
         $display .= '<table border="0" cellspacing="0" cellpadding="3">'.                  }
                     '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.              } else {
                     '<input type="button" value="check all" '.                  $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 />';
                     'onclick="javascript:checkAll(document.exportdoc.archive)" />'.              }
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.          }
                     ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.          $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package'));
                     '<td>&nbsp;</td><td>&nbsp;</td>'.   $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));
                     '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.          $r->print($outcome);
                     '</b></legend><input type="button" value="check all"'.          $r->print(&Apache::loncommon::end_page());
                     ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.      } else {
                     '&nbsp;&nbsp;<input type="button" value="uncheck all"'.          my $display;
                     ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.          $display = '<form name="exportdoc" method="post">'."\n";
                     '</tr></table>';          $display .= &mt('Choose which items you wish to export from your '.$type.'.<br /><br />');
         my $curRes;          $display .= '<table border="0" cellspacing="0" cellpadding="3">'.
         my $depth = 0;                      '<tr><td><fieldset><legend>&nbsp;<b>Content items</b></legend>'.
         my $count = 0;                      '<input type="button" value="check all" '.
         my $boards = 0;                      'onclick="javascript:checkAll(document.exportdoc.archive)" />'.
         my $startcount = 5;                      '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
         my %parent = ();                      ' onclick="javascript:uncheckAll(document.exportdoc.archive)" /></fieldset></td>'.
         my %children = ();                      '<td>&nbsp;</td><td>&nbsp;</td>'.
         my $lastcontainer = $startcount;                      '<td align="right"><fieldset><legend>&nbsp;<b>Discussion posts'.
         my @bgcolors = ('#F6F6F6','#FFFFFF');                      '</b></legend><input type="button" value="check all"'.
         $display .= '<table cellspacing="0"><tr>'.                      ' onclick="javascript:checkAll(document.exportdoc.discussion)" />'.
             '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";                      '&nbsp;&nbsp;<input type="button" value="uncheck all"'.
         if ($numdisc > 0) {                      ' onclick="javascript:uncheckAll(document.exportdoc.discussion)" /></fieldset></td>'.
             $display.='<b>Export&nbsp;discussion posts?</b>'."\n";                      '</tr></table>';
         }          my $curRes;
         $display.='&nbsp;</td></tr>';          my $depth = 0;
         while ($curRes = $it->next()) {          my $count = 0;
             if (ref($curRes)) {          my $boards = 0;
                 $count ++;          my $startcount = 5;
             }          my %parent = ();
             if ($curRes == $it->BEGIN_MAP()) {          my %children = ();
                 $depth++;          my $lastcontainer = $startcount;
                 $parent{$depth} = $lastcontainer;          my @bgcolors = ('#F6F6F6','#FFFFFF');
             }          $display .= '<table cellspacing="0"><tr>'.
             if ($curRes == $it->END_MAP()) {              '<td><b>Export content item?<br /></b></td><td>&nbsp;</td><td align="right">'."\n";
                 $depth--;          if ($numdisc > 0) {
                 $lastcontainer = $parent{$depth};              $display.='<b>Export&nbsp;discussion posts?</b>'."\n";
             }          }
             if (ref($curRes)) {          $display.='&nbsp;</td></tr>';
                 my $symb = $curRes->symb();          while ($curRes = $it->next()) {
                 my $color = $count%2;              if (ref($curRes)) {
                 $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".                  $count ++;
                     '<input type="checkbox" name="archive" value="'.$count.'" ';              }
                 if (($curRes->is_sequence()) || ($curRes->is_page())) {              if ($curRes == $it->BEGIN_MAP()) {
                     my $checkitem = $count + $boards + $startcount;                  $depth++;
                     $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';                  $parent{$depth} = $lastcontainer;
                 }              }
                 $display .= ' />'."\n";              if ($curRes == $it->END_MAP()) {
                 for (my $i=0; $i<$depth; $i++) {                  $depth--;
                     $display .= '<img src="/adm/lonIcons/whitespace1.gif" width="25" height="1" alt="" border="0" /><img src="/adm/lonIcons/whitespace1.gif" width="25" height="1" alt="" border="0" />'."\n";                  $lastcontainer = $parent{$depth};
                 }              }
                 if ($curRes->is_sequence()) {              if (ref($curRes)) {
                     $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";                  my $symb = $curRes->symb();
                     $lastcontainer = $count + $startcount + $boards;                  my $ressymb = $symb;
                 } elsif ($curRes->is_page()) {                  if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
                     $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";                      unless ($ressymb =~ m|adm/wrapper/adm|) {
                     $lastcontainer = $count + $startcount + $boards;                          $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
                 }                      }
                 my $currelem = $count+$boards+$startcount;                  }
                 $children{$parent{$depth}} .= $currelem.':';                  my $color = $count%2;
                 $display .= '&nbsp;'.$curRes->title().'</td>';                  $display .='<tr bgcolor='.$bgcolors[$color].'><td>'."\n".
                 if ($discussiontime{$symb} > 0) {                      '<input type="checkbox" name="archive" value="'.$count.'" ';
                     $boards ++;                  if (($curRes->is_sequence()) || ($curRes->is_page())) {
                     $currelem = $count+$boards+$startcount;                      my $checkitem = $count + $boards + $startcount;
                     $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";                      $display .= 'onClick="javascript:propagateCheck('."'$checkitem'".')"';
                 } else {                  }
                     $display .= '<td colspan="2">&nbsp;</td>'."\n";                  $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";
         }                  }
         my $scripttag = qq|                  if ($curRes->is_sequence()) {
 <script>                      $display .= '<img src="/adm/lonIcons/navmap.folder.open.gif">&nbsp;'."\n";
                       $lastcontainer = $count + $startcount + $boards;
 function checkAll(field) {                  } elsif ($curRes->is_page()) {
     for (i = 0; i < field.length; i++)                      $display .= '<img src="/adm/lonIcons/navmap.page.open.gif">&nbsp;'."\n";
         field[i].checked = true ;                      $lastcontainer = $count + $startcount + $boards;
 }                  }
                   my $currelem = $count+$boards+$startcount;
 function uncheckAll(field) {                  $children{$parent{$depth}} .= $currelem.':';
     for (i = 0; i < field.length; i++)                  $display .= '&nbsp;'.$curRes->title().'</td>';
         field[i].checked = false ;                  if ($discussiontime{$ressymb} > 0) {
 }                      $boards ++;
                       $currelem = $count+$boards+$startcount;
 function propagateCheck(item) {                      $display .= '<td>&nbsp;</td><td align="right"><input type="checkbox" name="discussion" value="'.$count.'" />&nbsp;</td>'."\n";
     if (document.exportdoc.elements[item].checked == true) {                  } else {
         containerCheck(item)                      $display .= '<td colspan="2">&nbsp;</td>'."\n";
     }                  }
 }               }
           }
 function containerCheck(item) {          my $scripttag = qq|
     document.exportdoc.elements[item].checked = true  <script>
     var numitems = $count + $boards + $startcount  
     var parents = new Array(numitems)  function checkAll(field) {
     for (var i=$startcount; i<numitems; i++) {      if (field.length > 0) {
         parents[i] = new Array          for (i = 0; i < field.length; i++) {
     }              field[i].checked = true ;
         |;          }
       } else {
         foreach my $container (sort { $a <=> $b } keys %children) {          field.checked = true
             my @contents = split/:/,$children{$container};      }
             for (my $i=0; $i<@contents; $i ++) {  }
                 $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";                                                                                 
             }  function uncheckAll(field) {
         }      if (field.length > 0) {
           for (i = 0; i < field.length; i++) {
         $scripttag .= qq|              field[i].checked = false ;
     if (parents[item].length > 0) {          }
         for (var j=0; j<parents[item].length; j++) {      } else {
             containerCheck(parents[item][j])          field.checked = false ;
         }      }
      }     }
 }  
   function propagateCheck(item) {
 </script>      if (document.exportdoc.elements[item].checked == true) {
         |;          containerCheck(item)
         $r->print('<html><head><title>Export Course</title>'.$scripttag.'</head>'.      }
             &Apache::loncommon::bodytag('Export course to IMS or SCORM content package'  }
 ));  
   function containerCheck(item) {
         $r->print($display.'</table>'.      document.exportdoc.elements[item].checked = true
                   '<p><input type="hidden" name="finishexport" value="1">'.      var numitems = $count + $boards + $startcount
                   '<input type="submit" name="exportcourse" value="'.      var parents = new Array(numitems)
                   &mt('Export Course DOCS').'" /></p></form></body></html>');      for (var i=$startcount; i<numitems; i++) {
     }          parents[i] = new Array
 }      }
           |;
 sub create_ims_store {  
     my ($now,$manifestok,$outcome,$tempexport) = @_;          foreach my $container (sort { $a <=> $b } (keys(%children))) {
     $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';              my @contents = split(/:/,$children{$container});
     my $ims_manifest;              for (my $i=0; $i<@contents; $i ++) {
     if (!-e $$tempexport) {                  $scripttag .= '    parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
         mkdir($$tempexport,0700);              }
     }          }
     $$tempexport .= '/'.$now;  
     if (!-e $$tempexport) {          $scripttag .= qq|
         mkdir($$tempexport,0700);      if (parents[item].length > 0) {
     }          for (var j=0; j<parents[item].length; j++) {
     $$tempexport .= '/'.$ENV{'user.domain'}.'_'.$ENV{'user.name'};              containerCheck(parents[item][j])
     if (!-e $$tempexport) {          }
         mkdir($$tempexport,0700);       }  
     }  }
 # open manifest file  
     my $manifest = '/imsmanifest.xml';  </script>
     my $manifestfilename = $$tempexport.$manifest;          |;
     if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {   $r->print(&Apache::loncommon::start_page('Export '.lc($type).' to IMS content package',
         $$manifestok=1;   $scripttag));
         print $ims_manifest   $r->print(&Apache::lonhtmlcommon::breadcrumbs('Export '.lc($type).' to IMS content package'));
 '<?xml version="1.0" encoding="UTF-8"?>'."\n".   $r->print($display.'</table>'.
 '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.                    '<p><input type="hidden" name="finishexport" value="1">'.
 ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.                    '<input type="submit" name="exportcourse" value="'.
 ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.                    &mt('Export '.$type.' DOCS').'" /></p></form>');
 ' identifier="MANIFEST-'.$ENV{'request.course.id'}.'-'.$now.'"'.      }
 '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.  }
 '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".  
 '  <organizations default="ORG-."'.$ENV{'request,course.id'}.'-'.$now.'">'."\n".  sub create_ims_store {
 '    <organization identifier="ORG-'.$ENV{'request.course.id'}.'-'.$now.'"'.      my ($now,$manifestok,$outcome,$tempexport) = @_;
 ' structure="hierarchical">'."\n".      $$tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';
 '      <title>'.$ENV{'request.'.$ENV{'request.course.id'}.'.description'}.'</title>'      my $ims_manifest;
     } else {      if (!-e $$tempexport) {
         $$outcome .= 'An error occurred opening the IMS manifest file.<br />'          mkdir($$tempexport,0700);
 ;      }
     }      $$tempexport .= '/'.$now;
     return $ims_manifest;      if (!-e $$tempexport) {
 }          mkdir($$tempexport,0700);
       }
 sub build_package {      $$tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};
     my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;      if (!-e $$tempexport) {
 # first iterator to look for dependencies          mkdir($$tempexport,0700);
     my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);      }
     my $curRes;      if (!-e "$$tempexport/resources") {
     my $count = 0;          mkdir("$$tempexport/resources",0700);
     my $depth = 0;      }
     my $lastcontainer = 0;  # open manifest file
     my %parent = ();      my $manifest = '/imsmanifest.xml';
     my @dependencies = ();      my $manifestfilename = $$tempexport.$manifest;
     my $cnum = $ENV{'request.'.$ENV{'request.course.id'}.'.num'};      if ($ims_manifest = Apache::File->new('>'.$manifestfilename)) {
     my $cdom = $ENV{'request.'.$ENV{'request.course.id'}.'.domain'};          $$manifestok=1;
     while ($curRes = $it->next()) {          print $ims_manifest
         if (ref($curRes)) {  '<?xml version="1.0" encoding="UTF-8"?>'."\n".
             $count ++;  '<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"'.
         }  ' xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2"'.
         if ($curRes == $it->BEGIN_MAP()) {  ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
             $depth++;  ' identifier="MANIFEST-'.$env{'request.course.id'}.'-'.$now.'"'.
             $parent{$depth} = $lastcontainer;  '  xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1imscp_v1p1.xsd'.
         }  '  http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">'."\n".
         if ($curRes == $it->END_MAP()) {  '  <metadata>
             $depth--;      <schema></schema>
             $lastcontainer = $parent{$depth};      <imsmd:lom>
         }        <imsmd:general>
         if (ref($curRes)) {          <imsmd:identifier>'.$env{'request.course.id'}.'</imsmd:identifier>
             if ($curRes->is_sequence() || $curRes->is_page()) {          <imsmd:title>
                 $lastcontainer = $count;            <imsmd:langstring xml:lang="en">'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</imsmd:langstring>
             }          </imsmd:title>
             if (grep/^$count$/,@$exportitems) {        </imsmd:general>
                 &get_dependencies($exportitems,\%parent,$depth,\@dependencies);      </imsmd:lom>
             }    </metadata>'."\n".
         }  '  <organizations default="ORG-'.$env{'request.course.id'}.'-'.$now.'">'."\n".
     }  '    <organization identifier="ORG-'.$env{'request.course.id'}.'-'.$now.'"'.
 # second iterator to build manifest and store resources  ' structure="hierarchical">'."\n".
     $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);  '      <title>'.$env{'course.'.$env{'request.course.id'}.'.description'}.'</title>'
     $depth = 0;      } else {
     my $prevdepth;          $$outcome .= 'An error occurred opening the IMS manifest file.<br />'
     $count = 0;  ;
     my $imsresources;      }
     my $pkgdepth;      return $ims_manifest;
     if ($curRes == $it->BEGIN_MAP()) {  }
         $prevdepth = $depth;  
         $depth++;  sub build_package {
     }      my ($now,$navmap,$exportitems,$discussions,$outcome,$tempexport,$copyresult,$ims_manifest) = @_;
     if ($curRes == $it->END_MAP()) {  # first iterator to look for dependencies
         $prevdepth = $depth;      my $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
         $depth--;      my $curRes;
     }      my $count = 0;
       my $depth = 0;
     if (ref($curRes)) {      my $lastcontainer = 0;
         if ((grep/^$count$/,@$exportitems) || (grep/^$count$/,@dependencies)) {      my %parent = ();
             my $symb = $curRes->symb();      my @dependencies = ();
             my $isvisible = 'true';      my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
             my $resourceref;      my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
             if ($curRes->randomout()) {      while ($curRes = $it->next()) {
                 $isvisible = 'false';          if (ref($curRes)) {
             }              $count ++;
             unless ($curRes->is_sequence()) {          }
                 $resourceref = 'identifierref="RES-'.$ENV{'request.course.id'}.'-'.$count.'"';          if ($curRes == $it->BEGIN_MAP()) {
             }              $depth++;
             if (($depth <= $prevdepth) && ($count > 1)) {              $parent{$depth} = $lastcontainer;
                 print $ims_manifest '  </item>'."\n";          }
             }          if ($curRes == $it->END_MAP()) {
             $prevdepth = $depth;              $depth--;
               $lastcontainer = $parent{$depth};
             my $itementry =          }
               '<item identifier="ITEM-'.$ENV{'request.course.id'}.'-'.$count.          if (ref($curRes)) {
               '" isvisible="'.$isvisible.'" '.$resourceref.'>'.              if ($curRes->is_sequence() || $curRes->is_page()) {
               '<title>'.$curRes->title().'</title>';                  $lastcontainer = $count;
             print $ims_manifest "\n".$itementry;              }
               if (grep(/^$count$/,@$exportitems)) {
             unless ($curRes->is_sequence()) {                  &get_dependencies($exportitems,\%parent,$depth,\@dependencies);
                 my $content_file;              }
                 my @hrefs = ();          }
                 &process_content($count,$curRes,$cdom,$cnum,$symb,$content_file,\@hrefs,$copyresult,$tempexport);      }
                 if ($content_file) {  # second iterator to build manifest and store resources
                     $imsresources .= "\n".      $it = $navmap->getIterator(undef,undef,undef,1,undef,undef);
                      '   <resource identifier="RES-'.$ENV{'request.course.id'}.'-'.$count.      $depth = 0;
                      '" type="webcontent" href="'.$content_file.'">'."\n".      my $prevdepth;
                      '       <file href="'.$content_file.'" />'."\n";      $count = 0;
                     foreach (@hrefs) {      my $imsresources;
                         $imsresources .=      my $pkgdepth;
                      '        <file href="'.$_.'" />'."\n";      while ($curRes = $it->next()) {
                     }          if ($curRes == $it->BEGIN_MAP()) {
                     $imsresources .= '    </resource>'."\n";              $prevdepth = $depth;
                 }              $depth++;
             }          }
             $pkgdepth = $depth;          if ($curRes == $it->END_MAP()) {
         }              $prevdepth = $depth;
     }              $depth--;
     while ($pkgdepth > -1) {          }
         print $ims_manifest "    </item>\n";  
         $pkgdepth --;          if (ref($curRes)) {
     }              $count ++;
     my $resource_text = qq|              if ((grep(/^$count$/,@$exportitems)) || (grep(/^$count$/,@dependencies))) {
     </organization>                  my $symb = $curRes->symb();
   </organizations>                  my $isvisible = 'true';
   <resources>                  my $resourceref;
     $imsresources                  if ($curRes->randomout()) {
   </resources>                      $isvisible = 'false';
 </manifest>                  }
     |;                  unless ($curRes->is_sequence()) {
     print $ims_manifest $resource_text;                      $resourceref = 'identifierref="RES-'.$env{'request.course.id'}.'-'.$count.'"';
 }                  }
                   my $step = $prevdepth - $depth;
 sub get_dependencies {                  if (($step >= 0) && ($count > 1)) {
     my ($exportitems,$parent,$depth,$dependencies) = @_;                      while ($step >= 0) {
     if ($depth > 1) {                          print $ims_manifest "\n".'  </item>'."\n";
         unless (grep/^$$parent{$depth}$/,@$exportitems || grep/^$$parent{$depth}$/,@$dependencies) {                          $step --;
             push @$dependencies, $$parent{$depth};                      }
             if ($depth > 2) {                  }
                 &get_dependencies($exportitems,$parent,$depth-1,$dependencies);                  $prevdepth = $depth;
             }  
         }                  my $itementry =
     }                '<item identifier="ITEM-'.$env{'request.course.id'}.'-'.$count.
 }                '" isvisible="'.$isvisible.'" '.$resourceref.'>'.
                 '<title>'.$curRes->title().'</title>';
 sub process_content {                  print $ims_manifest "\n".$itementry;
     my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;  
     my $content_type;                  unless ($curRes->is_sequence()) {
     my $message;                      my $content_file;
 # find where user is author or co-author                      my @hrefs = ();
     my %roleshash = &Appache::lonnet::get_my_roles();                      &process_content($count,$curRes,$cdom,$cnum,$symb,\$content_file,\@hrefs,$copyresult,$tempexport);
     if ($curRes->is_page()) {                      if ($content_file) {
         $content_type = 'page';                          $imsresources .= "\n".
     } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {                       '   <resource identifier="RES-'.$env{'request.course.id'}.'-'.$count.
         $content_type = 'syllabus';                       '" type="webcontent" href="'.$content_file.'">'."\n".
     } elsif ($symb =~ m-\.sequence____\d+____ext-) {                       '       <file href="'.$content_file.'" />'."\n";
         $content_type = 'external';                          foreach my $item (@hrefs) {
     } elsif ($symb =~ m-adm/navmaps$-) {                              $imsresources .=
         $content_type =  'navmap';                       '        <file href="'.$item.'" />'."\n";
     } elsif ($symb =~ m-adm/$cdom/$cnum/\d+/smppg$-) {                          }
         $content_type = 'simplepage';                          if (grep(/^$count$/,@$discussions)) {
     } elsif ($symb =~ m-$-) {                              my $ressymb = $symb;
         $content_type = 'simpleproblem';                              my $mode;
     } elsif ($symb =~ m-adm/$cdom/$cnum/\d+/bulletinboard$-) {                              if ($ressymb =~ m|adm/($match_domain)/($match_username)/(\d+)/bulletinboard$|) {
         $content_type = 'bulletinboard';                                  unless ($ressymb =~ m|adm/wrapper/adm|) {
     } elsif ($symb =~ m-adm/$cdom/$cnum/\d+/aboutme$-) {                                      $ressymb = 'bulletin___'.$3.'___adm/wrapper/adm/'.$1.'/'.$2.'/'.$3.'/bulletinboard';
         $content_type = 'aboutme';                                  }
     } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {                                  $mode = 'board';
         &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,'uploaded');                              }
     } elsif ($symb =~ m-\.sequence____\d+____([^/])/([^/])-) {                              my %extras = (
         my $coauth = $2.':'.$1.':ca';                                            caller => 'imsexport',
         my $canedit = 0;                                            tempexport => $tempexport.'/resources',
         if ($1 eq $ENV{'user.domain'} && $2 eq $ENV{'user.name'})  {                                            count => $count
             $canedit= 1;                                           );
         } elsif (defined($roleshash{$coauth})) {                              my $discresult = &Apache::lonfeedback::list_discussion($mode,undef,$ressymb,\%extras);
             if ($roleshash{$coauth} =~ /(\d+):(\d+)/) {                          }
                 if (($1 < time || $1 == 0) && ($2 == 0 || $2 >= time)) {                          $imsresources .= '    </resource>'."\n";
                     $canedit = 1;                      }
                 }                  }
             } elsif ($roleshash{$coauth} eq ':') {                  $pkgdepth = $depth;
                 $canedit = 1;              }
             }          }
         }      }
         if ($canedit) {      while ($pkgdepth > 0) {
             &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,'resource');          print $ims_manifest "    </item>\n";
         } else {          $pkgdepth --;
             &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,'noedit');      }
         }      my $resource_text = qq|
     }      </organization>
     $$copyresult .= $message."\n";    </organizations>
 }    <resources>
       $imsresources
 sub replicate_content {    </resources>
     my ($cdom,$cnum,$tempexport,$symb,$count,$message,$caller) = @_;  </manifest>
     my ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);      |;
     my $feedurl = &Apache::lonnet::clutter($url);      print $ims_manifest $resource_text;
   }
     my $content;  
     my $filename;  sub get_dependencies {
     my $repstatus;      my ($exportitems,$parent,$depth,$dependencies) = @_;
     if ($url =~ m-[^/]/(.+)$-) {      if ($depth > 1) {
         $filename = $1;          if ((!grep(/^$$parent{$depth}$/,@$exportitems)) && (!grep(/^$$parent{$depth}$/,@$dependencies))) {
         if (!-e $tempexport.'/resources') {              push(@{$dependencies},$$parent{$depth});
             mkdir($tempexport.'/resources',0700);              if ($depth > 2) {
         }                  &get_dependencies($exportitems,$parent,$depth-1,$dependencies);
         if (!-e $tempexport.'/resources') {              }
             mkdir($tempexport.'/resources/'.$count,0700);          }
         }      }
         my $destination = $$tempexport.'/resources/'.$count.'/'.$filename;  }
         my $copiedfile;  
         if ($copiedfile = Apache::File->new('>'.$destination)) {  sub process_content {
             my $content;      my ($count,$curRes,$cdom,$cnum,$symb,$content_file,$href,$copyresult,$tempexport) = @_;
             if ($caller eq 'uploaded' || $caller eq 'resource') {      my $content_type;
                 $content = &Apache::lonnet::getfile($url);      my $message;
                 if ($content eq -1) {      my @uploads = ();
                     $$message = 'Could not copy file '.$filename;      if ($curRes->is_sequence()) {
                 } else {          $content_type = 'sequence';
                     $repstatus = 'ok';      } elsif ($curRes->is_page()) {
                 }          $content_type = 'page'; # need to handle individual items in pages.
             } elsif ($caller eq 'noedit') {      } elsif ($symb =~ m-public/$cdom/$cnum/syllabus$-) {
                 my $rtncode;          $content_type = 'syllabus';
                 $repstatus = &getuploaded('GET',$url,$cdom,$cnum,$content,$rtncode);          my $contents = &Apache::imsexport::templatedpage($content_type);
                 unless ($repstatus eq 'ok') {          if ($contents) {
                     $$message = 'Could not render '.$url.' server message - '.$rtncode;              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
                 }          }
             }      } elsif ($symb =~ m-\.sequence___\d+___ext-) {
             if ($repstatus eq 'ok') {          $content_type = 'external';
                 print $copiedfile $content;          my $title = $curRes->title;
             }          my $contents =  &Apache::imsexport::external($symb,$title);
             close($copiedfile);          if ($contents) {
         } else {              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
             $$message = 'Could not open destination file for '.$filename."\n";          }
         }      } elsif ($symb =~ m-adm/navmaps$-) {
     } else {          $content_type =  'navmap';
         $$message = 'Could not determine name of file for ';      } elsif ($symb =~ m-adm/[^/]+/[^/]+/(\d+)/smppg$-) {
     }          $content_type = 'simplepage';
     return $repstatus;          my $contents = &Apache::imsexport::templatedpage($content_type,$1,$count,\@uploads);
 }          if ($contents) {
               $$content_file = &store_template($contents,$tempexport,$count,$content_type);
 # Imports the given (name, url) resources into the course          }
 # coursenum, coursedom, and folder must precede the list      } elsif ($symb =~ m-lib/templates/simpleproblem\.problem$-) {
 sub group_import {          $content_type = 'simpleproblem';
     my $coursenum = shift;          my $contents =  &Apache::imsexport::simpleproblem($symb);
     my $coursedom = shift;          if ($contents) {
     my $folder = shift;              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
     my $container = shift;          }
     my $caller = shift;      } elsif ($symb =~ m-lib/templates/examupload\.problem$-) {
     while (@_) {          $content_type = 'examupload';
  my $name = shift;      } elsif ($symb =~ m-adm/($match_domain)/($match_username)/(\d+)/bulletinboard$-) {
  my $url = shift;          $content_type = 'bulletinboard';
         if (($url =~ m#^/uploaded/$coursedom/$coursenum/(default_\d+\.)(page|sequence)$#) && ($caller eq 'londocs')) {          my $contents =  &Apache::imsexport::templatedpage($content_type,$3,$count,\@uploads,$1,$2);
             my $errtext = '';          if ($contents) {
             my $fatal = 0;              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
             my $newmapstr = '<map>'."\n".          }
                             '<resource id="1" src="" type="start"></resource>'."\n".      } elsif ($symb =~ m-adm/([^/]+)/([^/]+)/aboutme$-) {
                             '<link from="1" to="2" index="1"></link>'."\n".          $content_type = 'aboutme';
                             '<resource id="2" src="" type="finish"></resource>'."\n".          my $contents =  &Apache::imsexport::templatedpage($content_type,undef,$count,\@uploads,$1,$2);
                             '</map>';          if ($contents) {
             $ENV{'form.output'}=$newmapstr;              $$content_file = &store_template($contents,$tempexport,$count,$content_type);
             my $home=&Apache::lonnet::homeserver($coursenum,$coursedom);          }
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,$home,      } elsif ($symb =~ m-\.(sequence|page)___\d+___uploaded/$cdom/$cnum/-) {
                                                 'output',$1.$2);          $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
             if ($result != m|^/uploaded/|) {      } elsif ($symb =~ m-\.(sequence|page)___\d+___([^/]+)/([^/]+)-) {
                 $errtext.='Map not saved: A network error occured when trying to save the new map. ';          my $canedit = 0;
                 $fatal = 2;          if ($2 eq $env{'user.domain'} && $3 eq $env{'user.name'})  {
             }              $canedit= 1;
             if ($fatal) {          }
                 return ($errtext,$fatal);  # only include problem code where current user is author
             }          if ($canedit) {
         }              $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'resource');
  if ($url) {          } else {
     my $idx = $#Apache::lonratedt::resources + 1;              $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'noedit');
     $Apache::lonratedt::order[$#Apache::lonratedt::order+1]=$idx;          }
     my $ext = 'false';      } elsif ($symb =~ m-uploaded/$cdom/$cnum-) {
     if ($url=~/^http:\/\//) { $ext = 'true'; }          $$content_file = &replicate_content($cdom,$cnum,$tempexport,$symb,$count,\$message,$href,'uploaded');
     $url =~ s/:/\&colon;/g;      }
     $name =~ s/:/\&colon;/g;      if (@uploads > 0) {
     $Apache::lonratedt::resources[$idx] =           foreach my $item (@uploads) {
  join ':', ($name, $url, $ext, 'normal', 'res');              my $uploadmsg = '';
  }              &replicate_content($cdom,$cnum,$tempexport,$item,$count,\$uploadmsg,$href,'templateupload');
     }              if ($uploadmsg) {
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);                  $$copyresult .= $uploadmsg."\n";
 }              }
           }
 sub breadcrumbs {      }
     my ($where)=@_;      if ($message) {
     &Apache::lonhtmlcommon::clear_breadcrumbs();          $$copyresult .= $message."\n";
     my (@folders);      }
     if ($ENV{'form.pagepath'}) {  }
         @folders = split('&',$ENV{'form.pagepath'});  
     } else {  sub replicate_content {
         @folders=split('&',$ENV{'form.folderpath'});      my ($cdom,$cnum,$tempexport,$symb,$count,$message,$href,$caller) = @_;
     }      my ($map,$ind,$url);
     my $folderpath;      if ($caller eq 'templateupload') {
     while (@folders) {          $url = $symb;
  my $folder=shift(@folders);          $url =~ s#//#/#g;
  my $foldername=shift(@folders);      } else {
  if ($folderpath) {$folderpath.='&';}          ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
  $folderpath.=$folder.'&'.$foldername;      }
  my $url='/adm/coursedocs?folderpath='.      my $content;
     &Apache::lonnet::escape($folderpath);      my $filename;
     &Apache::lonhtmlcommon::add_breadcrumb(      my $repstatus;
       {'href'=>$url,      my $content_name;
        'title'=>&Apache::lonnet::unescape($foldername),      if ($url =~ m-/([^/]+)$-) {
        'text'=>'<font size="+1">'.          $filename = $1;
    &Apache::lonnet::unescape($foldername).'</font>'          if (!-e $tempexport.'/resources') {
        });              mkdir($tempexport.'/resources',0700);
                  }
             if (!-e $tempexport.'/resources/'.$count) {
     }              mkdir($tempexport.'/resources/'.$count,0700);
     return &Apache::lonhtmlcommon::breadcrumbs(undef,undef,undef,undef,undef,          }
        0,'nohelp');          my $destination = $tempexport.'/resources/'.$count.'/'.$filename;
 }          my $copiedfile;
           if ($copiedfile = Apache::File->new('>'.$destination)) {
 sub editor {              my $content;
     my ($r,$coursenum,$coursedom,$folder,$allowed)=@_;              if ($caller eq 'resource') {
                   my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';
     $r->print(&breadcrumbs($folder));                  my $filepath = &Apache::lonnet::filelocation($respath,$url);
     my $errtext='';                  $content = &Apache::lonnet::getfile($filepath);
     my $fatal=0;                  if ($content eq -1) {
     my $container='sequence';                      $$message = 'Could not copy file '.$filename;
     if ($ENV{'form.pagepath'}) {                  } else {
         $container='page';                      &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'resource');
     }                      $repstatus = 'ok';
     ($errtext,$fatal)=                  }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);              } elsif ($caller eq 'uploaded' || $caller eq 'templateupload') {
     if ($#Apache::lonratedt::order<1) {                  my $rtncode;
         $Apache::lonratedt::order[0]=1;                  $repstatus = &Apache::lonnet::getuploaded('GET',$url,$cdom,$cnum,\$content,$rtncode);
         $Apache::lonratedt::resources[1]='';                  if ($repstatus eq 'ok') {
     }                      if ($url =~ /\.html?$/i) {
     if ($fatal) {                          &extract_media($url,$cdom,$cnum,\$content,$count,$tempexport,$href,$message,'uploaded');
    $r->print('<p><font color="red">'.$errtext.'</font></p>');                      }
     } else {                  } else {
 # ------------------------------------------------------------ Process commands                      $$message = 'Could not render '.$url.' server message - '.$rtncode."<br />\n";
                   }
 # ---------------- if they are for this folder and user allowed to make changes              } elsif ($caller eq 'noedit') {
  if (($allowed) && ($ENV{'form.folder'} eq $folder)) {  # Need to render the resource without the LON-CAPA Internal header and the Post discussion footer, and then set $content equal to this.
 # set parameters and change order                  $repstatus = 'ok';
     if (defined($ENV{'form.setparms'})) {                  $content = 'Not the owner of this resource';
  my $idx=$ENV{'form.setparms'};              }
 # set parameters              if ($repstatus eq 'ok') {
  if ($ENV{'form.randpick_'.$idx}) {                  print $copiedfile $content;
     &Apache::lonratedt::storeparameter($idx,'parameter_randompick',$ENV{'form.randpick_'.$idx},'int_pos');              }
  } else {              close($copiedfile);
     &Apache::lonratedt::delparameter($idx,'parameter_randompick');          } else {
  }              $$message = 'Could not open destination file for '.$filename."<br />\n";
  if ($ENV{'form.hidprs_'.$idx}) {          }
     &Apache::lonratedt::storeparameter($idx,'parameter_hiddenresource','yes','string_yesno');      } else {
  } else {          $$message = 'Could not determine name of file for '.$symb."<br />\n";
     &Apache::lonratedt::delparameter($idx,'parameter_hiddenresource');      }
  }      if ($repstatus eq 'ok') {
  if ($ENV{'form.encprs_'.$idx}) {          $content_name = 'resources/'.$count.'/'.$filename;
     &Apache::lonratedt::storeparameter($idx,'parameter_encrypturl','yes','string_yesno');      }
  } else {      return $content_name;
     &Apache::lonratedt::delparameter($idx,'parameter_encrypturl');  }
  }  
   sub extract_media {
  if ($ENV{'form.newpos'}) {      my ($url,$cdom,$cnum,$content,$count,$tempexport,$href,$message,$caller) = @_;
 # change order      my ($dirpath,$container);
       my %allfiles = ();
     my $newpos=$ENV{'form.newpos'}-1;      my %codebase = ();
     my $currentpos=$ENV{'form.currentpos'}-1;      if ($url =~ m-(.*/)([^/]+)$-) {
     my $i;          $dirpath = $1;
     my @neworder=();          $container = $2;
     if ($newpos>$currentpos) {      } else {
 # moving stuff up          $dirpath = $url;
  for ($i=0;$i<$currentpos;$i++) {          $container = '';
     $neworder[$i]=$Apache::lonratedt::order[$i];      }
  }      &Apache::lonnet::extract_embedded_items(undef,\%allfiles,\%codebase,$content);
  for ($i=$currentpos;$i<$newpos;$i++) {      foreach my $embed_file (keys(%allfiles)) {
     $neworder[$i]=$Apache::lonratedt::order[$i+1];          my $filename;
  }          if ($embed_file =~ m#([^/]+)$#) {
                         $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];              $filename = $1;
  for ($i=$newpos+1;$i<=$#Apache::lonratedt::order;$i++) {          } else {
     $neworder[$i]=$Apache::lonratedt::order[$i];              $filename = $embed_file;
  }          }
     } else {          my $newname = 'res/'.$filename;
 # moving stuff down          my ($rtncode,$embed_content,$repstatus);
  for ($i=0;$i<$newpos;$i++) {          my $embed_url;
     $neworder[$i]=$Apache::lonratedt::order[$i];          if ($embed_file =~ m-^/-) {
  }              $embed_url = $embed_file;           # points to absolute path
  $neworder[$newpos]=$Apache::lonratedt::order[$currentpos];          } else {
  for ($i=$newpos+1;$i<$currentpos+1;$i++) {              if ($embed_file =~ m-https?://-) {
     $neworder[$i]=$Apache::lonratedt::order[$i-1];                  next;                           # points to url
  }              } else {
  for ($i=$currentpos+1;$i<=$#Apache::lonratedt::order;$i++) {                  $embed_url = $dirpath.$embed_file;  # points to relative path
     $neworder[$i]=$Apache::lonratedt::order[$i];              }
  }          }
     }          if ($caller eq 'resource') {
     @Apache::lonratedt::order=@neworder;              my $respath =  $Apache::lonnet::perlvar{'lonDocRoot'}.'/res';  
  }              my $embed_path = &Apache::lonnet::filelocation($respath,$embed_url);
 # store the changed version              $embed_content = &Apache::lonnet::getfile($embed_path);
               unless ($embed_content eq -1) {
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);                  $repstatus = 'ok';
  if ($fatal) {              }
     $r->print('<p><font color="red">'.$errtext.'</font></p>');          } elsif ($caller eq 'uploaded') {
     return;             
  }              $repstatus = &Apache::lonnet::getuploaded('GET',$embed_url,$cdom,$cnum,\$embed_content,$rtncode);
           }
     }          if ($repstatus eq 'ok') {
               my $destination = $tempexport.'/resources/'.$count.'/res';
 # upload a file, if present              if (!-e "$destination") {
            if (($ENV{'form.uploaddoc.filename'}) &&                  mkdir($destination,0755);
                ($ENV{'form.cmd'}=~/^upload_(\w+)/)) {              }
     if ( ($folder=~/^$1/) || ($1 eq 'default') ) {              $destination .= '/'.$filename;
 # this is for a course, not a user, so set coursedoc flag              my $copiedfile;
 # probably the only place in the system where this should be "1"              if ($copiedfile = Apache::File->new('>'.$destination)) {
       my $url=&Apache::lonnet::userfileupload('uploaddoc',1,'docs');                  print $copiedfile $embed_content;
               my $ext='false';                  push(@{$href},'resources/'.$count.'/res/'.$filename);
               if ($url=~/^http\:\/\//) { $ext='true'; }                  my $attrib_regexp = '';
               $url=~s/\:/\&colon;/g;                  if (@{$allfiles{$embed_file}} > 1) {
       my $comment=$ENV{'form.comment'};                      $attrib_regexp = join('|',@{$allfiles{$embed_file}});
               $comment=~s/\</\&lt\;/g;                  } else {
               $comment=~s/\>/\&gt\;/g;                      $attrib_regexp = $allfiles{$embed_file}[0];
               $comment=~s/\:/\&colon;/g;                  }
               if ($folder=~/^supplemental/) {                  $$content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$embed_file\E(['"]?)#$1$newname$2#gi;
   $comment=time.'___&&&___'.$ENV{'user.name'}.'___&&&___'.                  if ($caller eq 'resource' && $container =~ /\.(problem|library)$/) {
       $ENV{'user.domain'}.'___&&&___'.$comment;                      $$content =~ s#\Q$embed_file\E#$newname#gi;
               }                  }
               my $newidx=$#Apache::lonratedt::resources+1;              }
               $Apache::lonratedt::resources[$newidx]=          } else {
                   $comment.':'.$url.':'.$ext.':normal:res';              $$message .= 'replication of embedded file - '.$embed_file.' in '.$url.' failed, reason -'.$rtncode."<br />\n";
               $Apache::lonratedt::order[$#Apache::lonratedt::order+1]=          }
                                                               $newidx;             }
       return;
       ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);  }
       if ($fatal) {  
   $r->print('<p><font color="red">'.$errtext.'</font></p>');  sub store_template {
   return;      my ($contents,$tempexport,$count,$content_type) = @_;
       }      if ($contents) {
      }          if ($tempexport) {
             }              if (!-e $tempexport.'/resources') {
     if ($ENV{'form.cmd'}) {                  mkdir($tempexport.'/resources',0700);
                 my ($cmd,$idx)=split(/\_/,$ENV{'form.cmd'});              }
                 if ($cmd eq 'del') {              if (!-e $tempexport.'/resources/'.$count) {
     my (undef,$url)=split(':',$Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]]);                  mkdir($tempexport.'/resources/'.$count,0700);
     if ($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) {              }
  &Apache::lonnet::removeuploadedurl($url);              my $destination = $tempexport.'/resources/'.$count.'/'.$content_type.'.xml';
     }              my $storetemplate;
     for (my $i=$idx;$i<$#Apache::lonratedt::order;$i++) {              if ($storetemplate = Apache::File->new('>'.$destination)) {
                         $Apache::lonratedt::order[$i]=                  print $storetemplate $contents;
                           $Apache::lonratedt::order[$i+1];                  close($storetemplate);
                     }              }
                     $#Apache::lonratedt::order--;              if ($content_type eq 'external') {
                 } elsif ($cmd eq 'up') {                  return 'resources/'.$count.'/'.$content_type.'.html';
   if (($idx) && (defined($Apache::lonratedt::order[$idx-1]))) {              } else {
                     my $i=$Apache::lonratedt::order[$idx-1];                  return 'resources/'.$count.'/'.$content_type.'.xml';
                     $Apache::lonratedt::order[$idx-1]=              }
  $Apache::lonratedt::order[$idx];          }
                     $Apache::lonratedt::order[$idx]=$i;      }
    }  }
                 } elsif ($cmd eq 'down') {  
    if (defined($Apache::lonratedt::order[$idx+1])) {  
                     my $i=$Apache::lonratedt::order[$idx+1];  sub group_import {
                     $Apache::lonratedt::order[$idx+1]=      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
  $Apache::lonratedt::order[$idx];  
                     $Apache::lonratedt::order[$idx]=$i;      while (@files) {
    }   my ($name, $url, $residx) = @{ shift(@files) };
                 } elsif ($cmd eq 'rename') {          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                     my $ratstr = $Apache::lonratedt::resources[$Apache::lonratedt::order[$idx]];       && ($caller eq 'londocs')
                     my ($rtitle,@rrest)=split(/\:/,       && (!&Apache::lonnet::stat_file($url))) {
                        $Apache::lonratedt::resources[      
        $Apache::lonratedt::order[$idx]]);              my $errtext = '';
                     my $comment=              my $fatal = 0;
                      &HTML::Entities::decode($ENV{'form.title'});              my $newmapstr = '<map>'."\n".
                     $comment=~s/\</\&lt\;/g;                              '<resource id="1" src="" type="start"></resource>'."\n".
                     $comment=~s/\>/\&gt\;/g;                              '<link from="1" to="2" index="1"></link>'."\n".
                     $comment=~s/\:/\&colon;/g;                              '<resource id="2" src="" type="finish"></resource>'."\n".
     if ($comment=~/\S/) {                              '</map>';
  $Apache::lonratedt::resources[              $env{'form.output'}=$newmapstr;
        $Apache::lonratedt::order[$idx]]=              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
             $comment.':'.join(':',@rrest);                                                  'output',$1.$2);
     }              if ($result != m|^/uploaded/|) {
                 }                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
 # Store the changed version                  $fatal = 2;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,              }
     $folder.'.'.$container);              if ($fatal) {
  if ($fatal) {                  return ($errtext,$fatal);
     $r->print('<p><font color="red">'.$errtext.'</font></p>');              }
     return;          }
  }   if ($url) {
             }      if (!$residx
 # Group import/search   || defined($LONCAPA::map::zombies[$residx])) {
     if ($ENV{'form.importdetail'}) {   $residx = &LONCAPA::map::getresidx($url,$residx);
  my @imports;   push(@LONCAPA::map::order, $residx);
  foreach (split(/\&/,$ENV{'form.importdetail'})) {      }
     if (defined($_)) {      my $ext = 'false';
  my ($name,$url)=split(/\=/,$_);      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
  $name=&Apache::lonnet::unescape($name);      $url  = &LONCAPA::map::qtunescape($url);
  $url=&Apache::lonnet::unescape($url);      $name = &LONCAPA::map::qtunescape($name);
  push @imports, $name, $url;      $LONCAPA::map::resources[$residx] =
     }   join(':', ($name, $url, $ext, 'normal', 'res'));
  }   }
 # Store the changed version      }
  ($errtext,$fatal)=group_import($coursenum, $coursedom, $folder,      return &storemap($coursenum, $coursedom, $folder.'.'.$container);
        $container,'londocs',@imports);  }
  if ($fatal) {  
     $r->print('<p><font color="red">'.$errtext.'</font></p>');  sub breadcrumbs {
     return;      my ($where,$allowed,$type)=@_;
  }      &Apache::lonhtmlcommon::clear_breadcrumbs();
             }      my (@folders);
 # Loading a complete map      if ($env{'form.pagepath'}) {
    if (($ENV{'form.importmap'}) && ($ENV{'form.loadmap'})) {          @folders = split('&',$env{'form.pagepath'});
        foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$ENV{'form.importmap'}))) {      } else {
                    my $idx=$#Apache::lonratedt::resources;          @folders=split('&',$env{'form.folderpath'});
                    $idx++;      }
                    $Apache::lonratedt::resources[$idx]=$_;      my $folderpath;
                    $Apache::lonratedt::order      my $cpinfo='';
        [$#Apache::lonratedt::order+1]=$idx;      my $plain='';
        }      my $randompick=-1;
       my $isencrypted=0;
 # Store the changed version      my $ishidden=0;
        ($errtext,$fatal)=&storemap($coursenum,$coursedom,      my $is_random_order=0;
    $folder.'.'.$container);      while (@folders) {
        if ($fatal) {   my $folder=shift(@folders);
    $r->print('<p><font color="red">'.$errtext.'</font></p>');      my $foldername=shift(@folders);
    return;   if ($folderpath) {$folderpath.='&';}
        }   $folderpath.=$folder.'&'.$foldername;
            }   my $url='/adm/coursedocs?folderpath='.
        }      &escape($folderpath);
 # ---------------------------------------------------------------- End commands      my $name=&unescape($foldername);
 # ---------------------------------------------------------------- Print screen  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
         my $idx=0;       $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
  my $shown=0;      if ($1 ne '') {
         $r->print('<table>');                 $randompick=$1;
         foreach (@Apache::lonratedt::order) {              } else {
            my ($name,$url)=split(/\:/,$Apache::lonratedt::resources[$_]);                 $randompick=-1;
            unless ($name) {  $name=(split(/\//,$url))[-1]; }              }
            unless ($name) { $idx++; next; }              if ($2) { $ishidden=1; }
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));              if ($3) { $isencrypted=1; }
            $idx++;      if ($4 ne '') { $is_random_order = 1; }
    $shown++;              if ($folder eq 'supplemental') {
         }                  if ($allowed) {
  unless ($shown) {                      $name = &mt('Supplemental '.$type.' Documents');
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');                  } else {
  }                      $name = &mt($type.' Documents');
         $r->print('</table>');                  }
     }              }
 }      &Apache::lonhtmlcommon::add_breadcrumb(
         {'href'=>$url.$cpinfo,
 # --------------------------------------------------------------- An entry line         'title'=>$name,
          'text'=>'<font size="+1">'.
 sub entryline {     $name.'</font>',
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;         'no_mt'=>1,
     $title=~s/\&colon\;/\:/g;         });
     $title=&HTML::Entities::encode(&HTML::Entities::decode(   $plain.=$name.' &gt; ';
      &Apache::lonnet::unescape($title)),'"<>&\'');      }
     my $renametitle=$title;      $plain=~s/\&gt\;\s*$//;
     my $foldertitle=$title;      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
     my $pagetitle=$title;         'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);
     my $orderidx=$Apache::lonratedt::order[$index];  }
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/ ) {   
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);  sub log_docs {
  $renametitle=$4;      return &Apache::lonnet::instructor_log('docslog',@_);
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.  }
     &Apache::loncommon::plainname($2,$3).': <br />'.  
     $foldertitle;  {
     }      my @oldresources=();
     $renametitle=~s/\&quot\;/\\\"/g;      my @oldorder=();
     my $line='<tr>';      my $parmidx;
 # Edit commands      my %parmaction=();
     my $container;      my %parmvalue=();
     my $folderpath;      my $changedflag;
     if ($ENV{'form.folderpath'}) {  
         $container = 'sequence';      sub snapshotbefore {
  $folderpath=&Apache::lonnet::escape($ENV{'form.folderpath'});          @oldresources=@LONCAPA::map::resources;
  # $htmlfoldername=&HTML::Entities::encode($ENV{'form.foldername'},'<>&"');          @oldorder=@LONCAPA::map::order;
     }          $parmidx=undef;
     my $pagepath;          %parmaction=();
     if ($ENV{'form.pagepath'}) {          %parmvalue=();
         $container = 'page';          $changedflag=0;
         $pagepath=&Apache::lonnet::escape($ENV{'form.pagepath'});      }
     }  
     if ($allowed) {      sub remember_parms {
  my $incindex=$index+1;          my ($idx,$parameter,$action,$value)=@_;
  my $selectbox='';          $parmidx=$idx;
  if ($folder!~/^supplemental/) {          $parmaction{$parameter}=$action;
     $selectbox=          $parmvalue{$parameter}=$value;
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.          $changedflag=1;
  '<select name="newpos" onChange="this.form.submit()">';      }
     for (my $i=1;$i<=$#Apache::lonratedt::order+1;$i++) {  
  if ($i==$incindex) {      sub log_differences {
     $selectbox.='<option value="" selected="1">('.$i.')</option>';          my ($plain)=@_;
  } else {          my %storehash=('folder' => $plain,
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';                         'currentfolder' => $env{'form.folder'});
  }          if ($parmidx) {
     }             $storehash{'parameter_res'}=$oldresources[$parmidx];
     $selectbox.='</select>';             foreach my $parm (keys(%parmaction)) {
  }                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
  my %lt=&Apache::lonlocal::texthash(                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
                 'up' => 'Move Up',             }
  'dw' => 'Move Down',          }
  'rm' => 'Remove',          my $maxidx=$#oldresources;
  'rn' => 'Rename');          if ($#LONCAPA::map::resources>$#oldresources) {
         if ($ENV{'form.pagepath'}) {             $maxidx=$#LONCAPA::map::resources;
             $line.=(<<END);          }
 <form name="entry_$index" action="/adm/coursedocs" method="post">          for (my $idx=0; $idx<=$maxidx; $idx++) {
 <input type="hidden" name="pagepath" value="$ENV{'form.pagepath'}" />             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
 <input type="hidden" name="setparms" value="$orderidx" />                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
 <td><table border='0' cellspacing='2' cellpadding='0'>                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
 <tr><td bgcolor="#DDDDDD">                $changedflag=1;
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath'>             }
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
 <tr><td bgcolor="#DDDDDD">                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath'>                $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>                $changedflag=1;
 </table></td>             }
 <td>$selectbox          }
 </td><td bgcolor="#DDDDDD">   $storehash{'maxidx'}=$maxidx;
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page");'>          if ($changedflag) { &log_docs(\%storehash); }
 <font size="-2" color="#990000">$lt{'rm'}</font></a>      }
 <a href='javascript:changename("$pagepath","$index","$renametitle","page");'>  }
 <font size="-2" color="#009900">$lt{'rn'}</font></a></td>  
 END  
         } else {  
             $line.=(<<END);   
 <form name="entry_$index" action="/adm/coursedocs" method="post">  
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />  sub docs_change_log {
 <input type="hidden" name="setparms" value="$orderidx" />      my ($r)=@_;
 <td><table border='0' cellspacing='2' cellpadding='0'>      my $folder=$env{'form.folder'};
 <tr><td bgcolor="#DDDDDD">      $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath'>      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>      my %docslog=&Apache::lonnet::dump('nohist_docslog',
 <tr><td bgcolor="#DDDDDD">                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath'>                                        $env{'course.'.$env{'request.course.id'}.'.num'});
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>  
 </table></td>      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
 <td>$selectbox  
 </td><td bgcolor="#DDDDDD">      $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>                '<input type="hidden" name="docslog" value="1" />');
 <font size="-2" color="#990000">$lt{'rm'}</font></a>  
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>      my %saveable_parameters = ('show' => 'scalar',);
 <font size="-2" color="#009900">$lt{'rn'}</font></a></td>      &Apache::loncommon::store_course_settings('docs_log',
 END                                                \%saveable_parameters);
         }      &Apache::loncommon::restore_course_settings('docs_log',
     }                                                  \%saveable_parameters);
 # Figure out what kind of a resource this is      if (!$env{'form.show'}) { $env{'form.show'}=10; }
     my ($extension)=($url=~/\.(\w+)$/);      my %lt=('hiddenresource' => 'Resources hidden',
     my $uploaded=($url=~/^\/*uploaded\//);      'encrypturl'     => 'URL hidden',
     my $icon=&Apache::loncommon::icon($url);      'randompick'     => 'Randomly pick',
     my $isfolder=0;      'randomorder'    => 'Randomly ordered',
     my $ispage=0;      'set'            => 'set to',
     my $folderarg;      'del'            => 'deleted');
     my $pagearg;      $r->print(&Apache::loncommon::display_filter().
     my $pagefile;                '<input type="hidden" name="folder" value="'.$folder.'" />'.
     if ($uploaded) {                '<input type="submit" value="'.&mt('Display').'" /></form>');
  if ($extension eq 'sequence') {      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
     $icon=$iconpath.'/folder_closed.gif';                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
     $url=~/$coursenum\/([\/\w]+)\.sequence$/;                &mt('After').'</th>'.
     $url='/adm/coursedocs?';                &Apache::loncommon::end_data_table_header_row());
     $folderarg=$1;      my $shown=0;
     $isfolder=1;      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
         } elsif ($extension eq 'page') {   if ($env{'form.displayfilter'} eq 'currentfolder') {
             $icon=$iconpath.'/page.gif';      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
             $url=~/$coursenum\/([\/\w]+)\.page$/;   }
             $pagearg=$1;          my @changes=keys(%{$docslog{$id}{'logentry'}});
             $url='/adm/coursedocs?';          if ($env{'form.displayfilter'} eq 'containing') {
             $ispage=1;      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
  } else {   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);      foreach my $key (@changes) {
  }   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
     }      }
     $url=~s/^http\&colon\;\/\//\/adm\/wrapper\/ext\//;      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }        
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {   }
  my $symb=&Apache::lonnet::symbclean(          my $count = 0;
           &Apache::lonnet::declutter('uploaded/'.          my $time =
            $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.'/'.              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
            $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.'/'.$folder.          my $plainname =
            '.sequence').              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
            '___'.$residx.'___'.                                            $docslog{$id}{'exe_udom'});
    &Apache::lonnet::declutter($url));          my $about_me_link =
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);              &Apache::loncommon::aboutmewrapper($plainname,
  $url=&Apache::lonnet::clutter($url);                                                 $docslog{$id}{'exe_uname'},
  if ($url=~/^\/*uploaded\//) {                                                 $docslog{$id}{'exe_udom'});
     $url=~/\.(\w+)$/;          my $send_msg_link='';
     my $embstyle=&Apache::loncommon::fileembstyle($1);          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
  $url='/adm/wrapper'.$url;              $send_msg_link ='<br />'.
     } elsif ($embstyle eq 'ssi') {                  &Apache::loncommon::messagewrapper(&mt('Send message'),
  #do nothing with these                                                     $docslog{$id}{'exe_uname'},
     } elsif ($url!~/\.(sequence|page)$/) {                                                     $docslog{$id}{'exe_udom'});
  $url='/adm/coursedocs/showdoc'.$url;          }
     }          $r->print(&Apache::loncommon::start_data_table_row());
  } elsif ($url=~m|^/ext/|) {           $r->print('<td>'.$time.'</td>
     $url='/adm/wrapper'.$url;                         <td>'.$about_me_link.
  }                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
         unless ($container eq 'page') {                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
     $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);                    $send_msg_link.'</td><td>'.
         }                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
     }  # Before
     my $parameterset='&nbsp;';   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     if ($isfolder) {      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
  my $foldername=&Apache::lonnet::escape($foldertitle);      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
  my $folderpath=$ENV{'form.folderpath'};      if ($oldname ne $newname) {
  if ($folderpath) { $folderpath.='&' };   $r->print(&LONCAPA::map::qtescape($oldname));
  $folderpath.=$folderarg.'&'.$foldername;      }
  $url.='folderpath='.&Apache::lonnet::escape($folderpath);   }
  $parameterset='<label>'.&mt('Randomly Pick: ').   $r->print('<ul>');
     '<input type="text" size="4" name="randpick_'.$orderidx.'" value="'.   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     (&Apache::lonratedt::getparameter($orderidx,              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
                                               'parameter_randompick'))[0].   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
                                               '" />'.'</label>';      }
           }
     }   $r->print('</ul>');
     if ($ispage) {  # After
         my $pagename=&Apache::lonnet::escape($pagetitle);          $r->print('</td><td>');
         my $pagepath;  
         my $folderpath=$ENV{'form.folderpath'};   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
         if ($folderpath) { $pagepath = $folderpath.'&' };      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
         $pagepath.=$pagearg.'&'.$pagename;      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
         $url.='pagepath='.&Apache::lonnet::escape($pagepath);      if ($oldname ne '' && $oldname ne $newname) {
     }   $r->print(&LONCAPA::map::qtescape($newname));
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.      }
  '" border="0"></a></td>'.   }        
         "<td bgcolor='#FFFFBB'><a href='$url'>$title</a></td>";   $r->print('<ul>');
     if (($allowed) && ($folder!~/^supplemental/)) {   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
   my %lt=&Apache::lonlocal::texthash(              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
        'hd' => 'Hidden',   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
        'ec' => 'URL hidden',      }
        'sp' => 'Store Parameters');   }
  my $enctext=   $r->print('</ul>');
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
  my $hidtext=      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
  $line.=(<<ENDPARMS);   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
 <td bgcolor="#BBBBFF"><font size='-2'>      $r->print('<li>'.
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" $hidtext/> $lt{'hd'}</label></nobr></td>        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
 <td bgcolor="#BBBBFF"><font size='-2'>    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
 <nobr><label><input type="checkbox" name="encprs_$orderidx" $enctext/> $lt{'ec'}</label></nobr></td>        .'</li>');
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>   }
 <td bgcolor="#BBBBFF"><font size='-2'>      }
 <input type="submit" value="$lt{'sp'}" />      $r->print('</ul>');
 </font></td>   }
 ENDPARMS  # End
     }          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
     $line.="</form></tr>";          $shown++;
     return $line;          if (!($env{'form.show'} eq &mt('all')
 }                || $shown<=$env{'form.show'})) { last; }
       }
 # ---------------------------------------------------------------- tie the hash      $r->print(&Apache::loncommon::end_data_table());
   }
 sub tiehash {  
     my ($mode)=@_;  sub update_paste_buffer {
     $hashtied=0;      my ($coursenum,$coursedom) = @_;
     if ($ENV{'request.course.fn'}) {  
  if ($mode eq 'write') {      return if (!defined($env{'form.markcopy'}));
     if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",      return if (!defined($env{'form.copyfolder'}));
     &GDBM_WRCREAT(),0640)) {      return if ($env{'form.markcopy'} < 0);
                 $hashtied=2;  
     }      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
  } else {      $env{'form.copyfolder'});
     if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.".db",     
     &GDBM_READER(),0640)) {      return if ($fatal);
                 $hashtied=1;  
     }  # Mark for copying
  }      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
     }          if (&is_supplemental_title($title)) {
 }          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
    ($title) = &parse_supplemental_title($title);
 sub untiehash {      } elsif ($env{'docs.markedcopy_supplemental'}) {
     if ($hashtied) { untie %hash; }          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
     $hashtied=0;      }
 }      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
   
 # --------------------------------------------------------------- check on this      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
       'docs.markedcopy_url'   => $url});
 sub checkonthis {      delete($env{'form.markcopy'});
     my ($r,$url,$level,$title)=@_;  }
     $url=&Apache::lonnet::unescape($url);  
     $alreadyseen{$url}=1;  sub print_paste_buffer {
     $r->rflush();      my ($r,$container) = @_;
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {      return if (!defined($env{'docs.markedcopy_url'}));
        $r->print("\n<br />");  
        for (my $i=0;$i<=$level*5;$i++) {      $r->print(<<ENDPASTE);
            $r->print('&nbsp;');  <form name="pasteform" action="/adm/coursedocs" method="post"><p>
        }  ENDPASTE
        $r->print('<a href="'.$url.'" target="cat">'.      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
  ($title?$title:$url).'</a> ');  
        if ($url=~/^\/res\//) {      my $type;
   my $result=&Apache::lonnet::repcopy(      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
                               &Apache::lonnet::filelocation('',$url));   $type = &mt('External Resource');
           if ($result==OK) {   $r->print($type.': '.
              $r->print('<font color="green">'.&mt('ok').'</font>');    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
              $r->rflush();    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
              &Apache::lonnet::countacc($url);      }  else {
              $url=~/\.(\w+)$/;   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {   my $icon = &Apache::loncommon::icon($extension);
  $r->print('<br />');   if ($extension eq 'sequence' &&
                  $r->rflush();      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
                  for (my $i=0;$i<=$level*5;$i++) {      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
                      $r->print('&nbsp;');      $icon .= '/folder_closed.gif';
                  }   }
                  $r->print('- '.&mt('Rendering').': ');   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
                  my $oldpath=$ENV{'request.filename'};   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
                  $ENV{'request.filename'}=&Apache::lonnet::filelocation('',$url);      }
                  &Apache::lonxml::xmlparse($r,'web',      if ($container eq 'page') {
                    &Apache::lonnet::getfile(   $r->print('
                     &Apache::lonnet::filelocation('',$url)));   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
  undef($Apache::lonhomework::parsing_a_problem);   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
  $ENV{'request.filename'}=$oldpath;  ');
                  if (($Apache::lonxml::errorcount) ||      } else {
                      ($Apache::lonxml::warningcount)) {   $r->print('
      if ($Apache::lonxml::errorcount) {          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.  ');
   $Apache::lonxml::errorcount.' '.      }
   &mt('error(s)').'</b></font> ');      $r->print('</p></form>');
                      }  }
      if ($Apache::lonxml::warningcount) {  
                         $r->print('<font color="blue">'.  sub do_paste_from_buffer {
   $Apache::lonxml::warningcount.' '.      my ($coursenum,$coursedom,$folder) = @_;
   &mt('warning(s)').'</font>');  
                      }      if (!$env{'form.pastemarked'}) {
                  } else {          return;
                      $r->print('<font color="green">'.&mt('ok').'</font>');      }
                  }  
                  $r->rflush();  # paste resource to end of list
              }      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
      my $dependencies=      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
                 &Apache::lonnet::metadata($url,'dependencies');  # Maps need to be copied first
              foreach (split(/\,/,$dependencies)) {      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {   $title=&mt('Copy of').' '.$title;
                     &checkonthis($r,$_,$level+1);   my $newid=$$.int(rand(100)).time;
                  }   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
              }          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
           } elsif ($result==HTTP_SERVICE_UNAVAILABLE) {              my $path = $1;
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');              my $prefix = $2;
           } elsif ($result==HTTP_NOT_FOUND) {              my $ancestor = $3;
       unless ($url=~/\$/) {              if (length($ancestor) > 10) {
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');                  $ancestor = substr($ancestor,-10,10);
       } else {              }
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');              $oldid = $path.$prefix.$ancestor;
       }          }
           } else {          my $counter = 0;
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');          my $newurl=$oldid.$newid.'.'.$ext;
           }          my $is_unique = &uniqueness_check($newurl);
       }          while (!$is_unique && $counter < 100) {
    }              $counter ++;
 }              $newid ++;
               $newurl = $oldid.$newid;
               $is_unique = &uniqueness_check($newurl);
 #          }
 # -------------------------------------------------------------- Verify Content          if (!$is_unique) {
 #               if ($url=~/\.page$/) {
 sub verifycontent {                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
    my $r=shift;               } else {
    my $loaderror=&Apache::lonnet::overloaderror($r);                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
    if ($loaderror) { return $loaderror; }              }
           }
    $r->print('<html><head><title>Verify Content</title></head>'.   my $storefn=$newurl;
               &Apache::loncommon::bodytag('Verify Course Documents'));   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
    $hashtied=0;   my $paste_map_result =
    undef %alreadyseen;              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
    %alreadyseen=();         &Apache::lonnet::getfile($url));
    &tiehash();          if ($paste_map_result eq '/adm/notfound.html') {
    foreach (keys %hash) {              if ($url=~/\.page$/) {
        if ($hash{$_}=~/\.(page|sequence)$/) {                  return &mt('Paste failed: an error occurred saving the composite page');
    if (($_=~/^src_/) && ($alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {              } else {
        $r->print('<hr /><font color="red">'.                  return &mt('Paste failed: an error occurred saving the folder');
  &mt('The following sequence or page is included more than once in your course: ').              }
  &Apache::lonnet::unescape($hash{$_}).'</font><br />'.          }
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));   $url = $newurl;
    }      }
        }  # published maps can only exists once, so remove it from paste buffer when done
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});   &Apache::lonnet::delenv('docs\\.markedcopy');
        }      }
    }      if ($url=~ m{/smppg$}) {
    &untiehash();   my $db_name = &Apache::lonsimplepage::get_db_name($url);
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.   if ($db_name =~ /^smppage_/) {
      &mt('Return to DOCS').'</a>');      #simple pages, need to copy the db contents to a new one.
 }      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
       my $now = time();
 # -------------------------------------------------------------- Check Versions      $db_name =~ s{_\d*$ }{_$now}x;
       my $result=&Apache::lonnet::put($db_name,\%contents,
 sub checkversions {      $coursedom,$coursenum);
     my $r=shift;      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
     $r->print('<html><head><title>Check Versions</title></head>'.      $title=&mt('Copy of').' '.$title;
               &Apache::loncommon::bodytag('Check Course Document Versions'));   }
     my $header='';      }
     my $startsel='';      $title = &LONCAPA::map::qtunescape($title);
     my $monthsel='';      my $ext='false';
     my $weeksel='';      if ($url=~m{^http(|s)://}) { $ext='true'; }
     my $daysel='';      $url       = &LONCAPA::map::qtunescape($url);
     my $allsel='';  # Now insert the URL at the bottom
     my %changes=();      my $newidx = &LONCAPA::map::getresidx($url);
     my $starttime=0;      if ($env{'docs.markedcopy_supplemental'}) {
     my $haschanged=0;          if ($folder =~ /^supplemental/) {
     my %setversions=&Apache::lonnet::dump('resourceversions',              $title = $env{'docs.markedcopy_supplemental'};
   $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},          } else {
   $ENV{'course.'.$ENV{'request.course.id'}.'.num'});              (undef,undef,$title) =
                   &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
     $hashtied=0;          }
     &tiehash();      } else {
     my %newsetversions=();          if ($folder=~/^supplemental/) {
     if ($ENV{'form.setmostrecent'}) {             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  $haschanged=1;                    $env{'user.domain'}.'___&&&___'.$title;
  foreach (keys %hash) {          }
     if ($_=~/^ids\_(\/res\/.+)$/) {      }
  $newsetversions{$1}='mostrecent';  
     }      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
  }      push(@LONCAPA::map::order, $newidx);
     } elsif ($ENV{'form.setcurrent'}) {      return 'ok';
  $haschanged=1;  # Store the result
  foreach (keys %hash) {  }
     if ($_=~/^ids\_(\/res\/.+)$/) {  
  my $getvers=&Apache::lonnet::getversion($1);  sub uniqueness_check {
  if ($getvers>0) {      my ($newurl) = @_;
     $newsetversions{$1}=$getvers;      my $unique = 1;
  }      foreach my $res (@LONCAPA::map::order) {
     }          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  }          $url=&LONCAPA::map::qtescape($url);
     } elsif ($ENV{'form.setversions'}) {          if ($newurl eq $url) {
  $haschanged=1;              $unique = 0;
  foreach (keys %ENV) {              last;    
     if ($_=~/^form\.set_version_(.+)$/) {          }
  my $src=$1;      }
  if (($ENV{$_}) && ($ENV{$_} ne $setversions{$src})) {      return $unique;
     $newsetversions{$src}=$ENV{$_};  }
  }  
     }  my %parameter_type = ( 'randompick'     => 'int_pos',
  }         'hiddenresource' => 'string_yesno',
     }         'encrypturl'     => 'string_yesno',
     if ($haschanged) {         'randomorder'    => 'string_yesno',);
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,  my $valid_parameters_re = join('|',keys(%parameter_type));
   $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},  # set parameters
   $ENV{'course.'.$ENV{'request.course.id'}.'.num'}) eq 'ok') {  sub update_parameter {
     $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');  
  } else {      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');  
  }      my $which = $env{'form.changeparms'};
  &mark_hash_old();      my $idx = $env{'form.setparms'};
     }      if ($env{'form.'.$which.'_'.$idx}) {
     &changewarning($r,'');   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
     if ($ENV{'form.timerange'} eq 'all') {                                       : 'yes';
 # show all documents   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
  $header=&mt('All Documents in Course');        $parameter_type{$which});
  $allsel=1;   &remember_parms($idx,$which,'set',$value);
  foreach (keys %hash) {      } else {
     if ($_=~/^ids\_(\/res\/.+)$/) {   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
  my $src=$1;  
  $changes{$src}=1;   &remember_parms($idx,$which,'del');
     }      }
  }      return 1;
     } else {  }
 # show documents which changed  
  %changes=&Apache::lonnet::dump  
  ('versionupdate',$ENV{'course.'.$ENV{'request.course.id'}.'.domain'},  sub handle_edit_cmd {
                      $ENV{'course.'.$ENV{'request.course.id'}.'.num'});      my ($coursenum,$coursedom) =@_;
  my $firstkey=(keys %changes)[0];  
  unless ($firstkey=~/^error\:/) {      my ($cmd,$idx)=split('_',$env{'form.cmd'});
     unless ($ENV{'form.timerange'}) {  
  $ENV{'form.timerange'}=604800;      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     }      my ($title, $url, @rrest) = split(':', $ratstr);
     my $seltext=&mt('during the last').' '.$ENV{'form.timerange'}.' '  
  .&mt('seconds');      if ($cmd eq 'del') {
     if ($ENV{'form.timerange'}==-1) {   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
  $seltext='since start of course';      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
  $startsel='selected';      &Apache::lonnet::removeuploadedurl($url);
  $ENV{'form.timerange'}=time;   } else {
     }      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
     $starttime=time-$ENV{'form.timerange'};   }
     if ($ENV{'form.timerange'}==2592000) {   splice(@LONCAPA::map::order, $idx, 1);
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  
  $monthsel='selected';      } elsif ($cmd eq 'cut') {
     } elsif ($ENV{'form.timerange'}==604800) {   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   splice(@LONCAPA::map::order, $idx, 1);
  $weeksel='selected';  
     } elsif ($ENV{'form.timerange'}==86400) {      } elsif ($cmd eq 'up'
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
  $daysel='selected';   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
     }  
     $header=&mt('Content changed').' '.$seltext;      } elsif ($cmd eq 'down'
  } else {       && defined($LONCAPA::map::order[$idx+1])) {
     $header=&mt('No content modifications yet.');   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
  }  
     }      } elsif ($cmd eq 'rename') {
     %setversions=&Apache::lonnet::dump('resourceversions',  
   $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
   $ENV{'course.'.$ENV{'request.course.id'}.'.num'});   if ($comment=~/\S/) {
     my %lt=&Apache::lonlocal::texthash      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
       ('st' => 'Version changes since start of Course',   $comment.':'.join(':', $url, @rrest);
        'lm' => 'Version changes since last Month',   }
        'lw' => 'Version changes since last Week',  # Devalidate title cache
        'sy' => 'Version changes since Yesterday',   my $renamed_url=&LONCAPA::map::qtescape($url);
                'al' => 'All Resources (possibly large output)',   &Apache::lonnet::devalidate_title_cache($renamed_url);
        'sd' => 'Display',      } else {
        'fi' => 'File',   return 0;
        'md' => 'Modification Date',      }
                'mr' => 'Most recently published Version',      return 1;
        've' => 'Version used in Course',  }
                'vu' => 'Set Version to be used in Course',  
 'sv' => 'Set Versions to be used in Course according to Selections below',  sub editor {
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',  
        'di' => 'Differences');      my $container= ($env{'form.pagepath'}) ? 'page'
     $r->print(<<ENDHEADERS);                             : 'sequence';
 <form action="/adm/coursedocs" method="post">  
 <input type="hidden" name="versions" value="1" />      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />      $folder.'.'.$container);
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />      return $errtext if ($fatal);
 <select name="timerange">  
 <option value='all' $allsel>$lt{'al'}</option>      if ($#LONCAPA::map::order<1) {
 <option value="-1" $startsel>$lt{'st'}</option>   my $idx=&LONCAPA::map::getresidx();
 <option value="2592000" $monthsel>$lt{'lm'}</option>   if ($idx<=0) { $idx=1; }
 <option value="604800" $weeksel>$lt{'lw'}</option>          $LONCAPA::map::order[0]=$idx;
 <option value="86400" $daysel>$lt{'sy'}</option>          $LONCAPA::map::resources[$idx]='';
 </select>      }
 <input type="submit" name="display" value="$lt{'sd'}" />     
 <h3>$header</h3>      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
 <input type="submit" name="setversions" value="$lt{'sv'}" />   &breadcrumbs($folder,$allowed,$type);
 <table border="0">      $r->print($breadcrumbtrail);
 ENDHEADERS     
     foreach (sort keys %changes) {  # ------------------------------------------------------------ Process commands
  if ($changes{$_}>$starttime) {  
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);  # ---------------- if they are for this folder and user allowed to make changes
     my $currentversion=&Apache::lonnet::getversion($_);      if (($allowed) && ($env{'form.folder'} eq $folder)) {
     if ($currentversion<0) {  # set parameters and change order
  $currentversion=&mt('Could not be determined.');   &snapshotbefore();
     }  
     my $linkurl=&Apache::lonnet::clutter($_);   if (&update_parameter()) {
     $r->print(      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      return $errtext if ($fatal);
       &Apache::lonnet::gettitle($linkurl).   }
                       '</b></font></td></tr>'.  
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
                       '<td colspan="4">'.  # change order
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
       '</a></td></tr>'.      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
                       '<tr><td></td>'.  
                       '<td title="'.$lt{'md'}.'">'.      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
       &Apache::lonlocal::locallocaltime(      return $errtext if ($fatal);
                            &Apache::lonnet::metadata($root.'.'.$extension,   }
                                                      'lastrevisiondate')      
                                                         ).   if ($env{'form.pastemarked'}) {
                       '</td>'.              my $paste_res =
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
                       '<font size="+1">'.$currentversion.'</font>'.              if ($paste_res eq 'ok') {
                       '</nobr></td>'.                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
                       '<td title="'.$lt{'ve'}.'"><nobr>In Course: '.                  return $errtext if ($fatal);
                       '<font size="+1">');              } elsif ($paste_res ne '') {
 # Used in course                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
     my $usedversion=$hash{'version_'.$linkurl};              }
     if (($usedversion) && ($usedversion ne 'mostrecent')) {   }
  $r->print($usedversion);  
     } else {   $r->print($upload_output);
  $r->print($currentversion);  
     }   if (&handle_edit_cmd()) {
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
                       '<nobr>Use: ');      return $errtext if ($fatal);
 # Set version   }
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},  # Group import/search
       'set_version_'.$linkurl,   if ($env{'form.importdetail'}) {
       ('select_form_order' =>      my @imports;
        ['',1..$currentversion,'mostrecent'],      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
        '' => '',   if (defined($item)) {
        'mostrecent' => 'most recent',      my ($name,$url,$residx)=
        map {$_,$_} (1..$currentversion))));   map {&unescape($_)} split(/\=/,$item);
     $r->print('</nobr></td></tr><tr><td></td>');      push(@imports, [$name, $url, $residx]);
     my $lastold=1;   }
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {      }
  my $url=$root.'.'.$prevvers.'.'.$extension;      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<      $container,'londocs',@imports);
     $starttime) {      return $errtext if ($fatal);
     $lastold=$prevvers;   }
  }  # Loading a complete map
     }   if ($env{'form.loadmap'}) {
             #       if ($env{'form.importmap'}=~/\w/) {
             # Code to figure out how many version entries should go in   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
             # each of the four columns      my ($title,$url,$ext,$type)=split(/\:/,$res);
             my $entries_per_col = 0;      my $idx=&LONCAPA::map::getresidx($url);
             my $num_entries = ($currentversion-$lastold);      $LONCAPA::map::resources[$idx]=$res;
             if ($num_entries % 4 == 0) {      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
                 $entries_per_col = $num_entries/4;   }
             } else {   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
                 $entries_per_col = $num_entries/4 + 1;      $folder.'.'.$container);
             }   return $errtext if ($fatal);
             my $entries_count = 0;      } else {
             $r->print('<td valign="top"><font size="-2">');    $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
             my $cols_output = 1;  
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {      }
  my $url=$root.'.'.$prevvers.'.'.$extension;   }
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).   &log_differences($plain);
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      }
   &Apache::lonlocal::locallocaltime(  # ---------------------------------------------------------------- End commands
                                 &Apache::lonnet::metadata($url,  # ---------------------------------------------------------------- Print screen
                                                           'lastrevisiondate')      my $idx=0;
                                                             ).      my $shown=0;
   ')');      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   $r->print('<p>'.&mt('Parameters').':<ul>'.
                     $r->print(' <a href="/adm/diff?filename='.    ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
       &Apache::lonnet::clutter($root.'.'.$extension).    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
       '&versionone='.$prevvers.    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
       '">'.&mt('Diffs').'</a>');    '</ul></p>');
  }      }                                                                                                    
  $r->print('</nobr><br />');      if ($randompick>=0) {
                 if (++$entries_count % $entries_per_col == 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>');
                     $r->print('</font></td>');      }
                     if ($cols_output != 4) {      if ($is_random_order) {
                         $r->print('<td valign="top"><font size="-2">');   $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>');
                         $cols_output++;      }
                     }      $r->print('<table class="LC_docs_editor">');
                 }      foreach my $res (@LONCAPA::map::order) {
     }   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
             while($cols_output++ < 4) {   $name=&LONCAPA::map::qtescape($name);
                 $r->print('</font></td><td><font>')   $url=&LONCAPA::map::qtescape($url);
             }   unless ($name) {  $name=(split(/\//,$url))[-1]; }
     $r->print('</font></td></tr>'."\n");   unless ($name) { $idx++; next; }
  }   $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
     }       $coursenum));
     $r->print('</table></form>');   $idx++;
     $r->print('<h1>'.&mt('Done').'.</h1>');   $shown++;
       }
     &untiehash();      unless ($shown) {
 }   $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
       }
 sub mark_hash_old {      $r->print("\n</table>\n");
     my $retie_hash=0;      if ($allowed) {
     if ($hashtied) {          &print_paste_buffer($r,$container);
  $retie_hash=1;      }
  &untiehash();      return;
     }  }
     &tiehash('write');  
     $hash{'old'}=1;  sub process_file_upload {
     &untiehash();      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     if ($retie_hash) { &tiehash(); }  # upload a file, if present
 }      my $parseaction;
      if ($env{'form.parserflag'}) {
 sub is_hash_old {          $parseaction = 'parse';
     my $untie_hash=0;      }
     if (!$hashtied) {      my $phase_status;
  $untie_hash=1;      my $folder=$env{'form.folder'};
  &tiehash();      if ($folder eq '') {
     }          $folder='default';
     my $return=$hash{'old'};      }
     if ($untie_hash) { &untiehash(); }      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
     return $return;          my $errtext='';
 }          my $fatal=0;
           my $container='sequence';
 sub changewarning {          if ($env{'form.pagepath'}) {
     my ($r,$postexec)=@_;              $container='page';
     if (!&is_hash_old()) { return; }          }
     my $pathvar='folderpath';          ($errtext,$fatal)=
     my $path=&Apache::lonnet::escape($ENV{'form.folderpath'});                &mapread($coursenum,$coursedom,$folder.'.'.$container);
     if (defined($ENV{'form.pagepath'})) {          if ($#LONCAPA::map::order<1) {
  $pathvar='pagepath';              $LONCAPA::map::order[0]=1;
  $path=&Apache::lonnet::escape($ENV{'form.pagepath'});              $LONCAPA::map::resources[1]='';
     }          }
     $r->print(          if ($fatal) {
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'.               return 'failed';
 '<form method="post" action="/adm/roles" target="loncapaclient">'.          }
 '<input type="hidden" name="orgurl" value="/adm/coursedocs?'.          my $destination = 'docs/';
 $pathvar.'='.$path.          if ($folder =~ /^supplemental/) {
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.              $destination = 'supplemental/';
 &mt('Changes will become active for your current session after').          }
 ' <input type="hidden" name="'.          if (($folder eq 'default') || ($folder eq 'supplemental')) {
 $ENV{'request.role'}.'" value="1" /><input type="button" value="'.              $destination .= 'default/';
 &mt('re-initializing course').'" onClick="reinit(this.form)"/>'.&mt(', or the next time you log in.').          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 $help{'Caching'}.'</font></h3></form>');              $destination .=  $2.'/';
 }          }
   # this is for a course, not a user, so set coursedoc flag
 # ================================================================ Main Handler  # probably the only place in the system where this should be "1"
 sub handler {          my $newidx=&LONCAPA::map::getresidx();
     my $r = shift;          $destination .= $newidx;
     &Apache::loncommon::content_type($r,'text/html');          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
     $r->send_http_header;   $parseaction,$allfiles,
     return OK if $r->header_only;   $codebase);
           my $ext='false';
 # --------------------------------------------- Initialize help topics for this          if ($url=~m{^http://}) { $ext='true'; }
   foreach ('Adding_Course_Doc','Main_Course_Documents',   $url     = &LONCAPA::map::qtunescape($url);
            'Adding_External_Resource','Navigate_Content',          my $comment=$env{'form.comment'};
            'Adding_Folders','Docs_Overview', 'Load_Map',   $comment = &LONCAPA::map::qtunescape($comment);
            'Supplemental','Score_Upload_Form','Adding_Pages',          if ($folder=~/^supplemental/) {
            'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
    'Check_Resource_Versions','Verify_Content') {                    $env{'user.domain'}.'___&&&___'.$comment;
       $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);          }
   }  
     # Composite help files          $LONCAPA::map::resources[$newidx]=
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      $comment.':'.$url.':'.$ext.':normal:res';
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');      $folder.'.'.$container);
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(          if ($fatal) {
     'Option_Response_Simple');              $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(              return 'failed';
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');          } else {
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(              if ($parseaction eq 'parse') {
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                  my $total_embedded = keys(%{$allfiles});
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');                  if ($total_embedded > 0) {
                       my $num = 0;
   if ($ENV{'form.verify'}) {      my $state = '
       &verifycontent($r);     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
   } elsif ($ENV{'form.versions'}) {     <input type="hidden" name="cmd" value="upload_embedded" />
       &checkversions($r);     <input type="hidden" name="newidx" value="'.$newidx.'" />
   } elsif ($ENV{'form.dumpcourse'}) {     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
       &dumpcourse($r);     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
   } elsif ($ENV{'form.exportcourse'}) {      $phase_status = 'phasetwo';
       &exportcourse($r);  
   } else {                      $$upload_output .=
 # is this a standard course?   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
    &Apache::loncommon::ask_for_embedded_content(
     my $standard=($ENV{'request.course.uri'}=~/^\/uploaded\//);                              '/adm/coursedocs',$state,$allfiles,$codebase);
     my $forcestandard;                  } else {
     my $forcesupplement;                      $$upload_output .= 'No embedded items identified<br />';
     my $script='';                  }
     my $allowed;              }
     my $events='';          }
     my $showdoc=0;      }
     my $containertag;      return $phase_status;
     my $uploadtag;  }
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  
     ['folderpath','pagepath']);  sub process_secondary_uploads {
     if ($ENV{'form.folderpath'}) {      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
  my (@folderpath)=split('&',$ENV{'form.folderpath'});      my $folder=$env{'form.folder'};
  $ENV{'form.foldername'}=&Apache::lonnet::unescape(pop(@folderpath));      my $destination = 'docs/';
  $ENV{'form.folder'}=pop(@folderpath);      if ($folder =~ /^supplemental/) {
     }          $destination = 'supplemental/';
     if ($ENV{'form.pagepath'}) {      }
         my (@pagepath)=split('&',$ENV{'form.pagepath'});      if (($folder eq 'default') || ($folder eq 'supplemental')) {
         $ENV{'form.pagename'}=&Apache::lonnet::unescape(pop(@pagepath));          $destination .= 'default/';
         $ENV{'form.folder'}=pop(@pagepath);      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
         $containertag = '<input type="hidden" name="pagepath" value="" />';          $destination .=  $2.'/';
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$ENV{'form.pagepath'}.'" />';      }
     }      $destination .= $newidx;
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {      my ($url,$filename);
        $showdoc='/'.$1;      $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
     }      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
     unless ($showdoc) { # got called from remote      return $filename;
        $forcestandard=($ENV{'form.folder'}=~/^default_/);  }
        $forcesupplement=($ENV{'form.folder'}=~/^supplemental_/);  
   sub is_supplemental_title {
 # does this user have privileges to post, etc?      my ($title) = @_;
        $allowed=&Apache::lonnet::allowed('mdc',$ENV{'request.course.id'});      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
        if ($allowed) {   }
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);  
          $script=&Apache::lonratedt::editscript('simple');   sub parse_supplemental_title {
        }      my ($title) = @_;
     } else { # got called in sequence from course  
        $allowed=0;      my ($foldertitle,$renametitle);
        $script='</script>'.&Apache::lonmenu::registerurl(1,undef).'<script>';      if ($title =~ /&amp;&amp;&amp;/) {
        $events='onLoad="'.&Apache::lonmenu::loadevents.   $title = &HTML::Entites::decode($title);
            '" onUnload="'.&Apache::lonmenu::unloadevents.'"';      }
     }   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
    $renametitle=$4;
 # get course data   my ($time,$uname,$udom) = ($1,$2,$3);
     my $coursenum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
     my $coursedom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};   my $name =  &Apache::loncommon::plainname($uname,$udom);
    $name = &HTML::Entities::encode($name,'"<>&\'');
 # get personal data   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
        $name.': <br />'.$foldertitle;
     my $uname=$ENV{'user.name'};      }
     my $udom=$ENV{'user.domain'};      if (wantarray) {
     my $plainname=&Apache::lonnet::escape(   return ($title,$foldertitle,$renametitle);
                      &Apache::loncommon::plainname($uname,$udom));      }
       return $title;
 # graphics settings  }
   
     $iconpath = $r->dir_config('lonIconsURL') . "/";  # --------------------------------------------------------------- An entry line
   
     my $now=time;  sub entryline {
       my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
 # print screen  
     $r->print(<<ENDDOCUMENT);      my ($foldertitle,$pagetitle,$renametitle);
 <html>      if (&is_supplemental_title($title)) {
 <head>   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
 <title>The LearningOnline Network with CAPA</title>   $pagetitle = $foldertitle;
 <script>      } else {
 $script   $title=&HTML::Entities::encode($title,'"<>&\'');
 </script>   $renametitle=$title;
 ENDDOCUMENT   $foldertitle=$title;
    if ($allowed) {   $pagetitle=$title;
     $r->print(<<ENDNEWSCRIPT);      }
 <script>  
 function makenewfolder(targetform,folderseq) {      my $orderidx=$LONCAPA::map::order[$index];
     var foldername=prompt('Name of New Folder','New Folder');     
     if (foldername) {  
  targetform.importdetail.value=foldername+"="+folderseq;      $renametitle=~s/\\/\\\\/g;
         targetform.submit();      $renametitle=~s/\&quot\;/\\\"/g;
     }      $renametitle=~s/ /%20/g;
 }      my $line='<tr>';
       my ($form_start,$form_end);
 function makenewpage(targetform,folderseq) {  # Edit commands
     var pagename=prompt('Name of New Page','New Page');      my ($container, $type, $esc_path, $path, $symb);
     if (pagename) {      if ($env{'form.folderpath'}) {
         targetform.importdetail.value=pagename+"="+folderseq;   $type = 'folder';
         targetform.submit();          $container = 'sequence';
     }   $esc_path=&escape($env{'form.folderpath'});
 }   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
    # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 function makenewext(targetname) {      }
     this.document.forms.extimport.useform.value=targetname;      if ($env{'form.pagepath'}) {
     window.open('/adm/rat/extpickframe.html');          $type = $container = 'page';
 }          $esc_path=&escape($path = $env{'form.pagepath'});
    $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
 function makeexamupload() {          $symb=&escape($env{'form.pagesymb'});
    var title=prompt('Listed Title for the Uploaded Score');      }
    if (title) {       my $cpinfo='';
     this.document.forms.newexamupload.importdetail.value=      if ($allowed) {
  title+'=/res/lib/templates/examupload.problem';   my $incindex=$index+1;
     this.document.forms.newexamupload.submit();   my $selectbox='';
    }   if (($folder!~/^supplemental/) &&
 }      ($#LONCAPA::map::order>0) &&
       ((split(/\:/,
 function makesmppage() {       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
    var title=prompt('Listed Title for the Page');       ne '') &&
    if (title) {       ((split(/\:/,
     this.document.forms.newsmppg.importdetail.value=       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
  title+'=/adm/$udom/$uname/$now/smppg';       ne '')) {
     this.document.forms.newsmppg.submit();      $selectbox=
    }   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 }   '<select name="newpos" onChange="this.form.submit()">';
       for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
 function makesmpproblem() {   if ($i==$incindex) {
    var title=prompt('Listed Title for the Problem');      $selectbox.='<option value="" selected="1">('.$i.')</option>';
    if (title) {    } else {
     this.document.forms.newsmpproblem.importdetail.value=      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
  title+'=/res/lib/templates/simpleproblem.problem';   }
     this.document.forms.newsmpproblem.submit();      }
    }      $selectbox.='</select>';
 }   }
    my %lt=&Apache::lonlocal::texthash(
 function makebulboard() {                  'up' => 'Move Up',
    var title=prompt('Listed Title for the Bulletin Board');   'dw' => 'Move Down',
    if (title) {   'rm' => 'Remove',
     this.document.forms.newbul.importdetail.value=                  'ct' => 'Cut',
  title+'=/adm/$udom/$uname/$now/bulletinboard';   'rn' => 'Rename',
     this.document.forms.newbul.submit();   'cp' => 'Copy');
    }   my $nocopy=0;
 }          my $nocut=0;
           if ($url=~/\.(page|sequence)$/) {
 function makeabout() {      if ($url =~ m{/res/}) {
    var user=prompt("Enter user\@domain for User's 'About Me' Page");   # no copy for published maps
    if (user) {   $nocopy = 1;
        var comp=new Array();      } else {
        comp=user.split('\@');   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {      my ($title,$url,$ext,$type)=split(/\:/,$item);
    if ((comp[0]) && (comp[1])) {      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
        this.document.forms.newaboutsomeone.importdetail.value=   $nocopy=1;
    'About '+user+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   last;
        this.document.forms.newaboutsomeone.submit();      }
    }   }
        }      }
    }   }
 }          if ($url=~/^\/res\/lib\/templates\//) {
              $nocopy=1;
 function makeims() {             $nocut=1;
     var caller = document.forms.ims.folder.value          }
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one"          my $copylink='&nbsp;';
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes")          my $cutlink='&nbsp;';
     newWindow.location.href = newlocation  
 }   my $skip_confirm = 0;
    if ( $folder =~ /^supplemental/
        || ($url =~ m{( /smppg$
 function finishpick() {      |/syllabus$
     var title=this.document.forms.extimport.title.value;      |/aboutme$
     var url=this.document.forms.extimport.url.value;      |/navmaps$
     var form=this.document.forms.extimport.useform.value;      |/bulletinboard$
     eval      |\.html$
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+      |^/adm/wrapper/ext)}x)) {
     '";this.document.forms.'+form+'.submit();');      $skip_confirm = 1;
 }   }
   
 function changename(folderpath,index,oldtitle,container) {   if (!$nocopy) {
     var title=prompt('New Title',oldtitle);      $copylink=(<<ENDCOPY);
     if (title) {  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
  this.document.forms.renameform.title.value=title;  ENDCOPY
  this.document.forms.renameform.cmd.value='rename_'+index;          }
         if (container == 'sequence') {   if (!$nocut) {
     this.document.forms.renameform.folderpath.value=folderpath;      $cutlink=(<<ENDCUT);
         }  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
         if (container == 'page') {  ENDCUT
             this.document.forms.renameform.pagepath.value=folderpath;          }
         }   $form_start = (<<END);
         this.document.forms.renameform.submit();     <form  action="/adm/coursedocs" method="post">
     }     <input type="hidden" name="${type}path" value="$path" />
 }     <input type="hidden" name="${type}symb" value="$symb" />
      <input type="hidden" name="setparms" value="$orderidx" />
 function removeres(folderpath,index,oldtitle,container) {     <input type="hidden" name="changeparms" value="0" />
     if (confirm('Remove "'+oldtitle+'"?')) {  END
  this.document.forms.renameform.cmd.value='del_'+index;          $form_end = '</form>';
         if (container == 'sequence') {   $line.=(<<END);
             this.document.forms.renameform.folderpath.value=folderpath;  <td>
         }     <table class="LC_docs_entry_move">
         if (container == 'page') {        <tr>
             this.document.forms.renameform.pagepath.value=folderpath;           <td>
         }              <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" /></a>
         this.document.forms.renameform.submit();           </td>
     }        </tr>
 }        <tr>
           <td>
 </script>             <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>
           </td>
 ENDNEWSCRIPT        </tr>
   }      </table>
 # -------------------------------------------------------------------- Body tag  </td>
   $r->print('</head>'.  <td>
             &Apache::loncommon::bodytag('Course Documents','',$events,     $form_start
  '','',$showdoc).     $selectbox
     &Apache::loncommon::help_open_menu('','','','',273,'RAT'));     $form_end
   unless ($showdoc) {  </td>
 # -----------------------------------------------------------------------------  <td class="LC_docs_entry_commands">
        my %lt=&Apache::lonlocal::texthash(     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
                 'uplm' => 'Upload a new main course document',  $cutlink
                 'upls' => 'Upload a new supplemental course document',     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
                 'impp' => 'Import a published document',  $copylink
                 'spec' => 'Special documents',  </td>
                 'upld' => 'Upload Document',  END
                 'srch' => 'Search',  
                 'impo' => 'Import',      }
                 'selm' => 'Select Map',  # Figure out what kind of a resource this is
                 'load' => 'Load Map',      my ($extension)=($url=~/\.(\w+)$/);
                 'newf' => 'New Folder',      my $uploaded=($url=~/^\/*uploaded\//);
                 'newp' => 'New Composite Page',      my $icon=&Apache::loncommon::icon($url);
                 'extr' => 'External Resource',      my $isfolder=0;
                 'syll' => 'Syllabus',      my $ispage=0;
                 'navc' => 'Navigate Contents',      my $folderarg;
                 'sipa' => 'Simple Page',      my $pagearg;
                 'sipr' => 'Simple Problem',      my $pagefile;
                 'scuf' => 'Score Upload Form',      if ($uploaded) {
                 'bull' => 'Bulletin Board',   if ($extension eq 'sequence') {
                 'mypi' => 'My Personal Info',      $icon=$iconpath.'/folder_closed.gif';
  'abou' => 'About User',      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
                 'imsf' => 'Import IMS package',      $url='/adm/coursedocs?';
                 'file' =>  'File',      $folderarg=$1;
                 'title' => 'Title',      $isfolder=1;
                 'comment' => 'Comment'           } elsif ($extension eq 'page') {
   );              $icon=$iconpath.'/page.gif';
 # -----------------------------------------------------------------------------              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
     if ($allowed) {              $pagearg=$1;
        my $dumpbut=&dumpbutton();              $url='/adm/coursedocs?';
        my $exportbut=&exportbutton();              $ispage=1;
        my %lt=&Apache::lonlocal::texthash(   } else {
  'vc' => 'Verify Content',      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
  'cv' => 'Check/Set Resource Versions',   }
   );      }
      
        my $folderpath=$ENV{'form.folderpath'};      my $orig_url = $url;
        if (!$folderpath) {      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
    if ($ENV{'form.folder'} eq '' ||      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
        $ENV{'form.folder'} eq 'supplemental') {   my $symb=&Apache::lonnet::symbclean(
        $folderpath='default&'.            &Apache::lonnet::declutter('uploaded/'.
    &Apache::lonnet::escape(&mt('Main Course Documents'));             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
    }             $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
        }             '.sequence').
        unless ($ENV{'form.pagepath'}) {             '___'.$residx.'___'.
            $containertag = '<input type="hidden" name="folderpath" value="" />';     &Apache::lonnet::declutter($url));
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
        }   $url=&Apache::lonnet::clutter($url);
    if ($url=~/^\/*uploaded\//) {
        $r->print(<<ENDCOURSEVERIFY);      $url=~/\.(\w+)$/;
 <form name="renameform" method="post" action="/adm/coursedocs">      my $embstyle=&Apache::loncommon::fileembstyle($1);
 <input type="hidden" name="title" />      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
 <input type="hidden" name="cmd" />   $url='/adm/wrapper'.$url;
 $containertag      } elsif ($embstyle eq 'ssi') {
 </form>   #do nothing with these
 <form name="simpleedit" method="post" action="/adm/coursedocs">      } elsif ($url!~/\.(sequence|page)$/) {
 <input type=hidden name="importdetail" value="">   $url='/adm/coursedocs/showdoc'.$url;
 $uploadtag      }
 </form>   } elsif ($url=~m|^/ext/|) {
 <form action="/adm/coursedocs" method="post" name="courseverify">      $url='/adm/wrapper'.$url;
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">      $external = 1;
 <tr><td bgcolor="#DDDDCC">   }
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}          if (&Apache::lonnet::symbverify($symb,$url)) {
 </td><td bgcolor="#DDDDCC">      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}          } else {
 $dumpbut              $url='';
 $exportbut          }
 </td></tr></table>   if ($container eq 'page') {
 </form>      my $symb=$env{'form.pagesymb'};
 ENDCOURSEVERIFY          
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
      &mt('Editing the Table of Contents for your Course')));      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
     }   }
 # --------------------------------------------------------- Standard documents      }
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
     if (($standard) && ($allowed) && (!$forcesupplement)) {      if ($isfolder || $extension eq 'sequence') {
  $r->print('<tr><td bgcolor="#BBBBBB">');   my $foldername=&escape($foldertitle);
 #  '<h2>'.&mt('Main Course Documents').   my $folderpath=$env{'form.folderpath'};
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');   if ($folderpath) { $folderpath.='&' };
        my $folder=$ENV{'form.folder'};  # Append randompick number, hidden, and encrypted with ":" to foldername,
        if ($folder eq '' || $folder eq 'supplemental') {  # so it gets transferred between levels
            $folder='default';   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
    $ENV{'form.folderpath'}='default&'.&Apache::lonnet::escape(&mt('Main Course Documents'));                                                'parameter_randompick'))[0]
        }                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
        my $postexec='';                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
        if ($folder eq 'default') {                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
    $r->print('<script>this.window.name="loncapaclient";</script>');                                                'parameter_encrypturl'))[0]=~/^yes$/i)
        } else {                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
            #$postexec='self.close();';                                                'parameter_randomorder'))[0]=~/^yes$/i);
        }   $url.='folderpath='.&escape($folderpath).$cpinfo;
        $hadchanges=0;   $parameterset='<label>'.&mt('Randomly Pick: ').
        &editor($r,$coursenum,$coursedom,$folder,$allowed);      '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
        if ($hadchanges) {      (&LONCAPA::map::getparameter($orderidx,
    &mark_hash_old()                                                'parameter_randompick'))[0].
        }                                                '" />'.
        &changewarning($r,$postexec);  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      my $ro_set=
                      '.sequence';      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   $rand_order_text ='
                      '.page';  <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>';  
       }
        $r->print(<<ENDFORM);      if ($ispage) {
 <table cellspacing=4 cellpadding=4><tr>          my $pagename=&escape($pagetitle);
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>          my $pagepath;
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>          my $folderpath=$env{'form.folderpath'};
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>          if ($folderpath) { $pagepath = $folderpath.'&' };
 </tr>          $pagepath.=$pagearg.'&'.$pagename;
 <tr><td bgcolor="#DDDDDD">   my $symb=$env{'form.pagesymb'};
 $lt{'file'}:<br />   if (!$symb) {
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      my $path='uploaded/'.
 <input type="file" name="uploaddoc" size="40">   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
 <br />   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
 $lt{'title'}:<br />      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
 <input type="text" size="50" name="comment">         $residx,
 $uploadtag         $path.$pagearg.'.page');
 <input type="hidden" name="cmd" value="upload_default">   }
 <nobr>   $url.='pagepath='.&escape($pagepath).
 <input type="submit" value="$lt{'upld'}">      '&amp;pagesymb='.&escape($symb).$cpinfo;
  $help{'Uploading_From_Harddrive'}      }
 </nobr>      if ($external) {
 </form>   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
 </td>   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
 <td bgcolor="#DDDDDD">      } else {
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   undef($external);
 $uploadtag      }
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}">      $line.='
 <nobr>    <td class="LC_docs_entry_icon">
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}">      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
 $help{'Importing_LON-CAPA_Resource'}    </td>
 </nobr>    <td class="LC_docs_entry_title">
 <p>      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
 <hr />    </td>";
 <input type="text" size="20" name="importmap"><br />      if (($allowed) && ($folder!~/^supplemental/)) {
 <nobr><input type=button     my %lt=&Apache::lonlocal::texthash(
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"         'hd' => 'Hidden',
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">         'ec' => 'URL hidden');
 $help{'Load_Map'}</nobr>   my $enctext=
 </p>      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
 </form>   my $hidtext=
 </td>      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
 <td bgcolor="#DDDDDD">   $line.=(<<ENDPARMS);
 ENDFORM    <td class="LC_docs_entry_parameter">
        unless ($ENV{'form.pagepath'}) {      $form_start
            $r->print(<<ENDFORM);      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
 <form action="/adm/coursedocs" method="post" name="newfolder">      $form_end
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />    </td>
 <input type=hidden name="importdetail" value="">    <td class="LC_docs_entry_parameter">
 <nobr>      $form_start
 <input name="newfolder" type="button"      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
 onClick="javascript:makenewfolder(this.form,'$folderseq');"      $form_end
 value="$lt{'newf'}" />$help{'Adding_Folders'}    </td>
 </nobr>    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
 </form>    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
 <form action="/adm/coursedocs" method="post" name="newpage">  ENDPARMS
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />      }
 <input type=hidden name="importdetail" value="">      $line.="</tr>";
 <nobr>      return $line;
 <input name="newpage" type="button"  }
 onClick="javascript:makenewpage(this.form,'$pageseq');"  
 value="$lt{'newp'}" />$help{'Adding_Pages'}  =pod
 </nobr>  
 </form>  =item tiehash()
 <form action="/adm/coursedocs" method="post" name="newext">  
 $uploadtag  tie the hash
 <input type=hidden name="importdetail" value="">  
 <nobr>  =cut
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"  
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  sub tiehash {
 </nobr>      my ($mode)=@_;
 </form>      $hashtied=0;
 <form action="/adm/coursedocs" method="post" name="newsyl">      if ($env{'request.course.fn'}) {
 $uploadtag   if ($mode eq 'write') {
 <input type=hidden name="importdetail"       if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">      &GDBM_WRCREAT(),0640)) {
 <nobr>                  $hashtied=2;
 <input name="newsyl" type="submit" value="$lt{'syll'}" />       }
  $help{'Syllabus'}   } else {
 </nobr>      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
 </form>      &GDBM_READER(),0640)) {
 <form action="/adm/coursedocs" method="post" name="newnav">                  $hashtied=1;
 $uploadtag      }
 <input type=hidden name="importdetail"    }
 value="Navigate Content=/adm/navmaps">      }    
 <nobr>  }
 <input name="newnav" type="submit" value="$lt{'navc'}" />  
 $help{'Navigate_Content'}  sub untiehash {
 </nobr>      if ($hashtied) { untie %hash; }
 </form>      $hashtied=0;
 <form action="/adm/coursedocs" method="post" name="newsmppg">      return OK;
 $uploadtag  }
 <input type=hidden name="importdetail" value="">  
 <nobr>  
 <input name="newsmppg" type="button" value="$lt{'sipa'}"  
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}  
 </nobr>  sub checkonthis {
 </form>      my ($r,$url,$level,$title)=@_;
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">      $url=&unescape($url);
 $uploadtag      $alreadyseen{$url}=1;
 <input type=hidden name="importdetail" value="">      $r->rflush();
 <nobr>      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"         $r->print("\n<br />");
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}         if ($level==0) {
 </nobr>             $r->print("<br />");
 </form>         }
 <form action="/adm/coursedocs" method="post" name="newexamupload">         for (my $i=0;$i<=$level*5;$i++) {
 $uploadtag             $r->print('&nbsp;');
 <input type=hidden name="importdetail" value="">         }
 <nobr>         $r->print('<a href="'.$url.'" target="cat">'.
 <input name="newexamupload" type="button" value="$lt{'scuf'}"   ($title?$title:$url).'</a> ');
 onClick="javascript:makeexamupload();" />         if ($url=~/^\/res\//) {
 $help{'Score_Upload_Form'}    my $result=&Apache::lonnet::repcopy(
 </nobr>                                &Apache::lonnet::filelocation('',$url));
 </form>            if ($result eq 'ok') {
 <form action="/adm/coursedocs" method="post" name="newbul">               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 $uploadtag               $r->rflush();
 <input type=hidden name="importdetail" value="">               &Apache::lonnet::countacc($url);
 <nobr>               $url=~/\.(\w+)$/;
 <input name="newbulletin" type="button" value="$lt{'bull'}"               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 onClick="javascript:makebulboard();" />   $r->print('<br />');
 $help{'Bulletin Board'}                   $r->rflush();
 </nobr>                   for (my $i=0;$i<=$level*5;$i++) {
 </form>                       $r->print('&nbsp;');
 <form action="/adm/coursedocs" method="post" name="newaboutme">                   }
 $uploadtag                   $r->print('- '.&mt('Rendering:').' ');
 <input type=hidden name="importdetail"    my ($errorcount,$warningcount)=split(/:/,
 value="$plainname=/adm/$udom/$uname/aboutme">         &Apache::lonnet::ssi_body($url,
 <nobr>         ('grade_target'=>'web',
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />   'return_only_error_and_warning_counts' => 1)));
 $help{'My Personal Info'}                   if (($errorcount) ||
 </nobr>                       ($warningcount)) {
 </form>       if ($errorcount) {
 <form action="/adm/coursedocs" method="post" name="newaboutsomeone">                          $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
 $uploadtag                            &mt('[quant,_1,error]',$errorcount).'</span>');
 <input type=hidden name="importdetail" value="">                       }
 <nobr>       if ($warningcount) {
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"                           $r->print('<span class="LC_warning">'.
 onClick="javascript:makeabout();" />                            &mt('[quant,_1,warning]',$warningcount).'</span>');
 </nobr>                       }
 ENDFORM                   } else {
        }                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
        if ($ENV{'form.pagepath'}) {                   }
            $r->print(<<ENDBLOCK);                   $r->rflush();
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">               }
 $uploadtag       my $dependencies=
 <input type=hidden name="importdetail" value="">                  &Apache::lonnet::metadata($url,'dependencies');
 <nobr>               foreach my $dep (split(/\,/,$dependencies)) {
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}                      &checkonthis($r,$dep,$level+1);
 </nobr>                   }
 </form>               }
 <form action="/adm/coursedocs" method="post" name="newexamupload">            } elsif ($result eq 'unavailable') {
 $uploadtag               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
 <input type=hidden name="importdetail" value="">            } elsif ($result eq 'not_found') {
 <nobr>        unless ($url=~/\$/) {
 <input name="newexamupload" type="button" value="$lt{'scuf'}"    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
 onClick="javascript:makeexamupload();" />        } else {
 $help{'Score_Upload_Form'}    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
 </nobr>        }
 </form>            } else {
 ENDBLOCK               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
        } else {            }
            $r->print(<<ENDFORM);         }
 </form>      }
 <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();" />  
 </nobr>  
 </form>  =pod
 ENDFORM  
        }  =item list_symbs()
        $r->print('</td></tr>'."\n".  
 '</table>');  List Symbs
        $r->print('</td></tr>');  
     }  =cut
 # ----------------------------------------------------- Supplemental documents  
     if (!$forcestandard) {  sub list_symbs {
        $r->print('<tr><td bgcolor="#BBBBBB">');      my ($r) = @_;
 # '<h2>'.&mt('Supplemental Course Documents').  
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');      my $type = &Apache::loncommon::course_type();
        my $folder=$ENV{'form.folder'};      $r->print(&Apache::loncommon::start_page('Symb List'));
        unless ($folder=~/^supplemental/) {      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
    $folder='supplemental';      my $navmap = Apache::lonnavmaps::navmap->new();
        }      if (!defined($navmap)) {
        if ($folder =~ /^supplemental$/ &&          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
    $ENV{'form.folderpath'} =~ /^default\&/) {                    '<div class="LC_error">'.
    $ENV{'form.folderpath'}='supplemental&'.                    &mt('Unable to retrieve information about course contents').
        &Apache::lonnet::escape(&mt('Supplemental Course Documents'));                    '</div>');
        }          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
        &editor($r,$coursenum,$coursedom,$folder,$allowed);      } else {
        if ($allowed) {          $r->print("<pre>\n");
        my $folderseq=          foreach my $res ($navmap->retrieveResources()) {
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.      $r->print($res->compTitle()."\t".$res->symb()."\n");
                      '.sequence';          }
           $r->print("\n</pre>\n");
           $r->print(<<ENDSUPFORM);      }
 <table cellspacing=4 cellpadding=4><tr>      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>  }
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>  
 </tr>  
 <tr><td bgcolor="#DDDDDD">  sub verifycontent {
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">      my ($r) = @_;
 <input type="file" name="uploaddoc" size="40">      my $type = &Apache::loncommon::course_type();
 <br />$lt{'comment'}:<br />     my $loaderror=&Apache::lonnet::overloaderror($r);
 <textarea cols=50 rows=4 name='comment'>     if ($loaderror) { return $loaderror; }
 </textarea>     $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
 <br />     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />     $hashtied=0;
 <input type="hidden" name="cmd" value="upload_supplemental">     undef %alreadyseen;
 <nobr>     %alreadyseen=();
 <input type="submit" value="$lt{'upld'}">     &tiehash();
  $help{'Uploading_From_Harddrive'}     foreach my $key (keys(%hash)) {
 </nobr>         if ($hash{$key}=~/\.(page|sequence)$/) {
 </form>     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 </td>         $r->print('<hr /><span class="LC_error">'.
 <td bgcolor="#DDDDDD">   &mt('The following sequence or page is included more than once in your '.$type.': ').
 <form action="/adm/coursedocs" method="post" name="supnewfolder">   &unescape($hash{$key}).'</span><br />'.
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
 <input type=hidden name="importdetail" value="">     }
 <nobr>         }
 <input name="newfolder" type="button"         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
 onClick="javascript:makenewfolder(this.form,'$folderseq');"             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
 value="$lt{'newf'}" /> $help{'Adding_Folders'}         }
 </nobr>     }
 </form>     &untiehash();
 <form action="/adm/coursedocs" method="post" name="supnewext">     $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />       &mt('Return to DOCS').'</a>');
 <input type=hidden name="importdetail" value="">  }
 <nobr>  
 <input name="newext" type="button"   
 onClick="javascript:makenewext('supnewext');"  sub devalidateversioncache {
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      my $src=shift;
 </nobr>      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
 </form>    &Apache::lonnet::clutter($src));
 <form action="/adm/coursedocs" method="post" name="supnewsyl">  }
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />  
 <input type=hidden name="importdetail"   sub checkversions {
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">      my ($r) = @_;
 <nobr>      my $type = &Apache::loncommon::course_type();
 <input name="newsyl" type="submit" value="$lt{'syll'}" />      $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
 $help{'Syllabus'}      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
 </nobr>      my $header='';
 </form>      my $startsel='';
 <form action="/adm/coursedocs" method="post" name="subnewaboutme">      my $monthsel='';
 <input type="hidden" name="folderpath" value="$ENV{'form.folderpath'}" />      my $weeksel='';
 <input type=hidden name="importdetail"       my $daysel='';
 value="$plainname=/adm/$udom/$uname/aboutme">      my $allsel='';
 <nobr>      my %changes=();
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />      my $starttime=0;
 $help{'My Personal Info'}      my $haschanged=0;
 </nobr>      my %setversions=&Apache::lonnet::dump('resourceversions',
 </form>    $env{'course.'.$env{'request.course.id'}.'.domain'},
 </td></tr>    $env{'course.'.$env{'request.course.id'}.'.num'});
 </table></td></tr>  
 ENDSUPFORM      $hashtied=0;
        }      &tiehash();
     }      my %newsetversions=();
     if ($allowed) {      if ($env{'form.setmostrecent'}) {
  $r->print('<form name="extimport"><input type="hidden" name="title"><input type="hidden" name="url"><input type="hidden" name="useform"></form>');   $haschanged=1;
     }   foreach my $key (keys(%hash)) {
     $r->print('</table>');      if ($key=~/^ids\_(\/res\/.+)$/) {
   } else {   $newsetversions{$1}='mostrecent';
 # -------------------------------------------------------- This is showdoc mode                  &devalidateversioncache($1);
       $r->print("<h1>".&mt('Uploaded Document').' - '.      }
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.   }
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".      } elsif ($env{'form.setcurrent'}) {
          &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');   $haschanged=1;
   }   foreach my $key (keys(%hash)) {
  }      if ($key=~/^ids\_(\/res\/.+)$/) {
  $r->print('</body></html>');   my $getvers=&Apache::lonnet::getversion($1);
  return OK;   if ($getvers>0) {
 }       $newsetversions{$1}=$getvers;
       &devalidateversioncache($1);
 1;   }
 __END__      }
    }
       } elsif ($env{'form.setversions'}) {
    $haschanged=1;
    foreach my $key (keys(%env)) {
       if ($key=~/^form\.set_version_(.+)$/) {
    my $src=$1;
    if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
       $newsetversions{$src}=$env{$key};
       &devalidateversioncache($src);
    }
       }
    }
       }
       if ($haschanged) {
           if (&Apache::lonnet::put('resourceversions',\%newsetversions,
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
       $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
    } else {
       $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
    }
    &mark_hash_old();
       }
       &changewarning($r,'');
       if ($env{'form.timerange'} eq 'all') {
   # show all documents
    $header=&mt('All Documents in '.$type);
    $allsel=1;
    foreach my $key (keys(%hash)) {
       if ($key=~/^ids\_(\/res\/.+)$/) {
    my $src=$1;
    $changes{$src}=1;
       }
    }
       } else {
   # show documents which changed
    %changes=&Apache::lonnet::dump
    ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
                        $env{'course.'.$env{'request.course.id'}.'.num'});
    my $firstkey=(keys(%changes))[0];
    unless ($firstkey=~/^error\:/) {
       unless ($env{'form.timerange'}) {
    $env{'form.timerange'}=604800;
       }
       my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
    .&mt('seconds');
       if ($env{'form.timerange'}==-1) {
    $seltext='since start of course';
    $startsel='selected';
    $env{'form.timerange'}=time;
       }
       $starttime=time-$env{'form.timerange'};
       if ($env{'form.timerange'}==2592000) {
    $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $monthsel='selected';
       } elsif ($env{'form.timerange'}==604800) {
    $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $weeksel='selected';
       } elsif ($env{'form.timerange'}==86400) {
    $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
    $daysel='selected';
       }
       $header=&mt('Content changed').' '.$seltext;
    } else {
       $header=&mt('No content modifications yet.');
    }
       }
       %setversions=&Apache::lonnet::dump('resourceversions',
     $env{'course.'.$env{'request.course.id'}.'.domain'},
     $env{'course.'.$env{'request.course.id'}.'.num'});
       my %lt=&Apache::lonlocal::texthash
         ('st' => 'Version changes since start of '.$type,
          'lm' => 'Version changes since last Month',
          'lw' => 'Version changes since last Week',
          'sy' => 'Version changes since Yesterday',
                  'al' => 'All Resources (possibly large output)',
          'sd' => 'Display',
          'fi' => 'File',
          'md' => 'Modification Date',
                  'mr' => 'Most recently published Version',
          've' => 'Version used in '.$type,
                  'vu' => 'Set Version to be used in '.$type,
   'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
   'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
   'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
          'di' => 'Differences');
       $r->print(<<ENDHEADERS);
   <form action="/adm/coursedocs" method="post">
   <input type="hidden" name="versions" value="1" />
   <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
   <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
   <select name="timerange">
   <option value='all' $allsel>$lt{'al'}</option>
   <option value="-1" $startsel>$lt{'st'}</option>
   <option value="2592000" $monthsel>$lt{'lm'}</option>
   <option value="604800" $weeksel>$lt{'lw'}</option>
   <option value="86400" $daysel>$lt{'sy'}</option>
   </select>
   <input type="submit" name="display" value="$lt{'sd'}" />
   <h3>$header</h3>
   <input type="submit" name="setversions" value="$lt{'sv'}" />
   <table border="0">
   ENDHEADERS
       foreach my $key (sort(keys(%changes))) {
    if ($changes{$key}>$starttime) {
       my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
       my $currentversion=&Apache::lonnet::getversion($key);
       if ($currentversion<0) {
    $currentversion=&mt('Could not be determined.');
       }
       my $linkurl=&Apache::lonnet::clutter($key);
       $r->print(
         '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
         &Apache::lonnet::gettitle($linkurl).
                         '</b></font></td></tr>'.
                         '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
                         '<td colspan="4">'.
                         '<a href="'.$linkurl.'" target="cat">'.$linkurl.
         '</a></td></tr>'.
                         '<tr><td></td>'.
                         '<td title="'.$lt{'md'}.'">'.
         &Apache::lonlocal::locallocaltime(
                              &Apache::lonnet::metadata($root.'.'.$extension,
                                                        'lastrevisiondate')
                                                           ).
                         '</td>'.
                         '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
                         '<font size="+1">'.$currentversion.'</font>'.
                         '</span></td>'.
                         '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
                         '<font size="+1">');
   # Used in course
       my $usedversion=$hash{'version_'.$linkurl};
       if (($usedversion) && ($usedversion ne 'mostrecent')) {
    $r->print($usedversion);
       } else {
    $r->print($currentversion);
       }
       $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
                         '<span class="LC_nobreak">Use: ');
   # Set version
       $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
         'set_version_'.$linkurl,
         ('select_form_order' =>
          ['',1..$currentversion,'mostrecent'],
          '' => '',
          'mostrecent' => 'most recent',
          map {$_,$_} (1..$currentversion))));
       $r->print('</span></td></tr><tr><td></td>');
       my $lastold=1;
       for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
    my $url=$root.'.'.$prevvers.'.'.$extension;
    if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
       $starttime) {
       $lastold=$prevvers;
    }
       }
               #
               # Code to figure out how many version entries should go in
               # each of the four columns
               my $entries_per_col = 0;
               my $num_entries = ($currentversion-$lastold);
               if ($num_entries % 4 == 0) {
                   $entries_per_col = $num_entries/4;
               } else {
                   $entries_per_col = $num_entries/4 + 1;
               }
               my $entries_count = 0;
               $r->print('<td valign="top"><font size="-2">');
               my $cols_output = 1;
               for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
    my $url=$root.'.'.$prevvers.'.'.$extension;
    $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
     '">'.&mt('Version').' '.$prevvers.'</a> ('.
     &Apache::lonlocal::locallocaltime(
                                   &Apache::lonnet::metadata($url,
                                                             'lastrevisiondate')
                                                               ).
     ')');
    if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
                       $r->print(' <a href="/adm/diff?filename='.
         &Apache::lonnet::clutter($root.'.'.$extension).
         '&versionone='.$prevvers.
         '">'.&mt('Diffs').'</a>');
    }
    $r->print('</span><br />');
                   if (++$entries_count % $entries_per_col == 0) {
                       $r->print('</font></td>');
                       if ($cols_output != 4) {
                           $r->print('<td valign="top"><font size="-2">');
                           $cols_output++;
                       }
                   }
       }
               while($cols_output++ < 4) {
                   $r->print('</font></td><td><font>')
               }
       $r->print('</font></td></tr>'."\n");
    }
       }
       $r->print('</table></form>');
       $r->print('<h1>'.&mt('Done').'.</h1>');
   
       &untiehash();
   }
   
   sub mark_hash_old {
       my $retie_hash=0;
       if ($hashtied) {
    $retie_hash=1;
    &untiehash();
       }
       &tiehash('write');
       $hash{'old'}=1;
       &untiehash();
       if ($retie_hash) { &tiehash(); }
   }
   
   sub is_hash_old {
       my $untie_hash=0;
       if (!$hashtied) {
    $untie_hash=1;
    &tiehash();
       }
       my $return=$hash{'old'};
       if ($untie_hash) { &untiehash(); }
       return $return;
   }
   
   sub changewarning {
       my ($r,$postexec,$message,$url)=@_;
       if (!&is_hash_old()) { return; }
       my $pathvar='folderpath';
       my $path=&escape($env{'form.folderpath'});
       if (!defined($url)) {
    if (defined($env{'form.pagepath'})) {
       $pathvar='pagepath';
       $path=&escape($env{'form.pagepath'});
       $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
    }
    $url='/adm/coursedocs?'.$pathvar.'='.$path;
       }
       my $course_type = &Apache::loncommon::course_type();
       if (!defined($message)) {
    $message='Changes will become active for your current session after [_1], or the next time you log in.';
       }
       $r->print("\n\n".
   '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
   '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
   '<input type="hidden" name="orgurl" value="'.$url.
   '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
   &mt($message,' <input type="hidden" name="'.
       $env{'request.role'}.'" value="1" /><input type="button" value="'.
       &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
   $help{'Caching'}.'</span></h3></form>'."\n\n");
   }
   
   
   sub init_breadcrumbs {
       my ($form,$text)=@_;
       &Apache::lonhtmlcommon::clear_breadcrumbs();
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
       text=>"Edit ".&Apache::loncommon::course_type(),
       faq=>273,
       bug=>'Instructor Interface',
                                               help => 'Docs_Adding_Course_Doc'});
       &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
       text=>$text,
       faq=>273,
       bug=>'Instructor Interface'});
   }
   
   
   
   
   sub handler {
       my $r = shift;
       &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
       return OK if $r->header_only;
       my $type = &Apache::loncommon::course_type();
   
   
   # --------------------------------------------- Initialize help topics for this
       foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
                  'Adding_External_Resource','Navigate_Content',
                  'Adding_Folders','Docs_Overview', 'Load_Map',
                  'Supplemental','Score_Upload_Form','Adding_Pages',
                  'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
                  'Check_Resource_Versions','Verify_Content') {
    $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
       }
       # Composite help files
       $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
       $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
       $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
       'Option_Response_Simple');
       $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
       $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
     'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
       $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
       $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
   
   # does this user have privileges to modify docs
       my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
     if ($allowed && $env{'form.verify'}) {
         &init_breadcrumbs('verify','Verify Content');
         &verifycontent($r);
     } elsif ($allowed && $env{'form.listsymbs'}) {
         &init_breadcrumbs('listsymbs','List Symbs');
         &list_symbs($r);
     } elsif ($allowed && $env{'form.docslog'}) {
         &init_breadcrumbs('docslog','Show Log');
         &docs_change_log($r);
     } elsif ($allowed && $env{'form.versions'}) {
         &init_breadcrumbs('versions','Check/Set Resource Versions');
         &checkversions($r);
     } elsif ($allowed && $env{'form.dumpcourse'}) {
         &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
         &dumpcourse($r);
     } elsif ($allowed && $env{'form.exportcourse'}) {
         &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
         &exportcourse($r);
     } else {
   # is this a standard course?
   
       my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
       my $forcestandard = 0;
       my $forcesupplement;
       my $script='';
       my $showdoc=0;
       my $containertag;
       my $uploadtag;
   
   
       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
       ['folderpath','pagepath',
        'pagesymb']);
   # No folderpath, no pagepath, see if we have something stored
       if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
           &Apache::loncommon::restore_course_settings('docs_folderpath',
                                                 {'folderpath' => 'scalar'});
       }
       if (!$env{'form.folderpath'}) {
           &Apache::loncommon::restore_course_settings('docs_folderpath',
                                                 {'pagepath' => 'scalar'});
       }
       if ($env{'form.pagepath'}) {
          $env{'form.folderpath'}='';
       }
       if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
           $env{'form.folderpath'} = 'supplemental&'.
                                     &escape(&mt('Supplemental '.$type.' Documents')).'&'.
                                     $env{'form.folderpath'};
       }
       &Apache::loncommon::store_course_settings('docs_folderpath',
                                                   {'pagepath' => 'scalar',
                                                    'folderpath' => 'scalar'});
       if ($env{'form.folderpath'}) {
    my (@folderpath)=split('&',$env{'form.folderpath'});
    $env{'form.foldername'}=&unescape(pop(@folderpath));
    $env{'form.folder'}=pop(@folderpath);
       }
       if ($env{'form.pagepath'}) {
           my (@pagepath)=split('&',$env{'form.pagepath'});
           $env{'form.pagename'}=&unescape(pop(@pagepath));
           $env{'form.folder'}=pop(@pagepath);
           $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'},'<>&"').'" />';
       }
       if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
          $showdoc='/'.$1;
       }
       unless ($showdoc) { # got called from remote
          if (($env{'form.folder'}=~/^(?:group|default)_/) ||
             ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
              $forcestandard = 1;
          }
          $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
   
          if ($allowed) {
            &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
            $script=&Apache::lonratedt::editscript('simple');
          }
       } else { # got called in sequence from course
          $allowed=0;
       }
   
   # get course data
       my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
       my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
   
   # get personal data
       my $uname=$env{'user.name'};
       my $udom=$env{'user.domain'};
       my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
   
   # graphics settings
   
       $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
   
       if ($allowed) {
    $script .= &editing_js($udom,$uname);
       }
   # -------------------------------------------------------------------- Body tag
       $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
       my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
       $r->print(&Apache::loncommon::start_page("$type Documents", $script,
       {'force_register' => $showdoc,
                                        'bread_crumbs' => $brcrum}).
         &Apache::loncommon::help_open_menu('','',273,'RAT'));
    
     my %allfiles = ();
     my %codebase = ();
     my ($upload_result,$upload_output);
     if ($allowed) {
         if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
   # Process file upload - phase one - upload and parse primary file.  
     undef($hadchanges);
             $upload_result = &process_file_upload(\$upload_output,$coursenum,
    $coursedom,\%allfiles,
    \%codebase,$1);
     if ($hadchanges) {
         &mark_hash_old();
     }
             if ($upload_result eq 'phasetwo') {
                 $r->print($upload_output);
             }
         } elsif ($env{'form.phasetwo'}) {
             my %newname = ();
             my %origname = ();
             my %attribs = ();
             my $updateflag = 0;
             my $residx = $env{'form.newidx'};
             my $primary_url = &unescape($env{'form.primaryurl'});
   # Process file upload - phase two - gather secondary files.
             for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
                 if ($env{'form.embedded_item_'.$i.'.filename'}) {
                     my $javacodebase;
                     $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
                     $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
                     if (exists($env{'form.embedded_codebase_'.$i})) {
                         $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
                         $origname{$i} =~ s#^\Q$javacodebase\E/##;
                     }
                     my @attributes = ();
                     if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
                         @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
                     } else {
                         @attributes = ($env{'form.embedded_attrib_'.$i});
                     }
                     foreach my $attr (@attributes) {
                         push(@{$attribs{$i}},&unescape($attr));
                     }
                     if ($javacodebase) {
                         $codebase{$i} = $javacodebase;
                         $codebase{$i} =~ s#/$##;
                         $updateflag = 1;
                     }
                 }
                 unless ($newname{$i} eq $origname{$i}) {
                     $updateflag = 1;
                 }
             }
   # Process file upload - phase three - modify primary file
             if ($updateflag) {
                 my ($content,$rtncode);
                 my $updateflag = 0;
                 my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
                 if ($getstatus eq 'ok') {
                     foreach my $item (keys(%newname)) {
                         if ($newname{$item} ne $origname{$item}) {
                             my $attrib_regexp = '';
                             if (@{$attribs{$item}} > 1) {
                                 $attrib_regexp = join('|',@{$attribs{$item}});
                             } else {
                                 $attrib_regexp = $attribs{$item}[0];
                             }
                             if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
                             }
                             $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
                         }
                         if (exists($codebase{$item})) {
                             $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
                         }
                     }
   # Save edited file.
                     my $saveresult;
                     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                     my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
                 } else {
                     &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
                 }
             }
         }
     }
   
     unless ($showdoc ||  $upload_result eq 'phasetwo') {
   # -----------------------------------------------------------------------------
          my %lt=&Apache::lonlocal::texthash(
                   'uplm' => 'Upload a new main '.lc($type).' document',
                   'upls' => 'Upload a new supplemental '.lc($type).' document',
                   'impp' => 'Import a document',
                   'pubd' => 'Published Documents',
    'copm' => 'All documents out of a published map into this folder',
                   'upld' => 'Upload Document',
                   'srch' => 'Search',
                   'impo' => 'Import',
    'book' => 'Import Bookmarks',
                   'selm' => 'Select Map',
                   'load' => 'Load Map',
                   'reco' => 'Recover Deleted Resources',
                   'newf' => 'New Folder',
                   'newp' => 'New Composite Page',
                   'extr' => 'External Resource',
                   'syll' => 'Syllabus',
                   'navc' => 'Navigate Contents',
                   'sipa' => 'Simple Page',
                   'sipr' => 'Simple Problem',
                   'drbx' => 'Drop Box',
                   'scuf' => 'Score Upload Form',
                   'bull' => 'Bulletin Board',
                   'mypi' => 'My Personal Info',
                   'grpo' => 'Group Files',
                   'rost' => 'Course Roster',
    'abou' => 'About User',
                   'imsf' => 'Import IMS package',
                   'file' =>  'File',
                   'title' => 'Title',
                   'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file!',
    'nd' => 'New Document',
    'pm' => 'Published Map',
    'sd' => 'Special Document',
    'mo' => 'More Options',
    'hao' => 'Hide all Options'
     );
   # -----------------------------------------------------------------------------
    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 $fileuploadform=(<<FUFORM);
    <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
    $fileupload
    <br />
    $lt{'title'}:<br />
    <input type="text" size="50" name="comment" />
    $uploadtag
    <input type="hidden" name="cmd" value="upload_default" />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br />
    <br />
    <span class="LC_nobreak">
    <input type="submit" value="$lt{'upld'}" />
    $help{'Uploading_From_Harddrive'}
    </span>
    </form>
   FUFORM
   
    my $simpleeditdefaultform=(<<SEDFFORM);
    <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
    $lt{'pubd'}<br />
    $uploadtag
    <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
    <br />
    <span class="LC_nobreak">
    <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
    $help{'Importing_LON-CAPA_Resource'}
    </span>
    <br />
    <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
    <hr />
    <p>
    $lt{'copm'}<br />
    <input type="text" size="40" name="importmap" /><br />
    <span class="LC_nobreak"><input type="button"
    onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
    value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
    $help{'Load_Map'}</span>
    </p>
    </form>
   SEDFFORM
   
    my $extresourcesform=(<<ERFORM);
    <form action="/adm/coursedocs" method="post" name="newext">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button" onClick="javascript:makenewext('newext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   ERFORM
   
       if ($allowed) {
    &update_paste_buffer($coursenum,$coursedom);
          my $dumpbut=&dumpbutton();
          my $exportbut=&exportbutton();
          my %lt=&Apache::lonlocal::texthash(
    'vc' => 'Verify Content',
    'cv' => 'Check/Set Resource Versions',
    'ls' => 'List Symbs',
                                            'sl' => 'Show Log'
     );
   
          my $folderpath=$env{'form.folderpath'};
          if (!$folderpath) {
      if ($env{'form.folder'} eq '' ||
          $env{'form.folder'} eq 'supplemental') {
          $folderpath='default&'.
      &escape(&mt('Main '.$type.' Documents'));
      }
          }
          unless ($env{'form.pagepath'}) {
              $containertag = '<input type="hidden" name="folderpath" value="" />';
              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
          }
   
          $r->print(<<ENDCOURSEVERIFY);
   <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>
   <form name="simpleedit" method="post" action="/adm/coursedocs">
     <input type="hidden" name="importdetail" value="" />
     $uploadtag
   </form>
   <form action="/adm/coursedocs" method="post" name="courseverify">
     <div class="LC_docs_course_commands">
   
         <div>
           <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}
         </div>
         <div>
           <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}
         </div>
           $dumpbut
           $exportbut
         <div>
           <input type="submit" name="listsymbs" value="$lt{'ls'}" />
         </div>
         <div>
           <input type="hidden" name="folder" value="$env{'form.folder'}" />
           <input type="submit" name="docslog" value="$lt{'sl'}" />
         </div>
     </div>
   </form>
   <div style="clear: both; height: 0px;">&nbsp;</div>
   ENDCOURSEVERIFY
          $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',
        &mt('Editing the Table of Contents for your '.$type)));
       }
   # --------------------------------------------------------- Standard documents
       $r->print('<table class="LC_docs_documents">');
   
       if (($standard) && ($allowed) && (!$forcesupplement)) {
    $r->print('<tr><td class="LC_docs_document">');
   #  '<h2>'.&mt('Main Course Documents').
   #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');
          my $folder=$env{'form.folder'};
          if ($folder eq '' || $folder eq 'supplemental') {
              $folder='default';
      $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));
              $uploadtag = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
          }
          my $postexec='';
          if ($folder eq 'default') {
      $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');
          } else {
              #$postexec='self.close();';
          }
          $hadchanges=0;
          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,
      $upload_output,$type);
          if ($error) {
      $r->print('<p><span class="LC_error">'.$error.'</span></p>');
          }
          if ($hadchanges) {
      &mark_hash_old();
          }
          &changewarning($r,$postexec);
          my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                        '.sequence';
          my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
                        '.page';
    my $container='sequence';
    if ($env{'form.pagepath'}) {
       $container='page';
    }
    my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
   
   
   
    my $recoverform=(<<RFORM);
    <form action="/adm/groupsort" method="post" name="recover">
    <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />
    </form>
   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
   
    my $newnavform=(<<NNFORM);
    <form action="/adm/coursedocs" method="post" name="newnav">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'navc'}=/adm/navmaps" />
    <span class="LC_nobreak">
    <input name="newnav" type="submit" value="$lt{'navc'}" />
    $help{'Navigate_Content'}
    </span>
    </form>
   NNFORM
    my $newsmppageform=(<<NSPFORM);
    <form action="/adm/coursedocs" method="post" name="newsmppg">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newsmppg" type="button" value="$lt{'sipa'}"
    onClick="javascript:makesmppage();" /> $help{'Simple Page'}
    </span>
    </form>
   NSPFORM
   
    my $newsmpproblemform=(<<NSPROBFORM);
    <form action="/adm/coursedocs" method="post" name="newsmpproblem">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newsmpproblem" type="button" value="$lt{'sipr'}"
    onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}
    </span>
    </form>
   
   NSPROBFORM
   
    my $newdropboxform=(<<NDBFORM);
    <form action="/adm/coursedocs" method="post" name="newdropbox">
    $uploadtag      
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">          
    <input name="newdropbox" type="button" value="$lt{'drbx'}"
    onClick="javascript:makedropbox();" />
    </span>        
    </form>
   NDBFORM
   
    my $newexuploadform=(<<NEXUFORM);
    <form action="/adm/coursedocs" method="post" name="newexamupload">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newexamupload" type="button" value="$lt{'scuf'}"
    onClick="javascript:makeexamupload();" />
    $help{'Score_Upload_Form'}
    </span>
    </form>
   NEXUFORM
   
    my $newbulform=(<<NBFORM);
    <form action="/adm/coursedocs" method="post" name="newbul">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newbulletin" type="button" value="$lt{'bull'}"
    onClick="javascript:makebulboard();" />
    $help{'Bulletin Board'}
    </span>
    </form>
   NBFORM
   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
    <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
    $help{'My Personal Info'}
    </span>
    </form>
   NAMFORM
   
    my $newaboutsomeoneform=(<<NASOFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newaboutsomeone" type="button" value="$lt{'abou'}"
    onClick="javascript:makeabout();" />
    </span>
    </form>
   NASOFORM
   
   
    my $newrosterform=(<<NROSTFORM);
    <form action="/adm/coursedocs" method="post" name="newroster">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'rost'}=/adm/viewclasslist" />
    <span class="LC_nobreak">
    <input name="newroster" type="submit" value="$lt{'rost'}" />
    $help{'Course Roster'}
    </span>
    </form>
   NROSTFORM
   
          $r->print(<<ENDFORM);
   
   <ul class="LC_TabContent">
   <li>$lt{'nd'}</li>
   <li>$lt{'pm'}</li>
   <li>$lt{'pubd'}</li>
   <li>$lt{'sd'}</li>
   <li>$lt{'mo'}</li>
   <li>$lt{'hao'}</li>
   </ul>
   
   <table class="LC_docs_adddocs">
   <!-- <tr>
   <th>$lt{'uplm'}</th>
   <th>$lt{'impp'}</th>
   <th>$lt{'spec'}</th>
   </tr> -->
   <tr>
   <td>
   $fileuploadform
   </td>
   <td>
   $simpleeditdefaultform
   <hr />
   $recoverform
   ENDFORM
          unless ($env{'form.pagepath'}) {
      $r->print(<<ENDFORM);
   <hr />
   $extresourcesform
    <br />
   $imspform
   ENDFORM
          }
          $r->print('</td><td>');
          unless ($env{'form.pagepath'}) {
      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="" />
    <span class="LC_nobreak">
    <input name="newpage" type="button"
    onClick="javascript:makenewpage(this.form,'$pageseq');"
    value="$lt{'newp'}" />$help{'Adding_Pages'}
    </span>
    </form>
   NPFORM
   
    my $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newfolder" type="button"
    onClick="javascript:makenewfolder(this.form,'$folderseq');"
    value="$lt{'newf'}" />$help{'Adding_Folders'}
    </span>
    </form>
   NFFORM
   
    my $newsylform=(<<NSYLFORM);
    <form action="/adm/coursedocs" method="post" name="newsyl">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
    <span class="LC_nobreak">
    <input name="newsyl" type="submit" value="$lt{'syll'}" />
    $help{'Syllabus'}
    </span>
    </form>
   NSYLFORM
   
    my $newgroupfileform=(<<NGFFORM);
    <form action="/adm/coursedocs" method="post" name="newgroupfiles">
    $uploadtag
    <input type="hidden" name="importdetail"
    value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
    <span class="LC_nobreak">
    <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />
    $help{'Group Files'}
    </span>
    </form>
   NGFFORM
   
   
              $r->print(<<ENDFORM);
   <br />
   $newfolderform
   <br />
   $newpageform
   <br />
   $newsylform
   <br />
   $newnavform
   <br />
   $newsmppageform
   <br />
   $newsmpproblemform
   <br />
   $newdropboxform
   <br />
   $newexuploadform
   <br />
   $newbulform
   <br />
   $newaboutmeform
   <br />
   $newaboutsomeoneform
   <br />
   $newgroupfileform
   <br />
   $newrosterform
   ENDFORM
          }
          if ($env{'form.pagepath'}) {
              $r->print(<<ENDBLOCK);
   $newsmpproblemform
   <br />
   $newexuploadform
   ENDBLOCK
          }
          $r->print('</td></tr>'."\n".
   '</table>');
          $r->print('</td></tr>');
       }
   # ----------------------------------------------------- Supplemental documents
       if (!$forcestandard) {
          $r->print('<tr><td class="LC_docs_document">');
   # '<h2>'.&mt('Supplemental Course Documents').
   #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');
          my $folder=$env{'form.folder'};
          unless ($folder=~/^supplemental/) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = 'supplemental&'.
                                       &escape(&mt('Supplemental '.$type.' Documents'));
          }
          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);
          if ($error) {
      $r->print('<p><span class="LC_error">'.$error.'</span></p>');
          }
          if ($allowed) {
      my $folderseq=
          '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
          '.sequence';
   
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
   
    my $supupdocform=(<<SUPDOCFORM);
    <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">
    $fileupload
    <br />
    <br />
    <span class="LC_nobreak">
    $checkbox
    </span>
    <br /><br />
    $lt{'comment'}:<br />
    <textarea cols=50 rows=4 name='comment'>
    </textarea>
    <br />
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="cmd" value="upload_supplemental" />
    <span class="LC_nobreak">
    <input type="submit" value="$lt{'upld'}" />
    $help{'Uploading_From_Harddrive'}
    </span>
    </form>
   SUPDOCFORM
   
    my $supnewfolderform=(<<SNFFORM);
    <form action="/adm/coursedocs" method="post" name="supnewfolder">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newfolder" type="button"
    onClick="javascript:makenewfolder(this.form,'$folderseq');"
    value="$lt{'newf'}" /> $help{'Adding_Folders'}
    </span>
    </form>
   SNFFORM
   
   
    my $supnewextform=(<<SNEFORM);
    <form action="/adm/coursedocs" method="post" name="supnewext">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button"
    onClick="javascript:makenewext('supnewext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   SNEFORM
   
    my $supnewsylform=(<<SNSFORM);
    <form action="/adm/coursedocs" method="post" name="supnewsyl">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail"
    value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
    <span class="LC_nobreak">
    <input name="newsyl" type="submit" value="$lt{'syll'}" />
    $help{'Syllabus'}
    </span>
    </form>
   SNSFORM
   
    my $supnewaboutmeform=(<<SNAMFORM);
    <form action="/adm/coursedocs" method="post" name="subnewaboutme">
    <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail"
    value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
    <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
    $help{'My Personal Info'}
    </span>
    </form>
   SNAMFORM
   
      $r->print(<<ENDSUPFORM);
   <ul class="LC_TabContent">
   <li>$lt{'nd'}</li>
   <li>$lt{'sd'}</li>
   <li>$lt{'hao'}</li>
   </ul>
   <table class="LC_docs_adddocs">
   <tr><td>
   $supupdocform
   </td>
   <td>
   $supnewfolderform
   <br />
   $supnewextform
   <br />
   $supnewsylform
   <br />
   $supnewaboutmeform
   </td></tr>
   </table></td></tr>
   ENDSUPFORM
          }
       }
       $r->print('</table>');
       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>');
       }
     } else {
         unless ($upload_result eq 'phasetwo') {
   # -------------------------------------------------------- This is showdoc mode
             $r->print("<h1>".&mt('Uploaded Document').' - '.
    &Apache::lonnet::gettitle($r->uri).'</h1><p>'.
   &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
             &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 editing_js {
       my ($udom,$uname) = @_;
       my $now = time();
       my %lt = &Apache::lonlocal::texthash(
                                             p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
                                             t_mnp => 'New Page',
                                             p_mxu => 'Title for the Uploaded Score',
                                             p_msp => 'Title for the Page',
                                             p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Bulletin Board',
                                             p_mab => "Enter user:domain for User's 'About Me' Page",
                                             p_mab2 => "About [_99]",
                                             p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
                                             p_chn => 'New Title',
                                             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]'
                                           );
   
       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 makenewext(targetname) {
       this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.title.value='';
       this.document.forms.extimport.url.value='';
       this.document.forms.extimport.residx.value='';
       window.open('/adm/rat/extpickframe.html');
   }
   
   function edittext(targetname,residx,title,url) {
       this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.residx.value=residx;
       this.document.forms.extimport.url.value=url;
       this.document.forms.extimport.title.value=title;
       window.open('/adm/rat/extpickframe.html');
   }
   
   function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
      if (title) {
       this.document.forms.newexamupload.importdetail.value=
    escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
      }
   }
   
   function makesmppage() {
      var title=prompt('$lt{"p_msp"}');
      if (title) {
       this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/smppg';
       this.document.forms.newsmppg.submit();
      }
   }
   
   function makesmpproblem() {
      var title=prompt('$lt{"p_msb"}');
      if (title) {
       this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
       this.document.forms.newsmpproblem.submit();
      }
   }
   
   function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
      if (title) {
       this.document.forms.newdropbox.importdetail.value=
           escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
      }
   }
   
   function makebulboard() {
      var title=prompt('$lt{"p_mbb"}');
      if (title) {
       this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
       this.document.forms.newbul.submit();
      }
   }
   
   function makeabout() {
      var user=prompt("$lt{'p_mab'}");
      if (user) {
          var comp=new Array();
          comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
      if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
      '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
      } else {
                  alert("$lt{'p_mab_alrt1'}");
              }
          } else {
              alert("$lt{'p_mab_alrt2'}");
          }
      }
   }
   
   function makeims() {
       var caller = document.forms.ims.folder.value;
       var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
       newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
       newWindow.location.href = newlocation;
   }
   
   
   function finishpick() {
       var title=this.document.forms.extimport.title.value;
       var url=this.document.forms.extimport.url.value;
       var form=this.document.forms.extimport.useform.value;
       var residx=this.document.forms.extimport.residx.value;
       eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
   }
   
   function changename(folderpath,index,oldtitle,container,pagesymb) {
       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;
           if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {
       if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
    this.document.forms.renameform.markcopy.value=-1;
    this.document.forms.renameform.cmd.value='del_'+index;
           if (container == 'sequence') {
               this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
       if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
    this.document.forms.renameform.cmd.value='cut_'+index;
    this.document.forms.renameform.markcopy.value=index;
    this.document.forms.renameform.copyfolder.value=folder+'.'+container;
           if (container == 'sequence') {
               this.document.forms.renameform.folderpath.value=folderpath;
           }
           if (container == 'page') {
               this.document.forms.renameform.pagepath.value=folderpath;
               this.document.forms.renameform.pagesymb.value=pagesymb;
           }
           this.document.forms.renameform.submit();
       }
   }
   
   function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
       this.document.forms.renameform.markcopy.value=index;
       this.document.forms.renameform.copyfolder.value=folder+'.'+container;
       if (container == 'sequence') {
    this.document.forms.renameform.folderpath.value=folderpath;
       }
       if (container == 'page') {
    this.document.forms.renameform.pagepath.value=folderpath;
    this.document.forms.renameform.pagesymb.value=pagesymb;
       }
       this.document.forms.renameform.submit();
   }
   
   
   ENDNEWSCRIPT
   }
   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 dumpbutton()
   
   Generate "dump" button
   
   =item clean()
   
   =item dumpcourse()
   
       Actually dump course
   
   
   =item exportbutton()
   
       Generate "export" button
   
   =item exportcourse()
   
   =item create_ims_store()
   
   =item build_package()
   
   =item get_dependencies()
   
   =item process_content()
   
   =item replicate_content()
   
   =item extract_media()
   
   =item store_template()
   
   =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 update_parameter()
   
   =item handle_edit_cmd()
   
   =item editor()
   
   =item process_file_upload()
   
   =item process_secondary_uploads()
   
   =item is_supplemental_title()
   
   =item parse_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
   
   =back
   
   =cut

Removed from v.1.151  
changed lines
  Added in v.1.326


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