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

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

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


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