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

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


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