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

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

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


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