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

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


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