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

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

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


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