Diff for /loncom/interface/londocs.pm between versions 1.325.2.3 and 1.327

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


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